const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/LeadSiteHome-BwGfSotH.js","assets/useLeadSiteSearchSuggestions-DrKlf2c1.js","assets/CityPagesModule-uRTvAFza.js","assets/ListingCarouselModule-cyRTjcgs.js","assets/imageOptimization-Csrlnz8M.js","assets/LeadSiteLuxuryHome-CEGYQyhj.js","assets/LeadSiteExchangeListings-2ExF9SnZ.js","assets/LeadSiteLandRanchHome-ysxr3lKH.js","assets/LeadSiteSearch-aidAFov1.js","assets/LeadSiteListingCardImage-COL0gDpF.js","assets/LeadSiteMap-94whKg66.js","assets/LeadSiteLuxurySearch-CJi7aaRC.js","assets/LeadSiteListingDetail-CMt0VEf7.js","assets/ListingVideoTour-Ddo_A6In.js","assets/useListingVideos-ocBeWLIB.js","assets/LeadSiteLuxuryListingDetail-Dn2H4bhF.js","assets/LeadSiteCityPage-BIZNcc98.js","assets/LeadSiteSubdivisionPage-D1Y2mVlQ.js","assets/LeadSiteFocusPage-3SUxeuV-.js","assets/PublicLiveEvent-D2NJYXPs.js","assets/useLiveEngagement-Dw-TQZRz.js","assets/LiveEventConsole-FAg1MAd7.js","assets/PostcardManager-IvNBr0iI.js","assets/usePostcardZones-BL2xyeOl.js","assets/DirectMail-CJCfx94j.js","assets/LeadSiteEditor-Do4tVEan.js","assets/ImageUrlField-GQRwopSC.js","assets/HomepageModuleManager-AxfVsXYF.js","assets/LeadSiteEditor-BzY4kI8E.css","assets/AdminLeadSiteThemes-DhpeYgAn.js","assets/AdminFreeWebsiteOfferStudio-CKe_WPny.js","assets/MLSListingDetail-Bn9Wf2ee.js","assets/EmailCampaignComposer-BSBdaDJR.js","assets/EditorModeSelector-DsO-dEFN.js","assets/SharedCampaignTemplates-F-2Y4Ag4.js","assets/TemplateEditorDialog-DQIUz4Gd.js","assets/AgentTemplates-GYxgTovS.js","assets/TheLocalMoveHome-C2gzw2B_.js","assets/tlm-hero-bg-BbD3acLf.js","assets/TheLocalMoveGetStarted-BuwM5gw0.js"])))=>i.map(i=>d[i]); var jQt=Object.defineProperty;var Ist=s=>{throw TypeError(s)};var NQt=(s,t,n)=>t in s?jQt(s,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):s[t]=n;var Lr=(s,t,n)=>NQt(s,typeof t!="symbol"?t+"":t,n),DMe=(s,t,n)=>t.has(s)||Ist("Cannot "+n);var pe=(s,t,n)=>(DMe(s,t,"read from private field"),n?n.call(s):t.get(s)),rs=(s,t,n)=>t.has(s)?Ist("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(s):t.set(s,n),$t=(s,t,n,r)=>(DMe(s,t,"write to private field"),r?r.call(s,n):t.set(s,n),n),Kt=(s,t,n)=>(DMe(s,t,"access private method"),n);var Xg=(s,t,n,r)=>({set _(a){$t(s,t,a,n)},get _(){return pe(s,t,r)}});function kQt(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)}})();const SQt="modulepreload",CQt=function(s){return"/"+s},Dst={},mi=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=CQt(c),c in Dst)return;Dst[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":SQt,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)})};var Sm=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function Uc(s){return s&&s.__esModule&&Object.prototype.hasOwnProperty.call(s,"default")?s.default:s}function AQt(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 kwt={exports:{}},y3e={},Swt={exports:{}},Zc={};/** * @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 $J=Symbol.for("react.element"),EQt=Symbol.for("react.portal"),TQt=Symbol.for("react.fragment"),MQt=Symbol.for("react.strict_mode"),LQt=Symbol.for("react.profiler"),PQt=Symbol.for("react.provider"),IQt=Symbol.for("react.context"),DQt=Symbol.for("react.forward_ref"),RQt=Symbol.for("react.suspense"),OQt=Symbol.for("react.memo"),FQt=Symbol.for("react.lazy"),Rst=Symbol.iterator;function zQt(s){return s===null||typeof s!="object"?null:(s=Rst&&s[Rst]||s["@@iterator"],typeof s=="function"?s:null)}var Cwt={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},Awt=Object.assign,Ewt={};function lq(s,t,n){this.props=s,this.context=t,this.refs=Ewt,this.updater=n||Cwt}lq.prototype.isReactComponent={};lq.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")};lq.prototype.forceUpdate=function(s){this.updater.enqueueForceUpdate(this,s,"forceUpdate")};function Twt(){}Twt.prototype=lq.prototype;function nqe(s,t,n){this.props=s,this.context=t,this.refs=Ewt,this.updater=n||Cwt}var rqe=nqe.prototype=new Twt;rqe.constructor=nqe;Awt(rqe,lq.prototype);rqe.isPureReactComponent=!0;var Ost=Array.isArray,Mwt=Object.prototype.hasOwnProperty,aqe={current:null},Lwt={key:!0,ref:!0,__self:!0,__source:!0};function Pwt(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)Mwt.call(t,r)&&!Lwt.hasOwnProperty(r)&&(a[r]=t[r]);var o=arguments.length-2;if(o===1)a.children=n;else if(1>>1,le=ce[ee];if(0>>1;eea(ge,ne))fea(je,ge)?(ce[ee]=je,ce[fe]=ne,ee=fe):(ce[ee]=ge,ce[ve]=ne,ee=ve);else if(fea(je,ne))ce[ee]=je,ce[fe]=ne,ee=fe;else break e}}return ue}function a(ce,ue){var ne=ce.sortIndex-ue.sortIndex;return ne!==0?ne:ce.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,x=!1,g=!1,y=typeof setTimeout=="function"?setTimeout:null,b=typeof clearTimeout=="function"?clearTimeout:null,v=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(ce){for(var ue=n(d);ue!==null;){if(ue.callback===null)r(d);else if(ue.startTime<=ce)r(d),ue.sortIndex=ue.expirationTime,t(c,ue);else break;ue=n(d)}}function C(ce){if(g=!1,N(ce),!x)if(n(c)!==null)x=!0,Q(A);else{var ue=n(d);ue!==null&&J(C,ue.startTime-ce)}}function A(ce,ue){x=!1,g&&(g=!1,b(M),M=-1),p=!0;var ne=m;try{for(N(ue),h=n(c);h!==null&&(!(h.expirationTime>ue)||ce&&!B());){var ee=h.callback;if(typeof ee=="function"){h.callback=null,m=h.priorityLevel;var le=ee(h.expirationTime<=ue);ue=s.unstable_now(),typeof le=="function"?h.callback=le:h===n(c)&&r(c),N(ue)}else r(c);h=n(c)}if(h!==null)var he=!0;else{var ve=n(d);ve!==null&&J(C,ve.startTime-ue),he=!1}return he}finally{h=null,m=ne,p=!1}}var T=!1,P=null,M=-1,I=5,D=-1;function B(){return!(s.unstable_now()-Dce||125ee?(ce.sortIndex=ne,t(d,ce),n(c)===null&&ce===n(d)&&(g?(b(M),M=-1):g=!0,J(C,ne-ee))):(ce.sortIndex=le,t(c,ce),x||p||(x=!0,Q(A))),ce},s.unstable_shouldYield=B,s.unstable_wrapCallback=function(ce){var ue=m;return function(){var ne=m;m=ue;try{return ce.apply(this,arguments)}finally{m=ne}}}})(Fwt);Owt.exports=Fwt;var nK=Owt.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 ZQt=j,mw=nK;function Ba(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"),DRe=Object.prototype.hasOwnProperty,XQt=/^[: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]*$/,zst={},Bst={};function QQt(s){return DRe.call(Bst,s)?!0:DRe.call(zst,s)?!1:XQt.test(s)?Bst[s]=!0:(zst[s]=!0,!1)}function JQt(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 eJt(s,t,n,r){if(t===null||typeof t>"u"||JQt(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 A1(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 jy={};"children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style".split(" ").forEach(function(s){jy[s]=new A1(s,0,!1,s,null,!1,!1)});[["acceptCharset","accept-charset"],["className","class"],["htmlFor","for"],["httpEquiv","http-equiv"]].forEach(function(s){var t=s[0];jy[t]=new A1(t,1,!1,s[1],null,!1,!1)});["contentEditable","draggable","spellCheck","value"].forEach(function(s){jy[s]=new A1(s,2,!1,s.toLowerCase(),null,!1,!1)});["autoReverse","externalResourcesRequired","focusable","preserveAlpha"].forEach(function(s){jy[s]=new A1(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){jy[s]=new A1(s,3,!1,s.toLowerCase(),null,!1,!1)});["checked","multiple","muted","selected"].forEach(function(s){jy[s]=new A1(s,3,!0,s,null,!1,!1)});["capture","download"].forEach(function(s){jy[s]=new A1(s,4,!1,s,null,!1,!1)});["cols","rows","size","span"].forEach(function(s){jy[s]=new A1(s,6,!1,s,null,!1,!1)});["rowSpan","start"].forEach(function(s){jy[s]=new A1(s,5,!1,s.toLowerCase(),null,!1,!1)});var lqe=/[\-:]([a-z])/g;function cqe(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(lqe,cqe);jy[t]=new A1(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(lqe,cqe);jy[t]=new A1(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(lqe,cqe);jy[t]=new A1(t,1,!1,s,"http://www.w3.org/XML/1998/namespace",!1,!1)});["tabIndex","crossOrigin"].forEach(function(s){jy[s]=new A1(s,1,!1,s.toLowerCase(),null,!1,!1)});jy.xlinkHref=new A1("xlinkHref",1,!1,"xlink:href","http://www.w3.org/1999/xlink",!0,!1);["src","href","action","formAction"].forEach(function(s){jy[s]=new A1(s,1,!1,s.toLowerCase(),null,!0,!0)});function dqe(s,t,n,r){var a=jy.hasOwnProperty(t)?jy[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{FMe=!1,Error.prepareStackTrace=n}return(s=s?s.displayName||s.name:"")?lW(s):""}function tJt(s){switch(s.tag){case 5:return lW(s.type);case 16:return lW("Lazy");case 13:return lW("Suspense");case 19:return lW("SuspenseList");case 0:case 2:case 15:return s=zMe(s.type,!1),s;case 11:return s=zMe(s.type.render,!1),s;case 1:return s=zMe(s.type,!0),s;default:return""}}function zRe(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 E9:return"Fragment";case A9:return"Portal";case RRe:return"Profiler";case uqe:return"StrictMode";case ORe:return"Suspense";case FRe:return"SuspenseList"}if(typeof s=="object")switch(s.$$typeof){case $wt:return(s.displayName||"Context")+".Consumer";case Bwt:return(s._context.displayName||"Context")+".Provider";case hqe:var t=s.render;return s=s.displayName,s||(s=t.displayName||t.name||"",s=s!==""?"ForwardRef("+s+")":"ForwardRef"),s;case mqe:return t=s.displayName||null,t!==null?t:zRe(s.type)||"Memo";case PA:t=s._payload,s=s._init;try{return zRe(s(t))}catch{}}return null}function sJt(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 zRe(t);case 8:return t===uqe?"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 ZT(s){switch(typeof s){case"boolean":case"number":case"string":case"undefined":return s;case"object":return s;default:return""}}function qwt(s){var t=s.type;return(s=s.nodeName)&&s.toLowerCase()==="input"&&(t==="checkbox"||t==="radio")}function nJt(s){var t=qwt(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 qse(s){s._valueTracker||(s._valueTracker=nJt(s))}function Vwt(s){if(!s)return!1;var t=s._valueTracker;if(!t)return!0;var n=t.getValue(),r="";return s&&(r=qwt(s)?s.checked?"true":"false":s.value),s=r,s!==n?(t.setValue(s),!0):!1}function GNe(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 BRe(s,t){var n=t.checked;return Hp({},t,{defaultChecked:void 0,defaultValue:void 0,value:void 0,checked:n??s._wrapperState.initialChecked})}function Ust(s,t){var n=t.defaultValue==null?"":t.defaultValue,r=t.checked!=null?t.checked:t.defaultChecked;n=ZT(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 Hwt(s,t){t=t.checked,t!=null&&dqe(s,"checked",t,!1)}function $Re(s,t){Hwt(s,t);var n=ZT(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")?URe(s,t.type,n):t.hasOwnProperty("defaultValue")&&URe(s,t.type,ZT(t.defaultValue)),t.checked==null&&t.defaultChecked!=null&&(s.defaultChecked=!!t.defaultChecked)}function qst(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 URe(s,t,n){(t!=="number"||GNe(s.ownerDocument)!==s)&&(n==null?s.defaultValue=""+s._wrapperState.initialValue:s.defaultValue!==""+n&&(s.defaultValue=""+n))}var cW=Array.isArray;function cz(s,t,n,r){if(s=s.options,t){t={};for(var a=0;a"+t.valueOf().toString()+"",t=Vse.firstChild;s.firstChild;)s.removeChild(s.firstChild);for(;t.firstChild;)s.appendChild(t.firstChild)}});function mZ(s,t){if(t){var n=s.firstChild;if(n&&n===s.lastChild&&n.nodeType===3){n.nodeValue=t;return}}s.textContent=t}var rK={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},rJt=["Webkit","ms","Moz","O"];Object.keys(rK).forEach(function(s){rJt.forEach(function(t){t=t+s.charAt(0).toUpperCase()+s.substring(1),rK[t]=rK[s]})});function Ywt(s,t,n){return t==null||typeof t=="boolean"||t===""?"":n||typeof t!="number"||t===0||rK.hasOwnProperty(s)&&rK[s]?(""+t).trim():t+"px"}function Zwt(s,t){s=s.style;for(var n in t)if(t.hasOwnProperty(n)){var r=n.indexOf("--")===0,a=Ywt(n,t[n],r);n==="float"&&(n="cssFloat"),r?s.setProperty(n,a):s[n]=a}}var aJt=Hp({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 HRe(s,t){if(t){if(aJt[s]&&(t.children!=null||t.dangerouslySetInnerHTML!=null))throw Error(Ba(137,s));if(t.dangerouslySetInnerHTML!=null){if(t.children!=null)throw Error(Ba(60));if(typeof t.dangerouslySetInnerHTML!="object"||!("__html"in t.dangerouslySetInnerHTML))throw Error(Ba(61))}if(t.style!=null&&typeof t.style!="object")throw Error(Ba(62))}}function GRe(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 WRe=null;function pqe(s){return s=s.target||s.srcElement||window,s.correspondingUseElement&&(s=s.correspondingUseElement),s.nodeType===3?s.parentNode:s}var KRe=null,dz=null,uz=null;function Gst(s){if(s=VJ(s)){if(typeof KRe!="function")throw Error(Ba(280));var t=s.stateNode;t&&(t=j3e(t),KRe(s.stateNode,s.type,t))}}function Xwt(s){dz?uz?uz.push(s):uz=[s]:dz=s}function Qwt(){if(dz){var s=dz,t=uz;if(uz=dz=null,Gst(s),t)for(s=0;s>>=0,s===0?32:31-(xJt(s)/gJt|0)|0}var Hse=64,Gse=4194304;function dW(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 ZNe(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=dW(o):(i&=l,i!==0&&(r=dW(i)))}else l=n&~a,l!==0?r=dW(l):i!==0&&(r=dW(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 UJ(s,t,n){s.pendingLanes|=t,t!==536870912&&(s.suspendedLanes=0,s.pingedLanes=0),s=s.eventTimes,t=31-TN(t),s[t]=n}function _Jt(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=iK),tnt=" ",snt=!1;function yjt(s,t){switch(s){case"keyup":return YJt.indexOf(t.keyCode)!==-1;case"keydown":return t.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function vjt(s){return s=s.detail,typeof s=="object"&&"data"in s?s.data:null}var T9=!1;function XJt(s,t){switch(s){case"compositionend":return vjt(t);case"keypress":return t.which!==32?null:(snt=!0,tnt);case"textInput":return s=t.data,s===tnt&&snt?null:s;default:return null}}function QJt(s,t){if(T9)return s==="compositionend"||!wqe&&yjt(s,t)?(s=xjt(),cie=vqe=VE=null,T9=!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=int(n)}}function jjt(s,t){return s&&t?s===t?!0:s&&s.nodeType===3?!1:t&&t.nodeType===3?jjt(s,t.parentNode):"contains"in s?s.contains(t):s.compareDocumentPosition?!!(s.compareDocumentPosition(t)&16):!1:!1}function Njt(){for(var s=window,t=GNe();t instanceof s.HTMLIFrameElement;){try{var n=typeof t.contentWindow.location.href=="string"}catch{n=!1}if(n)s=t.contentWindow;else break;t=GNe(s.document)}return t}function jqe(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 oes(s){var t=Njt(),n=s.focusedElem,r=s.selectionRange;if(t!==n&&n&&n.ownerDocument&&jjt(n.ownerDocument.documentElement,n)){if(r!==null&&jqe(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=ont(n,i);var l=ont(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,M9=null,eOe=null,lK=null,tOe=!1;function lnt(s,t,n){var r=n.window===n?n.document:n.nodeType===9?n:n.ownerDocument;tOe||M9==null||M9!==GNe(r)||(r=M9,"selectionStart"in r&&jqe(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}),lK&&vZ(lK,r)||(lK=r,r=JNe(eOe,"onSelect"),0I9||(s.current=oOe[I9],oOe[I9]=null,I9--)}function Yh(s,t){I9++,oOe[I9]=s.current,s.current=t}var XT={},pv=_6(XT),Cb=_6(!1),XR=XT;function z$(s,t){var n=s.type.contextTypes;if(!n)return XT;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 Ab(s){return s=s.childContextTypes,s!=null}function tke(){Cm(Cb),Cm(pv)}function fnt(s,t,n){if(pv.current!==XT)throw Error(Ba(168));Yh(pv,t),Yh(Cb,n)}function Pjt(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(Ba(108,sJt(s)||"Unknown",a));return Hp({},n,r)}function ske(s){return s=(s=s.stateNode)&&s.__reactInternalMemoizedMergedChildContext||XT,XR=pv.current,Yh(pv,s),Yh(Cb,Cb.current),!0}function xnt(s,t,n){var r=s.stateNode;if(!r)throw Error(Ba(169));n?(s=Pjt(s,t,XR),r.__reactInternalMemoizedMergedChildContext=s,Cm(Cb),Cm(pv),Yh(pv,s)):Cm(Cb),Yh(Cb,n)}var Y4=null,N3e=!1,JMe=!1;function Ijt(s){Y4===null?Y4=[s]:Y4.push(s)}function ves(s){N3e=!0,Ijt(s)}function w6(){if(!JMe&&Y4!==null){JMe=!0;var s=0,t=Zu;try{var n=Y4;for(Zu=1;s>=l,a-=l,T3=1<<32-TN(t)+a|n<M?(I=P,P=null):I=P.sibling;var D=m(b,P,N[M],C);if(D===null){P===null&&(P=I);break}s&&P&&D.alternate===null&&t(b,P),v=i(D,v,M),T===null?A=D:T.sibling=D,T=D,P=I}if(M===N.length)return n(b,P),Jm&&ZM(b,M),A;if(P===null){for(;MM?(I=P,P=null):I=P.sibling;var B=m(b,P,D.value,C);if(B===null){P===null&&(P=I);break}s&&P&&B.alternate===null&&t(b,P),v=i(B,v,M),T===null?A=B:T.sibling=B,T=B,P=I}if(D.done)return n(b,P),Jm&&ZM(b,M),A;if(P===null){for(;!D.done;M++,D=N.next())D=h(b,D.value,C),D!==null&&(v=i(D,v,M),T===null?A=D:T.sibling=D,T=D);return Jm&&ZM(b,M),A}for(P=r(b,P);!D.done;M++,D=N.next())D=p(P,b,M,D.value,C),D!==null&&(s&&D.alternate!==null&&P.delete(D.key===null?M:D.key),v=i(D,v,M),T===null?A=D:T.sibling=D,T=D);return s&&P.forEach(function(q){return t(b,q)}),Jm&&ZM(b,M),A}function y(b,v,N,C){if(typeof N=="object"&&N!==null&&N.type===E9&&N.key===null&&(N=N.props.children),typeof N=="object"&&N!==null){switch(N.$$typeof){case Use:e:{for(var A=N.key,T=v;T!==null;){if(T.key===A){if(A=N.type,A===E9){if(T.tag===7){n(b,T.sibling),v=a(T,N.props.children),v.return=b,b=v;break e}}else if(T.elementType===A||typeof A=="object"&&A!==null&&A.$$typeof===PA&&vnt(A)===T.type){n(b,T.sibling),v=a(T,N.props),v.ref=BH(b,T,N),v.return=b,b=v;break e}n(b,T);break}else t(b,T);T=T.sibling}N.type===E9?(v=rR(N.props.children,b.mode,C,N.key),v.return=b,b=v):(C=gie(N.type,N.key,N.props,null,b.mode,C),C.ref=BH(b,v,N),C.return=b,b=C)}return l(b);case A9:e:{for(T=N.key;v!==null;){if(v.key===T)if(v.tag===4&&v.stateNode.containerInfo===N.containerInfo&&v.stateNode.implementation===N.implementation){n(b,v.sibling),v=a(v,N.children||[]),v.return=b,b=v;break e}else{n(b,v);break}else t(b,v);v=v.sibling}v=oLe(N,b.mode,C),v.return=b,b=v}return l(b);case PA:return T=N._init,y(b,v,T(N._payload),C)}if(cW(N))return x(b,v,N,C);if(DH(N))return g(b,v,N,C);Jse(b,N)}return typeof N=="string"&&N!==""||typeof N=="number"?(N=""+N,v!==null&&v.tag===6?(n(b,v.sibling),v=a(v,N),v.return=b,b=v):(n(b,v),v=iLe(N,b.mode,C),v.return=b,b=v),l(b)):n(b,v)}return y}var $$=Fjt(!0),zjt=Fjt(!1),ake=_6(null),ike=null,O9=null,Cqe=null;function Aqe(){Cqe=O9=ike=null}function Eqe(s){var t=ake.current;Cm(ake),s._currentValue=t}function dOe(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 mz(s,t){ike=s,Cqe=O9=null,s=s.dependencies,s!==null&&s.firstContext!==null&&(s.lanes&t&&(_b=!0),s.firstContext=null)}function s2(s){var t=s._currentValue;if(Cqe!==s)if(s={context:s,memoizedValue:t,next:null},O9===null){if(ike===null)throw Error(Ba(308));O9=s,ike.dependencies={lanes:0,firstContext:s}}else O9=O9.next=s;return t}var C8=null;function Tqe(s){C8===null?C8=[s]:C8.push(s)}function Bjt(s,t,n,r){var a=t.interleaved;return a===null?(n.next=n,Tqe(t)):(n.next=a.next,a.next=n),t.interleaved=n,aC(s,r)}function aC(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 IA=!1;function Mqe(s){s.updateQueue={baseState:s.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,interleaved:null,lanes:0},effects:null}}function $jt(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 B3(s,t){return{eventTime:s,lane:t,tag:0,payload:null,callback:null,next:null}}function lT(s,t,n){var r=s.updateQueue;if(r===null)return null;if(r=r.shared,Ud&2){var a=r.pending;return a===null?t.next=t:(t.next=a.next,a.next=t),r.pending=t,aC(s,n)}return a=r.interleaved,a===null?(t.next=t,Tqe(r)):(t.next=a.next,a.next=t),r.interleaved=t,aC(s,n)}function uie(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,xqe(s,n)}}function bnt(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 oke(s,t,n,r){var a=s.updateQueue;IA=!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 x=s,g=o;switch(m=t,p=n,g.tag){case 1:if(x=g.payload,typeof x=="function"){h=x.call(p,h,m);break e}h=x;break e;case 3:x.flags=x.flags&-65537|128;case 0:if(x=g.payload,m=typeof x=="function"?x.call(p,h,m):x,m==null)break e;h=Hp({},h,m);break e;case 2:IA=!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);eO|=l,s.lanes=l,s.memoizedState=h}}function _nt(s,t,n){if(s=t.effects,t.effects=null,s!==null)for(t=0;tn?n:4,s(!0);var r=tLe.transition;tLe.transition={};try{s(!1),t()}finally{Zu=n,tLe.transition=r}}function r2t(){return n2().memoizedState}function jes(s,t,n){var r=dT(s);if(n={lane:r,action:n,hasEagerState:!1,eagerState:null,next:null},a2t(s))i2t(t,n);else if(n=Bjt(s,t,n,r),n!==null){var a=p1();MN(n,s,r,a),o2t(n,t,r)}}function Nes(s,t,n){var r=dT(s),a={lane:r,action:n,hasEagerState:!1,eagerState:null,next:null};if(a2t(s))i2t(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,qN(o,l)){var c=t.interleaved;c===null?(a.next=a,Tqe(t)):(a.next=c.next,c.next=a),t.interleaved=a;return}}catch{}finally{}n=Bjt(s,t,a,r),n!==null&&(a=p1(),MN(n,s,r,a),o2t(n,t,r))}}function a2t(s){var t=s.alternate;return s===Fp||t!==null&&t===Fp}function i2t(s,t){cK=cke=!0;var n=s.pending;n===null?t.next=t:(t.next=n.next,n.next=t),s.pending=t}function o2t(s,t,n){if(n&4194240){var r=t.lanes;r&=s.pendingLanes,n|=r,t.lanes=n,xqe(s,n)}}var dke={readContext:s2,useCallback:By,useContext:By,useEffect:By,useImperativeHandle:By,useInsertionEffect:By,useLayoutEffect:By,useMemo:By,useReducer:By,useRef:By,useState:By,useDebugValue:By,useDeferredValue:By,useTransition:By,useMutableSource:By,useSyncExternalStore:By,useId:By,unstable_isNewReconciler:!1},kes={readContext:s2,useCallback:function(s,t){return Jk().memoizedState=[s,t===void 0?null:t],s},useContext:s2,useEffect:jnt,useImperativeHandle:function(s,t,n){return n=n!=null?n.concat([s]):null,mie(4194308,4,Jjt.bind(null,t,s),n)},useLayoutEffect:function(s,t){return mie(4194308,4,s,t)},useInsertionEffect:function(s,t){return mie(4,2,s,t)},useMemo:function(s,t){var n=Jk();return t=t===void 0?null:t,s=s(),n.memoizedState=[s,t],s},useReducer:function(s,t,n){var r=Jk();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=jes.bind(null,Fp,s),[r.memoizedState,s]},useRef:function(s){var t=Jk();return s={current:s},t.memoizedState=s},useState:wnt,useDebugValue:zqe,useDeferredValue:function(s){return Jk().memoizedState=s},useTransition:function(){var s=wnt(!1),t=s[0];return s=wes.bind(null,s[1]),Jk().memoizedState=s,[t,s]},useMutableSource:function(){},useSyncExternalStore:function(s,t,n){var r=Fp,a=Jk();if(Jm){if(n===void 0)throw Error(Ba(407));n=n()}else{if(n=t(),g0===null)throw Error(Ba(349));JR&30||Hjt(r,t,n)}a.memoizedState=n;var i={value:n,getSnapshot:t};return a.queue=i,jnt(Wjt.bind(null,r,i,s),[s]),r.flags|=2048,CZ(9,Gjt.bind(null,r,i,n,t),void 0,null),n},useId:function(){var s=Jk(),t=g0.identifierPrefix;if(Jm){var n=M3,r=T3;n=(r&~(1<<32-TN(r)-1)).toString(32)+n,t=":"+t+"R"+n,n=kZ++,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[PS]=t,s[wZ]=r,g2t(s,t,!1,!1),t.stateNode=s;e:{switch(l=GRe(n,r),n){case"dialog":gm("cancel",s),gm("close",s),a=r;break;case"iframe":case"object":case"embed":gm("load",s),a=r;break;case"video":case"audio":for(a=0;aV$&&(t.flags|=128,r=!0,$H(i,!1),t.lanes=4194304)}else{if(!r)if(s=lke(l),s!==null){if(t.flags|=128,r=!0,n=s.updateQueue,n!==null&&(t.updateQueue=n,t.flags|=4),$H(i,!0),i.tail===null&&i.tailMode==="hidden"&&!l.alternate&&!Jm)return $y(t),null}else 2*Kf()-i.renderingStartTime>V$&&n!==1073741824&&(t.flags|=128,r=!0,$H(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=Kf(),t.sibling=null,n=Tp.current,Yh(Tp,r?n&1|2:n&1),t):($y(t),null);case 22:case 23:return Hqe(),r=t.memoizedState!==null,s!==null&&s.memoizedState!==null!==r&&(t.flags|=8192),r&&t.mode&1?z_&1073741824&&($y(t),t.subtreeFlags&6&&(t.flags|=8192)):$y(t),null;case 24:return null;case 25:return null}throw Error(Ba(156,t.tag))}function Pes(s,t){switch(kqe(t),t.tag){case 1:return Ab(t.type)&&tke(),s=t.flags,s&65536?(t.flags=s&-65537|128,t):null;case 3:return U$(),Cm(Cb),Cm(pv),Iqe(),s=t.flags,s&65536&&!(s&128)?(t.flags=s&-65537|128,t):null;case 5:return Pqe(t),null;case 13:if(Cm(Tp),s=t.memoizedState,s!==null&&s.dehydrated!==null){if(t.alternate===null)throw Error(Ba(340));B$()}return s=t.flags,s&65536?(t.flags=s&-65537|128,t):null;case 19:return Cm(Tp),null;case 4:return U$(),null;case 10:return Eqe(t.type._context),null;case 22:case 23:return Hqe(),null;case 24:return null;default:return null}}var tne=!1,nv=!1,Ies=typeof WeakSet=="function"?WeakSet:Set,eo=null;function F9(s,t){var n=s.ref;if(n!==null)if(typeof n=="function")try{n(null)}catch(r){pf(s,t,r)}else n.current=null}function vOe(s,t,n){try{n()}catch(r){pf(s,t,r)}}var Int=!1;function Des(s,t){if(sOe=XNe,s=Njt(),jqe(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(nOe={focusedElem:s,selectionRange:n},XNe=!1,eo=t;eo!==null;)if(t=eo,s=t.child,(t.subtreeFlags&1028)!==0&&s!==null)s.return=t,eo=s;else for(;eo!==null;){t=eo;try{var x=t.alternate;if(t.flags&1024)switch(t.tag){case 0:case 11:case 15:break;case 1:if(x!==null){var g=x.memoizedProps,y=x.memoizedState,b=t.stateNode,v=b.getSnapshotBeforeUpdate(t.elementType===t.type?g:X2(t.type,g),y);b.__reactInternalSnapshotBeforeUpdate=v}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(Ba(163))}}catch(C){pf(t,t.return,C)}if(s=t.sibling,s!==null){s.return=t.return,eo=s;break}eo=t.return}return x=Int,Int=!1,x}function dK(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&&vOe(t,n,i)}a=a.next}while(a!==r)}}function C3e(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 bOe(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 b2t(s){var t=s.alternate;t!==null&&(s.alternate=null,b2t(t)),s.child=null,s.deletions=null,s.sibling=null,s.tag===5&&(t=s.stateNode,t!==null&&(delete t[PS],delete t[wZ],delete t[iOe],delete t[ges],delete t[yes])),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 _2t(s){return s.tag===5||s.tag===3||s.tag===4}function Dnt(s){e:for(;;){for(;s.sibling===null;){if(s.return===null||_2t(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 _Oe(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=eke));else if(r!==4&&(s=s.child,s!==null))for(_Oe(s,t,n),s=s.sibling;s!==null;)_Oe(s,t,n),s=s.sibling}function wOe(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(wOe(s,t,n),s=s.sibling;s!==null;)wOe(s,t,n),s=s.sibling}var ny=null,pN=!1;function QC(s,t,n){for(n=n.child;n!==null;)w2t(s,t,n),n=n.sibling}function w2t(s,t,n){if(ZS&&typeof ZS.onCommitFiberUnmount=="function")try{ZS.onCommitFiberUnmount(v3e,n)}catch{}switch(n.tag){case 5:nv||F9(n,t);case 6:var r=ny,a=pN;ny=null,QC(s,t,n),ny=r,pN=a,ny!==null&&(pN?(s=ny,n=n.stateNode,s.nodeType===8?s.parentNode.removeChild(n):s.removeChild(n)):ny.removeChild(n.stateNode));break;case 18:ny!==null&&(pN?(s=ny,n=n.stateNode,s.nodeType===8?QMe(s.parentNode,n):s.nodeType===1&&QMe(s,n),gZ(s)):QMe(ny,n.stateNode));break;case 4:r=ny,a=pN,ny=n.stateNode.containerInfo,pN=!0,QC(s,t,n),ny=r,pN=a;break;case 0:case 11:case 14:case 15:if(!nv&&(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)&&vOe(n,t,l),a=a.next}while(a!==r)}QC(s,t,n);break;case 1:if(!nv&&(F9(n,t),r=n.stateNode,typeof r.componentWillUnmount=="function"))try{r.props=n.memoizedProps,r.state=n.memoizedState,r.componentWillUnmount()}catch(o){pf(n,t,o)}QC(s,t,n);break;case 21:QC(s,t,n);break;case 22:n.mode&1?(nv=(r=nv)||n.memoizedState!==null,QC(s,t,n),nv=r):QC(s,t,n);break;default:QC(s,t,n)}}function Rnt(s){var t=s.updateQueue;if(t!==null){s.updateQueue=null;var n=s.stateNode;n===null&&(n=s.stateNode=new Ies),t.forEach(function(r){var a=Ves.bind(null,s,r);n.has(r)||(n.add(r),r.then(a,a))})}}function B2(s,t){var n=t.deletions;if(n!==null)for(var r=0;ra&&(a=l),r&=~i}if(r=a,r=Kf()-r,r=(120>r?120:480>r?480:1080>r?1080:1920>r?1920:3e3>r?3e3:4320>r?4320:1960*Oes(r/1960))-r,10s?16:s,HE===null)var r=!1;else{if(s=HE,HE=null,mke=0,Ud&6)throw Error(Ba(331));var a=Ud;for(Ud|=4,eo=s.current;eo!==null;){var i=eo,l=i.child;if(eo.flags&16){var o=i.deletions;if(o!==null){for(var c=0;cKf()-qqe?nR(s,0):Uqe|=n),Eb(s,t)}function T2t(s,t){t===0&&(s.mode&1?(t=Gse,Gse<<=1,!(Gse&130023424)&&(Gse=4194304)):t=1);var n=p1();s=aC(s,t),s!==null&&(UJ(s,t,n),Eb(s,n))}function qes(s){var t=s.memoizedState,n=0;t!==null&&(n=t.retryLane),T2t(s,n)}function Ves(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(Ba(314))}r!==null&&r.delete(t),T2t(s,n)}var M2t;M2t=function(s,t,n){if(s!==null)if(s.memoizedProps!==t.pendingProps||Cb.current)_b=!0;else{if(!(s.lanes&n)&&!(t.flags&128))return _b=!1,Mes(s,t,n);_b=!!(s.flags&131072)}else _b=!1,Jm&&t.flags&1048576&&Djt(t,rke,t.index);switch(t.lanes=0,t.tag){case 2:var r=t.type;pie(s,t),s=t.pendingProps;var a=z$(t,pv.current);mz(t,n),a=Rqe(null,t,r,s,a,n);var i=Oqe();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,Ab(r)?(i=!0,ske(t)):i=!1,t.memoizedState=a.state!==null&&a.state!==void 0?a.state:null,Mqe(t),a.updater=S3e,t.stateNode=a,a._reactInternals=t,hOe(t,r,s,n),t=fOe(null,t,r,!0,i,n)):(t.tag=0,Jm&&i&&Nqe(t),Xv(null,t,a,n),t=t.child),t;case 16:r=t.elementType;e:{switch(pie(s,t),s=t.pendingProps,a=r._init,r=a(r._payload),t.type=r,a=t.tag=Ges(r),s=X2(r,s),a){case 0:t=pOe(null,t,r,s,n);break e;case 1:t=Mnt(null,t,r,s,n);break e;case 11:t=Ent(null,t,r,s,n);break e;case 14:t=Tnt(null,t,r,X2(r.type,s),n);break e}throw Error(Ba(306,r,""))}return t;case 0:return r=t.type,a=t.pendingProps,a=t.elementType===r?a:X2(r,a),pOe(s,t,r,a,n);case 1:return r=t.type,a=t.pendingProps,a=t.elementType===r?a:X2(r,a),Mnt(s,t,r,a,n);case 3:e:{if(p2t(t),s===null)throw Error(Ba(387));r=t.pendingProps,i=t.memoizedState,a=i.element,$jt(s,t),oke(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=q$(Error(Ba(423)),t),t=Lnt(s,t,r,n,a);break e}else if(r!==a){a=q$(Error(Ba(424)),t),t=Lnt(s,t,r,n,a);break e}else for(Y_=oT(t.stateNode.containerInfo.firstChild),ew=t,Jm=!0,bN=null,n=zjt(t,null,r,n),t.child=n;n;)n.flags=n.flags&-3|4096,n=n.sibling;else{if(B$(),r===a){t=iC(s,t,n);break e}Xv(s,t,r,n)}t=t.child}return t;case 5:return Ujt(t),s===null&&cOe(t),r=t.type,a=t.pendingProps,i=s!==null?s.memoizedProps:null,l=a.children,rOe(r,a)?l=null:i!==null&&rOe(r,i)&&(t.flags|=32),m2t(s,t),Xv(s,t,l,n),t.child;case 6:return s===null&&cOe(t),null;case 13:return f2t(s,t,n);case 4:return Lqe(t,t.stateNode.containerInfo),r=t.pendingProps,s===null?t.child=$$(t,null,r,n):Xv(s,t,r,n),t.child;case 11:return r=t.type,a=t.pendingProps,a=t.elementType===r?a:X2(r,a),Ent(s,t,r,a,n);case 7:return Xv(s,t,t.pendingProps,n),t.child;case 8:return Xv(s,t,t.pendingProps.children,n),t.child;case 12:return Xv(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,Yh(ake,r._currentValue),r._currentValue=l,i!==null)if(qN(i.value,l)){if(i.children===a.children&&!Cb.current){t=iC(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=B3(-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),dOe(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(Ba(341));l.lanes|=n,o=l.alternate,o!==null&&(o.lanes|=n),dOe(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}Xv(s,t,a.children,n),t=t.child}return t;case 9:return a=t.type,r=t.pendingProps.children,mz(t,n),a=s2(a),r=r(a),t.flags|=1,Xv(s,t,r,n),t.child;case 14:return r=t.type,a=X2(r,t.pendingProps),a=X2(r.type,a),Tnt(s,t,r,a,n);case 15:return u2t(s,t,t.type,t.pendingProps,n);case 17:return r=t.type,a=t.pendingProps,a=t.elementType===r?a:X2(r,a),pie(s,t),t.tag=1,Ab(r)?(s=!0,ske(t)):s=!1,mz(t,n),l2t(t,r,a),hOe(t,r,a,n),fOe(null,t,r,!0,s,n);case 19:return x2t(s,t,n);case 22:return h2t(s,t,n)}throw Error(Ba(156,t.tag))};function L2t(s,t){return ajt(s,t)}function Hes(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 Ij(s,t,n,r){return new Hes(s,t,n,r)}function Wqe(s){return s=s.prototype,!(!s||!s.isReactComponent)}function Ges(s){if(typeof s=="function")return Wqe(s)?1:0;if(s!=null){if(s=s.$$typeof,s===hqe)return 11;if(s===mqe)return 14}return 2}function uT(s,t){var n=s.alternate;return n===null?(n=Ij(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 gie(s,t,n,r,a,i){var l=2;if(r=s,typeof s=="function")Wqe(s)&&(l=1);else if(typeof s=="string")l=5;else e:switch(s){case E9:return rR(n.children,a,i,t);case uqe:l=8,a|=8;break;case RRe:return s=Ij(12,n,t,a|2),s.elementType=RRe,s.lanes=i,s;case ORe:return s=Ij(13,n,t,a),s.elementType=ORe,s.lanes=i,s;case FRe:return s=Ij(19,n,t,a),s.elementType=FRe,s.lanes=i,s;case Uwt:return E3e(n,a,i,t);default:if(typeof s=="object"&&s!==null)switch(s.$$typeof){case Bwt:l=10;break e;case $wt:l=9;break e;case hqe:l=11;break e;case mqe:l=14;break e;case PA:l=16,r=null;break e}throw Error(Ba(130,s==null?s:typeof s,""))}return t=Ij(l,n,t,a),t.elementType=s,t.type=r,t.lanes=i,t}function rR(s,t,n,r){return s=Ij(7,s,r,t),s.lanes=n,s}function E3e(s,t,n,r){return s=Ij(22,s,r,t),s.elementType=Uwt,s.lanes=n,s.stateNode={isHidden:!1},s}function iLe(s,t,n){return s=Ij(6,s,null,t),s.lanes=n,s}function oLe(s,t,n){return t=Ij(4,s.children!==null?s.children:[],s.key,t),t.lanes=n,t.stateNode={containerInfo:s.containerInfo,pendingChildren:null,implementation:s.implementation},t}function Wes(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=$Me(0),this.expirationTimes=$Me(-1),this.entangledLanes=this.finishedLanes=this.mutableReadLanes=this.expiredLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=$Me(0),this.identifierPrefix=r,this.onRecoverableError=a,this.mutableSourceEagerHydrationData=null}function Kqe(s,t,n,r,a,i,l,o,c){return s=new Wes(s,t,n,o,c),t===1?(t=1,i===!0&&(t|=8)):t=0,i=Ij(3,null,null,t),s.current=i,i.stateNode=s,i.memoizedState={element:r,isDehydrated:n,cache:null,transitions:null,pendingSuspenseBoundaries:null},Mqe(i),s}function Kes(s,t,n){var r=3"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(R2t)}catch(s){console.error(s)}}R2t(),Rwt.exports=ww;var n1=Rwt.exports;const Qqe=Uc(n1);var O2t,Vnt=n1;O2t=Vnt.createRoot,Vnt.hydrateRoot;const Jes=new Set(["localhost","relevelup.com","thelocalmove.com","www.thelocalmove.com"]),ets=s=>s.toLowerCase().replace(/:\d+$/,"").replace(/^www\./,"");function tts(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")||Jes.has(s))}function F2t(s){return z2t(s)!==null}function z2t(s){const t=ets(s);return tts(t)?null:t}const sts=1,nts=1e6;let lLe=0;function rts(){return lLe=(lLe+1)%Number.MAX_SAFE_INTEGER,lLe.toString()}const cLe=new Map,Hnt=s=>{if(cLe.has(s))return;const t=setTimeout(()=>{cLe.delete(s),mK({type:"REMOVE_TOAST",toastId:s})},nts);cLe.set(s,t)},ats=(s,t)=>{switch(t.type){case"ADD_TOAST":return{...s,toasts:[t.toast,...s.toasts].slice(0,sts)};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?Hnt(n):s.toasts.forEach(r=>{Hnt(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)}}},yie=[];let vie={toasts:[]};function mK(s){vie=ats(vie,s),yie.forEach(t=>{t(vie)})}function ja({...s}){const t=rts(),n=a=>mK({type:"UPDATE_TOAST",toast:{...a,id:t}}),r=()=>mK({type:"DISMISS_TOAST",toastId:t});return mK({type:"ADD_TOAST",toast:{...s,id:t,open:!0,onOpenChange:a=>{a||r()}}}),{id:t,dismiss:r,update:n}}function gi(){const[s,t]=j.useState(vie);return j.useEffect(()=>(yie.push(t),()=>{const n=yie.indexOf(t);n>-1&&yie.splice(n,1)}),[s]),{...s,toast:ja,dismiss:n=>mK({type:"DISMISS_TOAST",toastId:n})}}function xa(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 Gnt(s,t){if(typeof s=="function")return s(t);s!=null&&(s.current=t)}function oC(...s){return t=>{let n=!1;const r=s.map(a=>{const i=Gnt(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 ip(s,t=[]){let n=[];function r(i,l){const o=j.createContext(l),c=n.length;n=[...n,l];const d=h=>{var b;const{scope:m,children:p,...x}=h,g=((b=m==null?void 0:m[s])==null?void 0:b[c])||o,y=j.useMemo(()=>x,Object.values(x));return e.jsx(g.Provider,{value:y,children:p})};d.displayName=i+"Provider";function u(h,m){var g;const p=((g=m==null?void 0:m[s])==null?void 0:g[c])||o,x=j.useContext(p);if(x)return x;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,ots(a,...t)]}function ots(...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 QT(s){const t=lts(s),n=j.forwardRef((r,a)=>{const{children:i,...l}=r,o=j.Children.toArray(i),c=o.find(cts);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 Jqe=QT("Slot");function lts(s){const t=j.forwardRef((n,r)=>{const{children:a,...i}=n;if(j.isValidElement(a)){const l=uts(a),o=dts(i,a.props);return a.type!==j.Fragment&&(o.ref=r?oC(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 B2t=Symbol("radix.slottable");function $2t(s){const t=({children:n})=>e.jsx(e.Fragment,{children:n});return t.displayName=`${s}.Slottable`,t.__radixId=B2t,t}function cts(s){return j.isValidElement(s)&&typeof s.type=="function"&&"__radixId"in s.type&&s.type.__radixId===B2t}function dts(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 uts(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 uq(s){const t=s+"CollectionProvider",[n,r]=ip(t),[a,i]=n(t,{collectionRef:{current:null},itemMap:new Map}),l=g=>{const{scope:y,children:b}=g,v=It.useRef(null),N=It.useRef(new Map).current;return e.jsx(a,{scope:y,itemMap:N,collectionRef:v,children:b})};l.displayName=t;const o=s+"CollectionSlot",c=QT(o),d=It.forwardRef((g,y)=>{const{scope:b,children:v}=g,N=i(o,b),C=Po(y,N.collectionRef);return e.jsx(c,{ref:C,children:v})});d.displayName=o;const u=s+"CollectionItemSlot",h="data-radix-collection-item",m=QT(u),p=It.forwardRef((g,y)=>{const{scope:b,children:v,...N}=g,C=It.useRef(null),A=Po(y,C),T=i(u,b);return It.useEffect(()=>(T.itemMap.set(C,{ref:C,...N}),()=>void T.itemMap.delete(C))),e.jsx(m,{[h]:"",ref:A,children:v})});p.displayName=u;function x(g){const y=i(s+"CollectionConsumer",g);return It.useCallback(()=>{const v=y.collectionRef.current;if(!v)return[];const N=Array.from(v.querySelectorAll(`[${h}]`));return Array.from(y.itemMap.values()).sort((T,P)=>N.indexOf(T.ref.current)-N.indexOf(P.ref.current))},[y.collectionRef,y.itemMap])}return[{Provider:l,Slot:d,ItemSlot:p},x,r]}var hts=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],Ka=hts.reduce((s,t)=>{const n=QT(`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 eVe(s,t){s&&n1.flushSync(()=>s.dispatchEvent(t))}function bf(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 mts(s,t=globalThis==null?void 0:globalThis.document){const n=bf(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 pts="DismissableLayer",COe="dismissableLayer.update",fts="dismissableLayer.pointerDownOutside",xts="dismissableLayer.focusOutside",Wnt,U2t=j.createContext({layers:new Set,layersWithOutsidePointerEventsDisabled:new Set,branches:new Set}),j6=j.forwardRef((s,t)=>{const{disableOutsidePointerEvents:n=!1,onEscapeKeyDown:r,onPointerDownOutside:a,onFocusOutside:i,onInteractOutside:l,onDismiss:o,...c}=s,d=j.useContext(U2t),[u,h]=j.useState(null),m=(u==null?void 0:u.ownerDocument)??(globalThis==null?void 0:globalThis.document),[,p]=j.useState({}),x=Po(t,P=>h(P)),g=Array.from(d.layers),[y]=[...d.layersWithOutsidePointerEventsDisabled].slice(-1),b=g.indexOf(y),v=u?g.indexOf(u):-1,N=d.layersWithOutsidePointerEventsDisabled.size>0,C=v>=b,A=yts(P=>{const M=P.target,I=[...d.branches].some(D=>D.contains(M));!C||I||(a==null||a(P),l==null||l(P),P.defaultPrevented||o==null||o())},m),T=vts(P=>{const M=P.target;[...d.branches].some(D=>D.contains(M))||(i==null||i(P),l==null||l(P),P.defaultPrevented||o==null||o())},m);return mts(P=>{v===d.layers.size-1&&(r==null||r(P),!P.defaultPrevented&&o&&(P.preventDefault(),o()))},m),j.useEffect(()=>{if(u)return n&&(d.layersWithOutsidePointerEventsDisabled.size===0&&(Wnt=m.body.style.pointerEvents,m.body.style.pointerEvents="none"),d.layersWithOutsidePointerEventsDisabled.add(u)),d.layers.add(u),Knt(),()=>{n&&d.layersWithOutsidePointerEventsDisabled.size===1&&(m.body.style.pointerEvents=Wnt)}},[u,m,n,d]),j.useEffect(()=>()=>{u&&(d.layers.delete(u),d.layersWithOutsidePointerEventsDisabled.delete(u),Knt())},[u,d]),j.useEffect(()=>{const P=()=>p({});return document.addEventListener(COe,P),()=>document.removeEventListener(COe,P)},[]),e.jsx(Ka.div,{...c,ref:x,style:{pointerEvents:N?C?"auto":"none":void 0,...s.style},onFocusCapture:xa(s.onFocusCapture,T.onFocusCapture),onBlurCapture:xa(s.onBlurCapture,T.onBlurCapture),onPointerDownCapture:xa(s.onPointerDownCapture,A.onPointerDownCapture)})});j6.displayName=pts;var gts="DismissableLayerBranch",q2t=j.forwardRef((s,t)=>{const n=j.useContext(U2t),r=j.useRef(null),a=Po(t,r);return j.useEffect(()=>{const i=r.current;if(i)return n.branches.add(i),()=>{n.branches.delete(i)}},[n.branches]),e.jsx(Ka.div,{...s,ref:a})});q2t.displayName=gts;function yts(s,t=globalThis==null?void 0:globalThis.document){const n=bf(s),r=j.useRef(!1),a=j.useRef(()=>{});return j.useEffect(()=>{const i=o=>{if(o.target&&!r.current){let c=function(){V2t(fts,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 vts(s,t=globalThis==null?void 0:globalThis.document){const n=bf(s),r=j.useRef(!1);return j.useEffect(()=>{const a=i=>{i.target&&!r.current&&V2t(xts,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 Knt(){const s=new CustomEvent(COe);document.dispatchEvent(s)}function V2t(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?eVe(a,i):a.dispatchEvent(i)}var bts=j6,_ts=q2t,Sf=globalThis!=null&&globalThis.document?j.useLayoutEffect:()=>{},wts="Portal",hq=j.forwardRef((s,t)=>{var o;const{container:n,...r}=s,[a,i]=j.useState(!1);Sf(()=>i(!0),[]);const l=n||a&&((o=globalThis==null?void 0:globalThis.document)==null?void 0:o.body);return l?Qqe.createPortal(e.jsx(Ka.div,{...r,ref:t}),l):null});hq.displayName=wts;function jts(s,t){return j.useReducer((n,r)=>t[n][r]??n,s)}var dx=s=>{const{present:t,children:n}=s,r=Nts(t),a=typeof n=="function"?n({present:r.isPresent}):j.Children.only(n),i=Po(r.ref,kts(a));return typeof n=="function"||r.isPresent?j.cloneElement(a,{ref:i}):null};dx.displayName="Presence";function Nts(s){const[t,n]=j.useState(),r=j.useRef(null),a=j.useRef(s),i=j.useRef("none"),l=s?"mounted":"unmounted",[o,c]=jts(l,{mounted:{UNMOUNT:"unmounted",ANIMATION_OUT:"unmountSuspended"},unmountSuspended:{MOUNT:"mounted",ANIMATION_END:"unmounted"},unmounted:{MOUNT:"mounted"}});return j.useEffect(()=>{const d=rne(r.current);i.current=o==="mounted"?d:"none"},[o]),Sf(()=>{const d=r.current,u=a.current;if(u!==s){const m=i.current,p=rne(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]),Sf(()=>{if(t){let d;const u=t.ownerDocument.defaultView??window,h=p=>{const g=rne(r.current).includes(p.animationName);if(p.target===t&&g&&(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=rne(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 rne(s){return(s==null?void 0:s.animationName)||"none"}function kts(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 Sts=oqe[" useInsertionEffect ".trim().toString()]||Sf;function Ux({prop:s,defaultProp:t,onChange:n=()=>{},caller:r}){const[a,i,l]=Cts({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=Ats(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 Cts({defaultProp:s,onChange:t}){const[n,r]=j.useState(s),a=j.useRef(n),i=j.useRef(t);return Sts(()=>{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 Ats(s){return typeof s=="function"}var H2t=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"}),Ets="VisuallyHidden",I3e=j.forwardRef((s,t)=>e.jsx(Ka.span,{...s,ref:t,style:{...H2t,...s.style}}));I3e.displayName=Ets;var Tts=I3e,tVe="ToastProvider",[sVe,Mts,Lts]=uq("Toast"),[G2t,uXn]=ip("Toast",[Lts]),[Pts,D3e]=G2t(tVe),W2t=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 \`${tVe}\`. Expected non-empty \`string\`.`),e.jsx(sVe.Provider,{scope:t,children:e.jsx(Pts,{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})})};W2t.displayName=tVe;var K2t="ToastViewport",Its=["F8"],AOe="toast.viewportPause",EOe="toast.viewportResume",Y2t=j.forwardRef((s,t)=>{const{__scopeToast:n,hotkey:r=Its,label:a="Notifications ({hotkey})",...i}=s,l=D3e(K2t,n),o=Mts(n),c=j.useRef(null),d=j.useRef(null),u=j.useRef(null),h=j.useRef(null),m=Po(t,h,l.onViewportChange),p=r.join("+").replace(/Key/g,"").replace(/Digit/g,""),x=l.toastCount>0;j.useEffect(()=>{const y=b=>{var N;r.length!==0&&r.every(C=>b[C]||b.code===C)&&((N=h.current)==null||N.focus())};return document.addEventListener("keydown",y),()=>document.removeEventListener("keydown",y)},[r]),j.useEffect(()=>{const y=c.current,b=h.current;if(x&&y&&b){const v=()=>{if(!l.isClosePausedRef.current){const T=new CustomEvent(AOe);b.dispatchEvent(T),l.isClosePausedRef.current=!0}},N=()=>{if(l.isClosePausedRef.current){const T=new CustomEvent(EOe);b.dispatchEvent(T),l.isClosePausedRef.current=!1}},C=T=>{!y.contains(T.relatedTarget)&&N()},A=()=>{y.contains(document.activeElement)||N()};return y.addEventListener("focusin",v),y.addEventListener("focusout",C),y.addEventListener("pointermove",v),y.addEventListener("pointerleave",A),window.addEventListener("blur",v),window.addEventListener("focus",N),()=>{y.removeEventListener("focusin",v),y.removeEventListener("focusout",C),y.removeEventListener("pointermove",v),y.removeEventListener("pointerleave",A),window.removeEventListener("blur",v),window.removeEventListener("focus",N)}}},[x,l.isClosePausedRef]);const g=j.useCallback(({tabbingDirection:y})=>{const v=o().map(N=>{const C=N.ref.current,A=[C,...Wts(C)];return y==="forwards"?A:A.reverse()});return(y==="forwards"?v.reverse():v).flat()},[o]);return j.useEffect(()=>{const y=h.current;if(y){const b=v=>{var A,T,P;const N=v.altKey||v.ctrlKey||v.metaKey;if(v.key==="Tab"&&!N){const M=document.activeElement,I=v.shiftKey;if(v.target===y&&I){(A=d.current)==null||A.focus();return}const q=g({tabbingDirection:I?"backwards":"forwards"}),W=q.findIndex(V=>V===M);dLe(q.slice(W+1))?v.preventDefault():I?(T=d.current)==null||T.focus():(P=u.current)==null||P.focus()}};return y.addEventListener("keydown",b),()=>y.removeEventListener("keydown",b)}},[o,g]),e.jsxs(_ts,{ref:c,role:"region","aria-label":a.replace("{hotkey}",p),tabIndex:-1,style:{pointerEvents:x?void 0:"none"},children:[x&&e.jsx(TOe,{ref:d,onFocusFromOutsideViewport:()=>{const y=g({tabbingDirection:"forwards"});dLe(y)}}),e.jsx(sVe.Slot,{scope:n,children:e.jsx(Ka.ol,{tabIndex:-1,...i,ref:m})}),x&&e.jsx(TOe,{ref:u,onFocusFromOutsideViewport:()=>{const y=g({tabbingDirection:"backwards"});dLe(y)}})]})});Y2t.displayName=K2t;var Z2t="ToastFocusProxy",TOe=j.forwardRef((s,t)=>{const{__scopeToast:n,onFocusFromOutsideViewport:r,...a}=s,i=D3e(Z2t,n);return e.jsx(I3e,{"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()}})});TOe.displayName=Z2t;var GJ="Toast",Dts="toast.swipeStart",Rts="toast.swipeMove",Ots="toast.swipeCancel",Fts="toast.swipeEnd",X2t=j.forwardRef((s,t)=>{const{forceMount:n,open:r,defaultOpen:a,onOpenChange:i,...l}=s,[o,c]=Ux({prop:r,defaultProp:a??!0,onChange:i,caller:GJ});return e.jsx(dx,{present:n||o,children:e.jsx($ts,{open:o,...l,ref:t,onClose:()=>c(!1),onPause:bf(s.onPause),onResume:bf(s.onResume),onSwipeStart:xa(s.onSwipeStart,d=>{d.currentTarget.setAttribute("data-swipe","start")}),onSwipeMove:xa(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:xa(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:xa(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)})})})});X2t.displayName=GJ;var[zts,Bts]=G2t(GJ,{onClose(){}}),$ts=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,...x}=s,g=D3e(GJ,n),[y,b]=j.useState(null),v=Po(t,V=>b(V)),N=j.useRef(null),C=j.useRef(null),A=a||g.duration,T=j.useRef(0),P=j.useRef(A),M=j.useRef(0),{onToastAdd:I,onToastRemove:D}=g,B=bf(()=>{var K;(y==null?void 0:y.contains(document.activeElement))&&((K=g.viewport)==null||K.focus()),l()}),q=j.useCallback(V=>{!V||V===1/0||(window.clearTimeout(M.current),T.current=new Date().getTime(),M.current=window.setTimeout(B,V))},[B]);j.useEffect(()=>{const V=g.viewport;if(V){const K=()=>{q(P.current),d==null||d()},Q=()=>{const J=new Date().getTime()-T.current;P.current=P.current-J,window.clearTimeout(M.current),c==null||c()};return V.addEventListener(AOe,Q),V.addEventListener(EOe,K),()=>{V.removeEventListener(AOe,Q),V.removeEventListener(EOe,K)}}},[g.viewport,A,c,d,q]),j.useEffect(()=>{i&&!g.isClosePausedRef.current&&q(A)},[i,A,g.isClosePausedRef,q]),j.useEffect(()=>(I(),()=>D()),[I,D]);const W=j.useMemo(()=>y?rNt(y):null,[y]);return g.viewport?e.jsxs(e.Fragment,{children:[W&&e.jsx(Uts,{__scopeToast:n,role:"status","aria-live":r==="foreground"?"assertive":"polite","aria-atomic":!0,children:W}),e.jsx(zts,{scope:n,onClose:B,children:n1.createPortal(e.jsx(sVe.ItemSlot,{scope:n,children:e.jsx(bts,{asChild:!0,onEscapeKeyDown:xa(o,()=>{g.isFocusedToastEscapeKeyDownRef.current||B(),g.isFocusedToastEscapeKeyDownRef.current=!1}),children:e.jsx(Ka.li,{role:"status","aria-live":"off","aria-atomic":!0,tabIndex:0,"data-state":i?"open":"closed","data-swipe-direction":g.swipeDirection,...x,ref:v,style:{userSelect:"none",touchAction:"none",...s.style},onKeyDown:xa(s.onKeyDown,V=>{V.key==="Escape"&&(o==null||o(V.nativeEvent),V.nativeEvent.defaultPrevented||(g.isFocusedToastEscapeKeyDownRef.current=!0,B()))}),onPointerDown:xa(s.onPointerDown,V=>{V.button===0&&(N.current={x:V.clientX,y:V.clientY})}),onPointerMove:xa(s.onPointerMove,V=>{if(!N.current)return;const K=V.clientX-N.current.x,Q=V.clientY-N.current.y,J=!!C.current,ce=["left","right"].includes(g.swipeDirection),ue=["left","up"].includes(g.swipeDirection)?Math.min:Math.max,ne=ce?ue(0,K):0,ee=ce?0:ue(0,Q),le=V.pointerType==="touch"?10:2,he={x:ne,y:ee},ve={originalEvent:V,delta:he};J?(C.current=he,ane(Rts,h,ve,{discrete:!1})):Ynt(he,g.swipeDirection,le)?(C.current=he,ane(Dts,u,ve,{discrete:!1}),V.target.setPointerCapture(V.pointerId)):(Math.abs(K)>le||Math.abs(Q)>le)&&(N.current=null)}),onPointerUp:xa(s.onPointerUp,V=>{const K=C.current,Q=V.target;if(Q.hasPointerCapture(V.pointerId)&&Q.releasePointerCapture(V.pointerId),C.current=null,N.current=null,K){const J=V.currentTarget,ce={originalEvent:V,delta:K};Ynt(K,g.swipeDirection,g.swipeThreshold)?ane(Fts,p,ce,{discrete:!0}):ane(Ots,m,ce,{discrete:!0}),J.addEventListener("click",ue=>ue.preventDefault(),{once:!0})}})})})}),g.viewport)})]}):null}),Uts=s=>{const{__scopeToast:t,children:n,...r}=s,a=D3e(GJ,t),[i,l]=j.useState(!1),[o,c]=j.useState(!1);return Hts(()=>l(!0)),j.useEffect(()=>{const d=window.setTimeout(()=>c(!0),1e3);return()=>window.clearTimeout(d)},[]),o?null:e.jsx(hq,{asChild:!0,children:e.jsx(I3e,{...r,children:i&&e.jsxs(e.Fragment,{children:[a.label," ",n]})})})},qts="ToastTitle",Q2t=j.forwardRef((s,t)=>{const{__scopeToast:n,...r}=s;return e.jsx(Ka.div,{...r,ref:t})});Q2t.displayName=qts;var Vts="ToastDescription",J2t=j.forwardRef((s,t)=>{const{__scopeToast:n,...r}=s;return e.jsx(Ka.div,{...r,ref:t})});J2t.displayName=Vts;var eNt="ToastAction",tNt=j.forwardRef((s,t)=>{const{altText:n,...r}=s;return n.trim()?e.jsx(nNt,{altText:n,asChild:!0,children:e.jsx(nVe,{...r,ref:t})}):(console.error(`Invalid prop \`altText\` supplied to \`${eNt}\`. Expected non-empty \`string\`.`),null)});tNt.displayName=eNt;var sNt="ToastClose",nVe=j.forwardRef((s,t)=>{const{__scopeToast:n,...r}=s,a=Bts(sNt,n);return e.jsx(nNt,{asChild:!0,children:e.jsx(Ka.button,{type:"button",...r,ref:t,onClick:xa(s.onClick,a.onClose)})})});nVe.displayName=sNt;var nNt=j.forwardRef((s,t)=>{const{__scopeToast:n,altText:r,...a}=s;return e.jsx(Ka.div,{"data-radix-toast-announce-exclude":"","data-radix-toast-announce-alt":r||void 0,...a,ref:t})});function rNt(s){const t=[];return Array.from(s.childNodes).forEach(r=>{if(r.nodeType===r.TEXT_NODE&&r.textContent&&t.push(r.textContent),Gts(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(...rNt(r))}}),t}function ane(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?eVe(a,i):a.dispatchEvent(i)}var Ynt=(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 Hts(s=()=>{}){const t=bf(s);Sf(()=>{let n=0,r=0;return n=window.requestAnimationFrame(()=>r=window.requestAnimationFrame(t)),()=>{window.cancelAnimationFrame(n),window.cancelAnimationFrame(r)}},[t])}function Gts(s){return s.nodeType===s.ELEMENT_NODE}function Wts(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 dLe(s){const t=document.activeElement;return s.some(n=>n===t?!0:(n.focus(),document.activeElement!==t))}var Kts=W2t,aNt=Y2t,iNt=X2t,oNt=Q2t,lNt=J2t,cNt=tNt,dNt=nVe;function uNt(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,Xnt=$l,GO=(s,t)=>n=>{var r;if((t==null?void 0:t.variants)==null)return Xnt(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=Znt(u)||Znt(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(x=>{let[g,y]=x;return Array.isArray(y)?y.includes({...i,...o}[g]):{...i,...o}[g]===y})?[...d,h,m]:d},[]);return Xnt(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 Yts=s=>s.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),hNt=(...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 Zts={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 mNt=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,...Zts,width:t,height:t,stroke:s,strokeWidth:r?Number(n)*24/Number(t):n,className:hNt("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 de=(s,t)=>{const n=j.forwardRef(({className:r,...a},i)=>j.createElement(mNt,{ref:i,iconNode:t,className:hNt(`lucide-${Yts(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 bie=de("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 _ie=de("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 wie=de("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 jie=de("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 zp=de("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 Nie=de("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 kie=de("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 QM=de("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 JM=de("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 Sie=de("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 eL=de("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 Cie=de("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 Aie=de("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 Eie=de("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 Tie=de("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 Mie=de("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 aR=de("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 Lie=de("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 Pie=de("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 Iie=de("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 Die=de("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 Rie=de("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 Oie=de("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 Fie=de("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 zie=de("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 Bie=de("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 $ie=de("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 Uie=de("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 iR=de("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 oR=de("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 qie=de("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 Vie=de("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 Hie=de("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 Gie=de("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 Wie=de("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 Kie=de("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 Yie=de("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 Zie=de("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 Xie=de("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 Qie=de("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 Jie=de("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 eoe=de("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 toe=de("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 soe=de("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 noe=de("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 roe=de("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 aoe=de("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 ioe=de("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 ooe=de("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 loe=de("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 coe=de("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 doe=de("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 uoe=de("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 hT=de("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 hoe=de("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 Am=de("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 moe=de("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 poe=de("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 foe=de("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 xoe=de("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 goe=de("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 yoe=de("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 voe=de("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 boe=de("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 _oe=de("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 woe=de("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 joe=de("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 tL=de("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 Noe=de("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 koe=de("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 Soe=de("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 pK=de("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 Coe=de("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 Aoe=de("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 Eoe=de("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 sL=de("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 nL=de("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 ax=de("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 Toe=de("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 fK=de("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 Moe=de("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 ka=de("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 Loe=de("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 QS=de("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 Poe=de("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 ni=de("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 Ioe=de("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 Doe=de("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 rL=de("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 Tx=de("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 Roe=de("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 Ooe=de("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 Foe=de("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 aL=de("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 mT=de("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 zoe=de("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 Boe=de("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 iL=de("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 sp=de("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 $oe=de("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 Uoe=de("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 qoe=de("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 Voe=de("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 Hoe=de("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 Goe=de("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 pu=de("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 Woe=de("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 oL=de("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 Koe=de("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 Yoe=de("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 Zoe=de("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 Xoe=de("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 lL=de("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 Qoe=de("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 Joe=de("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 ele=de("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 tle=de("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 sle=de("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 nle=de("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 rle=de("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 ale=de("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 ile=de("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 ole=de("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 lle=de("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 cle=de("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 dle=de("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 ule=de("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 hle=de("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 fz=de("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 mle=de("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 ple=de("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 fle=de("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 xle=de("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 gle=de("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 _g=de("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 yle=de("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 vle=de("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 ble=de("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 _le=de("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 wle=de("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 jle=de("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 xK=de("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 Nle=de("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 kle=de("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 JS=de("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 Sle=de("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 tw=de("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 Cle=de("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 Ale=de("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 Ele=de("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 Tle=de("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 Mle=de("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 Lle=de("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 e5=de("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 Ple=de("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 $3=de("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 Dx=de("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 cL=de("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 dL=de("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 Ile=de("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 Dle=de("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 Rle=de("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 Ole=de("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 Fle=de("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 zle=de("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 Ble=de("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 $le=de("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 Ule=de("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 qle=de("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 Vle=de("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 Hle=de("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 Gle=de("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 Wle=de("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 Kle=de("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 Yle=de("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 pT=de("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 Zle=de("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 Xle=de("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 Qle=de("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 Jle=de("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 ece=de("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 tce=de("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 sce=de("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 uL=de("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 nce=de("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 rce=de("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 ace=de("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 ice=de("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 oce=de("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 lce=de("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 cce=de("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 dce=de("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 uce=de("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 hce=de("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 wf=de("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 mce=de("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 pce=de("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 fce=de("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 xce=de("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 gce=de("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 yce=de("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 vce=de("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 bce=de("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 _ce=de("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 wce=de("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 fT=de("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 jce=de("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 wg=de("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 Nce=de("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 kce=de("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 Sce=de("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 t5=de("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 gK=de("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 Cce=de("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 hL=de("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 Ace=de("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 Ece=de("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 Tce=de("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 yK=de("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 Mce=de("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 Lce=de("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 Pce=de("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 Ice=de("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 ix=de("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 Dce=de("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 Rce=de("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 Oce=de("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 Fce=de("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 zce=de("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 Ai=de("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 lR=de("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 Bce=de("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 $ce=de("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 Uce=de("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 qce=de("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 Vce=de("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 np=de("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 s5=de("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 Hce=de("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 Gce=de("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 Wce=de("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 Kce=de("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 gy=de("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 Xu=de("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 Yce=de("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 Nl=de("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 Zce=de("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 LN=de("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 Xce=de("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 Qce=de("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 xz=de("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 Jce=de("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 gg=de("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 ede=de("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 tde=de("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 sde=de("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 nde=de("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 vK=de("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 ia=de("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 rde=de("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 y0=de("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 ade=de("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 ide=de("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 ode=de("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 lde=de("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 cde=de("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 mL=de("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 dde=de("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 ude=de("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 hde=de("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 mde=de("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 pde=de("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 fde=de("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 xde=de("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 gde=de("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 yde=de("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 vde=de("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 bde=de("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 _de=de("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 wde=de("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 pL=de("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 fL=de("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 jde=de("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 Nde=de("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 kde=de("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 xL=de("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 gL=de("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 yL=de("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 Sde=de("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 vL=de("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 Cde=de("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 ml=de("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 Ade=de("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 bL=de("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 Ede=de("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 Tde=de("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 _L=de("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 wL=de("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 Mde=de("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 jL=de("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 NL=de("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 kL=de("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 Lde=de("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 cR=de("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 oa=de("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 Pde=de("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 Ide=de("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 _o=de("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 Dde=de("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 Rde=de("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 Ic=de("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 Ja=de("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 jg=de("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 Ode=de("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 Fde=de("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 zde=de("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 Bde=de("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 $de=de("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 Ude=de("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 qde=de("ChevronsRight",[["path",{d:"m6 17 5-5-5-5",key:"xnjwq"}],["path",{d:"m13 17 5-5-5-5",key:"17xmmf"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const sw=de("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 Vde=de("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 dR=de("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 Hde=de("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 Gde=de("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 Wde=de("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 xo=de("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 SL=de("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 CL=de("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 AL=de("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 EL=de("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 TL=de("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 ML=de("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 LL=de("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 PL=de("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 Ro=de("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 Fr=de("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 IL=de("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 DL=de("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 RL=de("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 OL=de("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 Kde=de("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 FL=de("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 Yde=de("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 Zde=de("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 Xde=de("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 Qde=de("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 Jde=de("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 eue=de("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 tue=de("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 zL=de("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 Z4=de("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 BL=de("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 sue=de("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 $L=de("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 UL=de("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 qL=de("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 VL=de("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 Sh=de("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 HL=de("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 GL=de("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 WL=de("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 nue=de("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 KL=de("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 YL=de("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 ZL=de("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 $d=de("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 Bp=de("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 rue=de("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 aue=de("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 gz=de("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 n5=de("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 iue=de("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 v0=de("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 oue=de("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 lue=de("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 XL=de("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 QL=de("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 cue=de("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 due=de("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 uue=de("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 hue=de("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 mue=de("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 pue=de("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 fue=de("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 xue=de("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 gue=de("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 bK=de("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 yue=de("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 vue=de("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 bue=de("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 _ue=de("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 wue=de("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 jue=de("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 Nue=de("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 kue=de("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 Sue=de("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 Hr=de("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 Cue=de("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 Aue=de("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 JL=de("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 Eue=de("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 Tue=de("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 Mue=de("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 Lue=de("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 Pue=de("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 Iue=de("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 Due=de("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 Rue=de("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 Oue=de("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 Fue=de("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 zue=de("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 Bue=de("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 eP=de("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 $ue=de("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 Uue=de("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 L3=de("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 que=de("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 X4=de("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 xT=de("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 Vue=de("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 Hue=de("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 Tb=de("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 Gue=de("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 _K=de("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 tP=de("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 DA=de("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 Wue=de("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 Kue=de("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 Yue=de("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 uR=de("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 Zue=de("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 Xue=de("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 Que=de("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 Jue=de("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 ehe=de("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 sP=de("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 hR=de("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 the=de("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 she=de("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 nhe=de("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 rhe=de("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 ahe=de("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 ihe=de("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 ohe=de("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 lhe=de("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 che=de("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 Ca=de("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 dhe=de("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 uhe=de("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 hhe=de("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 mhe=de("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 phe=de("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 fhe=de("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 xhe=de("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 ghe=de("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 yhe=de("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 vhe=de("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 bhe=de("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 _he=de("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 yy=de("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 whe=de("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 jhe=de("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 Nhe=de("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 khe=de("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 Ng=de("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 She=de("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 Che=de("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 Ahe=de("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 Ehe=de("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 The=de("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 Mhe=de("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 Lhe=de("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 wK=de("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 Phe=de("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 Ihe=de("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 Dhe=de("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 Rhe=de("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 nP=de("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 Ohe=de("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 Fhe=de("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 zhe=de("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 Bhe=de("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 $he=de("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 Uhe=de("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 qhe=de("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 Vhe=de("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 Hhe=de("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 Ghe=de("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 Whe=de("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 Khe=de("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 Yhe=de("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 Zhe=de("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 Xhe=de("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 Qhe=de("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 Jhe=de("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 eme=de("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 tme=de("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 qd=de("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 sme=de("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 nme=de("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 zj=de("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 rme=de("Dot",[["circle",{cx:"12.1",cy:"12.1",r:"1",key:"18d7e5"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const di=de("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 ame=de("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 ime=de("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 ome=de("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 lme=de("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 cme=de("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 f1=de("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 dme=de("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 ume=de("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 hme=de("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 mme=de("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 pme=de("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 fme=de("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 rP=de("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 xme=de("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 gme=de("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 yme=de("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 yz=de("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 cy=de("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 p0=de("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 vme=de("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 bme=de("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 _me=de("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 wme=de("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 jme=de("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 Nme=de("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 kme=de("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 Tr=de("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 Sme=de("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 b0=de("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 ga=de("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 jf=de("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 Cme=de("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 Ame=de("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 Eme=de("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 Tme=de("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 Mme=de("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 Lme=de("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 Pme=de("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 Ime=de("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 Dme=de("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 Rme=de("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 aP=de("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 Ome=de("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 Fme=de("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 zme=de("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 iP=de("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 oP=de("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 lP=de("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 cP=de("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 Bme=de("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 jK=de("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 $me=de("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 Ume=de("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 qme=de("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 dP=de("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 Vme=de("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 Hme=de("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 Bj=de("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 Gme=de("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 gT=de("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 Wme=de("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 Kme=de("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 Yme=de("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 Zme=de("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 Xme=de("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 Qme=de("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 Jme=de("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 epe=de("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 tpe=de("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 spe=de("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 npe=de("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 RA=de("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 uP=de("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 rpe=de("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 ape=de("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 ipe=de("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 ope=de("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 lpe=de("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 cpe=de("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 dpe=de("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 PN=de("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 NK=de("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 upe=de("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 hpe=de("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 Wr=de("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 mpe=de("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 ppe=de("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 fpe=de("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 xpe=de("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 gpe=de("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 kK=de("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 ype=de("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 vpe=de("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 bpe=de("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 _pe=de("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 wpe=de("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 vz=de("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 jpe=de("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 lh=de("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 Npe=de("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 $j=de("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 kpe=de("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 Spe=de("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 Cpe=de("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 Ape=de("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 Epe=de("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 Tpe=de("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 Mpe=de("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 Lpe=de("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 U3=de("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 Ppe=de("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 yd=de("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 Ipe=de("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 Dpe=de("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 Rpe=de("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 yT=de("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 Ope=de("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 Fpe=de("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 SK=de("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 zpe=de("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 Bpe=de("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 CN=de("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 $pe=de("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 Upe=de("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 qpe=de("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 Vpe=de("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 Hpe=de("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 Gpe=de("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 Wpe=de("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 Kpe=de("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 Ype=de("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 hP=de("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 Zpe=de("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 Xpe=de("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 Qpe=de("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 Jpe=de("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 efe=de("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 tfe=de("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 sfe=de("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 nfe=de("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 rfe=de("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 afe=de("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 ife=de("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 cv=de("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 ofe=de("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 mP=de("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 lfe=de("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 cfe=de("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 dfe=de("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 ufe=de("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 hfe=de("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 mfe=de("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 pfe=de("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 ffe=de("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 xfe=de("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 gfe=de("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 yfe=de("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 vfe=de("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 bfe=de("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 _fe=de("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 wfe=de("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 jfe=de("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 Nfe=de("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 kfe=de("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 Sfe=de("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 Cfe=de("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 Afe=de("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 Efe=de("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 Tfe=de("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 Mfe=de("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 Lfe=de("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 Pfe=de("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 Ife=de("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 Dfe=de("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 Rfe=de("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 mR=de("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 Co=de("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 Ofe=de("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 Ffe=de("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 pP=de("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 zfe=de("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 Bfe=de("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 $fe=de("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 Ufe=de("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 qfe=de("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 Vfe=de("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 Hfe=de("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 Gfe=de("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 Wfe=de("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 Kfe=de("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 Yfe=de("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 Zfe=de("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 Xfe=de("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 Qfe=de("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 Jfe=de("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 exe=de("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 txe=de("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 Gl=de("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 sxe=de("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 nxe=de("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 Ph=de("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 rxe=de("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 axe=de("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 fP=de("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 ixe=de("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 xP=de("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 R_=de("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 oxe=de("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 $p=de("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 lxe=de("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 cxe=de("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 dxe=de("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 uxe=de("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 CK=de("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 hxe=de("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 pR=de("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 ES=de("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 mxe=de("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 pxe=de("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 bz=de("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 IN=de("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 fxe=de("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 xxe=de("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 AK=de("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 gxe=de("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 vT=de("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 yxe=de("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 vxe=de("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 _z=de("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 wz=de("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 EK=de("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 bxe=de("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 _xe=de("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 wxe=de("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 jxe=de("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 Nxe=de("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 kxe=de("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 Sxe=de("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 Cxe=de("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 fR=de("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 Axe=de("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 Exe=de("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 fo=de("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 Txe=de("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 Mxe=de("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 Lxe=de("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 Uj=de("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 Pxe=de("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 Ixe=de("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 Dxe=de("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 Rxe=de("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 TK=de("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 Oxe=de("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 Fxe=de("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 sa=de("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 gP=de("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 yP=de("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 zxe=de("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 Bxe=de("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 $xe=de("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 Uxe=de("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 qxe=de("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 x1=de("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 Vxe=de("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 Hxe=de("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 Jl=de("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 Gxe=de("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 Wxe=de("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 bT=de("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 vP=de("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 bP=de("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 Kxe=de("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 Yxe=de("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 r5=de("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 Zxe=de("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 Qh=de("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 _T=de("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 Xxe=de("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 Qxe=de("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 Jxe=de("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 ege=de("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 a5=de("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 q3=de("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 tge=de("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 Mb=de("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 sge=de("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 nge=de("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 rge=de("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 age=de("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 ige=de("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 oge=de("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 lge=de("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 cge=de("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 dge=de("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 uge=de("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 jz=de("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 hge=de("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 mge=de("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 _P=de("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 pge=de("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 fge=de("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 xge=de("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 gge=de("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 yge=de("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 vge=de("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 xR=de("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 gR=de("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 _0=de("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 bge=de("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 _ge=de("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 wge=de("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 nw=de("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 jge=de("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 Nge=de("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 kge=de("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 Sge=de("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 Cge=de("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 g1=de("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 Nz=de("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 Age=de("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 Ege=de("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 i5=de("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 Tge=de("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 Dc=de("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 kc=de("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 kg=de("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 Mge=de("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 Jh=de("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 Lge=de("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 Pge=de("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 MK=de("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 Ige=de("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 Dge=de("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 qj=de("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 Rge=de("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 Oge=de("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 Fge=de("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 zge=de("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 Bge=de("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 $ge=de("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 Uge=de("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 Sg=de("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 Ht=de("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 qge=de("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 Vge=de("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 Hge=de("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 Gge=de("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 kz=de("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 wP=de("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 Wge=de("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 jP=de("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 Ad=de("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 yR=de("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 vR=de("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 Kge=de("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 Yge=de("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 Zge=de("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 Xge=de("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 Sz=de("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 Qge=de("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 Cz=de("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 LK=de("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 Jge=de("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 e0e=de("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 t0e=de("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 wT=de("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 nn=de("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 s0e=de("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 n0e=de("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 r0e=de("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 a0e=de("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 i0e=de("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 o0e=de("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 l0e=de("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 c0e=de("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 d0e=de("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 u0e=de("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 h0e=de("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 m0e=de("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 ai=de("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 p0e=de("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 bR=de("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 f0e=de("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 PK=de("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 _R=de("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 V3=de("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 x0e=de("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 Eh=de("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 g0e=de("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 y0e=de("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 jT=de("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 v0e=de("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 b0e=de("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 _0e=de("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 Az=de("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 w0e=de("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 j0e=de("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 N0e=de("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 Ez=de("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 k0e=de("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 S0e=de("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 C0e=de("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 Ed=de("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 A0e=de("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 E0e=de("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 T0e=de("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 M0e=de("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 Tz=de("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 L0e=de("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 IK=de("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 P0e=de("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 BS=de("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 H3=de("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 I0e=de("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 D0e=de("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 R0e=de("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 O0e=de("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 F0e=de("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 Ji=de("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 Mz=de("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 z0e=de("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 NP=de("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 Vj=de("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 B0e=de("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 $0e=de("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 U0e=de("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 q0e=de("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 V0e=de("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 H0e=de("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 G0e=de("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 W0e=de("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 DN=de("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 K0e=de("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 Y0e=de("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 Z0e=de("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 X0e=de("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 Q0e=de("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 J0e=de("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 Lz=de("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 eye=de("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 tye=de("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 sye=de("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 wR=de("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 nye=de("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 Hj=de("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 rye=de("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 aye=de("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 iye=de("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 oye=de("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 lye=de("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 cye=de("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 dye=de("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 uu=de("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 pg=de("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 uye=de("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 kP=de("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 hye=de("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 mye=de("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 pye=de("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 fye=de("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 xye=de("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 gye=de("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 yye=de("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 vye=de("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 bye=de("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 _ye=de("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 wye=de("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 jye=de("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 DK=de("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 Nye=de("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 kye=de("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 Sye=de("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 Pz=de("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 Cye=de("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 Aye=de("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 Eye=de("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 RK=de("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 Tye=de("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 Gj=de("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 Mye=de("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 Lye=de("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 Pye=de("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 Iye=de("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 Dye=de("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 Rye=de("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 Oye=de("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 Fye=de("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 zye=de("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 _N=de("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 Bye=de("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 SP=de("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 CP=de("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 $ye=de("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 Uye=de("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 qye=de("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 Vye=de("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 Hye=de("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 Gye=de("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 Wye=de("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 Kye=de("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 Yye=de("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 OK=de("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 Zye=de("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 Xye=de("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 Tu=de("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 Qye=de("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 Jye=de("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 AP=de("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 eve=de("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 Rc=de("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 tve=de("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 EP=de("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 sve=de("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 nve=de("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 TP=de("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 MP=de("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 LP=de("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 PP=de("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 rve=de("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 IP=de("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 ave=de("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 ive=de("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 ove=de("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 DP=de("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 lve=de("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 cve=de("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 dve=de("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 uve=de("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 Q4=de("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 NT=de("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 hve=de("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 mve=de("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 Nf=de("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 vy=de("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 pve=de("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 fve=de("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 wN=de("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 xve=de("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 kT=de("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 kj=de("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 Iz=de("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 gve=de("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 yve=de("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 Ya=de("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 vve=de("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 ST=de("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 bve=de("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 _ve=de("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 FK=de("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 wve=de("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 jve=de("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 Nve=de("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 kve=de("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 Sve=de("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 ya=de("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 Cve=de("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 Ave=de("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 Eve=de("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 Tve=de("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 Mve=de("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 Lve=de("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 Pve=de("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 Ive=de("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 Dve=de("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 Rve=de("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 Ove=de("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 zK=de("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 CT=de("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 Fve=de("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 zve=de("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 Bve=de("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 $ve=de("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 BK=de("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 Td=de("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 Uve=de("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 RP=de("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 Wj=de("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 sn=de("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 qve=de("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 Vve=de("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 Hve=de("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 Gve=de("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 Wve=de("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 Kve=de("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 Yve=de("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 Zve=de("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 Xve=de("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 $K=de("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 by=de("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 Qve=de("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 AT=de("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 Jve=de("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 e1e=de("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 t1e=de("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 s1e=de("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 Rx=de("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 RN=de("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 n1e=de("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 Dz=de("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 r1e=de("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 a1e=de("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 i1e=de("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 o1e=de("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 Cg=de("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 l1e=de("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 c1e=de("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 d1e=de("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 u1e=de("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 h1e=de("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 m1e=de("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 p1e=de("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 f1e=de("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 x1e=de("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 g1e=de("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 y1e=de("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 v1e=de("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 b1e=de("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 _1e=de("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 OP=de("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 w1e=de("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 j1e=de("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 N1e=de("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 k1e=de("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 S1e=de("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 ET=de("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 C1e=de("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 Rz=de("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 A1e=de("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 Wi=de("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 E1e=de("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 T1e=de("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 M1e=de("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 L1e=de("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 UK=de("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 Oz=de("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 P1e=de("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 I1e=de("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 D1e=de("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 qK=de("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 R1e=de("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 O1e=de("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 w0=de("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 F1e=de("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 z1e=de("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 FP=de("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 B1e=de("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 Ih=de("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 $1e=de("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 jR=de("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 U1e=de("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 Fz=de("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 q1e=de("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 zP=de("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 BP=de("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 V1e=de("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 H1e=de("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 o5=de("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 G1e=de("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 W1e=de("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 K1e=de("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 Y1e=de("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 Z1e=de("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 X1e=de("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 Q1e=de("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 J1e=de("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 Jo=de("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 $P=de("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 VK=de("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 ebe=de("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 tbe=de("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 sbe=de("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 nbe=de("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 rbe=de("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 abe=de("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 ibe=de("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 obe=de("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 lbe=de("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 cbe=de("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 dbe=de("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 ube=de("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 hbe=de("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 mbe=de("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 HK=de("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 pbe=de("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 fbe=de("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 xbe=de("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 gbe=de("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 GK=de("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 Vr=de("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 ybe=de("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 UP=de("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 vbe=de("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 Br=de("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 bbe=de("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 _be=de("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 wbe=de("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 jbe=de("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 Nbe=de("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 kbe=de("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 G3=de("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 pc=de("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 Sbe=de("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 vd=de("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 WK=de("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 Cbe=de("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 Abe=de("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 zz=de("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 Ebe=de("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 j0=de("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 Tbe=de("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 Mbe=de("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 Lbe=de("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 NR=de("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 Pbe=de("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 Ibe=de("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 qP=de("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 kf=de("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 Dbe=de("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 Rbe=de("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 Obe=de("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 l5=de("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 Fbe=de("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 ON=de("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 zbe=de("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 Bbe=de("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 $be=de("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 Ube=de("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 kR=de("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 qbe=de("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 Vbe=de("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 Hbe=de("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 Gbe=de("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 Wbe=de("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 Kbe=de("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 Ybe=de("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 Zbe=de("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 Xbe=de("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 Qbe=de("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 Jbe=de("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 KK=de("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 e_e=de("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 t_e=de("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 s_e=de("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 n_e=de("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 TT=de("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 VP=de("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 r_e=de("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 a_e=de("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 dv=de("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 i_e=de("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 o_e=de("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 l_e=de("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 Z_=de("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 c_e=de("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 d_e=de("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 u_e=de("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 h_e=de("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 W3=de("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 dn=de("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 m_e=de("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 p_e=de("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 f_e=de("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 x_e=de("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 g_e=de("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 y_e=de("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 v_e=de("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 MT=de("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 HP=de("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 GP=de("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 WP=de("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 KP=de("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 YP=de("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 ZP=de("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 XP=de("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 QP=de("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 JP=de("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 eI=de("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 tI=de("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 sI=de("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 nI=de("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 rI=de("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 aI=de("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 Kk=de("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 TS=de("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 iI=de("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 oI=de("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 lI=de("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 cI=de("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 dI=de("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 uI=de("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 b_e=de("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 __e=de("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 hI=de("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 mI=de("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 pI=de("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 fI=de("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 xI=de("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 gI=de("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 yI=de("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 vI=de("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 bI=de("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 _I=de("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 wI=de("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 jI=de("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 NI=de("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 kI=de("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 SI=de("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 bm=de("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 CI=de("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 AI=de("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 EI=de("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 TI=de("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 MI=de("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 LI=de("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 w_e=de("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 PI=de("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 II=de("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 DI=de("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 RI=de("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 OI=de("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 j_e=de("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 N_e=de("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 FI=de("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 zI=de("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 BI=de("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 $I=de("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 Lb=de("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 k_e=de("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 S_e=de("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 C_e=de("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 A_e=de("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 E_e=de("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 Qa=de("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 T_e=de("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 M_e=de("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 L_e=de("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 P_e=de("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 SR=de("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 Bz=de("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 I_e=de("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 D_e=de("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 YK=de("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 R_e=de("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 O_e=de("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 F_e=de("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 z_e=de("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 B_e=de("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 Kj=de("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 $_e=de("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 U_e=de("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 q_e=de("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 V_e=de("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 H_e=de("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 G_e=de("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 W_e=de("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 K_e=de("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 Y_e=de("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 $z=de("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 Z_e=de("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 X_e=de("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 Q_e=de("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 J_e=de("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 ewe=de("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 twe=de("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 Uz=de("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 swe=de("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 qz=de("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 nwe=de("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 Up=de("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 ZK=de("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 rwe=de("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 awe=de("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 iwe=de("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 owe=de("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 lwe=de("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 cwe=de("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 Mu=de("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 dwe=de("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 uwe=de("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 hwe=de("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 mwe=de("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 UI=de("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 pwe=de("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 fwe=de("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 xwe=de("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 gwe=de("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 ywe=de("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 vwe=de("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 qI=de("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 bwe=de("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 _we=de("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 wwe=de("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 jwe=de("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 XK=de("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 QK=de("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 Ox=de("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 Nwe=de("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 kwe=de("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 Swe=de("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 Cwe=de("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 Awe=de("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 Ewe=de("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 CR=de("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 Twe=de("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 Mwe=de("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 Lwe=de("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 Pwe=de("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 Iwe=de("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 Dwe=de("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 Rwe=de("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 Owe=de("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 Fwe=de("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 zwe=de("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 Bwe=de("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 $we=de("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 Uwe=de("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 qwe=de("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 Vwe=de("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 Hwe=de("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 Gwe=de("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 Wwe=de("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 Kwe=de("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 VI=de("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 Pn=de("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 Ywe=de("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 Zwe=de("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 HI=de("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 LT=de("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 Xwe=de("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 Qwe=de("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 FN=de("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 Jwe=de("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 Il=de("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 mc=de("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 eje=de("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 tje=de("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 pl=de("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 JK=de("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 sje=de("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 nje=de("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 GI=de("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 rje=de("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 aje=de("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 ije=de("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 oje=de("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 lje=de("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 cje=de("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 dje=de("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 Vz=de("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 eY=de("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 uje=de("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 PT=de("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 hje=de("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 mje=de("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 pje=de("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 WI=de("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 fje=de("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 AR=de("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 tY=de("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 si=de("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 xje=de("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 Yj=de("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 sY=de("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 Hz=de("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 gje=de("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 il=de("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 KI=de("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 YI=de("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 ZI=de("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 yje=de("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 XI=de("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 vje=de("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 QI=de("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 JI=de("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 bje=de("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 _je=de("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 Lo=de("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 t1=de("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 qn=de("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 e8=de("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 t8=de("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 wje=de("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 Gz=de("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 jje=de("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 Nje=de("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 kje=de("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 Sje=de("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 Cje=de("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 Aje=de("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 Xr=de("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 Eje=de("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 Tje=de("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 Mje=de("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 Lje=de("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 Pje=de("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 nY=de("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 Ije=de("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 rY=de("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 Dje=de("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 Rje=de("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 Oje=de("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 s8=de("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 aY=de("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 Fje=de("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 wm=de("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 zje=de("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 Bje=de("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 $je=de("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 Uje=de("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 qje=de("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 Vje=de("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 Hje=de("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 Gje=de("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 Wje=de("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 Kje=de("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 Yje=de("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 Zje=de("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 Xje=de("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 Qje=de("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 Jje=de("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 e2e=de("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 t2e=de("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 s2e=de("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 n2e=de("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 r2e=de("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 a2e=de("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 iY=de("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 oY=de("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 i2e=de("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 o2e=de("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 c5=de("Wrench",[["path",{d:"M14.7 6.3a1 1 0 0 0 0 1.4l1.6 1.6a1 1 0 0 0 1.4 0l3.77-3.77a6 6 0 0 1-7.94 7.94l-6.91 6.91a2.12 2.12 0 0 1-3-3l6.91-6.91a6 6 0 0 1 7.94-7.94l-3.76 3.76z",key:"cbrjhi"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const pr=de("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 l2e=de("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 c2e=de("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 ox=de("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 IT=de("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 Wz=de("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 Xts=Object.freeze(Object.defineProperty({__proto__:null,AArrowDown:bie,AArrowUp:_ie,ALargeSmall:wie,Accessibility:jie,Activity:zp,AirVent:Nie,Airplay:kie,AlarmClock:Cie,AlarmClockCheck:QM,AlarmClockMinus:JM,AlarmClockOff:Sie,AlarmClockPlus:eL,AlarmSmoke:Aie,Album:Eie,AlignCenter:aR,AlignCenterHorizontal:Tie,AlignCenterVertical:Mie,AlignEndHorizontal:Lie,AlignEndVertical:Pie,AlignHorizontalDistributeCenter:Iie,AlignHorizontalDistributeEnd:Die,AlignHorizontalDistributeStart:Rie,AlignHorizontalJustifyCenter:Oie,AlignHorizontalJustifyEnd:Fie,AlignHorizontalJustifyStart:zie,AlignHorizontalSpaceAround:Bie,AlignHorizontalSpaceBetween:$ie,AlignJustify:Uie,AlignLeft:iR,AlignRight:oR,AlignStartHorizontal:qie,AlignStartVertical:Vie,AlignVerticalDistributeCenter:Hie,AlignVerticalDistributeEnd:Gie,AlignVerticalDistributeStart:Wie,AlignVerticalJustifyCenter:Kie,AlignVerticalJustifyEnd:Yie,AlignVerticalJustifyStart:Zie,AlignVerticalSpaceAround:Xie,AlignVerticalSpaceBetween:Qie,Ambulance:Jie,Ampersand:eoe,Ampersands:toe,Amphora:soe,Anchor:noe,Angry:roe,Annoyed:aoe,Antenna:ioe,Anvil:ooe,Aperture:loe,AppWindow:doe,AppWindowMac:coe,Apple:uoe,Archive:Am,ArchiveRestore:hT,ArchiveX:hoe,Armchair:moe,ArrowBigDown:foe,ArrowBigDownDash:poe,ArrowBigLeft:goe,ArrowBigLeftDash:xoe,ArrowBigRight:voe,ArrowBigRightDash:yoe,ArrowBigUp:_oe,ArrowBigUpDash:boe,ArrowDown:ax,ArrowDown01:woe,ArrowDown10:joe,ArrowDownAZ:tL,ArrowDownFromLine:Noe,ArrowDownLeft:koe,ArrowDownNarrowWide:Soe,ArrowDownRight:pK,ArrowDownToDot:Coe,ArrowDownToLine:Aoe,ArrowDownUp:Eoe,ArrowDownWideNarrow:sL,ArrowDownZA:nL,ArrowLeft:ka,ArrowLeftFromLine:Toe,ArrowLeftRight:fK,ArrowLeftToLine:Moe,ArrowRight:ni,ArrowRightFromLine:Loe,ArrowRightLeft:QS,ArrowRightToLine:Poe,ArrowUp:sp,ArrowUp01:Ioe,ArrowUp10:Doe,ArrowUpAZ:rL,ArrowUpDown:Tx,ArrowUpFromDot:Roe,ArrowUpFromLine:Ooe,ArrowUpLeft:Foe,ArrowUpNarrowWide:aL,ArrowUpRight:mT,ArrowUpToLine:zoe,ArrowUpWideNarrow:Boe,ArrowUpZA:iL,ArrowsUpFromLine:$oe,Asterisk:Uoe,AtSign:qoe,Atom:Voe,AudioLines:Hoe,AudioWaveform:Goe,Award:pu,Axe:Woe,Axis3d:oL,Baby:Koe,Backpack:Yoe,Badge:ule,BadgeAlert:Zoe,BadgeCent:Xoe,BadgeCheck:lL,BadgeDollarSign:Qoe,BadgeEuro:Joe,BadgeHelp:ele,BadgeIndianRupee:tle,BadgeInfo:sle,BadgeJapaneseYen:nle,BadgeMinus:rle,BadgePercent:ale,BadgePlus:ile,BadgePoundSterling:ole,BadgeRussianRuble:lle,BadgeSwissFranc:cle,BadgeX:dle,BaggageClaim:hle,Ban:fz,Banana:mle,Bandage:ple,Banknote:fle,Barcode:xle,Baseline:gle,Bath:_g,Battery:jle,BatteryCharging:yle,BatteryFull:vle,BatteryLow:ble,BatteryMedium:_le,BatteryWarning:wle,Beaker:xK,Bean:kle,BeanOff:Nle,Bed:tw,BedDouble:JS,BedSingle:Sle,Beef:Cle,Beer:Ele,BeerOff:Ale,Bell:Dx,BellDot:Tle,BellElectric:Mle,BellMinus:Lle,BellOff:e5,BellPlus:Ple,BellRing:$3,BetweenHorizontalEnd:cL,BetweenHorizontalStart:dL,BetweenVerticalEnd:Ile,BetweenVerticalStart:Dle,BicepsFlexed:Rle,Bike:Ole,Binary:Fle,Binoculars:zle,Biohazard:Ble,Bird:$le,Bitcoin:Ule,Blend:qle,Blinds:Vle,Blocks:Hle,Bluetooth:Yle,BluetoothConnected:Gle,BluetoothOff:Wle,BluetoothSearching:Kle,Bold:pT,Bolt:Zle,Bomb:Xle,Bone:Qle,Book:bce,BookA:Jle,BookAudio:ece,BookCheck:tce,BookCopy:sce,BookDashed:uL,BookDown:nce,BookHeadphones:rce,BookHeart:ace,BookImage:ice,BookKey:oce,BookLock:lce,BookMarked:cce,BookMinus:dce,BookOpen:wf,BookOpenCheck:uce,BookOpenText:hce,BookPlus:mce,BookText:pce,BookType:fce,BookUp:gce,BookUp2:xce,BookUser:yce,BookX:vce,Bookmark:wg,BookmarkCheck:_ce,BookmarkMinus:wce,BookmarkPlus:fT,BookmarkX:jce,BoomBox:Nce,Bot:t5,BotMessageSquare:kce,BotOff:Sce,Box:gK,Boxes:Cce,Braces:hL,Brackets:Ace,Brain:yK,BrainCircuit:Ece,BrainCog:Tce,BrickWall:Mce,Briefcase:ix,BriefcaseBusiness:Lce,BriefcaseConveyorBelt:Pce,BriefcaseMedical:Ice,BringToFront:Dce,Brush:Rce,Bug:zce,BugOff:Oce,BugPlay:Fce,Building:lR,Building2:Ai,Bus:$ce,BusFront:Bce,Cable:qce,CableCar:Uce,Cake:np,CakeSlice:Vce,Calculator:s5,Calendar:ia,Calendar1:Hce,CalendarArrowDown:Gce,CalendarArrowUp:Wce,CalendarCheck:gy,CalendarCheck2:Kce,CalendarClock:Xu,CalendarCog:Yce,CalendarDays:Nl,CalendarFold:Zce,CalendarHeart:LN,CalendarMinus:Qce,CalendarMinus2:Xce,CalendarOff:xz,CalendarPlus:gg,CalendarPlus2:Jce,CalendarRange:ede,CalendarSearch:tde,CalendarSync:sde,CalendarX:vK,CalendarX2:nde,Camera:y0,CameraOff:rde,Candy:ode,CandyCane:ade,CandyOff:ide,Cannabis:lde,Captions:mL,CaptionsOff:cde,Car:hde,CarFront:dde,CarTaxiFront:ude,Caravan:mde,Carrot:pde,CaseLower:fde,CaseSensitive:xde,CaseUpper:gde,CassetteTape:yde,Cast:vde,Castle:bde,Cat:_de,Cctv:wde,ChartArea:pL,ChartBar:xL,ChartBarBig:fL,ChartBarDecreasing:jde,ChartBarIncreasing:Nde,ChartBarStacked:kde,ChartCandlestick:gL,ChartColumn:ml,ChartColumnBig:yL,ChartColumnDecreasing:Sde,ChartColumnIncreasing:vL,ChartColumnStacked:Cde,ChartGantt:Ade,ChartLine:bL,ChartNetwork:Ede,ChartNoAxesColumn:wL,ChartNoAxesColumnDecreasing:Tde,ChartNoAxesColumnIncreasing:_L,ChartNoAxesCombined:Mde,ChartNoAxesGantt:jL,ChartPie:NL,ChartScatter:kL,ChartSpline:Lde,Check:oa,CheckCheck:cR,ChefHat:Pde,Cherry:Ide,ChevronDown:_o,ChevronFirst:Dde,ChevronLast:Rde,ChevronLeft:Ic,ChevronRight:Ja,ChevronUp:jg,ChevronsDown:Fde,ChevronsDownUp:Ode,ChevronsLeft:$de,ChevronsLeftRight:Bde,ChevronsLeftRightEllipsis:zde,ChevronsRight:qde,ChevronsRightLeft:Ude,ChevronsUp:Vde,ChevronsUpDown:sw,Chrome:dR,Church:Hde,Cigarette:Wde,CigaretteOff:Gde,Circle:Bp,CircleAlert:xo,CircleArrowDown:SL,CircleArrowLeft:CL,CircleArrowOutDownLeft:AL,CircleArrowOutDownRight:EL,CircleArrowOutUpLeft:TL,CircleArrowOutUpRight:ML,CircleArrowRight:LL,CircleArrowUp:PL,CircleCheck:Fr,CircleCheckBig:Ro,CircleChevronDown:IL,CircleChevronLeft:DL,CircleChevronRight:RL,CircleChevronUp:OL,CircleDashed:Kde,CircleDivide:FL,CircleDollarSign:Yde,CircleDot:Xde,CircleDotDashed:Zde,CircleEllipsis:Qde,CircleEqual:Jde,CircleFadingArrowUp:eue,CircleFadingPlus:tue,CircleGauge:zL,CircleHelp:Z4,CircleMinus:BL,CircleOff:sue,CircleParking:UL,CircleParkingOff:$L,CirclePause:qL,CirclePercent:VL,CirclePlay:Sh,CirclePlus:HL,CirclePower:GL,CircleSlash:nue,CircleSlash2:WL,CircleStop:KL,CircleUser:ZL,CircleUserRound:YL,CircleX:$d,CircuitBoard:rue,Citrus:aue,Clapperboard:gz,Clipboard:hue,ClipboardCheck:n5,ClipboardCopy:iue,ClipboardList:v0,ClipboardMinus:oue,ClipboardPaste:lue,ClipboardPen:QL,ClipboardPenLine:XL,ClipboardPlus:cue,ClipboardType:due,ClipboardX:uue,Clock:Hr,Clock1:mue,Clock10:pue,Clock11:fue,Clock12:xue,Clock2:gue,Clock3:bK,Clock4:yue,Clock5:vue,Clock6:bue,Clock7:_ue,Clock8:wue,Clock9:jue,ClockAlert:Nue,ClockArrowDown:kue,ClockArrowUp:Sue,Cloud:$ue,CloudAlert:Cue,CloudCog:Aue,CloudDownload:JL,CloudDrizzle:Eue,CloudFog:Tue,CloudHail:Mue,CloudLightning:Lue,CloudMoon:Iue,CloudMoonRain:Pue,CloudOff:Due,CloudRain:Oue,CloudRainWind:Rue,CloudSnow:Fue,CloudSun:Bue,CloudSunRain:zue,CloudUpload:eP,Cloudy:Uue,Clover:L3,Club:que,Code:xT,CodeXml:X4,Codepen:Vue,Codesandbox:Hue,Coffee:Tb,Cog:Gue,Coins:_K,Columns2:tP,Columns3:DA,Columns4:Wue,Combine:Kue,Command:Yue,Compass:uR,Component:Zue,Computer:Xue,ConciergeBell:Que,Cone:Jue,Construction:ehe,Contact:hR,ContactRound:sP,Container:the,Contrast:she,Cookie:nhe,CookingPot:rhe,Copy:Ca,CopyCheck:ahe,CopyMinus:ihe,CopyPlus:ohe,CopySlash:lhe,CopyX:che,Copyleft:dhe,Copyright:uhe,CornerDownLeft:hhe,CornerDownRight:mhe,CornerLeftDown:phe,CornerLeftUp:fhe,CornerRightDown:xhe,CornerRightUp:ghe,CornerUpLeft:yhe,CornerUpRight:vhe,Cpu:bhe,CreativeCommons:_he,CreditCard:yy,Croissant:whe,Crop:jhe,Cross:Nhe,Crosshair:khe,Crown:Ng,Cuboid:She,CupSoda:Che,Currency:Ahe,Cylinder:Ehe,Dam:The,Database:wK,DatabaseBackup:Mhe,DatabaseZap:Lhe,Delete:Phe,Dessert:Ihe,Diameter:Dhe,Diamond:Fhe,DiamondMinus:Rhe,DiamondPercent:nP,DiamondPlus:Ohe,Dice1:zhe,Dice2:Bhe,Dice3:$he,Dice4:Uhe,Dice5:qhe,Dice6:Vhe,Dices:Hhe,Diff:Ghe,Disc:Zhe,Disc2:Whe,Disc3:Khe,DiscAlbum:Yhe,Divide:Xhe,Dna:Jhe,DnaOff:Qhe,Dock:eme,Dog:tme,DollarSign:qd,Donut:sme,DoorClosed:nme,DoorOpen:zj,Dot:rme,Download:di,DraftingCompass:ame,Drama:ime,Dribbble:ome,Drill:lme,Droplet:cme,Droplets:f1,Drum:dme,Drumstick:ume,Dumbbell:hme,Ear:pme,EarOff:mme,Earth:rP,EarthLock:fme,Eclipse:xme,Egg:yz,EggFried:gme,EggOff:yme,Ellipsis:p0,EllipsisVertical:cy,Equal:_me,EqualApproximately:vme,EqualNot:bme,Eraser:wme,EthernetPort:jme,Euro:Nme,Expand:kme,ExternalLink:Tr,Eye:ga,EyeClosed:Sme,EyeOff:b0,Facebook:jf,Factory:Cme,Fan:Ame,FastForward:Eme,Feather:Tme,Fence:Mme,FerrisWheel:Lme,Figma:Pme,File:vz,FileArchive:Ime,FileAudio:Rme,FileAudio2:Dme,FileAxis3d:aP,FileBadge:Fme,FileBadge2:Ome,FileBox:zme,FileChartColumn:oP,FileChartColumnIncreasing:iP,FileChartLine:lP,FileChartPie:cP,FileCheck:jK,FileCheck2:Bme,FileClock:$me,FileCode:qme,FileCode2:Ume,FileCog:dP,FileDiff:Vme,FileDigit:Hme,FileDown:Bj,FileHeart:Gme,FileImage:gT,FileInput:Wme,FileJson:Yme,FileJson2:Kme,FileKey:Xme,FileKey2:Zme,FileLock:Jme,FileLock2:Qme,FileMinus:tpe,FileMinus2:epe,FileMusic:spe,FileOutput:npe,FilePen:uP,FilePenLine:RA,FilePlus:ape,FilePlus2:rpe,FileQuestion:ipe,FileScan:ope,FileSearch:cpe,FileSearch2:lpe,FileSliders:dpe,FileSpreadsheet:PN,FileStack:NK,FileSymlink:upe,FileTerminal:hpe,FileText:Wr,FileType:ppe,FileType2:mpe,FileUp:fpe,FileUser:xpe,FileVideo:kK,FileVideo2:gpe,FileVolume:vpe,FileVolume2:ype,FileWarning:bpe,FileX:wpe,FileX2:_pe,Files:jpe,Film:lh,Filter:$j,FilterX:Npe,Fingerprint:kpe,FireExtinguisher:Spe,Fish:Epe,FishOff:Cpe,FishSymbol:Ape,Flag:U3,FlagOff:Tpe,FlagTriangleLeft:Mpe,FlagTriangleRight:Lpe,Flame:yd,FlameKindling:Ppe,Flashlight:Dpe,FlashlightOff:Ipe,FlaskConical:yT,FlaskConicalOff:Rpe,FlaskRound:Ope,FlipHorizontal:SK,FlipHorizontal2:Fpe,FlipVertical:Bpe,FlipVertical2:zpe,Flower:$pe,Flower2:CN,Focus:Upe,FoldHorizontal:qpe,FoldVertical:Vpe,Folder:gfe,FolderArchive:Hpe,FolderCheck:Gpe,FolderClock:Wpe,FolderClosed:Kpe,FolderCode:Ype,FolderCog:hP,FolderDot:Zpe,FolderDown:Xpe,FolderGit:Jpe,FolderGit2:Qpe,FolderHeart:efe,FolderInput:tfe,FolderKanban:sfe,FolderKey:nfe,FolderLock:rfe,FolderMinus:afe,FolderOpen:cv,FolderOpenDot:ife,FolderOutput:ofe,FolderPen:mP,FolderPlus:lfe,FolderRoot:cfe,FolderSearch:ufe,FolderSearch2:dfe,FolderSymlink:hfe,FolderSync:mfe,FolderTree:pfe,FolderUp:ffe,FolderX:xfe,Folders:yfe,Footprints:vfe,Forklift:bfe,Forward:_fe,Frame:wfe,Framer:jfe,Frown:Nfe,Fuel:kfe,Fullscreen:Sfe,GalleryHorizontal:Afe,GalleryHorizontalEnd:Cfe,GalleryThumbnails:Efe,GalleryVertical:Mfe,GalleryVerticalEnd:Tfe,Gamepad:Pfe,Gamepad2:Lfe,Gauge:Ife,Gavel:Dfe,Gem:Rfe,Ghost:mR,Gift:Co,GitBranch:Ffe,GitBranchPlus:Ofe,GitCommitHorizontal:pP,GitCommitVertical:zfe,GitCompare:$fe,GitCompareArrows:Bfe,GitFork:Ufe,GitGraph:qfe,GitMerge:Vfe,GitPullRequest:Zfe,GitPullRequestArrow:Hfe,GitPullRequestClosed:Gfe,GitPullRequestCreate:Kfe,GitPullRequestCreateArrow:Wfe,GitPullRequestDraft:Yfe,Github:Xfe,Gitlab:Qfe,GlassWater:Jfe,Glasses:exe,Globe:Gl,GlobeLock:txe,Goal:sxe,Grab:nxe,GraduationCap:Ph,Grape:rxe,Grid2x2:xP,Grid2x2Check:axe,Grid2x2Plus:fP,Grid2x2X:ixe,Grid3x3:R_,Grip:lxe,GripHorizontal:oxe,GripVertical:$p,Group:cxe,Guitar:dxe,Ham:uxe,Hammer:CK,Hand:bz,HandCoins:hxe,HandHeart:pR,HandHelping:ES,HandMetal:mxe,HandPlatter:pxe,Handshake:IN,HardDrive:AK,HardDriveDownload:fxe,HardDriveUpload:xxe,HardHat:gxe,Hash:vT,Haze:yxe,HdmiPort:vxe,Heading:jxe,Heading1:_z,Heading2:wz,Heading3:EK,Heading4:bxe,Heading5:_xe,Heading6:wxe,HeadphoneOff:Nxe,Headphones:kxe,Headset:Sxe,Heart:fo,HeartCrack:Cxe,HeartHandshake:fR,HeartOff:Axe,HeartPulse:Exe,Heater:Txe,Hexagon:Mxe,Highlighter:Lxe,History:Uj,Hop:Ixe,HopOff:Pxe,Hospital:Dxe,Hotel:Rxe,Hourglass:TK,House:sa,HousePlug:Oxe,HousePlus:Fxe,IceCreamBowl:gP,IceCreamCone:yP,IdCard:zxe,Image:Jl,ImageDown:Bxe,ImageMinus:$xe,ImageOff:Uxe,ImagePlay:qxe,ImagePlus:x1,ImageUp:Vxe,ImageUpscale:Hxe,Images:Gxe,Import:Wxe,Inbox:bT,IndentDecrease:vP,IndentIncrease:bP,IndianRupee:Kxe,Infinity:Yxe,Info:r5,InspectionPanel:Zxe,Instagram:Qh,Italic:_T,IterationCcw:Xxe,IterationCw:Qxe,JapaneseYen:Jxe,Joystick:ege,Kanban:a5,Key:Mb,KeyRound:q3,KeySquare:tge,Keyboard:rge,KeyboardMusic:sge,KeyboardOff:nge,Lamp:dge,LampCeiling:age,LampDesk:ige,LampFloor:oge,LampWallDown:lge,LampWallUp:cge,LandPlot:uge,Landmark:jz,Languages:hge,Laptop:pge,LaptopMinimal:_P,LaptopMinimalCheck:mge,Lasso:xge,LassoSelect:fge,Laugh:gge,Layers:xR,Layers2:yge,Layers3:vge,LayoutDashboard:gR,LayoutGrid:_0,LayoutList:bge,LayoutPanelLeft:_ge,LayoutPanelTop:wge,LayoutTemplate:nw,Leaf:jge,LeafyGreen:Nge,Lectern:kge,LetterText:Sge,Library:g1,LibraryBig:Cge,LifeBuoy:Nz,Ligature:Age,Lightbulb:i5,LightbulbOff:Ege,Link:kc,Link2:Dc,Link2Off:Tge,Linkedin:kg,List:Sg,ListCheck:Mge,ListChecks:Jh,ListCollapse:Lge,ListEnd:Pge,ListFilter:MK,ListMinus:Ige,ListMusic:Dge,ListOrdered:qj,ListPlus:Rge,ListRestart:Oge,ListStart:Fge,ListTodo:zge,ListTree:Bge,ListVideo:$ge,ListX:Uge,Loader:Vge,LoaderCircle:Ht,LoaderPinwheel:qge,Locate:kz,LocateFixed:Hge,LocateOff:Gge,Lock:Ad,LockKeyhole:Wge,LockKeyholeOpen:wP,LockOpen:jP,LogIn:yR,LogOut:vR,Logs:Kge,Lollipop:Yge,Luggage:Zge,Magnet:Xge,Mail:nn,MailCheck:Sz,MailMinus:Qge,MailOpen:Cz,MailPlus:LK,MailQuestion:Jge,MailSearch:e0e,MailWarning:t0e,MailX:wT,Mailbox:s0e,Mails:n0e,Map:bR,MapPin:ai,MapPinCheck:a0e,MapPinCheckInside:r0e,MapPinHouse:i0e,MapPinMinus:l0e,MapPinMinusInside:o0e,MapPinOff:c0e,MapPinPlus:u0e,MapPinPlusInside:d0e,MapPinX:m0e,MapPinXInside:h0e,MapPinned:p0e,Martini:f0e,Maximize:_R,Maximize2:PK,Medal:V3,Megaphone:Eh,MegaphoneOff:x0e,Meh:g0e,MemoryStick:y0e,Menu:jT,Merge:v0e,MessageCircle:Ed,MessageCircleCode:b0e,MessageCircleDashed:_0e,MessageCircleHeart:Az,MessageCircleMore:w0e,MessageCircleOff:j0e,MessageCirclePlus:N0e,MessageCircleQuestion:Ez,MessageCircleReply:k0e,MessageCircleWarning:S0e,MessageCircleX:C0e,MessageSquare:Ji,MessageSquareCode:A0e,MessageSquareDashed:E0e,MessageSquareDiff:T0e,MessageSquareDot:M0e,MessageSquareHeart:Tz,MessageSquareLock:L0e,MessageSquareMore:IK,MessageSquareOff:P0e,MessageSquarePlus:BS,MessageSquareQuote:H3,MessageSquareReply:I0e,MessageSquareShare:D0e,MessageSquareText:R0e,MessageSquareWarning:O0e,MessageSquareX:F0e,MessagesSquare:Mz,Mic:Vj,MicOff:z0e,MicVocal:NP,Microchip:B0e,Microscope:$0e,Microwave:U0e,Milestone:q0e,Milk:H0e,MilkOff:V0e,Minimize:W0e,Minimize2:G0e,Minus:DN,Monitor:Hj,MonitorCheck:K0e,MonitorCog:Y0e,MonitorDot:Z0e,MonitorDown:X0e,MonitorOff:Q0e,MonitorPause:J0e,MonitorPlay:Lz,MonitorSmartphone:eye,MonitorSpeaker:tye,MonitorStop:sye,MonitorUp:wR,MonitorX:nye,Moon:aye,MoonStar:rye,Mountain:oye,MountainSnow:iye,Mouse:uye,MouseOff:lye,MousePointer:pg,MousePointer2:cye,MousePointerBan:dye,MousePointerClick:uu,Move:DK,Move3d:kP,MoveDiagonal:mye,MoveDiagonal2:hye,MoveDown:xye,MoveDownLeft:pye,MoveDownRight:fye,MoveHorizontal:gye,MoveLeft:yye,MoveRight:vye,MoveUp:wye,MoveUpLeft:bye,MoveUpRight:_ye,MoveVertical:jye,Music:Pz,Music2:Nye,Music3:kye,Music4:Sye,Navigation:RK,Navigation2:Aye,Navigation2Off:Cye,NavigationOff:Eye,Network:Tye,Newspaper:Gj,Nfc:Mye,Notebook:Dye,NotebookPen:Lye,NotebookTabs:Pye,NotebookText:Iye,NotepadText:Oye,NotepadTextDashed:Rye,Nut:zye,NutOff:Fye,Octagon:$ye,OctagonAlert:_N,OctagonMinus:Bye,OctagonPause:SP,OctagonX:CP,Omega:Uye,Option:qye,Orbit:Vye,Origami:Hye,Package:Tu,Package2:Gye,PackageCheck:Wye,PackageMinus:Kye,PackageOpen:Yye,PackagePlus:OK,PackageSearch:Zye,PackageX:Xye,PaintBucket:Qye,PaintRoller:Jye,Paintbrush:eve,PaintbrushVertical:AP,Palette:Rc,PanelBottom:nve,PanelBottomClose:tve,PanelBottomDashed:EP,PanelBottomOpen:sve,PanelLeft:PP,PanelLeftClose:TP,PanelLeftDashed:MP,PanelLeftOpen:LP,PanelRight:ive,PanelRightClose:rve,PanelRightDashed:IP,PanelRightOpen:ave,PanelTop:cve,PanelTopClose:ove,PanelTopDashed:DP,PanelTopOpen:lve,PanelsLeftBottom:dve,PanelsRightBottom:uve,PanelsTopLeft:Q4,Paperclip:NT,Parentheses:hve,ParkingMeter:mve,PartyPopper:Nf,Pause:vy,PawPrint:pve,PcCase:fve,Pen:kj,PenLine:wN,PenOff:xve,PenTool:kT,Pencil:Ya,PencilLine:Iz,PencilOff:gve,PencilRuler:yve,Pentagon:vve,Percent:ST,PersonStanding:bve,PhilippinePeso:_ve,Phone:ya,PhoneCall:FK,PhoneForwarded:wve,PhoneIncoming:jve,PhoneMissed:Nve,PhoneOff:kve,PhoneOutgoing:Sve,Pi:Cve,Piano:Ave,Pickaxe:Eve,PictureInPicture:Mve,PictureInPicture2:Tve,PiggyBank:Lve,Pilcrow:Dve,PilcrowLeft:Pve,PilcrowRight:Ive,Pill:Ove,PillBottle:Rve,Pin:CT,PinOff:zK,Pipette:Fve,Pizza:zve,Plane:BK,PlaneLanding:Bve,PlaneTakeoff:$ve,Play:Td,Plug:Wj,Plug2:Uve,PlugZap:RP,Plus:sn,Pocket:Vve,PocketKnife:qve,Podcast:Hve,Pointer:Wve,PointerOff:Gve,Popcorn:Kve,Popsicle:Yve,PoundSterling:Zve,Power:$K,PowerOff:Xve,Presentation:by,Printer:AT,PrinterCheck:Qve,Projector:Jve,Proportions:e1e,Puzzle:t1e,Pyramid:s1e,QrCode:Rx,Quote:RN,Rabbit:n1e,Radar:Dz,Radiation:r1e,Radical:a1e,Radio:Cg,RadioReceiver:i1e,RadioTower:o1e,Radius:l1e,RailSymbol:c1e,Rainbow:d1e,Rat:u1e,Ratio:h1e,Receipt:_1e,ReceiptCent:m1e,ReceiptEuro:p1e,ReceiptIndianRupee:f1e,ReceiptJapaneseYen:x1e,ReceiptPoundSterling:g1e,ReceiptRussianRuble:y1e,ReceiptSwissFranc:v1e,ReceiptText:b1e,RectangleEllipsis:OP,RectangleHorizontal:w1e,RectangleVertical:j1e,Recycle:N1e,Redo:ET,Redo2:k1e,RedoDot:S1e,RefreshCcw:Rz,RefreshCcwDot:C1e,RefreshCw:Wi,RefreshCwOff:A1e,Refrigerator:E1e,Regex:T1e,RemoveFormatting:M1e,Repeat:Oz,Repeat1:L1e,Repeat2:UK,Replace:I1e,ReplaceAll:P1e,Reply:qK,ReplyAll:D1e,Rewind:R1e,Ribbon:O1e,Rocket:w0,RockingChair:F1e,RollerCoaster:z1e,Rotate3d:FP,RotateCcw:Ih,RotateCcwSquare:B1e,RotateCw:jR,RotateCwSquare:$1e,Route:Fz,RouteOff:U1e,Router:q1e,Rows2:zP,Rows3:BP,Rows4:V1e,Rss:H1e,Ruler:o5,RussianRuble:G1e,Sailboat:W1e,Salad:K1e,Sandwich:Y1e,Satellite:X1e,SatelliteDish:Z1e,Save:Jo,SaveAll:Q1e,SaveOff:J1e,Scale:VK,Scale3d:$P,Scaling:ebe,Scan:lbe,ScanBarcode:tbe,ScanEye:sbe,ScanFace:nbe,ScanLine:rbe,ScanQrCode:abe,ScanSearch:ibe,ScanText:obe,School:cbe,Scissors:ube,ScissorsLineDashed:dbe,ScreenShare:mbe,ScreenShareOff:hbe,Scroll:pbe,ScrollText:HK,Search:Vr,SearchCheck:fbe,SearchCode:xbe,SearchSlash:gbe,SearchX:GK,Section:ybe,Send:Br,SendHorizontal:UP,SendToBack:vbe,SeparatorHorizontal:bbe,SeparatorVertical:_be,Server:kbe,ServerCog:wbe,ServerCrash:jbe,ServerOff:Nbe,Settings:pc,Settings2:G3,Shapes:Sbe,Share:WK,Share2:vd,Sheet:Cbe,Shell:Abe,Shield:kf,ShieldAlert:zz,ShieldBan:Ebe,ShieldCheck:j0,ShieldEllipsis:Tbe,ShieldHalf:Mbe,ShieldMinus:Lbe,ShieldOff:NR,ShieldPlus:Pbe,ShieldQuestion:Ibe,ShieldX:qP,Ship:Rbe,ShipWheel:Dbe,Shirt:Obe,ShoppingBag:l5,ShoppingBasket:Fbe,ShoppingCart:ON,Shovel:zbe,ShowerHead:Bbe,Shrink:$be,Shrub:Ube,Shuffle:kR,Sigma:qbe,Signal:Kbe,SignalHigh:Vbe,SignalLow:Hbe,SignalMedium:Gbe,SignalZero:Wbe,Signature:Ybe,Signpost:Xbe,SignpostBig:Zbe,Siren:Qbe,SkipBack:Jbe,SkipForward:KK,Skull:e_e,Slack:t_e,Slash:s_e,Slice:n_e,SlidersHorizontal:TT,SlidersVertical:VP,Smartphone:dv,SmartphoneCharging:r_e,SmartphoneNfc:a_e,Smile:o_e,SmilePlus:i_e,Snail:l_e,Snowflake:Z_,Sofa:c_e,Soup:d_e,Space:u_e,Spade:h_e,Sparkle:W3,Sparkles:dn,Speaker:m_e,Speech:p_e,SpellCheck:x_e,SpellCheck2:f_e,Spline:g_e,Split:y_e,SprayCan:v_e,Sprout:MT,Square:Lb,SquareActivity:HP,SquareArrowDown:KP,SquareArrowDownLeft:GP,SquareArrowDownRight:WP,SquareArrowLeft:YP,SquareArrowOutDownLeft:ZP,SquareArrowOutDownRight:XP,SquareArrowOutUpLeft:QP,SquareArrowOutUpRight:JP,SquareArrowRight:eI,SquareArrowUp:nI,SquareArrowUpLeft:tI,SquareArrowUpRight:sI,SquareAsterisk:rI,SquareBottomDashedScissors:aI,SquareChartGantt:Kk,SquareCheck:iI,SquareCheckBig:TS,SquareChevronDown:oI,SquareChevronLeft:lI,SquareChevronRight:cI,SquareChevronUp:dI,SquareCode:uI,SquareDashed:pI,SquareDashedBottom:__e,SquareDashedBottomCode:b_e,SquareDashedKanban:hI,SquareDashedMousePointer:mI,SquareDivide:fI,SquareDot:xI,SquareEqual:gI,SquareFunction:yI,SquareKanban:vI,SquareLibrary:bI,SquareM:_I,SquareMenu:wI,SquareMinus:jI,SquareMousePointer:NI,SquareParking:SI,SquareParkingOff:kI,SquarePen:bm,SquarePercent:CI,SquarePi:AI,SquarePilcrow:EI,SquarePlay:TI,SquarePlus:MI,SquarePower:LI,SquareRadical:w_e,SquareScissors:PI,SquareSigma:II,SquareSlash:DI,SquareSplitHorizontal:RI,SquareSplitVertical:OI,SquareSquare:j_e,SquareStack:N_e,SquareTerminal:FI,SquareUser:BI,SquareUserRound:zI,SquareX:$I,Squircle:k_e,Squirrel:S_e,Stamp:C_e,Star:Qa,StarHalf:A_e,StarOff:E_e,StepBack:T_e,StepForward:M_e,Stethoscope:L_e,Sticker:P_e,StickyNote:SR,Store:Bz,StretchHorizontal:I_e,StretchVertical:D_e,Strikethrough:YK,Subscript:R_e,Sun:Kj,SunDim:O_e,SunMedium:F_e,SunMoon:z_e,SunSnow:B_e,Sunrise:$_e,Sunset:U_e,Superscript:q_e,SwatchBook:V_e,SwissFranc:H_e,SwitchCamera:G_e,Sword:W_e,Swords:K_e,Syringe:Y_e,Table:Uz,Table2:$z,TableCellsMerge:Z_e,TableCellsSplit:X_e,TableColumnsSplit:Q_e,TableOfContents:J_e,TableProperties:ewe,TableRowsSplit:twe,Tablet:qz,TabletSmartphone:swe,Tablets:nwe,Tag:Up,Tags:ZK,Tally1:rwe,Tally2:awe,Tally3:iwe,Tally4:owe,Tally5:lwe,Tangent:cwe,Target:Mu,Telescope:dwe,Tent:hwe,TentTree:uwe,Terminal:mwe,TestTube:pwe,TestTubeDiagonal:UI,TestTubes:fwe,Text:bwe,TextCursor:gwe,TextCursorInput:xwe,TextQuote:ywe,TextSearch:vwe,TextSelect:qI,Theater:_we,Thermometer:XK,ThermometerSnowflake:wwe,ThermometerSun:jwe,ThumbsDown:QK,ThumbsUp:Ox,Ticket:CR,TicketCheck:Nwe,TicketMinus:kwe,TicketPercent:Swe,TicketPlus:Cwe,TicketSlash:Awe,TicketX:Ewe,Tickets:Mwe,TicketsPlane:Twe,Timer:Iwe,TimerOff:Lwe,TimerReset:Pwe,ToggleLeft:Dwe,ToggleRight:Rwe,Toilet:Owe,Tornado:Fwe,Torus:zwe,Touchpad:$we,TouchpadOff:Bwe,TowerControl:Uwe,ToyBrick:qwe,Tractor:Vwe,TrafficCone:Hwe,TrainFront:Wwe,TrainFrontTunnel:Gwe,TrainTrack:Kwe,TramFront:VI,Trash:Ywe,Trash2:Pn,TreeDeciduous:Zwe,TreePalm:HI,TreePine:LT,Trees:Xwe,Trello:Qwe,TrendingDown:FN,TrendingUp:Il,TrendingUpDown:Jwe,Triangle:tje,TriangleAlert:mc,TriangleRight:eje,Trophy:pl,Truck:JK,Turtle:sje,Tv:rje,TvMinimal:GI,TvMinimalPlay:nje,Twitch:aje,Twitter:ije,Type:lje,TypeOutline:oje,Umbrella:dje,UmbrellaOff:cje,Underline:Vz,Undo:PT,Undo2:eY,UndoDot:uje,UnfoldHorizontal:hje,UnfoldVertical:mje,Ungroup:pje,University:WI,Unlink:AR,Unlink2:fje,Unplug:tY,Upload:si,Usb:xje,User:Lo,UserCheck:Yj,UserCog:sY,UserMinus:Hz,UserPen:gje,UserPlus:il,UserRound:JI,UserRoundCheck:KI,UserRoundCog:YI,UserRoundMinus:ZI,UserRoundPen:yje,UserRoundPlus:XI,UserRoundSearch:vje,UserRoundX:QI,UserSearch:bje,UserX:_je,Users:qn,UsersRound:t1,Utensils:t8,UtensilsCrossed:e8,UtilityPole:wje,Variable:Gz,Vault:jje,Vegan:Nje,VenetianMask:kje,Vibrate:Cje,VibrateOff:Sje,Video:Xr,VideoOff:Aje,Videotape:Eje,View:Tje,Voicemail:Mje,Volleyball:Lje,Volume:Dje,Volume1:Pje,Volume2:nY,VolumeOff:Ije,VolumeX:rY,Vote:Rje,Wallet:aY,WalletCards:Oje,WalletMinimal:s8,Wallpaper:Fje,Wand:zje,WandSparkles:wm,Warehouse:Bje,WashingMachine:$je,Watch:Uje,Waves:qje,Waypoints:Vje,Webcam:Hje,Webhook:Wje,WebhookOff:Gje,Weight:Kje,Wheat:Zje,WheatOff:Yje,WholeWord:Xje,Wifi:s2e,WifiHigh:Qje,WifiLow:Jje,WifiOff:e2e,WifiZero:t2e,Wind:r2e,WindArrowDown:n2e,Wine:iY,WineOff:a2e,Workflow:oY,Worm:i2e,WrapText:o2e,Wrench:c5,X:pr,Youtube:l2e,Zap:ox,ZapOff:c2e,ZoomIn:IT,ZoomOut:Wz},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 R3e=Object.freeze(Object.defineProperty({__proto__:null,AArrowDown:bie,AArrowDownIcon:bie,AArrowUp:_ie,AArrowUpIcon:_ie,ALargeSmall:wie,ALargeSmallIcon:wie,Accessibility:jie,AccessibilityIcon:jie,Activity:zp,ActivityIcon:zp,ActivitySquare:HP,ActivitySquareIcon:HP,AirVent:Nie,AirVentIcon:Nie,Airplay:kie,AirplayIcon:kie,AlarmCheck:QM,AlarmCheckIcon:QM,AlarmClock:Cie,AlarmClockCheck:QM,AlarmClockCheckIcon:QM,AlarmClockIcon:Cie,AlarmClockMinus:JM,AlarmClockMinusIcon:JM,AlarmClockOff:Sie,AlarmClockOffIcon:Sie,AlarmClockPlus:eL,AlarmClockPlusIcon:eL,AlarmMinus:JM,AlarmMinusIcon:JM,AlarmPlus:eL,AlarmPlusIcon:eL,AlarmSmoke:Aie,AlarmSmokeIcon:Aie,Album:Eie,AlbumIcon:Eie,AlertCircle:xo,AlertCircleIcon:xo,AlertOctagon:_N,AlertOctagonIcon:_N,AlertTriangle:mc,AlertTriangleIcon:mc,AlignCenter:aR,AlignCenterHorizontal:Tie,AlignCenterHorizontalIcon:Tie,AlignCenterIcon:aR,AlignCenterVertical:Mie,AlignCenterVerticalIcon:Mie,AlignEndHorizontal:Lie,AlignEndHorizontalIcon:Lie,AlignEndVertical:Pie,AlignEndVerticalIcon:Pie,AlignHorizontalDistributeCenter:Iie,AlignHorizontalDistributeCenterIcon:Iie,AlignHorizontalDistributeEnd:Die,AlignHorizontalDistributeEndIcon:Die,AlignHorizontalDistributeStart:Rie,AlignHorizontalDistributeStartIcon:Rie,AlignHorizontalJustifyCenter:Oie,AlignHorizontalJustifyCenterIcon:Oie,AlignHorizontalJustifyEnd:Fie,AlignHorizontalJustifyEndIcon:Fie,AlignHorizontalJustifyStart:zie,AlignHorizontalJustifyStartIcon:zie,AlignHorizontalSpaceAround:Bie,AlignHorizontalSpaceAroundIcon:Bie,AlignHorizontalSpaceBetween:$ie,AlignHorizontalSpaceBetweenIcon:$ie,AlignJustify:Uie,AlignJustifyIcon:Uie,AlignLeft:iR,AlignLeftIcon:iR,AlignRight:oR,AlignRightIcon:oR,AlignStartHorizontal:qie,AlignStartHorizontalIcon:qie,AlignStartVertical:Vie,AlignStartVerticalIcon:Vie,AlignVerticalDistributeCenter:Hie,AlignVerticalDistributeCenterIcon:Hie,AlignVerticalDistributeEnd:Gie,AlignVerticalDistributeEndIcon:Gie,AlignVerticalDistributeStart:Wie,AlignVerticalDistributeStartIcon:Wie,AlignVerticalJustifyCenter:Kie,AlignVerticalJustifyCenterIcon:Kie,AlignVerticalJustifyEnd:Yie,AlignVerticalJustifyEndIcon:Yie,AlignVerticalJustifyStart:Zie,AlignVerticalJustifyStartIcon:Zie,AlignVerticalSpaceAround:Xie,AlignVerticalSpaceAroundIcon:Xie,AlignVerticalSpaceBetween:Qie,AlignVerticalSpaceBetweenIcon:Qie,Ambulance:Jie,AmbulanceIcon:Jie,Ampersand:eoe,AmpersandIcon:eoe,Ampersands:toe,AmpersandsIcon:toe,Amphora:soe,AmphoraIcon:soe,Anchor:noe,AnchorIcon:noe,Angry:roe,AngryIcon:roe,Annoyed:aoe,AnnoyedIcon:aoe,Antenna:ioe,AntennaIcon:ioe,Anvil:ooe,AnvilIcon:ooe,Aperture:loe,ApertureIcon:loe,AppWindow:doe,AppWindowIcon:doe,AppWindowMac:coe,AppWindowMacIcon:coe,Apple:uoe,AppleIcon:uoe,Archive:Am,ArchiveIcon:Am,ArchiveRestore:hT,ArchiveRestoreIcon:hT,ArchiveX:hoe,ArchiveXIcon:hoe,AreaChart:pL,AreaChartIcon:pL,Armchair:moe,ArmchairIcon:moe,ArrowBigDown:foe,ArrowBigDownDash:poe,ArrowBigDownDashIcon:poe,ArrowBigDownIcon:foe,ArrowBigLeft:goe,ArrowBigLeftDash:xoe,ArrowBigLeftDashIcon:xoe,ArrowBigLeftIcon:goe,ArrowBigRight:voe,ArrowBigRightDash:yoe,ArrowBigRightDashIcon:yoe,ArrowBigRightIcon:voe,ArrowBigUp:_oe,ArrowBigUpDash:boe,ArrowBigUpDashIcon:boe,ArrowBigUpIcon:_oe,ArrowDown:ax,ArrowDown01:woe,ArrowDown01Icon:woe,ArrowDown10:joe,ArrowDown10Icon:joe,ArrowDownAZ:tL,ArrowDownAZIcon:tL,ArrowDownAz:tL,ArrowDownAzIcon:tL,ArrowDownCircle:SL,ArrowDownCircleIcon:SL,ArrowDownFromLine:Noe,ArrowDownFromLineIcon:Noe,ArrowDownIcon:ax,ArrowDownLeft:koe,ArrowDownLeftFromCircle:AL,ArrowDownLeftFromCircleIcon:AL,ArrowDownLeftFromSquare:ZP,ArrowDownLeftFromSquareIcon:ZP,ArrowDownLeftIcon:koe,ArrowDownLeftSquare:GP,ArrowDownLeftSquareIcon:GP,ArrowDownNarrowWide:Soe,ArrowDownNarrowWideIcon:Soe,ArrowDownRight:pK,ArrowDownRightFromCircle:EL,ArrowDownRightFromCircleIcon:EL,ArrowDownRightFromSquare:XP,ArrowDownRightFromSquareIcon:XP,ArrowDownRightIcon:pK,ArrowDownRightSquare:WP,ArrowDownRightSquareIcon:WP,ArrowDownSquare:KP,ArrowDownSquareIcon:KP,ArrowDownToDot:Coe,ArrowDownToDotIcon:Coe,ArrowDownToLine:Aoe,ArrowDownToLineIcon:Aoe,ArrowDownUp:Eoe,ArrowDownUpIcon:Eoe,ArrowDownWideNarrow:sL,ArrowDownWideNarrowIcon:sL,ArrowDownZA:nL,ArrowDownZAIcon:nL,ArrowDownZa:nL,ArrowDownZaIcon:nL,ArrowLeft:ka,ArrowLeftCircle:CL,ArrowLeftCircleIcon:CL,ArrowLeftFromLine:Toe,ArrowLeftFromLineIcon:Toe,ArrowLeftIcon:ka,ArrowLeftRight:fK,ArrowLeftRightIcon:fK,ArrowLeftSquare:YP,ArrowLeftSquareIcon:YP,ArrowLeftToLine:Moe,ArrowLeftToLineIcon:Moe,ArrowRight:ni,ArrowRightCircle:LL,ArrowRightCircleIcon:LL,ArrowRightFromLine:Loe,ArrowRightFromLineIcon:Loe,ArrowRightIcon:ni,ArrowRightLeft:QS,ArrowRightLeftIcon:QS,ArrowRightSquare:eI,ArrowRightSquareIcon:eI,ArrowRightToLine:Poe,ArrowRightToLineIcon:Poe,ArrowUp:sp,ArrowUp01:Ioe,ArrowUp01Icon:Ioe,ArrowUp10:Doe,ArrowUp10Icon:Doe,ArrowUpAZ:rL,ArrowUpAZIcon:rL,ArrowUpAz:rL,ArrowUpAzIcon:rL,ArrowUpCircle:PL,ArrowUpCircleIcon:PL,ArrowUpDown:Tx,ArrowUpDownIcon:Tx,ArrowUpFromDot:Roe,ArrowUpFromDotIcon:Roe,ArrowUpFromLine:Ooe,ArrowUpFromLineIcon:Ooe,ArrowUpIcon:sp,ArrowUpLeft:Foe,ArrowUpLeftFromCircle:TL,ArrowUpLeftFromCircleIcon:TL,ArrowUpLeftFromSquare:QP,ArrowUpLeftFromSquareIcon:QP,ArrowUpLeftIcon:Foe,ArrowUpLeftSquare:tI,ArrowUpLeftSquareIcon:tI,ArrowUpNarrowWide:aL,ArrowUpNarrowWideIcon:aL,ArrowUpRight:mT,ArrowUpRightFromCircle:ML,ArrowUpRightFromCircleIcon:ML,ArrowUpRightFromSquare:JP,ArrowUpRightFromSquareIcon:JP,ArrowUpRightIcon:mT,ArrowUpRightSquare:sI,ArrowUpRightSquareIcon:sI,ArrowUpSquare:nI,ArrowUpSquareIcon:nI,ArrowUpToLine:zoe,ArrowUpToLineIcon:zoe,ArrowUpWideNarrow:Boe,ArrowUpWideNarrowIcon:Boe,ArrowUpZA:iL,ArrowUpZAIcon:iL,ArrowUpZa:iL,ArrowUpZaIcon:iL,ArrowsUpFromLine:$oe,ArrowsUpFromLineIcon:$oe,Asterisk:Uoe,AsteriskIcon:Uoe,AsteriskSquare:rI,AsteriskSquareIcon:rI,AtSign:qoe,AtSignIcon:qoe,Atom:Voe,AtomIcon:Voe,AudioLines:Hoe,AudioLinesIcon:Hoe,AudioWaveform:Goe,AudioWaveformIcon:Goe,Award:pu,AwardIcon:pu,Axe:Woe,AxeIcon:Woe,Axis3D:oL,Axis3DIcon:oL,Axis3d:oL,Axis3dIcon:oL,Baby:Koe,BabyIcon:Koe,Backpack:Yoe,BackpackIcon:Yoe,Badge:ule,BadgeAlert:Zoe,BadgeAlertIcon:Zoe,BadgeCent:Xoe,BadgeCentIcon:Xoe,BadgeCheck:lL,BadgeCheckIcon:lL,BadgeDollarSign:Qoe,BadgeDollarSignIcon:Qoe,BadgeEuro:Joe,BadgeEuroIcon:Joe,BadgeHelp:ele,BadgeHelpIcon:ele,BadgeIcon:ule,BadgeIndianRupee:tle,BadgeIndianRupeeIcon:tle,BadgeInfo:sle,BadgeInfoIcon:sle,BadgeJapaneseYen:nle,BadgeJapaneseYenIcon:nle,BadgeMinus:rle,BadgeMinusIcon:rle,BadgePercent:ale,BadgePercentIcon:ale,BadgePlus:ile,BadgePlusIcon:ile,BadgePoundSterling:ole,BadgePoundSterlingIcon:ole,BadgeRussianRuble:lle,BadgeRussianRubleIcon:lle,BadgeSwissFranc:cle,BadgeSwissFrancIcon:cle,BadgeX:dle,BadgeXIcon:dle,BaggageClaim:hle,BaggageClaimIcon:hle,Ban:fz,BanIcon:fz,Banana:mle,BananaIcon:mle,Bandage:ple,BandageIcon:ple,Banknote:fle,BanknoteIcon:fle,BarChart:_L,BarChart2:wL,BarChart2Icon:wL,BarChart3:ml,BarChart3Icon:ml,BarChart4:vL,BarChart4Icon:vL,BarChartBig:yL,BarChartBigIcon:yL,BarChartHorizontal:xL,BarChartHorizontalBig:fL,BarChartHorizontalBigIcon:fL,BarChartHorizontalIcon:xL,BarChartIcon:_L,Barcode:xle,BarcodeIcon:xle,Baseline:gle,BaselineIcon:gle,Bath:_g,BathIcon:_g,Battery:jle,BatteryCharging:yle,BatteryChargingIcon:yle,BatteryFull:vle,BatteryFullIcon:vle,BatteryIcon:jle,BatteryLow:ble,BatteryLowIcon:ble,BatteryMedium:_le,BatteryMediumIcon:_le,BatteryWarning:wle,BatteryWarningIcon:wle,Beaker:xK,BeakerIcon:xK,Bean:kle,BeanIcon:kle,BeanOff:Nle,BeanOffIcon:Nle,Bed:tw,BedDouble:JS,BedDoubleIcon:JS,BedIcon:tw,BedSingle:Sle,BedSingleIcon:Sle,Beef:Cle,BeefIcon:Cle,Beer:Ele,BeerIcon:Ele,BeerOff:Ale,BeerOffIcon:Ale,Bell:Dx,BellDot:Tle,BellDotIcon:Tle,BellElectric:Mle,BellElectricIcon:Mle,BellIcon:Dx,BellMinus:Lle,BellMinusIcon:Lle,BellOff:e5,BellOffIcon:e5,BellPlus:Ple,BellPlusIcon:Ple,BellRing:$3,BellRingIcon:$3,BetweenHorizonalEnd:cL,BetweenHorizonalEndIcon:cL,BetweenHorizonalStart:dL,BetweenHorizonalStartIcon:dL,BetweenHorizontalEnd:cL,BetweenHorizontalEndIcon:cL,BetweenHorizontalStart:dL,BetweenHorizontalStartIcon:dL,BetweenVerticalEnd:Ile,BetweenVerticalEndIcon:Ile,BetweenVerticalStart:Dle,BetweenVerticalStartIcon:Dle,BicepsFlexed:Rle,BicepsFlexedIcon:Rle,Bike:Ole,BikeIcon:Ole,Binary:Fle,BinaryIcon:Fle,Binoculars:zle,BinocularsIcon:zle,Biohazard:Ble,BiohazardIcon:Ble,Bird:$le,BirdIcon:$le,Bitcoin:Ule,BitcoinIcon:Ule,Blend:qle,BlendIcon:qle,Blinds:Vle,BlindsIcon:Vle,Blocks:Hle,BlocksIcon:Hle,Bluetooth:Yle,BluetoothConnected:Gle,BluetoothConnectedIcon:Gle,BluetoothIcon:Yle,BluetoothOff:Wle,BluetoothOffIcon:Wle,BluetoothSearching:Kle,BluetoothSearchingIcon:Kle,Bold:pT,BoldIcon:pT,Bolt:Zle,BoltIcon:Zle,Bomb:Xle,BombIcon:Xle,Bone:Qle,BoneIcon:Qle,Book:bce,BookA:Jle,BookAIcon:Jle,BookAudio:ece,BookAudioIcon:ece,BookCheck:tce,BookCheckIcon:tce,BookCopy:sce,BookCopyIcon:sce,BookDashed:uL,BookDashedIcon:uL,BookDown:nce,BookDownIcon:nce,BookHeadphones:rce,BookHeadphonesIcon:rce,BookHeart:ace,BookHeartIcon:ace,BookIcon:bce,BookImage:ice,BookImageIcon:ice,BookKey:oce,BookKeyIcon:oce,BookLock:lce,BookLockIcon:lce,BookMarked:cce,BookMarkedIcon:cce,BookMinus:dce,BookMinusIcon:dce,BookOpen:wf,BookOpenCheck:uce,BookOpenCheckIcon:uce,BookOpenIcon:wf,BookOpenText:hce,BookOpenTextIcon:hce,BookPlus:mce,BookPlusIcon:mce,BookTemplate:uL,BookTemplateIcon:uL,BookText:pce,BookTextIcon:pce,BookType:fce,BookTypeIcon:fce,BookUp:gce,BookUp2:xce,BookUp2Icon:xce,BookUpIcon:gce,BookUser:yce,BookUserIcon:yce,BookX:vce,BookXIcon:vce,Bookmark:wg,BookmarkCheck:_ce,BookmarkCheckIcon:_ce,BookmarkIcon:wg,BookmarkMinus:wce,BookmarkMinusIcon:wce,BookmarkPlus:fT,BookmarkPlusIcon:fT,BookmarkX:jce,BookmarkXIcon:jce,BoomBox:Nce,BoomBoxIcon:Nce,Bot:t5,BotIcon:t5,BotMessageSquare:kce,BotMessageSquareIcon:kce,BotOff:Sce,BotOffIcon:Sce,Box:gK,BoxIcon:gK,BoxSelect:pI,BoxSelectIcon:pI,Boxes:Cce,BoxesIcon:Cce,Braces:hL,BracesIcon:hL,Brackets:Ace,BracketsIcon:Ace,Brain:yK,BrainCircuit:Ece,BrainCircuitIcon:Ece,BrainCog:Tce,BrainCogIcon:Tce,BrainIcon:yK,BrickWall:Mce,BrickWallIcon:Mce,Briefcase:ix,BriefcaseBusiness:Lce,BriefcaseBusinessIcon:Lce,BriefcaseConveyorBelt:Pce,BriefcaseConveyorBeltIcon:Pce,BriefcaseIcon:ix,BriefcaseMedical:Ice,BriefcaseMedicalIcon:Ice,BringToFront:Dce,BringToFrontIcon:Dce,Brush:Rce,BrushIcon:Rce,Bug:zce,BugIcon:zce,BugOff:Oce,BugOffIcon:Oce,BugPlay:Fce,BugPlayIcon:Fce,Building:lR,Building2:Ai,Building2Icon:Ai,BuildingIcon:lR,Bus:$ce,BusFront:Bce,BusFrontIcon:Bce,BusIcon:$ce,Cable:qce,CableCar:Uce,CableCarIcon:Uce,CableIcon:qce,Cake:np,CakeIcon:np,CakeSlice:Vce,CakeSliceIcon:Vce,Calculator:s5,CalculatorIcon:s5,Calendar:ia,Calendar1:Hce,Calendar1Icon:Hce,CalendarArrowDown:Gce,CalendarArrowDownIcon:Gce,CalendarArrowUp:Wce,CalendarArrowUpIcon:Wce,CalendarCheck:gy,CalendarCheck2:Kce,CalendarCheck2Icon:Kce,CalendarCheckIcon:gy,CalendarClock:Xu,CalendarClockIcon:Xu,CalendarCog:Yce,CalendarCogIcon:Yce,CalendarDays:Nl,CalendarDaysIcon:Nl,CalendarFold:Zce,CalendarFoldIcon:Zce,CalendarHeart:LN,CalendarHeartIcon:LN,CalendarIcon:ia,CalendarMinus:Qce,CalendarMinus2:Xce,CalendarMinus2Icon:Xce,CalendarMinusIcon:Qce,CalendarOff:xz,CalendarOffIcon:xz,CalendarPlus:gg,CalendarPlus2:Jce,CalendarPlus2Icon:Jce,CalendarPlusIcon:gg,CalendarRange:ede,CalendarRangeIcon:ede,CalendarSearch:tde,CalendarSearchIcon:tde,CalendarSync:sde,CalendarSyncIcon:sde,CalendarX:vK,CalendarX2:nde,CalendarX2Icon:nde,CalendarXIcon:vK,Camera:y0,CameraIcon:y0,CameraOff:rde,CameraOffIcon:rde,CandlestickChart:gL,CandlestickChartIcon:gL,Candy:ode,CandyCane:ade,CandyCaneIcon:ade,CandyIcon:ode,CandyOff:ide,CandyOffIcon:ide,Cannabis:lde,CannabisIcon:lde,Captions:mL,CaptionsIcon:mL,CaptionsOff:cde,CaptionsOffIcon:cde,Car:hde,CarFront:dde,CarFrontIcon:dde,CarIcon:hde,CarTaxiFront:ude,CarTaxiFrontIcon:ude,Caravan:mde,CaravanIcon:mde,Carrot:pde,CarrotIcon:pde,CaseLower:fde,CaseLowerIcon:fde,CaseSensitive:xde,CaseSensitiveIcon:xde,CaseUpper:gde,CaseUpperIcon:gde,CassetteTape:yde,CassetteTapeIcon:yde,Cast:vde,CastIcon:vde,Castle:bde,CastleIcon:bde,Cat:_de,CatIcon:_de,Cctv:wde,CctvIcon:wde,ChartArea:pL,ChartAreaIcon:pL,ChartBar:xL,ChartBarBig:fL,ChartBarBigIcon:fL,ChartBarDecreasing:jde,ChartBarDecreasingIcon:jde,ChartBarIcon:xL,ChartBarIncreasing:Nde,ChartBarIncreasingIcon:Nde,ChartBarStacked:kde,ChartBarStackedIcon:kde,ChartCandlestick:gL,ChartCandlestickIcon:gL,ChartColumn:ml,ChartColumnBig:yL,ChartColumnBigIcon:yL,ChartColumnDecreasing:Sde,ChartColumnDecreasingIcon:Sde,ChartColumnIcon:ml,ChartColumnIncreasing:vL,ChartColumnIncreasingIcon:vL,ChartColumnStacked:Cde,ChartColumnStackedIcon:Cde,ChartGantt:Ade,ChartGanttIcon:Ade,ChartLine:bL,ChartLineIcon:bL,ChartNetwork:Ede,ChartNetworkIcon:Ede,ChartNoAxesColumn:wL,ChartNoAxesColumnDecreasing:Tde,ChartNoAxesColumnDecreasingIcon:Tde,ChartNoAxesColumnIcon:wL,ChartNoAxesColumnIncreasing:_L,ChartNoAxesColumnIncreasingIcon:_L,ChartNoAxesCombined:Mde,ChartNoAxesCombinedIcon:Mde,ChartNoAxesGantt:jL,ChartNoAxesGanttIcon:jL,ChartPie:NL,ChartPieIcon:NL,ChartScatter:kL,ChartScatterIcon:kL,ChartSpline:Lde,ChartSplineIcon:Lde,Check:oa,CheckCheck:cR,CheckCheckIcon:cR,CheckCircle:Ro,CheckCircle2:Fr,CheckCircle2Icon:Fr,CheckCircleIcon:Ro,CheckIcon:oa,CheckSquare:TS,CheckSquare2:iI,CheckSquare2Icon:iI,CheckSquareIcon:TS,ChefHat:Pde,ChefHatIcon:Pde,Cherry:Ide,CherryIcon:Ide,ChevronDown:_o,ChevronDownCircle:IL,ChevronDownCircleIcon:IL,ChevronDownIcon:_o,ChevronDownSquare:oI,ChevronDownSquareIcon:oI,ChevronFirst:Dde,ChevronFirstIcon:Dde,ChevronLast:Rde,ChevronLastIcon:Rde,ChevronLeft:Ic,ChevronLeftCircle:DL,ChevronLeftCircleIcon:DL,ChevronLeftIcon:Ic,ChevronLeftSquare:lI,ChevronLeftSquareIcon:lI,ChevronRight:Ja,ChevronRightCircle:RL,ChevronRightCircleIcon:RL,ChevronRightIcon:Ja,ChevronRightSquare:cI,ChevronRightSquareIcon:cI,ChevronUp:jg,ChevronUpCircle:OL,ChevronUpCircleIcon:OL,ChevronUpIcon:jg,ChevronUpSquare:dI,ChevronUpSquareIcon:dI,ChevronsDown:Fde,ChevronsDownIcon:Fde,ChevronsDownUp:Ode,ChevronsDownUpIcon:Ode,ChevronsLeft:$de,ChevronsLeftIcon:$de,ChevronsLeftRight:Bde,ChevronsLeftRightEllipsis:zde,ChevronsLeftRightEllipsisIcon:zde,ChevronsLeftRightIcon:Bde,ChevronsRight:qde,ChevronsRightIcon:qde,ChevronsRightLeft:Ude,ChevronsRightLeftIcon:Ude,ChevronsUp:Vde,ChevronsUpDown:sw,ChevronsUpDownIcon:sw,ChevronsUpIcon:Vde,Chrome:dR,ChromeIcon:dR,Church:Hde,ChurchIcon:Hde,Cigarette:Wde,CigaretteIcon:Wde,CigaretteOff:Gde,CigaretteOffIcon:Gde,Circle:Bp,CircleAlert:xo,CircleAlertIcon:xo,CircleArrowDown:SL,CircleArrowDownIcon:SL,CircleArrowLeft:CL,CircleArrowLeftIcon:CL,CircleArrowOutDownLeft:AL,CircleArrowOutDownLeftIcon:AL,CircleArrowOutDownRight:EL,CircleArrowOutDownRightIcon:EL,CircleArrowOutUpLeft:TL,CircleArrowOutUpLeftIcon:TL,CircleArrowOutUpRight:ML,CircleArrowOutUpRightIcon:ML,CircleArrowRight:LL,CircleArrowRightIcon:LL,CircleArrowUp:PL,CircleArrowUpIcon:PL,CircleCheck:Fr,CircleCheckBig:Ro,CircleCheckBigIcon:Ro,CircleCheckIcon:Fr,CircleChevronDown:IL,CircleChevronDownIcon:IL,CircleChevronLeft:DL,CircleChevronLeftIcon:DL,CircleChevronRight:RL,CircleChevronRightIcon:RL,CircleChevronUp:OL,CircleChevronUpIcon:OL,CircleDashed:Kde,CircleDashedIcon:Kde,CircleDivide:FL,CircleDivideIcon:FL,CircleDollarSign:Yde,CircleDollarSignIcon:Yde,CircleDot:Xde,CircleDotDashed:Zde,CircleDotDashedIcon:Zde,CircleDotIcon:Xde,CircleEllipsis:Qde,CircleEllipsisIcon:Qde,CircleEqual:Jde,CircleEqualIcon:Jde,CircleFadingArrowUp:eue,CircleFadingArrowUpIcon:eue,CircleFadingPlus:tue,CircleFadingPlusIcon:tue,CircleGauge:zL,CircleGaugeIcon:zL,CircleHelp:Z4,CircleHelpIcon:Z4,CircleIcon:Bp,CircleMinus:BL,CircleMinusIcon:BL,CircleOff:sue,CircleOffIcon:sue,CircleParking:UL,CircleParkingIcon:UL,CircleParkingOff:$L,CircleParkingOffIcon:$L,CirclePause:qL,CirclePauseIcon:qL,CirclePercent:VL,CirclePercentIcon:VL,CirclePlay:Sh,CirclePlayIcon:Sh,CirclePlus:HL,CirclePlusIcon:HL,CirclePower:GL,CirclePowerIcon:GL,CircleSlash:nue,CircleSlash2:WL,CircleSlash2Icon:WL,CircleSlashIcon:nue,CircleSlashed:WL,CircleSlashedIcon:WL,CircleStop:KL,CircleStopIcon:KL,CircleUser:ZL,CircleUserIcon:ZL,CircleUserRound:YL,CircleUserRoundIcon:YL,CircleX:$d,CircleXIcon:$d,CircuitBoard:rue,CircuitBoardIcon:rue,Citrus:aue,CitrusIcon:aue,Clapperboard:gz,ClapperboardIcon:gz,Clipboard:hue,ClipboardCheck:n5,ClipboardCheckIcon:n5,ClipboardCopy:iue,ClipboardCopyIcon:iue,ClipboardEdit:QL,ClipboardEditIcon:QL,ClipboardIcon:hue,ClipboardList:v0,ClipboardListIcon:v0,ClipboardMinus:oue,ClipboardMinusIcon:oue,ClipboardPaste:lue,ClipboardPasteIcon:lue,ClipboardPen:QL,ClipboardPenIcon:QL,ClipboardPenLine:XL,ClipboardPenLineIcon:XL,ClipboardPlus:cue,ClipboardPlusIcon:cue,ClipboardSignature:XL,ClipboardSignatureIcon:XL,ClipboardType:due,ClipboardTypeIcon:due,ClipboardX:uue,ClipboardXIcon:uue,Clock:Hr,Clock1:mue,Clock10:pue,Clock10Icon:pue,Clock11:fue,Clock11Icon:fue,Clock12:xue,Clock12Icon:xue,Clock1Icon:mue,Clock2:gue,Clock2Icon:gue,Clock3:bK,Clock3Icon:bK,Clock4:yue,Clock4Icon:yue,Clock5:vue,Clock5Icon:vue,Clock6:bue,Clock6Icon:bue,Clock7:_ue,Clock7Icon:_ue,Clock8:wue,Clock8Icon:wue,Clock9:jue,Clock9Icon:jue,ClockAlert:Nue,ClockAlertIcon:Nue,ClockArrowDown:kue,ClockArrowDownIcon:kue,ClockArrowUp:Sue,ClockArrowUpIcon:Sue,ClockIcon:Hr,Cloud:$ue,CloudAlert:Cue,CloudAlertIcon:Cue,CloudCog:Aue,CloudCogIcon:Aue,CloudDownload:JL,CloudDownloadIcon:JL,CloudDrizzle:Eue,CloudDrizzleIcon:Eue,CloudFog:Tue,CloudFogIcon:Tue,CloudHail:Mue,CloudHailIcon:Mue,CloudIcon:$ue,CloudLightning:Lue,CloudLightningIcon:Lue,CloudMoon:Iue,CloudMoonIcon:Iue,CloudMoonRain:Pue,CloudMoonRainIcon:Pue,CloudOff:Due,CloudOffIcon:Due,CloudRain:Oue,CloudRainIcon:Oue,CloudRainWind:Rue,CloudRainWindIcon:Rue,CloudSnow:Fue,CloudSnowIcon:Fue,CloudSun:Bue,CloudSunIcon:Bue,CloudSunRain:zue,CloudSunRainIcon:zue,CloudUpload:eP,CloudUploadIcon:eP,Cloudy:Uue,CloudyIcon:Uue,Clover:L3,CloverIcon:L3,Club:que,ClubIcon:que,Code:xT,Code2:X4,Code2Icon:X4,CodeIcon:xT,CodeSquare:uI,CodeSquareIcon:uI,CodeXml:X4,CodeXmlIcon:X4,Codepen:Vue,CodepenIcon:Vue,Codesandbox:Hue,CodesandboxIcon:Hue,Coffee:Tb,CoffeeIcon:Tb,Cog:Gue,CogIcon:Gue,Coins:_K,CoinsIcon:_K,Columns:tP,Columns2:tP,Columns2Icon:tP,Columns3:DA,Columns3Icon:DA,Columns4:Wue,Columns4Icon:Wue,ColumnsIcon:tP,Combine:Kue,CombineIcon:Kue,Command:Yue,CommandIcon:Yue,Compass:uR,CompassIcon:uR,Component:Zue,ComponentIcon:Zue,Computer:Xue,ComputerIcon:Xue,ConciergeBell:Que,ConciergeBellIcon:Que,Cone:Jue,ConeIcon:Jue,Construction:ehe,ConstructionIcon:ehe,Contact:hR,Contact2:sP,Contact2Icon:sP,ContactIcon:hR,ContactRound:sP,ContactRoundIcon:sP,Container:the,ContainerIcon:the,Contrast:she,ContrastIcon:she,Cookie:nhe,CookieIcon:nhe,CookingPot:rhe,CookingPotIcon:rhe,Copy:Ca,CopyCheck:ahe,CopyCheckIcon:ahe,CopyIcon:Ca,CopyMinus:ihe,CopyMinusIcon:ihe,CopyPlus:ohe,CopyPlusIcon:ohe,CopySlash:lhe,CopySlashIcon:lhe,CopyX:che,CopyXIcon:che,Copyleft:dhe,CopyleftIcon:dhe,Copyright:uhe,CopyrightIcon:uhe,CornerDownLeft:hhe,CornerDownLeftIcon:hhe,CornerDownRight:mhe,CornerDownRightIcon:mhe,CornerLeftDown:phe,CornerLeftDownIcon:phe,CornerLeftUp:fhe,CornerLeftUpIcon:fhe,CornerRightDown:xhe,CornerRightDownIcon:xhe,CornerRightUp:ghe,CornerRightUpIcon:ghe,CornerUpLeft:yhe,CornerUpLeftIcon:yhe,CornerUpRight:vhe,CornerUpRightIcon:vhe,Cpu:bhe,CpuIcon:bhe,CreativeCommons:_he,CreativeCommonsIcon:_he,CreditCard:yy,CreditCardIcon:yy,Croissant:whe,CroissantIcon:whe,Crop:jhe,CropIcon:jhe,Cross:Nhe,CrossIcon:Nhe,Crosshair:khe,CrosshairIcon:khe,Crown:Ng,CrownIcon:Ng,Cuboid:She,CuboidIcon:She,CupSoda:Che,CupSodaIcon:Che,CurlyBraces:hL,CurlyBracesIcon:hL,Currency:Ahe,CurrencyIcon:Ahe,Cylinder:Ehe,CylinderIcon:Ehe,Dam:The,DamIcon:The,Database:wK,DatabaseBackup:Mhe,DatabaseBackupIcon:Mhe,DatabaseIcon:wK,DatabaseZap:Lhe,DatabaseZapIcon:Lhe,Delete:Phe,DeleteIcon:Phe,Dessert:Ihe,DessertIcon:Ihe,Diameter:Dhe,DiameterIcon:Dhe,Diamond:Fhe,DiamondIcon:Fhe,DiamondMinus:Rhe,DiamondMinusIcon:Rhe,DiamondPercent:nP,DiamondPercentIcon:nP,DiamondPlus:Ohe,DiamondPlusIcon:Ohe,Dice1:zhe,Dice1Icon:zhe,Dice2:Bhe,Dice2Icon:Bhe,Dice3:$he,Dice3Icon:$he,Dice4:Uhe,Dice4Icon:Uhe,Dice5:qhe,Dice5Icon:qhe,Dice6:Vhe,Dice6Icon:Vhe,Dices:Hhe,DicesIcon:Hhe,Diff:Ghe,DiffIcon:Ghe,Disc:Zhe,Disc2:Whe,Disc2Icon:Whe,Disc3:Khe,Disc3Icon:Khe,DiscAlbum:Yhe,DiscAlbumIcon:Yhe,DiscIcon:Zhe,Divide:Xhe,DivideCircle:FL,DivideCircleIcon:FL,DivideIcon:Xhe,DivideSquare:fI,DivideSquareIcon:fI,Dna:Jhe,DnaIcon:Jhe,DnaOff:Qhe,DnaOffIcon:Qhe,Dock:eme,DockIcon:eme,Dog:tme,DogIcon:tme,DollarSign:qd,DollarSignIcon:qd,Donut:sme,DonutIcon:sme,DoorClosed:nme,DoorClosedIcon:nme,DoorOpen:zj,DoorOpenIcon:zj,Dot:rme,DotIcon:rme,DotSquare:xI,DotSquareIcon:xI,Download:di,DownloadCloud:JL,DownloadCloudIcon:JL,DownloadIcon:di,DraftingCompass:ame,DraftingCompassIcon:ame,Drama:ime,DramaIcon:ime,Dribbble:ome,DribbbleIcon:ome,Drill:lme,DrillIcon:lme,Droplet:cme,DropletIcon:cme,Droplets:f1,DropletsIcon:f1,Drum:dme,DrumIcon:dme,Drumstick:ume,DrumstickIcon:ume,Dumbbell:hme,DumbbellIcon:hme,Ear:pme,EarIcon:pme,EarOff:mme,EarOffIcon:mme,Earth:rP,EarthIcon:rP,EarthLock:fme,EarthLockIcon:fme,Eclipse:xme,EclipseIcon:xme,Edit:bm,Edit2:kj,Edit2Icon:kj,Edit3:wN,Edit3Icon:wN,EditIcon:bm,Egg:yz,EggFried:gme,EggFriedIcon:gme,EggIcon:yz,EggOff:yme,EggOffIcon:yme,Ellipsis:p0,EllipsisIcon:p0,EllipsisVertical:cy,EllipsisVerticalIcon:cy,Equal:_me,EqualApproximately:vme,EqualApproximatelyIcon:vme,EqualIcon:_me,EqualNot:bme,EqualNotIcon:bme,EqualSquare:gI,EqualSquareIcon:gI,Eraser:wme,EraserIcon:wme,EthernetPort:jme,EthernetPortIcon:jme,Euro:Nme,EuroIcon:Nme,Expand:kme,ExpandIcon:kme,ExternalLink:Tr,ExternalLinkIcon:Tr,Eye:ga,EyeClosed:Sme,EyeClosedIcon:Sme,EyeIcon:ga,EyeOff:b0,EyeOffIcon:b0,Facebook:jf,FacebookIcon:jf,Factory:Cme,FactoryIcon:Cme,Fan:Ame,FanIcon:Ame,FastForward:Eme,FastForwardIcon:Eme,Feather:Tme,FeatherIcon:Tme,Fence:Mme,FenceIcon:Mme,FerrisWheel:Lme,FerrisWheelIcon:Lme,Figma:Pme,FigmaIcon:Pme,File:vz,FileArchive:Ime,FileArchiveIcon:Ime,FileAudio:Rme,FileAudio2:Dme,FileAudio2Icon:Dme,FileAudioIcon:Rme,FileAxis3D:aP,FileAxis3DIcon:aP,FileAxis3d:aP,FileAxis3dIcon:aP,FileBadge:Fme,FileBadge2:Ome,FileBadge2Icon:Ome,FileBadgeIcon:Fme,FileBarChart:iP,FileBarChart2:oP,FileBarChart2Icon:oP,FileBarChartIcon:iP,FileBox:zme,FileBoxIcon:zme,FileChartColumn:oP,FileChartColumnIcon:oP,FileChartColumnIncreasing:iP,FileChartColumnIncreasingIcon:iP,FileChartLine:lP,FileChartLineIcon:lP,FileChartPie:cP,FileChartPieIcon:cP,FileCheck:jK,FileCheck2:Bme,FileCheck2Icon:Bme,FileCheckIcon:jK,FileClock:$me,FileClockIcon:$me,FileCode:qme,FileCode2:Ume,FileCode2Icon:Ume,FileCodeIcon:qme,FileCog:dP,FileCog2:dP,FileCog2Icon:dP,FileCogIcon:dP,FileDiff:Vme,FileDiffIcon:Vme,FileDigit:Hme,FileDigitIcon:Hme,FileDown:Bj,FileDownIcon:Bj,FileEdit:uP,FileEditIcon:uP,FileHeart:Gme,FileHeartIcon:Gme,FileIcon:vz,FileImage:gT,FileImageIcon:gT,FileInput:Wme,FileInputIcon:Wme,FileJson:Yme,FileJson2:Kme,FileJson2Icon:Kme,FileJsonIcon:Yme,FileKey:Xme,FileKey2:Zme,FileKey2Icon:Zme,FileKeyIcon:Xme,FileLineChart:lP,FileLineChartIcon:lP,FileLock:Jme,FileLock2:Qme,FileLock2Icon:Qme,FileLockIcon:Jme,FileMinus:tpe,FileMinus2:epe,FileMinus2Icon:epe,FileMinusIcon:tpe,FileMusic:spe,FileMusicIcon:spe,FileOutput:npe,FileOutputIcon:npe,FilePen:uP,FilePenIcon:uP,FilePenLine:RA,FilePenLineIcon:RA,FilePieChart:cP,FilePieChartIcon:cP,FilePlus:ape,FilePlus2:rpe,FilePlus2Icon:rpe,FilePlusIcon:ape,FileQuestion:ipe,FileQuestionIcon:ipe,FileScan:ope,FileScanIcon:ope,FileSearch:cpe,FileSearch2:lpe,FileSearch2Icon:lpe,FileSearchIcon:cpe,FileSignature:RA,FileSignatureIcon:RA,FileSliders:dpe,FileSlidersIcon:dpe,FileSpreadsheet:PN,FileSpreadsheetIcon:PN,FileStack:NK,FileStackIcon:NK,FileSymlink:upe,FileSymlinkIcon:upe,FileTerminal:hpe,FileTerminalIcon:hpe,FileText:Wr,FileTextIcon:Wr,FileType:ppe,FileType2:mpe,FileType2Icon:mpe,FileTypeIcon:ppe,FileUp:fpe,FileUpIcon:fpe,FileUser:xpe,FileUserIcon:xpe,FileVideo:kK,FileVideo2:gpe,FileVideo2Icon:gpe,FileVideoIcon:kK,FileVolume:vpe,FileVolume2:ype,FileVolume2Icon:ype,FileVolumeIcon:vpe,FileWarning:bpe,FileWarningIcon:bpe,FileX:wpe,FileX2:_pe,FileX2Icon:_pe,FileXIcon:wpe,Files:jpe,FilesIcon:jpe,Film:lh,FilmIcon:lh,Filter:$j,FilterIcon:$j,FilterX:Npe,FilterXIcon:Npe,Fingerprint:kpe,FingerprintIcon:kpe,FireExtinguisher:Spe,FireExtinguisherIcon:Spe,Fish:Epe,FishIcon:Epe,FishOff:Cpe,FishOffIcon:Cpe,FishSymbol:Ape,FishSymbolIcon:Ape,Flag:U3,FlagIcon:U3,FlagOff:Tpe,FlagOffIcon:Tpe,FlagTriangleLeft:Mpe,FlagTriangleLeftIcon:Mpe,FlagTriangleRight:Lpe,FlagTriangleRightIcon:Lpe,Flame:yd,FlameIcon:yd,FlameKindling:Ppe,FlameKindlingIcon:Ppe,Flashlight:Dpe,FlashlightIcon:Dpe,FlashlightOff:Ipe,FlashlightOffIcon:Ipe,FlaskConical:yT,FlaskConicalIcon:yT,FlaskConicalOff:Rpe,FlaskConicalOffIcon:Rpe,FlaskRound:Ope,FlaskRoundIcon:Ope,FlipHorizontal:SK,FlipHorizontal2:Fpe,FlipHorizontal2Icon:Fpe,FlipHorizontalIcon:SK,FlipVertical:Bpe,FlipVertical2:zpe,FlipVertical2Icon:zpe,FlipVerticalIcon:Bpe,Flower:$pe,Flower2:CN,Flower2Icon:CN,FlowerIcon:$pe,Focus:Upe,FocusIcon:Upe,FoldHorizontal:qpe,FoldHorizontalIcon:qpe,FoldVertical:Vpe,FoldVerticalIcon:Vpe,Folder:gfe,FolderArchive:Hpe,FolderArchiveIcon:Hpe,FolderCheck:Gpe,FolderCheckIcon:Gpe,FolderClock:Wpe,FolderClockIcon:Wpe,FolderClosed:Kpe,FolderClosedIcon:Kpe,FolderCode:Ype,FolderCodeIcon:Ype,FolderCog:hP,FolderCog2:hP,FolderCog2Icon:hP,FolderCogIcon:hP,FolderDot:Zpe,FolderDotIcon:Zpe,FolderDown:Xpe,FolderDownIcon:Xpe,FolderEdit:mP,FolderEditIcon:mP,FolderGit:Jpe,FolderGit2:Qpe,FolderGit2Icon:Qpe,FolderGitIcon:Jpe,FolderHeart:efe,FolderHeartIcon:efe,FolderIcon:gfe,FolderInput:tfe,FolderInputIcon:tfe,FolderKanban:sfe,FolderKanbanIcon:sfe,FolderKey:nfe,FolderKeyIcon:nfe,FolderLock:rfe,FolderLockIcon:rfe,FolderMinus:afe,FolderMinusIcon:afe,FolderOpen:cv,FolderOpenDot:ife,FolderOpenDotIcon:ife,FolderOpenIcon:cv,FolderOutput:ofe,FolderOutputIcon:ofe,FolderPen:mP,FolderPenIcon:mP,FolderPlus:lfe,FolderPlusIcon:lfe,FolderRoot:cfe,FolderRootIcon:cfe,FolderSearch:ufe,FolderSearch2:dfe,FolderSearch2Icon:dfe,FolderSearchIcon:ufe,FolderSymlink:hfe,FolderSymlinkIcon:hfe,FolderSync:mfe,FolderSyncIcon:mfe,FolderTree:pfe,FolderTreeIcon:pfe,FolderUp:ffe,FolderUpIcon:ffe,FolderX:xfe,FolderXIcon:xfe,Folders:yfe,FoldersIcon:yfe,Footprints:vfe,FootprintsIcon:vfe,ForkKnife:t8,ForkKnifeCrossed:e8,ForkKnifeCrossedIcon:e8,ForkKnifeIcon:t8,Forklift:bfe,ForkliftIcon:bfe,FormInput:OP,FormInputIcon:OP,Forward:_fe,ForwardIcon:_fe,Frame:wfe,FrameIcon:wfe,Framer:jfe,FramerIcon:jfe,Frown:Nfe,FrownIcon:Nfe,Fuel:kfe,FuelIcon:kfe,Fullscreen:Sfe,FullscreenIcon:Sfe,FunctionSquare:yI,FunctionSquareIcon:yI,GalleryHorizontal:Afe,GalleryHorizontalEnd:Cfe,GalleryHorizontalEndIcon:Cfe,GalleryHorizontalIcon:Afe,GalleryThumbnails:Efe,GalleryThumbnailsIcon:Efe,GalleryVertical:Mfe,GalleryVerticalEnd:Tfe,GalleryVerticalEndIcon:Tfe,GalleryVerticalIcon:Mfe,Gamepad:Pfe,Gamepad2:Lfe,Gamepad2Icon:Lfe,GamepadIcon:Pfe,GanttChart:jL,GanttChartIcon:jL,GanttChartSquare:Kk,GanttChartSquareIcon:Kk,Gauge:Ife,GaugeCircle:zL,GaugeCircleIcon:zL,GaugeIcon:Ife,Gavel:Dfe,GavelIcon:Dfe,Gem:Rfe,GemIcon:Rfe,Ghost:mR,GhostIcon:mR,Gift:Co,GiftIcon:Co,GitBranch:Ffe,GitBranchIcon:Ffe,GitBranchPlus:Ofe,GitBranchPlusIcon:Ofe,GitCommit:pP,GitCommitHorizontal:pP,GitCommitHorizontalIcon:pP,GitCommitIcon:pP,GitCommitVertical:zfe,GitCommitVerticalIcon:zfe,GitCompare:$fe,GitCompareArrows:Bfe,GitCompareArrowsIcon:Bfe,GitCompareIcon:$fe,GitFork:Ufe,GitForkIcon:Ufe,GitGraph:qfe,GitGraphIcon:qfe,GitMerge:Vfe,GitMergeIcon:Vfe,GitPullRequest:Zfe,GitPullRequestArrow:Hfe,GitPullRequestArrowIcon:Hfe,GitPullRequestClosed:Gfe,GitPullRequestClosedIcon:Gfe,GitPullRequestCreate:Kfe,GitPullRequestCreateArrow:Wfe,GitPullRequestCreateArrowIcon:Wfe,GitPullRequestCreateIcon:Kfe,GitPullRequestDraft:Yfe,GitPullRequestDraftIcon:Yfe,GitPullRequestIcon:Zfe,Github:Xfe,GithubIcon:Xfe,Gitlab:Qfe,GitlabIcon:Qfe,GlassWater:Jfe,GlassWaterIcon:Jfe,Glasses:exe,GlassesIcon:exe,Globe:Gl,Globe2:rP,Globe2Icon:rP,GlobeIcon:Gl,GlobeLock:txe,GlobeLockIcon:txe,Goal:sxe,GoalIcon:sxe,Grab:nxe,GrabIcon:nxe,GraduationCap:Ph,GraduationCapIcon:Ph,Grape:rxe,GrapeIcon:rxe,Grid:R_,Grid2X2:xP,Grid2X2Icon:xP,Grid2X2Plus:fP,Grid2X2PlusIcon:fP,Grid2x2:xP,Grid2x2Check:axe,Grid2x2CheckIcon:axe,Grid2x2Icon:xP,Grid2x2Plus:fP,Grid2x2PlusIcon:fP,Grid2x2X:ixe,Grid2x2XIcon:ixe,Grid3X3:R_,Grid3X3Icon:R_,Grid3x3:R_,Grid3x3Icon:R_,GridIcon:R_,Grip:lxe,GripHorizontal:oxe,GripHorizontalIcon:oxe,GripIcon:lxe,GripVertical:$p,GripVerticalIcon:$p,Group:cxe,GroupIcon:cxe,Guitar:dxe,GuitarIcon:dxe,Ham:uxe,HamIcon:uxe,Hammer:CK,HammerIcon:CK,Hand:bz,HandCoins:hxe,HandCoinsIcon:hxe,HandHeart:pR,HandHeartIcon:pR,HandHelping:ES,HandHelpingIcon:ES,HandIcon:bz,HandMetal:mxe,HandMetalIcon:mxe,HandPlatter:pxe,HandPlatterIcon:pxe,Handshake:IN,HandshakeIcon:IN,HardDrive:AK,HardDriveDownload:fxe,HardDriveDownloadIcon:fxe,HardDriveIcon:AK,HardDriveUpload:xxe,HardDriveUploadIcon:xxe,HardHat:gxe,HardHatIcon:gxe,Hash:vT,HashIcon:vT,Haze:yxe,HazeIcon:yxe,HdmiPort:vxe,HdmiPortIcon:vxe,Heading:jxe,Heading1:_z,Heading1Icon:_z,Heading2:wz,Heading2Icon:wz,Heading3:EK,Heading3Icon:EK,Heading4:bxe,Heading4Icon:bxe,Heading5:_xe,Heading5Icon:_xe,Heading6:wxe,Heading6Icon:wxe,HeadingIcon:jxe,HeadphoneOff:Nxe,HeadphoneOffIcon:Nxe,Headphones:kxe,HeadphonesIcon:kxe,Headset:Sxe,HeadsetIcon:Sxe,Heart:fo,HeartCrack:Cxe,HeartCrackIcon:Cxe,HeartHandshake:fR,HeartHandshakeIcon:fR,HeartIcon:fo,HeartOff:Axe,HeartOffIcon:Axe,HeartPulse:Exe,HeartPulseIcon:Exe,Heater:Txe,HeaterIcon:Txe,HelpCircle:Z4,HelpCircleIcon:Z4,HelpingHand:ES,HelpingHandIcon:ES,Hexagon:Mxe,HexagonIcon:Mxe,Highlighter:Lxe,HighlighterIcon:Lxe,History:Uj,HistoryIcon:Uj,Home:sa,HomeIcon:sa,Hop:Ixe,HopIcon:Ixe,HopOff:Pxe,HopOffIcon:Pxe,Hospital:Dxe,HospitalIcon:Dxe,Hotel:Rxe,HotelIcon:Rxe,Hourglass:TK,HourglassIcon:TK,House:sa,HouseIcon:sa,HousePlug:Oxe,HousePlugIcon:Oxe,HousePlus:Fxe,HousePlusIcon:Fxe,IceCream:yP,IceCream2:gP,IceCream2Icon:gP,IceCreamBowl:gP,IceCreamBowlIcon:gP,IceCreamCone:yP,IceCreamConeIcon:yP,IceCreamIcon:yP,Icon:mNt,IdCard:zxe,IdCardIcon:zxe,Image:Jl,ImageDown:Bxe,ImageDownIcon:Bxe,ImageIcon:Jl,ImageMinus:$xe,ImageMinusIcon:$xe,ImageOff:Uxe,ImageOffIcon:Uxe,ImagePlay:qxe,ImagePlayIcon:qxe,ImagePlus:x1,ImagePlusIcon:x1,ImageUp:Vxe,ImageUpIcon:Vxe,ImageUpscale:Hxe,ImageUpscaleIcon:Hxe,Images:Gxe,ImagesIcon:Gxe,Import:Wxe,ImportIcon:Wxe,Inbox:bT,InboxIcon:bT,Indent:bP,IndentDecrease:vP,IndentDecreaseIcon:vP,IndentIcon:bP,IndentIncrease:bP,IndentIncreaseIcon:bP,IndianRupee:Kxe,IndianRupeeIcon:Kxe,Infinity:Yxe,InfinityIcon:Yxe,Info:r5,InfoIcon:r5,Inspect:NI,InspectIcon:NI,InspectionPanel:Zxe,InspectionPanelIcon:Zxe,Instagram:Qh,InstagramIcon:Qh,Italic:_T,ItalicIcon:_T,IterationCcw:Xxe,IterationCcwIcon:Xxe,IterationCw:Qxe,IterationCwIcon:Qxe,JapaneseYen:Jxe,JapaneseYenIcon:Jxe,Joystick:ege,JoystickIcon:ege,Kanban:a5,KanbanIcon:a5,KanbanSquare:vI,KanbanSquareDashed:hI,KanbanSquareDashedIcon:hI,KanbanSquareIcon:vI,Key:Mb,KeyIcon:Mb,KeyRound:q3,KeyRoundIcon:q3,KeySquare:tge,KeySquareIcon:tge,Keyboard:rge,KeyboardIcon:rge,KeyboardMusic:sge,KeyboardMusicIcon:sge,KeyboardOff:nge,KeyboardOffIcon:nge,Lamp:dge,LampCeiling:age,LampCeilingIcon:age,LampDesk:ige,LampDeskIcon:ige,LampFloor:oge,LampFloorIcon:oge,LampIcon:dge,LampWallDown:lge,LampWallDownIcon:lge,LampWallUp:cge,LampWallUpIcon:cge,LandPlot:uge,LandPlotIcon:uge,Landmark:jz,LandmarkIcon:jz,Languages:hge,LanguagesIcon:hge,Laptop:pge,Laptop2:_P,Laptop2Icon:_P,LaptopIcon:pge,LaptopMinimal:_P,LaptopMinimalCheck:mge,LaptopMinimalCheckIcon:mge,LaptopMinimalIcon:_P,Lasso:xge,LassoIcon:xge,LassoSelect:fge,LassoSelectIcon:fge,Laugh:gge,LaughIcon:gge,Layers:xR,Layers2:yge,Layers2Icon:yge,Layers3:vge,Layers3Icon:vge,LayersIcon:xR,Layout:Q4,LayoutDashboard:gR,LayoutDashboardIcon:gR,LayoutGrid:_0,LayoutGridIcon:_0,LayoutIcon:Q4,LayoutList:bge,LayoutListIcon:bge,LayoutPanelLeft:_ge,LayoutPanelLeftIcon:_ge,LayoutPanelTop:wge,LayoutPanelTopIcon:wge,LayoutTemplate:nw,LayoutTemplateIcon:nw,Leaf:jge,LeafIcon:jge,LeafyGreen:Nge,LeafyGreenIcon:Nge,Lectern:kge,LecternIcon:kge,LetterText:Sge,LetterTextIcon:Sge,Library:g1,LibraryBig:Cge,LibraryBigIcon:Cge,LibraryIcon:g1,LibrarySquare:bI,LibrarySquareIcon:bI,LifeBuoy:Nz,LifeBuoyIcon:Nz,Ligature:Age,LigatureIcon:Age,Lightbulb:i5,LightbulbIcon:i5,LightbulbOff:Ege,LightbulbOffIcon:Ege,LineChart:bL,LineChartIcon:bL,Link:kc,Link2:Dc,Link2Icon:Dc,Link2Off:Tge,Link2OffIcon:Tge,LinkIcon:kc,Linkedin:kg,LinkedinIcon:kg,List:Sg,ListCheck:Mge,ListCheckIcon:Mge,ListChecks:Jh,ListChecksIcon:Jh,ListCollapse:Lge,ListCollapseIcon:Lge,ListEnd:Pge,ListEndIcon:Pge,ListFilter:MK,ListFilterIcon:MK,ListIcon:Sg,ListMinus:Ige,ListMinusIcon:Ige,ListMusic:Dge,ListMusicIcon:Dge,ListOrdered:qj,ListOrderedIcon:qj,ListPlus:Rge,ListPlusIcon:Rge,ListRestart:Oge,ListRestartIcon:Oge,ListStart:Fge,ListStartIcon:Fge,ListTodo:zge,ListTodoIcon:zge,ListTree:Bge,ListTreeIcon:Bge,ListVideo:$ge,ListVideoIcon:$ge,ListX:Uge,ListXIcon:Uge,Loader:Vge,Loader2:Ht,Loader2Icon:Ht,LoaderCircle:Ht,LoaderCircleIcon:Ht,LoaderIcon:Vge,LoaderPinwheel:qge,LoaderPinwheelIcon:qge,Locate:kz,LocateFixed:Hge,LocateFixedIcon:Hge,LocateIcon:kz,LocateOff:Gge,LocateOffIcon:Gge,Lock:Ad,LockIcon:Ad,LockKeyhole:Wge,LockKeyholeIcon:Wge,LockKeyholeOpen:wP,LockKeyholeOpenIcon:wP,LockOpen:jP,LockOpenIcon:jP,LogIn:yR,LogInIcon:yR,LogOut:vR,LogOutIcon:vR,Logs:Kge,LogsIcon:Kge,Lollipop:Yge,LollipopIcon:Yge,LucideAArrowDown:bie,LucideAArrowUp:_ie,LucideALargeSmall:wie,LucideAccessibility:jie,LucideActivity:zp,LucideActivitySquare:HP,LucideAirVent:Nie,LucideAirplay:kie,LucideAlarmCheck:QM,LucideAlarmClock:Cie,LucideAlarmClockCheck:QM,LucideAlarmClockMinus:JM,LucideAlarmClockOff:Sie,LucideAlarmClockPlus:eL,LucideAlarmMinus:JM,LucideAlarmPlus:eL,LucideAlarmSmoke:Aie,LucideAlbum:Eie,LucideAlertCircle:xo,LucideAlertOctagon:_N,LucideAlertTriangle:mc,LucideAlignCenter:aR,LucideAlignCenterHorizontal:Tie,LucideAlignCenterVertical:Mie,LucideAlignEndHorizontal:Lie,LucideAlignEndVertical:Pie,LucideAlignHorizontalDistributeCenter:Iie,LucideAlignHorizontalDistributeEnd:Die,LucideAlignHorizontalDistributeStart:Rie,LucideAlignHorizontalJustifyCenter:Oie,LucideAlignHorizontalJustifyEnd:Fie,LucideAlignHorizontalJustifyStart:zie,LucideAlignHorizontalSpaceAround:Bie,LucideAlignHorizontalSpaceBetween:$ie,LucideAlignJustify:Uie,LucideAlignLeft:iR,LucideAlignRight:oR,LucideAlignStartHorizontal:qie,LucideAlignStartVertical:Vie,LucideAlignVerticalDistributeCenter:Hie,LucideAlignVerticalDistributeEnd:Gie,LucideAlignVerticalDistributeStart:Wie,LucideAlignVerticalJustifyCenter:Kie,LucideAlignVerticalJustifyEnd:Yie,LucideAlignVerticalJustifyStart:Zie,LucideAlignVerticalSpaceAround:Xie,LucideAlignVerticalSpaceBetween:Qie,LucideAmbulance:Jie,LucideAmpersand:eoe,LucideAmpersands:toe,LucideAmphora:soe,LucideAnchor:noe,LucideAngry:roe,LucideAnnoyed:aoe,LucideAntenna:ioe,LucideAnvil:ooe,LucideAperture:loe,LucideAppWindow:doe,LucideAppWindowMac:coe,LucideApple:uoe,LucideArchive:Am,LucideArchiveRestore:hT,LucideArchiveX:hoe,LucideAreaChart:pL,LucideArmchair:moe,LucideArrowBigDown:foe,LucideArrowBigDownDash:poe,LucideArrowBigLeft:goe,LucideArrowBigLeftDash:xoe,LucideArrowBigRight:voe,LucideArrowBigRightDash:yoe,LucideArrowBigUp:_oe,LucideArrowBigUpDash:boe,LucideArrowDown:ax,LucideArrowDown01:woe,LucideArrowDown10:joe,LucideArrowDownAZ:tL,LucideArrowDownAz:tL,LucideArrowDownCircle:SL,LucideArrowDownFromLine:Noe,LucideArrowDownLeft:koe,LucideArrowDownLeftFromCircle:AL,LucideArrowDownLeftFromSquare:ZP,LucideArrowDownLeftSquare:GP,LucideArrowDownNarrowWide:Soe,LucideArrowDownRight:pK,LucideArrowDownRightFromCircle:EL,LucideArrowDownRightFromSquare:XP,LucideArrowDownRightSquare:WP,LucideArrowDownSquare:KP,LucideArrowDownToDot:Coe,LucideArrowDownToLine:Aoe,LucideArrowDownUp:Eoe,LucideArrowDownWideNarrow:sL,LucideArrowDownZA:nL,LucideArrowDownZa:nL,LucideArrowLeft:ka,LucideArrowLeftCircle:CL,LucideArrowLeftFromLine:Toe,LucideArrowLeftRight:fK,LucideArrowLeftSquare:YP,LucideArrowLeftToLine:Moe,LucideArrowRight:ni,LucideArrowRightCircle:LL,LucideArrowRightFromLine:Loe,LucideArrowRightLeft:QS,LucideArrowRightSquare:eI,LucideArrowRightToLine:Poe,LucideArrowUp:sp,LucideArrowUp01:Ioe,LucideArrowUp10:Doe,LucideArrowUpAZ:rL,LucideArrowUpAz:rL,LucideArrowUpCircle:PL,LucideArrowUpDown:Tx,LucideArrowUpFromDot:Roe,LucideArrowUpFromLine:Ooe,LucideArrowUpLeft:Foe,LucideArrowUpLeftFromCircle:TL,LucideArrowUpLeftFromSquare:QP,LucideArrowUpLeftSquare:tI,LucideArrowUpNarrowWide:aL,LucideArrowUpRight:mT,LucideArrowUpRightFromCircle:ML,LucideArrowUpRightFromSquare:JP,LucideArrowUpRightSquare:sI,LucideArrowUpSquare:nI,LucideArrowUpToLine:zoe,LucideArrowUpWideNarrow:Boe,LucideArrowUpZA:iL,LucideArrowUpZa:iL,LucideArrowsUpFromLine:$oe,LucideAsterisk:Uoe,LucideAsteriskSquare:rI,LucideAtSign:qoe,LucideAtom:Voe,LucideAudioLines:Hoe,LucideAudioWaveform:Goe,LucideAward:pu,LucideAxe:Woe,LucideAxis3D:oL,LucideAxis3d:oL,LucideBaby:Koe,LucideBackpack:Yoe,LucideBadge:ule,LucideBadgeAlert:Zoe,LucideBadgeCent:Xoe,LucideBadgeCheck:lL,LucideBadgeDollarSign:Qoe,LucideBadgeEuro:Joe,LucideBadgeHelp:ele,LucideBadgeIndianRupee:tle,LucideBadgeInfo:sle,LucideBadgeJapaneseYen:nle,LucideBadgeMinus:rle,LucideBadgePercent:ale,LucideBadgePlus:ile,LucideBadgePoundSterling:ole,LucideBadgeRussianRuble:lle,LucideBadgeSwissFranc:cle,LucideBadgeX:dle,LucideBaggageClaim:hle,LucideBan:fz,LucideBanana:mle,LucideBandage:ple,LucideBanknote:fle,LucideBarChart:_L,LucideBarChart2:wL,LucideBarChart3:ml,LucideBarChart4:vL,LucideBarChartBig:yL,LucideBarChartHorizontal:xL,LucideBarChartHorizontalBig:fL,LucideBarcode:xle,LucideBaseline:gle,LucideBath:_g,LucideBattery:jle,LucideBatteryCharging:yle,LucideBatteryFull:vle,LucideBatteryLow:ble,LucideBatteryMedium:_le,LucideBatteryWarning:wle,LucideBeaker:xK,LucideBean:kle,LucideBeanOff:Nle,LucideBed:tw,LucideBedDouble:JS,LucideBedSingle:Sle,LucideBeef:Cle,LucideBeer:Ele,LucideBeerOff:Ale,LucideBell:Dx,LucideBellDot:Tle,LucideBellElectric:Mle,LucideBellMinus:Lle,LucideBellOff:e5,LucideBellPlus:Ple,LucideBellRing:$3,LucideBetweenHorizonalEnd:cL,LucideBetweenHorizonalStart:dL,LucideBetweenHorizontalEnd:cL,LucideBetweenHorizontalStart:dL,LucideBetweenVerticalEnd:Ile,LucideBetweenVerticalStart:Dle,LucideBicepsFlexed:Rle,LucideBike:Ole,LucideBinary:Fle,LucideBinoculars:zle,LucideBiohazard:Ble,LucideBird:$le,LucideBitcoin:Ule,LucideBlend:qle,LucideBlinds:Vle,LucideBlocks:Hle,LucideBluetooth:Yle,LucideBluetoothConnected:Gle,LucideBluetoothOff:Wle,LucideBluetoothSearching:Kle,LucideBold:pT,LucideBolt:Zle,LucideBomb:Xle,LucideBone:Qle,LucideBook:bce,LucideBookA:Jle,LucideBookAudio:ece,LucideBookCheck:tce,LucideBookCopy:sce,LucideBookDashed:uL,LucideBookDown:nce,LucideBookHeadphones:rce,LucideBookHeart:ace,LucideBookImage:ice,LucideBookKey:oce,LucideBookLock:lce,LucideBookMarked:cce,LucideBookMinus:dce,LucideBookOpen:wf,LucideBookOpenCheck:uce,LucideBookOpenText:hce,LucideBookPlus:mce,LucideBookTemplate:uL,LucideBookText:pce,LucideBookType:fce,LucideBookUp:gce,LucideBookUp2:xce,LucideBookUser:yce,LucideBookX:vce,LucideBookmark:wg,LucideBookmarkCheck:_ce,LucideBookmarkMinus:wce,LucideBookmarkPlus:fT,LucideBookmarkX:jce,LucideBoomBox:Nce,LucideBot:t5,LucideBotMessageSquare:kce,LucideBotOff:Sce,LucideBox:gK,LucideBoxSelect:pI,LucideBoxes:Cce,LucideBraces:hL,LucideBrackets:Ace,LucideBrain:yK,LucideBrainCircuit:Ece,LucideBrainCog:Tce,LucideBrickWall:Mce,LucideBriefcase:ix,LucideBriefcaseBusiness:Lce,LucideBriefcaseConveyorBelt:Pce,LucideBriefcaseMedical:Ice,LucideBringToFront:Dce,LucideBrush:Rce,LucideBug:zce,LucideBugOff:Oce,LucideBugPlay:Fce,LucideBuilding:lR,LucideBuilding2:Ai,LucideBus:$ce,LucideBusFront:Bce,LucideCable:qce,LucideCableCar:Uce,LucideCake:np,LucideCakeSlice:Vce,LucideCalculator:s5,LucideCalendar:ia,LucideCalendar1:Hce,LucideCalendarArrowDown:Gce,LucideCalendarArrowUp:Wce,LucideCalendarCheck:gy,LucideCalendarCheck2:Kce,LucideCalendarClock:Xu,LucideCalendarCog:Yce,LucideCalendarDays:Nl,LucideCalendarFold:Zce,LucideCalendarHeart:LN,LucideCalendarMinus:Qce,LucideCalendarMinus2:Xce,LucideCalendarOff:xz,LucideCalendarPlus:gg,LucideCalendarPlus2:Jce,LucideCalendarRange:ede,LucideCalendarSearch:tde,LucideCalendarSync:sde,LucideCalendarX:vK,LucideCalendarX2:nde,LucideCamera:y0,LucideCameraOff:rde,LucideCandlestickChart:gL,LucideCandy:ode,LucideCandyCane:ade,LucideCandyOff:ide,LucideCannabis:lde,LucideCaptions:mL,LucideCaptionsOff:cde,LucideCar:hde,LucideCarFront:dde,LucideCarTaxiFront:ude,LucideCaravan:mde,LucideCarrot:pde,LucideCaseLower:fde,LucideCaseSensitive:xde,LucideCaseUpper:gde,LucideCassetteTape:yde,LucideCast:vde,LucideCastle:bde,LucideCat:_de,LucideCctv:wde,LucideChartArea:pL,LucideChartBar:xL,LucideChartBarBig:fL,LucideChartBarDecreasing:jde,LucideChartBarIncreasing:Nde,LucideChartBarStacked:kde,LucideChartCandlestick:gL,LucideChartColumn:ml,LucideChartColumnBig:yL,LucideChartColumnDecreasing:Sde,LucideChartColumnIncreasing:vL,LucideChartColumnStacked:Cde,LucideChartGantt:Ade,LucideChartLine:bL,LucideChartNetwork:Ede,LucideChartNoAxesColumn:wL,LucideChartNoAxesColumnDecreasing:Tde,LucideChartNoAxesColumnIncreasing:_L,LucideChartNoAxesCombined:Mde,LucideChartNoAxesGantt:jL,LucideChartPie:NL,LucideChartScatter:kL,LucideChartSpline:Lde,LucideCheck:oa,LucideCheckCheck:cR,LucideCheckCircle:Ro,LucideCheckCircle2:Fr,LucideCheckSquare:TS,LucideCheckSquare2:iI,LucideChefHat:Pde,LucideCherry:Ide,LucideChevronDown:_o,LucideChevronDownCircle:IL,LucideChevronDownSquare:oI,LucideChevronFirst:Dde,LucideChevronLast:Rde,LucideChevronLeft:Ic,LucideChevronLeftCircle:DL,LucideChevronLeftSquare:lI,LucideChevronRight:Ja,LucideChevronRightCircle:RL,LucideChevronRightSquare:cI,LucideChevronUp:jg,LucideChevronUpCircle:OL,LucideChevronUpSquare:dI,LucideChevronsDown:Fde,LucideChevronsDownUp:Ode,LucideChevronsLeft:$de,LucideChevronsLeftRight:Bde,LucideChevronsLeftRightEllipsis:zde,LucideChevronsRight:qde,LucideChevronsRightLeft:Ude,LucideChevronsUp:Vde,LucideChevronsUpDown:sw,LucideChrome:dR,LucideChurch:Hde,LucideCigarette:Wde,LucideCigaretteOff:Gde,LucideCircle:Bp,LucideCircleAlert:xo,LucideCircleArrowDown:SL,LucideCircleArrowLeft:CL,LucideCircleArrowOutDownLeft:AL,LucideCircleArrowOutDownRight:EL,LucideCircleArrowOutUpLeft:TL,LucideCircleArrowOutUpRight:ML,LucideCircleArrowRight:LL,LucideCircleArrowUp:PL,LucideCircleCheck:Fr,LucideCircleCheckBig:Ro,LucideCircleChevronDown:IL,LucideCircleChevronLeft:DL,LucideCircleChevronRight:RL,LucideCircleChevronUp:OL,LucideCircleDashed:Kde,LucideCircleDivide:FL,LucideCircleDollarSign:Yde,LucideCircleDot:Xde,LucideCircleDotDashed:Zde,LucideCircleEllipsis:Qde,LucideCircleEqual:Jde,LucideCircleFadingArrowUp:eue,LucideCircleFadingPlus:tue,LucideCircleGauge:zL,LucideCircleHelp:Z4,LucideCircleMinus:BL,LucideCircleOff:sue,LucideCircleParking:UL,LucideCircleParkingOff:$L,LucideCirclePause:qL,LucideCirclePercent:VL,LucideCirclePlay:Sh,LucideCirclePlus:HL,LucideCirclePower:GL,LucideCircleSlash:nue,LucideCircleSlash2:WL,LucideCircleSlashed:WL,LucideCircleStop:KL,LucideCircleUser:ZL,LucideCircleUserRound:YL,LucideCircleX:$d,LucideCircuitBoard:rue,LucideCitrus:aue,LucideClapperboard:gz,LucideClipboard:hue,LucideClipboardCheck:n5,LucideClipboardCopy:iue,LucideClipboardEdit:QL,LucideClipboardList:v0,LucideClipboardMinus:oue,LucideClipboardPaste:lue,LucideClipboardPen:QL,LucideClipboardPenLine:XL,LucideClipboardPlus:cue,LucideClipboardSignature:XL,LucideClipboardType:due,LucideClipboardX:uue,LucideClock:Hr,LucideClock1:mue,LucideClock10:pue,LucideClock11:fue,LucideClock12:xue,LucideClock2:gue,LucideClock3:bK,LucideClock4:yue,LucideClock5:vue,LucideClock6:bue,LucideClock7:_ue,LucideClock8:wue,LucideClock9:jue,LucideClockAlert:Nue,LucideClockArrowDown:kue,LucideClockArrowUp:Sue,LucideCloud:$ue,LucideCloudAlert:Cue,LucideCloudCog:Aue,LucideCloudDownload:JL,LucideCloudDrizzle:Eue,LucideCloudFog:Tue,LucideCloudHail:Mue,LucideCloudLightning:Lue,LucideCloudMoon:Iue,LucideCloudMoonRain:Pue,LucideCloudOff:Due,LucideCloudRain:Oue,LucideCloudRainWind:Rue,LucideCloudSnow:Fue,LucideCloudSun:Bue,LucideCloudSunRain:zue,LucideCloudUpload:eP,LucideCloudy:Uue,LucideClover:L3,LucideClub:que,LucideCode:xT,LucideCode2:X4,LucideCodeSquare:uI,LucideCodeXml:X4,LucideCodepen:Vue,LucideCodesandbox:Hue,LucideCoffee:Tb,LucideCog:Gue,LucideCoins:_K,LucideColumns:tP,LucideColumns2:tP,LucideColumns3:DA,LucideColumns4:Wue,LucideCombine:Kue,LucideCommand:Yue,LucideCompass:uR,LucideComponent:Zue,LucideComputer:Xue,LucideConciergeBell:Que,LucideCone:Jue,LucideConstruction:ehe,LucideContact:hR,LucideContact2:sP,LucideContactRound:sP,LucideContainer:the,LucideContrast:she,LucideCookie:nhe,LucideCookingPot:rhe,LucideCopy:Ca,LucideCopyCheck:ahe,LucideCopyMinus:ihe,LucideCopyPlus:ohe,LucideCopySlash:lhe,LucideCopyX:che,LucideCopyleft:dhe,LucideCopyright:uhe,LucideCornerDownLeft:hhe,LucideCornerDownRight:mhe,LucideCornerLeftDown:phe,LucideCornerLeftUp:fhe,LucideCornerRightDown:xhe,LucideCornerRightUp:ghe,LucideCornerUpLeft:yhe,LucideCornerUpRight:vhe,LucideCpu:bhe,LucideCreativeCommons:_he,LucideCreditCard:yy,LucideCroissant:whe,LucideCrop:jhe,LucideCross:Nhe,LucideCrosshair:khe,LucideCrown:Ng,LucideCuboid:She,LucideCupSoda:Che,LucideCurlyBraces:hL,LucideCurrency:Ahe,LucideCylinder:Ehe,LucideDam:The,LucideDatabase:wK,LucideDatabaseBackup:Mhe,LucideDatabaseZap:Lhe,LucideDelete:Phe,LucideDessert:Ihe,LucideDiameter:Dhe,LucideDiamond:Fhe,LucideDiamondMinus:Rhe,LucideDiamondPercent:nP,LucideDiamondPlus:Ohe,LucideDice1:zhe,LucideDice2:Bhe,LucideDice3:$he,LucideDice4:Uhe,LucideDice5:qhe,LucideDice6:Vhe,LucideDices:Hhe,LucideDiff:Ghe,LucideDisc:Zhe,LucideDisc2:Whe,LucideDisc3:Khe,LucideDiscAlbum:Yhe,LucideDivide:Xhe,LucideDivideCircle:FL,LucideDivideSquare:fI,LucideDna:Jhe,LucideDnaOff:Qhe,LucideDock:eme,LucideDog:tme,LucideDollarSign:qd,LucideDonut:sme,LucideDoorClosed:nme,LucideDoorOpen:zj,LucideDot:rme,LucideDotSquare:xI,LucideDownload:di,LucideDownloadCloud:JL,LucideDraftingCompass:ame,LucideDrama:ime,LucideDribbble:ome,LucideDrill:lme,LucideDroplet:cme,LucideDroplets:f1,LucideDrum:dme,LucideDrumstick:ume,LucideDumbbell:hme,LucideEar:pme,LucideEarOff:mme,LucideEarth:rP,LucideEarthLock:fme,LucideEclipse:xme,LucideEdit:bm,LucideEdit2:kj,LucideEdit3:wN,LucideEgg:yz,LucideEggFried:gme,LucideEggOff:yme,LucideEllipsis:p0,LucideEllipsisVertical:cy,LucideEqual:_me,LucideEqualApproximately:vme,LucideEqualNot:bme,LucideEqualSquare:gI,LucideEraser:wme,LucideEthernetPort:jme,LucideEuro:Nme,LucideExpand:kme,LucideExternalLink:Tr,LucideEye:ga,LucideEyeClosed:Sme,LucideEyeOff:b0,LucideFacebook:jf,LucideFactory:Cme,LucideFan:Ame,LucideFastForward:Eme,LucideFeather:Tme,LucideFence:Mme,LucideFerrisWheel:Lme,LucideFigma:Pme,LucideFile:vz,LucideFileArchive:Ime,LucideFileAudio:Rme,LucideFileAudio2:Dme,LucideFileAxis3D:aP,LucideFileAxis3d:aP,LucideFileBadge:Fme,LucideFileBadge2:Ome,LucideFileBarChart:iP,LucideFileBarChart2:oP,LucideFileBox:zme,LucideFileChartColumn:oP,LucideFileChartColumnIncreasing:iP,LucideFileChartLine:lP,LucideFileChartPie:cP,LucideFileCheck:jK,LucideFileCheck2:Bme,LucideFileClock:$me,LucideFileCode:qme,LucideFileCode2:Ume,LucideFileCog:dP,LucideFileCog2:dP,LucideFileDiff:Vme,LucideFileDigit:Hme,LucideFileDown:Bj,LucideFileEdit:uP,LucideFileHeart:Gme,LucideFileImage:gT,LucideFileInput:Wme,LucideFileJson:Yme,LucideFileJson2:Kme,LucideFileKey:Xme,LucideFileKey2:Zme,LucideFileLineChart:lP,LucideFileLock:Jme,LucideFileLock2:Qme,LucideFileMinus:tpe,LucideFileMinus2:epe,LucideFileMusic:spe,LucideFileOutput:npe,LucideFilePen:uP,LucideFilePenLine:RA,LucideFilePieChart:cP,LucideFilePlus:ape,LucideFilePlus2:rpe,LucideFileQuestion:ipe,LucideFileScan:ope,LucideFileSearch:cpe,LucideFileSearch2:lpe,LucideFileSignature:RA,LucideFileSliders:dpe,LucideFileSpreadsheet:PN,LucideFileStack:NK,LucideFileSymlink:upe,LucideFileTerminal:hpe,LucideFileText:Wr,LucideFileType:ppe,LucideFileType2:mpe,LucideFileUp:fpe,LucideFileUser:xpe,LucideFileVideo:kK,LucideFileVideo2:gpe,LucideFileVolume:vpe,LucideFileVolume2:ype,LucideFileWarning:bpe,LucideFileX:wpe,LucideFileX2:_pe,LucideFiles:jpe,LucideFilm:lh,LucideFilter:$j,LucideFilterX:Npe,LucideFingerprint:kpe,LucideFireExtinguisher:Spe,LucideFish:Epe,LucideFishOff:Cpe,LucideFishSymbol:Ape,LucideFlag:U3,LucideFlagOff:Tpe,LucideFlagTriangleLeft:Mpe,LucideFlagTriangleRight:Lpe,LucideFlame:yd,LucideFlameKindling:Ppe,LucideFlashlight:Dpe,LucideFlashlightOff:Ipe,LucideFlaskConical:yT,LucideFlaskConicalOff:Rpe,LucideFlaskRound:Ope,LucideFlipHorizontal:SK,LucideFlipHorizontal2:Fpe,LucideFlipVertical:Bpe,LucideFlipVertical2:zpe,LucideFlower:$pe,LucideFlower2:CN,LucideFocus:Upe,LucideFoldHorizontal:qpe,LucideFoldVertical:Vpe,LucideFolder:gfe,LucideFolderArchive:Hpe,LucideFolderCheck:Gpe,LucideFolderClock:Wpe,LucideFolderClosed:Kpe,LucideFolderCode:Ype,LucideFolderCog:hP,LucideFolderCog2:hP,LucideFolderDot:Zpe,LucideFolderDown:Xpe,LucideFolderEdit:mP,LucideFolderGit:Jpe,LucideFolderGit2:Qpe,LucideFolderHeart:efe,LucideFolderInput:tfe,LucideFolderKanban:sfe,LucideFolderKey:nfe,LucideFolderLock:rfe,LucideFolderMinus:afe,LucideFolderOpen:cv,LucideFolderOpenDot:ife,LucideFolderOutput:ofe,LucideFolderPen:mP,LucideFolderPlus:lfe,LucideFolderRoot:cfe,LucideFolderSearch:ufe,LucideFolderSearch2:dfe,LucideFolderSymlink:hfe,LucideFolderSync:mfe,LucideFolderTree:pfe,LucideFolderUp:ffe,LucideFolderX:xfe,LucideFolders:yfe,LucideFootprints:vfe,LucideForkKnife:t8,LucideForkKnifeCrossed:e8,LucideForklift:bfe,LucideFormInput:OP,LucideForward:_fe,LucideFrame:wfe,LucideFramer:jfe,LucideFrown:Nfe,LucideFuel:kfe,LucideFullscreen:Sfe,LucideFunctionSquare:yI,LucideGalleryHorizontal:Afe,LucideGalleryHorizontalEnd:Cfe,LucideGalleryThumbnails:Efe,LucideGalleryVertical:Mfe,LucideGalleryVerticalEnd:Tfe,LucideGamepad:Pfe,LucideGamepad2:Lfe,LucideGanttChart:jL,LucideGanttChartSquare:Kk,LucideGauge:Ife,LucideGaugeCircle:zL,LucideGavel:Dfe,LucideGem:Rfe,LucideGhost:mR,LucideGift:Co,LucideGitBranch:Ffe,LucideGitBranchPlus:Ofe,LucideGitCommit:pP,LucideGitCommitHorizontal:pP,LucideGitCommitVertical:zfe,LucideGitCompare:$fe,LucideGitCompareArrows:Bfe,LucideGitFork:Ufe,LucideGitGraph:qfe,LucideGitMerge:Vfe,LucideGitPullRequest:Zfe,LucideGitPullRequestArrow:Hfe,LucideGitPullRequestClosed:Gfe,LucideGitPullRequestCreate:Kfe,LucideGitPullRequestCreateArrow:Wfe,LucideGitPullRequestDraft:Yfe,LucideGithub:Xfe,LucideGitlab:Qfe,LucideGlassWater:Jfe,LucideGlasses:exe,LucideGlobe:Gl,LucideGlobe2:rP,LucideGlobeLock:txe,LucideGoal:sxe,LucideGrab:nxe,LucideGraduationCap:Ph,LucideGrape:rxe,LucideGrid:R_,LucideGrid2X2:xP,LucideGrid2X2Plus:fP,LucideGrid2x2:xP,LucideGrid2x2Check:axe,LucideGrid2x2Plus:fP,LucideGrid2x2X:ixe,LucideGrid3X3:R_,LucideGrid3x3:R_,LucideGrip:lxe,LucideGripHorizontal:oxe,LucideGripVertical:$p,LucideGroup:cxe,LucideGuitar:dxe,LucideHam:uxe,LucideHammer:CK,LucideHand:bz,LucideHandCoins:hxe,LucideHandHeart:pR,LucideHandHelping:ES,LucideHandMetal:mxe,LucideHandPlatter:pxe,LucideHandshake:IN,LucideHardDrive:AK,LucideHardDriveDownload:fxe,LucideHardDriveUpload:xxe,LucideHardHat:gxe,LucideHash:vT,LucideHaze:yxe,LucideHdmiPort:vxe,LucideHeading:jxe,LucideHeading1:_z,LucideHeading2:wz,LucideHeading3:EK,LucideHeading4:bxe,LucideHeading5:_xe,LucideHeading6:wxe,LucideHeadphoneOff:Nxe,LucideHeadphones:kxe,LucideHeadset:Sxe,LucideHeart:fo,LucideHeartCrack:Cxe,LucideHeartHandshake:fR,LucideHeartOff:Axe,LucideHeartPulse:Exe,LucideHeater:Txe,LucideHelpCircle:Z4,LucideHelpingHand:ES,LucideHexagon:Mxe,LucideHighlighter:Lxe,LucideHistory:Uj,LucideHome:sa,LucideHop:Ixe,LucideHopOff:Pxe,LucideHospital:Dxe,LucideHotel:Rxe,LucideHourglass:TK,LucideHouse:sa,LucideHousePlug:Oxe,LucideHousePlus:Fxe,LucideIceCream:yP,LucideIceCream2:gP,LucideIceCreamBowl:gP,LucideIceCreamCone:yP,LucideIdCard:zxe,LucideImage:Jl,LucideImageDown:Bxe,LucideImageMinus:$xe,LucideImageOff:Uxe,LucideImagePlay:qxe,LucideImagePlus:x1,LucideImageUp:Vxe,LucideImageUpscale:Hxe,LucideImages:Gxe,LucideImport:Wxe,LucideInbox:bT,LucideIndent:bP,LucideIndentDecrease:vP,LucideIndentIncrease:bP,LucideIndianRupee:Kxe,LucideInfinity:Yxe,LucideInfo:r5,LucideInspect:NI,LucideInspectionPanel:Zxe,LucideInstagram:Qh,LucideItalic:_T,LucideIterationCcw:Xxe,LucideIterationCw:Qxe,LucideJapaneseYen:Jxe,LucideJoystick:ege,LucideKanban:a5,LucideKanbanSquare:vI,LucideKanbanSquareDashed:hI,LucideKey:Mb,LucideKeyRound:q3,LucideKeySquare:tge,LucideKeyboard:rge,LucideKeyboardMusic:sge,LucideKeyboardOff:nge,LucideLamp:dge,LucideLampCeiling:age,LucideLampDesk:ige,LucideLampFloor:oge,LucideLampWallDown:lge,LucideLampWallUp:cge,LucideLandPlot:uge,LucideLandmark:jz,LucideLanguages:hge,LucideLaptop:pge,LucideLaptop2:_P,LucideLaptopMinimal:_P,LucideLaptopMinimalCheck:mge,LucideLasso:xge,LucideLassoSelect:fge,LucideLaugh:gge,LucideLayers:xR,LucideLayers2:yge,LucideLayers3:vge,LucideLayout:Q4,LucideLayoutDashboard:gR,LucideLayoutGrid:_0,LucideLayoutList:bge,LucideLayoutPanelLeft:_ge,LucideLayoutPanelTop:wge,LucideLayoutTemplate:nw,LucideLeaf:jge,LucideLeafyGreen:Nge,LucideLectern:kge,LucideLetterText:Sge,LucideLibrary:g1,LucideLibraryBig:Cge,LucideLibrarySquare:bI,LucideLifeBuoy:Nz,LucideLigature:Age,LucideLightbulb:i5,LucideLightbulbOff:Ege,LucideLineChart:bL,LucideLink:kc,LucideLink2:Dc,LucideLink2Off:Tge,LucideLinkedin:kg,LucideList:Sg,LucideListCheck:Mge,LucideListChecks:Jh,LucideListCollapse:Lge,LucideListEnd:Pge,LucideListFilter:MK,LucideListMinus:Ige,LucideListMusic:Dge,LucideListOrdered:qj,LucideListPlus:Rge,LucideListRestart:Oge,LucideListStart:Fge,LucideListTodo:zge,LucideListTree:Bge,LucideListVideo:$ge,LucideListX:Uge,LucideLoader:Vge,LucideLoader2:Ht,LucideLoaderCircle:Ht,LucideLoaderPinwheel:qge,LucideLocate:kz,LucideLocateFixed:Hge,LucideLocateOff:Gge,LucideLock:Ad,LucideLockKeyhole:Wge,LucideLockKeyholeOpen:wP,LucideLockOpen:jP,LucideLogIn:yR,LucideLogOut:vR,LucideLogs:Kge,LucideLollipop:Yge,LucideLuggage:Zge,LucideMSquare:_I,LucideMagnet:Xge,LucideMail:nn,LucideMailCheck:Sz,LucideMailMinus:Qge,LucideMailOpen:Cz,LucideMailPlus:LK,LucideMailQuestion:Jge,LucideMailSearch:e0e,LucideMailWarning:t0e,LucideMailX:wT,LucideMailbox:s0e,LucideMails:n0e,LucideMap:bR,LucideMapPin:ai,LucideMapPinCheck:a0e,LucideMapPinCheckInside:r0e,LucideMapPinHouse:i0e,LucideMapPinMinus:l0e,LucideMapPinMinusInside:o0e,LucideMapPinOff:c0e,LucideMapPinPlus:u0e,LucideMapPinPlusInside:d0e,LucideMapPinX:m0e,LucideMapPinXInside:h0e,LucideMapPinned:p0e,LucideMartini:f0e,LucideMaximize:_R,LucideMaximize2:PK,LucideMedal:V3,LucideMegaphone:Eh,LucideMegaphoneOff:x0e,LucideMeh:g0e,LucideMemoryStick:y0e,LucideMenu:jT,LucideMenuSquare:wI,LucideMerge:v0e,LucideMessageCircle:Ed,LucideMessageCircleCode:b0e,LucideMessageCircleDashed:_0e,LucideMessageCircleHeart:Az,LucideMessageCircleMore:w0e,LucideMessageCircleOff:j0e,LucideMessageCirclePlus:N0e,LucideMessageCircleQuestion:Ez,LucideMessageCircleReply:k0e,LucideMessageCircleWarning:S0e,LucideMessageCircleX:C0e,LucideMessageSquare:Ji,LucideMessageSquareCode:A0e,LucideMessageSquareDashed:E0e,LucideMessageSquareDiff:T0e,LucideMessageSquareDot:M0e,LucideMessageSquareHeart:Tz,LucideMessageSquareLock:L0e,LucideMessageSquareMore:IK,LucideMessageSquareOff:P0e,LucideMessageSquarePlus:BS,LucideMessageSquareQuote:H3,LucideMessageSquareReply:I0e,LucideMessageSquareShare:D0e,LucideMessageSquareText:R0e,LucideMessageSquareWarning:O0e,LucideMessageSquareX:F0e,LucideMessagesSquare:Mz,LucideMic:Vj,LucideMic2:NP,LucideMicOff:z0e,LucideMicVocal:NP,LucideMicrochip:B0e,LucideMicroscope:$0e,LucideMicrowave:U0e,LucideMilestone:q0e,LucideMilk:H0e,LucideMilkOff:V0e,LucideMinimize:W0e,LucideMinimize2:G0e,LucideMinus:DN,LucideMinusCircle:BL,LucideMinusSquare:jI,LucideMonitor:Hj,LucideMonitorCheck:K0e,LucideMonitorCog:Y0e,LucideMonitorDot:Z0e,LucideMonitorDown:X0e,LucideMonitorOff:Q0e,LucideMonitorPause:J0e,LucideMonitorPlay:Lz,LucideMonitorSmartphone:eye,LucideMonitorSpeaker:tye,LucideMonitorStop:sye,LucideMonitorUp:wR,LucideMonitorX:nye,LucideMoon:aye,LucideMoonStar:rye,LucideMoreHorizontal:p0,LucideMoreVertical:cy,LucideMountain:oye,LucideMountainSnow:iye,LucideMouse:uye,LucideMouseOff:lye,LucideMousePointer:pg,LucideMousePointer2:cye,LucideMousePointerBan:dye,LucideMousePointerClick:uu,LucideMousePointerSquareDashed:mI,LucideMove:DK,LucideMove3D:kP,LucideMove3d:kP,LucideMoveDiagonal:mye,LucideMoveDiagonal2:hye,LucideMoveDown:xye,LucideMoveDownLeft:pye,LucideMoveDownRight:fye,LucideMoveHorizontal:gye,LucideMoveLeft:yye,LucideMoveRight:vye,LucideMoveUp:wye,LucideMoveUpLeft:bye,LucideMoveUpRight:_ye,LucideMoveVertical:jye,LucideMusic:Pz,LucideMusic2:Nye,LucideMusic3:kye,LucideMusic4:Sye,LucideNavigation:RK,LucideNavigation2:Aye,LucideNavigation2Off:Cye,LucideNavigationOff:Eye,LucideNetwork:Tye,LucideNewspaper:Gj,LucideNfc:Mye,LucideNotebook:Dye,LucideNotebookPen:Lye,LucideNotebookTabs:Pye,LucideNotebookText:Iye,LucideNotepadText:Oye,LucideNotepadTextDashed:Rye,LucideNut:zye,LucideNutOff:Fye,LucideOctagon:$ye,LucideOctagonAlert:_N,LucideOctagonMinus:Bye,LucideOctagonPause:SP,LucideOctagonX:CP,LucideOmega:Uye,LucideOption:qye,LucideOrbit:Vye,LucideOrigami:Hye,LucideOutdent:vP,LucidePackage:Tu,LucidePackage2:Gye,LucidePackageCheck:Wye,LucidePackageMinus:Kye,LucidePackageOpen:Yye,LucidePackagePlus:OK,LucidePackageSearch:Zye,LucidePackageX:Xye,LucidePaintBucket:Qye,LucidePaintRoller:Jye,LucidePaintbrush:eve,LucidePaintbrush2:AP,LucidePaintbrushVertical:AP,LucidePalette:Rc,LucidePalmtree:HI,LucidePanelBottom:nve,LucidePanelBottomClose:tve,LucidePanelBottomDashed:EP,LucidePanelBottomInactive:EP,LucidePanelBottomOpen:sve,LucidePanelLeft:PP,LucidePanelLeftClose:TP,LucidePanelLeftDashed:MP,LucidePanelLeftInactive:MP,LucidePanelLeftOpen:LP,LucidePanelRight:ive,LucidePanelRightClose:rve,LucidePanelRightDashed:IP,LucidePanelRightInactive:IP,LucidePanelRightOpen:ave,LucidePanelTop:cve,LucidePanelTopClose:ove,LucidePanelTopDashed:DP,LucidePanelTopInactive:DP,LucidePanelTopOpen:lve,LucidePanelsLeftBottom:dve,LucidePanelsLeftRight:DA,LucidePanelsRightBottom:uve,LucidePanelsTopBottom:BP,LucidePanelsTopLeft:Q4,LucidePaperclip:NT,LucideParentheses:hve,LucideParkingCircle:UL,LucideParkingCircleOff:$L,LucideParkingMeter:mve,LucideParkingSquare:SI,LucideParkingSquareOff:kI,LucidePartyPopper:Nf,LucidePause:vy,LucidePauseCircle:qL,LucidePauseOctagon:SP,LucidePawPrint:pve,LucidePcCase:fve,LucidePen:kj,LucidePenBox:bm,LucidePenLine:wN,LucidePenOff:xve,LucidePenSquare:bm,LucidePenTool:kT,LucidePencil:Ya,LucidePencilLine:Iz,LucidePencilOff:gve,LucidePencilRuler:yve,LucidePentagon:vve,LucidePercent:ST,LucidePercentCircle:VL,LucidePercentDiamond:nP,LucidePercentSquare:CI,LucidePersonStanding:bve,LucidePhilippinePeso:_ve,LucidePhone:ya,LucidePhoneCall:FK,LucidePhoneForwarded:wve,LucidePhoneIncoming:jve,LucidePhoneMissed:Nve,LucidePhoneOff:kve,LucidePhoneOutgoing:Sve,LucidePi:Cve,LucidePiSquare:AI,LucidePiano:Ave,LucidePickaxe:Eve,LucidePictureInPicture:Mve,LucidePictureInPicture2:Tve,LucidePieChart:NL,LucidePiggyBank:Lve,LucidePilcrow:Dve,LucidePilcrowLeft:Pve,LucidePilcrowRight:Ive,LucidePilcrowSquare:EI,LucidePill:Ove,LucidePillBottle:Rve,LucidePin:CT,LucidePinOff:zK,LucidePipette:Fve,LucidePizza:zve,LucidePlane:BK,LucidePlaneLanding:Bve,LucidePlaneTakeoff:$ve,LucidePlay:Td,LucidePlayCircle:Sh,LucidePlaySquare:TI,LucidePlug:Wj,LucidePlug2:Uve,LucidePlugZap:RP,LucidePlugZap2:RP,LucidePlus:sn,LucidePlusCircle:HL,LucidePlusSquare:MI,LucidePocket:Vve,LucidePocketKnife:qve,LucidePodcast:Hve,LucidePointer:Wve,LucidePointerOff:Gve,LucidePopcorn:Kve,LucidePopsicle:Yve,LucidePoundSterling:Zve,LucidePower:$K,LucidePowerCircle:GL,LucidePowerOff:Xve,LucidePowerSquare:LI,LucidePresentation:by,LucidePrinter:AT,LucidePrinterCheck:Qve,LucideProjector:Jve,LucideProportions:e1e,LucidePuzzle:t1e,LucidePyramid:s1e,LucideQrCode:Rx,LucideQuote:RN,LucideRabbit:n1e,LucideRadar:Dz,LucideRadiation:r1e,LucideRadical:a1e,LucideRadio:Cg,LucideRadioReceiver:i1e,LucideRadioTower:o1e,LucideRadius:l1e,LucideRailSymbol:c1e,LucideRainbow:d1e,LucideRat:u1e,LucideRatio:h1e,LucideReceipt:_1e,LucideReceiptCent:m1e,LucideReceiptEuro:p1e,LucideReceiptIndianRupee:f1e,LucideReceiptJapaneseYen:x1e,LucideReceiptPoundSterling:g1e,LucideReceiptRussianRuble:y1e,LucideReceiptSwissFranc:v1e,LucideReceiptText:b1e,LucideRectangleEllipsis:OP,LucideRectangleHorizontal:w1e,LucideRectangleVertical:j1e,LucideRecycle:N1e,LucideRedo:ET,LucideRedo2:k1e,LucideRedoDot:S1e,LucideRefreshCcw:Rz,LucideRefreshCcwDot:C1e,LucideRefreshCw:Wi,LucideRefreshCwOff:A1e,LucideRefrigerator:E1e,LucideRegex:T1e,LucideRemoveFormatting:M1e,LucideRepeat:Oz,LucideRepeat1:L1e,LucideRepeat2:UK,LucideReplace:I1e,LucideReplaceAll:P1e,LucideReply:qK,LucideReplyAll:D1e,LucideRewind:R1e,LucideRibbon:O1e,LucideRocket:w0,LucideRockingChair:F1e,LucideRollerCoaster:z1e,LucideRotate3D:FP,LucideRotate3d:FP,LucideRotateCcw:Ih,LucideRotateCcwSquare:B1e,LucideRotateCw:jR,LucideRotateCwSquare:$1e,LucideRoute:Fz,LucideRouteOff:U1e,LucideRouter:q1e,LucideRows:zP,LucideRows2:zP,LucideRows3:BP,LucideRows4:V1e,LucideRss:H1e,LucideRuler:o5,LucideRussianRuble:G1e,LucideSailboat:W1e,LucideSalad:K1e,LucideSandwich:Y1e,LucideSatellite:X1e,LucideSatelliteDish:Z1e,LucideSave:Jo,LucideSaveAll:Q1e,LucideSaveOff:J1e,LucideScale:VK,LucideScale3D:$P,LucideScale3d:$P,LucideScaling:ebe,LucideScan:lbe,LucideScanBarcode:tbe,LucideScanEye:sbe,LucideScanFace:nbe,LucideScanLine:rbe,LucideScanQrCode:abe,LucideScanSearch:ibe,LucideScanText:obe,LucideScatterChart:kL,LucideSchool:cbe,LucideSchool2:WI,LucideScissors:ube,LucideScissorsLineDashed:dbe,LucideScissorsSquare:PI,LucideScissorsSquareDashedBottom:aI,LucideScreenShare:mbe,LucideScreenShareOff:hbe,LucideScroll:pbe,LucideScrollText:HK,LucideSearch:Vr,LucideSearchCheck:fbe,LucideSearchCode:xbe,LucideSearchSlash:gbe,LucideSearchX:GK,LucideSection:ybe,LucideSend:Br,LucideSendHorizonal:UP,LucideSendHorizontal:UP,LucideSendToBack:vbe,LucideSeparatorHorizontal:bbe,LucideSeparatorVertical:_be,LucideServer:kbe,LucideServerCog:wbe,LucideServerCrash:jbe,LucideServerOff:Nbe,LucideSettings:pc,LucideSettings2:G3,LucideShapes:Sbe,LucideShare:WK,LucideShare2:vd,LucideSheet:Cbe,LucideShell:Abe,LucideShield:kf,LucideShieldAlert:zz,LucideShieldBan:Ebe,LucideShieldCheck:j0,LucideShieldClose:qP,LucideShieldEllipsis:Tbe,LucideShieldHalf:Mbe,LucideShieldMinus:Lbe,LucideShieldOff:NR,LucideShieldPlus:Pbe,LucideShieldQuestion:Ibe,LucideShieldX:qP,LucideShip:Rbe,LucideShipWheel:Dbe,LucideShirt:Obe,LucideShoppingBag:l5,LucideShoppingBasket:Fbe,LucideShoppingCart:ON,LucideShovel:zbe,LucideShowerHead:Bbe,LucideShrink:$be,LucideShrub:Ube,LucideShuffle:kR,LucideSidebar:PP,LucideSidebarClose:TP,LucideSidebarOpen:LP,LucideSigma:qbe,LucideSigmaSquare:II,LucideSignal:Kbe,LucideSignalHigh:Vbe,LucideSignalLow:Hbe,LucideSignalMedium:Gbe,LucideSignalZero:Wbe,LucideSignature:Ybe,LucideSignpost:Xbe,LucideSignpostBig:Zbe,LucideSiren:Qbe,LucideSkipBack:Jbe,LucideSkipForward:KK,LucideSkull:e_e,LucideSlack:t_e,LucideSlash:s_e,LucideSlashSquare:DI,LucideSlice:n_e,LucideSliders:VP,LucideSlidersHorizontal:TT,LucideSlidersVertical:VP,LucideSmartphone:dv,LucideSmartphoneCharging:r_e,LucideSmartphoneNfc:a_e,LucideSmile:o_e,LucideSmilePlus:i_e,LucideSnail:l_e,LucideSnowflake:Z_,LucideSofa:c_e,LucideSortAsc:aL,LucideSortDesc:sL,LucideSoup:d_e,LucideSpace:u_e,LucideSpade:h_e,LucideSparkle:W3,LucideSparkles:dn,LucideSpeaker:m_e,LucideSpeech:p_e,LucideSpellCheck:x_e,LucideSpellCheck2:f_e,LucideSpline:g_e,LucideSplit:y_e,LucideSplitSquareHorizontal:RI,LucideSplitSquareVertical:OI,LucideSprayCan:v_e,LucideSprout:MT,LucideSquare:Lb,LucideSquareActivity:HP,LucideSquareArrowDown:KP,LucideSquareArrowDownLeft:GP,LucideSquareArrowDownRight:WP,LucideSquareArrowLeft:YP,LucideSquareArrowOutDownLeft:ZP,LucideSquareArrowOutDownRight:XP,LucideSquareArrowOutUpLeft:QP,LucideSquareArrowOutUpRight:JP,LucideSquareArrowRight:eI,LucideSquareArrowUp:nI,LucideSquareArrowUpLeft:tI,LucideSquareArrowUpRight:sI,LucideSquareAsterisk:rI,LucideSquareBottomDashedScissors:aI,LucideSquareChartGantt:Kk,LucideSquareCheck:iI,LucideSquareCheckBig:TS,LucideSquareChevronDown:oI,LucideSquareChevronLeft:lI,LucideSquareChevronRight:cI,LucideSquareChevronUp:dI,LucideSquareCode:uI,LucideSquareDashed:pI,LucideSquareDashedBottom:__e,LucideSquareDashedBottomCode:b_e,LucideSquareDashedKanban:hI,LucideSquareDashedMousePointer:mI,LucideSquareDivide:fI,LucideSquareDot:xI,LucideSquareEqual:gI,LucideSquareFunction:yI,LucideSquareGanttChart:Kk,LucideSquareKanban:vI,LucideSquareLibrary:bI,LucideSquareM:_I,LucideSquareMenu:wI,LucideSquareMinus:jI,LucideSquareMousePointer:NI,LucideSquareParking:SI,LucideSquareParkingOff:kI,LucideSquarePen:bm,LucideSquarePercent:CI,LucideSquarePi:AI,LucideSquarePilcrow:EI,LucideSquarePlay:TI,LucideSquarePlus:MI,LucideSquarePower:LI,LucideSquareRadical:w_e,LucideSquareScissors:PI,LucideSquareSigma:II,LucideSquareSlash:DI,LucideSquareSplitHorizontal:RI,LucideSquareSplitVertical:OI,LucideSquareSquare:j_e,LucideSquareStack:N_e,LucideSquareTerminal:FI,LucideSquareUser:BI,LucideSquareUserRound:zI,LucideSquareX:$I,LucideSquircle:k_e,LucideSquirrel:S_e,LucideStamp:C_e,LucideStar:Qa,LucideStarHalf:A_e,LucideStarOff:E_e,LucideStars:dn,LucideStepBack:T_e,LucideStepForward:M_e,LucideStethoscope:L_e,LucideSticker:P_e,LucideStickyNote:SR,LucideStopCircle:KL,LucideStore:Bz,LucideStretchHorizontal:I_e,LucideStretchVertical:D_e,LucideStrikethrough:YK,LucideSubscript:R_e,LucideSubtitles:mL,LucideSun:Kj,LucideSunDim:O_e,LucideSunMedium:F_e,LucideSunMoon:z_e,LucideSunSnow:B_e,LucideSunrise:$_e,LucideSunset:U_e,LucideSuperscript:q_e,LucideSwatchBook:V_e,LucideSwissFranc:H_e,LucideSwitchCamera:G_e,LucideSword:W_e,LucideSwords:K_e,LucideSyringe:Y_e,LucideTable:Uz,LucideTable2:$z,LucideTableCellsMerge:Z_e,LucideTableCellsSplit:X_e,LucideTableColumnsSplit:Q_e,LucideTableOfContents:J_e,LucideTableProperties:ewe,LucideTableRowsSplit:twe,LucideTablet:qz,LucideTabletSmartphone:swe,LucideTablets:nwe,LucideTag:Up,LucideTags:ZK,LucideTally1:rwe,LucideTally2:awe,LucideTally3:iwe,LucideTally4:owe,LucideTally5:lwe,LucideTangent:cwe,LucideTarget:Mu,LucideTelescope:dwe,LucideTent:hwe,LucideTentTree:uwe,LucideTerminal:mwe,LucideTerminalSquare:FI,LucideTestTube:pwe,LucideTestTube2:UI,LucideTestTubeDiagonal:UI,LucideTestTubes:fwe,LucideText:bwe,LucideTextCursor:gwe,LucideTextCursorInput:xwe,LucideTextQuote:ywe,LucideTextSearch:vwe,LucideTextSelect:qI,LucideTextSelection:qI,LucideTheater:_we,LucideThermometer:XK,LucideThermometerSnowflake:wwe,LucideThermometerSun:jwe,LucideThumbsDown:QK,LucideThumbsUp:Ox,LucideTicket:CR,LucideTicketCheck:Nwe,LucideTicketMinus:kwe,LucideTicketPercent:Swe,LucideTicketPlus:Cwe,LucideTicketSlash:Awe,LucideTicketX:Ewe,LucideTickets:Mwe,LucideTicketsPlane:Twe,LucideTimer:Iwe,LucideTimerOff:Lwe,LucideTimerReset:Pwe,LucideToggleLeft:Dwe,LucideToggleRight:Rwe,LucideToilet:Owe,LucideTornado:Fwe,LucideTorus:zwe,LucideTouchpad:$we,LucideTouchpadOff:Bwe,LucideTowerControl:Uwe,LucideToyBrick:qwe,LucideTractor:Vwe,LucideTrafficCone:Hwe,LucideTrain:VI,LucideTrainFront:Wwe,LucideTrainFrontTunnel:Gwe,LucideTrainTrack:Kwe,LucideTramFront:VI,LucideTrash:Ywe,LucideTrash2:Pn,LucideTreeDeciduous:Zwe,LucideTreePalm:HI,LucideTreePine:LT,LucideTrees:Xwe,LucideTrello:Qwe,LucideTrendingDown:FN,LucideTrendingUp:Il,LucideTrendingUpDown:Jwe,LucideTriangle:tje,LucideTriangleAlert:mc,LucideTriangleRight:eje,LucideTrophy:pl,LucideTruck:JK,LucideTurtle:sje,LucideTv:rje,LucideTv2:GI,LucideTvMinimal:GI,LucideTvMinimalPlay:nje,LucideTwitch:aje,LucideTwitter:ije,LucideType:lje,LucideTypeOutline:oje,LucideUmbrella:dje,LucideUmbrellaOff:cje,LucideUnderline:Vz,LucideUndo:PT,LucideUndo2:eY,LucideUndoDot:uje,LucideUnfoldHorizontal:hje,LucideUnfoldVertical:mje,LucideUngroup:pje,LucideUniversity:WI,LucideUnlink:AR,LucideUnlink2:fje,LucideUnlock:jP,LucideUnlockKeyhole:wP,LucideUnplug:tY,LucideUpload:si,LucideUploadCloud:eP,LucideUsb:xje,LucideUser:Lo,LucideUser2:JI,LucideUserCheck:Yj,LucideUserCheck2:KI,LucideUserCircle:ZL,LucideUserCircle2:YL,LucideUserCog:sY,LucideUserCog2:YI,LucideUserMinus:Hz,LucideUserMinus2:ZI,LucideUserPen:gje,LucideUserPlus:il,LucideUserPlus2:XI,LucideUserRound:JI,LucideUserRoundCheck:KI,LucideUserRoundCog:YI,LucideUserRoundMinus:ZI,LucideUserRoundPen:yje,LucideUserRoundPlus:XI,LucideUserRoundSearch:vje,LucideUserRoundX:QI,LucideUserSearch:bje,LucideUserSquare:BI,LucideUserSquare2:zI,LucideUserX:_je,LucideUserX2:QI,LucideUsers:qn,LucideUsers2:t1,LucideUsersRound:t1,LucideUtensils:t8,LucideUtensilsCrossed:e8,LucideUtilityPole:wje,LucideVariable:Gz,LucideVault:jje,LucideVegan:Nje,LucideVenetianMask:kje,LucideVerified:lL,LucideVibrate:Cje,LucideVibrateOff:Sje,LucideVideo:Xr,LucideVideoOff:Aje,LucideVideotape:Eje,LucideView:Tje,LucideVoicemail:Mje,LucideVolleyball:Lje,LucideVolume:Dje,LucideVolume1:Pje,LucideVolume2:nY,LucideVolumeOff:Ije,LucideVolumeX:rY,LucideVote:Rje,LucideWallet:aY,LucideWallet2:s8,LucideWalletCards:Oje,LucideWalletMinimal:s8,LucideWallpaper:Fje,LucideWand:zje,LucideWand2:wm,LucideWandSparkles:wm,LucideWarehouse:Bje,LucideWashingMachine:$je,LucideWatch:Uje,LucideWaves:qje,LucideWaypoints:Vje,LucideWebcam:Hje,LucideWebhook:Wje,LucideWebhookOff:Gje,LucideWeight:Kje,LucideWheat:Zje,LucideWheatOff:Yje,LucideWholeWord:Xje,LucideWifi:s2e,LucideWifiHigh:Qje,LucideWifiLow:Jje,LucideWifiOff:e2e,LucideWifiZero:t2e,LucideWind:r2e,LucideWindArrowDown:n2e,LucideWine:iY,LucideWineOff:a2e,LucideWorkflow:oY,LucideWorm:i2e,LucideWrapText:o2e,LucideWrench:c5,LucideX:pr,LucideXCircle:$d,LucideXOctagon:CP,LucideXSquare:$I,LucideYoutube:l2e,LucideZap:ox,LucideZapOff:c2e,LucideZoomIn:IT,LucideZoomOut:Wz,Luggage:Zge,LuggageIcon:Zge,MSquare:_I,MSquareIcon:_I,Magnet:Xge,MagnetIcon:Xge,Mail:nn,MailCheck:Sz,MailCheckIcon:Sz,MailIcon:nn,MailMinus:Qge,MailMinusIcon:Qge,MailOpen:Cz,MailOpenIcon:Cz,MailPlus:LK,MailPlusIcon:LK,MailQuestion:Jge,MailQuestionIcon:Jge,MailSearch:e0e,MailSearchIcon:e0e,MailWarning:t0e,MailWarningIcon:t0e,MailX:wT,MailXIcon:wT,Mailbox:s0e,MailboxIcon:s0e,Mails:n0e,MailsIcon:n0e,Map:bR,MapIcon:bR,MapPin:ai,MapPinCheck:a0e,MapPinCheckIcon:a0e,MapPinCheckInside:r0e,MapPinCheckInsideIcon:r0e,MapPinHouse:i0e,MapPinHouseIcon:i0e,MapPinIcon:ai,MapPinMinus:l0e,MapPinMinusIcon:l0e,MapPinMinusInside:o0e,MapPinMinusInsideIcon:o0e,MapPinOff:c0e,MapPinOffIcon:c0e,MapPinPlus:u0e,MapPinPlusIcon:u0e,MapPinPlusInside:d0e,MapPinPlusInsideIcon:d0e,MapPinX:m0e,MapPinXIcon:m0e,MapPinXInside:h0e,MapPinXInsideIcon:h0e,MapPinned:p0e,MapPinnedIcon:p0e,Martini:f0e,MartiniIcon:f0e,Maximize:_R,Maximize2:PK,Maximize2Icon:PK,MaximizeIcon:_R,Medal:V3,MedalIcon:V3,Megaphone:Eh,MegaphoneIcon:Eh,MegaphoneOff:x0e,MegaphoneOffIcon:x0e,Meh:g0e,MehIcon:g0e,MemoryStick:y0e,MemoryStickIcon:y0e,Menu:jT,MenuIcon:jT,MenuSquare:wI,MenuSquareIcon:wI,Merge:v0e,MergeIcon:v0e,MessageCircle:Ed,MessageCircleCode:b0e,MessageCircleCodeIcon:b0e,MessageCircleDashed:_0e,MessageCircleDashedIcon:_0e,MessageCircleHeart:Az,MessageCircleHeartIcon:Az,MessageCircleIcon:Ed,MessageCircleMore:w0e,MessageCircleMoreIcon:w0e,MessageCircleOff:j0e,MessageCircleOffIcon:j0e,MessageCirclePlus:N0e,MessageCirclePlusIcon:N0e,MessageCircleQuestion:Ez,MessageCircleQuestionIcon:Ez,MessageCircleReply:k0e,MessageCircleReplyIcon:k0e,MessageCircleWarning:S0e,MessageCircleWarningIcon:S0e,MessageCircleX:C0e,MessageCircleXIcon:C0e,MessageSquare:Ji,MessageSquareCode:A0e,MessageSquareCodeIcon:A0e,MessageSquareDashed:E0e,MessageSquareDashedIcon:E0e,MessageSquareDiff:T0e,MessageSquareDiffIcon:T0e,MessageSquareDot:M0e,MessageSquareDotIcon:M0e,MessageSquareHeart:Tz,MessageSquareHeartIcon:Tz,MessageSquareIcon:Ji,MessageSquareLock:L0e,MessageSquareLockIcon:L0e,MessageSquareMore:IK,MessageSquareMoreIcon:IK,MessageSquareOff:P0e,MessageSquareOffIcon:P0e,MessageSquarePlus:BS,MessageSquarePlusIcon:BS,MessageSquareQuote:H3,MessageSquareQuoteIcon:H3,MessageSquareReply:I0e,MessageSquareReplyIcon:I0e,MessageSquareShare:D0e,MessageSquareShareIcon:D0e,MessageSquareText:R0e,MessageSquareTextIcon:R0e,MessageSquareWarning:O0e,MessageSquareWarningIcon:O0e,MessageSquareX:F0e,MessageSquareXIcon:F0e,MessagesSquare:Mz,MessagesSquareIcon:Mz,Mic:Vj,Mic2:NP,Mic2Icon:NP,MicIcon:Vj,MicOff:z0e,MicOffIcon:z0e,MicVocal:NP,MicVocalIcon:NP,Microchip:B0e,MicrochipIcon:B0e,Microscope:$0e,MicroscopeIcon:$0e,Microwave:U0e,MicrowaveIcon:U0e,Milestone:q0e,MilestoneIcon:q0e,Milk:H0e,MilkIcon:H0e,MilkOff:V0e,MilkOffIcon:V0e,Minimize:W0e,Minimize2:G0e,Minimize2Icon:G0e,MinimizeIcon:W0e,Minus:DN,MinusCircle:BL,MinusCircleIcon:BL,MinusIcon:DN,MinusSquare:jI,MinusSquareIcon:jI,Monitor:Hj,MonitorCheck:K0e,MonitorCheckIcon:K0e,MonitorCog:Y0e,MonitorCogIcon:Y0e,MonitorDot:Z0e,MonitorDotIcon:Z0e,MonitorDown:X0e,MonitorDownIcon:X0e,MonitorIcon:Hj,MonitorOff:Q0e,MonitorOffIcon:Q0e,MonitorPause:J0e,MonitorPauseIcon:J0e,MonitorPlay:Lz,MonitorPlayIcon:Lz,MonitorSmartphone:eye,MonitorSmartphoneIcon:eye,MonitorSpeaker:tye,MonitorSpeakerIcon:tye,MonitorStop:sye,MonitorStopIcon:sye,MonitorUp:wR,MonitorUpIcon:wR,MonitorX:nye,MonitorXIcon:nye,Moon:aye,MoonIcon:aye,MoonStar:rye,MoonStarIcon:rye,MoreHorizontal:p0,MoreHorizontalIcon:p0,MoreVertical:cy,MoreVerticalIcon:cy,Mountain:oye,MountainIcon:oye,MountainSnow:iye,MountainSnowIcon:iye,Mouse:uye,MouseIcon:uye,MouseOff:lye,MouseOffIcon:lye,MousePointer:pg,MousePointer2:cye,MousePointer2Icon:cye,MousePointerBan:dye,MousePointerBanIcon:dye,MousePointerClick:uu,MousePointerClickIcon:uu,MousePointerIcon:pg,MousePointerSquareDashed:mI,MousePointerSquareDashedIcon:mI,Move:DK,Move3D:kP,Move3DIcon:kP,Move3d:kP,Move3dIcon:kP,MoveDiagonal:mye,MoveDiagonal2:hye,MoveDiagonal2Icon:hye,MoveDiagonalIcon:mye,MoveDown:xye,MoveDownIcon:xye,MoveDownLeft:pye,MoveDownLeftIcon:pye,MoveDownRight:fye,MoveDownRightIcon:fye,MoveHorizontal:gye,MoveHorizontalIcon:gye,MoveIcon:DK,MoveLeft:yye,MoveLeftIcon:yye,MoveRight:vye,MoveRightIcon:vye,MoveUp:wye,MoveUpIcon:wye,MoveUpLeft:bye,MoveUpLeftIcon:bye,MoveUpRight:_ye,MoveUpRightIcon:_ye,MoveVertical:jye,MoveVerticalIcon:jye,Music:Pz,Music2:Nye,Music2Icon:Nye,Music3:kye,Music3Icon:kye,Music4:Sye,Music4Icon:Sye,MusicIcon:Pz,Navigation:RK,Navigation2:Aye,Navigation2Icon:Aye,Navigation2Off:Cye,Navigation2OffIcon:Cye,NavigationIcon:RK,NavigationOff:Eye,NavigationOffIcon:Eye,Network:Tye,NetworkIcon:Tye,Newspaper:Gj,NewspaperIcon:Gj,Nfc:Mye,NfcIcon:Mye,Notebook:Dye,NotebookIcon:Dye,NotebookPen:Lye,NotebookPenIcon:Lye,NotebookTabs:Pye,NotebookTabsIcon:Pye,NotebookText:Iye,NotebookTextIcon:Iye,NotepadText:Oye,NotepadTextDashed:Rye,NotepadTextDashedIcon:Rye,NotepadTextIcon:Oye,Nut:zye,NutIcon:zye,NutOff:Fye,NutOffIcon:Fye,Octagon:$ye,OctagonAlert:_N,OctagonAlertIcon:_N,OctagonIcon:$ye,OctagonMinus:Bye,OctagonMinusIcon:Bye,OctagonPause:SP,OctagonPauseIcon:SP,OctagonX:CP,OctagonXIcon:CP,Omega:Uye,OmegaIcon:Uye,Option:qye,OptionIcon:qye,Orbit:Vye,OrbitIcon:Vye,Origami:Hye,OrigamiIcon:Hye,Outdent:vP,OutdentIcon:vP,Package:Tu,Package2:Gye,Package2Icon:Gye,PackageCheck:Wye,PackageCheckIcon:Wye,PackageIcon:Tu,PackageMinus:Kye,PackageMinusIcon:Kye,PackageOpen:Yye,PackageOpenIcon:Yye,PackagePlus:OK,PackagePlusIcon:OK,PackageSearch:Zye,PackageSearchIcon:Zye,PackageX:Xye,PackageXIcon:Xye,PaintBucket:Qye,PaintBucketIcon:Qye,PaintRoller:Jye,PaintRollerIcon:Jye,Paintbrush:eve,Paintbrush2:AP,Paintbrush2Icon:AP,PaintbrushIcon:eve,PaintbrushVertical:AP,PaintbrushVerticalIcon:AP,Palette:Rc,PaletteIcon:Rc,Palmtree:HI,PalmtreeIcon:HI,PanelBottom:nve,PanelBottomClose:tve,PanelBottomCloseIcon:tve,PanelBottomDashed:EP,PanelBottomDashedIcon:EP,PanelBottomIcon:nve,PanelBottomInactive:EP,PanelBottomInactiveIcon:EP,PanelBottomOpen:sve,PanelBottomOpenIcon:sve,PanelLeft:PP,PanelLeftClose:TP,PanelLeftCloseIcon:TP,PanelLeftDashed:MP,PanelLeftDashedIcon:MP,PanelLeftIcon:PP,PanelLeftInactive:MP,PanelLeftInactiveIcon:MP,PanelLeftOpen:LP,PanelLeftOpenIcon:LP,PanelRight:ive,PanelRightClose:rve,PanelRightCloseIcon:rve,PanelRightDashed:IP,PanelRightDashedIcon:IP,PanelRightIcon:ive,PanelRightInactive:IP,PanelRightInactiveIcon:IP,PanelRightOpen:ave,PanelRightOpenIcon:ave,PanelTop:cve,PanelTopClose:ove,PanelTopCloseIcon:ove,PanelTopDashed:DP,PanelTopDashedIcon:DP,PanelTopIcon:cve,PanelTopInactive:DP,PanelTopInactiveIcon:DP,PanelTopOpen:lve,PanelTopOpenIcon:lve,PanelsLeftBottom:dve,PanelsLeftBottomIcon:dve,PanelsLeftRight:DA,PanelsLeftRightIcon:DA,PanelsRightBottom:uve,PanelsRightBottomIcon:uve,PanelsTopBottom:BP,PanelsTopBottomIcon:BP,PanelsTopLeft:Q4,PanelsTopLeftIcon:Q4,Paperclip:NT,PaperclipIcon:NT,Parentheses:hve,ParenthesesIcon:hve,ParkingCircle:UL,ParkingCircleIcon:UL,ParkingCircleOff:$L,ParkingCircleOffIcon:$L,ParkingMeter:mve,ParkingMeterIcon:mve,ParkingSquare:SI,ParkingSquareIcon:SI,ParkingSquareOff:kI,ParkingSquareOffIcon:kI,PartyPopper:Nf,PartyPopperIcon:Nf,Pause:vy,PauseCircle:qL,PauseCircleIcon:qL,PauseIcon:vy,PauseOctagon:SP,PauseOctagonIcon:SP,PawPrint:pve,PawPrintIcon:pve,PcCase:fve,PcCaseIcon:fve,Pen:kj,PenBox:bm,PenBoxIcon:bm,PenIcon:kj,PenLine:wN,PenLineIcon:wN,PenOff:xve,PenOffIcon:xve,PenSquare:bm,PenSquareIcon:bm,PenTool:kT,PenToolIcon:kT,Pencil:Ya,PencilIcon:Ya,PencilLine:Iz,PencilLineIcon:Iz,PencilOff:gve,PencilOffIcon:gve,PencilRuler:yve,PencilRulerIcon:yve,Pentagon:vve,PentagonIcon:vve,Percent:ST,PercentCircle:VL,PercentCircleIcon:VL,PercentDiamond:nP,PercentDiamondIcon:nP,PercentIcon:ST,PercentSquare:CI,PercentSquareIcon:CI,PersonStanding:bve,PersonStandingIcon:bve,PhilippinePeso:_ve,PhilippinePesoIcon:_ve,Phone:ya,PhoneCall:FK,PhoneCallIcon:FK,PhoneForwarded:wve,PhoneForwardedIcon:wve,PhoneIcon:ya,PhoneIncoming:jve,PhoneIncomingIcon:jve,PhoneMissed:Nve,PhoneMissedIcon:Nve,PhoneOff:kve,PhoneOffIcon:kve,PhoneOutgoing:Sve,PhoneOutgoingIcon:Sve,Pi:Cve,PiIcon:Cve,PiSquare:AI,PiSquareIcon:AI,Piano:Ave,PianoIcon:Ave,Pickaxe:Eve,PickaxeIcon:Eve,PictureInPicture:Mve,PictureInPicture2:Tve,PictureInPicture2Icon:Tve,PictureInPictureIcon:Mve,PieChart:NL,PieChartIcon:NL,PiggyBank:Lve,PiggyBankIcon:Lve,Pilcrow:Dve,PilcrowIcon:Dve,PilcrowLeft:Pve,PilcrowLeftIcon:Pve,PilcrowRight:Ive,PilcrowRightIcon:Ive,PilcrowSquare:EI,PilcrowSquareIcon:EI,Pill:Ove,PillBottle:Rve,PillBottleIcon:Rve,PillIcon:Ove,Pin:CT,PinIcon:CT,PinOff:zK,PinOffIcon:zK,Pipette:Fve,PipetteIcon:Fve,Pizza:zve,PizzaIcon:zve,Plane:BK,PlaneIcon:BK,PlaneLanding:Bve,PlaneLandingIcon:Bve,PlaneTakeoff:$ve,PlaneTakeoffIcon:$ve,Play:Td,PlayCircle:Sh,PlayCircleIcon:Sh,PlayIcon:Td,PlaySquare:TI,PlaySquareIcon:TI,Plug:Wj,Plug2:Uve,Plug2Icon:Uve,PlugIcon:Wj,PlugZap:RP,PlugZap2:RP,PlugZap2Icon:RP,PlugZapIcon:RP,Plus:sn,PlusCircle:HL,PlusCircleIcon:HL,PlusIcon:sn,PlusSquare:MI,PlusSquareIcon:MI,Pocket:Vve,PocketIcon:Vve,PocketKnife:qve,PocketKnifeIcon:qve,Podcast:Hve,PodcastIcon:Hve,Pointer:Wve,PointerIcon:Wve,PointerOff:Gve,PointerOffIcon:Gve,Popcorn:Kve,PopcornIcon:Kve,Popsicle:Yve,PopsicleIcon:Yve,PoundSterling:Zve,PoundSterlingIcon:Zve,Power:$K,PowerCircle:GL,PowerCircleIcon:GL,PowerIcon:$K,PowerOff:Xve,PowerOffIcon:Xve,PowerSquare:LI,PowerSquareIcon:LI,Presentation:by,PresentationIcon:by,Printer:AT,PrinterCheck:Qve,PrinterCheckIcon:Qve,PrinterIcon:AT,Projector:Jve,ProjectorIcon:Jve,Proportions:e1e,ProportionsIcon:e1e,Puzzle:t1e,PuzzleIcon:t1e,Pyramid:s1e,PyramidIcon:s1e,QrCode:Rx,QrCodeIcon:Rx,Quote:RN,QuoteIcon:RN,Rabbit:n1e,RabbitIcon:n1e,Radar:Dz,RadarIcon:Dz,Radiation:r1e,RadiationIcon:r1e,Radical:a1e,RadicalIcon:a1e,Radio:Cg,RadioIcon:Cg,RadioReceiver:i1e,RadioReceiverIcon:i1e,RadioTower:o1e,RadioTowerIcon:o1e,Radius:l1e,RadiusIcon:l1e,RailSymbol:c1e,RailSymbolIcon:c1e,Rainbow:d1e,RainbowIcon:d1e,Rat:u1e,RatIcon:u1e,Ratio:h1e,RatioIcon:h1e,Receipt:_1e,ReceiptCent:m1e,ReceiptCentIcon:m1e,ReceiptEuro:p1e,ReceiptEuroIcon:p1e,ReceiptIcon:_1e,ReceiptIndianRupee:f1e,ReceiptIndianRupeeIcon:f1e,ReceiptJapaneseYen:x1e,ReceiptJapaneseYenIcon:x1e,ReceiptPoundSterling:g1e,ReceiptPoundSterlingIcon:g1e,ReceiptRussianRuble:y1e,ReceiptRussianRubleIcon:y1e,ReceiptSwissFranc:v1e,ReceiptSwissFrancIcon:v1e,ReceiptText:b1e,ReceiptTextIcon:b1e,RectangleEllipsis:OP,RectangleEllipsisIcon:OP,RectangleHorizontal:w1e,RectangleHorizontalIcon:w1e,RectangleVertical:j1e,RectangleVerticalIcon:j1e,Recycle:N1e,RecycleIcon:N1e,Redo:ET,Redo2:k1e,Redo2Icon:k1e,RedoDot:S1e,RedoDotIcon:S1e,RedoIcon:ET,RefreshCcw:Rz,RefreshCcwDot:C1e,RefreshCcwDotIcon:C1e,RefreshCcwIcon:Rz,RefreshCw:Wi,RefreshCwIcon:Wi,RefreshCwOff:A1e,RefreshCwOffIcon:A1e,Refrigerator:E1e,RefrigeratorIcon:E1e,Regex:T1e,RegexIcon:T1e,RemoveFormatting:M1e,RemoveFormattingIcon:M1e,Repeat:Oz,Repeat1:L1e,Repeat1Icon:L1e,Repeat2:UK,Repeat2Icon:UK,RepeatIcon:Oz,Replace:I1e,ReplaceAll:P1e,ReplaceAllIcon:P1e,ReplaceIcon:I1e,Reply:qK,ReplyAll:D1e,ReplyAllIcon:D1e,ReplyIcon:qK,Rewind:R1e,RewindIcon:R1e,Ribbon:O1e,RibbonIcon:O1e,Rocket:w0,RocketIcon:w0,RockingChair:F1e,RockingChairIcon:F1e,RollerCoaster:z1e,RollerCoasterIcon:z1e,Rotate3D:FP,Rotate3DIcon:FP,Rotate3d:FP,Rotate3dIcon:FP,RotateCcw:Ih,RotateCcwIcon:Ih,RotateCcwSquare:B1e,RotateCcwSquareIcon:B1e,RotateCw:jR,RotateCwIcon:jR,RotateCwSquare:$1e,RotateCwSquareIcon:$1e,Route:Fz,RouteIcon:Fz,RouteOff:U1e,RouteOffIcon:U1e,Router:q1e,RouterIcon:q1e,Rows:zP,Rows2:zP,Rows2Icon:zP,Rows3:BP,Rows3Icon:BP,Rows4:V1e,Rows4Icon:V1e,RowsIcon:zP,Rss:H1e,RssIcon:H1e,Ruler:o5,RulerIcon:o5,RussianRuble:G1e,RussianRubleIcon:G1e,Sailboat:W1e,SailboatIcon:W1e,Salad:K1e,SaladIcon:K1e,Sandwich:Y1e,SandwichIcon:Y1e,Satellite:X1e,SatelliteDish:Z1e,SatelliteDishIcon:Z1e,SatelliteIcon:X1e,Save:Jo,SaveAll:Q1e,SaveAllIcon:Q1e,SaveIcon:Jo,SaveOff:J1e,SaveOffIcon:J1e,Scale:VK,Scale3D:$P,Scale3DIcon:$P,Scale3d:$P,Scale3dIcon:$P,ScaleIcon:VK,Scaling:ebe,ScalingIcon:ebe,Scan:lbe,ScanBarcode:tbe,ScanBarcodeIcon:tbe,ScanEye:sbe,ScanEyeIcon:sbe,ScanFace:nbe,ScanFaceIcon:nbe,ScanIcon:lbe,ScanLine:rbe,ScanLineIcon:rbe,ScanQrCode:abe,ScanQrCodeIcon:abe,ScanSearch:ibe,ScanSearchIcon:ibe,ScanText:obe,ScanTextIcon:obe,ScatterChart:kL,ScatterChartIcon:kL,School:cbe,School2:WI,School2Icon:WI,SchoolIcon:cbe,Scissors:ube,ScissorsIcon:ube,ScissorsLineDashed:dbe,ScissorsLineDashedIcon:dbe,ScissorsSquare:PI,ScissorsSquareDashedBottom:aI,ScissorsSquareDashedBottomIcon:aI,ScissorsSquareIcon:PI,ScreenShare:mbe,ScreenShareIcon:mbe,ScreenShareOff:hbe,ScreenShareOffIcon:hbe,Scroll:pbe,ScrollIcon:pbe,ScrollText:HK,ScrollTextIcon:HK,Search:Vr,SearchCheck:fbe,SearchCheckIcon:fbe,SearchCode:xbe,SearchCodeIcon:xbe,SearchIcon:Vr,SearchSlash:gbe,SearchSlashIcon:gbe,SearchX:GK,SearchXIcon:GK,Section:ybe,SectionIcon:ybe,Send:Br,SendHorizonal:UP,SendHorizonalIcon:UP,SendHorizontal:UP,SendHorizontalIcon:UP,SendIcon:Br,SendToBack:vbe,SendToBackIcon:vbe,SeparatorHorizontal:bbe,SeparatorHorizontalIcon:bbe,SeparatorVertical:_be,SeparatorVerticalIcon:_be,Server:kbe,ServerCog:wbe,ServerCogIcon:wbe,ServerCrash:jbe,ServerCrashIcon:jbe,ServerIcon:kbe,ServerOff:Nbe,ServerOffIcon:Nbe,Settings:pc,Settings2:G3,Settings2Icon:G3,SettingsIcon:pc,Shapes:Sbe,ShapesIcon:Sbe,Share:WK,Share2:vd,Share2Icon:vd,ShareIcon:WK,Sheet:Cbe,SheetIcon:Cbe,Shell:Abe,ShellIcon:Abe,Shield:kf,ShieldAlert:zz,ShieldAlertIcon:zz,ShieldBan:Ebe,ShieldBanIcon:Ebe,ShieldCheck:j0,ShieldCheckIcon:j0,ShieldClose:qP,ShieldCloseIcon:qP,ShieldEllipsis:Tbe,ShieldEllipsisIcon:Tbe,ShieldHalf:Mbe,ShieldHalfIcon:Mbe,ShieldIcon:kf,ShieldMinus:Lbe,ShieldMinusIcon:Lbe,ShieldOff:NR,ShieldOffIcon:NR,ShieldPlus:Pbe,ShieldPlusIcon:Pbe,ShieldQuestion:Ibe,ShieldQuestionIcon:Ibe,ShieldX:qP,ShieldXIcon:qP,Ship:Rbe,ShipIcon:Rbe,ShipWheel:Dbe,ShipWheelIcon:Dbe,Shirt:Obe,ShirtIcon:Obe,ShoppingBag:l5,ShoppingBagIcon:l5,ShoppingBasket:Fbe,ShoppingBasketIcon:Fbe,ShoppingCart:ON,ShoppingCartIcon:ON,Shovel:zbe,ShovelIcon:zbe,ShowerHead:Bbe,ShowerHeadIcon:Bbe,Shrink:$be,ShrinkIcon:$be,Shrub:Ube,ShrubIcon:Ube,Shuffle:kR,ShuffleIcon:kR,Sidebar:PP,SidebarClose:TP,SidebarCloseIcon:TP,SidebarIcon:PP,SidebarOpen:LP,SidebarOpenIcon:LP,Sigma:qbe,SigmaIcon:qbe,SigmaSquare:II,SigmaSquareIcon:II,Signal:Kbe,SignalHigh:Vbe,SignalHighIcon:Vbe,SignalIcon:Kbe,SignalLow:Hbe,SignalLowIcon:Hbe,SignalMedium:Gbe,SignalMediumIcon:Gbe,SignalZero:Wbe,SignalZeroIcon:Wbe,Signature:Ybe,SignatureIcon:Ybe,Signpost:Xbe,SignpostBig:Zbe,SignpostBigIcon:Zbe,SignpostIcon:Xbe,Siren:Qbe,SirenIcon:Qbe,SkipBack:Jbe,SkipBackIcon:Jbe,SkipForward:KK,SkipForwardIcon:KK,Skull:e_e,SkullIcon:e_e,Slack:t_e,SlackIcon:t_e,Slash:s_e,SlashIcon:s_e,SlashSquare:DI,SlashSquareIcon:DI,Slice:n_e,SliceIcon:n_e,Sliders:VP,SlidersHorizontal:TT,SlidersHorizontalIcon:TT,SlidersIcon:VP,SlidersVertical:VP,SlidersVerticalIcon:VP,Smartphone:dv,SmartphoneCharging:r_e,SmartphoneChargingIcon:r_e,SmartphoneIcon:dv,SmartphoneNfc:a_e,SmartphoneNfcIcon:a_e,Smile:o_e,SmileIcon:o_e,SmilePlus:i_e,SmilePlusIcon:i_e,Snail:l_e,SnailIcon:l_e,Snowflake:Z_,SnowflakeIcon:Z_,Sofa:c_e,SofaIcon:c_e,SortAsc:aL,SortAscIcon:aL,SortDesc:sL,SortDescIcon:sL,Soup:d_e,SoupIcon:d_e,Space:u_e,SpaceIcon:u_e,Spade:h_e,SpadeIcon:h_e,Sparkle:W3,SparkleIcon:W3,Sparkles:dn,SparklesIcon:dn,Speaker:m_e,SpeakerIcon:m_e,Speech:p_e,SpeechIcon:p_e,SpellCheck:x_e,SpellCheck2:f_e,SpellCheck2Icon:f_e,SpellCheckIcon:x_e,Spline:g_e,SplineIcon:g_e,Split:y_e,SplitIcon:y_e,SplitSquareHorizontal:RI,SplitSquareHorizontalIcon:RI,SplitSquareVertical:OI,SplitSquareVerticalIcon:OI,SprayCan:v_e,SprayCanIcon:v_e,Sprout:MT,SproutIcon:MT,Square:Lb,SquareActivity:HP,SquareActivityIcon:HP,SquareArrowDown:KP,SquareArrowDownIcon:KP,SquareArrowDownLeft:GP,SquareArrowDownLeftIcon:GP,SquareArrowDownRight:WP,SquareArrowDownRightIcon:WP,SquareArrowLeft:YP,SquareArrowLeftIcon:YP,SquareArrowOutDownLeft:ZP,SquareArrowOutDownLeftIcon:ZP,SquareArrowOutDownRight:XP,SquareArrowOutDownRightIcon:XP,SquareArrowOutUpLeft:QP,SquareArrowOutUpLeftIcon:QP,SquareArrowOutUpRight:JP,SquareArrowOutUpRightIcon:JP,SquareArrowRight:eI,SquareArrowRightIcon:eI,SquareArrowUp:nI,SquareArrowUpIcon:nI,SquareArrowUpLeft:tI,SquareArrowUpLeftIcon:tI,SquareArrowUpRight:sI,SquareArrowUpRightIcon:sI,SquareAsterisk:rI,SquareAsteriskIcon:rI,SquareBottomDashedScissors:aI,SquareBottomDashedScissorsIcon:aI,SquareChartGantt:Kk,SquareChartGanttIcon:Kk,SquareCheck:iI,SquareCheckBig:TS,SquareCheckBigIcon:TS,SquareCheckIcon:iI,SquareChevronDown:oI,SquareChevronDownIcon:oI,SquareChevronLeft:lI,SquareChevronLeftIcon:lI,SquareChevronRight:cI,SquareChevronRightIcon:cI,SquareChevronUp:dI,SquareChevronUpIcon:dI,SquareCode:uI,SquareCodeIcon:uI,SquareDashed:pI,SquareDashedBottom:__e,SquareDashedBottomCode:b_e,SquareDashedBottomCodeIcon:b_e,SquareDashedBottomIcon:__e,SquareDashedIcon:pI,SquareDashedKanban:hI,SquareDashedKanbanIcon:hI,SquareDashedMousePointer:mI,SquareDashedMousePointerIcon:mI,SquareDivide:fI,SquareDivideIcon:fI,SquareDot:xI,SquareDotIcon:xI,SquareEqual:gI,SquareEqualIcon:gI,SquareFunction:yI,SquareFunctionIcon:yI,SquareGanttChart:Kk,SquareGanttChartIcon:Kk,SquareIcon:Lb,SquareKanban:vI,SquareKanbanIcon:vI,SquareLibrary:bI,SquareLibraryIcon:bI,SquareM:_I,SquareMIcon:_I,SquareMenu:wI,SquareMenuIcon:wI,SquareMinus:jI,SquareMinusIcon:jI,SquareMousePointer:NI,SquareMousePointerIcon:NI,SquareParking:SI,SquareParkingIcon:SI,SquareParkingOff:kI,SquareParkingOffIcon:kI,SquarePen:bm,SquarePenIcon:bm,SquarePercent:CI,SquarePercentIcon:CI,SquarePi:AI,SquarePiIcon:AI,SquarePilcrow:EI,SquarePilcrowIcon:EI,SquarePlay:TI,SquarePlayIcon:TI,SquarePlus:MI,SquarePlusIcon:MI,SquarePower:LI,SquarePowerIcon:LI,SquareRadical:w_e,SquareRadicalIcon:w_e,SquareScissors:PI,SquareScissorsIcon:PI,SquareSigma:II,SquareSigmaIcon:II,SquareSlash:DI,SquareSlashIcon:DI,SquareSplitHorizontal:RI,SquareSplitHorizontalIcon:RI,SquareSplitVertical:OI,SquareSplitVerticalIcon:OI,SquareSquare:j_e,SquareSquareIcon:j_e,SquareStack:N_e,SquareStackIcon:N_e,SquareTerminal:FI,SquareTerminalIcon:FI,SquareUser:BI,SquareUserIcon:BI,SquareUserRound:zI,SquareUserRoundIcon:zI,SquareX:$I,SquareXIcon:$I,Squircle:k_e,SquircleIcon:k_e,Squirrel:S_e,SquirrelIcon:S_e,Stamp:C_e,StampIcon:C_e,Star:Qa,StarHalf:A_e,StarHalfIcon:A_e,StarIcon:Qa,StarOff:E_e,StarOffIcon:E_e,Stars:dn,StarsIcon:dn,StepBack:T_e,StepBackIcon:T_e,StepForward:M_e,StepForwardIcon:M_e,Stethoscope:L_e,StethoscopeIcon:L_e,Sticker:P_e,StickerIcon:P_e,StickyNote:SR,StickyNoteIcon:SR,StopCircle:KL,StopCircleIcon:KL,Store:Bz,StoreIcon:Bz,StretchHorizontal:I_e,StretchHorizontalIcon:I_e,StretchVertical:D_e,StretchVerticalIcon:D_e,Strikethrough:YK,StrikethroughIcon:YK,Subscript:R_e,SubscriptIcon:R_e,Subtitles:mL,SubtitlesIcon:mL,Sun:Kj,SunDim:O_e,SunDimIcon:O_e,SunIcon:Kj,SunMedium:F_e,SunMediumIcon:F_e,SunMoon:z_e,SunMoonIcon:z_e,SunSnow:B_e,SunSnowIcon:B_e,Sunrise:$_e,SunriseIcon:$_e,Sunset:U_e,SunsetIcon:U_e,Superscript:q_e,SuperscriptIcon:q_e,SwatchBook:V_e,SwatchBookIcon:V_e,SwissFranc:H_e,SwissFrancIcon:H_e,SwitchCamera:G_e,SwitchCameraIcon:G_e,Sword:W_e,SwordIcon:W_e,Swords:K_e,SwordsIcon:K_e,Syringe:Y_e,SyringeIcon:Y_e,Table:Uz,Table2:$z,Table2Icon:$z,TableCellsMerge:Z_e,TableCellsMergeIcon:Z_e,TableCellsSplit:X_e,TableCellsSplitIcon:X_e,TableColumnsSplit:Q_e,TableColumnsSplitIcon:Q_e,TableIcon:Uz,TableOfContents:J_e,TableOfContentsIcon:J_e,TableProperties:ewe,TablePropertiesIcon:ewe,TableRowsSplit:twe,TableRowsSplitIcon:twe,Tablet:qz,TabletIcon:qz,TabletSmartphone:swe,TabletSmartphoneIcon:swe,Tablets:nwe,TabletsIcon:nwe,Tag:Up,TagIcon:Up,Tags:ZK,TagsIcon:ZK,Tally1:rwe,Tally1Icon:rwe,Tally2:awe,Tally2Icon:awe,Tally3:iwe,Tally3Icon:iwe,Tally4:owe,Tally4Icon:owe,Tally5:lwe,Tally5Icon:lwe,Tangent:cwe,TangentIcon:cwe,Target:Mu,TargetIcon:Mu,Telescope:dwe,TelescopeIcon:dwe,Tent:hwe,TentIcon:hwe,TentTree:uwe,TentTreeIcon:uwe,Terminal:mwe,TerminalIcon:mwe,TerminalSquare:FI,TerminalSquareIcon:FI,TestTube:pwe,TestTube2:UI,TestTube2Icon:UI,TestTubeDiagonal:UI,TestTubeDiagonalIcon:UI,TestTubeIcon:pwe,TestTubes:fwe,TestTubesIcon:fwe,Text:bwe,TextCursor:gwe,TextCursorIcon:gwe,TextCursorInput:xwe,TextCursorInputIcon:xwe,TextIcon:bwe,TextQuote:ywe,TextQuoteIcon:ywe,TextSearch:vwe,TextSearchIcon:vwe,TextSelect:qI,TextSelectIcon:qI,TextSelection:qI,TextSelectionIcon:qI,Theater:_we,TheaterIcon:_we,Thermometer:XK,ThermometerIcon:XK,ThermometerSnowflake:wwe,ThermometerSnowflakeIcon:wwe,ThermometerSun:jwe,ThermometerSunIcon:jwe,ThumbsDown:QK,ThumbsDownIcon:QK,ThumbsUp:Ox,ThumbsUpIcon:Ox,Ticket:CR,TicketCheck:Nwe,TicketCheckIcon:Nwe,TicketIcon:CR,TicketMinus:kwe,TicketMinusIcon:kwe,TicketPercent:Swe,TicketPercentIcon:Swe,TicketPlus:Cwe,TicketPlusIcon:Cwe,TicketSlash:Awe,TicketSlashIcon:Awe,TicketX:Ewe,TicketXIcon:Ewe,Tickets:Mwe,TicketsIcon:Mwe,TicketsPlane:Twe,TicketsPlaneIcon:Twe,Timer:Iwe,TimerIcon:Iwe,TimerOff:Lwe,TimerOffIcon:Lwe,TimerReset:Pwe,TimerResetIcon:Pwe,ToggleLeft:Dwe,ToggleLeftIcon:Dwe,ToggleRight:Rwe,ToggleRightIcon:Rwe,Toilet:Owe,ToiletIcon:Owe,Tornado:Fwe,TornadoIcon:Fwe,Torus:zwe,TorusIcon:zwe,Touchpad:$we,TouchpadIcon:$we,TouchpadOff:Bwe,TouchpadOffIcon:Bwe,TowerControl:Uwe,TowerControlIcon:Uwe,ToyBrick:qwe,ToyBrickIcon:qwe,Tractor:Vwe,TractorIcon:Vwe,TrafficCone:Hwe,TrafficConeIcon:Hwe,Train:VI,TrainFront:Wwe,TrainFrontIcon:Wwe,TrainFrontTunnel:Gwe,TrainFrontTunnelIcon:Gwe,TrainIcon:VI,TrainTrack:Kwe,TrainTrackIcon:Kwe,TramFront:VI,TramFrontIcon:VI,Trash:Ywe,Trash2:Pn,Trash2Icon:Pn,TrashIcon:Ywe,TreeDeciduous:Zwe,TreeDeciduousIcon:Zwe,TreePalm:HI,TreePalmIcon:HI,TreePine:LT,TreePineIcon:LT,Trees:Xwe,TreesIcon:Xwe,Trello:Qwe,TrelloIcon:Qwe,TrendingDown:FN,TrendingDownIcon:FN,TrendingUp:Il,TrendingUpDown:Jwe,TrendingUpDownIcon:Jwe,TrendingUpIcon:Il,Triangle:tje,TriangleAlert:mc,TriangleAlertIcon:mc,TriangleIcon:tje,TriangleRight:eje,TriangleRightIcon:eje,Trophy:pl,TrophyIcon:pl,Truck:JK,TruckIcon:JK,Turtle:sje,TurtleIcon:sje,Tv:rje,Tv2:GI,Tv2Icon:GI,TvIcon:rje,TvMinimal:GI,TvMinimalIcon:GI,TvMinimalPlay:nje,TvMinimalPlayIcon:nje,Twitch:aje,TwitchIcon:aje,Twitter:ije,TwitterIcon:ije,Type:lje,TypeIcon:lje,TypeOutline:oje,TypeOutlineIcon:oje,Umbrella:dje,UmbrellaIcon:dje,UmbrellaOff:cje,UmbrellaOffIcon:cje,Underline:Vz,UnderlineIcon:Vz,Undo:PT,Undo2:eY,Undo2Icon:eY,UndoDot:uje,UndoDotIcon:uje,UndoIcon:PT,UnfoldHorizontal:hje,UnfoldHorizontalIcon:hje,UnfoldVertical:mje,UnfoldVerticalIcon:mje,Ungroup:pje,UngroupIcon:pje,University:WI,UniversityIcon:WI,Unlink:AR,Unlink2:fje,Unlink2Icon:fje,UnlinkIcon:AR,Unlock:jP,UnlockIcon:jP,UnlockKeyhole:wP,UnlockKeyholeIcon:wP,Unplug:tY,UnplugIcon:tY,Upload:si,UploadCloud:eP,UploadCloudIcon:eP,UploadIcon:si,Usb:xje,UsbIcon:xje,User:Lo,User2:JI,User2Icon:JI,UserCheck:Yj,UserCheck2:KI,UserCheck2Icon:KI,UserCheckIcon:Yj,UserCircle:ZL,UserCircle2:YL,UserCircle2Icon:YL,UserCircleIcon:ZL,UserCog:sY,UserCog2:YI,UserCog2Icon:YI,UserCogIcon:sY,UserIcon:Lo,UserMinus:Hz,UserMinus2:ZI,UserMinus2Icon:ZI,UserMinusIcon:Hz,UserPen:gje,UserPenIcon:gje,UserPlus:il,UserPlus2:XI,UserPlus2Icon:XI,UserPlusIcon:il,UserRound:JI,UserRoundCheck:KI,UserRoundCheckIcon:KI,UserRoundCog:YI,UserRoundCogIcon:YI,UserRoundIcon:JI,UserRoundMinus:ZI,UserRoundMinusIcon:ZI,UserRoundPen:yje,UserRoundPenIcon:yje,UserRoundPlus:XI,UserRoundPlusIcon:XI,UserRoundSearch:vje,UserRoundSearchIcon:vje,UserRoundX:QI,UserRoundXIcon:QI,UserSearch:bje,UserSearchIcon:bje,UserSquare:BI,UserSquare2:zI,UserSquare2Icon:zI,UserSquareIcon:BI,UserX:_je,UserX2:QI,UserX2Icon:QI,UserXIcon:_je,Users:qn,Users2:t1,Users2Icon:t1,UsersIcon:qn,UsersRound:t1,UsersRoundIcon:t1,Utensils:t8,UtensilsCrossed:e8,UtensilsCrossedIcon:e8,UtensilsIcon:t8,UtilityPole:wje,UtilityPoleIcon:wje,Variable:Gz,VariableIcon:Gz,Vault:jje,VaultIcon:jje,Vegan:Nje,VeganIcon:Nje,VenetianMask:kje,VenetianMaskIcon:kje,Verified:lL,VerifiedIcon:lL,Vibrate:Cje,VibrateIcon:Cje,VibrateOff:Sje,VibrateOffIcon:Sje,Video:Xr,VideoIcon:Xr,VideoOff:Aje,VideoOffIcon:Aje,Videotape:Eje,VideotapeIcon:Eje,View:Tje,ViewIcon:Tje,Voicemail:Mje,VoicemailIcon:Mje,Volleyball:Lje,VolleyballIcon:Lje,Volume:Dje,Volume1:Pje,Volume1Icon:Pje,Volume2:nY,Volume2Icon:nY,VolumeIcon:Dje,VolumeOff:Ije,VolumeOffIcon:Ije,VolumeX:rY,VolumeXIcon:rY,Vote:Rje,VoteIcon:Rje,Wallet:aY,Wallet2:s8,Wallet2Icon:s8,WalletCards:Oje,WalletCardsIcon:Oje,WalletIcon:aY,WalletMinimal:s8,WalletMinimalIcon:s8,Wallpaper:Fje,WallpaperIcon:Fje,Wand:zje,Wand2:wm,Wand2Icon:wm,WandIcon:zje,WandSparkles:wm,WandSparklesIcon:wm,Warehouse:Bje,WarehouseIcon:Bje,WashingMachine:$je,WashingMachineIcon:$je,Watch:Uje,WatchIcon:Uje,Waves:qje,WavesIcon:qje,Waypoints:Vje,WaypointsIcon:Vje,Webcam:Hje,WebcamIcon:Hje,Webhook:Wje,WebhookIcon:Wje,WebhookOff:Gje,WebhookOffIcon:Gje,Weight:Kje,WeightIcon:Kje,Wheat:Zje,WheatIcon:Zje,WheatOff:Yje,WheatOffIcon:Yje,WholeWord:Xje,WholeWordIcon:Xje,Wifi:s2e,WifiHigh:Qje,WifiHighIcon:Qje,WifiIcon:s2e,WifiLow:Jje,WifiLowIcon:Jje,WifiOff:e2e,WifiOffIcon:e2e,WifiZero:t2e,WifiZeroIcon:t2e,Wind:r2e,WindArrowDown:n2e,WindArrowDownIcon:n2e,WindIcon:r2e,Wine:iY,WineIcon:iY,WineOff:a2e,WineOffIcon:a2e,Workflow:oY,WorkflowIcon:oY,Worm:i2e,WormIcon:i2e,WrapText:o2e,WrapTextIcon:o2e,Wrench:c5,WrenchIcon:c5,X:pr,XCircle:$d,XCircleIcon:$d,XIcon:pr,XOctagon:CP,XOctagonIcon:CP,XSquare:$I,XSquareIcon:$I,Youtube:l2e,YoutubeIcon:l2e,Zap:ox,ZapIcon:ox,ZapOff:c2e,ZapOffIcon:c2e,ZoomIn:IT,ZoomInIcon:IT,ZoomOut:Wz,ZoomOutIcon:Wz,createLucideIcon:de,icons:Xts},Symbol.toStringTag,{value:"Module"})),rVe="-",Qts=s=>{const t=ess(s),{conflictingClassGroups:n,conflictingClassGroupModifiers:r}=s;return{getClassGroupId:l=>{const o=l.split(rVe);return o[0]===""&&o.length!==1&&o.shift(),pNt(o,t)||Jts(l)},getConflictingClassGroupIds:(l,o)=>{const c=n[l]||[];return o&&r[l]?[...c,...r[l]]:c}}},pNt=(s,t)=>{var l;if(s.length===0)return t.classGroupId;const n=s[0],r=t.nextPart.get(n),a=r?pNt(s.slice(1),r):void 0;if(a)return a;if(t.validators.length===0)return;const i=s.join(rVe);return(l=t.validators.find(({validator:o})=>o(i)))==null?void 0:l.classGroupId},Qnt=/^\[(.+)\]$/,Jts=s=>{if(Qnt.test(s)){const t=Qnt.exec(s)[1],n=t==null?void 0:t.substring(0,t.indexOf(":"));if(n)return"arbitrary.."+n}},ess=s=>{const{theme:t,prefix:n}=s,r={nextPart:new Map,validators:[]};return sss(Object.entries(s.classGroups),n).forEach(([i,l])=>{MOe(l,r,i,t)}),r},MOe=(s,t,n,r)=>{s.forEach(a=>{if(typeof a=="string"){const i=a===""?t:Jnt(t,a);i.classGroupId=n;return}if(typeof a=="function"){if(tss(a)){MOe(a(r),t,n,r);return}t.validators.push({validator:a,classGroupId:n});return}Object.entries(a).forEach(([i,l])=>{MOe(l,Jnt(t,i),n,r)})})},Jnt=(s,t)=>{let n=s;return t.split(rVe).forEach(r=>{n.nextPart.has(r)||n.nextPart.set(r,{nextPart:new Map,validators:[]}),n=n.nextPart.get(r)}),n},tss=s=>s.isThemeGetter,sss=(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,nss=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)}}},fNt="!",rss=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:x,maybePostfixModifierPosition:g}};return n?o=>n({className:o,parseClassName:l}):l},ass=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},iss=s=>({cache:nss(s.cacheSize),parseClassName:rss(s),...Qts(s)}),oss=/\s+/,lss=(s,t)=>{const{parseClassName:n,getClassGroupId:r,getConflictingClassGroupIds:a}=t,i=[],l=s.trim().split(oss);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 x=!!p,g=r(x?m.substring(0,p):m);if(!g){if(!x){o=d+(o.length>0?" "+o:o);continue}if(g=r(m),!g){o=d+(o.length>0?" "+o:o);continue}x=!1}const y=ass(u).join(":"),b=h?y+fNt:y,v=b+g;if(i.includes(v))continue;i.push(v);const N=a(g,x);for(let C=0;C0?" "+o:o)}return o};function css(){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=iss(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=lss(c,n);return a(c,u),u}return function(){return i(css.apply(null,arguments))}}const fm=s=>{const t=n=>n[s]||[];return t.isThemeGetter=!0,t},gNt=/^\[(?:([a-z-]+):)?(.+)\]$/i,uss=/^\d+\/\d+$/,hss=new Set(["px","full","screen"]),mss=/^(\d+(\.\d+)?)?(xs|sm|md|lg|xl)$/,pss=/\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$/,fss=/^(rgba?|hsla?|hwb|(ok)?(lab|lch))\(.+\)$/,xss=/^(inset_)?-?((\d+)?\.?(\d+)[a-z]+|0)_-?((\d+)?\.?(\d+)[a-z]+|0)/,gss=/^(url|image|image-set|cross-fade|element|(repeating-)?(linear|radial|conic)-gradient)\(.+\)$/,y4=s=>Kz(s)||hss.has(s)||uss.test(s),JC=s=>mq(s,"length",kss),Kz=s=>!!s&&!Number.isNaN(Number(s)),uLe=s=>mq(s,"number",Kz),qH=s=>!!s&&Number.isInteger(Number(s)),yss=s=>s.endsWith("%")&&Kz(s.slice(0,-1)),dc=s=>gNt.test(s),eA=s=>mss.test(s),vss=new Set(["length","size","percentage"]),bss=s=>mq(s,vss,yNt),_ss=s=>mq(s,"position",yNt),wss=new Set(["image","url"]),jss=s=>mq(s,wss,Css),Nss=s=>mq(s,"",Sss),VH=()=>!0,mq=(s,t,n)=>{const r=gNt.exec(s);return r?r[1]?typeof t=="string"?r[1]===t:t.has(r[1]):n(r[2]):!1},kss=s=>pss.test(s)&&!fss.test(s),yNt=()=>!1,Sss=s=>xss.test(s),Css=s=>gss.test(s),Ass=()=>{const s=fm("colors"),t=fm("spacing"),n=fm("blur"),r=fm("brightness"),a=fm("borderColor"),i=fm("borderRadius"),l=fm("borderSpacing"),o=fm("borderWidth"),c=fm("contrast"),d=fm("grayscale"),u=fm("hueRotate"),h=fm("invert"),m=fm("gap"),p=fm("gradientColorStops"),x=fm("gradientColorStopPositions"),g=fm("inset"),y=fm("margin"),b=fm("opacity"),v=fm("padding"),N=fm("saturate"),C=fm("scale"),A=fm("sepia"),T=fm("skew"),P=fm("space"),M=fm("translate"),I=()=>["auto","contain","none"],D=()=>["auto","hidden","clip","visible","scroll"],B=()=>["auto",dc,t],q=()=>[dc,t],W=()=>["",y4,JC],V=()=>["auto",Kz,dc],K=()=>["bottom","center","left","left-bottom","left-top","right","right-bottom","right-top","top"],Q=()=>["solid","dashed","dotted","double","none"],J=()=>["normal","multiply","screen","overlay","darken","lighten","color-dodge","color-burn","hard-light","soft-light","difference","exclusion","hue","saturation","color","luminosity"],ce=()=>["start","end","center","between","around","evenly","stretch"],ue=()=>["","0",dc],ne=()=>["auto","avoid","all","avoid-page","page","left","right","column"],ee=()=>[Kz,dc];return{cacheSize:500,separator:":",theme:{colors:[VH],spacing:[y4,JC],blur:["none","",eA,dc],brightness:ee(),borderColor:[s],borderRadius:["none","","full",eA,dc],borderSpacing:q(),borderWidth:W(),contrast:ee(),grayscale:ue(),hueRotate:ee(),invert:ue(),gap:q(),gradientColorStops:[s],gradientColorStopPositions:[yss,JC],inset:B(),margin:B(),opacity:ee(),padding:q(),saturate:ee(),scale:ee(),sepia:ue(),skew:ee(),space:q(),translate:q()},classGroups:{aspect:[{aspect:["auto","square","video",dc]}],container:["container"],columns:[{columns:[eA]}],"break-after":[{"break-after":ne()}],"break-before":[{"break-before":ne()}],"break-inside":[{"break-inside":["auto","avoid","avoid-page","avoid-column"]}],"box-decoration":[{"box-decoration":["slice","clone"]}],box:[{box:["border","content"]}],display:["block","inline-block","inline","flex","inline-flex","table","inline-table","table-caption","table-cell","table-column","table-column-group","table-footer-group","table-header-group","table-row-group","table-row","flow-root","grid","inline-grid","contents","list-item","hidden"],float:[{float:["right","left","none","start","end"]}],clear:[{clear:["left","right","both","none","start","end"]}],isolation:["isolate","isolation-auto"],"object-fit":[{object:["contain","cover","fill","none","scale-down"]}],"object-position":[{object:[...K(),dc]}],overflow:[{overflow:D()}],"overflow-x":[{"overflow-x":D()}],"overflow-y":[{"overflow-y":D()}],overscroll:[{overscroll:I()}],"overscroll-x":[{"overscroll-x":I()}],"overscroll-y":[{"overscroll-y":I()}],position:["static","fixed","absolute","relative","sticky"],inset:[{inset:[g]}],"inset-x":[{"inset-x":[g]}],"inset-y":[{"inset-y":[g]}],start:[{start:[g]}],end:[{end:[g]}],top:[{top:[g]}],right:[{right:[g]}],bottom:[{bottom:[g]}],left:[{left:[g]}],visibility:["visible","invisible","collapse"],z:[{z:["auto",qH,dc]}],basis:[{basis:B()}],"flex-direction":[{flex:["row","row-reverse","col","col-reverse"]}],"flex-wrap":[{flex:["wrap","wrap-reverse","nowrap"]}],flex:[{flex:["1","auto","initial","none",dc]}],grow:[{grow:ue()}],shrink:[{shrink:ue()}],order:[{order:["first","last","none",qH,dc]}],"grid-cols":[{"grid-cols":[VH]}],"col-start-end":[{col:["auto",{span:["full",qH,dc]},dc]}],"col-start":[{"col-start":V()}],"col-end":[{"col-end":V()}],"grid-rows":[{"grid-rows":[VH]}],"row-start-end":[{row:["auto",{span:[qH,dc]},dc]}],"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",dc]}],"auto-rows":[{"auto-rows":["auto","min","max","fr",dc]}],gap:[{gap:[m]}],"gap-x":[{"gap-x":[m]}],"gap-y":[{"gap-y":[m]}],"justify-content":[{justify:["normal",...ce()]}],"justify-items":[{"justify-items":["start","end","center","stretch"]}],"justify-self":[{"justify-self":["auto","start","end","center","stretch"]}],"align-content":[{content:["normal",...ce(),"baseline"]}],"align-items":[{items:["start","end","center","baseline","stretch"]}],"align-self":[{self:["auto","start","end","center","stretch","baseline"]}],"place-content":[{"place-content":[...ce(),"baseline"]}],"place-items":[{"place-items":["start","end","center","baseline","stretch"]}],"place-self":[{"place-self":["auto","start","end","center","stretch"]}],p:[{p:[v]}],px:[{px:[v]}],py:[{py:[v]}],ps:[{ps:[v]}],pe:[{pe:[v]}],pt:[{pt:[v]}],pr:[{pr:[v]}],pb:[{pb:[v]}],pl:[{pl:[v]}],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":[P]}],"space-x-reverse":["space-x-reverse"],"space-y":[{"space-y":[P]}],"space-y-reverse":["space-y-reverse"],w:[{w:["auto","min","max","fit","svw","lvw","dvw",dc,t]}],"min-w":[{"min-w":[dc,t,"min","max","fit"]}],"max-w":[{"max-w":[dc,t,"none","full","min","max","fit","prose",{screen:[eA]},eA]}],h:[{h:[dc,t,"auto","min","max","fit","svh","lvh","dvh"]}],"min-h":[{"min-h":[dc,t,"min","max","fit","svh","lvh","dvh"]}],"max-h":[{"max-h":[dc,t,"min","max","fit","svh","lvh","dvh"]}],size:[{size:[dc,t,"auto","min","max","fit"]}],"font-size":[{text:["base",eA,JC]}],"font-smoothing":["antialiased","subpixel-antialiased"],"font-style":["italic","not-italic"],"font-weight":[{font:["thin","extralight","light","normal","medium","semibold","bold","extrabold","black",uLe]}],"font-family":[{font:[VH]}],"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",dc]}],"line-clamp":[{"line-clamp":["none",Kz,uLe]}],leading:[{leading:["none","tight","snug","normal","relaxed","loose",y4,dc]}],"list-image":[{"list-image":["none",dc]}],"list-style-type":[{list:["none","disc","decimal",dc]}],"list-style-position":[{list:["inside","outside"]}],"placeholder-color":[{placeholder:[s]}],"placeholder-opacity":[{"placeholder-opacity":[b]}],"text-alignment":[{text:["left","center","right","justify","start","end"]}],"text-color":[{text:[s]}],"text-opacity":[{"text-opacity":[b]}],"text-decoration":["underline","overline","line-through","no-underline"],"text-decoration-style":[{decoration:[...Q(),"wavy"]}],"text-decoration-thickness":[{decoration:["auto","from-font",y4,JC]}],"underline-offset":[{"underline-offset":["auto",y4,dc]}],"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:q()}],"vertical-align":[{align:["baseline","top","middle","bottom","text-top","text-bottom","sub","super",dc]}],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",dc]}],"bg-attachment":[{bg:["fixed","local","scroll"]}],"bg-clip":[{"bg-clip":["border","padding","content","text"]}],"bg-opacity":[{"bg-opacity":[b]}],"bg-origin":[{"bg-origin":["border","padding","content"]}],"bg-position":[{bg:[...K(),_ss]}],"bg-repeat":[{bg:["no-repeat",{repeat:["","x","y","round","space"]}]}],"bg-size":[{bg:["auto","cover","contain",bss]}],"bg-image":[{bg:["none",{"gradient-to":["t","tr","r","br","b","bl","l","tl"]},jss]}],"bg-color":[{bg:[s]}],"gradient-from-pos":[{from:[x]}],"gradient-via-pos":[{via:[x]}],"gradient-to-pos":[{to:[x]}],"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":[b]}],"border-style":[{border:[...Q(),"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":[b]}],"divide-style":[{divide:Q()}],"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:["",...Q()]}],"outline-offset":[{"outline-offset":[y4,dc]}],"outline-w":[{outline:[y4,JC]}],"outline-color":[{outline:[s]}],"ring-w":[{ring:W()}],"ring-w-inset":["ring-inset"],"ring-color":[{ring:[s]}],"ring-opacity":[{"ring-opacity":[b]}],"ring-offset-w":[{"ring-offset":[y4,JC]}],"ring-offset-color":[{"ring-offset":[s]}],shadow:[{shadow:["","inner","none",eA,Nss]}],"shadow-color":[{shadow:[VH]}],opacity:[{opacity:[b]}],"mix-blend":[{"mix-blend":[...J(),"plus-lighter","plus-darker"]}],"bg-blend":[{"bg-blend":J()}],filter:[{filter:["","none"]}],blur:[{blur:[n]}],brightness:[{brightness:[r]}],contrast:[{contrast:[c]}],"drop-shadow":[{"drop-shadow":["","none",eA,dc]}],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":[b]}],"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",dc]}],duration:[{duration:ee()}],ease:[{ease:["linear","in","out","in-out",dc]}],delay:[{delay:ee()}],animate:[{animate:["none","spin","ping","pulse","bounce",dc]}],transform:[{transform:["","gpu","none"]}],scale:[{scale:[C]}],"scale-x":[{"scale-x":[C]}],"scale-y":[{"scale-y":[C]}],rotate:[{rotate:[qH,dc]}],"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",dc]}],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",dc]}],"caret-color":[{caret:[s]}],"pointer-events":[{"pointer-events":["none","auto"]}],resize:[{resize:["none","y","x",""]}],"scroll-behavior":[{scroll:["auto","smooth"]}],"scroll-m":[{"scroll-m":q()}],"scroll-mx":[{"scroll-mx":q()}],"scroll-my":[{"scroll-my":q()}],"scroll-ms":[{"scroll-ms":q()}],"scroll-me":[{"scroll-me":q()}],"scroll-mt":[{"scroll-mt":q()}],"scroll-mr":[{"scroll-mr":q()}],"scroll-mb":[{"scroll-mb":q()}],"scroll-ml":[{"scroll-ml":q()}],"scroll-p":[{"scroll-p":q()}],"scroll-px":[{"scroll-px":q()}],"scroll-py":[{"scroll-py":q()}],"scroll-ps":[{"scroll-ps":q()}],"scroll-pe":[{"scroll-pe":q()}],"scroll-pt":[{"scroll-pt":q()}],"scroll-pr":[{"scroll-pr":q()}],"scroll-pb":[{"scroll-pb":q()}],"scroll-pl":[{"scroll-pl":q()}],"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",dc]}],fill:[{fill:[s,"none"]}],"stroke-w":[{stroke:[y4,JC,uLe]}],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"]}}},Ess=dss(Ass);function Tt(...s){return Ess($l(s))}function Au(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 ert(s){const t=new Date(s);return new Intl.DateTimeFormat("en-US",{month:"short",day:"numeric",year:"numeric"}).format(t)}function EZ(s){return s?s.replace(/<[^>]*>/g,""):""}const Tss=Kts,vNt=j.forwardRef(({className:s,...t},n)=>e.jsx(aNt,{ref:n,className:Tt("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}));vNt.displayName=aNt.displayName;const Mss=GO("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"}}),bNt=j.forwardRef(({className:s,variant:t,...n},r)=>e.jsx(iNt,{ref:r,className:Tt(Mss({variant:t}),s),...n}));bNt.displayName=iNt.displayName;const Lss=j.forwardRef(({className:s,...t},n)=>e.jsx(cNt,{ref:n,className:Tt("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}));Lss.displayName=cNt.displayName;const _Nt=j.forwardRef(({className:s,...t},n)=>e.jsx(dNt,{ref:n,className:Tt("absolute right-2 top-2 rounded-md p-1 text-foreground/50 opacity-0 transition-opacity group-hover:opacity-100 group-[.destructive]:text-red-300 hover:text-foreground group-[.destructive]:hover:text-red-50 focus:opacity-100 focus:outline-none focus:ring-2 group-[.destructive]:focus:ring-red-400 group-[.destructive]:focus:ring-offset-red-600",s),"toast-close":"",...t,children:e.jsx(pr,{className:"h-4 w-4"})}));_Nt.displayName=dNt.displayName;const wNt=j.forwardRef(({className:s,...t},n)=>e.jsx(oNt,{ref:n,className:Tt("text-sm font-semibold",s),...t}));wNt.displayName=oNt.displayName;const jNt=j.forwardRef(({className:s,...t},n)=>e.jsx(lNt,{ref:n,className:Tt("text-sm opacity-90",s),...t}));jNt.displayName=lNt.displayName;function Pss(){const{toasts:s}=gi();return e.jsxs(Tss,{children:[s.map(function({id:t,title:n,description:r,action:a,...i}){return e.jsxs(bNt,{...i,children:[e.jsxs("div",{className:"grid gap-1",children:[n&&e.jsx(wNt,{children:n}),r&&e.jsx(jNt,{children:r})]}),a,e.jsx(_Nt,{})]},t)}),e.jsx(vNt,{})]})}var trt=["light","dark"],Iss="(prefers-color-scheme: dark)",Dss=j.createContext(void 0),Rss={setTheme:s=>{},themes:[]},Oss=()=>{var s;return(s=j.useContext(Dss))!=null?s:Rss};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(x=>`'${x}'`).join(",")})`};`:`var d=document.documentElement,n='${n}',s='setAttribute';`,h=a?trt.includes(i)&&i?`if(e==='light'||e==='dark'||!e)d.style.colorScheme=e||'${i}'`:"if(e==='light'||e==='dark')d.style.colorScheme=e":"",m=(x,g=!1,y=!0)=>{let b=l?l[x]:x,v=g?x+"|| ''":`'${b}'`,N="";return a&&y&&!g&&trt.includes(x)&&(N+=`d.style.colorScheme = '${x}';`),n==="class"?g||b?N+=`c.add(${v})`:N+="null":b&&(N+=`d[s](n,${v})`),N},p=s?`!function(){${u}${m(s)}}()`:r?`!function(){try{${u}var e=localStorage.getItem('${t}');if('system'===e||(!e&&${d})){var t='${Iss}',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 Fss=s=>{switch(s){case"success":return $ss;case"info":return qss;case"warning":return Uss;case"error":return Vss;default:return null}},zss=Array(12).fill(0),Bss=({visible:s,className:t})=>It.createElement("div",{className:["sonner-loading-wrapper",t].filter(Boolean).join(" "),"data-visible":s},It.createElement("div",{className:"sonner-spinner"},zss.map((n,r)=>It.createElement("div",{className:"sonner-loading-bar",key:`spinner-bar-${r}`})))),$ss=It.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",fill:"currentColor",height:"20",width:"20"},It.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"})),Uss=It.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"currentColor",height:"20",width:"20"},It.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"})),qss=It.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",fill:"currentColor",height:"20",width:"20"},It.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"})),Vss=It.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",fill:"currentColor",height:"20",width:"20"},It.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"})),Hss=It.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"},It.createElement("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),It.createElement("line",{x1:"6",y1:"6",x2:"18",y2:"18"})),Gss=()=>{let[s,t]=It.useState(document.hidden);return It.useEffect(()=>{let n=()=>{t(document.hidden)};return document.addEventListener("visibilitychange",n),()=>window.removeEventListener("visibilitychange",n)},[]),s},LOe=1,Wss=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:LOe++,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],It.isValidElement(d))i=!1,this.create({id:r,type:"default",message:d});else if(Yss(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)||LOe++;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}},pb=new Wss,Kss=(s,t)=>{let n=(t==null?void 0:t.id)||LOe++;return pb.addToast({title:s,...t,id:n}),n},Yss=s=>s&&typeof s=="object"&&"ok"in s&&typeof s.ok=="boolean"&&"status"in s&&typeof s.status=="number",Zss=Kss,Xss=()=>pb.toasts,Qss=()=>pb.getActiveToasts(),ae=Object.assign(Zss,{success:pb.success,info:pb.info,warning:pb.warning,error:pb.error,custom:pb.custom,message:pb.message,promise:pb.promise,dismiss:pb.dismiss,loading:pb.loading},{getHistory:Xss,getToasts:Qss});function Jss(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))}Jss(`: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 ine(s){return s.label!==void 0}var ens=3,tns="32px",sns="16px",srt=4e3,nns=356,rns=14,ans=20,ins=200;function $2(...s){return s.filter(Boolean).join(" ")}function ons(s){let[t,n]=s.split("-"),r=[];return t&&r.push(t),n&&r.push(n),r}var lns=s=>{var t,n,r,a,i,l,o,c,d,u,h;let{invert:m,toast:p,unstyled:x,interacting:g,setHeights:y,visibleToasts:b,heights:v,index:N,toasts:C,expanded:A,removeToast:T,defaultRichColors:P,closeButton:M,style:I,cancelButtonStyle:D,actionButtonStyle:B,className:q="",descriptionClassName:W="",duration:V,position:K,gap:Q,loadingIcon:J,expandByDefault:ce,classNames:ue,icons:ne,closeButtonAriaLabel:ee="Close toast",pauseWhenPageIsHidden:le}=s,[he,ve]=It.useState(null),[ge,fe]=It.useState(null),[je,Ee]=It.useState(!1),[Me,De]=It.useState(!1),[ze,ke]=It.useState(!1),[Xe,Se]=It.useState(!1),[Re,Ae]=It.useState(!1),[Be,qe]=It.useState(0),[Ke,Ze]=It.useState(0),Ue=It.useRef(p.duration||V||srt),et=It.useRef(null),Qe=It.useRef(null),Ge=N===0,nt=N+1<=b,ft=p.type,lt=p.dismissible!==!1,Mt=p.className||"",Ft=p.descriptionClassName||"",Ts=It.useMemo(()=>v.findIndex(or=>or.toastId===p.id)||0,[v,p.id]),js=It.useMemo(()=>{var or;return(or=p.closeButton)!=null?or:M},[p.closeButton,M]),zt=It.useMemo(()=>p.duration||V||srt,[p.duration,V]),Nt=It.useRef(0),Ds=It.useRef(0),_t=It.useRef(0),Xs=It.useRef(null),[rn,Ps]=K.split("-"),_n=It.useMemo(()=>v.reduce((or,qs,yr)=>yr>=Ts?or:or+qs.height,0),[v,Ts]),Zs=Gss(),gr=p.invert||m,Un=ft==="loading";Ds.current=It.useMemo(()=>Ts*Q+_n,[Ts,_n]),It.useEffect(()=>{Ue.current=zt},[zt]),It.useEffect(()=>{Ee(!0)},[]),It.useEffect(()=>{let or=Qe.current;if(or){let qs=or.getBoundingClientRect().height;return Ze(qs),y(yr=>[{toastId:p.id,height:qs,position:p.position},...yr]),()=>y(yr=>yr.filter(fn=>fn.toastId!==p.id))}},[y,p.id]),It.useLayoutEffect(()=>{if(!je)return;let or=Qe.current,qs=or.style.height;or.style.height="auto";let yr=or.getBoundingClientRect().height;or.style.height=qs,Ze(yr),y(fn=>fn.find(Zn=>Zn.toastId===p.id)?fn.map(Zn=>Zn.toastId===p.id?{...Zn,height:yr}:Zn):[{toastId:p.id,height:yr,position:p.position},...fn])},[je,p.title,p.description,y,p.id]);let In=It.useCallback(()=>{De(!0),qe(Ds.current),y(or=>or.filter(qs=>qs.toastId!==p.id)),setTimeout(()=>{T(p)},ins)},[p,T,y,Ds]);It.useEffect(()=>{if(p.promise&&ft==="loading"||p.duration===1/0||p.type==="loading")return;let or;return A||g||le&&Zs?(()=>{if(_t.current{var qs;(qs=p.onAutoClose)==null||qs.call(p,p),In()},Ue.current)),()=>clearTimeout(or)},[A,g,p,ft,le,Zs,In]),It.useEffect(()=>{p.delete&&In()},[In,p.delete]);function Ar(){var or,qs,yr;return ne!=null&&ne.loading?It.createElement("div",{className:$2(ue==null?void 0:ue.loader,(or=p==null?void 0:p.classNames)==null?void 0:or.loader,"sonner-loader"),"data-visible":ft==="loading"},ne.loading):J?It.createElement("div",{className:$2(ue==null?void 0:ue.loader,(qs=p==null?void 0:p.classNames)==null?void 0:qs.loader,"sonner-loader"),"data-visible":ft==="loading"},J):It.createElement(Bss,{className:$2(ue==null?void 0:ue.loader,(yr=p==null?void 0:p.classNames)==null?void 0:yr.loader),visible:ft==="loading"})}return It.createElement("li",{tabIndex:0,ref:Qe,className:$2(q,Mt,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[ft],(n=p==null?void 0:p.classNames)==null?void 0:n[ft]),"data-sonner-toast":"","data-rich-colors":(r=p.richColors)!=null?r:P,"data-styled":!(p.jsx||p.unstyled||x),"data-mounted":je,"data-promise":!!p.promise,"data-swiped":Re,"data-removed":Me,"data-visible":nt,"data-y-position":rn,"data-x-position":Ps,"data-index":N,"data-front":Ge,"data-swiping":ze,"data-dismissible":lt,"data-type":ft,"data-invert":gr,"data-swipe-out":Xe,"data-swipe-direction":ge,"data-expanded":!!(A||ce&&je),style:{"--index":N,"--toasts-before":N,"--z-index":C.length-N,"--offset":`${Me?Be:Ds.current}px`,"--initial-height":ce?"auto":`${Ke}px`,...I,...p.style},onDragEnd:()=>{ke(!1),ve(null),Xs.current=null},onPointerDown:or=>{Un||!lt||(et.current=new Date,qe(Ds.current),or.target.setPointerCapture(or.pointerId),or.target.tagName!=="BUTTON"&&(ke(!0),Xs.current={x:or.clientX,y:or.clientY}))},onPointerUp:()=>{var or,qs,yr,fn;if(Xe||!lt)return;Xs.current=null;let Zn=Number(((or=Qe.current)==null?void 0:or.style.getPropertyValue("--swipe-amount-x").replace("px",""))||0),Xt=Number(((qs=Qe.current)==null?void 0:qs.style.getPropertyValue("--swipe-amount-y").replace("px",""))||0),rr=new Date().getTime()-((yr=et.current)==null?void 0:yr.getTime()),Qn=he==="x"?Zn:Xt,Sn=Math.abs(Qn)/rr;if(Math.abs(Qn)>=ans||Sn>.11){qe(Ds.current),(fn=p.onDismiss)==null||fn.call(p,p),fe(he==="x"?Zn>0?"right":"left":Xt>0?"down":"up"),In(),Se(!0),Ae(!1);return}ke(!1),ve(null)},onPointerMove:or=>{var qs,yr,fn,Zn;if(!Xs.current||!lt||((qs=window.getSelection())==null?void 0:qs.toString().length)>0)return;let Xt=or.clientY-Xs.current.y,rr=or.clientX-Xs.current.x,Qn=(yr=s.swipeDirections)!=null?yr:ons(K);!he&&(Math.abs(rr)>1||Math.abs(Xt)>1)&&ve(Math.abs(rr)>Math.abs(Xt)?"x":"y");let Sn={x:0,y:0};he==="y"?(Qn.includes("top")||Qn.includes("bottom"))&&(Qn.includes("top")&&Xt<0||Qn.includes("bottom")&&Xt>0)&&(Sn.y=Xt):he==="x"&&(Qn.includes("left")||Qn.includes("right"))&&(Qn.includes("left")&&rr<0||Qn.includes("right")&&rr>0)&&(Sn.x=rr),(Math.abs(Sn.x)>0||Math.abs(Sn.y)>0)&&Ae(!0),(fn=Qe.current)==null||fn.style.setProperty("--swipe-amount-x",`${Sn.x}px`),(Zn=Qe.current)==null||Zn.style.setProperty("--swipe-amount-y",`${Sn.y}px`)}},js&&!p.jsx?It.createElement("button",{"aria-label":ee,"data-disabled":Un,"data-close-button":!0,onClick:Un||!lt?()=>{}:()=>{var or;In(),(or=p.onDismiss)==null||or.call(p,p)},className:$2(ue==null?void 0:ue.closeButton,(a=p==null?void 0:p.classNames)==null?void 0:a.closeButton)},(i=ne==null?void 0:ne.close)!=null?i:Hss):null,p.jsx||j.isValidElement(p.title)?p.jsx?p.jsx:typeof p.title=="function"?p.title():p.title:It.createElement(It.Fragment,null,ft||p.icon||p.promise?It.createElement("div",{"data-icon":"",className:$2(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||Ar():null,p.type!=="loading"?p.icon||(ne==null?void 0:ne[ft])||Fss(ft):null):null,It.createElement("div",{"data-content":"",className:$2(ue==null?void 0:ue.content,(o=p==null?void 0:p.classNames)==null?void 0:o.content)},It.createElement("div",{"data-title":"",className:$2(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?It.createElement("div",{"data-description":"",className:$2(W,Ft,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&&ine(p.cancel)?It.createElement("button",{"data-button":!0,"data-cancel":!0,style:p.cancelButtonStyle||D,onClick:or=>{var qs,yr;ine(p.cancel)&<&&((yr=(qs=p.cancel).onClick)==null||yr.call(qs,or),In())},className:$2(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&&ine(p.action)?It.createElement("button",{"data-button":!0,"data-action":!0,style:p.actionButtonStyle||B,onClick:or=>{var qs,yr;ine(p.action)&&((yr=(qs=p.action).onClick)==null||yr.call(qs,or),!or.defaultPrevented&&In())},className:$2(ue==null?void 0:ue.actionButton,(h=p==null?void 0:p.classNames)==null?void 0:h.actionButton)},p.action.label):null))};function nrt(){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 cns(s,t){let n={};return[s,t].forEach((r,a)=>{let i=a===1,l=i?"--mobile-offset":"--offset",o=i?sns:tns;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 dns=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:x=ens,toastOptions:g,dir:y=nrt(),gap:b=rns,loadingIcon:v,icons:N,containerAriaLabel:C="Notifications",pauseWhenPageIsHidden:A}=s,[T,P]=It.useState([]),M=It.useMemo(()=>Array.from(new Set([r].concat(T.filter(le=>le.position).map(le=>le.position)))),[T,r]),[I,D]=It.useState([]),[B,q]=It.useState(!1),[W,V]=It.useState(!1),[K,Q]=It.useState(u!=="system"?u:typeof window<"u"&&window.matchMedia&&window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"),J=It.useRef(null),ce=a.join("+").replace(/Key/g,"").replace(/Digit/g,""),ue=It.useRef(null),ne=It.useRef(!1),ee=It.useCallback(le=>{P(he=>{var ve;return(ve=he.find(ge=>ge.id===le.id))!=null&&ve.delete||pb.dismiss(le.id),he.filter(({id:ge})=>ge!==le.id)})},[]);return It.useEffect(()=>pb.subscribe(le=>{if(le.dismiss){P(he=>he.map(ve=>ve.id===le.id?{...ve,delete:!0}:ve));return}setTimeout(()=>{Qqe.flushSync(()=>{P(he=>{let ve=he.findIndex(ge=>ge.id===le.id);return ve!==-1?[...he.slice(0,ve),{...he[ve],...le},...he.slice(ve+1)]:[le,...he]})})})}),[]),It.useEffect(()=>{if(u!=="system"){Q(u);return}if(u==="system"&&(window.matchMedia&&window.matchMedia("(prefers-color-scheme: dark)").matches?Q("dark"):Q("light")),typeof window>"u")return;let le=window.matchMedia("(prefers-color-scheme: dark)");try{le.addEventListener("change",({matches:he})=>{Q(he?"dark":"light")})}catch{le.addListener(({matches:ve})=>{try{Q(ve?"dark":"light")}catch(ge){console.error(ge)}})}},[u]),It.useEffect(()=>{T.length<=1&&q(!1)},[T]),It.useEffect(()=>{let le=he=>{var ve,ge;a.every(fe=>he[fe]||he.code===fe)&&(q(!0),(ve=J.current)==null||ve.focus()),he.code==="Escape"&&(document.activeElement===J.current||(ge=J.current)!=null&&ge.contains(document.activeElement))&&q(!1)};return document.addEventListener("keydown",le),()=>document.removeEventListener("keydown",le)},[a]),It.useEffect(()=>{if(J.current)return()=>{ue.current&&(ue.current.focus({preventScroll:!0}),ue.current=null,ne.current=!1)}},[J.current]),It.createElement("section",{ref:t,"aria-label":`${C} ${ce}`,tabIndex:-1,"aria-live":"polite","aria-relevant":"additions text","aria-atomic":"false",suppressHydrationWarning:!0},M.map((le,he)=>{var ve;let[ge,fe]=le.split("-");return T.length?It.createElement("ol",{key:le,dir:y==="auto"?nrt():y,tabIndex:-1,ref:J,className:o,"data-sonner-toaster":!0,"data-theme":K,"data-y-position":ge,"data-lifted":B&&T.length>1&&!i,"data-x-position":fe,style:{"--front-toast-height":`${((ve=I[0])==null?void 0:ve.height)||0}px`,"--width":`${nns}px`,"--gap":`${b}px`,...p,...cns(c,d)},onBlur:je=>{ne.current&&!je.currentTarget.contains(je.relatedTarget)&&(ne.current=!1,ue.current&&(ue.current.focus({preventScroll:!0}),ue.current=null))},onFocus:je=>{je.target instanceof HTMLElement&&je.target.dataset.dismissible==="false"||ne.current||(ne.current=!0,ue.current=je.relatedTarget)},onMouseEnter:()=>q(!0),onMouseMove:()=>q(!0),onMouseLeave:()=>{W||q(!1)},onDragEnd:()=>q(!1),onPointerDown:je=>{je.target instanceof HTMLElement&&je.target.dataset.dismissible==="false"||V(!0)},onPointerUp:()=>V(!1)},T.filter(je=>!je.position&&he===0||je.position===le).map((je,Ee)=>{var Me,De;return It.createElement(lns,{key:je.id,icons:N,index:Ee,toast:je,defaultRichColors:h,duration:(Me=g==null?void 0:g.duration)!=null?Me:m,className:g==null?void 0:g.className,descriptionClassName:g==null?void 0:g.descriptionClassName,invert:n,visibleToasts:x,closeButton:(De=g==null?void 0:g.closeButton)!=null?De:l,interacting:W,position:le,style:g==null?void 0:g.style,unstyled:g==null?void 0:g.unstyled,classNames:g==null?void 0:g.classNames,cancelButtonStyle:g==null?void 0:g.cancelButtonStyle,actionButtonStyle:g==null?void 0:g.actionButtonStyle,removeToast:ee,toasts:T.filter(ze=>ze.position==je.position),heights:I.filter(ze=>ze.position==je.position),setHeights:D,expandByDefault:i,gap:b,loadingIcon:v,expanded:B,pauseWhenPageIsHidden:A,swipeDirections:s.swipeDirections})})):null}))});const uns=({...s})=>{const{theme:t="system"}=Oss();return e.jsx(dns,{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 hns=oqe[" useId ".trim().toString()]||(()=>{}),mns=0;function Fx(s){const[t,n]=j.useState(hns());return Sf(()=>{n(r=>r??String(mns++))},[s]),t?`radix-${t}`:""}var hLe="focusScope.autoFocusOnMount",mLe="focusScope.autoFocusOnUnmount",rrt={bubbles:!1,cancelable:!0},pns="FocusScope",WJ=j.forwardRef((s,t)=>{const{loop:n=!1,trapped:r=!1,onMountAutoFocus:a,onUnmountAutoFocus:i,...l}=s,[o,c]=j.useState(null),d=bf(a),u=bf(i),h=j.useRef(null),m=Po(t,g=>c(g)),p=j.useRef({paused:!1,pause(){this.paused=!0},resume(){this.paused=!1}}).current;j.useEffect(()=>{if(r){let g=function(N){if(p.paused||!o)return;const C=N.target;o.contains(C)?h.current=C:vA(h.current,{select:!0})},y=function(N){if(p.paused||!o)return;const C=N.relatedTarget;C!==null&&(o.contains(C)||vA(h.current,{select:!0}))},b=function(N){if(document.activeElement===document.body)for(const A of N)A.removedNodes.length>0&&vA(o)};document.addEventListener("focusin",g),document.addEventListener("focusout",y);const v=new MutationObserver(b);return o&&v.observe(o,{childList:!0,subtree:!0}),()=>{document.removeEventListener("focusin",g),document.removeEventListener("focusout",y),v.disconnect()}}},[r,o,p.paused]),j.useEffect(()=>{if(o){irt.add(p);const g=document.activeElement;if(!o.contains(g)){const b=new CustomEvent(hLe,rrt);o.addEventListener(hLe,d),o.dispatchEvent(b),b.defaultPrevented||(fns(bns(NNt(o)),{select:!0}),document.activeElement===g&&vA(o))}return()=>{o.removeEventListener(hLe,d),setTimeout(()=>{const b=new CustomEvent(mLe,rrt);o.addEventListener(mLe,u),o.dispatchEvent(b),b.defaultPrevented||vA(g??document.body,{select:!0}),o.removeEventListener(mLe,u),irt.remove(p)},0)}}},[o,d,u,p]);const x=j.useCallback(g=>{if(!n&&!r||p.paused)return;const y=g.key==="Tab"&&!g.altKey&&!g.ctrlKey&&!g.metaKey,b=document.activeElement;if(y&&b){const v=g.currentTarget,[N,C]=xns(v);N&&C?!g.shiftKey&&b===C?(g.preventDefault(),n&&vA(N,{select:!0})):g.shiftKey&&b===N&&(g.preventDefault(),n&&vA(C,{select:!0})):b===v&&g.preventDefault()}},[n,r,p.paused]);return e.jsx(Ka.div,{tabIndex:-1,...l,ref:m,onKeyDown:x})});WJ.displayName=pns;function fns(s,{select:t=!1}={}){const n=document.activeElement;for(const r of s)if(vA(r,{select:t}),document.activeElement!==n)return}function xns(s){const t=NNt(s),n=art(t,s),r=art(t.reverse(),s);return[n,r]}function NNt(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 art(s,t){for(const n of s)if(!gns(n,{upTo:t}))return n}function gns(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 yns(s){return s instanceof HTMLInputElement&&"select"in s}function vA(s,{select:t=!1}={}){if(s&&s.focus){const n=document.activeElement;s.focus({preventScroll:!0}),s!==n&&yns(s)&&t&&s.select()}}var irt=vns();function vns(){let s=[];return{add(t){const n=s[0];t!==n&&(n==null||n.pause()),s=ort(s,t),s.unshift(t)},remove(t){var n;s=ort(s,t),(n=s[0])==null||n.resume()}}}function ort(s,t){const n=[...s],r=n.indexOf(t);return r!==-1&&n.splice(r,1),n}function bns(s){return s.filter(t=>t.tagName!=="A")}var pLe=0;function O3e(){j.useEffect(()=>{const s=document.querySelectorAll("[data-radix-focus-guard]");return document.body.insertAdjacentElement("afterbegin",s[0]??lrt()),document.body.insertAdjacentElement("beforeend",s[1]??lrt()),pLe++,()=>{pLe===1&&document.querySelectorAll("[data-radix-focus-guard]").forEach(t=>t.remove()),pLe--}},[])}function lrt(){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 IS=function(){return IS=Object.assign||function(t){for(var n,r=1,a=arguments.length;r"u")return Ons;var t=Fns(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])}},Bns=ANt(),Yz="data-scroll-locked",$ns=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(wns,` { overflow: hidden `).concat(r,`; padding-right: `).concat(o,"px ").concat(r,`; } body[`).concat(Yz,`] { 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(d2e,` { right: `).concat(o,"px ").concat(r,`; } .`).concat(u2e,` { margin-right: `).concat(o,"px ").concat(r,`; } .`).concat(d2e," .").concat(d2e,` { right: 0 `).concat(r,`; } .`).concat(u2e," .").concat(u2e,` { margin-right: 0 `).concat(r,`; } body[`).concat(Yz,`] { `).concat(jns,": ").concat(o,`px; } `)},drt=function(){var s=parseInt(document.body.getAttribute(Yz)||"0",10);return isFinite(s)?s:0},Uns=function(){j.useEffect(function(){return document.body.setAttribute(Yz,(drt()+1).toString()),function(){var s=drt()-1;s<=0?document.body.removeAttribute(Yz):document.body.setAttribute(Yz,s.toString())}},[])},qns=function(s){var t=s.noRelative,n=s.noImportant,r=s.gapMode,a=r===void 0?"margin":r;Uns();var i=j.useMemo(function(){return zns(a)},[a]);return j.createElement(Bns,{styles:$ns(i,!t,a,n?"":"!important")})},POe=!1;if(typeof window<"u")try{var one=Object.defineProperty({},"passive",{get:function(){return POe=!0,!0}});window.addEventListener("test",one,one),window.removeEventListener("test",one,one)}catch{POe=!1}var c7=POe?{passive:!1}:!1,Vns=function(s){return s.tagName==="TEXTAREA"},ENt=function(s,t){if(!(s instanceof Element))return!1;var n=window.getComputedStyle(s);return n[t]!=="hidden"&&!(n.overflowY===n.overflowX&&!Vns(s)&&n[t]==="visible")},Hns=function(s){return ENt(s,"overflowY")},Gns=function(s){return ENt(s,"overflowX")},urt=function(s,t){var n=t.ownerDocument,r=t;do{typeof ShadowRoot<"u"&&r instanceof ShadowRoot&&(r=r.host);var a=TNt(s,r);if(a){var i=MNt(s,r),l=i[1],o=i[2];if(l>o)return!0}r=r.parentNode}while(r&&r!==n.body);return!1},Wns=function(s){var t=s.scrollTop,n=s.scrollHeight,r=s.clientHeight;return[t,n,r]},Kns=function(s){var t=s.scrollLeft,n=s.scrollWidth,r=s.clientWidth;return[t,n,r]},TNt=function(s,t){return s==="v"?Hns(t):Gns(t)},MNt=function(s,t){return s==="v"?Wns(t):Kns(t)},Yns=function(s,t){return s==="h"&&t==="rtl"?-1:1},Zns=function(s,t,n,r,a){var i=Yns(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=MNt(s,o),x=p[0],g=p[1],y=p[2],b=g-y-i*x;(x||b)&&TNt(s,o)&&(h+=b,m+=x);var v=o.parentNode;o=v&&v.nodeType===Node.DOCUMENT_FRAGMENT_NODE?v.host:v}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},lne=function(s){return"changedTouches"in s?[s.changedTouches[0].clientX,s.changedTouches[0].clientY]:[0,0]},hrt=function(s){return[s.deltaX,s.deltaY]},mrt=function(s){return s&&"current"in s?s.current:s},Xns=function(s,t){return s[0]===t[0]&&s[1]===t[1]},Qns=function(s){return` .block-interactivity-`.concat(s,` {pointer-events: none;} .allow-interactivity-`).concat(s,` {pointer-events: all;} `)},Jns=0,d7=[];function ers(s){var t=j.useRef([]),n=j.useRef([0,0]),r=j.useRef(),a=j.useState(Jns++)[0],i=j.useState(ANt)[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 g=_ns([s.lockRef.current],(s.shards||[]).map(mrt),!0).filter(Boolean);return g.forEach(function(y){return y.classList.add("allow-interactivity-".concat(a))}),function(){document.body.classList.remove("block-interactivity-".concat(a)),g.forEach(function(y){return y.classList.remove("allow-interactivity-".concat(a))})}}},[s.inert,s.lockRef.current,s.shards]);var o=j.useCallback(function(g,y){if("touches"in g&&g.touches.length===2||g.type==="wheel"&&g.ctrlKey)return!l.current.allowPinchZoom;var b=lne(g),v=n.current,N="deltaX"in g?g.deltaX:v[0]-b[0],C="deltaY"in g?g.deltaY:v[1]-b[1],A,T=g.target,P=Math.abs(N)>Math.abs(C)?"h":"v";if("touches"in g&&P==="h"&&T.type==="range")return!1;var M=urt(P,T);if(!M)return!0;if(M?A=P:(A=P==="v"?"h":"v",M=urt(P,T)),!M)return!1;if(!r.current&&"changedTouches"in g&&(N||C)&&(r.current=A),!A)return!0;var I=r.current||A;return Zns(I,y,g,I==="h"?N:C,!0)},[]),c=j.useCallback(function(g){var y=g;if(!(!d7.length||d7[d7.length-1]!==i)){var b="deltaY"in y?hrt(y):lne(y),v=t.current.filter(function(A){return A.name===y.type&&(A.target===y.target||y.target===A.shadowParent)&&Xns(A.delta,b)})[0];if(v&&v.should){y.cancelable&&y.preventDefault();return}if(!v){var N=(l.current.shards||[]).map(mrt).filter(Boolean).filter(function(A){return A.contains(y.target)}),C=N.length>0?o(y,N[0]):!l.current.noIsolation;C&&y.cancelable&&y.preventDefault()}}},[]),d=j.useCallback(function(g,y,b,v){var N={name:g,delta:y,target:b,should:v,shadowParent:trs(b)};t.current.push(N),setTimeout(function(){t.current=t.current.filter(function(C){return C!==N})},1)},[]),u=j.useCallback(function(g){n.current=lne(g),r.current=void 0},[]),h=j.useCallback(function(g){d(g.type,hrt(g),g.target,o(g,s.lockRef.current))},[]),m=j.useCallback(function(g){d(g.type,lne(g),g.target,o(g,s.lockRef.current))},[]);j.useEffect(function(){return d7.push(i),s.setCallbacks({onScrollCapture:h,onWheelCapture:h,onTouchMoveCapture:m}),document.addEventListener("wheel",c,c7),document.addEventListener("touchmove",c,c7),document.addEventListener("touchstart",u,c7),function(){d7=d7.filter(function(g){return g!==i}),document.removeEventListener("wheel",c,c7),document.removeEventListener("touchmove",c,c7),document.removeEventListener("touchstart",u,c7)}},[]);var p=s.removeScrollBar,x=s.inert;return j.createElement(j.Fragment,null,x?j.createElement(i,{styles:Qns(a)}):null,p?j.createElement(qns,{noRelative:s.noRelative,gapMode:s.gapMode}):null)}function trs(s){for(var t=null;s!==null;)s instanceof ShadowRoot&&(t=s.host,s=s.host),s=s.parentNode;return t}const srs=Tns(CNt,ers);var KJ=j.forwardRef(function(s,t){return j.createElement(F3e,IS({},s,{ref:t,sideCar:srs}))});KJ.classNames=F3e.classNames;var nrs=function(s){if(typeof document>"u")return null;var t=Array.isArray(s)?s[0]:s;return t.ownerDocument.body},u7=new WeakMap,cne=new WeakMap,dne={},yLe=0,LNt=function(s){return s&&(s.host||LNt(s.parentNode))},rrs=function(s,t){return t.map(function(n){if(s.contains(n))return n;var r=LNt(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})},ars=function(s,t,n,r){var a=rrs(t,Array.isArray(s)?s:[s]);dne[n]||(dne[n]=new WeakMap);var i=dne[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),x=p!==null&&p!=="false",g=(u7.get(m)||0)+1,y=(i.get(m)||0)+1;u7.set(m,g),i.set(m,y),l.push(m),g===1&&x&&cne.set(m,!0),y===1&&m.setAttribute(n,"true"),x||m.setAttribute(r,"true")}catch(b){console.error("aria-hidden: cannot operate on ",m,b)}})};return u(t),o.clear(),yLe++,function(){l.forEach(function(h){var m=u7.get(h)-1,p=i.get(h)-1;u7.set(h,m),i.set(h,p),m||(cne.has(h)||h.removeAttribute(r),cne.delete(h)),p||h.removeAttribute(n)}),yLe--,yLe||(u7=new WeakMap,u7=new WeakMap,cne=new WeakMap,dne={})}},z3e=function(s,t,n){n===void 0&&(n="data-aria-hidden");var r=Array.from(Array.isArray(s)?s:[s]),a=nrs(s);return a?(r.push.apply(r,Array.from(a.querySelectorAll("[aria-live]"))),ars(r,a,n,"aria-hidden")):function(){return null}},B3e="Dialog",[PNt,INt]=ip(B3e),[irs,QN]=PNt(B3e),DNt=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]=Ux({prop:r,defaultProp:a??!1,onChange:i,caller:B3e});return e.jsx(irs,{scope:t,triggerRef:o,contentRef:c,contentId:Fx(),titleId:Fx(),descriptionId:Fx(),open:d,onOpenChange:u,onOpenToggle:j.useCallback(()=>u(h=>!h),[u]),modal:l,children:n})};DNt.displayName=B3e;var RNt="DialogTrigger",ONt=j.forwardRef((s,t)=>{const{__scopeDialog:n,...r}=s,a=QN(RNt,n),i=Po(t,a.triggerRef);return e.jsx(Ka.button,{type:"button","aria-haspopup":"dialog","aria-expanded":a.open,"aria-controls":a.contentId,"data-state":oVe(a.open),...r,ref:i,onClick:xa(s.onClick,a.onOpenToggle)})});ONt.displayName=RNt;var aVe="DialogPortal",[ors,FNt]=PNt(aVe,{forceMount:void 0}),zNt=s=>{const{__scopeDialog:t,forceMount:n,children:r,container:a}=s,i=QN(aVe,t);return e.jsx(ors,{scope:t,forceMount:n,children:j.Children.map(r,l=>e.jsx(dx,{present:n||i.open,children:e.jsx(hq,{asChild:!0,container:a,children:l})}))})};zNt.displayName=aVe;var xke="DialogOverlay",BNt=j.forwardRef((s,t)=>{const n=FNt(xke,s.__scopeDialog),{forceMount:r=n.forceMount,...a}=s,i=QN(xke,s.__scopeDialog);return i.modal?e.jsx(dx,{present:r||i.open,children:e.jsx(crs,{...a,ref:t})}):null});BNt.displayName=xke;var lrs=QT("DialogOverlay.RemoveScroll"),crs=j.forwardRef((s,t)=>{const{__scopeDialog:n,...r}=s,a=QN(xke,n);return e.jsx(KJ,{as:lrs,allowPinchZoom:!0,shards:[a.contentRef],children:e.jsx(Ka.div,{"data-state":oVe(a.open),...r,ref:t,style:{pointerEvents:"auto",...r.style}})})}),sO="DialogContent",$Nt=j.forwardRef((s,t)=>{const n=FNt(sO,s.__scopeDialog),{forceMount:r=n.forceMount,...a}=s,i=QN(sO,s.__scopeDialog);return e.jsx(dx,{present:r||i.open,children:i.modal?e.jsx(drs,{...a,ref:t}):e.jsx(urs,{...a,ref:t})})});$Nt.displayName=sO;var drs=j.forwardRef((s,t)=>{const n=QN(sO,s.__scopeDialog),r=j.useRef(null),a=Po(t,n.contentRef,r);return j.useEffect(()=>{const i=r.current;if(i)return z3e(i)},[]),e.jsx(UNt,{...s,ref:a,trapFocus:n.open,disableOutsidePointerEvents:!0,onCloseAutoFocus:xa(s.onCloseAutoFocus,i=>{var l;i.preventDefault(),(l=n.triggerRef.current)==null||l.focus()}),onPointerDownOutside:xa(s.onPointerDownOutside,i=>{const l=i.detail.originalEvent,o=l.button===0&&l.ctrlKey===!0;(l.button===2||o)&&i.preventDefault()}),onFocusOutside:xa(s.onFocusOutside,i=>i.preventDefault())})}),urs=j.forwardRef((s,t)=>{const n=QN(sO,s.__scopeDialog),r=j.useRef(!1),a=j.useRef(!1);return e.jsx(UNt,{...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()}})}),UNt=j.forwardRef((s,t)=>{const{__scopeDialog:n,trapFocus:r,onOpenAutoFocus:a,onCloseAutoFocus:i,...l}=s,o=QN(sO,n),c=j.useRef(null),d=Po(t,c);return O3e(),e.jsxs(e.Fragment,{children:[e.jsx(WJ,{asChild:!0,loop:!0,trapped:r,onMountAutoFocus:a,onUnmountAutoFocus:i,children:e.jsx(j6,{role:"dialog",id:o.contentId,"aria-describedby":o.descriptionId,"aria-labelledby":o.titleId,"data-state":oVe(o.open),...l,ref:d,onDismiss:()=>o.onOpenChange(!1)})}),e.jsxs(e.Fragment,{children:[e.jsx(mrs,{titleId:o.titleId}),e.jsx(frs,{contentRef:c,descriptionId:o.descriptionId})]})]})}),iVe="DialogTitle",qNt=j.forwardRef((s,t)=>{const{__scopeDialog:n,...r}=s,a=QN(iVe,n);return e.jsx(Ka.h2,{id:a.titleId,...r,ref:t})});qNt.displayName=iVe;var VNt="DialogDescription",HNt=j.forwardRef((s,t)=>{const{__scopeDialog:n,...r}=s,a=QN(VNt,n);return e.jsx(Ka.p,{id:a.descriptionId,...r,ref:t})});HNt.displayName=VNt;var GNt="DialogClose",WNt=j.forwardRef((s,t)=>{const{__scopeDialog:n,...r}=s,a=QN(GNt,n);return e.jsx(Ka.button,{type:"button",...r,ref:t,onClick:xa(s.onClick,()=>a.onOpenChange(!1))})});WNt.displayName=GNt;function oVe(s){return s?"open":"closed"}var KNt="DialogTitleWarning",[hrs,YNt]=its(KNt,{contentName:sO,titleName:iVe,docsSlug:"dialog"}),mrs=({titleId:s})=>{const t=YNt(KNt),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},prs="DialogDescriptionWarning",frs=({contentRef:s,descriptionId:t})=>{const r=`Warning: Missing \`Description\` or \`aria-describedby={undefined}\` for {${YNt(prs).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},$3e=DNt,lVe=ONt,U3e=zNt,pq=BNt,fq=$Nt,YJ=qNt,ZJ=HNt,XJ=WNt,ZNt="AlertDialog",[xrs,mXn]=ip(ZNt,[INt]),_C=INt(),XNt=s=>{const{__scopeAlertDialog:t,...n}=s,r=_C(t);return e.jsx($3e,{...r,...n,modal:!0})};XNt.displayName=ZNt;var grs="AlertDialogTrigger",QNt=j.forwardRef((s,t)=>{const{__scopeAlertDialog:n,...r}=s,a=_C(n);return e.jsx(lVe,{...a,...r,ref:t})});QNt.displayName=grs;var yrs="AlertDialogPortal",JNt=s=>{const{__scopeAlertDialog:t,...n}=s,r=_C(t);return e.jsx(U3e,{...r,...n})};JNt.displayName=yrs;var vrs="AlertDialogOverlay",ekt=j.forwardRef((s,t)=>{const{__scopeAlertDialog:n,...r}=s,a=_C(n);return e.jsx(pq,{...a,...r,ref:t})});ekt.displayName=vrs;var Zz="AlertDialogContent",[brs,_rs]=xrs(Zz),wrs=$2t("AlertDialogContent"),tkt=j.forwardRef((s,t)=>{const{__scopeAlertDialog:n,children:r,...a}=s,i=_C(n),l=j.useRef(null),o=Po(t,l),c=j.useRef(null);return e.jsx(hrs,{contentName:Zz,titleName:skt,docsSlug:"alert-dialog",children:e.jsx(brs,{scope:n,cancelRef:c,children:e.jsxs(fq,{role:"alertdialog",...i,...a,ref:o,onOpenAutoFocus:xa(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(wrs,{children:r}),e.jsx(Nrs,{contentRef:l})]})})})});tkt.displayName=Zz;var skt="AlertDialogTitle",nkt=j.forwardRef((s,t)=>{const{__scopeAlertDialog:n,...r}=s,a=_C(n);return e.jsx(YJ,{...a,...r,ref:t})});nkt.displayName=skt;var rkt="AlertDialogDescription",akt=j.forwardRef((s,t)=>{const{__scopeAlertDialog:n,...r}=s,a=_C(n);return e.jsx(ZJ,{...a,...r,ref:t})});akt.displayName=rkt;var jrs="AlertDialogAction",ikt=j.forwardRef((s,t)=>{const{__scopeAlertDialog:n,...r}=s,a=_C(n);return e.jsx(XJ,{...a,...r,ref:t})});ikt.displayName=jrs;var okt="AlertDialogCancel",lkt=j.forwardRef((s,t)=>{const{__scopeAlertDialog:n,...r}=s,{cancelRef:a}=_rs(okt,n),i=_C(n),l=Po(t,a);return e.jsx(XJ,{...i,...r,ref:l})});lkt.displayName=okt;var Nrs=({contentRef:s})=>{const t=`\`${Zz}\` requires a description for the component to be accessible for screen reader users. You can add a description to the \`${Zz}\` by passing a \`${rkt}\` 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 \`${Zz}\`. 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},krs=XNt,Srs=QNt,Crs=JNt,ckt=ekt,dkt=tkt,ukt=ikt,hkt=lkt,mkt=nkt,pkt=akt;const H$=GO("inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-full text-sm font-medium ring-offset-background transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0",{variants:{variant:{default:"bg-primary text-primary-foreground hover:bg-primary/90",destructive:"bg-destructive text-destructive-foreground hover:bg-destructive/90",outline:"border border-input bg-background hover:bg-accent hover:text-accent-foreground",secondary:"bg-secondary text-secondary-foreground hover:bg-secondary/80",ghost:"hover:bg-accent hover:text-accent-foreground",link:"text-primary underline-offset-4 hover:underline"},size:{default:"h-10 px-4 py-2",sm:"h-9 rounded-md px-3",lg:"h-11 rounded-full px-8",icon:"h-10 w-10"}},defaultVariants:{variant:"default",size:"default"}}),$=j.forwardRef(({className:s,variant:t,size:n,asChild:r=!1,...a},i)=>{const l=r?Jqe:"button";return e.jsx(l,{className:Tt(H$({variant:t,size:n,className:s})),ref:i,...a})});$.displayName="Button";const Ll=krs,_f=Srs,Ars=Crs,fkt=j.forwardRef(({className:s,...t},n)=>e.jsx(ckt,{className:Tt("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}));fkt.displayName=ckt.displayName;const yl=j.forwardRef(({className:s,...t},n)=>e.jsxs(Ars,{children:[e.jsx(fkt,{}),e.jsx(dkt,{ref:n,className:Tt("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})]}));yl.displayName=dkt.displayName;const vl=({className:s,...t})=>e.jsx("div",{className:Tt("flex flex-col space-y-2 text-center sm:text-left",s),...t});vl.displayName="AlertDialogHeader";const bl=({className:s,...t})=>e.jsx("div",{className:Tt("flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2",s),...t});bl.displayName="AlertDialogFooter";const _l=j.forwardRef(({className:s,...t},n)=>e.jsx(mkt,{ref:n,className:Tt("text-lg font-semibold",s),...t}));_l.displayName=mkt.displayName;const wl=j.forwardRef(({className:s,...t},n)=>e.jsx(pkt,{ref:n,className:Tt("text-sm text-muted-foreground",s),...t}));wl.displayName=pkt.displayName;const fl=j.forwardRef(({className:s,...t},n)=>e.jsx(ukt,{ref:n,className:Tt(H$(),s),...t}));fl.displayName=ukt.displayName;const jl=j.forwardRef(({className:s,...t},n)=>e.jsx(hkt,{ref:n,className:Tt(H$({variant:"outline"}),"mt-2 sm:mt-0",s),...t}));jl.displayName=hkt.displayName;let gke=null;const Ers=["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??Ers.some(i=>r.includes(i));return new Promise(i=>{if(!gke){i(window.confirm(n.description??n.title??"Are you sure?"));return}gke({...n,destructive:a,resolve:i})})}function Trs(){const[s,t]=j.useState(null);j.useEffect(()=>(gke=a=>t(a),()=>{gke=null}),[]);const n=a=>{s==null||s.resolve(a),t(null)},r=!!(s!=null&&s.destructive);return e.jsx(Ll,{open:!!s,onOpenChange:a=>!a&&n(!1),children:e.jsxs(yl,{className:"sm:max-w-md",children:[e.jsx(vl,{children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:Tt("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(mc,{className:"h-5 w-5"})}),e.jsxs("div",{className:"space-y-1.5 text-left",children:[e.jsx(_l,{children:(s==null?void 0:s.title)??(r?"Are you sure?":"Please confirm")}),(s==null?void 0:s.description)&&e.jsx(wl,{className:"leading-relaxed",children:s.description})]})]})}),e.jsxs(bl,{className:"gap-2 sm:gap-2",children:[e.jsx(jl,{onClick:()=>n(!1),children:(s==null?void 0:s.cancelText)??"Cancel"}),e.jsx(fl,{onClick:()=>n(!0),className:Tt(r&&"bg-destructive text-destructive-foreground hover:bg-destructive/90"),children:(s==null?void 0:s.confirmText)??(r?"Delete":"Continue")})]})]})})}const Mrs=["top","right","bottom","left"],JT=Math.min,U_=Math.max,yke=Math.round,une=Math.floor,e6=s=>({x:s,y:s}),Lrs={left:"right",right:"left",bottom:"top",top:"bottom"},Prs={start:"end",end:"start"};function IOe(s,t,n){return U_(s,JT(t,n))}function lC(s,t){return typeof s=="function"?s(t):s}function cC(s){return s.split("-")[0]}function xq(s){return s.split("-")[1]}function cVe(s){return s==="x"?"y":"x"}function dVe(s){return s==="y"?"height":"width"}function t6(s){return["top","bottom"].includes(cC(s))?"y":"x"}function uVe(s){return cVe(t6(s))}function Irs(s,t,n){n===void 0&&(n=!1);const r=xq(s),a=uVe(s),i=dVe(a);let l=a==="x"?r===(n?"end":"start")?"right":"left":r==="start"?"bottom":"top";return t.reference[i]>t.floating[i]&&(l=vke(l)),[l,vke(l)]}function Drs(s){const t=vke(s);return[DOe(s),t,DOe(t)]}function DOe(s){return s.replace(/start|end/g,t=>Prs[t])}function Rrs(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 Ors(s,t,n,r){const a=xq(s);let i=Rrs(cC(s),n==="start",r);return a&&(i=i.map(l=>l+"-"+a),t&&(i=i.concat(i.map(DOe)))),i}function vke(s){return s.replace(/left|right|bottom|top/g,t=>Lrs[t])}function Frs(s){return{top:0,right:0,bottom:0,left:0,...s}}function xkt(s){return typeof s!="number"?Frs(s):{top:s,right:s,bottom:s,left:s}}function bke(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 prt(s,t,n){let{reference:r,floating:a}=s;const i=t6(t),l=uVe(t),o=dVe(l),c=cC(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(xq(t)){case"start":p[l]-=m*(n&&d?-1:1);break;case"end":p[l]+=m*(n&&d?-1:1);break}return p}const zrs=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}=prt(d,r,c),m=r,p={},x=0;for(let g=0;g({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}=lC(s,t)||{};if(d==null)return{};const h=xkt(u),m={x:n,y:r},p=uVe(a),x=dVe(p),g=await l.getDimensions(d),y=p==="y",b=y?"top":"left",v=y?"bottom":"right",N=y?"clientHeight":"clientWidth",C=i.reference[x]+i.reference[p]-m[p]-i.floating[x],A=m[p]-i.reference[p],T=await(l.getOffsetParent==null?void 0:l.getOffsetParent(d));let P=T?T[N]:0;(!P||!await(l.isElement==null?void 0:l.isElement(T)))&&(P=o.floating[N]||i.floating[x]);const M=C/2-A/2,I=P/2-g[x]/2-1,D=JT(h[b],I),B=JT(h[v],I),q=D,W=P-g[x]-B,V=P/2-g[x]/2+M,K=IOe(q,V,W),Q=!c.arrow&&xq(a)!=null&&V!==K&&i.reference[x]/2-(VV<=0)){var B,q;const V=(((B=i.flip)==null?void 0:B.index)||0)+1,K=P[V];if(K)return{data:{index:V,overflows:D},reset:{placement:K}};let Q=(q=D.filter(J=>J.overflows[0]<=0).sort((J,ce)=>J.overflows[1]-ce.overflows[1])[0])==null?void 0:q.placement;if(!Q)switch(p){case"bestFit":{var W;const J=(W=D.filter(ce=>{if(T){const ue=t6(ce.placement);return ue===v||ue==="y"}return!0}).map(ce=>[ce.placement,ce.overflows.filter(ue=>ue>0).reduce((ue,ne)=>ue+ne,0)]).sort((ce,ue)=>ce[1]-ue[1])[0])==null?void 0:W[0];J&&(Q=J);break}case"initialPlacement":Q=o;break}if(a!==Q)return{reset:{placement:Q}}}return{}}}};function frt(s,t){return{top:s.top-t.height,right:s.right-t.width,bottom:s.bottom-t.height,left:s.left-t.width}}function xrt(s){return Mrs.some(t=>s[t]>=0)}const Urs=function(s){return s===void 0&&(s={}),{name:"hide",options:s,async fn(t){const{rects:n}=t,{strategy:r="referenceHidden",...a}=lC(s,t);switch(r){case"referenceHidden":{const i=await TZ(t,{...a,elementContext:"reference"}),l=frt(i,n.reference);return{data:{referenceHiddenOffsets:l,referenceHidden:xrt(l)}}}case"escaped":{const i=await TZ(t,{...a,altBoundary:!0}),l=frt(i,n.floating);return{data:{escapedOffsets:l,escaped:xrt(l)}}}default:return{}}}}};async function qrs(s,t){const{placement:n,platform:r,elements:a}=s,i=await(r.isRTL==null?void 0:r.isRTL(a.floating)),l=cC(n),o=xq(n),c=t6(n)==="y",d=["left","top"].includes(l)?-1:1,u=i&&c?-1:1,h=lC(t,s);let{mainAxis:m,crossAxis:p,alignmentAxis:x}=typeof h=="number"?{mainAxis:h,crossAxis:0,alignmentAxis:null}:{mainAxis:h.mainAxis||0,crossAxis:h.crossAxis||0,alignmentAxis:h.alignmentAxis};return o&&typeof x=="number"&&(p=o==="end"?x*-1:x),c?{x:p*u,y:m*d}:{x:m*d,y:p*u}}const Vrs=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 qrs(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}}}}},Hrs=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:b,y:v}=y;return{x:b,y:v}}},...c}=lC(s,t),d={x:n,y:r},u=await TZ(t,c),h=t6(cC(a)),m=cVe(h);let p=d[m],x=d[h];if(i){const y=m==="y"?"top":"left",b=m==="y"?"bottom":"right",v=p+u[y],N=p-u[b];p=IOe(v,p,N)}if(l){const y=h==="y"?"top":"left",b=h==="y"?"bottom":"right",v=x+u[y],N=x-u[b];x=IOe(v,x,N)}const g=o.fn({...t,[m]:p,[h]:x});return{...g,data:{x:g.x-n,y:g.y-r,enabled:{[m]:i,[h]:l}}}}}},Grs=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}=lC(s,t),u={x:n,y:r},h=t6(a),m=cVe(h);let p=u[m],x=u[h];const g=lC(o,t),y=typeof g=="number"?{mainAxis:g,crossAxis:0}:{mainAxis:0,crossAxis:0,...g};if(c){const N=m==="y"?"height":"width",C=i.reference[m]-i.floating[N]+y.mainAxis,A=i.reference[m]+i.reference[N]-y.mainAxis;pA&&(p=A)}if(d){var b,v;const N=m==="y"?"width":"height",C=["top","left"].includes(cC(a)),A=i.reference[h]-i.floating[N]+(C&&((b=l.offset)==null?void 0:b[h])||0)+(C?0:y.crossAxis),T=i.reference[h]+i.reference[N]+(C?0:((v=l.offset)==null?void 0:v[h])||0)-(C?y.crossAxis:0);xT&&(x=T)}return{[m]:p,[h]:x}}}},Wrs=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}=lC(s,t),u=await TZ(t,d),h=cC(a),m=xq(a),p=t6(a)==="y",{width:x,height:g}=i.floating;let y,b;h==="top"||h==="bottom"?(y=h,b=m===(await(l.isRTL==null?void 0:l.isRTL(o.floating))?"start":"end")?"left":"right"):(b=h,y=m==="end"?"top":"bottom");const v=g-u.top-u.bottom,N=x-u.left-u.right,C=JT(g-u[y],v),A=JT(x-u[b],N),T=!t.middlewareData.shift;let P=C,M=A;if((n=t.middlewareData.shift)!=null&&n.enabled.x&&(M=N),(r=t.middlewareData.shift)!=null&&r.enabled.y&&(P=v),T&&!m){const D=U_(u.left,0),B=U_(u.right,0),q=U_(u.top,0),W=U_(u.bottom,0);p?M=x-2*(D!==0||B!==0?D+B:U_(u.left,u.right)):P=g-2*(q!==0||W!==0?q+W:U_(u.top,u.bottom))}await c({...t,availableWidth:M,availableHeight:P});const I=await l.getDimensions(o.floating);return x!==I.width||g!==I.height?{reset:{rects:!0}}:{}}}};function q3e(){return typeof window<"u"}function gq(s){return gkt(s)?(s.nodeName||"").toLowerCase():"#document"}function rw(s){var t;return(s==null||(t=s.ownerDocument)==null?void 0:t.defaultView)||window}function T5(s){var t;return(t=(gkt(s)?s.ownerDocument:s.document)||window.document)==null?void 0:t.documentElement}function gkt(s){return q3e()?s instanceof Node||s instanceof rw(s).Node:!1}function VN(s){return q3e()?s instanceof Element||s instanceof rw(s).Element:!1}function v5(s){return q3e()?s instanceof HTMLElement||s instanceof rw(s).HTMLElement:!1}function grt(s){return!q3e()||typeof ShadowRoot>"u"?!1:s instanceof ShadowRoot||s instanceof rw(s).ShadowRoot}function QJ(s){const{overflow:t,overflowX:n,overflowY:r,display:a}=HN(s);return/auto|scroll|overlay|hidden|clip/.test(t+r+n)&&!["inline","contents"].includes(a)}function Krs(s){return["table","td","th"].includes(gq(s))}function V3e(s){return[":popover-open",":modal"].some(t=>{try{return s.matches(t)}catch{return!1}})}function hVe(s){const t=mVe(),n=VN(s)?HN(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 Yrs(s){let t=s6(s);for(;v5(t)&&!G$(t);){if(hVe(t))return t;if(V3e(t))return null;t=s6(t)}return null}function mVe(){return typeof CSS>"u"||!CSS.supports?!1:CSS.supports("-webkit-backdrop-filter","none")}function G$(s){return["html","body","#document"].includes(gq(s))}function HN(s){return rw(s).getComputedStyle(s)}function H3e(s){return VN(s)?{scrollLeft:s.scrollLeft,scrollTop:s.scrollTop}:{scrollLeft:s.scrollX,scrollTop:s.scrollY}}function s6(s){if(gq(s)==="html")return s;const t=s.assignedSlot||s.parentNode||grt(s)&&s.host||T5(s);return grt(t)?t.host:t}function ykt(s){const t=s6(s);return G$(t)?s.ownerDocument?s.ownerDocument.body:s.body:v5(t)&&QJ(t)?t:ykt(t)}function MZ(s,t,n){var r;t===void 0&&(t=[]),n===void 0&&(n=!0);const a=ykt(s),i=a===((r=s.ownerDocument)==null?void 0:r.body),l=rw(a);if(i){const o=ROe(l);return t.concat(l,l.visualViewport||[],QJ(a)?a:[],o&&n?MZ(o):[])}return t.concat(a,MZ(a,[],n))}function ROe(s){return s.parent&&Object.getPrototypeOf(s.parent)?s.frameElement:null}function vkt(s){const t=HN(s);let n=parseFloat(t.width)||0,r=parseFloat(t.height)||0;const a=v5(s),i=a?s.offsetWidth:n,l=a?s.offsetHeight:r,o=yke(n)!==i||yke(r)!==l;return o&&(n=i,r=l),{width:n,height:r,$:o}}function pVe(s){return VN(s)?s:s.contextElement}function Xz(s){const t=pVe(s);if(!v5(t))return e6(1);const n=t.getBoundingClientRect(),{width:r,height:a,$:i}=vkt(t);let l=(i?yke(n.width):n.width)/r,o=(i?yke(n.height):n.height)/a;return(!l||!Number.isFinite(l))&&(l=1),(!o||!Number.isFinite(o))&&(o=1),{x:l,y:o}}const Zrs=e6(0);function bkt(s){const t=rw(s);return!mVe()||!t.visualViewport?Zrs:{x:t.visualViewport.offsetLeft,y:t.visualViewport.offsetTop}}function Xrs(s,t,n){return t===void 0&&(t=!1),!n||t&&n!==rw(s)?!1:t}function nO(s,t,n,r){t===void 0&&(t=!1),n===void 0&&(n=!1);const a=s.getBoundingClientRect(),i=pVe(s);let l=e6(1);t&&(r?VN(r)&&(l=Xz(r)):l=Xz(s));const o=Xrs(i,n,r)?bkt(i):e6(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=rw(i),p=r&&VN(r)?rw(r):r;let x=m,g=ROe(x);for(;g&&r&&p!==x;){const y=Xz(g),b=g.getBoundingClientRect(),v=HN(g),N=b.left+(g.clientLeft+parseFloat(v.paddingLeft))*y.x,C=b.top+(g.clientTop+parseFloat(v.paddingTop))*y.y;c*=y.x,d*=y.y,u*=y.x,h*=y.y,c+=N,d+=C,x=rw(g),g=ROe(x)}}return bke({width:u,height:h,x:c,y:d})}function Qrs(s){let{elements:t,rect:n,offsetParent:r,strategy:a}=s;const i=a==="fixed",l=T5(r),o=t?V3e(t.floating):!1;if(r===l||o&&i)return n;let c={scrollLeft:0,scrollTop:0},d=e6(1);const u=e6(0),h=v5(r);if((h||!h&&!i)&&((gq(r)!=="body"||QJ(l))&&(c=H3e(r)),v5(r))){const m=nO(r);d=Xz(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 Jrs(s){return Array.from(s.getClientRects())}function OOe(s,t){const n=H3e(s).scrollLeft;return t?t.left+n:nO(T5(s)).left+n}function eas(s){const t=T5(s),n=H3e(s),r=s.ownerDocument.body,a=U_(t.scrollWidth,t.clientWidth,r.scrollWidth,r.clientWidth),i=U_(t.scrollHeight,t.clientHeight,r.scrollHeight,r.clientHeight);let l=-n.scrollLeft+OOe(s);const o=-n.scrollTop;return HN(r).direction==="rtl"&&(l+=U_(t.clientWidth,r.clientWidth)-a),{width:a,height:i,x:l,y:o}}function tas(s,t){const n=rw(s),r=T5(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=mVe();(!d||d&&t==="fixed")&&(o=a.offsetLeft,c=a.offsetTop)}return{width:i,height:l,x:o,y:c}}function sas(s,t){const n=nO(s,!0,t==="fixed"),r=n.top+s.clientTop,a=n.left+s.clientLeft,i=v5(s)?Xz(s):e6(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 yrt(s,t,n){let r;if(t==="viewport")r=tas(s,n);else if(t==="document")r=eas(T5(s));else if(VN(t))r=sas(t,n);else{const a=bkt(s);r={...t,x:t.x-a.x,y:t.y-a.y}}return bke(r)}function _kt(s,t){const n=s6(s);return n===t||!VN(n)||G$(n)?!1:HN(n).position==="fixed"||_kt(n,t)}function nas(s,t){const n=t.get(s);if(n)return n;let r=MZ(s,[],!1).filter(o=>VN(o)&&gq(o)!=="body"),a=null;const i=HN(s).position==="fixed";let l=i?s6(s):s;for(;VN(l)&&!G$(l);){const o=HN(l),c=hVe(l);!c&&o.position==="fixed"&&(a=null),(i?!c&&!a:!c&&o.position==="static"&&!!a&&["absolute","fixed"].includes(a.position)||QJ(l)&&!c&&_kt(s,l))?r=r.filter(u=>u!==l):a=o,l=s6(l)}return t.set(s,r),r}function ras(s){let{element:t,boundary:n,rootBoundary:r,strategy:a}=s;const l=[...n==="clippingAncestors"?V3e(t)?[]:nas(t,this._c):[].concat(n),r],o=l[0],c=l.reduce((d,u)=>{const h=yrt(t,u,a);return d.top=U_(h.top,d.top),d.right=JT(h.right,d.right),d.bottom=JT(h.bottom,d.bottom),d.left=U_(h.left,d.left),d},yrt(t,o,a));return{width:c.right-c.left,height:c.bottom-c.top,x:c.left,y:c.top}}function aas(s){const{width:t,height:n}=vkt(s);return{width:t,height:n}}function ias(s,t,n){const r=v5(t),a=T5(t),i=n==="fixed",l=nO(s,!0,i,t);let o={scrollLeft:0,scrollTop:0};const c=e6(0);if(r||!r&&!i)if((gq(t)!=="body"||QJ(a))&&(o=H3e(t)),r){const p=nO(t,!0,i,t);c.x=p.x+t.clientLeft,c.y=p.y+t.clientTop}else a&&(c.x=OOe(a));let d=0,u=0;if(a&&!r&&!i){const p=a.getBoundingClientRect();u=p.top+o.scrollTop,d=p.left+o.scrollLeft-OOe(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 vLe(s){return HN(s).position==="static"}function vrt(s,t){if(!v5(s)||HN(s).position==="fixed")return null;if(t)return t(s);let n=s.offsetParent;return T5(s)===n&&(n=n.ownerDocument.body),n}function wkt(s,t){const n=rw(s);if(V3e(s))return n;if(!v5(s)){let a=s6(s);for(;a&&!G$(a);){if(VN(a)&&!vLe(a))return a;a=s6(a)}return n}let r=vrt(s,t);for(;r&&Krs(r)&&vLe(r);)r=vrt(r,t);return r&&G$(r)&&vLe(r)&&!hVe(r)?n:r||Yrs(s)||n}const oas=async function(s){const t=this.getOffsetParent||wkt,n=this.getDimensions,r=await n(s.floating);return{reference:ias(s.reference,await t(s.floating),s.strategy),floating:{x:0,y:0,width:r.width,height:r.height}}};function las(s){return HN(s).direction==="rtl"}const cas={convertOffsetParentRelativeRectToViewportRelativeRect:Qrs,getDocumentElement:T5,getClippingRect:ras,getOffsetParent:wkt,getElementRects:oas,getClientRects:Jrs,getDimensions:aas,getScale:Xz,isElement:VN,isRTL:las};function das(s,t){let n=null,r;const a=T5(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=une(u),x=une(a.clientWidth-(d+h)),g=une(a.clientHeight-(u+m)),y=une(d),v={rootMargin:-p+"px "+-x+"px "+-g+"px "+-y+"px",threshold:U_(0,JT(1,c))||1};let N=!0;function C(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(C,{...v,root:a.ownerDocument})}catch{n=new IntersectionObserver(C,v)}n.observe(s)}return l(!0),i}function uas(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=pVe(s),u=a||i?[...d?MZ(d):[],...MZ(t)]:[];u.forEach(b=>{a&&b.addEventListener("scroll",n,{passive:!0}),i&&b.addEventListener("resize",n)});const h=d&&o?das(d,n):null;let m=-1,p=null;l&&(p=new ResizeObserver(b=>{let[v]=b;v&&v.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 x,g=c?nO(s):null;c&&y();function y(){const b=nO(s);g&&(b.x!==g.x||b.y!==g.y||b.width!==g.width||b.height!==g.height)&&n(),g=b,x=requestAnimationFrame(y)}return n(),()=>{var b;u.forEach(v=>{a&&v.removeEventListener("scroll",n),i&&v.removeEventListener("resize",n)}),h==null||h(),(b=p)==null||b.disconnect(),p=null,c&&cancelAnimationFrame(x)}}const has=Vrs,mas=Hrs,pas=$rs,fas=Wrs,xas=Urs,brt=Brs,gas=Grs,yas=(s,t,n)=>{const r=new Map,a={platform:cas,...n},i={...a.platform,_c:r};return zrs(s,t,{...a,platform:i})};var h2e=typeof document<"u"?j.useLayoutEffect:j.useEffect;function _ke(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(!_ke(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)&&!_ke(s[i],t[i]))return!1}return!0}return s!==s&&t!==t}function jkt(s){return typeof window>"u"?1:(s.ownerDocument.defaultView||window).devicePixelRatio||1}function _rt(s,t){const n=jkt(s);return Math.round(t*n)/n}function bLe(s){const t=j.useRef(s);return h2e(()=>{t.current=s}),t}function vas(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);_ke(m,r)||p(r);const[x,g]=j.useState(null),[y,b]=j.useState(null),v=j.useCallback(ce=>{ce!==T.current&&(T.current=ce,g(ce))},[]),N=j.useCallback(ce=>{ce!==P.current&&(P.current=ce,b(ce))},[]),C=i||x,A=l||y,T=j.useRef(null),P=j.useRef(null),M=j.useRef(u),I=c!=null,D=bLe(c),B=bLe(a),q=bLe(d),W=j.useCallback(()=>{if(!T.current||!P.current)return;const ce={placement:t,strategy:n,middleware:m};B.current&&(ce.platform=B.current),yas(T.current,P.current,ce).then(ue=>{const ne={...ue,isPositioned:q.current!==!1};V.current&&!_ke(M.current,ne)&&(M.current=ne,n1.flushSync(()=>{h(ne)}))})},[m,t,n,B,q]);h2e(()=>{d===!1&&M.current.isPositioned&&(M.current.isPositioned=!1,h(ce=>({...ce,isPositioned:!1})))},[d]);const V=j.useRef(!1);h2e(()=>(V.current=!0,()=>{V.current=!1}),[]),h2e(()=>{if(C&&(T.current=C),A&&(P.current=A),C&&A){if(D.current)return D.current(C,A,W);W()}},[C,A,W,D,I]);const K=j.useMemo(()=>({reference:T,floating:P,setReference:v,setFloating:N}),[v,N]),Q=j.useMemo(()=>({reference:C,floating:A}),[C,A]),J=j.useMemo(()=>{const ce={position:n,left:0,top:0};if(!Q.floating)return ce;const ue=_rt(Q.floating,u.x),ne=_rt(Q.floating,u.y);return o?{...ce,transform:"translate("+ue+"px, "+ne+"px)",...jkt(Q.floating)>=1.5&&{willChange:"transform"}}:{position:n,left:ue,top:ne}},[n,o,Q.floating,u.x,u.y]);return j.useMemo(()=>({...u,update:W,refs:K,elements:Q,floatingStyles:J}),[u,W,K,Q,J])}const bas=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?brt({element:r.current,padding:a}).fn(n):{}:r?brt({element:r,padding:a}).fn(n):{}}}},_as=(s,t)=>({...has(s),options:[s,t]}),was=(s,t)=>({...mas(s),options:[s,t]}),jas=(s,t)=>({...gas(s),options:[s,t]}),Nas=(s,t)=>({...pas(s),options:[s,t]}),kas=(s,t)=>({...fas(s),options:[s,t]}),Sas=(s,t)=>({...xas(s),options:[s,t]}),Cas=(s,t)=>({...bas(s),options:[s,t]});var Aas="Arrow",Nkt=j.forwardRef((s,t)=>{const{children:n,width:r=10,height:a=5,...i}=s;return e.jsx(Ka.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"})})});Nkt.displayName=Aas;var Eas=Nkt;function JJ(s){const[t,n]=j.useState(void 0);return Sf(()=>{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 fVe="Popper",[kkt,M5]=ip(fVe),[Tas,Skt]=kkt(fVe),Ckt=s=>{const{__scopePopper:t,children:n}=s,[r,a]=j.useState(null);return e.jsx(Tas,{scope:t,anchor:r,onAnchorChange:a,children:n})};Ckt.displayName=fVe;var Akt="PopperAnchor",Ekt=j.forwardRef((s,t)=>{const{__scopePopper:n,virtualRef:r,...a}=s,i=Skt(Akt,n),l=j.useRef(null),o=Po(t,l);return j.useEffect(()=>{i.onAnchorChange((r==null?void 0:r.current)||l.current)}),r?null:e.jsx(Ka.div,{...a,ref:o})});Ekt.displayName=Akt;var xVe="PopperContent",[Mas,Las]=kkt(xVe),Tkt=j.forwardRef((s,t)=>{var je,Ee,Me,De,ze,ke;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:x,...g}=s,y=Skt(xVe,n),[b,v]=j.useState(null),N=Po(t,Xe=>v(Xe)),[C,A]=j.useState(null),T=JJ(C),P=(T==null?void 0:T.width)??0,M=(T==null?void 0:T.height)??0,I=r+(i!=="center"?"-"+i:""),D=typeof u=="number"?u:{top:0,right:0,bottom:0,left:0,...u},B=Array.isArray(d)?d:[d],q=B.length>0,W={padding:D,boundary:B.filter(Ias),altBoundary:q},{refs:V,floatingStyles:K,placement:Q,isPositioned:J,middlewareData:ce}=vas({strategy:"fixed",placement:I,whileElementsMounted:(...Xe)=>uas(...Xe,{animationFrame:p==="always"}),elements:{reference:y.anchor},middleware:[_as({mainAxis:a+M,alignmentAxis:l}),c&&was({mainAxis:!0,crossAxis:!1,limiter:h==="partial"?jas():void 0,...W}),c&&Nas({...W}),kas({...W,apply:({elements:Xe,rects:Se,availableWidth:Re,availableHeight:Ae})=>{const{width:Be,height:qe}=Se.reference,Ke=Xe.floating.style;Ke.setProperty("--radix-popper-available-width",`${Re}px`),Ke.setProperty("--radix-popper-available-height",`${Ae}px`),Ke.setProperty("--radix-popper-anchor-width",`${Be}px`),Ke.setProperty("--radix-popper-anchor-height",`${qe}px`)}}),C&&Cas({element:C,padding:o}),Das({arrowWidth:P,arrowHeight:M}),m&&Sas({strategy:"referenceHidden",...W})]}),[ue,ne]=Pkt(Q),ee=bf(x);Sf(()=>{J&&(ee==null||ee())},[J,ee]);const le=(je=ce.arrow)==null?void 0:je.x,he=(Ee=ce.arrow)==null?void 0:Ee.y,ve=((Me=ce.arrow)==null?void 0:Me.centerOffset)!==0,[ge,fe]=j.useState();return Sf(()=>{b&&fe(window.getComputedStyle(b).zIndex)},[b]),e.jsx("div",{ref:V.setFloating,"data-radix-popper-content-wrapper":"",style:{...K,transform:J?K.transform:"translate(0, -200%)",minWidth:"max-content",zIndex:ge,"--radix-popper-transform-origin":[(De=ce.transformOrigin)==null?void 0:De.x,(ze=ce.transformOrigin)==null?void 0:ze.y].join(" "),...((ke=ce.hide)==null?void 0:ke.referenceHidden)&&{visibility:"hidden",pointerEvents:"none"}},dir:s.dir,children:e.jsx(Mas,{scope:n,placedSide:ue,onArrowChange:A,arrowX:le,arrowY:he,shouldHideArrow:ve,children:e.jsx(Ka.div,{"data-side":ue,"data-align":ne,...g,ref:N,style:{...g.style,animation:J?void 0:"none"}})})})});Tkt.displayName=xVe;var Mkt="PopperArrow",Pas={top:"bottom",right:"left",bottom:"top",left:"right"},Lkt=j.forwardRef(function(t,n){const{__scopePopper:r,...a}=t,i=Las(Mkt,r),l=Pas[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(Eas,{...a,ref:n,style:{...a.style,display:"block"}})})});Lkt.displayName=Mkt;function Ias(s){return s!==null}var Das=s=>({name:"transformOrigin",options:s,fn(t){var y,b,v;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]=Pkt(n),h={start:"0%",center:"50%",end:"100%"}[u],m=(((b=a.arrow)==null?void 0:b.x)??0)+o/2,p=(((v=a.arrow)==null?void 0:v.y)??0)+c/2;let x="",g="";return d==="bottom"?(x=l?h:`${m}px`,g=`${-c}px`):d==="top"?(x=l?h:`${m}px`,g=`${r.floating.height+c}px`):d==="right"?(x=`${-c}px`,g=l?h:`${p}px`):d==="left"&&(x=`${r.floating.width+c}px`,g=l?h:`${p}px`),{data:{x,y:g}}}});function Pkt(s){const[t,n="center"]=s.split("-");return[t,n]}var eee=Ckt,yq=Ekt,tee=Tkt,see=Lkt,[G3e,pXn]=ip("Tooltip",[M5]),W3e=M5(),Ikt="TooltipProvider",Ras=700,FOe="tooltip.open",[Oas,gVe]=G3e(Ikt),Dkt=s=>{const{__scopeTooltip:t,delayDuration:n=Ras,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(Oas,{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})};Dkt.displayName=Ikt;var LZ="Tooltip",[Fas,K3e]=G3e(LZ),Rkt=s=>{const{__scopeTooltip:t,children:n,open:r,defaultOpen:a,onOpenChange:i,disableHoverableContent:l,delayDuration:o}=s,c=gVe(LZ,s.__scopeTooltip),d=W3e(t),[u,h]=j.useState(null),m=Fx(),p=j.useRef(0),x=l??c.disableHoverableContent,g=o??c.delayDuration,y=j.useRef(!1),[b,v]=Ux({prop:r,defaultProp:a??!1,onChange:P=>{P?(c.onOpen(),document.dispatchEvent(new CustomEvent(FOe))):c.onClose(),i==null||i(P)},caller:LZ}),N=j.useMemo(()=>b?y.current?"delayed-open":"instant-open":"closed",[b]),C=j.useCallback(()=>{window.clearTimeout(p.current),p.current=0,y.current=!1,v(!0)},[v]),A=j.useCallback(()=>{window.clearTimeout(p.current),p.current=0,v(!1)},[v]),T=j.useCallback(()=>{window.clearTimeout(p.current),p.current=window.setTimeout(()=>{y.current=!0,v(!0),p.current=0},g)},[g,v]);return j.useEffect(()=>()=>{p.current&&(window.clearTimeout(p.current),p.current=0)},[]),e.jsx(eee,{...d,children:e.jsx(Fas,{scope:t,contentId:m,open:b,stateAttribute:N,trigger:u,onTriggerChange:h,onTriggerEnter:j.useCallback(()=>{c.isOpenDelayedRef.current?T():C()},[c.isOpenDelayedRef,T,C]),onTriggerLeave:j.useCallback(()=>{x?A():(window.clearTimeout(p.current),p.current=0)},[A,x]),onOpen:C,onClose:A,disableHoverableContent:x,children:n})})};Rkt.displayName=LZ;var zOe="TooltipTrigger",Okt=j.forwardRef((s,t)=>{const{__scopeTooltip:n,...r}=s,a=K3e(zOe,n),i=gVe(zOe,n),l=W3e(n),o=j.useRef(null),c=Po(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(yq,{asChild:!0,...l,children:e.jsx(Ka.button,{"aria-describedby":a.open?a.contentId:void 0,"data-state":a.stateAttribute,...r,ref:c,onPointerMove:xa(s.onPointerMove,m=>{m.pointerType!=="touch"&&!u.current&&!i.isPointerInTransitRef.current&&(a.onTriggerEnter(),u.current=!0)}),onPointerLeave:xa(s.onPointerLeave,()=>{a.onTriggerLeave(),u.current=!1}),onPointerDown:xa(s.onPointerDown,()=>{a.open&&a.onClose(),d.current=!0,document.addEventListener("pointerup",h,{once:!0})}),onFocus:xa(s.onFocus,()=>{d.current||a.onOpen()}),onBlur:xa(s.onBlur,a.onClose),onClick:xa(s.onClick,a.onClose)})})});Okt.displayName=zOe;var zas="TooltipPortal",[fXn,Bas]=G3e(zas,{forceMount:void 0}),W$="TooltipContent",Fkt=j.forwardRef((s,t)=>{const n=Bas(W$,s.__scopeTooltip),{forceMount:r=n.forceMount,side:a="top",...i}=s,l=K3e(W$,s.__scopeTooltip);return e.jsx(dx,{present:r||l.open,children:l.disableHoverableContent?e.jsx(zkt,{side:a,...i,ref:t}):e.jsx($as,{side:a,...i,ref:t})})}),$as=j.forwardRef((s,t)=>{const n=K3e(W$,s.__scopeTooltip),r=gVe(W$,s.__scopeTooltip),a=j.useRef(null),i=Po(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((x,g)=>{const y=x.currentTarget,b={x:x.clientX,y:x.clientY},v=Gas(b,y.getBoundingClientRect()),N=Was(b,v),C=Kas(g.getBoundingClientRect()),A=Zas([...N,...C]);o(A),h(!0)},[h]);return j.useEffect(()=>()=>m(),[m]),j.useEffect(()=>{if(c&&u){const x=y=>p(y,u),g=y=>p(y,c);return c.addEventListener("pointerleave",x),u.addEventListener("pointerleave",g),()=>{c.removeEventListener("pointerleave",x),u.removeEventListener("pointerleave",g)}}},[c,u,p,m]),j.useEffect(()=>{if(l){const x=g=>{const y=g.target,b={x:g.clientX,y:g.clientY},v=(c==null?void 0:c.contains(y))||(u==null?void 0:u.contains(y)),N=!Yas(b,l);v?m():N&&(m(),d())};return document.addEventListener("pointermove",x),()=>document.removeEventListener("pointermove",x)}},[c,u,l,d,m]),e.jsx(zkt,{...s,ref:i})}),[Uas,qas]=G3e(LZ,{isInside:!1}),Vas=$2t("TooltipContent"),zkt=j.forwardRef((s,t)=>{const{__scopeTooltip:n,children:r,"aria-label":a,onEscapeKeyDown:i,onPointerDownOutside:l,...o}=s,c=K3e(W$,n),d=W3e(n),{onClose:u}=c;return j.useEffect(()=>(document.addEventListener(FOe,u),()=>document.removeEventListener(FOe,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(j6,{asChild:!0,disableOutsidePointerEvents:!1,onEscapeKeyDown:i,onPointerDownOutside:l,onFocusOutside:h=>h.preventDefault(),onDismiss:u,children:e.jsxs(tee,{"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(Vas,{children:r}),e.jsx(Uas,{scope:n,isInside:!0,children:e.jsx(Tts,{id:c.contentId,role:"tooltip",children:a||r})})]})})});Fkt.displayName=W$;var Bkt="TooltipArrow",Has=j.forwardRef((s,t)=>{const{__scopeTooltip:n,...r}=s,a=W3e(n);return qas(Bkt,n).isInside?null:e.jsx(see,{...a,...r,ref:t})});Has.displayName=Bkt;function Gas(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 Was(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 Kas(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 Yas(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 Zas(s){const t=s.slice();return t.sort((n,r)=>n.xr.x?1:n.yr.y?1:0),Xas(t)}function Xas(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 Qas=Dkt,Jas=Rkt,eis=Okt,$kt=Fkt;const JN=Qas,Mx=Jas,Lx=eis,tx=j.forwardRef(({className:s,sideOffset:t=4,...n},r)=>e.jsx($kt,{ref:r,sideOffset:t,className:Tt("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}));tx.displayName=$kt.displayName;var vq=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(){}},rO=typeof window>"u"||"Deno"in globalThis;function Qv(){}function tis(s,t){return typeof s=="function"?s(t):s}function BOe(s){return typeof s=="number"&&s>=0&&s!==1/0}function Ukt(s,t){return Math.max(s+(t||0)-Date.now(),0)}function DT(s,t){return typeof s=="function"?s(t):s}function bj(s,t){return typeof s=="function"?s(t):s}function wrt(s,t){const{type:n="all",exact:r,fetchStatus:a,predicate:i,queryKey:l,stale:o}=s;if(l){if(r){if(t.queryHash!==yVe(l,t.options))return!1}else if(!PZ(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 jrt(s,t){const{exact:n,status:r,predicate:a,mutationKey:i}=s;if(i){if(!t.options.mutationKey)return!1;if(n){if(aO(t.options.mutationKey)!==aO(i))return!1}else if(!PZ(t.options.mutationKey,i))return!1}return!(r&&t.state.status!==r||a&&!a(t))}function yVe(s,t){return((t==null?void 0:t.queryKeyHashFn)||aO)(s)}function aO(s){return JSON.stringify(s,(t,n)=>$Oe(n)?Object.keys(n).sort().reduce((r,a)=>(r[a]=n[a],r),{}):n)}function PZ(s,t){return s===t?!0:typeof s!=typeof t?!1:s&&t&&typeof s=="object"&&typeof t=="object"?Object.keys(t).every(n=>PZ(s[n],t[n])):!1}function qkt(s,t){if(s===t)return s;const n=Nrt(s)&&Nrt(t);if(n||$Oe(s)&&$Oe(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 UOe(s,t,n){return typeof n.structuralSharing=="function"?n.structuralSharing(s,t):n.structuralSharing!==!1?qkt(s,t):t}function nis(s,t,n=0){const r=[...s,t];return n&&r.length>n?r.slice(1):r}function ris(s,t,n=0){const r=[t,...s];return n&&r.length>n?r.slice(0,-1):r}var vVe=Symbol();function Vkt(s,t){return!s.queryFn&&(t!=null&&t.initialPromise)?()=>t.initialPromise:!s.queryFn||s.queryFn===vVe?()=>Promise.reject(new Error(`Missing queryFn: '${s.queryHash}'`)):s.queryFn}function Hkt(s,t){return typeof s=="function"?s(...t):!!s}var X8,oE,AB,mwt,ais=(mwt=class extends vq{constructor(){super();rs(this,X8);rs(this,oE);rs(this,AB);$t(this,AB,t=>{if(!rO&&window.addEventListener){const n=()=>t();return window.addEventListener("visibilitychange",n,!1),()=>{window.removeEventListener("visibilitychange",n)}}})}onSubscribe(){pe(this,oE)||this.setEventListener(pe(this,AB))}onUnsubscribe(){var t;this.hasListeners()||((t=pe(this,oE))==null||t.call(this),$t(this,oE,void 0))}setEventListener(t){var n;$t(this,AB,t),(n=pe(this,oE))==null||n.call(this),$t(this,oE,t(r=>{typeof r=="boolean"?this.setFocused(r):this.onFocus()}))}setFocused(t){pe(this,X8)!==t&&($t(this,X8,t),this.onFocus())}onFocus(){const t=this.isFocused();this.listeners.forEach(n=>{n(t)})}isFocused(){var t;return typeof pe(this,X8)=="boolean"?pe(this,X8):((t=globalThis.document)==null?void 0:t.visibilityState)!=="hidden"}},X8=new WeakMap,oE=new WeakMap,AB=new WeakMap,mwt),bVe=new ais,EB,lE,TB,pwt,iis=(pwt=class extends vq{constructor(){super();rs(this,EB,!0);rs(this,lE);rs(this,TB);$t(this,TB,t=>{if(!rO&&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(){pe(this,lE)||this.setEventListener(pe(this,TB))}onUnsubscribe(){var t;this.hasListeners()||((t=pe(this,lE))==null||t.call(this),$t(this,lE,void 0))}setEventListener(t){var n;$t(this,TB,t),(n=pe(this,lE))==null||n.call(this),$t(this,lE,t(this.setOnline.bind(this)))}setOnline(t){pe(this,EB)!==t&&($t(this,EB,t),this.listeners.forEach(r=>{r(t)}))}isOnline(){return pe(this,EB)}},EB=new WeakMap,lE=new WeakMap,TB=new WeakMap,pwt),jke=new iis;function qOe(){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 ois(s){return Math.min(1e3*2**s,3e4)}function Gkt(s){return(s??"online")==="online"?jke.isOnline():!0}var Wkt=class extends Error{constructor(s){super("CancelledError"),this.revert=s==null?void 0:s.revert,this.silent=s==null?void 0:s.silent}};function _Le(s){return s instanceof Wkt}function Kkt(s){let t=!1,n=0,r=!1,a;const i=qOe(),l=g=>{var y;r||(m(new Wkt(g)),(y=s.abort)==null||y.call(s))},o=()=>{t=!0},c=()=>{t=!1},d=()=>bVe.isFocused()&&(s.networkMode==="always"||jke.isOnline())&&s.canRun(),u=()=>Gkt(s.networkMode)&&s.canRun(),h=g=>{var y;r||(r=!0,(y=s.onSuccess)==null||y.call(s,g),a==null||a(),i.resolve(g))},m=g=>{var y;r||(r=!0,(y=s.onError)==null||y.call(s,g),a==null||a(),i.reject(g))},p=()=>new Promise(g=>{var y;a=b=>{(r||d())&&g(b)},(y=s.onPause)==null||y.call(s)}).then(()=>{var g;a=void 0,r||(g=s.onContinue)==null||g.call(s)}),x=()=>{if(r)return;let g;const y=n===0?s.initialPromise:void 0;try{g=y??s.fn()}catch(b){g=Promise.reject(b)}Promise.resolve(g).then(h).catch(b=>{var T;if(r)return;const v=s.retry??(rO?0:3),N=s.retryDelay??ois,C=typeof N=="function"?N(n,b):N,A=v===!0||typeof v=="number"&&nd()?void 0:p()).then(()=>{t?m(b):x()})})};return{promise:i,cancel:l,continue:()=>(a==null||a(),i),cancelRetry:o,continueRetry:c,canStart:u,start:()=>(u()?x():p().then(x),i)}}var lis=s=>setTimeout(s,0);function cis(){let s=[],t=0,n=o=>{o()},r=o=>{o()},a=lis;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 hg=cis(),Q8,fwt,Ykt=(fwt=class{constructor(){rs(this,Q8)}destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),BOe(this.gcTime)&&$t(this,Q8,setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(s){this.gcTime=Math.max(this.gcTime||0,s??(rO?1/0:5*60*1e3))}clearGcTimeout(){pe(this,Q8)&&(clearTimeout(pe(this,Q8)),$t(this,Q8,void 0))}},Q8=new WeakMap,fwt),MB,J8,pj,eD,Yy,wQ,tD,J2,I4,xwt,dis=(xwt=class extends Ykt{constructor(t){super();rs(this,J2);rs(this,MB);rs(this,J8);rs(this,pj);rs(this,eD);rs(this,Yy);rs(this,wQ);rs(this,tD);$t(this,tD,!1),$t(this,wQ,t.defaultOptions),this.setOptions(t.options),this.observers=[],$t(this,eD,t.client),$t(this,pj,pe(this,eD).getQueryCache()),this.queryKey=t.queryKey,this.queryHash=t.queryHash,$t(this,MB,uis(this.options)),this.state=t.state??pe(this,MB),this.scheduleGc()}get meta(){return this.options.meta}get promise(){var t;return(t=pe(this,Yy))==null?void 0:t.promise}setOptions(t){this.options={...pe(this,wQ),...t},this.updateGcTime(this.options.gcTime)}optionalRemove(){!this.observers.length&&this.state.fetchStatus==="idle"&&pe(this,pj).remove(this)}setData(t,n){const r=UOe(this.state.data,t,this.options);return Kt(this,J2,I4).call(this,{data:r,type:"success",dataUpdatedAt:n==null?void 0:n.updatedAt,manual:n==null?void 0:n.manual}),r}setState(t,n){Kt(this,J2,I4).call(this,{type:"setState",state:t,setStateOptions:n})}cancel(t){var r,a;const n=(r=pe(this,Yy))==null?void 0:r.promise;return(a=pe(this,Yy))==null||a.cancel(t),n?n.then(Qv).catch(Qv):Promise.resolve()}destroy(){super.destroy(),this.cancel({silent:!0})}reset(){this.destroy(),this.setState(pe(this,MB))}isActive(){return this.observers.some(t=>bj(t.options.enabled,this)!==!1)}isDisabled(){return this.getObserversCount()>0?!this.isActive():this.options.queryFn===vVe||this.state.dataUpdateCount+this.state.errorUpdateCount===0}isStatic(){return this.getObserversCount()>0?this.observers.some(t=>DT(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:!Ukt(this.state.dataUpdatedAt,t)}onFocus(){var n;const t=this.observers.find(r=>r.shouldFetchOnWindowFocus());t==null||t.refetch({cancelRefetch:!1}),(n=pe(this,Yy))==null||n.continue()}onOnline(){var n;const t=this.observers.find(r=>r.shouldFetchOnReconnect());t==null||t.refetch({cancelRefetch:!1}),(n=pe(this,Yy))==null||n.continue()}addObserver(t){this.observers.includes(t)||(this.observers.push(t),this.clearGcTimeout(),pe(this,pj).notify({type:"observerAdded",query:this,observer:t}))}removeObserver(t){this.observers.includes(t)&&(this.observers=this.observers.filter(n=>n!==t),this.observers.length||(pe(this,Yy)&&(pe(this,tD)?pe(this,Yy).cancel({revert:!0}):pe(this,Yy).cancelRetry()),this.scheduleGc()),pe(this,pj).notify({type:"observerRemoved",query:this,observer:t}))}getObserversCount(){return this.observers.length}invalidate(){this.state.isInvalidated||Kt(this,J2,I4).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(pe(this,Yy))return pe(this,Yy).continueRetry(),pe(this,Yy).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,tD,!0),r.signal)})},i=()=>{const m=Vkt(this.options,n),x=(()=>{const g={client:pe(this,eD),queryKey:this.queryKey,meta:this.meta};return a(g),g})();return $t(this,tD,!1),this.options.persister?this.options.persister(m,x,this):m(x)},o=(()=>{const m={fetchOptions:n,options:this.options,queryKey:this.queryKey,client:pe(this,eD),state:this.state,fetchFn:i};return a(m),m})();(d=this.options.behavior)==null||d.onFetch(o,this),$t(this,J8,this.state),(this.state.fetchStatus==="idle"||this.state.fetchMeta!==((u=o.fetchOptions)==null?void 0:u.meta))&&Kt(this,J2,I4).call(this,{type:"fetch",meta:(h=o.fetchOptions)==null?void 0:h.meta});const c=m=>{var p,x,g,y;_Le(m)&&m.silent||Kt(this,J2,I4).call(this,{type:"error",error:m}),_Le(m)||((x=(p=pe(this,pj).config).onError)==null||x.call(p,m,this),(y=(g=pe(this,pj).config).onSettled)==null||y.call(g,this.state.data,m,this)),this.scheduleGc()};return $t(this,Yy,Kkt({initialPromise:n==null?void 0:n.initialPromise,fn:o.fetchFn,abort:r.abort.bind(r),onSuccess:m=>{var p,x,g,y;if(m===void 0){c(new Error(`${this.queryHash} data is undefined`));return}try{this.setData(m)}catch(b){c(b);return}(x=(p=pe(this,pj).config).onSuccess)==null||x.call(p,m,this),(y=(g=pe(this,pj).config).onSettled)==null||y.call(g,m,this.state.error,this),this.scheduleGc()},onError:c,onFail:(m,p)=>{Kt(this,J2,I4).call(this,{type:"failed",failureCount:m,error:p})},onPause:()=>{Kt(this,J2,I4).call(this,{type:"pause"})},onContinue:()=>{Kt(this,J2,I4).call(this,{type:"continue"})},retry:o.options.retry,retryDelay:o.options.retryDelay,networkMode:o.options.networkMode,canRun:()=>!0})),pe(this,Yy).start()}},MB=new WeakMap,J8=new WeakMap,pj=new WeakMap,eD=new WeakMap,Yy=new WeakMap,wQ=new WeakMap,tD=new WeakMap,J2=new WeakSet,I4=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,...Zkt(r.data,this.options),fetchMeta:t.meta??null};case"success":return $t(this,J8,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 _Le(a)&&a.revert&&pe(this,J8)?{...pe(this,J8),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),hg.batch(()=>{this.observers.forEach(r=>{r.onQueryUpdate()}),pe(this,pj).notify({query:this,type:"updated",action:t})})},xwt);function Zkt(s,t){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:Gkt(t.networkMode)?"fetching":"paused",...s===void 0&&{error:null,status:"pending"}}}function uis(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 lS,gwt,his=(gwt=class extends vq{constructor(t={}){super();rs(this,lS);this.config=t,$t(this,lS,new Map)}build(t,n,r){const a=n.queryKey,i=n.queryHash??yVe(a,n);let l=this.get(i);return l||(l=new dis({client:t,queryKey:a,queryHash:i,options:t.defaultQueryOptions(n),state:r,defaultOptions:t.getQueryDefaults(a)}),this.add(l)),l}add(t){pe(this,lS).has(t.queryHash)||(pe(this,lS).set(t.queryHash,t),this.notify({type:"added",query:t}))}remove(t){const n=pe(this,lS).get(t.queryHash);n&&(t.destroy(),n===t&&pe(this,lS).delete(t.queryHash),this.notify({type:"removed",query:t}))}clear(){hg.batch(()=>{this.getAll().forEach(t=>{this.remove(t)})})}get(t){return pe(this,lS).get(t)}getAll(){return[...pe(this,lS).values()]}find(t){const n={exact:!0,...t};return this.getAll().find(r=>wrt(n,r))}findAll(t={}){const n=this.getAll();return Object.keys(t).length>0?n.filter(r=>wrt(t,r)):n}notify(t){hg.batch(()=>{this.listeners.forEach(n=>{n(t)})})}onFocus(){hg.batch(()=>{this.getAll().forEach(t=>{t.onFocus()})})}onOnline(){hg.batch(()=>{this.getAll().forEach(t=>{t.onOnline()})})}},lS=new WeakMap,gwt),cS,Yv,sD,dS,bA,ywt,mis=(ywt=class extends Ykt{constructor(t){super();rs(this,dS);rs(this,cS);rs(this,Yv);rs(this,sD);this.mutationId=t.mutationId,$t(this,Yv,t.mutationCache),$t(this,cS,[]),this.state=t.state||Xkt(),this.setOptions(t.options),this.scheduleGc()}setOptions(t){this.options=t,this.updateGcTime(this.options.gcTime)}get meta(){return this.options.meta}addObserver(t){pe(this,cS).includes(t)||(pe(this,cS).push(t),this.clearGcTimeout(),pe(this,Yv).notify({type:"observerAdded",mutation:this,observer:t}))}removeObserver(t){$t(this,cS,pe(this,cS).filter(n=>n!==t)),this.scheduleGc(),pe(this,Yv).notify({type:"observerRemoved",mutation:this,observer:t})}optionalRemove(){pe(this,cS).length||(this.state.status==="pending"?this.scheduleGc():pe(this,Yv).remove(this))}continue(){var t;return((t=pe(this,sD))==null?void 0:t.continue())??this.execute(this.state.variables)}async execute(t){var i,l,o,c,d,u,h,m,p,x,g,y,b,v,N,C,A,T,P,M;const n=()=>{Kt(this,dS,bA).call(this,{type:"continue"})};$t(this,sD,Kkt({fn:()=>this.options.mutationFn?this.options.mutationFn(t):Promise.reject(new Error("No mutationFn found")),onFail:(I,D)=>{Kt(this,dS,bA).call(this,{type:"failed",failureCount:I,error:D})},onPause:()=>{Kt(this,dS,bA).call(this,{type:"pause"})},onContinue:n,retry:this.options.retry??0,retryDelay:this.options.retryDelay,networkMode:this.options.networkMode,canRun:()=>pe(this,Yv).canRun(this)}));const r=this.state.status==="pending",a=!pe(this,sD).canStart();try{if(r)n();else{Kt(this,dS,bA).call(this,{type:"pending",variables:t,isPaused:a}),await((l=(i=pe(this,Yv).config).onMutate)==null?void 0:l.call(i,t,this));const D=await((c=(o=this.options).onMutate)==null?void 0:c.call(o,t));D!==this.state.context&&Kt(this,dS,bA).call(this,{type:"pending",context:D,variables:t,isPaused:a})}const I=await pe(this,sD).start();return await((u=(d=pe(this,Yv).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((x=(p=pe(this,Yv).config).onSettled)==null?void 0:x.call(p,I,null,this.state.variables,this.state.context,this)),await((y=(g=this.options).onSettled)==null?void 0:y.call(g,I,null,t,this.state.context)),Kt(this,dS,bA).call(this,{type:"success",data:I}),I}catch(I){try{throw await((v=(b=pe(this,Yv).config).onError)==null?void 0:v.call(b,I,t,this.state.context,this)),await((C=(N=this.options).onError)==null?void 0:C.call(N,I,t,this.state.context)),await((T=(A=pe(this,Yv).config).onSettled)==null?void 0:T.call(A,void 0,I,this.state.variables,this.state.context,this)),await((M=(P=this.options).onSettled)==null?void 0:M.call(P,void 0,I,t,this.state.context)),I}finally{Kt(this,dS,bA).call(this,{type:"error",error:I})}}finally{pe(this,Yv).runNext(this)}}},cS=new WeakMap,Yv=new WeakMap,sD=new WeakMap,dS=new WeakSet,bA=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),hg.batch(()=>{pe(this,cS).forEach(r=>{r.onMutationUpdate(t)}),pe(this,Yv).notify({mutation:this,type:"updated",action:t})})},ywt);function Xkt(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:"idle",variables:void 0,submittedAt:0}}var t3,eN,jQ,vwt,pis=(vwt=class extends vq{constructor(t={}){super();rs(this,t3);rs(this,eN);rs(this,jQ);this.config=t,$t(this,t3,new Set),$t(this,eN,new Map),$t(this,jQ,0)}build(t,n,r){const a=new mis({mutationCache:this,mutationId:++Xg(this,jQ)._,options:t.defaultMutationOptions(n),state:r});return this.add(a),a}add(t){pe(this,t3).add(t);const n=hne(t);if(typeof n=="string"){const r=pe(this,eN).get(n);r?r.push(t):pe(this,eN).set(n,[t])}this.notify({type:"added",mutation:t})}remove(t){if(pe(this,t3).delete(t)){const n=hne(t);if(typeof n=="string"){const r=pe(this,eN).get(n);if(r)if(r.length>1){const a=r.indexOf(t);a!==-1&&r.splice(a,1)}else r[0]===t&&pe(this,eN).delete(n)}}this.notify({type:"removed",mutation:t})}canRun(t){const n=hne(t);if(typeof n=="string"){const r=pe(this,eN).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=hne(t);if(typeof n=="string"){const a=(r=pe(this,eN).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(){hg.batch(()=>{pe(this,t3).forEach(t=>{this.notify({type:"removed",mutation:t})}),pe(this,t3).clear(),pe(this,eN).clear()})}getAll(){return Array.from(pe(this,t3))}find(t){const n={exact:!0,...t};return this.getAll().find(r=>jrt(n,r))}findAll(t={}){return this.getAll().filter(n=>jrt(t,n))}notify(t){hg.batch(()=>{this.listeners.forEach(n=>{n(t)})})}resumePausedMutations(){const t=this.getAll().filter(n=>n.state.isPaused);return hg.batch(()=>Promise.all(t.map(n=>n.continue().catch(Qv))))}},t3=new WeakMap,eN=new WeakMap,jQ=new WeakMap,vwt);function hne(s){var t;return(t=s.options.scope)==null?void 0:t.id}function Nke(s){return{onFetch:(t,n)=>{var u,h,m,p,x;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=((x=t.state.data)==null?void 0:x.pageParams)||[];let o={pages:[],pageParams:[]},c=0;const d=async()=>{let g=!1;const y=N=>{Object.defineProperty(N,"signal",{enumerable:!0,get:()=>(t.signal.aborted?g=!0:t.signal.addEventListener("abort",()=>{g=!0}),t.signal)})},b=Vkt(t.options,t.fetchOptions),v=async(N,C,A)=>{if(g)return Promise.reject();if(C==null&&N.pages.length)return Promise.resolve(N);const P=(()=>{const B={client:t.client,queryKey:t.queryKey,pageParam:C,direction:A?"backward":"forward",meta:t.options.meta};return y(B),B})(),M=await b(P),{maxPages:I}=t.options,D=A?ris:nis;return{pages:D(N.pages,M,I),pageParams:D(N.pageParams,C,I)}};if(a&&i.length){const N=a==="backward",C=N?Qkt:VOe,A={pages:i,pageParams:l},T=C(r,A);o=await v(A,T,N)}else{const N=s??i.length;do{const C=c===0?l[0]??r.initialPageParam:VOe(r,o);if(c>0&&C==null)break;o=await v(o,C),c++}while(c{var g,y;return(y=(g=t.options).persister)==null?void 0:y.call(g,d,{client:t.client,queryKey:t.queryKey,meta:t.options.meta,signal:t.signal},n)}:t.fetchFn=d}}}function VOe(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 Qkt(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 fis(s,t){return t?VOe(s,t)!=null:!1}function xis(s,t){return!t||!s.getPreviousPageParam?!1:Qkt(s,t)!=null}var uf,cE,dE,LB,PB,uE,IB,DB,bwt,gis=(bwt=class{constructor(s={}){rs(this,uf);rs(this,cE);rs(this,dE);rs(this,LB);rs(this,PB);rs(this,uE);rs(this,IB);rs(this,DB);$t(this,uf,s.queryCache||new his),$t(this,cE,s.mutationCache||new pis),$t(this,dE,s.defaultOptions||{}),$t(this,LB,new Map),$t(this,PB,new Map),$t(this,uE,0)}mount(){Xg(this,uE)._++,pe(this,uE)===1&&($t(this,IB,bVe.subscribe(async s=>{s&&(await this.resumePausedMutations(),pe(this,uf).onFocus())})),$t(this,DB,jke.subscribe(async s=>{s&&(await this.resumePausedMutations(),pe(this,uf).onOnline())})))}unmount(){var s,t;Xg(this,uE)._--,pe(this,uE)===0&&((s=pe(this,IB))==null||s.call(this),$t(this,IB,void 0),(t=pe(this,DB))==null||t.call(this),$t(this,DB,void 0))}isFetching(s){return pe(this,uf).findAll({...s,fetchStatus:"fetching"}).length}isMutating(s){return pe(this,cE).findAll({...s,status:"pending"}).length}getQueryData(s){var n;const t=this.defaultQueryOptions({queryKey:s});return(n=pe(this,uf).get(t.queryHash))==null?void 0:n.state.data}ensureQueryData(s){const t=this.defaultQueryOptions(s),n=pe(this,uf).build(this,t),r=n.state.data;return r===void 0?this.fetchQuery(s):(s.revalidateIfStale&&n.isStaleByTime(DT(t.staleTime,n))&&this.prefetchQuery(t),Promise.resolve(r))}getQueriesData(s){return pe(this,uf).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=pe(this,uf).get(r.queryHash),i=a==null?void 0:a.state.data,l=tis(t,i);if(l!==void 0)return pe(this,uf).build(this,r).setData(l,{...n,manual:!0})}setQueriesData(s,t,n){return hg.batch(()=>pe(this,uf).findAll(s).map(({queryKey:r})=>[r,this.setQueryData(r,t,n)]))}getQueryState(s){var n;const t=this.defaultQueryOptions({queryKey:s});return(n=pe(this,uf).get(t.queryHash))==null?void 0:n.state}removeQueries(s){const t=pe(this,uf);hg.batch(()=>{t.findAll(s).forEach(n=>{t.remove(n)})})}resetQueries(s,t){const n=pe(this,uf);return hg.batch(()=>(n.findAll(s).forEach(r=>{r.reset()}),this.refetchQueries({type:"active",...s},t)))}cancelQueries(s,t={}){const n={revert:!0,...t},r=hg.batch(()=>pe(this,uf).findAll(s).map(a=>a.cancel(n)));return Promise.all(r).then(Qv).catch(Qv)}invalidateQueries(s,t={}){return hg.batch(()=>(pe(this,uf).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=hg.batch(()=>pe(this,uf).findAll(s).filter(a=>!a.isDisabled()&&!a.isStatic()).map(a=>{let i=a.fetch(void 0,n);return n.throwOnError||(i=i.catch(Qv)),a.state.fetchStatus==="paused"?Promise.resolve():i}));return Promise.all(r).then(Qv)}fetchQuery(s){const t=this.defaultQueryOptions(s);t.retry===void 0&&(t.retry=!1);const n=pe(this,uf).build(this,t);return n.isStaleByTime(DT(t.staleTime,n))?n.fetch(t):Promise.resolve(n.state.data)}prefetchQuery(s){return this.fetchQuery(s).then(Qv).catch(Qv)}fetchInfiniteQuery(s){return s.behavior=Nke(s.pages),this.fetchQuery(s)}prefetchInfiniteQuery(s){return this.fetchInfiniteQuery(s).then(Qv).catch(Qv)}ensureInfiniteQueryData(s){return s.behavior=Nke(s.pages),this.ensureQueryData(s)}resumePausedMutations(){return jke.isOnline()?pe(this,cE).resumePausedMutations():Promise.resolve()}getQueryCache(){return pe(this,uf)}getMutationCache(){return pe(this,cE)}getDefaultOptions(){return pe(this,dE)}setDefaultOptions(s){$t(this,dE,s)}setQueryDefaults(s,t){pe(this,LB).set(aO(s),{queryKey:s,defaultOptions:t})}getQueryDefaults(s){const t=[...pe(this,LB).values()],n={};return t.forEach(r=>{PZ(s,r.queryKey)&&Object.assign(n,r.defaultOptions)}),n}setMutationDefaults(s,t){pe(this,PB).set(aO(s),{mutationKey:s,defaultOptions:t})}getMutationDefaults(s){const t=[...pe(this,PB).values()],n={};return t.forEach(r=>{PZ(s,r.mutationKey)&&Object.assign(n,r.defaultOptions)}),n}defaultQueryOptions(s){if(s._defaulted)return s;const t={...pe(this,dE).queries,...this.getQueryDefaults(s.queryKey),...s,_defaulted:!0};return t.queryHash||(t.queryHash=yVe(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===vVe&&(t.enabled=!1),t}defaultMutationOptions(s){return s!=null&&s._defaulted?s:{...pe(this,dE).mutations,...(s==null?void 0:s.mutationKey)&&this.getMutationDefaults(s.mutationKey),...s,_defaulted:!0}}clear(){pe(this,uf).clear(),pe(this,cE).clear()}},uf=new WeakMap,cE=new WeakMap,dE=new WeakMap,LB=new WeakMap,PB=new WeakMap,uE=new WeakMap,IB=new WeakMap,DB=new WeakMap,bwt),lb,md,NQ,Zv,nD,RB,hE,mE,kQ,OB,FB,rD,aD,pE,zB,Eu,hW,HOe,GOe,WOe,KOe,YOe,ZOe,XOe,eSt,_wt,Jkt=(_wt=class extends vq{constructor(t,n){super();rs(this,Eu);rs(this,lb);rs(this,md);rs(this,NQ);rs(this,Zv);rs(this,nD);rs(this,RB);rs(this,hE);rs(this,mE);rs(this,kQ);rs(this,OB);rs(this,FB);rs(this,rD);rs(this,aD);rs(this,pE);rs(this,zB,new Set);this.options=n,$t(this,lb,t),$t(this,mE,null),$t(this,hE,qOe()),this.options.experimental_prefetchInRender||pe(this,hE).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&&(pe(this,md).addObserver(this),Srt(pe(this,md),this.options)?Kt(this,Eu,hW).call(this):this.updateResult(),Kt(this,Eu,KOe).call(this))}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return QOe(pe(this,md),this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return QOe(pe(this,md),this.options,this.options.refetchOnWindowFocus)}destroy(){this.listeners=new Set,Kt(this,Eu,YOe).call(this),Kt(this,Eu,ZOe).call(this),pe(this,md).removeObserver(this)}setOptions(t){const n=this.options,r=pe(this,md);if(this.options=pe(this,lb).defaultQueryOptions(t),this.options.enabled!==void 0&&typeof this.options.enabled!="boolean"&&typeof this.options.enabled!="function"&&typeof bj(this.options.enabled,pe(this,md))!="boolean")throw new Error("Expected enabled to be a boolean or a callback that returns a boolean");Kt(this,Eu,XOe).call(this),pe(this,md).setOptions(this.options),n._defaulted&&!wke(this.options,n)&&pe(this,lb).getQueryCache().notify({type:"observerOptionsUpdated",query:pe(this,md),observer:this});const a=this.hasListeners();a&&Crt(pe(this,md),r,this.options,n)&&Kt(this,Eu,hW).call(this),this.updateResult(),a&&(pe(this,md)!==r||bj(this.options.enabled,pe(this,md))!==bj(n.enabled,pe(this,md))||DT(this.options.staleTime,pe(this,md))!==DT(n.staleTime,pe(this,md)))&&Kt(this,Eu,HOe).call(this);const i=Kt(this,Eu,GOe).call(this);a&&(pe(this,md)!==r||bj(this.options.enabled,pe(this,md))!==bj(n.enabled,pe(this,md))||i!==pe(this,pE))&&Kt(this,Eu,WOe).call(this,i)}getOptimisticResult(t){const n=pe(this,lb).getQueryCache().build(pe(this,lb),t),r=this.createResult(n,t);return vis(this,r)&&($t(this,Zv,r),$t(this,RB,this.options),$t(this,nD,pe(this,md).state)),r}getCurrentResult(){return pe(this,Zv)}trackResult(t,n){return new Proxy(t,{get:(r,a)=>(this.trackProp(a),n==null||n(a),Reflect.get(r,a))})}trackProp(t){pe(this,zB).add(t)}getCurrentQuery(){return pe(this,md)}refetch({...t}={}){return this.fetch({...t})}fetchOptimistic(t){const n=pe(this,lb).defaultQueryOptions(t),r=pe(this,lb).getQueryCache().build(pe(this,lb),n);return r.fetch().then(()=>this.createResult(r,n))}fetch(t){return Kt(this,Eu,hW).call(this,{...t,cancelRefetch:t.cancelRefetch??!0}).then(()=>(this.updateResult(),pe(this,Zv)))}createResult(t,n){var I;const r=pe(this,md),a=this.options,i=pe(this,Zv),l=pe(this,nD),o=pe(this,RB),d=t!==r?t.state:pe(this,NQ),{state:u}=t;let h={...u},m=!1,p;if(n._optimisticResults){const D=this.hasListeners(),B=!D&&Srt(t,n),q=D&&Crt(t,r,n,a);(B||q)&&(h={...h,...Zkt(u.data,t.options)}),n._optimisticResults==="isRestoring"&&(h.fetchStatus="idle")}let{error:x,errorUpdatedAt:g,status:y}=h;p=h.data;let b=!1;if(n.placeholderData!==void 0&&p===void 0&&y==="pending"){let D;i!=null&&i.isPlaceholderData&&n.placeholderData===(o==null?void 0:o.placeholderData)?(D=i.data,b=!0):D=typeof n.placeholderData=="function"?n.placeholderData((I=pe(this,FB))==null?void 0:I.state.data,pe(this,FB)):n.placeholderData,D!==void 0&&(y="success",p=UOe(i==null?void 0:i.data,D,n),m=!0)}if(n.select&&p!==void 0&&!b)if(i&&p===(l==null?void 0:l.data)&&n.select===pe(this,kQ))p=pe(this,OB);else try{$t(this,kQ,n.select),p=n.select(p),p=UOe(i==null?void 0:i.data,p,n),$t(this,OB,p),$t(this,mE,null)}catch(D){$t(this,mE,D)}pe(this,mE)&&(x=pe(this,mE),p=pe(this,OB),g=Date.now(),y="error");const v=h.fetchStatus==="fetching",N=y==="pending",C=y==="error",A=N&&v,T=p!==void 0,M={status:y,fetchStatus:h.fetchStatus,isPending:N,isSuccess:y==="success",isError:C,isInitialLoading:A,isLoading:A,data:p,dataUpdatedAt:h.dataUpdatedAt,error:x,errorUpdatedAt:g,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:v,isRefetching:v&&!N,isLoadingError:C&&!T,isPaused:h.fetchStatus==="paused",isPlaceholderData:m,isRefetchError:C&&T,isStale:_Ve(t,n),refetch:this.refetch,promise:pe(this,hE),isEnabled:bj(n.enabled,t)!==!1};if(this.options.experimental_prefetchInRender){const D=W=>{M.status==="error"?W.reject(M.error):M.data!==void 0&&W.resolve(M.data)},B=()=>{const W=$t(this,hE,M.promise=qOe());D(W)},q=pe(this,hE);switch(q.status){case"pending":t.queryHash===r.queryHash&&D(q);break;case"fulfilled":(M.status==="error"||M.data!==q.value)&&B();break;case"rejected":(M.status!=="error"||M.error!==q.reason)&&B();break}}return M}updateResult(){const t=pe(this,Zv),n=this.createResult(pe(this,md),this.options);if($t(this,nD,pe(this,md).state),$t(this,RB,this.options),pe(this,nD).data!==void 0&&$t(this,FB,pe(this,md)),wke(n,t))return;$t(this,Zv,n);const r=()=>{if(!t)return!0;const{notifyOnChangeProps:a}=this.options,i=typeof a=="function"?a():a;if(i==="all"||!i&&!pe(this,zB).size)return!0;const l=new Set(i??pe(this,zB));return this.options.throwOnError&&l.add("error"),Object.keys(pe(this,Zv)).some(o=>{const c=o;return pe(this,Zv)[c]!==t[c]&&l.has(c)})};Kt(this,Eu,eSt).call(this,{listeners:r()})}onQueryUpdate(){this.updateResult(),this.hasListeners()&&Kt(this,Eu,KOe).call(this)}},lb=new WeakMap,md=new WeakMap,NQ=new WeakMap,Zv=new WeakMap,nD=new WeakMap,RB=new WeakMap,hE=new WeakMap,mE=new WeakMap,kQ=new WeakMap,OB=new WeakMap,FB=new WeakMap,rD=new WeakMap,aD=new WeakMap,pE=new WeakMap,zB=new WeakMap,Eu=new WeakSet,hW=function(t){Kt(this,Eu,XOe).call(this);let n=pe(this,md).fetch(this.options,t);return t!=null&&t.throwOnError||(n=n.catch(Qv)),n},HOe=function(){Kt(this,Eu,YOe).call(this);const t=DT(this.options.staleTime,pe(this,md));if(rO||pe(this,Zv).isStale||!BOe(t))return;const r=Ukt(pe(this,Zv).dataUpdatedAt,t)+1;$t(this,rD,setTimeout(()=>{pe(this,Zv).isStale||this.updateResult()},r))},GOe=function(){return(typeof this.options.refetchInterval=="function"?this.options.refetchInterval(pe(this,md)):this.options.refetchInterval)??!1},WOe=function(t){Kt(this,Eu,ZOe).call(this),$t(this,pE,t),!(rO||bj(this.options.enabled,pe(this,md))===!1||!BOe(pe(this,pE))||pe(this,pE)===0)&&$t(this,aD,setInterval(()=>{(this.options.refetchIntervalInBackground||bVe.isFocused())&&Kt(this,Eu,hW).call(this)},pe(this,pE)))},KOe=function(){Kt(this,Eu,HOe).call(this),Kt(this,Eu,WOe).call(this,Kt(this,Eu,GOe).call(this))},YOe=function(){pe(this,rD)&&(clearTimeout(pe(this,rD)),$t(this,rD,void 0))},ZOe=function(){pe(this,aD)&&(clearInterval(pe(this,aD)),$t(this,aD,void 0))},XOe=function(){const t=pe(this,lb).getQueryCache().build(pe(this,lb),this.options);if(t===pe(this,md))return;const n=pe(this,md);$t(this,md,t),$t(this,NQ,t.state),this.hasListeners()&&(n==null||n.removeObserver(this),t.addObserver(this))},eSt=function(t){hg.batch(()=>{t.listeners&&this.listeners.forEach(n=>{n(pe(this,Zv))}),pe(this,lb).getQueryCache().notify({query:pe(this,md),type:"observerResultsUpdated"})})},_wt);function yis(s,t){return bj(t.enabled,s)!==!1&&s.state.data===void 0&&!(s.state.status==="error"&&t.retryOnMount===!1)}function Srt(s,t){return yis(s,t)||s.state.data!==void 0&&QOe(s,t,t.refetchOnMount)}function QOe(s,t,n){if(bj(t.enabled,s)!==!1&&DT(t.staleTime,s)!=="static"){const r=typeof n=="function"?n(s):n;return r==="always"||r!==!1&&_Ve(s,t)}return!1}function Crt(s,t,n,r){return(s!==t||bj(r.enabled,s)===!1)&&(!n.suspense||s.state.status!=="error")&&_Ve(s,n)}function _Ve(s,t){return bj(t.enabled,s)!==!1&&s.isStaleByTime(DT(t.staleTime,s))}function vis(s,t){return!wke(s.getCurrentResult(),t)}var bis=class extends Jkt{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:Nke()})}getOptimisticResult(s){return s.behavior=Nke(),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 x,g;const{state:n}=s,r=super.createResult(s,t),{isFetching:a,isRefetching:i,isError:l,isRefetchError:o}=r,c=(g=(x=n.fetchMeta)==null?void 0:x.fetchMore)==null?void 0:g.direction,d=l&&c==="forward",u=a&&c==="forward",h=l&&c==="backward",m=a&&c==="backward";return{...r,fetchNextPage:this.fetchNextPage,fetchPreviousPage:this.fetchPreviousPage,hasNextPage:fis(t,n.data),hasPreviousPage:xis(t,n.data),isFetchNextPageError:d,isFetchingNextPage:u,isFetchPreviousPageError:h,isFetchingPreviousPage:m,isRefetchError:o&&!d&&!h,isRefetching:i&&!u&&!m}}},fE,xE,cb,s3,eC,m2e,JOe,wwt,_is=(wwt=class extends vq{constructor(n,r){super();rs(this,eC);rs(this,fE);rs(this,xE);rs(this,cb);rs(this,s3);$t(this,fE,n),this.setOptions(r),this.bindMethods(),Kt(this,eC,m2e).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=pe(this,fE).defaultMutationOptions(n),wke(this.options,r)||pe(this,fE).getMutationCache().notify({type:"observerOptionsUpdated",mutation:pe(this,cb),observer:this}),r!=null&&r.mutationKey&&this.options.mutationKey&&aO(r.mutationKey)!==aO(this.options.mutationKey)?this.reset():((a=pe(this,cb))==null?void 0:a.state.status)==="pending"&&pe(this,cb).setOptions(this.options)}onUnsubscribe(){var n;this.hasListeners()||(n=pe(this,cb))==null||n.removeObserver(this)}onMutationUpdate(n){Kt(this,eC,m2e).call(this),Kt(this,eC,JOe).call(this,n)}getCurrentResult(){return pe(this,xE)}reset(){var n;(n=pe(this,cb))==null||n.removeObserver(this),$t(this,cb,void 0),Kt(this,eC,m2e).call(this),Kt(this,eC,JOe).call(this)}mutate(n,r){var a;return $t(this,s3,r),(a=pe(this,cb))==null||a.removeObserver(this),$t(this,cb,pe(this,fE).getMutationCache().build(pe(this,fE),this.options)),pe(this,cb).addObserver(this),pe(this,cb).execute(n)}},fE=new WeakMap,xE=new WeakMap,cb=new WeakMap,s3=new WeakMap,eC=new WeakSet,m2e=function(){var r;const n=((r=pe(this,cb))==null?void 0:r.state)??Xkt();$t(this,xE,{...n,isPending:n.status==="pending",isSuccess:n.status==="success",isError:n.status==="error",isIdle:n.status==="idle",mutate:this.mutate,reset:this.reset})},JOe=function(n){hg.batch(()=>{var r,a,i,l,o,c,d,u;if(pe(this,s3)&&this.hasListeners()){const h=pe(this,xE).variables,m=pe(this,xE).context;(n==null?void 0:n.type)==="success"?((a=(r=pe(this,s3)).onSuccess)==null||a.call(r,n.data,h,m),(l=(i=pe(this,s3)).onSettled)==null||l.call(i,n.data,null,h,m)):(n==null?void 0:n.type)==="error"&&((c=(o=pe(this,s3)).onError)==null||c.call(o,n.error,h,m),(u=(d=pe(this,s3)).onSettled)==null||u.call(d,void 0,n.error,h,m))}this.listeners.forEach(h=>{h(pe(this,xE))})})},wwt),tSt=j.createContext(void 0),ts=s=>{const t=j.useContext(tSt);if(!t)throw new Error("No QueryClient set, use QueryClientProvider to set one");return t},wis=({client:s,children:t})=>(j.useEffect(()=>(s.mount(),()=>{s.unmount()}),[s]),e.jsx(tSt.Provider,{value:s,children:t})),sSt=j.createContext(!1),jis=()=>j.useContext(sSt);sSt.Provider;function Nis(){let s=!1;return{clearReset:()=>{s=!1},reset:()=>{s=!0},isReset:()=>s}}var kis=j.createContext(Nis()),Sis=()=>j.useContext(kis),Cis=(s,t)=>{(s.suspense||s.throwOnError||s.experimental_prefetchInRender)&&(t.isReset()||(s.retryOnMount=!1))},Ais=s=>{j.useEffect(()=>{s.clearReset()},[s])},Eis=({result:s,errorResetBoundary:t,throwOnError:n,query:r,suspense:a})=>s.isError&&!t.isReset()&&!s.isFetching&&r&&(a&&s.data===void 0||Hkt(n,[s.error,r])),Tis=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))}},Mis=(s,t)=>s.isLoading&&s.isFetching&&!t,Lis=(s,t)=>(s==null?void 0:s.suspense)&&t.isPending,Art=(s,t,n)=>t.fetchOptimistic(s).catch(()=>{n.clearReset()});function nSt(s,t,n){var h,m,p,x,g;const r=jis(),a=Sis(),i=ts(),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",Tis(l),Cis(l,a),Ais(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 b=u?c.subscribe(hg.batchCalls(y)):Qv;return c.updateResult(),b},[c,u]),()=>c.getCurrentResult(),()=>c.getCurrentResult()),j.useEffect(()=>{c.setOptions(l)},[l,c]),Lis(l,d))throw Art(l,c,a);if(Eis({result:d,errorResetBoundary:a,throwOnError:l.throwOnError,query:i.getQueryCache().get(l.queryHash),suspense:l.suspense}))throw d.error;if((x=(p=i.getDefaultOptions().queries)==null?void 0:p._experimental_afterQuery)==null||x.call(p,l,d),l.experimental_prefetchInRender&&!rO&&Mis(d,r)){const y=o?Art(l,c,a):(g=i.getQueryCache().get(l.queryHash))==null?void 0:g.promise;y==null||y.catch(Qv).finally(()=>{c.updateResult()})}return l.notifyOnChangeProps?d:c.trackResult(d)}function ht(s,t){return nSt(s,Jkt)}function yt(s,t){const n=ts(),[r]=j.useState(()=>new _is(n,s));j.useEffect(()=>{r.setOptions(s)},[r,s]);const a=j.useSyncExternalStore(j.useCallback(l=>r.subscribe(hg.batchCalls(l)),[r]),()=>r.getCurrentResult(),()=>r.getCurrentResult()),i=j.useCallback((l,o)=>{r.mutate(l,o).catch(Qv)},[r]);if(a.error&&Hkt(r.options.throwOnError,[a.error]))throw a.error;return{...a,mutate:i,mutateAsync:a.mutate}}function Pis(s,t){return nSt(s,bis)}/** * @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 IZ(){return IZ=Object.assign?Object.assign.bind():function(s){for(var t=1;t"u")throw new Error(t)}function rSt(s,t){if(!s){typeof console<"u"&&console.warn(t);try{throw new Error(t)}catch{}}}function Dis(){return Math.random().toString(36).substr(2,8)}function Trt(s,t){return{usr:s.state,key:s.key,idx:t}}function eFe(s,t,n,r){return n===void 0&&(n=null),IZ({pathname:typeof s=="string"?s:s.pathname,search:"",hash:""},typeof t=="string"?bq(t):t,{state:n,key:t&&t.key||r||Dis()})}function kke(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 bq(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 Ris(s,t,n,r){r===void 0&&(r={});let{window:a=document.defaultView,v5Compat:i=!1}=r,l=a.history,o=GE.Pop,c=null,d=u();d==null&&(d=0,l.replaceState(IZ({},l.state,{idx:d}),""));function u(){return(l.state||{idx:null}).idx}function h(){o=GE.Pop;let y=u(),b=y==null?null:y-d;d=y,c&&c({action:o,location:g.location,delta:b})}function m(y,b){o=GE.Push;let v=eFe(g.location,y,b);d=u()+1;let N=Trt(v,d),C=g.createHref(v);try{l.pushState(N,"",C)}catch(A){if(A instanceof DOMException&&A.name==="DataCloneError")throw A;a.location.assign(C)}i&&c&&c({action:o,location:g.location,delta:1})}function p(y,b){o=GE.Replace;let v=eFe(g.location,y,b);d=u();let N=Trt(v,d),C=g.createHref(v);l.replaceState(N,"",C),i&&c&&c({action:o,location:g.location,delta:0})}function x(y){let b=a.location.origin!=="null"?a.location.origin:a.location.href,v=typeof y=="string"?y:kke(y);return v=v.replace(/ $/,"%20"),qp(b,"No window.location.(origin|href) available to create URL for href: "+v),new URL(v,b)}let g={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(Ert,h),c=y,()=>{a.removeEventListener(Ert,h),c=null}},createHref(y){return t(a,y)},createURL:x,encodeLocation(y){let b=x(y);return{pathname:b.pathname,search:b.search,hash:b.hash}},push:m,replace:p,go(y){return l.go(y)}};return g}var Mrt;(function(s){s.data="data",s.deferred="deferred",s.redirect="redirect",s.error="error"})(Mrt||(Mrt={}));function Ois(s,t,n){return n===void 0&&(n="/"),Fis(s,t,n,!1)}function Fis(s,t,n,r){let a=typeof t=="string"?bq(t):t,i=K$(a.pathname||"/",n);if(i==null)return null;let l=aSt(s);zis(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("/")&&(qp(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=RT([r,c.relativePath]),u=n.concat(c);i.children&&i.children.length>0&&(qp(i.index!==!0,"Index routes must not have child routes. Please remove "+('all child routes from route path "'+d+'".')),aSt(i.children,t,u,d)),!(i.path==null&&!i.index)&&t.push({path:d,score:Gis(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 iSt(i.path))a(i,l,c)}),t}function iSt(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=iSt(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 zis(s){s.sort((t,n)=>t.score!==n.score?n.score-t.score:Wis(t.routesMeta.map(r=>r.childrenIndex),n.routesMeta.map(r=>r.childrenIndex)))}const Bis=/^:[\w-]+$/,$is=3,Uis=2,qis=1,Vis=10,His=-2,Lrt=s=>s==="*";function Gis(s,t){let n=s.split("/"),r=n.length;return n.some(Lrt)&&(r+=His),t&&(r+=Uis),n.filter(a=>!Lrt(a)).reduce((a,i)=>a+(Bis.test(i)?$is:i===""?qis:Vis),r)}function Wis(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 Kis(s,t,n){let{routesMeta:r}=s,a={},i="/",l=[];for(let o=0;o{let{paramName:m,isOptional:p}=u;if(m==="*"){let g=o[h]||"";l=i.slice(0,i.length-g.length).replace(/(.)\/+$/,"$1")}const x=o[h];return p&&!x?d[m]=void 0:d[m]=(x||"").replace(/%2F/g,"/"),d},{}),pathname:i,pathnameBase:l,pattern:s}}function Yis(s,t,n){t===void 0&&(t=!1),n===void 0&&(n=!0),rSt(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 Zis(s){try{return s.split("/").map(t=>decodeURIComponent(t).replace(/\//g,"%2F")).join("/")}catch(t){return rSt(!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 K$(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 Xis(s,t){t===void 0&&(t="/");let{pathname:n,search:r="",hash:a=""}=typeof s=="string"?bq(s):s;return{pathname:n?n.startsWith("/")?n:Qis(n,t):t,search:tos(r),hash:sos(a)}}function Qis(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 wLe(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 Jis(s){return s.filter((t,n)=>n===0||t.route.path&&t.route.path.length>0)}function wVe(s,t){let n=Jis(s);return t?n.map((r,a)=>a===n.length-1?r.pathname:r.pathnameBase):n.map(r=>r.pathnameBase)}function jVe(s,t,n,r){r===void 0&&(r=!1);let a;typeof s=="string"?a=bq(s):(a=IZ({},s),qp(!a.pathname||!a.pathname.includes("?"),wLe("?","pathname","search",a)),qp(!a.pathname||!a.pathname.includes("#"),wLe("#","pathname","hash",a)),qp(!a.search||!a.search.includes("#"),wLe("#","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=Xis(a,o),d=l&&l!=="/"&&l.endsWith("/"),u=(i||l===".")&&n.endsWith("/");return!c.pathname.endsWith("/")&&(d||u)&&(c.pathname+="/"),c}const RT=s=>s.join("/").replace(/\/\/+/g,"/"),eos=s=>s.replace(/\/+$/,"").replace(/^\/*/,"/"),tos=s=>!s||s==="?"?"":s.startsWith("?")?s:"?"+s,sos=s=>!s||s==="#"?"":s.startsWith("#")?s:"#"+s;function nos(s){return s!=null&&typeof s.status=="number"&&typeof s.statusText=="string"&&typeof s.internal=="boolean"&&"data"in s}const oSt=["post","put","patch","delete"];new Set(oSt);const ros=["get",...oSt];new Set(ros);/** * 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 DZ(){return DZ=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=jVe(d,JSON.parse(l),i,u.relative==="path");s==null&&t!=="/"&&(h.pathname=h.pathname==="/"?t:RT([t,h.pathname])),(u.replace?r.replace:r.push)(h,u.state,u)},[t,r,l,i,s])}const oos=j.createContext(null);function los(s){let t=j.useContext(L5).outlet;return t&&j.createElement(oos.Provider,{value:s},t)}function Vi(){let{matches:s}=j.useContext(L5),t=s[s.length-1];return t?t.params:{}}function X3e(s,t){let{relative:n}=t===void 0?{}:t,{future:r}=j.useContext(wC),{matches:a}=j.useContext(L5),{pathname:i}=Wd(),l=JSON.stringify(wVe(a,r.v7_relativeSplatPath));return j.useMemo(()=>jVe(s,JSON.parse(l),i,n==="path"),[s,l,i,n])}function cos(s,t){return dos(s,t)}function dos(s,t,n,r){_q()||qp(!1);let{navigator:a}=j.useContext(wC),{matches:i}=j.useContext(L5),l=i[i.length-1],o=l?l.params:{};l&&l.pathname;let c=l?l.pathnameBase:"/";l&&l.route;let d=Wd(),u;if(t){var h;let y=typeof t=="string"?bq(t):t;c==="/"||(h=y.pathname)!=null&&h.startsWith(c)||qp(!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 x=Ois(s,{pathname:p}),g=fos(x&&x.map(y=>Object.assign({},y,{params:Object.assign({},o,y.params),pathname:RT([c,a.encodeLocation?a.encodeLocation(y.pathname).pathname:y.pathname]),pathnameBase:y.pathnameBase==="/"?c:RT([c,a.encodeLocation?a.encodeLocation(y.pathnameBase).pathname:y.pathnameBase])})),i,n,r);return t&&g?j.createElement(Z3e.Provider,{value:{location:DZ({pathname:"/",search:"",hash:"",state:null,key:"default"},u),navigationType:GE.Pop}},g):g}function uos(){let s=vos(),t=nos(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 hos=j.createElement(uos,null);class mos 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(L5.Provider,{value:this.props.routeContext},j.createElement(cSt.Provider,{value:this.state.error,children:this.props.component})):this.props.children}}function pos(s){let{routeContext:t,match:n,children:r}=s,a=j.useContext(Y3e);return a&&a.static&&a.staticContext&&(n.route.errorElement||n.route.ErrorBoundary)&&(a.staticContext._deepestRenderedBoundaryId=n.route.id),j.createElement(L5.Provider,{value:t},r)}function fos(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||qp(!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,x=!1,g=null,y=null;n&&(p=o&&h.route.id?o[h.route.id]:void 0,g=h.route.errorElement||hos,c&&(d<0&&m===0?(x=!0,y=null):d===m&&(x=!0,y=h.route.hydrateFallbackElement||null)));let b=t.concat(l.slice(0,m+1)),v=()=>{let N;return p?N=g:x?N=y:h.route.Component?N=j.createElement(h.route.Component,null):h.route.element?N=h.route.element:N=u,j.createElement(pos,{match:h,routeContext:{outlet:u,matches:b,isDataRoute:n!=null},children:N})};return n&&(h.route.ErrorBoundary||h.route.errorElement||m===0)?j.createElement(mos,{location:n.location,revalidation:n.revalidation,component:g,error:p,children:v(),routeContext:{outlet:null,matches:b,isDataRoute:!0}}):v()},null)}var uSt=function(s){return s.UseBlocker="useBlocker",s.UseRevalidator="useRevalidator",s.UseNavigateStable="useNavigate",s}(uSt||{}),Cke=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}(Cke||{});function xos(s){let t=j.useContext(Y3e);return t||qp(!1),t}function gos(s){let t=j.useContext(lSt);return t||qp(!1),t}function yos(s){let t=j.useContext(L5);return t||qp(!1),t}function hSt(s){let t=yos(),n=t.matches[t.matches.length-1];return n.route.id||qp(!1),n.route.id}function vos(){var s;let t=j.useContext(cSt),n=gos(Cke.UseRouteError),r=hSt(Cke.UseRouteError);return t!==void 0?t:(s=n.errors)==null?void 0:s[r]}function bos(){let{router:s}=xos(uSt.UseNavigateStable),t=hSt(Cke.UseNavigateStable),n=j.useRef(!1);return dSt(()=>{n.current=!0}),j.useCallback(function(a,i){i===void 0&&(i={}),n.current&&(typeof a=="number"?s.navigate(a):s.navigate(a,DZ({fromRouteId:t},i)))},[s,t])}function _os(s,t){s==null||s.v7_startTransition,s==null||s.v7_relativeSplatPath}function r1(s){let{to:t,replace:n,state:r,relative:a}=s;_q()||qp(!1);let{future:i,static:l}=j.useContext(wC),{matches:o}=j.useContext(L5),{pathname:c}=Wd(),d=Vn(),u=jVe(t,wVe(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 mSt(s){return los(s.context)}function ds(s){qp(!1)}function wos(s){let{basename:t="/",children:n=null,location:r,navigationType:a=GE.Pop,navigator:i,static:l=!1,future:o}=s;_q()&&qp(!1);let c=t.replace(/^\/*/,"/"),d=j.useMemo(()=>({basename:c,navigator:i,static:l,future:DZ({v7_relativeSplatPath:!1},o)}),[c,o,i,l]);typeof r=="string"&&(r=bq(r));let{pathname:u="/",search:h="",hash:m="",state:p=null,key:x="default"}=r,g=j.useMemo(()=>{let y=K$(u,c);return y==null?null:{location:{pathname:y,search:h,hash:m,state:p,key:x},navigationType:a}},[c,u,h,m,p,x,a]);return g==null?null:j.createElement(wC.Provider,{value:d},j.createElement(Z3e.Provider,{children:n,value:g}))}function RZ(s){let{children:t,location:n}=s;return cos(tFe(t),n)}new Promise(()=>{});function tFe(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,tFe(r.props.children,i));return}r.type!==ds&&qp(!1),!r.props.index||!r.props.children||qp(!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=tFe(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 Ake(){return Ake=Object.assign?Object.assign.bind():function(s){for(var t=1;t=0)&&(n[a]=s[a]);return n}function jos(s){return!!(s.metaKey||s.altKey||s.ctrlKey||s.shiftKey)}function Nos(s,t){return s.button===0&&(!t||t==="_self")&&!jos(s)}function sFe(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 kos(s,t){let n=sFe(s);return t&&t.forEach((r,a)=>{n.has(a)||t.getAll(a).forEach(i=>{n.append(a,i)})}),n}const Sos=["onClick","relative","reloadDocument","replace","state","target","to","preventScrollReset","viewTransition"],Cos=["aria-current","caseSensitive","className","end","style","to","viewTransition","children"],Aos="6";try{window.__reactRouterVersion=Aos}catch{}const Eos=j.createContext({isTransitioning:!1}),Tos="startTransition",Prt=oqe[Tos];function Mos(s){let{basename:t,children:n,future:r,window:a}=s,i=j.useRef();i.current==null&&(i.current=Iis({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&&Prt?Prt(()=>c(h)):c(h)},[c,d]);return j.useLayoutEffect(()=>l.listen(u),[l,u]),j.useEffect(()=>_os(r),[r]),j.createElement(wos,{basename:t,children:n,location:o.location,navigationType:o.action,navigator:l,future:r})}const Los=typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u",Pos=/^(?:[a-z][a-z0-9+.-]*:|\/\/)/i,Wn=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=pSt(t,Sos),{basename:p}=j.useContext(wC),x,g=!1;if(typeof d=="string"&&Pos.test(d)&&(x=d,Los))try{let N=new URL(window.location.href),C=d.startsWith("//")?new URL(N.protocol+d):new URL(d),A=K$(C.pathname,p);C.origin===N.origin&&A!=null?d=A+C.search+C.hash:g=!0}catch{}let y=aos(d,{relative:a}),b=Dos(d,{replace:l,state:o,target:c,preventScrollReset:u,relative:a,viewTransition:h});function v(N){r&&r(N),N.defaultPrevented||b(N)}return j.createElement("a",Ake({},m,{href:x||y,onClick:g||i?r:v,ref:n,target:c}))}),_A=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=pSt(t,Cos),m=X3e(c,{relative:h.relative}),p=Wd(),x=j.useContext(lSt),{navigator:g,basename:y}=j.useContext(wC),b=x!=null&&Ros(m)&&d===!0,v=g.encodeLocation?g.encodeLocation(m).pathname:m.pathname,N=p.pathname,C=x&&x.navigation&&x.navigation.location?x.navigation.location.pathname:null;a||(N=N.toLowerCase(),C=C?C.toLowerCase():null,v=v.toLowerCase()),C&&y&&(C=K$(C,y)||C);const A=v!=="/"&&v.endsWith("/")?v.length-1:v.length;let T=N===v||!l&&N.startsWith(v)&&N.charAt(A)==="/",P=C!=null&&(C===v||!l&&C.startsWith(v)&&C.charAt(v.length)==="/"),M={isActive:T,isPending:P,isTransitioning:b},I=T?r:void 0,D;typeof i=="function"?D=i(M):D=[i,T?"active":null,P?"pending":null,b?"transitioning":null].filter(Boolean).join(" ");let B=typeof o=="function"?o(M):o;return j.createElement(Wn,Ake({},h,{"aria-current":I,className:D,ref:n,style:B,to:c,viewTransition:d}),typeof u=="function"?u(M):u)});var nFe;(function(s){s.UseScrollRestoration="useScrollRestoration",s.UseSubmit="useSubmit",s.UseSubmitFetcher="useSubmitFetcher",s.UseFetcher="useFetcher",s.useViewTransitionState="useViewTransitionState"})(nFe||(nFe={}));var Irt;(function(s){s.UseFetcher="useFetcher",s.UseFetchers="useFetchers",s.UseScrollRestoration="useScrollRestoration"})(Irt||(Irt={}));function Ios(s){let t=j.useContext(Y3e);return t||qp(!1),t}function Dos(s,t){let{target:n,replace:r,state:a,preventScrollReset:i,relative:l,viewTransition:o}=t===void 0?{}:t,c=Vn(),d=Wd(),u=X3e(s,{relative:l});return j.useCallback(h=>{if(Nos(h,n)){h.preventDefault();let m=r!==void 0?r:kke(d)===kke(u);c(s,{replace:m,state:a,preventScrollReset:i,relative:l,viewTransition:o})}},[d,c,u,r,a,n,s,i,l,o])}function oc(s){let t=j.useRef(sFe(s)),n=j.useRef(!1),r=Wd(),a=j.useMemo(()=>kos(r.search,n.current?null:t.current),[r.search]),i=Vn(),l=j.useCallback((o,c)=>{const d=sFe(typeof o=="function"?o(a):o);n.current=!0,i("?"+d,c)},[i,a]);return[a,l]}function Ros(s,t){t===void 0&&(t={});let n=j.useContext(Eos);n==null&&qp(!1);let{basename:r}=Ios(nFe.useViewTransitionState),a=X3e(s,{relative:t.relative});if(!n.isTransitioning)return!1;let i=K$(n.currentLocation.pathname,r)||n.currentLocation.pathname,l=K$(n.nextLocation.pathname,r)||n.nextLocation.pathname;return Ske(a.pathname,l)!=null||Ske(a.pathname,i)!=null}var Oos=typeof Element<"u",Fos=typeof Map=="function",zos=typeof Set=="function",Bos=typeof ArrayBuffer=="function"&&!!ArrayBuffer.isView;function p2e(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(!p2e(s[r],t[r]))return!1;return!0}var i;if(Fos&&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(!p2e(r.value[1],t.get(r.value[0])))return!1;return!0}if(zos&&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(Bos&&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(Oos&&s instanceof Element)return!1;for(r=n;r--!==0;)if(!((a[r]==="_owner"||a[r]==="__v"||a[r]==="__o")&&s.$$typeof)&&!p2e(s[a[r]],t[a[r]]))return!1;return!0}return s!==s&&t!==t}var $os=function(t,n){try{return p2e(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 Uos=Uc($os);var qos=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}},Vos=qos;const Drt=Uc(Vos);var Hos=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))(fSt||{}),jLe={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"]}},Rrt=Object.values(fSt),NVe={accesskey:"accessKey",charset:"charSet",class:"className",contenteditable:"contentEditable",contextmenu:"contextMenu","http-equiv":"httpEquiv",itemprop:"itemProp",tabindex:"tabIndex"},Wos=Object.entries(NVe).reduce((s,[t,n])=>(s[n]=t,s),{}),AN="data-rh",Qz={DEFAULT_TITLE:"defaultTitle",DEFER:"defer",ENCODE_SPECIAL_CHARACTERS:"encodeSpecialCharacters",ON_CHANGE_CLIENT_STATE:"onChangeClientState",TITLE_TEMPLATE:"titleTemplate",PRIORITIZE_SEO_TAGS:"prioritizeSeoTags"},Jz=(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},Kos=s=>{let t=Jz(s,"title");const n=Jz(s,Qz.TITLE_TEMPLATE);if(Array.isArray(t)&&(t=t.join("")),n&&t)return n.replace(/%s/g,()=>t);const r=Jz(s,Qz.DEFAULT_TITLE);return t||r||void 0},Yos=s=>Jz(s,Qz.ON_CHANGE_CLIENT_STATE)||(()=>{}),NLe=(s,t)=>t.filter(n=>typeof n[s]<"u").map(n=>n[s]).reduce((n,r)=>({...n,...r}),{}),Zos=(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),HH=(s,t,n)=>{const r={};return n.filter(a=>Array.isArray(a[s])?!0:(typeof a[s]<"u"&&Xos(`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:Zos(["href"],s),bodyAttributes:NLe("bodyAttributes",s),defer:Jz(s,Qz.DEFER),encode:Jz(s,Qz.ENCODE_SPECIAL_CHARACTERS),htmlAttributes:NLe("htmlAttributes",s),linkTags:HH("link",["rel","href"],s),metaTags:HH("meta",["name","charset","http-equiv","property","itemprop"],s),noscriptTags:HH("noscript",["innerHTML"],s),onChangeClientState:Yos(s),scriptTags:HH("script",["src","innerHTML"],s),styleTags:HH("style",["cssText"],s),title:Kos(s),titleAttributes:NLe("titleAttributes",s),prioritizeSeoTags:Qos(s,Qz.PRIORITIZE_SEO_TAGS)}),xSt=s=>Array.isArray(s)?s.join(""):s,els=(s,t)=>{const n=Object.keys(s);for(let r=0;rArray.isArray(s)?s.reduce((n,r)=>(els(r,t)?n.priority.push(r):n.default.push(r),n),{priority:[],default:[]}):{default:s,priority:[]},Ort=(s,t)=>({...s,[t]:void 0}),tls=["noscript","script","style"],rFe=(s,t=!0)=>t===!1?String(s):String(s).replace(/&/g,"&").replace(//g,">").replace(/"/g,""").replace(/'/g,"'"),gSt=s=>Object.keys(s).reduce((t,n)=>{const r=typeof s[n]<"u"?`${n}="${s[n]}"`:`${n}`;return t?`${t} ${r}`:r},""),sls=(s,t,n,r)=>{const a=gSt(n),i=xSt(t);return a?`<${s} ${AN}="true" ${a}>${rFe(i,r)}`:`<${s} ${AN}="true">${rFe(i,r)}`},nls=(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}="${rFe(i[u],n)}"`;return d?`${d} ${h}`:h},""),o=i.innerHTML||i.cssText||"",c=tls.indexOf(s)===-1;return`${r}<${s} ${AN}="true" ${l}${c?"/>":`>${o}`}`},""),ySt=(s,t={})=>Object.keys(s).reduce((n,r)=>{const a=NVe[r];return n[a||r]=s[r],n},t),rls=(s,t,n)=>{const r={key:t,[AN]:!0},a=ySt(n,r);return[It.createElement("title",a,t)]},f2e=(s,t)=>t.map((n,r)=>{const a={key:r,[AN]:!0};return Object.keys(n).forEach(i=>{const o=NVe[i]||i;if(o==="innerHTML"||o==="cssText"){const c=n.innerHTML||n.cssText;a.dangerouslySetInnerHTML={__html:c}}else a[o]=n[i]}),It.createElement(s,a)}),mj=(s,t,n=!0)=>{switch(s){case"title":return{toComponent:()=>rls(s,t.title,t.titleAttributes),toString:()=>sls(s,t.title,t.titleAttributes,n)};case"bodyAttributes":case"htmlAttributes":return{toComponent:()=>ySt(t),toString:()=>gSt(t)};default:return{toComponent:()=>f2e(s,t),toString:()=>nls(s,t,n)}}},als=({metaTags:s,linkTags:t,scriptTags:n,encode:r})=>{const a=kLe(s,jLe.meta),i=kLe(t,jLe.link),l=kLe(n,jLe.script);return{priorityMethods:{toComponent:()=>[...f2e("meta",a.priority),...f2e("link",i.priority),...f2e("script",l.priority)],toString:()=>`${mj("meta",a.priority,r)} ${mj("link",i.priority,r)} ${mj("script",l.priority,r)}`},metaTags:a.default,linkTags:i.default,scriptTags:l.default}},ils=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}=als(s)),{priority:p,base:mj("base",t,r),bodyAttributes:mj("bodyAttributes",n,r),htmlAttributes:mj("htmlAttributes",a,r),link:mj("link",u,r),meta:mj("meta",h,r),noscript:mj("noscript",i,r),script:mj("script",m,r),style:mj("style",l,r),title:mj("title",{title:o,titleAttributes:c},r)}},aFe=ils,mne=[],vSt=!!(typeof window<"u"&&window.document&&window.document.createElement),iFe=class{constructor(s,t){Lr(this,"instances",[]);Lr(this,"canUseDOM",vSt);Lr(this,"context");Lr(this,"value",{setHelmet:s=>{this.context.helmet=s},helmetInstances:{get:()=>this.canUseDOM?mne:this.instances,add:s=>{(this.canUseDOM?mne:this.instances).push(s)},remove:s=>{const t=(this.canUseDOM?mne:this.instances).indexOf(s);(this.canUseDOM?mne:this.instances).splice(t,1)}}});this.context=s,this.canUseDOM=t||!1,t||(s.helmet=aFe({baseTag:[],bodyAttributes:{},encodeSpecialCharacters:!0,htmlAttributes:{},linkTags:[],metaTags:[],noscriptTags:[],scriptTags:[],styleTags:[],title:"",titleAttributes:{}}))}},ols={},bSt=It.createContext(ols),iD,_St=(iD=class extends j.Component{constructor(n){super(n);Lr(this,"helmetData");this.helmetData=new iFe(this.props.context||{},iD.canUseDOM)}render(){return It.createElement(bSt.Provider,{value:this.helmetData.value},this.props.children)}},Lr(iD,"canUseDOM",vSt),iD),h7=(s,t)=>{const n=document.head||document.querySelector("head"),r=n.querySelectorAll(`${s}[${AN}]`),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(AN,"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}},oFe=(s,t)=>{const n=document.getElementsByTagName(s)[0];if(!n)return;const r=n.getAttribute(AN),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(AN):n.getAttribute(AN)!==l.join(",")&&n.setAttribute(AN,l.join(","))},lls=(s,t)=>{typeof s<"u"&&document.title!==s&&(document.title=xSt(s)),oFe("title",t)},Frt=(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;oFe("body",r),oFe("html",a),lls(h,m);const p={baseTag:h7("base",n),linkTags:h7("link",i),metaTags:h7("meta",l),noscriptTags:h7("noscript",o),scriptTags:h7("script",d),styleTags:h7("style",u)},x={},g={};Object.keys(p).forEach(y=>{const{newTags:b,oldTags:v}=p[y];b.length&&(x[y]=b),v.length&&(g[y]=p[y].oldTags)}),t&&t(),c(s,x,g)},GH=null,cls=s=>{GH&&cancelAnimationFrame(GH),s.defer?GH=requestAnimationFrame(()=>{Frt(s,()=>{GH=null})}):(Frt(s),GH=null)},dls=cls,zrt=class extends j.Component{constructor(){super(...arguments);Lr(this,"rendered",!1)}shouldComponentUpdate(t){return!Gos(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=Jos(t.get().map(i=>{const l={...i.props};return delete l.context,l}));_St.canUseDOM?dls(a):aFe&&(r=aFe(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}},IRe,Ul=(IRe=class extends j.Component{shouldComponentUpdate(s){return!Uos(Ort(this.props,"helmetData"),Ort(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 Drt(Rrt.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 ${Rrt.join(", ")} are allowed. Helmet does not support rendering <${s.type}> elements. Refer to our API for more information.`),Drt(!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 It.Children.forEach(s,r=>{if(!r||!r.props)return;const{children:a,...i}=r.props,l=Object.keys(i).reduce((c,d)=>(c[Wos[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 iFe)){const a=r;r=new iFe(a.context,!0),delete n.helmetData}return r?It.createElement(zrt,{...n,context:r.value}):It.createElement(bSt.Consumer,null,a=>It.createElement(zrt,{...n,context:a}))}},Lr(IRe,"defaultProps",{defer:!0,encodeSpecialCharacters:!0,prioritizeSeoTags:!1}),IRe);const uls=s=>{let t;return s?t=s:typeof fetch>"u"?t=(...n)=>mi(async()=>{const{default:r}=await Promise.resolve().then(()=>wq);return{default:r}},void 0).then(({default:r})=>r(...n)):t=fetch,(...n)=>t(...n)};class kVe extends Error{constructor(t,n="FunctionsError",r){super(t),this.name=n,this.context=r}}class hls extends kVe{constructor(t){super("Failed to send a request to the Edge Function","FunctionsFetchError",t)}}class mls extends kVe{constructor(t){super("Relay Error invoking the Edge Function","FunctionsRelayError",t)}}class wSt extends kVe{constructor(t){super("Edge Function returned a non-2xx status code","FunctionsHttpError",t)}}var lFe;(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"})(lFe||(lFe={}));var pls=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 fls{constructor(t,{headers:n={},customFetch:r,region:a=lFe.Any}={}){this.url=t,this.headers=n,this.region=a,this.fetch=uls(r)}setAuth(t){this.headers.Authorization=`Bearer ${t}`}invoke(t,n={}){var r;return pls(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(x=>{throw new hls(x)}),h=u.headers.get("x-relay-error");if(h&&h==="true")throw new mls(u);if(!u.ok)throw new wSt(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 yb={},SVe={},Q3e={},nee={},J3e={},eCe={},xls=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")},Y$=xls();const gls=Y$.fetch,jSt=Y$.fetch.bind(Y$),NSt=Y$.Headers,yls=Y$.Request,vls=Y$.Response,wq=Object.freeze(Object.defineProperty({__proto__:null,Headers:NSt,Request:yls,Response:vls,default:jSt,fetch:gls},Symbol.toStringTag,{value:"Module"})),bls=AQt(wq);var tCe={};Object.defineProperty(tCe,"__esModule",{value:!0});let _ls=class extends Error{constructor(t){super(t.message),this.name="PostgrestError",this.details=t.details,this.hint=t.hint,this.code=t.code}};tCe.default=_ls;var kSt=Sm&&Sm.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(eCe,"__esModule",{value:!0});const wls=kSt(bls),jls=kSt(tCe);let Nls=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=wls.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 b=await i.text();b===""||(this.headers.Accept==="text/csv"||this.headers.Accept&&this.headers.Accept.includes("application/vnd.pgrst.plan+text")?u=b:u=JSON.parse(b))}const g=(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("/");g&&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 g=await i.text();try{d=JSON.parse(g),Array.isArray(d)&&i.status===404&&(u=[],d=null,m=200,p="OK")}catch{i.status===404&&g===""?(m=204,p="No Content"):d={message:g}}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 jls.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}};eCe.default=Nls;var kls=Sm&&Sm.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(J3e,"__esModule",{value:!0});const Sls=kls(eCe);let Cls=class extends Sls.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}};J3e.default=Cls;var Als=Sm&&Sm.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(nee,"__esModule",{value:!0});const Els=Als(J3e);let Tls=class extends Els.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}};nee.default=Tls;var Mls=Sm&&Sm.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(Q3e,"__esModule",{value:!0});const WH=Mls(nee);let Lls=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 WH.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 WH.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 WH.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 WH.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 WH.default({method:n,url:this.url,headers:this.headers,schema:this.schema,fetch:this.fetch,allowEmpty:!1})}};Q3e.default=Lls;var sCe={},nCe={};Object.defineProperty(nCe,"__esModule",{value:!0});nCe.version=void 0;nCe.version="0.0.0-automated";Object.defineProperty(sCe,"__esModule",{value:!0});sCe.DEFAULT_HEADERS=void 0;const Pls=nCe;sCe.DEFAULT_HEADERS={"X-Client-Info":`postgrest-js/${Pls.version}`};var SSt=Sm&&Sm.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(SVe,"__esModule",{value:!0});const Ils=SSt(Q3e),Dls=SSt(nee),Rls=sCe;let Ols=class CSt{constructor(t,{headers:n={},schema:r,fetch:a}={}){this.url=t,this.headers=Object.assign(Object.assign({},Rls.DEFAULT_HEADERS),n),this.schemaName=r,this.fetch=a}from(t){const n=new URL(`${this.url}/${t}`);return new Ils.default(n,{headers:Object.assign({},this.headers),schema:this.schemaName,fetch:this.fetch})}schema(t){return new CSt(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 Dls.default({method:l,url:o,headers:d,schema:this.schemaName,body:c,fetch:this.fetch,allowEmpty:!1})}};SVe.default=Ols;var jq=Sm&&Sm.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(yb,"__esModule",{value:!0});yb.PostgrestError=yb.PostgrestBuilder=yb.PostgrestTransformBuilder=yb.PostgrestFilterBuilder=yb.PostgrestQueryBuilder=yb.PostgrestClient=void 0;const ASt=jq(SVe);yb.PostgrestClient=ASt.default;const ESt=jq(Q3e);yb.PostgrestQueryBuilder=ESt.default;const TSt=jq(nee);yb.PostgrestFilterBuilder=TSt.default;const MSt=jq(J3e);yb.PostgrestTransformBuilder=MSt.default;const LSt=jq(eCe);yb.PostgrestBuilder=LSt.default;const PSt=jq(tCe);yb.PostgrestError=PSt.default;var Fls=yb.default={PostgrestClient:ASt.default,PostgrestQueryBuilder:ESt.default,PostgrestFilterBuilder:TSt.default,PostgrestTransformBuilder:MSt.default,PostgrestBuilder:LSt.default,PostgrestError:PSt.default};const{PostgrestClient:zls,PostgrestQueryBuilder:wXn,PostgrestFilterBuilder:jXn,PostgrestTransformBuilder:NXn,PostgrestBuilder:kXn,PostgrestError:SXn}=Fls;let cFe;typeof window>"u"?cFe=require("ws"):cFe=window.WebSocket;const Bls=cFe,$ls="2.11.10",Uls={"X-Client-Info":`realtime-js/${$ls}`},qls="1.0.0",ISt=1e4,Vls=1e3;var eB;(function(s){s[s.connecting=0]="connecting",s[s.open=1]="open",s[s.closing=2]="closing",s[s.closed=3]="closed"})(eB||(eB={}));var Wv;(function(s){s.closed="closed",s.errored="errored",s.joined="joined",s.joining="joining",s.leaving="leaving"})(Wv||(Wv={}));var fN;(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"})(fN||(fN={}));var dFe;(function(s){s.websocket="websocket"})(dFe||(dFe={}));var y8;(function(s){s.Connecting="connecting",s.Open="open",s.Closing="closing",s.Closed="closed"})(y8||(y8={}));class Hls{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 DSt{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 Uh;(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"})(Uh||(Uh={}));const Brt=(s,t,n={})=>{var r;const a=(r=n.skipTypes)!==null&&r!==void 0?r:[];return Object.keys(t).reduce((i,l)=>(i[l]=Gls(l,s,t,a),i),{})},Gls=(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)?RSt(i,l):uFe(l)},RSt=(s,t)=>{if(s.charAt(0)==="_"){const n=s.slice(1,s.length);return Zls(t,n)}switch(s){case Uh.bool:return Wls(t);case Uh.float4:case Uh.float8:case Uh.int2:case Uh.int4:case Uh.int8:case Uh.numeric:case Uh.oid:return Kls(t);case Uh.json:case Uh.jsonb:return Yls(t);case Uh.timestamp:return Xls(t);case Uh.abstime:case Uh.date:case Uh.daterange:case Uh.int4range:case Uh.int8range:case Uh.money:case Uh.reltime:case Uh.text:case Uh.time:case Uh.timestamptz:case Uh.timetz:case Uh.tsrange:case Uh.tstzrange:return uFe(t);default:return uFe(t)}},uFe=s=>s,Wls=s=>{switch(s){case"t":return!0;case"f":return!1;default:return s}},Kls=s=>{if(typeof s=="string"){const t=parseFloat(s);if(!Number.isNaN(t))return t}return s},Yls=s=>{if(typeof s=="string")try{return JSON.parse(s)}catch(t){return console.log(`JSON parse error: ${t}`),s}return s},Zls=(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=>RSt(t,o))}return s},Xls=s=>typeof s=="string"?s.replace(" ","T"):s,OSt=s=>{let t=s;return t=t.replace(/^ws/i,"http"),t=t.replace(/(\/socket\/websocket|\/socket|\/websocket)\/?$/i,""),t.replace(/\/+$/,"")};class SLe{constructor(t,n,r={},a=ISt){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 $rt;(function(s){s.SYNC="sync",s.JOIN="join",s.LEAVE="leave"})($rt||($rt={}));class lY{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=lY.syncState(this.state,a,i,l),this.pendingDiffs.forEach(c=>{this.state=lY.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=lY.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),x=u.filter(y=>p.indexOf(y.presence_ref)<0),g=h.filter(y=>m.indexOf(y.presence_ref)<0);x.length>0&&(o[d]=x),g.length>0&&(c[d]=g)}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 Urt;(function(s){s.ALL="*",s.INSERT="INSERT",s.UPDATE="UPDATE",s.DELETE="DELETE"})(Urt||(Urt={}));var qrt;(function(s){s.BROADCAST="broadcast",s.PRESENCE="presence",s.POSTGRES_CHANGES="postgres_changes",s.SYSTEM="system"})(qrt||(qrt={}));var U4;(function(s){s.SUBSCRIBED="SUBSCRIBED",s.TIMED_OUT="TIMED_OUT",s.CLOSED="CLOSED",s.CHANNEL_ERROR="CHANNEL_ERROR"})(U4||(U4={}));class CVe{constructor(t,n={config:{}},r){this.topic=t,this.params=n,this.socket=r,this.bindings={},this.state=Wv.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 SLe(this,fN.join,this.params,this.timeout),this.rejoinTimer=new DSt(()=>this._rejoinUntilConnected(),this.socket.reconnectAfterMs),this.joinPush.receive("ok",()=>{this.state=Wv.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=Wv.closed,this.socket._remove(this)}),this._onError(a=>{this._isLeaving()||this._isClosed()||(this.socket.log("channel",`error ${this.topic}`,a),this.state=Wv.errored,this.rejoinTimer.scheduleTimeout())}),this.joinPush.receive("timeout",()=>{this._isJoining()&&(this.socket.log("channel",`timeout ${this.topic}`,this.joinPush.timeout),this.state=Wv.errored,this.rejoinTimer.scheduleTimeout())}),this._on(fN.reply,{},(a,i)=>{this._trigger(this._replyEventName(i),a)}),this.presence=new lY(this),this.broadcastEndpointURL=OSt(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(U4.CHANNEL_ERROR,u)),this._onClose(()=>t==null?void 0:t(U4.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(U4.SUBSCRIBED);return}else{const m=this.bindings.postgres_changes,p=(h=m==null?void 0:m.length)!==null&&h!==void 0?h:0,x=[];for(let g=0;g{this.state=Wv.errored,t==null||t(U4.CHANNEL_ERROR,new Error(JSON.stringify(Object.values(u).join(", ")||"error")))}).receive("timeout",()=>{t==null||t(U4.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=Wv.leaving;const n=()=>{this.socket.log("channel",`leave ${this.topic}`),this._trigger(fN.close,"leave",this._joinRef())};return this.joinPush.destroy(),new Promise(r=>{const a=new SLe(this,fN.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 SLe(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}=fN;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 x,g,y;return((x=p.filter)===null||x===void 0?void 0:x.event)==="*"||((y=(g=p.filter)===null||g===void 0?void 0:g.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 x,g,y,b,v,N;if(["broadcast","presence","postgres_changes"].includes(l))if("id"in p){const C=p.id,A=(x=p.filter)===null||x===void 0?void 0:x.event;return C&&((g=n.ids)===null||g===void 0?void 0:g.includes(C))&&(A==="*"||(A==null?void 0:A.toLocaleLowerCase())===((y=n.data)===null||y===void 0?void 0:y.type.toLocaleLowerCase()))}else{const C=(v=(b=p==null?void 0:p.filter)===null||b===void 0?void 0:b.event)===null||v===void 0?void 0:v.toLocaleLowerCase();return C==="*"||C===((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 x=m.data,{schema:g,table:y,commit_timestamp:b,type:v,errors:N}=x;m=Object.assign(Object.assign({},{schema:g,table:y,commit_timestamp:b,eventType:v,new:{},old:{},errors:N}),this._getPayloadRecords(x))}p.callback(m,r)})}_isClosed(){return this.state===Wv.closed}_isJoined(){return this.state===Wv.joined}_isJoining(){return this.state===Wv.joining}_isLeaving(){return this.state===Wv.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&&CVe.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(fN.close,{},t)}_onError(t){this._on(fN.error,{},n=>t(n))}_canPush(){return this.socket.isConnected()&&this._isJoined()}_rejoin(t=this.timeout){this._isLeaving()||(this.socket._leaveOpenTopic(this.topic),this.state=Wv.joining,this.joinPush.resend(t))}_getPayloadRecords(t){const n={new:{},old:{}};return(t.type==="INSERT"||t.type==="UPDATE")&&(n.new=Brt(t.columns,t.record)),(t.type==="UPDATE"||t.type==="DELETE")&&(n.old=Brt(t.columns,t.old_record)),n}}const Vrt=()=>{},Qls=` addEventListener("message", (e) => { if (e.data.event === "start") { setInterval(() => postMessage({ event: "keepAlive" }), e.data.interval); } });`;class Jls{constructor(t,n){var r;this.accessTokenValue=null,this.apiKey=null,this.channels=new Array,this.endPoint="",this.httpEndpoint="",this.headers=Uls,this.params={},this.timeout=ISt,this.heartbeatIntervalMs=25e3,this.heartbeatTimer=void 0,this.pendingHeartbeatRef=null,this.heartbeatCallback=Vrt,this.ref=0,this.logger=Vrt,this.conn=null,this.sendBuffer=[],this.serializer=new Hls,this.stateChangeCallbacks={open:[],close:[],error:[],message:[]},this.accessToken=null,this._resolveFetch=i=>{let l;return i?l=i:typeof fetch>"u"?l=(...o)=>mi(async()=>{const{default:c}=await Promise.resolve().then(()=>wq);return{default:c}},void 0).then(({default:c})=>c(...o)):l=fetch,(...o)=>l(...o)},this.endPoint=`${t}/${dFe.websocket}`,this.httpEndpoint=OSt(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 DSt(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=Bls),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 ecs(this.endpointURL(),void 0,{close:()=>{this.conn=null}})}}endpointURL(){return this._appendParams(this.endPoint,Object.assign({},this.params,{vsn:qls}))}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 eB.connecting:return y8.Connecting;case eB.open:return y8.Open;case eB.closing:return y8.Closing;default:return y8.Closed}}isConnected(){return this.connectionState()===y8.Open}channel(t,n={config:{}}){const r=`realtime:${t}`,a=this.getChannels().find(i=>i.topic===r);if(a)return a;{const i=new CVe(`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(fN.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(Vls,"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(fN.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([Qls],{type:"application/javascript"});n=URL.createObjectURL(r)}return n}}class ecs{constructor(t,n,r){this.binaryType="arraybuffer",this.onclose=()=>{},this.onerror=()=>{},this.onmessage=()=>{},this.onopen=()=>{},this.readyState=eB.connecting,this.send=()=>{},this.url=null,this.url=t,this.close=r.close}}class AVe extends Error{constructor(t){super(t),this.__isStorageError=!0,this.name="StorageError"}}function o0(s){return typeof s=="object"&&s!==null&&"__isStorageError"in s}class tcs extends AVe{constructor(t,n){super(t),this.name="StorageApiError",this.status=n}toJSON(){return{name:this.name,message:this.message,status:this.status}}}class hFe extends AVe{constructor(t,n){super(t),this.name="StorageUnknownError",this.originalError=n}}var scs=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 FSt=s=>{let t;return s?t=s:typeof fetch>"u"?t=(...n)=>mi(async()=>{const{default:r}=await Promise.resolve().then(()=>wq);return{default:r}},void 0).then(({default:r})=>r(...n)):t=fetch,(...n)=>t(...n)},ncs=()=>scs(void 0,void 0,void 0,function*(){return typeof Response>"u"?(yield mi(()=>Promise.resolve().then(()=>wq),void 0)).Response:Response}),mFe=s=>{if(Array.isArray(s))return s.map(n=>mFe(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]=mFe(r)}),t};var WO=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 CLe=s=>s.msg||s.message||s.error_description||s.error||JSON.stringify(s),rcs=(s,t,n)=>WO(void 0,void 0,void 0,function*(){const r=yield ncs();s instanceof r&&!(n!=null&&n.noResolveJson)?s.json().then(a=>{t(new tcs(CLe(a),s.status||500))}).catch(a=>{t(new hFe(CLe(a),a))}):t(new hFe(CLe(s),s))}),acs=(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 ree(s,t,n,r,a,i){return WO(this,void 0,void 0,function*(){return new Promise((l,o)=>{s(n,acs(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=>rcs(c,o,r))})})}function Eke(s,t,n,r){return WO(this,void 0,void 0,function*(){return ree(s,"GET",t,n,r)})}function OA(s,t,n,r,a){return WO(this,void 0,void 0,function*(){return ree(s,"POST",t,r,a,n)})}function ics(s,t,n,r,a){return WO(this,void 0,void 0,function*(){return ree(s,"PUT",t,r,a,n)})}function ocs(s,t,n,r){return WO(this,void 0,void 0,function*(){return ree(s,"HEAD",t,Object.assign(Object.assign({},n),{noResolveJson:!0}),r)})}function zSt(s,t,n,r,a){return WO(this,void 0,void 0,function*(){return ree(s,"DELETE",t,r,a,n)})}var X1=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 lcs={limit:100,offset:0,sortBy:{column:"name",order:"asc"}},Hrt={cacheControl:"3600",contentType:"text/plain;charset=UTF-8",upsert:!1};class ccs{constructor(t,n={},r,a){this.url=t,this.headers=n,this.bucketId=r,this.fetch=FSt(a)}uploadOrUpdate(t,n,r,a){return X1(this,void 0,void 0,function*(){try{let i;const l=Object.assign(Object.assign({},Hrt),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(o0(i))return{data:null,error:i};throw i}})}upload(t,n,r){return X1(this,void 0,void 0,function*(){return this.uploadOrUpdate("POST",t,n,r)})}uploadToSignedUrl(t,n,r,a){return X1(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:Hrt.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(o0(c))return{data:null,error:c};throw c}})}createSignedUploadUrl(t,n){return X1(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 OA(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 AVe("No token returned by API");return{data:{signedUrl:l.toString(),path:t,token:o},error:null}}catch(r){if(o0(r))return{data:null,error:r};throw r}})}update(t,n,r){return X1(this,void 0,void 0,function*(){return this.uploadOrUpdate("PUT",t,n,r)})}move(t,n,r){return X1(this,void 0,void 0,function*(){try{return{data:yield OA(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(o0(a))return{data:null,error:a};throw a}})}copy(t,n,r){return X1(this,void 0,void 0,function*(){try{return{data:{path:(yield OA(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(o0(a))return{data:null,error:a};throw a}})}createSignedUrl(t,n,r){return X1(this,void 0,void 0,function*(){try{let a=this._getFinalPath(t),i=yield OA(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(o0(a))return{data:null,error:a};throw a}})}createSignedUrls(t,n,r){return X1(this,void 0,void 0,function*(){try{const a=yield OA(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(o0(a))return{data:null,error:a};throw a}})}download(t,n){return X1(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 Eke(this.fetch,`${this.url}/${a}/${o}${l}`,{headers:this.headers,noResolveJson:!0})).blob(),error:null}}catch(o){if(o0(o))return{data:null,error:o};throw o}})}info(t){return X1(this,void 0,void 0,function*(){const n=this._getFinalPath(t);try{const r=yield Eke(this.fetch,`${this.url}/object/info/${n}`,{headers:this.headers});return{data:mFe(r),error:null}}catch(r){if(o0(r))return{data:null,error:r};throw r}})}exists(t){return X1(this,void 0,void 0,function*(){const n=this._getFinalPath(t);try{return yield ocs(this.fetch,`${this.url}/object/${n}`,{headers:this.headers}),{data:!0,error:null}}catch(r){if(o0(r)&&r instanceof hFe){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 X1(this,void 0,void 0,function*(){try{return{data:yield zSt(this.fetch,`${this.url}/object/${this.bucketId}`,{prefixes:t},{headers:this.headers}),error:null}}catch(n){if(o0(n))return{data:null,error:n};throw n}})}list(t,n,r){return X1(this,void 0,void 0,function*(){try{const a=Object.assign(Object.assign(Object.assign({},lcs),n),{prefix:t||""});return{data:yield OA(this.fetch,`${this.url}/object/list/${this.bucketId}`,a,{headers:this.headers},r),error:null}}catch(a){if(o0(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 dcs="2.7.1",ucs={"X-Client-Info":`storage-js/${dcs}`};var m7=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 hcs{constructor(t,n={},r){this.url=t,this.headers=Object.assign(Object.assign({},ucs),n),this.fetch=FSt(r)}listBuckets(){return m7(this,void 0,void 0,function*(){try{return{data:yield Eke(this.fetch,`${this.url}/bucket`,{headers:this.headers}),error:null}}catch(t){if(o0(t))return{data:null,error:t};throw t}})}getBucket(t){return m7(this,void 0,void 0,function*(){try{return{data:yield Eke(this.fetch,`${this.url}/bucket/${t}`,{headers:this.headers}),error:null}}catch(n){if(o0(n))return{data:null,error:n};throw n}})}createBucket(t,n={public:!1}){return m7(this,void 0,void 0,function*(){try{return{data:yield OA(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(o0(r))return{data:null,error:r};throw r}})}updateBucket(t,n){return m7(this,void 0,void 0,function*(){try{return{data:yield ics(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(o0(r))return{data:null,error:r};throw r}})}emptyBucket(t){return m7(this,void 0,void 0,function*(){try{return{data:yield OA(this.fetch,`${this.url}/bucket/${t}/empty`,{},{headers:this.headers}),error:null}}catch(n){if(o0(n))return{data:null,error:n};throw n}})}deleteBucket(t){return m7(this,void 0,void 0,function*(){try{return{data:yield zSt(this.fetch,`${this.url}/bucket/${t}`,{},{headers:this.headers}),error:null}}catch(n){if(o0(n))return{data:null,error:n};throw n}})}}class mcs extends hcs{constructor(t,n={},r){super(t,n,r)}from(t){return new ccs(this.url,this.headers,t,this.fetch)}}const pcs="2.49.10";let mW="";typeof Deno<"u"?mW="deno":typeof document<"u"?mW="web":typeof navigator<"u"&&navigator.product==="ReactNative"?mW="react-native":mW="node";const fcs={"X-Client-Info":`supabase-js-${mW}/${pcs}`},xcs={headers:fcs},gcs={schema:"public"},ycs={autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,flowType:"implicit"},vcs={};var bcs=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 _cs=s=>{let t;return s?t=s:typeof fetch>"u"?t=jSt:t=fetch,(...n)=>t(...n)},wcs=()=>typeof Headers>"u"?NSt:Headers,jcs=(s,t,n)=>{const r=_cs(n),a=wcs();return(i,l)=>bcs(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 Ncs=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 kcs(s){return s.endsWith("/")?s:s+"/"}function Scs(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:()=>Ncs(this,void 0,void 0,function*(){return""})};return s.accessToken?m.accessToken=s.accessToken:delete m.accessToken,m}const BSt="2.69.1",o9=30*1e3,pFe=3,ALe=pFe*o9,Ccs="http://localhost:9999",Acs="supabase.auth.token",Ecs={"X-Client-Info":`gotrue-js/${BSt}`},fFe="X-Supabase-Api-Version",$St={"2024-01-01":{timestamp:Date.parse("2024-01-01T00:00:00.0Z"),name:"2024-01-01"}},Tcs=/^([a-z0-9_-]{4})*($|[a-z0-9_-]{3}$|[a-z0-9_-]{2}$)$/i,Mcs=6e5;class EVe extends Error{constructor(t,n,r){super(t),this.__isAuthError=!0,this.name="AuthError",this.status=n,this.code=r}}function uc(s){return typeof s=="object"&&s!==null&&"__isAuthError"in s}class Lcs extends EVe{constructor(t,n,r){super(t,n,r),this.name="AuthApiError",this.status=n,this.code=r}}function Pcs(s){return uc(s)&&s.name==="AuthApiError"}class USt extends EVe{constructor(t,n){super(t),this.name="AuthUnknownError",this.originalError=n}}class N6 extends EVe{constructor(t,n,r,a){super(t,r,a),this.name=n,this.status=r}}class wA extends N6{constructor(){super("Auth session missing!","AuthSessionMissingError",400,void 0)}}function Ics(s){return uc(s)&&s.name==="AuthSessionMissingError"}class ELe extends N6{constructor(){super("Auth session or user missing","AuthInvalidTokenResponseError",500,void 0)}}class pne extends N6{constructor(t){super(t,"AuthInvalidCredentialsError",400,void 0)}}class fne extends N6{constructor(t,n=null){super(t,"AuthImplicitGrantRedirectError",500,void 0),this.details=null,this.details=n}toJSON(){return{name:this.name,message:this.message,status:this.status,details:this.details}}}function Dcs(s){return uc(s)&&s.name==="AuthImplicitGrantRedirectError"}class Grt extends N6{constructor(t,n=null){super(t,"AuthPKCEGrantCodeExchangeError",500,void 0),this.details=null,this.details=n}toJSON(){return{name:this.name,message:this.message,status:this.status,details:this.details}}}class xFe extends N6{constructor(t,n){super(t,"AuthRetryableFetchError",n,void 0)}}function TLe(s){return uc(s)&&s.name==="AuthRetryableFetchError"}class Wrt extends N6{constructor(t,n,r){super(t,"AuthWeakPasswordError",n,"weak_password"),this.reasons=r}}class cY extends N6{constructor(t){super(t,"AuthInvalidJwtError",400,"invalid_jwt")}}const Krt="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_".split(""),Yrt=` \r=`.split(""),Rcs=(()=>{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 Zrt(s){const t=[],n=l=>{t.push(String.fromCodePoint(l))},r={utf8seq:0,codepoint:0},a={queue:0,queuedBits:0},i=l=>{zcs(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 Fcs(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}Ocs(r,t)}}function zcs(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 Bcs(s){const t=[],n={queue:0,queuedBits:0},r=a=>{t.push(a)};for(let a=0;at.push(n)),new Uint8Array(t)}function Ucs(s){return Math.round(Date.now()/1e3)+s}function qcs(){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 Yk=()=>typeof window<"u"&&typeof document<"u",IM={tested:!1,writable:!1},dY=()=>{if(!Yk())return!1;try{if(typeof globalThis.localStorage!="object")return!1}catch{return!1}if(IM.tested)return IM.writable;const s=`lswt-${Math.random()}${Math.random()}`;try{globalThis.localStorage.setItem(s,s),globalThis.localStorage.removeItem(s),IM.tested=!0,IM.writable=!0}catch{IM.tested=!0,IM.writable=!1}return IM.writable};function Vcs(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 VSt=s=>{let t;return s?t=s:typeof fetch>"u"?t=(...n)=>mi(async()=>{const{default:r}=await Promise.resolve().then(()=>wq);return{default:r}},void 0).then(({default:r})=>r(...n)):t=fetch,(...n)=>t(...n)},Hcs=s=>typeof s=="object"&&s!==null&&"status"in s&&"ok"in s&&"json"in s&&typeof s.json=="function",HSt=async(s,t,n)=>{await s.setItem(t,JSON.stringify(n))},xne=async(s,t)=>{const n=await s.getItem(t);if(!n)return null;try{return JSON.parse(n)}catch{return n}},gne=async(s,t)=>{await s.removeItem(t)};class rCe{constructor(){this.promise=new rCe.promiseConstructor((t,n)=>{this.resolve=t,this.reject=n})}}rCe.promiseConstructor=Promise;function MLe(s){const t=s.split(".");if(t.length!==3)throw new cY("Invalid JWT structure");for(let r=0;r{setTimeout(()=>t(null),s)})}function Wcs(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 Kcs(s){return("0"+s.toString(16)).substr(-2)}function Ycs(){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,Kcs).join("")}async function Zcs(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 Xcs(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 Zcs(s);return btoa(n).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function p7(s,t,n=!1){const r=Ycs();let a=r;n&&(a+="/PASSWORD_RECOVERY"),await HSt(s,`${t}-code-verifier`,a);const i=await Xcs(r);return[i,r===i?"plain":"s256"]}const Qcs=/^2[0-9]{3}-(0[1-9]|1[0-2])-(0[1-9]|1[0-9]|2[0-9]|3[0-1])$/i;function Jcs(s){const t=s.headers.get(fFe);if(!t||!t.match(Qcs))return null;try{return new Date(`${t}T00:00:00.0Z`)}catch{return null}}function eds(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 tds(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 sds=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),nds=[502,503,504];async function Xrt(s){var t;if(!Hcs(s))throw new xFe(n8(s),0);if(nds.includes(s.status))throw new xFe(n8(s),s.status);let n;try{n=await s.json()}catch(i){throw new USt(n8(i),i)}let r;const a=Jcs(s);if(a&&a.getTime()>=$St["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 Wrt(n8(n),s.status,((t=n.weak_password)===null||t===void 0?void 0:t.reasons)||[]);if(r==="session_not_found")throw new wA}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 Wrt(n8(n),s.status,n.weak_password.reasons);throw new Lcs(n8(n),s.status||500,r)}const rds=(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 nd(s,t,n,r){var a;const i=Object.assign({},r==null?void 0:r.headers);i[fFe]||(i[fFe]=$St["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 ads(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 ads(s,t,n,r,a,i){const l=rds(t,r,a,i);let o;try{o=await s(n,Object.assign({},l))}catch(c){throw console.error(c),new xFe(n8(c),0)}if(o.ok||await Xrt(o),r!=null&&r.noResolveJson)return o;try{return await o.json()}catch(c){await Xrt(c)}}function jA(s){var t;let n=null;cds(s)&&(n=Object.assign({},s),s.expires_at||(n.expires_at=Ucs(s.expires_in)));const r=(t=s.user)!==null&&t!==void 0?t:s;return{data:{session:n,user:r},error:null}}function Qrt(s){const t=jA(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 QA(s){var t;return{data:{user:(t=s.user)!==null&&t!==void 0?t:s},error:null}}function ids(s){return{data:s,error:null}}function ods(s){const{action_link:t,email_otp:n,hashed_token:r,redirect_to:a,verification_type:i}=s,l=sds(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 lds(s){return s}function cds(s){return s.access_token&&s.refresh_token&&s.expires_in}var dds=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(x=>{const g=parseInt(x.split(";")[0].split("=")[1].substring(0,1)),y=JSON.parse(x.split(";")[1].split("=")[1]);d[`${y}Page`]=g}),d.total=parseInt(m)),{data:Object.assign(Object.assign({},h),d),error:null}}catch(d){if(uc(d))return{data:{users:[]},error:d};throw d}}async getUserById(t){try{return await nd(this.fetch,"GET",`${this.url}/admin/users/${t}`,{headers:this.headers,xform:QA})}catch(n){if(uc(n))return{data:{user:null},error:n};throw n}}async updateUserById(t,n){try{return await nd(this.fetch,"PUT",`${this.url}/admin/users/${t}`,{body:n,headers:this.headers,xform:QA})}catch(r){if(uc(r))return{data:{user:null},error:r};throw r}}async deleteUser(t,n=!1){try{return await nd(this.fetch,"DELETE",`${this.url}/admin/users/${t}`,{headers:this.headers,body:{should_soft_delete:n},xform:QA})}catch(r){if(uc(r))return{data:{user:null},error:r};throw r}}async _listFactors(t){try{const{data:n,error:r}=await nd(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(uc(n))return{data:null,error:n};throw n}}async _deleteFactor(t){try{return{data:await nd(this.fetch,"DELETE",`${this.url}/admin/users/${t.userId}/factors/${t.id}`,{headers:this.headers}),error:null}}catch(n){if(uc(n))return{data:null,error:n};throw n}}}const hds={getItem:s=>dY()?globalThis.localStorage.getItem(s):null,setItem:(s,t)=>{dY()&&globalThis.localStorage.setItem(s,t)},removeItem:s=>{dY()&&globalThis.localStorage.removeItem(s)}};function Jrt(s={}){return{getItem:t=>s[t]||null,setItem:(t,n)=>{s[t]=n},removeItem:t=>{delete s[t]}}}function mds(){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 f7={debug:!!(globalThis&&dY()&&globalThis.localStorage&&globalThis.localStorage.getItem("supabase.gotrue-js.locks.debug")==="true")};class GSt extends Error{constructor(t){super(t),this.isAcquireTimeout=!0}}class pds extends GSt{}async function fds(s,t,n){f7.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquire lock",s,t);const r=new globalThis.AbortController;return t>0&&setTimeout(()=>{r.abort(),f7.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){f7.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquired",s,a.name);try{return await n()}finally{f7.debug&&console.log("@supabase/gotrue-js: navigatorLock: released",s,a.name)}}else{if(t===0)throw f7.debug&&console.log("@supabase/gotrue-js: navigatorLock: not immediately available",s),new pds(`Acquiring an exclusive Navigator LockManager lock "${s}" immediately failed`);if(f7.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()}}))}mds();const xds={url:Ccs,storageKey:Acs,autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,headers:Ecs,flowType:"implicit",debug:!1,hasCustomAuthorizationHeader:!1};async function eat(s,t,n){return await n()}class OZ{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=OZ.nextInstanceID,OZ.nextInstanceID+=1,this.instanceID>0&&Yk()&&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({},xds),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 uds({url:a.url,headers:a.headers,fetch:a.fetch}),this.url=a.url,this.headers=a.headers,this.fetch=VSt(a.fetch),this.lock=a.lock||eat,this.detectSessionInUrl=a.detectSessionInUrl,this.flowType=a.flowType,this.hasCustomAuthorizationHeader=a.hasCustomAuthorizationHeader,a.lock?this.lock=a.lock:Yk()&&(!((n=globalThis==null?void 0:globalThis.navigator)===null||n===void 0)&&n.locks)?this.lock=fds:this.lock=eat,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:dY()?this.storage=hds:(this.memoryStorage={},this.storage=Jrt(this.memoryStorage)):(this.memoryStorage={},this.storage=Jrt(this.memoryStorage)),Yk()&&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} (${BSt}) ${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=Vcs(window.location.href);let r="none";if(this._isImplicitGrantCallback(n)?r="implicit":await this._isPKCECallback(n)&&(r="pkce"),Yk()&&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),Dcs(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 uc(n)?{error:n}:{error:new USt("Unexpected error during initialization",n)}}finally{await this._handleVisibilityChange(),this._debug("#_initialize()","end")}}async signInAnonymously(t){var n,r,a;try{const i=await nd(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:jA}),{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(uc(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,x=null;this.flowType==="pkce"&&([p,x]=await p7(this.storage,this.storageKey)),i=await nd(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:x},xform:jA})}else if("phone"in t){const{phone:u,password:h,options:m}=t;i=await nd(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:jA})}else throw new pne("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(uc(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 nd(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:Qrt})}else if("phone"in t){const{phone:i,password:l,options:o}=t;n=await nd(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:Qrt})}else throw new pne("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 ELe}:(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(uc(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 xne(this.storage,`${this.storageKey}-code-verifier`),[r,a]=(n??"").split("/");try{const{data:i,error:l}=await nd(this.fetch,"POST",`${this.url}/token?grant_type=pkce`,{headers:this.headers,body:{auth_code:t,code_verifier:r},xform:jA});if(await gne(this.storage,`${this.storageKey}-code-verifier`),l)throw l;return!i||!i.session||!i.user?{data:{user:null,session:null,redirectType:null},error:new ELe}:(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(uc(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 nd(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:jA}),{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 ELe}:(c.session&&(await this._saveSession(c.session),await this._notifyAllSubscribers("SIGNED_IN",c.session)),{data:c,error:d})}catch(n){if(uc(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 p7(this.storage,this.storageKey));const{error:h}=await nd(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 nd(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 pne("You must provide either an email or phone number.")}catch(o){if(uc(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 nd(this.fetch,"POST",`${this.url}/verify`,{headers:this.headers,body:Object.assign(Object.assign({},t),{gotrue_meta_security:{captcha_token:i}}),redirectTo:a,xform:jA});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(uc(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 p7(this.storage,this.storageKey)),await nd(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:ids})}catch(i){if(uc(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 wA;const{error:a}=await nd(this.fetch,"GET",`${this.url}/reauthenticate`,{headers:this.headers,jwt:n.access_token});return{data:{user:null,session:null},error:a}})}catch(t){if(uc(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 nd(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 nd(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 pne("You must provide either an email or phone number and a type")}catch(n){if(uc(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 xne(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 nd(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:t,xform:QA}):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 wA}:await nd(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:QA})})}catch(n){if(uc(n))return Ics(n)&&(await this._removeSession(),await gne(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 wA;const l=a.session;let o=null,c=null;this.flowType==="pkce"&&t.email!=null&&([o,c]=await p7(this.storage,this.storageKey));const{data:d,error:u}=await nd(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:QA});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(uc(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 wA;const n=Date.now()/1e3;let r=n,a=!0,i=null;const{payload:l}=MLe(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(uc(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 wA;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(uc(n))return{data:{user:null,session:null},error:n};throw n}}async _getSessionFromURL(t,n){try{if(!Yk())throw new fne("No browser detected.");if(t.error||t.error_description||t.error_code)throw new fne(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 Grt("Not a valid PKCE flow url.");break;case"pkce":if(this.flowType==="implicit")throw new fne("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 Grt("No code detected.");const{data:v,error:N}=await this._exchangeCodeForSession(t.code);if(N)throw N;const C=new URL(window.location.href);return C.searchParams.delete("code"),window.history.replaceState(window.history.state,"",C.toString()),{data:{session:v.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 fne("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<=o9&&console.warn(`@supabase/gotrue-js: Session as retrieved from URL expires in ${p}s, should have been closer to ${h}s`);const x=m-h;u-x>=120?console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued over 120s ago, URL could be stale",x,m,u):u-x<0&&console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued in the future? Check the device clock for skew",x,m,u);const{data:g,error:y}=await this._getUser(i);if(y)throw y;const b={provider_token:r,provider_refresh_token:a,access_token:i,expires_in:h,expires_at:m,refresh_token:l,token_type:d,user:g.user};return window.location.hash="",this._debug("#_getSessionFromURL()","clearing window.location.hash"),{data:{session:b,redirectType:t.type},error:null}}catch(r){if(uc(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 xne(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&&!(Pcs(o)&&(o.status===404||o.status===401||o.status===403)))return{error:o}}return t!=="others"&&(await this._removeSession(),await gne(this.storage,`${this.storageKey}-code-verifier`)),{error:null}})}onAuthStateChange(t){const n=qcs(),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 p7(this.storage,this.storageKey,!0));try{return await nd(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(uc(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(uc(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 nd(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 Yk()&&!(!((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(uc(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 nd(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(uc(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 Wcs(async a=>(a>0&&await Gcs(200*Math.pow(2,a-1)),this._debug(n,"refreshing attempt",a),await nd(this.fetch,"POST",`${this.url}/token?grant_type=refresh_token`,{body:{refresh_token:t},headers:this.headers,xform:jA})),(a,i)=>{const l=200*Math.pow(2,a);return i&&TLe(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(),o9);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)/o9);this._debug("#_autoRefreshTokenTick()",`access token expires in ${a} ticks, a tick lasts ${o9}ms, refresh threshold is ${pFe} ticks`),a<=pFe&&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 GSt)this._debug("auto refresh token tick lock not available");else throw t}}async _handleVisibilityChange(){if(this._debug("#_handleVisibilityChange()"),!Yk()||!(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 p7(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 nd(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(uc(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 nd(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(uc(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 nd(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(uc(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 nd(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(uc(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}=MLe(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+Mcs>Date.now()))return r;const{data:a,error:i}=await nd(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 cY("JWKS is empty");if(this.jwks=a,this.jwks_cached_at=Date.now(),r=a.keys.find(l=>l.kid===t),!r)throw new cY("No matching signing key found in JWKS");return r}async getClaims(t,n={keys:[]}){try{let r=t;if(!r){const{data:p,error:x}=await this.getSession();if(x||!p.session)return{data:null,error:x};r=p.session.access_token}const{header:a,payload:i,signature:l,raw:{header:o,payload:c}}=MLe(r);if(eds(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=tds(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,$cs(`${o}.${c}`)))throw new cY("Invalid JWT signature");return{data:{claims:i,header:a,signature:l},error:null}}catch(r){if(uc(r))return{data:null,error:r};throw r}}}OZ.nextInstanceID=0;const gds=OZ;class yds extends gds{constructor(t){super(t)}}var vds=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 bds{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=kcs(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:gcs,realtime:vcs,auth:Object.assign(Object.assign({},ycs),{storageKey:d}),global:xcs},h=Scs(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=jcs(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 zls(new URL("rest/v1",c).href,{headers:this.headers,schema:h.db.schema,fetch:this.fetch}),h.accessToken||this._listenForAuthEvents()}get functions(){return new fls(this.functionsUrl.href,{headers:this.headers,customFetch:this.fetch})}get storage(){return new mcs(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 vds(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 yds({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 Jls(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 _ds=(s,t,n)=>new bds(s,t,n);function wds(){var y,b;if(typeof window>"u")return;const s=location.hostname,n=["lovableproject.com","lovableproject-dev.com","lovable.app","gpt-eng.com","gptengineer.run"].some(v=>s===v||s.endsWith("."+v)),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])??((b=s.match(new RegExp("^("+r+")(?=[.-])","i")))==null?void 0:b[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=(v,N,C)=>new Promise(A=>{const T=m();let P=!1,M;const I=q=>{P||(P=!0,clearTimeout(M),window.removeEventListener("message",D),A(q))},D=q=>{if(d.indexOf(q.origin)<0)return;const W=q.data;W&&W.type===u&&W.requestId===T&&I(W)};window.addEventListener("message",D);const B={type:v,requestId:T,projectId:a,key:N};C!==void 0&&(B.value=C);for(const q of d)window.parent.postMessage(B,q);M=setTimeout(()=>I(null),h)});let x=!0;const g=250;return{getItem:async v=>{let N=await p("lovable-preview-auth:get",v);return!N&&x&&(await new Promise(C=>setTimeout(C,g)),N=await p("lovable-preview-auth:get",v)),x=!1,N&&N.ok&&typeof N.value=="string"?N.value===""?(localStorage.removeItem(v),null):N.value:localStorage.getItem(v)},setItem:(v,N)=>(localStorage.setItem(v,N),p("lovable-preview-auth:set",v,N).then(()=>{})),removeItem:v=>(localStorage.removeItem(v),p("lovable-preview-auth:remove",v).then(()=>{}))}}const jds="https://relzejiswnotikjgvjhz.supabase.co",Nds="eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6InJlbHplamlzd25vdGlramd2amh6Iiwicm9sZSI6ImFub24iLCJpYXQiOjE3NjE5NTAzNDQsImV4cCI6MjA3NzUyNjM0NH0.dzIkIr_oFSbFE3oWS0ktIr83iKHHkZxt40Gc7SpC_mM",U=_ds(jds,Nds,{auth:{storage:wds(),persistSession:!0,autoRefreshToken:!0}}),kds=Object.freeze(Object.defineProperty({__proto__:null,supabase:U},Symbol.toStringTag,{value:"Module"})),WSt=j.createContext(void 0),Sds=({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,x]=j.useState(!1),[g,y]=j.useState(null),[b,v]=j.useState([]),[N,C]=j.useState(null),A=j.useRef(null),T=j.useRef(!1),P=j.useRef(!1),M=Vn(),I=()=>{u(!1),m(!1),x(!1),y(null),v([]),C(null),A.current=null,T.current=!1},D=async V=>{if(!(T.current&&A.current===V)&&!P.current){P.current=!0,c(!0);try{console.log("Checking roles via RPC for user:",V);const[{data:K,error:Q},{data:J,error:ce},{data:ue,error:ne}]=await Promise.all([U.rpc("has_role",{_user_id:V,_role:"admin"}),U.rpc("has_role",{_user_id:V,_role:"brokerage_manager"}),U.rpc("has_role",{_user_id:V,_role:"coach"})]);if(Q||ce)console.error("Role RPC errors:",{isAdminError:Q,isBrokerError:ce,isCoachError:ne}),u(!1),m(!1),x(!1);else{const he=!!K,ve=!!J,ge=!!ue;console.log("RPC roles result:",{adminValue:he,brokerValue:ve,coachValue:ge}),u(he),m(ve),x(ge)}const{data:ee,error:le}=await U.from("profiles").select("brokerage_id").eq("id",V).single();if(y(!le&&ee?ee.brokerage_id:null),J){console.log("Fetching managed brokerages for user:",V);const{data:he,error:ve}=await U.from("brokerage_manager_assignments").select("brokerage_id").eq("user_id",V);if(console.log("Managed brokerage assignments result:",{assignments:he,assignmentsError:ve}),ve||!he){console.error("Error fetching managed brokerage assignments:",ve),v([]);return}const ge=Array.from(new Set(he.map(Me=>Me.brokerage_id).filter(Boolean)));if(ge.length===0){v([]);return}const{data:fe,error:je}=await U.from("brokerages").select("id, name").in("id",ge);if(console.log("Managed brokerages details result:",{brokeragesData:fe,brokeragesError:je}),je||!fe){console.error("Error fetching managed brokerages details:",je),v([]);return}const Ee=fe.map(Me=>({id:Me.id,name:Me.name})).sort((Me,De)=>ge.indexOf(Me.id)-ge.indexOf(De.id));console.log("Parsed managed brokerages:",Ee),v(Ee),Ee.length>0&&C(Me=>Me??Ee[0].id)}else console.log("User is not a brokerage manager, skipping managed brokerages fetch"),v([]);A.current=V,T.current=!0}catch(K){console.error("Unexpected error in checkRoles:",K),I()}finally{P.current=!1,c(!1)}}};j.useEffect(()=>{let V=!0,K=!1;const Q=()=>{!V||K||(K=!0,l(!1))},{data:{subscription:J}}=U.auth.onAuthStateChange((ne,ee)=>{console.log("Auth event:",ne),V&&(a(ee),n((ee==null?void 0:ee.user)??null),Q(),ne==="PASSWORD_RECOVERY"&&(console.log("Password recovery detected, redirecting to profile"),setTimeout(()=>{M("/profile?reset=true")},100)),ee!=null&&ee.user?(!T.current||A.current!==ee.user.id)&&setTimeout(()=>{D(ee.user.id)},0):(I(),c(!1)))}),ce=window.setTimeout(()=>{console.warn("Auth initialization timeout reached. Continuing without blocking UI."),Q()},4e3);return(async()=>{try{const{data:{session:ne}}=await U.auth.getSession();if(!V)return;a(ne),n((ne==null?void 0:ne.user)??null),ne!=null&&ne.user?await D(ne.user.id):I()}catch(ne){console.error("Error restoring auth session:",ne),V&&(a(null),n(null),I())}finally{Q()}})(),()=>{V=!1,window.clearTimeout(ce),J.unsubscribe()}},[]);const B=async(V,K)=>{const{error:Q}=await U.auth.signInWithPassword({email:V,password:K});if(Q)throw ae.error(Q.message),Q;ae.success("Welcome back!")},q=async(V,K,Q)=>{var ee;const J=`${window.location.origin}/dashboard`,ce=localStorage.getItem("levelup_referral_code")||null,{data:ue,error:ne}=await U.auth.signUp({email:V,password:K,options:{emailRedirectTo:J,data:{name:Q,referred_by_code:ce}}});if(ne)throw ae.error(ne.message),ne;if(ce&&((ee=ue.user)!=null&&ee.id))try{await U.from("profiles").update({referred_by_code:ce}).eq("id",ue.user.id),localStorage.removeItem("levelup_referral_code")}catch(le){console.warn("Failed to attach referral code to profile",le)}ae.success("Account created! Welcome to LevelUp."),M("/dashboard")},W=async()=>{try{const{data:{session:V}}=await U.auth.getSession();if(V){const{error:K}=await U.auth.signOut();K?K.message==="Auth session missing!"?console.warn("Sign out warning (ignored):",K.message):(console.error("Sign out error:",K),ae.error(K.message)):ae.success("Signed out successfully")}else console.log("No active session found, redirecting to auth");n(null),a(null),u(!1),m(!1),y(null),v([]),C(null),M("/auth")}catch(V){console.error("Unexpected sign out error:",V),M("/auth")}};return e.jsx(WSt.Provider,{value:{user:t,session:r,loading:i,rolesLoading:o,signIn:B,signUp:q,signOut:W,isAdmin:d,isBrokerageManager:h,isCoach:p,brokerageId:g,managedBrokerages:b,selectedBrokerageId:N,setSelectedBrokerageId:C},children:s})},_s=()=>{const s=j.useContext(WSt);if(s===void 0)throw new Error("useAuth must be used within an AuthProvider");return s},KSt=j.createContext({onlineUsers:[],totalOnline:0}),Cds=3*60*1e3,Ads=45*1e3,Eds=30*1e3,Tds=({children:s})=>{const{user:t,brokerageId:n,isAdmin:r}=_s(),[a,i]=j.useState([]),l=j.useRef(new Date().toISOString()),o=j.useCallback(async()=>{t&&await U.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()-Cds).toISOString(),{data:h}=await U.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(g=>g.user_id),{data:p}=await U.from("profiles").select("id, name, email, avatar_url, brokerage_id").in("id",m),x=new Map((p||[]).map(g=>[g.id,g]));i(h.map(g=>{var b;const y=x.get(g.user_id);return{id:g.user_id,name:(y==null?void 0:y.name)||((b=y==null?void 0:y.email)==null?void 0:b.split("@")[0])||"Member",avatarUrl:(y==null?void 0:y.avatar_url)||void 0,brokerageId:(y==null?void 0:y.brokerage_id)||void 0,onlineSince:g.online_since||g.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()},Ads),p=window.setInterval(()=>{c()},Eds),x=()=>{document.visibilityState==="visible"&&h()};return document.addEventListener("visibilitychange",x),()=>{u=!0,window.clearInterval(m),window.clearInterval(p),document.removeEventListener("visibilitychange",x)}},[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(KSt.Provider,{value:{onlineUsers:d,totalOnline:d.length},children:s})},YSt=()=>j.useContext(KSt),ZSt=j.createContext(void 0),DM="levelup_admin_session",tA="levelup_impersonation",LLe="levelup_impersonation_return",Mds=({children:s})=>{const[t,n]=j.useState(!1),[r,a]=j.useState(null),[i,l]=j.useState(!1);j.useEffect(()=>{const d=sessionStorage.getItem(tA);if(d)try{const u=JSON.parse(d);n(!0),a(u)}catch{sessionStorage.removeItem(tA)}},[]);const o=async(d,u)=>{l(!0);try{const{data:{session:h}}=await U.auth.getSession();if(!h)return ae.error("No active session found"),!1;const m={access_token:h.access_token,refresh_token:h.refresh_token};sessionStorage.setItem(DM,JSON.stringify(m)),u&&sessionStorage.setItem(LLe,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})}),x=await p.json();if(!p.ok)throw new Error(x.error||"Failed to impersonate user");const g={id:x.targetUser.id,name:x.targetUser.name,email:x.targetUser.email};if(sessionStorage.setItem(tA,JSON.stringify(g)),x.method==="session"){const{error:y}=await U.auth.setSession({access_token:x.access_token,refresh_token:x.refresh_token});if(y)throw console.error("Set session error:",y),sessionStorage.removeItem(DM),sessionStorage.removeItem(tA),new Error("Failed to establish impersonation session")}else{const y=x.type||"recovery",{error:b}=await U.auth.verifyOtp({token_hash:x.token_hash,type:y});if(b)throw console.error("Verify OTP error:",b),sessionStorage.removeItem(DM),sessionStorage.removeItem(tA),new Error("Failed to establish impersonation session")}return n(!0),a(g),ae.success(`Now viewing as ${g.name}`),window.location.href="/dashboard",!0}catch(h){return console.error("Impersonation error:",h),ae.error(h.message||"Failed to impersonate user"),sessionStorage.removeItem(DM),sessionStorage.removeItem(tA),!1}finally{l(!1)}},c=async()=>{l(!0);try{const d=sessionStorage.getItem(DM);if(!d){await U.auth.signOut(),window.location.href="/auth";return}const u=JSON.parse(d);await U.auth.signOut();const{error:h}=await U.auth.setSession({access_token:u.access_token,refresh_token:u.refresh_token});if(sessionStorage.removeItem(DM),sessionStorage.removeItem(tA),h){console.error("Failed to restore admin session:",h),ae.error("Admin session expired, please sign in again"),window.location.href="/auth";return}n(!1),a(null),ae.success("Returned to your account");const m=sessionStorage.getItem(LLe)||"/admin/members";sessionStorage.removeItem(LLe),window.location.href=m}catch(d){console.error("Stop impersonation error:",d),ae.error("Failed to restore admin session"),sessionStorage.removeItem(DM),sessionStorage.removeItem(tA),window.location.href="/auth"}finally{l(!1)}};return e.jsx(ZSt.Provider,{value:{isImpersonating:t,impersonatedUser:r,startImpersonation:o,stopImpersonation:c,isLoading:i},children:s})},aCe=()=>{const s=j.useContext(ZSt);if(s===void 0)throw new Error("useImpersonation must be used within an ImpersonationProvider");return s},Lds=()=>{const{isImpersonating:s,impersonatedUser:t,stopImpersonation:n,isLoading:r}=aCe();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(mc,{className:"h-5 w-5 flex-shrink-0"}),e.jsxs("span",{className:"font-medium text-sm md:text-base",children:[e.jsx("span",{className:"hidden sm:inline",children:"You are viewing as "}),e.jsx("strong",{children:t.name}),e.jsxs("span",{className:"hidden md:inline text-amber-800",children:[" (",t.email,")"]})]})]}),e.jsx($,{size:"sm",variant:"secondary",onClick:n,disabled:r,className:"bg-amber-100 hover:bg-amber-200 text-amber-950 border-0",children:r?e.jsx(Ht,{className:"h-4 w-4 animate-spin"}):e.jsxs(e.Fragment,{children:[e.jsx(pr,{className:"h-4 w-4 mr-1"}),e.jsx("span",{className:"hidden sm:inline",children:"Exit Impersonation"}),e.jsx("span",{className:"sm:hidden",children:"Exit"})]})})]})})},XSt=j.createContext(void 0),x7="levelup_acting_as",yne="levelup_acting_as_self",Pds=({children:s})=>{const{user:t}=_s(),[n,r]=j.useState(!1),[a,i]=j.useState([]),[l,o]=j.useState(null),[c,d]=j.useState({}),[u,h]=j.useState(!0),[m,p]=j.useState(()=>sessionStorage.getItem(yne)==="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 U.rpc("has_role",{_user_id:t.id,_role:"assistant"});if(!N){r(!1),i([]),o(null),d({}),h(!1);return}r(!0);const{data:C,error:A}=await U.from("agent_assistant_assignments").select("agent_id, permissions").eq("assistant_id",t.id);if(A||!C||C.length===0){i([]),h(!1);return}const T=C.map(I=>I.agent_id),{data:P}=await U.from("profiles").select("id, name, email, avatar_url").in("id",T),M=(P||[]).map(I=>({id:I.id,name:I.name||I.email||"Unknown",email:I.email||"",avatar_url:I.avatar_url}));if(i(M),sessionStorage.getItem(yne)==="true")p(!0),o(null),d({});else{const I=sessionStorage.getItem(x7);if(I){const D=M.find(B=>B.id===I);if(D){o(D);const B=C.find(q=>q.agent_id===I);d((B==null?void 0:B.permissions)||{})}else if(M.length>0){o(M[0]);const B=C.find(q=>q.agent_id===M[0].id);d((B==null?void 0:B.permissions)||{}),sessionStorage.setItem(x7,M[0].id)}}else if(M.length>0){o(M[0]);const D=C.find(B=>B.agent_id===M[0].id);d((D==null?void 0:D.permissions)||{}),sessionStorage.setItem(x7,M[0].id)}}}catch(N){console.error("Error loading assistant data:",N)}finally{h(!1)}})()},[t==null?void 0:t.id]);const x=v=>{o(v),p(!1),sessionStorage.removeItem(yne),v?(sessionStorage.setItem(x7,v.id),U.from("agent_assistant_assignments").select("permissions").eq("assistant_id",(t==null?void 0:t.id)||"").eq("agent_id",v.id).single().then(({data:N})=>{d((N==null?void 0:N.permissions)||{})})):(sessionStorage.removeItem(x7),d({}))},g=()=>{p(!0),o(null),d({}),sessionStorage.setItem(yne,"true"),sessionStorage.removeItem(x7)},y=v=>!n||m?!0:c[v]===!0,b=n&&l&&!m?l.id:(t==null?void 0:t.id)||null;return e.jsx(XSt.Provider,{value:{isAssistant:n,assignedAgents:a,actingAsAgent:l,setActingAsAgent:x,effectiveUserId:b,permissions:c,hasPermission:y,isLoading:u,isActingAsSelf:m,setActingAsSelf:g},children:s})},aee=()=>{const s=j.useContext(XSt);if(s===void 0)throw new Error("useActingAs must be used within an ActingAsProvider");return s},Za=()=>{const{effectiveUserId:s}=aee();return s};var QSt={exports:{}},JSt={};/** * @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 Z$=j;function Ids(s,t){return s===t&&(s!==0||1/s===1/t)||s!==s&&t!==t}var Dds=typeof Object.is=="function"?Object.is:Ids,Rds=Z$.useState,Ods=Z$.useEffect,Fds=Z$.useLayoutEffect,zds=Z$.useDebugValue;function Bds(s,t){var n=t(),r=Rds({inst:{value:n,getSnapshot:t}}),a=r[0].inst,i=r[1];return Fds(function(){a.value=n,a.getSnapshot=t,PLe(a)&&i({inst:a})},[s,n,t]),Ods(function(){return PLe(a)&&i({inst:a}),s(function(){PLe(a)&&i({inst:a})})},[s]),zds(n),n}function PLe(s){var t=s.getSnapshot;s=s.value;try{var n=t();return!Dds(s,n)}catch{return!0}}function $ds(s,t){return t()}var Uds=typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"?$ds:Bds;JSt.useSyncExternalStore=Z$.useSyncExternalStore!==void 0?Z$.useSyncExternalStore:Uds;QSt.exports=JSt;var qds=QSt.exports;function Vds(){return qds.useSyncExternalStore(Hds,()=>!0,()=>!1)}function Hds(){return()=>{}}var TVe="Avatar",[Gds,CXn]=ip(TVe),[Wds,e5t]=Gds(TVe),t5t=j.forwardRef((s,t)=>{const{__scopeAvatar:n,...r}=s,[a,i]=j.useState("idle");return e.jsx(Wds,{scope:n,imageLoadingStatus:a,onImageLoadingStatusChange:i,children:e.jsx(Ka.span,{...r,ref:t})})});t5t.displayName=TVe;var s5t="AvatarImage",n5t=j.forwardRef((s,t)=>{const{__scopeAvatar:n,src:r,onLoadingStatusChange:a=()=>{},...i}=s,l=e5t(s5t,n),o=Kds(r,i),c=bf(d=>{a(d),l.onImageLoadingStatusChange(d)});return Sf(()=>{o!=="idle"&&c(o)},[o,c]),o==="loaded"?e.jsx(Ka.img,{...i,ref:t,src:r}):null});n5t.displayName=s5t;var r5t="AvatarFallback",a5t=j.forwardRef((s,t)=>{const{__scopeAvatar:n,delayMs:r,...a}=s,i=e5t(r5t,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(Ka.span,{...a,ref:t}):null});a5t.displayName=r5t;function tat(s,t){return s?t?(s.src!==t&&(s.src=t),s.complete&&s.naturalWidth>0?"loaded":"loading"):"error":"idle"}function Kds(s,{referrerPolicy:t,crossOrigin:n}){const r=Vds(),a=j.useRef(null),i=r?(a.current||(a.current=new window.Image),a.current):null,[l,o]=j.useState(()=>tat(i,s));return Sf(()=>{o(tat(i,s))},[i,s]),Sf(()=>{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 i5t=t5t,o5t=n5t,l5t=a5t;const Ea=j.forwardRef(({className:s,...t},n)=>e.jsx(i5t,{ref:n,className:Tt("relative flex h-10 w-10 shrink-0 overflow-hidden rounded-full",s),...t}));Ea.displayName=i5t.displayName;const ki=j.forwardRef(({className:s,...t},n)=>e.jsx(o5t,{ref:n,className:Tt("aspect-square h-full w-full",s),...t}));ki.displayName=o5t.displayName;const Ta=j.forwardRef(({className:s,...t},n)=>e.jsx(l5t,{ref:n,className:Tt("flex h-full w-full items-center justify-center rounded-full bg-muted",s),...t}));Ta.displayName=l5t.displayName;const Yds=GO("inline-flex items-center rounded-full border px-2.5 py-0.5 text-xs font-semibold transition-colors focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2",{variants:{variant:{default:"border-transparent bg-primary text-primary-foreground hover:bg-primary/80",secondary:"border-transparent bg-secondary text-secondary-foreground hover:bg-secondary/80",destructive:"border-transparent bg-destructive text-destructive-foreground hover:bg-destructive/80",outline:"text-foreground"}},defaultVariants:{variant:"default"}});function $e({className:s,variant:t,...n}){return e.jsx("div",{className:Tt(Yds({variant:t}),s),...n})}var Zds=j.createContext(void 0);function jC(s){const t=j.useContext(Zds);return s||t||"ltr"}var ILe="rovingFocusGroup.onEntryFocus",Xds={bubbles:!1,cancelable:!0},iee="RovingFocusGroup",[gFe,c5t,Qds]=uq(iee),[Jds,k6]=ip(iee,[Qds]),[eus,tus]=Jds(iee),d5t=j.forwardRef((s,t)=>e.jsx(gFe.Provider,{scope:s.__scopeRovingFocusGroup,children:e.jsx(gFe.Slot,{scope:s.__scopeRovingFocusGroup,children:e.jsx(sus,{...s,ref:t})})}));d5t.displayName=iee;var sus=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=Po(t,m),x=jC(i),[g,y]=Ux({prop:l,defaultProp:o??null,onChange:c,caller:iee}),[b,v]=j.useState(!1),N=bf(d),C=c5t(n),A=j.useRef(!1),[T,P]=j.useState(0);return j.useEffect(()=>{const M=m.current;if(M)return M.addEventListener(ILe,N),()=>M.removeEventListener(ILe,N)},[N]),e.jsx(eus,{scope:n,orientation:r,dir:x,loop:a,currentTabStopId:g,onItemFocus:j.useCallback(M=>y(M),[y]),onItemShiftTab:j.useCallback(()=>v(!0),[]),onFocusableItemAdd:j.useCallback(()=>P(M=>M+1),[]),onFocusableItemRemove:j.useCallback(()=>P(M=>M-1),[]),children:e.jsx(Ka.div,{tabIndex:b||T===0?-1:0,"data-orientation":r,...h,ref:p,style:{outline:"none",...s.style},onMouseDown:xa(s.onMouseDown,()=>{A.current=!0}),onFocus:xa(s.onFocus,M=>{const I=!A.current;if(M.target===M.currentTarget&&I&&!b){const D=new CustomEvent(ILe,Xds);if(M.currentTarget.dispatchEvent(D),!D.defaultPrevented){const B=C().filter(Q=>Q.focusable),q=B.find(Q=>Q.active),W=B.find(Q=>Q.id===g),K=[q,W,...B].filter(Boolean).map(Q=>Q.ref.current);m5t(K,u)}}A.current=!1}),onBlur:xa(s.onBlur,()=>v(!1))})})}),u5t="RovingFocusGroupItem",h5t=j.forwardRef((s,t)=>{const{__scopeRovingFocusGroup:n,focusable:r=!0,active:a=!1,tabStopId:i,children:l,...o}=s,c=Fx(),d=i||c,u=tus(u5t,n),h=u.currentTabStopId===d,m=c5t(n),{onFocusableItemAdd:p,onFocusableItemRemove:x,currentTabStopId:g}=u;return j.useEffect(()=>{if(r)return p(),()=>x()},[r,p,x]),e.jsx(gFe.ItemSlot,{scope:n,id:d,focusable:r,active:a,children:e.jsx(Ka.span,{tabIndex:h?0:-1,"data-orientation":u.orientation,...o,ref:t,onMouseDown:xa(s.onMouseDown,y=>{r?u.onItemFocus(d):y.preventDefault()}),onFocus:xa(s.onFocus,()=>u.onItemFocus(d)),onKeyDown:xa(s.onKeyDown,y=>{if(y.key==="Tab"&&y.shiftKey){u.onItemShiftTab();return}if(y.target!==y.currentTarget)return;const b=aus(y,u.orientation,u.dir);if(b!==void 0){if(y.metaKey||y.ctrlKey||y.altKey||y.shiftKey)return;y.preventDefault();let N=m().filter(C=>C.focusable).map(C=>C.ref.current);if(b==="last")N.reverse();else if(b==="prev"||b==="next"){b==="prev"&&N.reverse();const C=N.indexOf(y.currentTarget);N=u.loop?ius(N,C+1):N.slice(C+1)}setTimeout(()=>m5t(N))}}),children:typeof l=="function"?l({isCurrentTabStop:h,hasTabStop:g!=null}):l})})});h5t.displayName=u5t;var nus={ArrowLeft:"prev",ArrowUp:"prev",ArrowRight:"next",ArrowDown:"next",PageUp:"first",Home:"first",PageDown:"last",End:"last"};function rus(s,t){return t!=="rtl"?s:s==="ArrowLeft"?"ArrowRight":s==="ArrowRight"?"ArrowLeft":s}function aus(s,t,n){const r=rus(s.key,n);if(!(t==="vertical"&&["ArrowLeft","ArrowRight"].includes(r))&&!(t==="horizontal"&&["ArrowUp","ArrowDown"].includes(r)))return nus[r]}function m5t(s,t=!1){const n=document.activeElement;for(const r of s)if(r===n||(r.focus({preventScroll:t}),document.activeElement!==n))return}function ius(s,t){return s.map((n,r)=>s[(t+r)%s.length])}var iCe=d5t,oCe=h5t,yFe=["Enter"," "],ous=["ArrowDown","PageUp","Home"],p5t=["ArrowUp","PageDown","End"],lus=[...ous,...p5t],cus={ltr:[...yFe,"ArrowRight"],rtl:[...yFe,"ArrowLeft"]},dus={ltr:["ArrowLeft"],rtl:["ArrowRight"]},oee="Menu",[FZ,uus,hus]=uq(oee),[KO,f5t]=ip(oee,[hus,M5,k6]),lCe=M5(),x5t=k6(),[mus,YO]=KO(oee),[pus,lee]=KO(oee),g5t=s=>{const{__scopeMenu:t,open:n=!1,children:r,dir:a,onOpenChange:i,modal:l=!0}=s,o=lCe(t),[c,d]=j.useState(null),u=j.useRef(!1),h=bf(i),m=jC(a);return j.useEffect(()=>{const p=()=>{u.current=!0,document.addEventListener("pointerdown",x,{capture:!0,once:!0}),document.addEventListener("pointermove",x,{capture:!0,once:!0})},x=()=>u.current=!1;return document.addEventListener("keydown",p,{capture:!0}),()=>{document.removeEventListener("keydown",p,{capture:!0}),document.removeEventListener("pointerdown",x,{capture:!0}),document.removeEventListener("pointermove",x,{capture:!0})}},[]),e.jsx(eee,{...o,children:e.jsx(mus,{scope:t,open:n,onOpenChange:h,content:c,onContentChange:d,children:e.jsx(pus,{scope:t,onClose:j.useCallback(()=>h(!1),[h]),isUsingKeyboardRef:u,dir:m,modal:l,children:r})})})};g5t.displayName=oee;var fus="MenuAnchor",MVe=j.forwardRef((s,t)=>{const{__scopeMenu:n,...r}=s,a=lCe(n);return e.jsx(yq,{...a,...r,ref:t})});MVe.displayName=fus;var LVe="MenuPortal",[xus,y5t]=KO(LVe,{forceMount:void 0}),v5t=s=>{const{__scopeMenu:t,forceMount:n,children:r,container:a}=s,i=YO(LVe,t);return e.jsx(xus,{scope:t,forceMount:n,children:e.jsx(dx,{present:n||i.open,children:e.jsx(hq,{asChild:!0,container:a,children:r})})})};v5t.displayName=LVe;var Zj="MenuContent",[gus,PVe]=KO(Zj),b5t=j.forwardRef((s,t)=>{const n=y5t(Zj,s.__scopeMenu),{forceMount:r=n.forceMount,...a}=s,i=YO(Zj,s.__scopeMenu),l=lee(Zj,s.__scopeMenu);return e.jsx(FZ.Provider,{scope:s.__scopeMenu,children:e.jsx(dx,{present:r||i.open,children:e.jsx(FZ.Slot,{scope:s.__scopeMenu,children:l.modal?e.jsx(yus,{...a,ref:t}):e.jsx(vus,{...a,ref:t})})})})}),yus=j.forwardRef((s,t)=>{const n=YO(Zj,s.__scopeMenu),r=j.useRef(null),a=Po(t,r);return j.useEffect(()=>{const i=r.current;if(i)return z3e(i)},[]),e.jsx(IVe,{...s,ref:a,trapFocus:n.open,disableOutsidePointerEvents:n.open,disableOutsideScroll:!0,onFocusOutside:xa(s.onFocusOutside,i=>i.preventDefault(),{checkForDefaultPrevented:!1}),onDismiss:()=>n.onOpenChange(!1)})}),vus=j.forwardRef((s,t)=>{const n=YO(Zj,s.__scopeMenu);return e.jsx(IVe,{...s,ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,disableOutsideScroll:!1,onDismiss:()=>n.onOpenChange(!1)})}),bus=QT("MenuContent.ScrollLock"),IVe=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:x,...g}=s,y=YO(Zj,n),b=lee(Zj,n),v=lCe(n),N=x5t(n),C=uus(n),[A,T]=j.useState(null),P=j.useRef(null),M=Po(t,P,y.onContentChange),I=j.useRef(0),D=j.useRef(""),B=j.useRef(0),q=j.useRef(null),W=j.useRef("right"),V=j.useRef(0),K=x?KJ:j.Fragment,Q=x?{as:bus,allowPinchZoom:!0}:void 0,J=ue=>{var je,Ee;const ne=D.current+ue,ee=C().filter(Me=>!Me.disabled),le=document.activeElement,he=(je=ee.find(Me=>Me.ref.current===le))==null?void 0:je.textValue,ve=ee.map(Me=>Me.textValue),ge=Lus(ve,ne,he),fe=(Ee=ee.find(Me=>Me.textValue===ge))==null?void 0:Ee.ref.current;(function Me(De){D.current=De,window.clearTimeout(I.current),De!==""&&(I.current=window.setTimeout(()=>Me(""),1e3))})(ne),fe&&setTimeout(()=>fe.focus())};j.useEffect(()=>()=>window.clearTimeout(I.current),[]),O3e();const ce=j.useCallback(ue=>{var ee,le;return W.current===((ee=q.current)==null?void 0:ee.side)&&Ius(ue,(le=q.current)==null?void 0:le.area)},[]);return e.jsx(gus,{scope:n,searchRef:D,onItemEnter:j.useCallback(ue=>{ce(ue)&&ue.preventDefault()},[ce]),onItemLeave:j.useCallback(ue=>{var ne;ce(ue)||((ne=P.current)==null||ne.focus(),T(null))},[ce]),onTriggerLeave:j.useCallback(ue=>{ce(ue)&&ue.preventDefault()},[ce]),pointerGraceTimerRef:B,onPointerGraceIntentChange:j.useCallback(ue=>{q.current=ue},[]),children:e.jsx(K,{...Q,children:e.jsx(WJ,{asChild:!0,trapped:a,onMountAutoFocus:xa(i,ue=>{var ne;ue.preventDefault(),(ne=P.current)==null||ne.focus({preventScroll:!0})}),onUnmountAutoFocus:l,children:e.jsx(j6,{asChild:!0,disableOutsidePointerEvents:o,onEscapeKeyDown:d,onPointerDownOutside:u,onFocusOutside:h,onInteractOutside:m,onDismiss:p,children:e.jsx(iCe,{asChild:!0,...N,dir:b.dir,orientation:"vertical",loop:r,currentTabStopId:A,onCurrentTabStopIdChange:T,onEntryFocus:xa(c,ue=>{b.isUsingKeyboardRef.current||ue.preventDefault()}),preventScrollOnEntryFocus:!0,children:e.jsx(tee,{role:"menu","aria-orientation":"vertical","data-state":R5t(y.open),"data-radix-menu-content":"",dir:b.dir,...v,...g,ref:M,style:{outline:"none",...g.style},onKeyDown:xa(g.onKeyDown,ue=>{const ee=ue.target.closest("[data-radix-menu-content]")===ue.currentTarget,le=ue.ctrlKey||ue.altKey||ue.metaKey,he=ue.key.length===1;ee&&(ue.key==="Tab"&&ue.preventDefault(),!le&&he&&J(ue.key));const ve=P.current;if(ue.target!==ve||!lus.includes(ue.key))return;ue.preventDefault();const fe=C().filter(je=>!je.disabled).map(je=>je.ref.current);p5t.includes(ue.key)&&fe.reverse(),Tus(fe)}),onBlur:xa(s.onBlur,ue=>{ue.currentTarget.contains(ue.target)||(window.clearTimeout(I.current),D.current="")}),onPointerMove:xa(s.onPointerMove,zZ(ue=>{const ne=ue.target,ee=V.current!==ue.clientX;if(ue.currentTarget.contains(ne)&&ee){const le=ue.clientX>V.current?"right":"left";W.current=le,V.current=ue.clientX}}))})})})})})})});b5t.displayName=Zj;var _us="MenuGroup",DVe=j.forwardRef((s,t)=>{const{__scopeMenu:n,...r}=s;return e.jsx(Ka.div,{role:"group",...r,ref:t})});DVe.displayName=_us;var wus="MenuLabel",_5t=j.forwardRef((s,t)=>{const{__scopeMenu:n,...r}=s;return e.jsx(Ka.div,{...r,ref:t})});_5t.displayName=wus;var Tke="MenuItem",sat="menu.itemSelect",cCe=j.forwardRef((s,t)=>{const{disabled:n=!1,onSelect:r,...a}=s,i=j.useRef(null),l=lee(Tke,s.__scopeMenu),o=PVe(Tke,s.__scopeMenu),c=Po(t,i),d=j.useRef(!1),u=()=>{const h=i.current;if(!n&&h){const m=new CustomEvent(sat,{bubbles:!0,cancelable:!0});h.addEventListener(sat,p=>r==null?void 0:r(p),{once:!0}),eVe(h,m),m.defaultPrevented?d.current=!1:l.onClose()}};return e.jsx(w5t,{...a,ref:c,disabled:n,onClick:xa(s.onClick,u),onPointerDown:h=>{var m;(m=s.onPointerDown)==null||m.call(s,h),d.current=!0},onPointerUp:xa(s.onPointerUp,h=>{var m;d.current||(m=h.currentTarget)==null||m.click()}),onKeyDown:xa(s.onKeyDown,h=>{const m=o.searchRef.current!=="";n||m&&h.key===" "||yFe.includes(h.key)&&(h.currentTarget.click(),h.preventDefault())})})});cCe.displayName=Tke;var w5t=j.forwardRef((s,t)=>{const{__scopeMenu:n,disabled:r=!1,textValue:a,...i}=s,l=PVe(Tke,n),o=x5t(n),c=j.useRef(null),d=Po(t,c),[u,h]=j.useState(!1),[m,p]=j.useState("");return j.useEffect(()=>{const x=c.current;x&&p((x.textContent??"").trim())},[i.children]),e.jsx(FZ.ItemSlot,{scope:n,disabled:r,textValue:a??m,children:e.jsx(oCe,{asChild:!0,...o,focusable:!r,children:e.jsx(Ka.div,{role:"menuitem","data-highlighted":u?"":void 0,"aria-disabled":r||void 0,"data-disabled":r?"":void 0,...i,ref:d,onPointerMove:xa(s.onPointerMove,zZ(x=>{r?l.onItemLeave(x):(l.onItemEnter(x),x.defaultPrevented||x.currentTarget.focus({preventScroll:!0}))})),onPointerLeave:xa(s.onPointerLeave,zZ(x=>l.onItemLeave(x))),onFocus:xa(s.onFocus,()=>h(!0)),onBlur:xa(s.onBlur,()=>h(!1))})})})}),jus="MenuCheckboxItem",j5t=j.forwardRef((s,t)=>{const{checked:n=!1,onCheckedChange:r,...a}=s;return e.jsx(A5t,{scope:s.__scopeMenu,checked:n,children:e.jsx(cCe,{role:"menuitemcheckbox","aria-checked":Mke(n)?"mixed":n,...a,ref:t,"data-state":OVe(n),onSelect:xa(a.onSelect,()=>r==null?void 0:r(Mke(n)?!0:!n),{checkForDefaultPrevented:!1})})})});j5t.displayName=jus;var N5t="MenuRadioGroup",[Nus,kus]=KO(N5t,{value:void 0,onValueChange:()=>{}}),k5t=j.forwardRef((s,t)=>{const{value:n,onValueChange:r,...a}=s,i=bf(r);return e.jsx(Nus,{scope:s.__scopeMenu,value:n,onValueChange:i,children:e.jsx(DVe,{...a,ref:t})})});k5t.displayName=N5t;var S5t="MenuRadioItem",C5t=j.forwardRef((s,t)=>{const{value:n,...r}=s,a=kus(S5t,s.__scopeMenu),i=n===a.value;return e.jsx(A5t,{scope:s.__scopeMenu,checked:i,children:e.jsx(cCe,{role:"menuitemradio","aria-checked":i,...r,ref:t,"data-state":OVe(i),onSelect:xa(r.onSelect,()=>{var l;return(l=a.onValueChange)==null?void 0:l.call(a,n)},{checkForDefaultPrevented:!1})})})});C5t.displayName=S5t;var RVe="MenuItemIndicator",[A5t,Sus]=KO(RVe,{checked:!1}),E5t=j.forwardRef((s,t)=>{const{__scopeMenu:n,forceMount:r,...a}=s,i=Sus(RVe,n);return e.jsx(dx,{present:r||Mke(i.checked)||i.checked===!0,children:e.jsx(Ka.span,{...a,ref:t,"data-state":OVe(i.checked)})})});E5t.displayName=RVe;var Cus="MenuSeparator",T5t=j.forwardRef((s,t)=>{const{__scopeMenu:n,...r}=s;return e.jsx(Ka.div,{role:"separator","aria-orientation":"horizontal",...r,ref:t})});T5t.displayName=Cus;var Aus="MenuArrow",M5t=j.forwardRef((s,t)=>{const{__scopeMenu:n,...r}=s,a=lCe(n);return e.jsx(see,{...a,...r,ref:t})});M5t.displayName=Aus;var Eus="MenuSub",[AXn,L5t]=KO(Eus),pW="MenuSubTrigger",P5t=j.forwardRef((s,t)=>{const n=YO(pW,s.__scopeMenu),r=lee(pW,s.__scopeMenu),a=L5t(pW,s.__scopeMenu),i=PVe(pW,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(MVe,{asChild:!0,...d,children:e.jsx(w5t,{id:a.triggerId,"aria-haspopup":"menu","aria-expanded":n.open,"aria-controls":a.contentId,"data-state":R5t(n.open),...s,ref:oC(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:xa(s.onPointerMove,zZ(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:xa(s.onPointerLeave,zZ(h=>{var p,x;u();const m=(p=n.content)==null?void 0:p.getBoundingClientRect();if(m){const g=(x=n.content)==null?void 0:x.dataset.side,y=g==="right",b=y?-5:5,v=m[y?"left":"right"],N=m[y?"right":"left"];i.onPointerGraceIntentChange({area:[{x:h.clientX+b,y:h.clientY},{x:v,y:m.top},{x:N,y:m.top},{x:N,y:m.bottom},{x:v,y:m.bottom}],side:g}),window.clearTimeout(o.current),o.current=window.setTimeout(()=>i.onPointerGraceIntentChange(null),300)}else{if(i.onTriggerLeave(h),h.defaultPrevented)return;i.onPointerGraceIntentChange(null)}})),onKeyDown:xa(s.onKeyDown,h=>{var p;const m=i.searchRef.current!=="";s.disabled||m&&h.key===" "||cus[r.dir].includes(h.key)&&(n.onOpenChange(!0),(p=n.content)==null||p.focus(),h.preventDefault())})})})});P5t.displayName=pW;var I5t="MenuSubContent",D5t=j.forwardRef((s,t)=>{const n=y5t(Zj,s.__scopeMenu),{forceMount:r=n.forceMount,...a}=s,i=YO(Zj,s.__scopeMenu),l=lee(Zj,s.__scopeMenu),o=L5t(I5t,s.__scopeMenu),c=j.useRef(null),d=Po(t,c);return e.jsx(FZ.Provider,{scope:s.__scopeMenu,children:e.jsx(dx,{present:r||i.open,children:e.jsx(FZ.Slot,{scope:s.__scopeMenu,children:e.jsx(IVe,{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:xa(s.onFocusOutside,u=>{u.target!==o.trigger&&i.onOpenChange(!1)}),onEscapeKeyDown:xa(s.onEscapeKeyDown,u=>{l.onClose(),u.preventDefault()}),onKeyDown:xa(s.onKeyDown,u=>{var p;const h=u.currentTarget.contains(u.target),m=dus[l.dir].includes(u.key);h&&m&&(i.onOpenChange(!1),(p=o.trigger)==null||p.focus(),u.preventDefault())})})})})})});D5t.displayName=I5t;function R5t(s){return s?"open":"closed"}function Mke(s){return s==="indeterminate"}function OVe(s){return Mke(s)?"indeterminate":s?"checked":"unchecked"}function Tus(s){const t=document.activeElement;for(const n of s)if(n===t||(n.focus(),document.activeElement!==t))return}function Mus(s,t){return s.map((n,r)=>s[(t+r)%s.length])}function Lus(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=Mus(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 Pus(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 Ius(s,t){if(!t)return!1;const n={x:s.clientX,y:s.clientY};return Pus(n,t)}function zZ(s){return t=>t.pointerType==="mouse"?s(t):void 0}var Dus=g5t,Rus=MVe,Ous=v5t,Fus=b5t,zus=DVe,Bus=_5t,$us=cCe,Uus=j5t,qus=k5t,Vus=C5t,Hus=E5t,Gus=T5t,Wus=M5t,Kus=P5t,Yus=D5t,dCe="DropdownMenu",[Zus,EXn]=ip(dCe,[f5t]),E1=f5t(),[Xus,O5t]=Zus(dCe),F5t=s=>{const{__scopeDropdownMenu:t,children:n,dir:r,open:a,defaultOpen:i,onOpenChange:l,modal:o=!0}=s,c=E1(t),d=j.useRef(null),[u,h]=Ux({prop:a,defaultProp:i??!1,onChange:l,caller:dCe});return e.jsx(Xus,{scope:t,triggerId:Fx(),triggerRef:d,contentId:Fx(),open:u,onOpenChange:h,onOpenToggle:j.useCallback(()=>h(m=>!m),[h]),modal:o,children:e.jsx(Dus,{...c,open:u,onOpenChange:h,dir:r,modal:o,children:n})})};F5t.displayName=dCe;var z5t="DropdownMenuTrigger",B5t=j.forwardRef((s,t)=>{const{__scopeDropdownMenu:n,disabled:r=!1,...a}=s,i=O5t(z5t,n),l=E1(n);return e.jsx(Rus,{asChild:!0,...l,children:e.jsx(Ka.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:oC(t,i.triggerRef),onPointerDown:xa(s.onPointerDown,o=>{!r&&o.button===0&&o.ctrlKey===!1&&(i.onOpenToggle(),i.open||o.preventDefault())}),onKeyDown:xa(s.onKeyDown,o=>{r||(["Enter"," "].includes(o.key)&&i.onOpenToggle(),o.key==="ArrowDown"&&i.onOpenChange(!0),["Enter"," ","ArrowDown"].includes(o.key)&&o.preventDefault())})})})});B5t.displayName=z5t;var Qus="DropdownMenuPortal",$5t=s=>{const{__scopeDropdownMenu:t,...n}=s,r=E1(t);return e.jsx(Ous,{...r,...n})};$5t.displayName=Qus;var U5t="DropdownMenuContent",q5t=j.forwardRef((s,t)=>{const{__scopeDropdownMenu:n,...r}=s,a=O5t(U5t,n),i=E1(n),l=j.useRef(!1);return e.jsx(Fus,{id:a.contentId,"aria-labelledby":a.triggerId,...i,...r,ref:t,onCloseAutoFocus:xa(s.onCloseAutoFocus,o=>{var c;l.current||(c=a.triggerRef.current)==null||c.focus(),l.current=!1,o.preventDefault()}),onInteractOutside:xa(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)"}})});q5t.displayName=U5t;var Jus="DropdownMenuGroup",ehs=j.forwardRef((s,t)=>{const{__scopeDropdownMenu:n,...r}=s,a=E1(n);return e.jsx(zus,{...a,...r,ref:t})});ehs.displayName=Jus;var ths="DropdownMenuLabel",V5t=j.forwardRef((s,t)=>{const{__scopeDropdownMenu:n,...r}=s,a=E1(n);return e.jsx(Bus,{...a,...r,ref:t})});V5t.displayName=ths;var shs="DropdownMenuItem",H5t=j.forwardRef((s,t)=>{const{__scopeDropdownMenu:n,...r}=s,a=E1(n);return e.jsx($us,{...a,...r,ref:t})});H5t.displayName=shs;var nhs="DropdownMenuCheckboxItem",G5t=j.forwardRef((s,t)=>{const{__scopeDropdownMenu:n,...r}=s,a=E1(n);return e.jsx(Uus,{...a,...r,ref:t})});G5t.displayName=nhs;var rhs="DropdownMenuRadioGroup",ahs=j.forwardRef((s,t)=>{const{__scopeDropdownMenu:n,...r}=s,a=E1(n);return e.jsx(qus,{...a,...r,ref:t})});ahs.displayName=rhs;var ihs="DropdownMenuRadioItem",W5t=j.forwardRef((s,t)=>{const{__scopeDropdownMenu:n,...r}=s,a=E1(n);return e.jsx(Vus,{...a,...r,ref:t})});W5t.displayName=ihs;var ohs="DropdownMenuItemIndicator",K5t=j.forwardRef((s,t)=>{const{__scopeDropdownMenu:n,...r}=s,a=E1(n);return e.jsx(Hus,{...a,...r,ref:t})});K5t.displayName=ohs;var lhs="DropdownMenuSeparator",Y5t=j.forwardRef((s,t)=>{const{__scopeDropdownMenu:n,...r}=s,a=E1(n);return e.jsx(Gus,{...a,...r,ref:t})});Y5t.displayName=lhs;var chs="DropdownMenuArrow",dhs=j.forwardRef((s,t)=>{const{__scopeDropdownMenu:n,...r}=s,a=E1(n);return e.jsx(Wus,{...a,...r,ref:t})});dhs.displayName=chs;var uhs="DropdownMenuSubTrigger",Z5t=j.forwardRef((s,t)=>{const{__scopeDropdownMenu:n,...r}=s,a=E1(n);return e.jsx(Kus,{...a,...r,ref:t})});Z5t.displayName=uhs;var hhs="DropdownMenuSubContent",X5t=j.forwardRef((s,t)=>{const{__scopeDropdownMenu:n,...r}=s,a=E1(n);return e.jsx(Yus,{...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)"}})});X5t.displayName=hhs;var mhs=F5t,phs=B5t,fhs=$5t,Q5t=q5t,J5t=V5t,e4t=H5t,t4t=G5t,s4t=W5t,n4t=K5t,r4t=Y5t,a4t=Z5t,i4t=X5t;const Hd=mhs,Gd=phs,xhs=j.forwardRef(({className:s,inset:t,children:n,...r},a)=>e.jsxs(a4t,{ref:a,className:Tt("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(Ja,{className:"ml-auto h-4 w-4"})]}));xhs.displayName=a4t.displayName;const ghs=j.forwardRef(({className:s,...t},n)=>e.jsx(i4t,{ref:n,className:Tt("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}));ghs.displayName=i4t.displayName;const Md=j.forwardRef(({className:s,sideOffset:t=4,...n},r)=>e.jsx(fhs,{children:e.jsx(Q5t,{ref:r,sideOffset:t,className:Tt("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})}));Md.displayName=Q5t.displayName;const Na=j.forwardRef(({className:s,inset:t,...n},r)=>e.jsx(e4t,{ref:r,className:Tt("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}));Na.displayName=e4t.displayName;const yhs=j.forwardRef(({className:s,children:t,checked:n,...r},a)=>e.jsxs(t4t,{ref:a,className:Tt("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(n4t,{children:e.jsx(oa,{className:"h-4 w-4"})})}),t]}));yhs.displayName=t4t.displayName;const vhs=j.forwardRef(({className:s,children:t,...n},r)=>e.jsxs(s4t,{ref:r,className:Tt("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(n4t,{children:e.jsx(Bp,{className:"h-2 w-2 fill-current"})})}),t]}));vhs.displayName=s4t.displayName;const iO=j.forwardRef(({className:s,inset:t,...n},r)=>e.jsx(J5t,{ref:r,className:Tt("px-2 py-1.5 text-sm font-semibold",t&&"pl-8",s),...n}));iO.displayName=J5t.displayName;const S0=j.forwardRef(({className:s,...t},n)=>e.jsx(r4t,{ref:n,className:Tt("-mx-1 my-1 h-px bg-muted",s),...t}));S0.displayName=r4t.displayName;const bhs=()=>{const{isAssistant:s,actingAsAgent:t,assignedAgents:n,setActingAsAgent:r,isActingAsSelf:a,setActingAsSelf:i}=aee();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(Lo,{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(qn,{className:"h-4 w-4 flex-shrink-0"}),e.jsx("span",{className:"font-medium text-sm",children:"Acting as"})]}),e.jsxs(Hd,{children:[e.jsx(Gd,{asChild:!0,children:e.jsxs($,{variant:"secondary",size:"sm",className:"gap-2 bg-primary-foreground/20 hover:bg-primary-foreground/30 text-primary-foreground border-0",children:[a?e.jsxs(e.Fragment,{children:[e.jsx(Lo,{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(ki,{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(_o,{className:"h-3 w-3"})]})}),e.jsxs(Md,{align:"start",className:"z-[2147483647]",children:[e.jsxs(Na,{onClick:i,className:"gap-2",children:[e.jsx(Lo,{className:"h-4 w-4"}),e.jsx("span",{children:"My Account"}),a&&e.jsx($e,{variant:"secondary",className:"ml-auto text-[10px]",children:"Current"})]}),e.jsx(S0,{}),n.map(o=>e.jsxs(Na,{onClick:()=>r(o),className:"gap-2",children:[e.jsxs(Ea,{className:"h-6 w-6",children:[e.jsx(ki,{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($e,{variant:"secondary",className:"ml-auto text-[10px]",children:"Current"})]},o.id))]})]})]}),e.jsx($e,{variant:"secondary",className:"bg-primary-foreground/20 text-primary-foreground border-0 text-xs",children:a?"Personal Mode":"Assistant Mode"})]})})};function ek(){var c,d;const{user:s,isAdmin:t}=_s(),{data:n,isLoading:r}=ht({queryKey:["partnership-membership",s==null?void 0:s.id],enabled:!!(s!=null&&s.id),staleTime:5*60*1e3,queryFn:async()=>{const{data:u}=await U.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([U.from("partnership_packages").select("*").eq("id",u.package_id).maybeSingle(),U.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,x;const h=((p=n==null?void 0:n.pkg)==null?void 0:p.feature_limits)||{},m=(x=h==null?void 0:h[u])==null?void 0:x.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 FVe={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"},TXn=Object.keys(FVe),_hs={home:null,crm:"crm",deals:"deals",listings:"listing_exchange",marketing:"marketing_studio",websites:"website",academy:"learn",events:"learn",apps:null,brokerage:"community",more:null},nat={"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"},whs={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 jhs(s){return s.id in nat?nat[s.id]:_hs[s.primaryCategory]??null}function Nhs(s){return whs[s]??null}const khs=[["/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 o4t(s){let t=null;for(const n of khs){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 _e=j.forwardRef(({className:s,...t},n)=>e.jsx("div",{ref:n,className:Tt("rounded-lg border bg-card text-card-foreground shadow-sm",s),...t}));_e.displayName="Card";const Bt=j.forwardRef(({className:s,...t},n)=>e.jsx("div",{ref:n,className:Tt("flex flex-col space-y-1.5 p-6",s),...t}));Bt.displayName="CardHeader";const Ut=j.forwardRef(({className:s,...t},n)=>e.jsx("h3",{ref:n,className:Tt("text-2xl font-semibold leading-none tracking-tight",s),...t}));Ut.displayName="CardTitle";const vr=j.forwardRef(({className:s,...t},n)=>e.jsx("p",{ref:n,className:Tt("text-sm text-muted-foreground",s),...t}));vr.displayName="CardDescription";const Oe=j.forwardRef(({className:s,...t},n)=>e.jsx("div",{ref:n,className:Tt("p-6 pt-0",s),...t}));Oe.displayName="CardContent";const uY=j.forwardRef(({className:s,...t},n)=>e.jsx("div",{ref:n,className:Tt("flex items-center p-6 pt-0",s),...t}));uY.displayName="CardFooter";const Is=j.forwardRef(({className:s,...t},n)=>e.jsx("textarea",{className:Tt("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}));Is.displayName="Textarea";const Os=$3e,Ko=lVe,Shs=U3e,MXn=XJ,l4t=j.forwardRef(({className:s,...t},n)=>e.jsx(pq,{ref:n,className:Tt("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}));l4t.displayName=pq.displayName;const Rs=j.forwardRef(({className:s,children:t,overlayClassName:n,...r},a)=>e.jsxs(Shs,{children:[e.jsx(l4t,{className:n}),e.jsxs(fq,{ref:a,className:Tt("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(XJ,{className:"absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity data-[state=open]:bg-accent data-[state=open]:text-muted-foreground hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none",children:[e.jsx(pr,{className:"h-4 w-4"}),e.jsx("span",{className:"sr-only",children:"Close"})]})]})]}));Rs.displayName=fq.displayName;const Us=({className:s,...t})=>e.jsx("div",{className:Tt("flex flex-col space-y-1.5 text-center sm:text-left",s),...t});Us.displayName="DialogHeader";const kr=({className:s,...t})=>e.jsx("div",{className:Tt("flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2",s),...t});kr.displayName="DialogFooter";const zs=j.forwardRef(({className:s,...t},n)=>e.jsx(YJ,{ref:n,className:Tt("text-lg font-semibold leading-none tracking-tight",s),...t}));zs.displayName=YJ.displayName;const Sr=j.forwardRef(({className:s,...t},n)=>e.jsx(ZJ,{ref:n,className:Tt("text-sm text-muted-foreground",s),...t}));Sr.displayName=ZJ.displayName;function Chs({featureKey:s,open:t,onOpenChange:n}){const{user:r}=_s(),a=ts(),[i,l]=j.useState(""),{data:o}=ht({queryKey:["partnership-upgrade-requests",r==null?void 0:r.id],enabled:!!(r!=null&&r.id)&&t,queryFn:async()=>{const{data:h}=await U.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 U.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"]}),ae.success("Request sent — we'll be in touch shortly."),l(""),n(!1)},onError:h=>ae.error((h==null?void 0:h.message)||"Could not send your request")}),u=FVe[s]||s;return e.jsx(Os,{open:t,onOpenChange:n,children:e.jsxs(Rs,{className:"sm:max-w-md",children:[e.jsxs(Us,{children:[e.jsxs(zs,{className:"flex items-center gap-2",children:[e.jsx(dn,{className:"h-5 w-5 text-primary"}),"Request ",u]}),e.jsxs(Sr,{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(oa,{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(Is,{placeholder:"Anything we should know? (optional)",value:i,onChange:h=>l(h.target.value),rows:4}),e.jsxs(kr,{children:[e.jsx($,{variant:"outline",onClick:()=>n(!1),children:"Close"}),!c&&e.jsx($,{onClick:()=>d.mutate(),disabled:d.isPending,children:d.isPending?"Sending…":"Send request"})]})]})})}function Ahs({featureKey:s}){const[t,n]=j.useState(!1),r=FVe[s]||s;return e.jsxs("div",{className:"flex items-center justify-center py-16 px-4",children:[e.jsx(_e,{className:"max-w-lg w-full border-border/60",children:e.jsxs(Oe,{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(Ad,{className:"h-6 w-6 text-primary"})}),e.jsxs("h2",{className:"text-2xl font-semibold",children:[r," is a Signature feature"]}),e.jsxs("p",{className:"text-muted-foreground",children:["Your current package doesn't include ",r,". Request access and our team will upgrade your account."]}),e.jsxs($,{onClick:()=>n(!0),className:"gap-2",children:[e.jsx(dn,{className:"h-4 w-4"})," Request access"]})]})}),e.jsx(Chs,{featureKey:s,open:t,onOpenChange:n})]})}const c4t=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 U.storage.from("avatars").list(`${s}`);if(o&&o.length>0){const{data:c}=U.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 U.storage.from("avatars").list(`${s}`);if(l&&l.length>0){const{data:o}=U.storage.from("avatars").getPublicUrl(`${s}/${l[0].name}`);n(`${o.publicUrl}?t=${Date.now()}`)}}catch(l){console.error("Error refreshing avatar:",l)}}}},d4t=async s=>{const t=new Map;return await Promise.all(s.map(async n=>{try{const{data:r}=await U.storage.from("avatars").list(`${n}`);if(r&&r.length>0){const{data:a}=U.storage.from("avatars").getPublicUrl(`${n}/${r[0].name}`);t.set(n,a.publicUrl)}}catch{}})),t},Ehs=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 U.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)),x=p<=0;n({isTrial:!0,isExpired:x,expiresAt:d,daysLeft:x?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},zVe=()=>{const{data:s,isLoading:t}=ht({queryKey:["feature-flags"],queryFn:async()=>{const{data:r,error:a}=await U.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")}},rat="community_last_seen_post_at";function Ths(){const{user:s}=_s(),t=Wd(),[n,r]=j.useState(0),[a,i]=j.useState(null);j.useEffect(()=>{if(!s)return;const o=localStorage.getItem(`${rat}_${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 x=JSON.parse(p);if(x.ts&&Date.now()-x.ts{if(!s)return;const o=U.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(g=>g+1);const{data:h}=await U.from("profiles").select("name").eq("id",d.user_id).single(),m=(h==null?void 0:h.name)||"Someone",p=d.content.replace(/@\[([^\]]+)\]\([^)]+\)/g,"@$1"),x=p.length>50?p.substring(0,50)+"...":p;u||ae("New Community Post",{description:`${m}: ${x}`,action:{label:"View",onClick:()=>{window.location.href="/community"}}})}).subscribe();return()=>{U.removeChannel(o)}},[s,t.pathname]);const l=j.useCallback(()=>{if(!s)return;const o=new Date().toISOString();localStorage.setItem(`${rat}_${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 Mhs(){const{isAdmin:s}=_s(),{data:t=0}=ht({queryKey:["wishlist-open-count"],queryFn:async()=>{const{count:n,error:r}=await U.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 DLe=s=>`levelup:activeTeam:${s}`,Lhs=()=>{const s=Za();return ht({queryKey:["user-teams",s],queryFn:async()=>{const{data:t,error:n}=await U.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 U.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})},Nw=()=>{const s=Za(),t=Lhs(),n=j.useMemo(()=>t.data||[],[t.data]),[r,a]=j.useState(()=>!s||typeof window>"u"?null:window.localStorage.getItem(DLe(s)));j.useEffect(()=>{!s||typeof window>"u"||a(window.localStorage.getItem(DLe(s)))},[s]);const i=j.useCallback(o=>{a(o),s&&typeof window<"u"&&window.localStorage.setItem(DLe(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}},B9="weekly_reels";function uCe(){const{user:s,loading:t,isAdmin:n}=_s(),{data:r,isLoading:a}=ht({queryKey:["feature-entitlement",B9,s==null?void 0:s.id],enabled:!!s&&!n,staleTime:5*60*1e3,queryFn:async()=>{const{data:i,error:l}=await U.from("feature_entitlements").select("enabled, expires_at, tier").eq("user_id",s.id).eq("feature_key",B9).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 Ub=$3e,cee=lVe,Phs=U3e,u4t=j.forwardRef(({className:s,...t},n)=>e.jsx(pq,{className:Tt("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}));u4t.displayName=pq.displayName;const Ihs=GO("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"}}),T1=j.forwardRef(({side:s="right",className:t,children:n,...r},a)=>e.jsxs(Phs,{children:[e.jsx(u4t,{}),e.jsxs(fq,{ref:a,className:Tt(Ihs({side:s}),t),...r,children:[n,e.jsxs(XJ,{className:"absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity data-[state=open]:bg-secondary hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none",children:[e.jsx(pr,{className:"h-4 w-4"}),e.jsx("span",{className:"sr-only",children:"Close"})]})]})]}));T1.displayName=fq.displayName;const kw=({className:s,...t})=>e.jsx("div",{className:Tt("flex flex-col space-y-2 text-center sm:text-left",s),...t});kw.displayName="SheetHeader";const h4t=({className:s,...t})=>e.jsx("div",{className:Tt("flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2",s),...t});h4t.displayName="SheetFooter";const Sw=j.forwardRef(({className:s,...t},n)=>e.jsx(YJ,{ref:n,className:Tt("text-lg font-semibold text-foreground",s),...t}));Sw.displayName=YJ.displayName;const dee=j.forwardRef(({className:s,...t},n)=>e.jsx(ZJ,{ref:n,className:Tt("text-sm text-muted-foreground",s),...t}));dee.displayName=ZJ.displayName;function BZ(s,[t,n]){return Math.min(n,Math.max(t,s))}function Dhs(s,t){return j.useReducer((n,r)=>t[n][r]??n,s)}var BVe="ScrollArea",[m4t,LXn]=ip(BVe),[Rhs,u2]=m4t(BVe),p4t=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,x]=j.useState(null),[g,y]=j.useState(null),[b,v]=j.useState(0),[N,C]=j.useState(0),[A,T]=j.useState(!1),[P,M]=j.useState(!1),I=Po(t,B=>c(B)),D=jC(a);return e.jsx(Rhs,{scope:n,type:r,dir:D,scrollHideDelay:i,scrollArea:o,viewport:d,onViewportChange:u,content:h,onContentChange:m,scrollbarX:p,onScrollbarXChange:x,scrollbarXEnabled:A,onScrollbarXEnabledChange:T,scrollbarY:g,onScrollbarYChange:y,scrollbarYEnabled:P,onScrollbarYEnabledChange:M,onCornerWidthChange:v,onCornerHeightChange:C,children:e.jsx(Ka.div,{dir:D,...l,ref:I,style:{position:"relative","--radix-scroll-area-corner-width":b+"px","--radix-scroll-area-corner-height":N+"px",...s.style}})})});p4t.displayName=BVe;var f4t="ScrollAreaViewport",x4t=j.forwardRef((s,t)=>{const{__scopeScrollArea:n,children:r,nonce:a,...i}=s,l=u2(f4t,n),o=j.useRef(null),c=Po(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(Ka.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})})]})});x4t.displayName=f4t;var P5="ScrollAreaScrollbar",$Ve=j.forwardRef((s,t)=>{const{forceMount:n,...r}=s,a=u2(P5,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(Ohs,{...r,ref:t,forceMount:n}):a.type==="scroll"?e.jsx(Fhs,{...r,ref:t,forceMount:n}):a.type==="auto"?e.jsx(g4t,{...r,ref:t,forceMount:n}):a.type==="always"?e.jsx(UVe,{...r,ref:t}):null});$Ve.displayName=P5;var Ohs=j.forwardRef((s,t)=>{const{forceMount:n,...r}=s,a=u2(P5,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(dx,{present:n||i,children:e.jsx(g4t,{"data-state":i?"visible":"hidden",...r,ref:t})})}),Fhs=j.forwardRef((s,t)=>{const{forceMount:n,...r}=s,a=u2(P5,s.__scopeScrollArea),i=s.orientation==="horizontal",l=mCe(()=>c("SCROLL_END"),100),[o,c]=Dhs("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(dx,{present:n||o!=="hidden",children:e.jsx(UVe,{"data-state":o==="hidden"?"hidden":"visible",...r,ref:t,onPointerEnter:xa(s.onPointerEnter,()=>c("POINTER_ENTER")),onPointerLeave:xa(s.onPointerLeave,()=>c("POINTER_LEAVE"))})})}),g4t=j.forwardRef((s,t)=>{const n=u2(P5,s.__scopeScrollArea),{forceMount:r,...a}=s,[i,l]=j.useState(!1),o=s.orientation==="horizontal",c=mCe(()=>{if(n.viewport){const d=n.viewport.offsetWidth{const{orientation:n="vertical",...r}=s,a=u2(P5,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=w4t(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 Vhs(m,l.current,o,p)}return n==="horizontal"?e.jsx(zhs,{...u,ref:t,onThumbPositionChange:()=>{if(a.viewport&&i.current){const m=a.viewport.scrollLeft,p=aat(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(Bhs,{...u,ref:t,onThumbPositionChange:()=>{if(a.viewport&&i.current){const m=a.viewport.scrollTop,p=aat(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}),zhs=j.forwardRef((s,t)=>{const{sizes:n,onSizesChange:r,...a}=s,i=u2(P5,s.__scopeScrollArea),[l,o]=j.useState(),c=j.useRef(null),d=Po(t,c,i.onScrollbarXChange);return j.useEffect(()=>{c.current&&o(getComputedStyle(c.current))},[c]),e.jsx(v4t,{"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":hCe(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),N4t(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:Pke(l.paddingLeft),paddingEnd:Pke(l.paddingRight)}})}})}),Bhs=j.forwardRef((s,t)=>{const{sizes:n,onSizesChange:r,...a}=s,i=u2(P5,s.__scopeScrollArea),[l,o]=j.useState(),c=j.useRef(null),d=Po(t,c,i.onScrollbarYChange);return j.useEffect(()=>{c.current&&o(getComputedStyle(c.current))},[c]),e.jsx(v4t,{"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":hCe(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),N4t(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:Pke(l.paddingTop),paddingEnd:Pke(l.paddingBottom)}})}})}),[$hs,y4t]=m4t(P5),v4t=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=u2(P5,n),[x,g]=j.useState(null),y=Po(t,I=>g(I)),b=j.useRef(null),v=j.useRef(""),N=p.viewport,C=r.content-r.viewport,A=bf(u),T=bf(c),P=mCe(h,10);function M(I){if(b.current){const D=I.clientX-b.current.left,B=I.clientY-b.current.top;d({x:D,y:B})}}return j.useEffect(()=>{const I=D=>{const B=D.target;(x==null?void 0:x.contains(B))&&A(D,C)};return document.addEventListener("wheel",I,{passive:!1}),()=>document.removeEventListener("wheel",I,{passive:!1})},[N,x,C,A]),j.useEffect(T,[r,T]),X$(x,P),X$(p.content,P),e.jsx($hs,{scope:n,scrollbar:x,hasThumb:a,onThumbChange:bf(i),onThumbPointerUp:bf(l),onThumbPositionChange:T,onThumbPointerDown:bf(o),children:e.jsx(Ka.div,{...m,ref:y,style:{position:"absolute",...m.style},onPointerDown:xa(s.onPointerDown,I=>{I.button===0&&(I.target.setPointerCapture(I.pointerId),b.current=x.getBoundingClientRect(),v.current=document.body.style.webkitUserSelect,document.body.style.webkitUserSelect="none",p.viewport&&(p.viewport.style.scrollBehavior="auto"),M(I))}),onPointerMove:xa(s.onPointerMove,M),onPointerUp:xa(s.onPointerUp,I=>{const D=I.target;D.hasPointerCapture(I.pointerId)&&D.releasePointerCapture(I.pointerId),document.body.style.webkitUserSelect=v.current,p.viewport&&(p.viewport.style.scrollBehavior=""),b.current=null})})})}),Lke="ScrollAreaThumb",b4t=j.forwardRef((s,t)=>{const{forceMount:n,...r}=s,a=y4t(Lke,s.__scopeScrollArea);return e.jsx(dx,{present:n||a.hasThumb,children:e.jsx(Uhs,{ref:t,...r})})}),Uhs=j.forwardRef((s,t)=>{const{__scopeScrollArea:n,style:r,...a}=s,i=u2(Lke,n),l=y4t(Lke,n),{onThumbPositionChange:o}=l,c=Po(t,h=>l.onThumbChange(h)),d=j.useRef(void 0),u=mCe(()=>{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=Hhs(h,o);d.current=p,o()}};return o(),h.addEventListener("scroll",m),()=>h.removeEventListener("scroll",m)}},[i.viewport,u,o]),e.jsx(Ka.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:xa(s.onPointerDownCapture,h=>{const p=h.target.getBoundingClientRect(),x=h.clientX-p.left,g=h.clientY-p.top;l.onThumbPointerDown({x,y:g})}),onPointerUp:xa(s.onPointerUp,l.onThumbPointerUp)})});b4t.displayName=Lke;var qVe="ScrollAreaCorner",_4t=j.forwardRef((s,t)=>{const n=u2(qVe,s.__scopeScrollArea),r=!!(n.scrollbarX&&n.scrollbarY);return n.type!=="scroll"&&r?e.jsx(qhs,{...s,ref:t}):null});_4t.displayName=qVe;var qhs=j.forwardRef((s,t)=>{const{__scopeScrollArea:n,...r}=s,a=u2(qVe,n),[i,l]=j.useState(0),[o,c]=j.useState(0),d=!!(i&&o);return X$(a.scrollbarX,()=>{var h;const u=((h=a.scrollbarX)==null?void 0:h.offsetHeight)||0;a.onCornerHeightChange(u),c(u)}),X$(a.scrollbarY,()=>{var h;const u=((h=a.scrollbarY)==null?void 0:h.offsetWidth)||0;a.onCornerWidthChange(u),l(u)}),d?e.jsx(Ka.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 Pke(s){return s?parseInt(s,10):0}function w4t(s,t){const n=s/t;return isNaN(n)?0:n}function hCe(s){const t=w4t(s.viewport,s.content),n=s.scrollbar.paddingStart+s.scrollbar.paddingEnd,r=(s.scrollbar.size-n)*t;return Math.max(r,18)}function Vhs(s,t,n,r="ltr"){const a=hCe(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 j4t([c,d],h)(s)}function aat(s,t,n="ltr"){const r=hCe(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=BZ(s,c);return j4t([0,l],[0,o])(d)}function j4t(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 N4t(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 mCe(s,t){const n=bf(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 X$(s,t){const n=bf(t);Sf(()=>{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 k4t=p4t,Ghs=x4t,Whs=_4t;const Oi=j.forwardRef(({className:s,children:t,...n},r)=>e.jsxs(k4t,{ref:r,className:Tt("relative overflow-hidden",s),...n,children:[e.jsx(Ghs,{className:"h-full w-full rounded-[inherit]",children:t}),e.jsx(Nq,{}),e.jsx(Whs,{})]}));Oi.displayName=k4t.displayName;const Nq=j.forwardRef(({className:s,orientation:t="vertical",...n},r)=>e.jsx($Ve,{ref:r,orientation:t,className:Tt("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(b4t,{className:"relative flex-1 rounded-full bg-border"})}));Nq.displayName=$Ve.displayName;const Khs="/assets/levelup-logo-Eif24dqY.png",Yhs="/assets/levelup-logo-icon-C-7iromj.png",Zhs="/assets/levelup-logo-mobile-B9skSjUG.png";var uee=s=>s.type==="checkbox",E8=s=>s instanceof Date,Jv=s=>s==null;const S4t=s=>typeof s=="object";var lx=s=>!Jv(s)&&!Array.isArray(s)&&S4t(s)&&!E8(s),C4t=s=>lx(s)&&s.target?uee(s.target)?s.target.checked:s.target.value:s,Xhs=s=>s.substring(0,s.search(/\.\d+(\.|$)/))||s,A4t=(s,t)=>s.has(Xhs(t)),Qhs=s=>{const t=s.constructor&&s.constructor.prototype;return lx(t)&&t.hasOwnProperty("isPrototypeOf")},VVe=typeof window<"u"&&typeof window.HTMLElement<"u"&&typeof document<"u";function tg(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(!(VVe&&(s instanceof Blob||r))&&(n||lx(s)))if(t=n?[]:{},!n&&!Qhs(s))t=s;else for(const a in s)s.hasOwnProperty(a)&&(t[a]=tg(s[a]));else return s;return t}var pCe=s=>/^\w*$/.test(s),Gf=s=>s===void 0,HVe=s=>Array.isArray(s)?s.filter(Boolean):[],GVe=s=>HVe(s.replace(/["|']|\]/g,"").split(/\.|\[/)),ji=(s,t,n)=>{if(!t||!lx(s))return n;const r=(pCe(t)?[t]:GVe(t)).reduce((a,i)=>Jv(a)?a:a[i],s);return Gf(r)||r===s?Gf(s[t])?n:s[t]:r},$_=s=>typeof s=="boolean",$u=(s,t,n)=>{let r=-1;const a=pCe(t)?[t]:GVe(t),i=a.length,l=i-1;for(;++rIt.useContext(WVe),Jhs=s=>{const{children:t,...n}=s;return It.createElement(WVe.Provider,{value:n},t)};var E4t=(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]!==jN.all&&(t._proxyFormState[l]=!r||jN.all),n&&(n[l]=!0),s[l]}});return a};const KVe=typeof window<"u"?It.useLayoutEffect:It.useEffect;function ems(s){const t=fCe(),{control:n=t.control,disabled:r,name:a,exact:i}=s||{},[l,o]=It.useState(n._formState),c=It.useRef({isDirty:!1,isLoading:!1,dirtyFields:!1,touchedFields:!1,validatingFields:!1,isValidating:!1,isValid:!1,errors:!1});return KVe(()=>n._subscribe({name:a,formState:c.current,exact:i,callback:d=>{!r&&o({...n._formState,...d})}}),[a,r,i]),It.useEffect(()=>{c.current.isValid&&n._setValid(!0)},[n]),It.useMemo(()=>E4t(l,n,c.current,!1),[l,n])}var $S=s=>typeof s=="string",T4t=(s,t,n,r,a)=>$S(s)?(r&&t.watch.add(s),ji(n,s,a)):Array.isArray(s)?s.map(i=>(r&&t.watch.add(i),ji(n,i))):(r&&(t.watchAll=!0),n),vFe=s=>Jv(s)||!S4t(s);function C3(s,t,n=new WeakSet){if(vFe(s)||vFe(t))return s===t;if(E8(s)&&E8(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(E8(l)&&E8(o)||lx(l)&&lx(o)||Array.isArray(l)&&Array.isArray(o)?!C3(l,o,n):l!==o)return!1}}return!0}function tms(s){const t=fCe(),{control:n=t.control,name:r,defaultValue:a,disabled:i,exact:l,compute:o}=s||{},c=It.useRef(a),d=It.useRef(o),u=It.useRef(void 0);d.current=o;const h=It.useMemo(()=>n._getWatch(r,c.current),[n,r]),[m,p]=It.useState(d.current?d.current(h):h);return KVe(()=>n._subscribe({name:r,formState:{values:!0},exact:l,callback:x=>{if(!i){const g=T4t(r,n._names,x.values||n._formValues,!1,c.current);if(d.current){const y=d.current(g);C3(y,u.current)||(p(y),u.current=y)}else p(g)}}}),[n,i,r,l]),It.useEffect(()=>n._removeUnmounted()),m}function sms(s){const t=fCe(),{name:n,disabled:r,control:a=t.control,shouldUnregister:i,defaultValue:l}=s,o=A4t(a._names.array,n),c=It.useMemo(()=>ji(a._formValues,n,ji(a._defaultValues,n,l)),[a,n,l]),d=tms({control:a,name:n,defaultValue:c,exact:!0}),u=ems({control:a,name:n,exact:!0}),h=It.useRef(s),m=It.useRef(a.register(n,{...s.rules,value:d,...$_(s.disabled)?{disabled:s.disabled}:{}}));h.current=s;const p=It.useMemo(()=>Object.defineProperties({},{invalid:{enumerable:!0,get:()=>!!ji(u.errors,n)},isDirty:{enumerable:!0,get:()=>!!ji(u.dirtyFields,n)},isTouched:{enumerable:!0,get:()=>!!ji(u.touchedFields,n)},isValidating:{enumerable:!0,get:()=>!!ji(u.validatingFields,n)},error:{enumerable:!0,get:()=>ji(u.errors,n)}}),[u,n]),x=It.useCallback(v=>m.current.onChange({target:{value:C4t(v),name:n},type:Ike.CHANGE}),[n]),g=It.useCallback(()=>m.current.onBlur({target:{value:ji(a._formValues,n),name:n},type:Ike.BLUR}),[n,a._formValues]),y=It.useCallback(v=>{const N=ji(a._fields,n);N&&v&&(N._f.ref={focus:()=>v.focus&&v.focus(),select:()=>v.select&&v.select(),setCustomValidity:C=>v.setCustomValidity(C),reportValidity:()=>v.reportValidity()})},[a._fields,n]),b=It.useMemo(()=>({name:n,value:d,...$_(r)||u.disabled?{disabled:u.disabled||r}:{},onChange:x,onBlur:g,ref:y}),[n,r,u.disabled,x,g,y,d]);return It.useEffect(()=>{const v=a._options.shouldUnregister||i;a.register(n,{...h.current.rules,...$_(h.current.disabled)?{disabled:h.current.disabled}:{}});const N=(C,A)=>{const T=ji(a._fields,C);T&&T._f&&(T._f.mount=A)};if(N(n,!0),v){const C=tg(ji(a._options.defaultValues,n));$u(a._defaultValues,n,C),Gf(ji(a._formValues,n))&&$u(a._formValues,n,C)}return!o&&a.register(n),()=>{(o?v&&!a._state.action:v)?a.unregister(n):N(n,!1)}},[n,a,o,i]),It.useEffect(()=>{a._setDisabledField({disabled:r,name:n})},[r,n,a]),It.useMemo(()=>({field:b,formState:u,fieldState:p}),[b,u,p])}const nms=s=>s.render(sms(s));var M4t=(s,t,n,r,a)=>t?{...n[s],types:{...n[s]&&n[s].types?n[s].types:{},[r]:a||!0}}:{},hY=s=>Array.isArray(s)?s:[s],iat=()=>{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=[]}}},mb=s=>lx(s)&&!Object.keys(s).length,YVe=s=>s.type==="file",NN=s=>typeof s=="function",Dke=s=>{if(!VVe)return!1;const t=s?s.ownerDocument:0;return s instanceof(t&&t.defaultView?t.defaultView.HTMLElement:HTMLElement)},L4t=s=>s.type==="select-multiple",ZVe=s=>s.type==="radio",rms=s=>ZVe(s)||uee(s),RLe=s=>Dke(s)&&s.isConnected;function ams(s,t){const n=t.slice(0,-1).length;let r=0;for(;r{for(const t in s)if(NN(s[t]))return!0;return!1};function Rke(s,t={}){const n=Array.isArray(s);if(lx(s)||n)for(const r in s)Array.isArray(s[r])||lx(s[r])&&!P4t(s[r])?(t[r]=Array.isArray(s[r])?[]:{},Rke(s[r],t[r])):Jv(s[r])||(t[r]=!0);return t}function I4t(s,t,n){const r=Array.isArray(s);if(lx(s)||r)for(const a in s)Array.isArray(s[a])||lx(s[a])&&!P4t(s[a])?Gf(t)||vFe(n[a])?n[a]=Array.isArray(s[a])?Rke(s[a],[]):{...Rke(s[a])}:I4t(s[a],Jv(t)?{}:t[a],n[a]):n[a]=!C3(s[a],t[a]);return n}var KH=(s,t)=>I4t(s,t,Rke(t));const oat={value:!1,isValid:!1},lat={value:!0,isValid:!0};var D4t=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&&!Gf(s[0].attributes.value)?Gf(s[0].value)||s[0].value===""?lat:{value:s[0].value,isValid:!0}:lat:oat}return oat},R4t=(s,{valueAsNumber:t,valueAsDate:n,setValueAs:r})=>Gf(s)?s:t?s===""?NaN:s&&+s:n&&$S(s)?new Date(s):r?r(s):s;const cat={isValid:!1,value:null};var O4t=s=>Array.isArray(s)?s.reduce((t,n)=>n&&n.checked&&!n.disabled?{isValid:!0,value:n.value}:t,cat):cat;function dat(s){const t=s.ref;return YVe(t)?t.files:ZVe(t)?O4t(s.refs).value:L4t(t)?[...t.selectedOptions].map(({value:n})=>n):uee(t)?D4t(s.refs).value:R4t(Gf(t.value)?s.ref.value:t.value,s)}var oms=(s,t,n,r)=>{const a={};for(const i of s){const l=ji(t,i);l&&$u(a,i,l._f)}return{criteriaMode:n,names:[...s],fields:a,shouldUseNativeValidation:r}},Oke=s=>s instanceof RegExp,YH=s=>Gf(s)?s:Oke(s)?s.source:lx(s)?Oke(s.value)?s.value.source:s.value:s,uat=s=>({isOnSubmit:!s||s===jN.onSubmit,isOnBlur:s===jN.onBlur,isOnChange:s===jN.onChange,isOnAll:s===jN.all,isOnTouch:s===jN.onTouched});const hat="AsyncFunction";var lms=s=>!!s&&!!s.validate&&!!(NN(s.validate)&&s.validate.constructor.name===hat||lx(s.validate)&&Object.values(s.validate).find(t=>t.constructor.name===hat)),cms=s=>s.mount&&(s.required||s.min||s.max||s.maxLength||s.minLength||s.pattern||s.validate),mat=(s,t,n)=>!n&&(t.watchAll||t.watch.has(s)||[...t.watch].some(r=>s.startsWith(r)&&/^\.\w+/.test(s.slice(r.length))));const mY=(s,t,n,r)=>{for(const a of n||Object.keys(s)){const i=ji(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(mY(o,t))break}else if(lx(o)&&mY(o,t))break}}};function pat(s,t,n){const r=ji(s,n);if(r||pCe(n))return{error:r,name:n};const a=n.split(".");for(;a.length;){const i=a.join("."),l=ji(t,i),o=ji(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 dms=(s,t,n,r)=>{n(s);const{name:a,...i}=s;return mb(i)||Object.keys(i).length>=Object.keys(t).length||Object.keys(i).find(l=>t[l]===(!r||jN.all))},ums=(s,t,n)=>!s||!t||s===t||hY(s).some(r=>r&&(n?r===t:r.startsWith(t)||t.startsWith(r))),hms=(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,mms=(s,t)=>!HVe(ji(s,t)).length&&_x(s,t),pms=(s,t,n)=>{const r=hY(ji(s,n));return $u(r,"root",t[n]),$u(s,n,r),s},x2e=s=>$S(s);function fat(s,t,n="validate"){if(x2e(s)||Array.isArray(s)&&s.every(x2e)||$_(s)&&!s)return{type:n,message:x2e(s)?s:"",ref:t}}var g7=s=>lx(s)&&!Oke(s)?s:{value:s,message:""},xat=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:x,name:g,valueAsNumber:y,mount:b}=s._f,v=ji(n,g);if(!b||t.has(g))return{};const N=o?o[0]:l,C=q=>{a&&N.reportValidity&&(N.setCustomValidity($_(q)?"":q||""),N.reportValidity())},A={},T=ZVe(l),P=uee(l),M=T||P,I=(y||YVe(l))&&Gf(l.value)&&Gf(v)||Dke(l)&&l.value===""||v===""||Array.isArray(v)&&!v.length,D=M4t.bind(null,g,r,A),B=(q,W,V,K=v4.maxLength,Q=v4.minLength)=>{const J=q?W:V;A[g]={type:q?K:Q,message:J,ref:l,...D(q?K:Q,J)}};if(i?!Array.isArray(v)||!v.length:c&&(!M&&(I||Jv(v))||$_(v)&&!v||P&&!D4t(o).isValid||T&&!O4t(o).isValid)){const{value:q,message:W}=x2e(c)?{value:!!c,message:c}:g7(c);if(q&&(A[g]={type:v4.required,message:W,ref:N,...D(v4.required,W)},!r))return C(W),A}if(!I&&(!Jv(h)||!Jv(m))){let q,W;const V=g7(m),K=g7(h);if(!Jv(v)&&!isNaN(v)){const Q=l.valueAsNumber||v&&+v;Jv(V.value)||(q=Q>V.value),Jv(K.value)||(W=Qnew Date(new Date().toDateString()+" "+ne),ce=l.type=="time",ue=l.type=="week";$S(V.value)&&v&&(q=ce?J(v)>J(V.value):ue?v>V.value:Q>new Date(V.value)),$S(K.value)&&v&&(W=ce?J(v)+q.value,K=!Jv(W.value)&&v.length<+W.value;if((V||K)&&(B(V,q.message,W.message),!r))return C(A[g].message),A}if(p&&!I&&$S(v)){const{value:q,message:W}=g7(p);if(Oke(q)&&!v.match(q)&&(A[g]={type:v4.pattern,message:W,ref:l,...D(v4.pattern,W)},!r))return C(W),A}if(x){if(NN(x)){const q=await x(v,n),W=fat(q,N);if(W&&(A[g]={...W,...D(v4.validate,W.message)},!r))return C(W.message),A}else if(lx(x)){let q={};for(const W in x){if(!mb(q)&&!r)break;const V=fat(await x[W](v,n),N,W);V&&(q={...V,...D(W,V.message)},C(V.message),r&&(A[g]=q))}if(!mb(q)&&(A[g]={ref:N,...q},!r))return A}}return C(!0),A};const fms={mode:jN.onSubmit,reValidateMode:jN.onChange,shouldFocusError:!0};function xms(s={}){let t={...fms,...s},n={submitCount:0,isDirty:!1,isReady:!1,isLoading:NN(t.defaultValues),isValidating:!1,isSubmitted:!1,isSubmitting:!1,isSubmitSuccessful:!1,isValid:!1,touchedFields:{},dirtyFields:{},validatingFields:{},errors:t.errors||{},disabled:t.disabled||!1},r={},a=lx(t.defaultValues)||lx(t.values)?tg(t.defaultValues||t.values)||{}:{},i=t.shouldUnregister?{}:tg(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:iat(),state:iat()},p=t.criteriaMode===jN.all,x=Ze=>Ue=>{clearTimeout(d),d=setTimeout(Ze,Ue)},g=async Ze=>{if(!t.disabled&&(u.isValid||h.isValid||Ze)){const Ue=t.resolver?mb((await P()).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(et=>{et&&(Ue?$u(n.validatingFields,et,Ue):_x(n.validatingFields,et))}),m.state.next({validatingFields:n.validatingFields,isValidating:!mb(n.validatingFields)}))},b=(Ze,Ue=[],et,Qe,Ge=!0,nt=!0)=>{if(Qe&&et&&!t.disabled){if(l.action=!0,nt&&Array.isArray(ji(r,Ze))){const ft=et(ji(r,Ze),Qe.argA,Qe.argB);Ge&&$u(r,Ze,ft)}if(nt&&Array.isArray(ji(n.errors,Ze))){const ft=et(ji(n.errors,Ze),Qe.argA,Qe.argB);Ge&&$u(n.errors,Ze,ft),mms(n.errors,Ze)}if((u.touchedFields||h.touchedFields)&&nt&&Array.isArray(ji(n.touchedFields,Ze))){const ft=et(ji(n.touchedFields,Ze),Qe.argA,Qe.argB);Ge&&$u(n.touchedFields,Ze,ft)}(u.dirtyFields||h.dirtyFields)&&(n.dirtyFields=KH(a,i)),m.state.next({name:Ze,isDirty:B(Ze,Ue),dirtyFields:n.dirtyFields,errors:n.errors,isValid:n.isValid})}else $u(i,Ze,Ue)},v=(Ze,Ue)=>{$u(n.errors,Ze,Ue),m.state.next({errors:n.errors})},N=Ze=>{n.errors=Ze,m.state.next({errors:n.errors,isValid:!1})},C=(Ze,Ue,et,Qe)=>{const Ge=ji(r,Ze);if(Ge){const nt=ji(i,Ze,Gf(et)?ji(a,Ze):et);Gf(nt)||Qe&&Qe.defaultChecked||Ue?$u(i,Ze,Ue?nt:dat(Ge._f)):V(Ze,nt),l.mount&&g()}},A=(Ze,Ue,et,Qe,Ge)=>{let nt=!1,ft=!1;const lt={name:Ze};if(!t.disabled){if(!et||Qe){(u.isDirty||h.isDirty)&&(ft=n.isDirty,n.isDirty=lt.isDirty=B(),nt=ft!==lt.isDirty);const Mt=C3(ji(a,Ze),Ue);ft=!!ji(n.dirtyFields,Ze),Mt?_x(n.dirtyFields,Ze):$u(n.dirtyFields,Ze,!0),lt.dirtyFields=n.dirtyFields,nt=nt||(u.dirtyFields||h.dirtyFields)&&ft!==!Mt}if(et){const Mt=ji(n.touchedFields,Ze);Mt||($u(n.touchedFields,Ze,et),lt.touchedFields=n.touchedFields,nt=nt||(u.touchedFields||h.touchedFields)&&Mt!==et)}nt&&Ge&&m.state.next(lt)}return nt?lt:{}},T=(Ze,Ue,et,Qe)=>{const Ge=ji(n.errors,Ze),nt=(u.isValid||h.isValid)&&$_(Ue)&&n.isValid!==Ue;if(t.delayError&&et?(c=x(()=>v(Ze,et)),c(t.delayError)):(clearTimeout(d),c=null,et?$u(n.errors,Ze,et):_x(n.errors,Ze)),(et?!C3(Ge,et):Ge)||!mb(Qe)||nt){const ft={...Qe,...nt&&$_(Ue)?{isValid:Ue}:{},errors:n.errors,name:Ze};n={...n,...ft},m.state.next(ft)}},P=async Ze=>{y(Ze,!0);const Ue=await t.resolver(i,t.context,oms(Ze||o.mount,r,t.criteriaMode,t.shouldUseNativeValidation));return y(Ze),Ue},M=async Ze=>{const{errors:Ue}=await P(Ze);if(Ze)for(const et of Ze){const Qe=ji(Ue,et);Qe?$u(n.errors,et,Qe):_x(n.errors,et)}else n.errors=Ue;return Ue},I=async(Ze,Ue,et={valid:!0})=>{for(const Qe in Ze){const Ge=Ze[Qe];if(Ge){const{_f:nt,...ft}=Ge;if(nt){const lt=o.array.has(nt.name),Mt=Ge._f&&lms(Ge._f);Mt&&u.validatingFields&&y([Qe],!0);const Ft=await xat(Ge,o.disabled,i,p,t.shouldUseNativeValidation&&!Ue,lt);if(Mt&&u.validatingFields&&y([Qe]),Ft[nt.name]&&(et.valid=!1,Ue))break;!Ue&&(ji(Ft,nt.name)?lt?pms(n.errors,Ft,nt.name):$u(n.errors,nt.name,Ft[nt.name]):_x(n.errors,nt.name))}!mb(ft)&&await I(ft,Ue,et)}}return et.valid},D=()=>{for(const Ze of o.unMount){const Ue=ji(r,Ze);Ue&&(Ue._f.refs?Ue._f.refs.every(et=>!RLe(et)):!RLe(Ue._f.ref))&&je(Ze)}o.unMount=new Set},B=(Ze,Ue)=>!t.disabled&&(Ze&&Ue&&$u(i,Ze,Ue),!C3(ne(),a)),q=(Ze,Ue,et)=>T4t(Ze,o,{...l.mount?i:Gf(Ue)?a:$S(Ze)?{[Ze]:Ue}:Ue},et,Ue),W=Ze=>HVe(ji(l.mount?i:a,Ze,t.shouldUnregister?ji(a,Ze,[]):[])),V=(Ze,Ue,et={})=>{const Qe=ji(r,Ze);let Ge=Ue;if(Qe){const nt=Qe._f;nt&&(!nt.disabled&&$u(i,Ze,R4t(Ue,nt)),Ge=Dke(nt.ref)&&Jv(Ue)?"":Ue,L4t(nt.ref)?[...nt.ref.options].forEach(ft=>ft.selected=Ge.includes(ft.value)):nt.refs?uee(nt.ref)?nt.refs.forEach(ft=>{(!ft.defaultChecked||!ft.disabled)&&(Array.isArray(Ge)?ft.checked=!!Ge.find(lt=>lt===ft.value):ft.checked=Ge===ft.value||!!Ge)}):nt.refs.forEach(ft=>ft.checked=ft.value===Ge):YVe(nt.ref)?nt.ref.value="":(nt.ref.value=Ge,nt.ref.type||m.state.next({name:Ze,values:tg(i)})))}(et.shouldDirty||et.shouldTouch)&&A(Ze,Ge,et.shouldTouch,et.shouldDirty,!0),et.shouldValidate&&ue(Ze)},K=(Ze,Ue,et)=>{for(const Qe in Ue){if(!Ue.hasOwnProperty(Qe))return;const Ge=Ue[Qe],nt=Ze+"."+Qe,ft=ji(r,nt);(o.array.has(Ze)||lx(Ge)||ft&&!ft._f)&&!E8(Ge)?K(nt,Ge,et):V(nt,Ge,et)}},Q=(Ze,Ue,et={})=>{const Qe=ji(r,Ze),Ge=o.array.has(Ze),nt=tg(Ue);$u(i,Ze,nt),Ge?(m.array.next({name:Ze,values:tg(i)}),(u.isDirty||u.dirtyFields||h.isDirty||h.dirtyFields)&&et.shouldDirty&&m.state.next({name:Ze,dirtyFields:KH(a,i),isDirty:B(Ze,nt)})):Qe&&!Qe._f&&!Jv(nt)?K(Ze,nt,et):V(Ze,nt,et),mat(Ze,o)&&m.state.next({...n,name:Ze}),m.state.next({name:l.mount?Ze:void 0,values:tg(i)})},J=async Ze=>{l.mount=!0;const Ue=Ze.target;let et=Ue.name,Qe=!0;const Ge=ji(r,et),nt=Mt=>{Qe=Number.isNaN(Mt)||E8(Mt)&&isNaN(Mt.getTime())||C3(Mt,ji(i,et,Mt))},ft=uat(t.mode),lt=uat(t.reValidateMode);if(Ge){let Mt,Ft;const Ts=Ue.type?dat(Ge._f):C4t(Ze),js=Ze.type===Ike.BLUR||Ze.type===Ike.FOCUS_OUT,zt=!cms(Ge._f)&&!t.resolver&&!ji(n.errors,et)&&!Ge._f.deps||hms(js,ji(n.touchedFields,et),n.isSubmitted,lt,ft),Nt=mat(et,o,js);$u(i,et,Ts),js?(Ge._f.onBlur&&Ge._f.onBlur(Ze),c&&c(0)):Ge._f.onChange&&Ge._f.onChange(Ze);const Ds=A(et,Ts,js),_t=!mb(Ds)||Nt;if(!js&&m.state.next({name:et,type:Ze.type,values:tg(i)}),zt)return(u.isValid||h.isValid)&&(t.mode==="onBlur"?js&&g():js||g()),_t&&m.state.next({name:et,...Nt?{}:Ds});if(!js&&Nt&&m.state.next({...n}),t.resolver){const{errors:Xs}=await P([et]);if(nt(Ts),Qe){const rn=pat(n.errors,r,et),Ps=pat(Xs,r,rn.name||et);Mt=Ps.error,et=Ps.name,Ft=mb(Xs)}}else y([et],!0),Mt=(await xat(Ge,o.disabled,i,p,t.shouldUseNativeValidation))[et],y([et]),nt(Ts),Qe&&(Mt?Ft=!1:(u.isValid||h.isValid)&&(Ft=await I(r,!0)));Qe&&(Ge._f.deps&&ue(Ge._f.deps),T(et,Ft,Mt,Ds))}},ce=(Ze,Ue)=>{if(ji(n.errors,Ue)&&Ze.focus)return Ze.focus(),1},ue=async(Ze,Ue={})=>{let et,Qe;const Ge=hY(Ze);if(t.resolver){const nt=await M(Gf(Ze)?Ze:Ge);et=mb(nt),Qe=Ze?!Ge.some(ft=>ji(nt,ft)):et}else Ze?(Qe=(await Promise.all(Ge.map(async nt=>{const ft=ji(r,nt);return await I(ft&&ft._f?{[nt]:ft}:ft)}))).every(Boolean),!(!Qe&&!n.isValid)&&g()):Qe=et=await I(r);return m.state.next({...!$S(Ze)||(u.isValid||h.isValid)&&et!==n.isValid?{}:{name:Ze},...t.resolver||!Ze?{isValid:et}:{},errors:n.errors}),Ue.shouldFocus&&!Qe&&mY(r,ce,Ze?Ge:o.mount),Qe},ne=Ze=>{const Ue={...l.mount?i:a};return Gf(Ze)?Ue:$S(Ze)?ji(Ue,Ze):Ze.map(et=>ji(Ue,et))},ee=(Ze,Ue)=>({invalid:!!ji((Ue||n).errors,Ze),isDirty:!!ji((Ue||n).dirtyFields,Ze),error:ji((Ue||n).errors,Ze),isValidating:!!ji(n.validatingFields,Ze),isTouched:!!ji((Ue||n).touchedFields,Ze)}),le=Ze=>{Ze&&hY(Ze).forEach(Ue=>_x(n.errors,Ue)),m.state.next({errors:Ze?n.errors:{}})},he=(Ze,Ue,et)=>{const Qe=(ji(r,Ze,{_f:{}})._f||{}).ref,Ge=ji(n.errors,Ze)||{},{ref:nt,message:ft,type:lt,...Mt}=Ge;$u(n.errors,Ze,{...Mt,...Ue,ref:Qe}),m.state.next({name:Ze,errors:n.errors,isValid:!1}),et&&et.shouldFocus&&Qe&&Qe.focus&&Qe.focus()},ve=(Ze,Ue)=>NN(Ze)?m.state.subscribe({next:et=>"values"in et&&Ze(q(void 0,Ue),et)}):q(Ze,Ue,!0),ge=Ze=>m.state.subscribe({next:Ue=>{ums(Ze.name,Ue.name,Ze.exact)&&dms(Ue,Ze.formState||u,Be,Ze.reRenderRoot)&&Ze.callback({values:{...i},...n,...Ue,defaultValues:a})}}).unsubscribe,fe=Ze=>(l.mount=!0,h={...h,...Ze.formState},ge({...Ze,formState:h})),je=(Ze,Ue={})=>{for(const et of Ze?hY(Ze):o.mount)o.mount.delete(et),o.array.delete(et),Ue.keepValue||(_x(r,et),_x(i,et)),!Ue.keepError&&_x(n.errors,et),!Ue.keepDirty&&_x(n.dirtyFields,et),!Ue.keepTouched&&_x(n.touchedFields,et),!Ue.keepIsValidating&&_x(n.validatingFields,et),!t.shouldUnregister&&!Ue.keepDefaultValue&&_x(a,et);m.state.next({values:tg(i)}),m.state.next({...n,...Ue.keepDirty?{isDirty:B()}:{}}),!Ue.keepIsValid&&g()},Ee=({disabled:Ze,name:Ue})=>{($_(Ze)&&l.mount||Ze||o.disabled.has(Ue))&&(Ze?o.disabled.add(Ue):o.disabled.delete(Ue))},Me=(Ze,Ue={})=>{let et=ji(r,Ze);const Qe=$_(Ue.disabled)||$_(t.disabled);return $u(r,Ze,{...et||{},_f:{...et&&et._f?et._f:{ref:{name:Ze}},name:Ze,mount:!0,...Ue}}),o.mount.add(Ze),et?Ee({disabled:$_(Ue.disabled)?Ue.disabled:t.disabled,name:Ze}):C(Ze,!0,Ue.value),{...Qe?{disabled:Ue.disabled||t.disabled}:{},...t.progressive?{required:!!Ue.required,min:YH(Ue.min),max:YH(Ue.max),minLength:YH(Ue.minLength),maxLength:YH(Ue.maxLength),pattern:YH(Ue.pattern)}:{},name:Ze,onChange:J,onBlur:J,ref:Ge=>{if(Ge){Me(Ze,Ue),et=ji(r,Ze);const nt=Gf(Ge.value)&&Ge.querySelectorAll&&Ge.querySelectorAll("input,select,textarea")[0]||Ge,ft=rms(nt),lt=et._f.refs||[];if(ft?lt.find(Mt=>Mt===nt):nt===et._f.ref)return;$u(r,Ze,{_f:{...et._f,...ft?{refs:[...lt.filter(RLe),nt,...Array.isArray(ji(a,Ze))?[{}]:[]],ref:{type:nt.type,name:Ze}}:{ref:nt}}}),C(Ze,!1,void 0,nt)}else et=ji(r,Ze,{}),et._f&&(et._f.mount=!1),(t.shouldUnregister||Ue.shouldUnregister)&&!(A4t(o.array,Ze)&&l.action)&&o.unMount.add(Ze)}}},De=()=>t.shouldFocusError&&mY(r,ce,o.mount),ze=Ze=>{$_(Ze)&&(m.state.next({disabled:Ze}),mY(r,(Ue,et)=>{const Qe=ji(r,et);Qe&&(Ue.disabled=Qe._f.disabled||Ze,Array.isArray(Qe._f.refs)&&Qe._f.refs.forEach(Ge=>{Ge.disabled=Qe._f.disabled||Ze}))},0,!1))},ke=(Ze,Ue)=>async et=>{let Qe;et&&(et.preventDefault&&et.preventDefault(),et.persist&&et.persist());let Ge=tg(i);if(m.state.next({isSubmitting:!0}),t.resolver){const{errors:nt,values:ft}=await P();n.errors=nt,Ge=tg(ft)}else await I(r);if(o.disabled.size)for(const nt of o.disabled)_x(Ge,nt);if(_x(n.errors,"root"),mb(n.errors)){m.state.next({errors:{}});try{await Ze(Ge,et)}catch(nt){Qe=nt}}else Ue&&await Ue({...n.errors},et),De(),setTimeout(De);if(m.state.next({isSubmitted:!0,isSubmitting:!1,isSubmitSuccessful:mb(n.errors)&&!Qe,submitCount:n.submitCount+1,errors:n.errors}),Qe)throw Qe},Xe=(Ze,Ue={})=>{ji(r,Ze)&&(Gf(Ue.defaultValue)?Q(Ze,tg(ji(a,Ze))):(Q(Ze,Ue.defaultValue),$u(a,Ze,tg(Ue.defaultValue))),Ue.keepTouched||_x(n.touchedFields,Ze),Ue.keepDirty||(_x(n.dirtyFields,Ze),n.isDirty=Ue.defaultValue?B(Ze,tg(ji(a,Ze))):B()),Ue.keepError||(_x(n.errors,Ze),u.isValid&&g()),m.state.next({...n}))},Se=(Ze,Ue={})=>{const et=Ze?tg(Ze):a,Qe=tg(et),Ge=mb(Ze),nt=Ge?a:Qe;if(Ue.keepDefaultValues||(a=et),!Ue.keepValues){if(Ue.keepDirtyValues){const ft=new Set([...o.mount,...Object.keys(KH(a,i))]);for(const lt of Array.from(ft))ji(n.dirtyFields,lt)?$u(nt,lt,ji(i,lt)):Q(lt,ji(nt,lt))}else{if(VVe&&Gf(Ze))for(const ft of o.mount){const lt=ji(r,ft);if(lt&<._f){const Mt=Array.isArray(lt._f.refs)?lt._f.refs[0]:lt._f.ref;if(Dke(Mt)){const Ft=Mt.closest("form");if(Ft){Ft.reset();break}}}}if(Ue.keepFieldsRef)for(const ft of o.mount)Q(ft,ji(nt,ft));else r={}}i=t.shouldUnregister?Ue.keepDefaultValues?tg(a):{}:tg(nt),m.array.next({values:{...nt}}),m.state.next({values:{...nt}})}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:Ge?!1:Ue.keepDirty?n.isDirty:!!(Ue.keepDefaultValues&&!C3(Ze,a)),isSubmitted:Ue.keepIsSubmitted?n.isSubmitted:!1,dirtyFields:Ge?{}:Ue.keepDirtyValues?Ue.keepDefaultValues&&i?KH(a,i):n.dirtyFields:Ue.keepDefaultValues&&Ze?KH(a,Ze):Ue.keepDirty?n.dirtyFields:{},touchedFields:Ue.keepTouched?n.touchedFields:{},errors:Ue.keepErrors?n.errors:{},isSubmitSuccessful:Ue.keepIsSubmitSuccessful?n.isSubmitSuccessful:!1,isSubmitting:!1})},Re=(Ze,Ue)=>Se(NN(Ze)?Ze(i):Ze,Ue),Ae=(Ze,Ue={})=>{const et=ji(r,Ze),Qe=et&&et._f;if(Qe){const Ge=Qe.refs?Qe.refs[0]:Qe.ref;Ge.focus&&(Ge.focus(),Ue.shouldSelect&&NN(Ge.select)&&Ge.select())}},Be=Ze=>{n={...n,...Ze}},Ke={control:{register:Me,unregister:je,getFieldState:ee,handleSubmit:ke,setError:he,_subscribe:ge,_runSchema:P,_focusError:De,_getWatch:q,_getDirty:B,_setValid:g,_setFieldArray:b,_setDisabledField:Ee,_setErrors:N,_getFieldArray:W,_reset:Se,_resetDefaultValues:()=>NN(t.defaultValues)&&t.defaultValues().then(Ze=>{Re(Ze,t.resetOptions),m.state.next({isLoading:!1})}),_removeUnmounted:D,_disableForm:ze,_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:fe,trigger:ue,register:Me,handleSubmit:ke,watch:ve,setValue:Q,getValues:ne,reset:Re,resetField:Xe,clearErrors:le,unregister:je,setError:he,setFocus:Ae,getFieldState:ee};return{...Ke,formControl:Ke}}function xCe(s={}){const t=It.useRef(void 0),n=It.useRef(void 0),[r,a]=It.useState({isDirty:!1,isValidating:!1,isLoading:NN(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:NN(s.defaultValues)?void 0:s.defaultValues});if(!t.current)if(s.formControl)t.current={...s.formControl,formState:r},s.defaultValues&&!NN(s.defaultValues)&&s.formControl.reset(s.defaultValues,s.resetOptions);else{const{formControl:l,...o}=xms(s);t.current={...o,formState:r}}const i=t.current.control;return i._options=s,KVe(()=>{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]),It.useEffect(()=>i._disableForm(s.disabled),[i,s.disabled]),It.useEffect(()=>{s.mode&&(i._options.mode=s.mode),s.reValidateMode&&(i._options.reValidateMode=s.reValidateMode)},[i,s.mode,s.reValidateMode]),It.useEffect(()=>{s.errors&&(i._setErrors(s.errors),i._focusError())},[i,s.errors]),It.useEffect(()=>{s.shouldUnregister&&i._subjects.state.next({values:i._getWatch()})},[i,s.shouldUnregister]),It.useEffect(()=>{if(i._proxyFormState.isDirty){const l=i._getDirty();l!==r.isDirty&&i._subjects.state.next({isDirty:l})}},[i,r.isDirty]),It.useEffect(()=>{s.values&&!C3(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]),It.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=E4t(r,i),t.current}const gat=(s,t,n)=>{if(s&&"reportValidity"in s){const r=ji(n,t);s.setCustomValidity(r&&r.message||""),s.reportValidity()}},F4t=(s,t)=>{for(const n in t.fields){const r=t.fields[n];r&&r.ref&&"reportValidity"in r.ref?gat(r.ref,n,s):r.refs&&r.refs.forEach(a=>gat(a,n,s))}},gms=(s,t)=>{t.shouldUseNativeValidation&&F4t(s,t);const n={};for(const r in s){const a=ji(t.fields,r),i=Object.assign(s[r]||{},{ref:a&&a.ref});if(yms(t.names||Object.keys(s),r)){const l=Object.assign({},ji(n,r));$u(l,"root",i),$u(n,r,l)}else $u(n,r,i)}return n},yms=(s,t)=>s.some(n=>n.startsWith(t+"."));var vms=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]=M4t(l,t,n,a,d?[].concat(d,r.message):r.message)}s.shift()}return n},gCe=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&&F4t({},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:gms(vms(l.errors,!i.shouldUseNativeValidation&&i.criteriaMode==="all"),i)};throw l}))}catch(l){return Promise.reject(l)}}},yat;function la(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 tB extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class z4t extends Error{constructor(t){super(`Encountered unidirectional transform during encode: ${t}`),this.name="ZodEncodeError"}}(yat=globalThis).__zod_globalConfig??(yat.__zod_globalConfig={});const XVe=globalThis.__zod_globalConfig;function oO(s){return XVe}function B4t(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 bFe(s,t){return typeof t=="bigint"?t.toString():t}function QVe(s){return{get value(){{const t=s();return Object.defineProperty(this,"value",{value:t}),t}}}}function JVe(s){return s==null}function eHe(s){const t=s.startsWith("^")?1:0,n=s.endsWith("$")?s.length-1:s.length;return s.slice(t,n)}function bms(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 Fke(s){return typeof s=="object"&&s!==null&&!Array.isArray(s)}const wms=QVe(()=>{var s;if(XVe.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 $Z(s){if(Fke(s)===!1)return!1;const t=s.constructor;if(t===void 0||typeof t!="function")return!0;const n=t.prototype;return!(Fke(n)===!1||Object.prototype.hasOwnProperty.call(n,"isPrototypeOf")===!1)}function U4t(s){return $Z(s)?{...s}:Array.isArray(s)?[...s]:s instanceof Map?new Map(s):s instanceof Set?new Set(s):s}const jms=new Set(["string","number","symbol"]);function Q$(s){return s.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function C6(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 Bo(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 Nms(s){return Object.keys(s).filter(t=>s[t]._zod.optin==="optional"&&s[t]._zod.optout==="optional")}const kms={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 Sms(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=S6(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 ZO(this,"shape",l),l},checks:[]});return C6(s,i)}function Cms(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=S6(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 ZO(this,"shape",l),l},checks:[]});return C6(s,i)}function Ams(s,t){if(!$Z(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=S6(s._zod.def,{get shape(){const i={...s._zod.def.shape,...t};return ZO(this,"shape",i),i}});return C6(s,a)}function Ems(s,t){if(!$Z(t))throw new Error("Invalid input to safeExtend: expected a plain object");const n=S6(s._zod.def,{get shape(){const r={...s._zod.def.shape,...t};return ZO(this,"shape",r),r}});return C6(s,n)}function Tms(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=S6(s._zod.def,{get shape(){const a={...s._zod.def.shape,...t._zod.def.shape};return ZO(this,"shape",a),a},get catchall(){return t._zod.def.catchall},checks:t._zod.def.checks??[]});return C6(s,n)}function Mms(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=S6(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 ZO(this,"shape",c),c},checks:[]});return C6(t,l)}function Lms(s,t,n){const r=S6(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 ZO(this,"shape",i),i}});return C6(t,r)}function $9(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 vne(s){return typeof s=="string"?s:s==null?void 0:s.message}function lO(s,t,n){var c,d,u,h,m,p;const r=s.message?s.message:vne((u=(d=(c=s.inst)==null?void 0:c._zod.def)==null?void 0:d.error)==null?void 0:u.call(d,s))??vne((h=t==null?void 0:t.error)==null?void 0:h.call(t,s))??vne((m=n.customError)==null?void 0:m.call(n,s))??vne((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 tHe(s){return Array.isArray(s)?"array":typeof s=="string"?"string":"unknown"}function UZ(...s){const[t,n,r]=s;return typeof t=="string"?{message:t,code:"custom",input:n,inst:r}:{...t}}const V4t=(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,bFe,2),Object.defineProperty(s,"toString",{value:()=>s.message,enumerable:!1})},H4t=la("$ZodError",V4t),G4t=la("$ZodError",V4t,{Parent:Error});function Ims(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 Dms(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 tB;if(l.issues.length){const o=new((a==null?void 0:a.Err)??s)(l.issues.map(c=>lO(c,i,oO())));throw $4t(o,a==null?void 0:a.callee),o}return l.value},nHe=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=>lO(c,i,oO())));throw $4t(o,a==null?void 0:a.callee),o}return l.value},yCe=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 tB;return i.issues.length?{success:!1,error:new(s??H4t)(i.issues.map(l=>lO(l,a,oO())))}:{success:!0,data:i.value}},Rms=yCe(G4t),vCe=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=>lO(l,a,oO())))}:{success:!0,data:i.value}},Oms=vCe(G4t),Fms=s=>(t,n,r)=>{const a=r?{...r,direction:"backward"}:{direction:"backward"};return sHe(s)(t,n,a)},zms=s=>(t,n,r)=>sHe(s)(t,n,r),Bms=s=>async(t,n,r)=>{const a=r?{...r,direction:"backward"}:{direction:"backward"};return nHe(s)(t,n,a)},$ms=s=>async(t,n,r)=>nHe(s)(t,n,r),Ums=s=>(t,n,r)=>{const a=r?{...r,direction:"backward"}:{direction:"backward"};return yCe(s)(t,n,a)},qms=s=>(t,n,r)=>yCe(s)(t,n,r),Vms=s=>async(t,n,r)=>{const a=r?{...r,direction:"backward"}:{direction:"backward"};return vCe(s)(t,n,a)},Hms=s=>async(t,n,r)=>vCe(s)(t,n,r),Gms=/^[cC][0-9a-z]{6,}$/,Wms=/^[0-9a-z]+$/,Kms=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,Yms=/^[0-9a-vA-V]{20}$/,Zms=/^[A-Za-z0-9]{27}$/,Xms=/^[a-zA-Z0-9_-]{21}$/,Qms=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,Jms=/^([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})$/,_at=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)$/,eps=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,tps="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function sps(){return new RegExp(tps,"u")}const nps=/^(?:(?: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])$/,rps=/^(([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}|:))$/,aps=/^((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])$/,ips=/^(([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])$/,ops=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,W4t=/^[A-Za-z0-9_-]*$/,lps=/^https?$/,cps=/^\+[1-9]\d{6,14}$/,K4t="(?:(?:\\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])))",dps=new RegExp(`^${K4t}$`);function Y4t(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 ups(s){return new RegExp(`^${Y4t(s)}$`)}function hps(s){const t=Y4t({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(`^${K4t}T(?:${r})$`)}const mps=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}$`)},pps=/^-?\d+$/,fps=/^-?\d+(?:\.\d+)?$/,xps=/^(?:true|false)$/i,gps=/^[^A-Z]*$/,yps=/^[^a-z]*$/,qb=la("$ZodCheck",(s,t)=>{var n;s._zod??(s._zod={}),s._zod.def=t,(n=s._zod).onattach??(n.onattach=[])}),Z4t={number:"number",bigint:"bigint",object:"date"},X4t=la("$ZodCheckLessThan",(s,t)=>{qb.init(s,t);const n=Z4t[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{qb.init(s,t);const n=Z4t[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})}}),vps=la("$ZodCheckMultipleOf",(s,t)=>{qb.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):bms(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})}}),bps=la("$ZodCheckNumberFormat",(s,t)=>{var l;qb.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]=kms[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=pps)}),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})}}),_ps=la("$ZodCheckMaxLength",(s,t)=>{var n;qb.init(s,t),(n=s._zod.def).when??(n.when=r=>{const a=r.value;return!JVe(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=tHe(a);r.issues.push({origin:l,code:"too_big",maximum:t.maximum,inclusive:!0,input:a,inst:s,continue:!t.abort})}}),wps=la("$ZodCheckMinLength",(s,t)=>{var n;qb.init(s,t),(n=s._zod.def).when??(n.when=r=>{const a=r.value;return!JVe(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=tHe(a);r.issues.push({origin:l,code:"too_small",minimum:t.minimum,inclusive:!0,input:a,inst:s,continue:!t.abort})}}),jps=la("$ZodCheckLengthEquals",(s,t)=>{var n;qb.init(s,t),(n=s._zod.def).when??(n.when=r=>{const a=r.value;return!JVe(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=tHe(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})}}),bCe=la("$ZodCheckStringFormat",(s,t)=>{var n,r;qb.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=()=>{})}),Nps=la("$ZodCheckRegex",(s,t)=>{bCe.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})}}),kps=la("$ZodCheckLowerCase",(s,t)=>{t.pattern??(t.pattern=gps),bCe.init(s,t)}),Sps=la("$ZodCheckUpperCase",(s,t)=>{t.pattern??(t.pattern=yps),bCe.init(s,t)}),Cps=la("$ZodCheckIncludes",(s,t)=>{qb.init(s,t);const n=Q$(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})}}),Aps=la("$ZodCheckStartsWith",(s,t)=>{qb.init(s,t);const n=new RegExp(`^${Q$(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})}}),Eps=la("$ZodCheckEndsWith",(s,t)=>{qb.init(s,t);const n=new RegExp(`.*${Q$(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})}}),Tps=la("$ZodCheckOverwrite",(s,t)=>{qb.init(s,t),s._zod.check=n=>{n.value=t.tx(n.value)}});class Mps{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 Lps={major:4,minor:4,patch:3},Ef=la("$ZodType",(s,t)=>{var a;var n;s??(s={}),s._zod.def=t,s._zod.bag=s._zod.bag||{},s._zod.version=Lps;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=$9(o),h;for(const m of c){if(m._zod.def.when){if(Pms(o)||!m._zod.def.when(o))continue}else if(u)continue;const p=o.issues.length,x=m._zod.check(o);if(x instanceof Promise&&(d==null?void 0:d.async)===!1)throw new tB;if(h||x instanceof Promise)h=(h??Promise.resolve()).then(async()=>{await x,o.issues.length!==p&&(u||(u=$9(o,p)))});else{if(o.issues.length===p)continue;u||(u=$9(o,p))}}return h?h.then(()=>o):o},l=(o,c,d)=>{if($9(o))return o.aborted=!0,o;const u=i(c,r,d);if(u instanceof Promise){if(d.async===!1)throw new tB;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 tB;return d.then(u=>i(u,r,c))}return i(d,r,c)}}ch(s,"~standard",()=>({validate:i=>{var l;try{const o=Rms(s,i);return o.success?{value:o.data}:{issues:(l=o.error)==null?void 0:l.issues}}catch{return Oms(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}))}),rHe=la("$ZodString",(s,t)=>{var n;Ef.init(s,t),s._zod.pattern=[...((n=s==null?void 0:s._zod.bag)==null?void 0:n.patterns)??[]].pop()??mps(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}}),op=la("$ZodStringFormat",(s,t)=>{bCe.init(s,t),rHe.init(s,t)}),Pps=la("$ZodGUID",(s,t)=>{t.pattern??(t.pattern=Jms),op.init(s,t)}),Ips=la("$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=_at(r))}else t.pattern??(t.pattern=_at());op.init(s,t)}),Dps=la("$ZodEmail",(s,t)=>{t.pattern??(t.pattern=eps),op.init(s,t)}),Rps=la("$ZodURL",(s,t)=>{op.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)===lps.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})}}}),Ops=la("$ZodEmoji",(s,t)=>{t.pattern??(t.pattern=sps()),op.init(s,t)}),Fps=la("$ZodNanoID",(s,t)=>{t.pattern??(t.pattern=Xms),op.init(s,t)}),zps=la("$ZodCUID",(s,t)=>{t.pattern??(t.pattern=Gms),op.init(s,t)}),Bps=la("$ZodCUID2",(s,t)=>{t.pattern??(t.pattern=Wms),op.init(s,t)}),$ps=la("$ZodULID",(s,t)=>{t.pattern??(t.pattern=Kms),op.init(s,t)}),Ups=la("$ZodXID",(s,t)=>{t.pattern??(t.pattern=Yms),op.init(s,t)}),qps=la("$ZodKSUID",(s,t)=>{t.pattern??(t.pattern=Zms),op.init(s,t)}),Vps=la("$ZodISODateTime",(s,t)=>{t.pattern??(t.pattern=hps(t)),op.init(s,t)}),Hps=la("$ZodISODate",(s,t)=>{t.pattern??(t.pattern=dps),op.init(s,t)}),Gps=la("$ZodISOTime",(s,t)=>{t.pattern??(t.pattern=ups(t)),op.init(s,t)}),Wps=la("$ZodISODuration",(s,t)=>{t.pattern??(t.pattern=Qms),op.init(s,t)}),Kps=la("$ZodIPv4",(s,t)=>{t.pattern??(t.pattern=nps),op.init(s,t),s._zod.bag.format="ipv4"}),Yps=la("$ZodIPv6",(s,t)=>{t.pattern??(t.pattern=rps),op.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})}}}),Zps=la("$ZodCIDRv4",(s,t)=>{t.pattern??(t.pattern=aps),op.init(s,t)}),Xps=la("$ZodCIDRv6",(s,t)=>{t.pattern??(t.pattern=ips),op.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 J4t(s){if(s==="")return!0;if(/\s/.test(s)||s.length%4!==0)return!1;try{return atob(s),!0}catch{return!1}}const Qps=la("$ZodBase64",(s,t)=>{t.pattern??(t.pattern=ops),op.init(s,t),s._zod.bag.contentEncoding="base64",s._zod.check=n=>{J4t(n.value)||n.issues.push({code:"invalid_format",format:"base64",input:n.value,inst:s,continue:!t.abort})}});function Jps(s){if(!W4t.test(s))return!1;const t=s.replace(/[-_]/g,r=>r==="-"?"+":"/"),n=t.padEnd(Math.ceil(t.length/4)*4,"=");return J4t(n)}const efs=la("$ZodBase64URL",(s,t)=>{t.pattern??(t.pattern=W4t),op.init(s,t),s._zod.bag.contentEncoding="base64url",s._zod.check=n=>{Jps(n.value)||n.issues.push({code:"invalid_format",format:"base64url",input:n.value,inst:s,continue:!t.abort})}}),tfs=la("$ZodE164",(s,t)=>{t.pattern??(t.pattern=cps),op.init(s,t)});function sfs(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 nfs=la("$ZodJWT",(s,t)=>{op.init(s,t),s._zod.check=n=>{sfs(n.value,t.alg)||n.issues.push({code:"invalid_format",format:"jwt",input:n.value,inst:s,continue:!t.abort})}}),e3t=la("$ZodNumber",(s,t)=>{Ef.init(s,t),s._zod.pattern=s._zod.bag.pattern??fps,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}}),rfs=la("$ZodNumberFormat",(s,t)=>{bps.init(s,t),e3t.init(s,t)}),afs=la("$ZodBoolean",(s,t)=>{Ef.init(s,t),s._zod.pattern=xps,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}}),ifs=la("$ZodUnknown",(s,t)=>{Ef.init(s,t),s._zod.parse=n=>n}),ofs=la("$ZodNever",(s,t)=>{Ef.init(s,t),s._zod.parse=(n,r)=>(n.issues.push({expected:"never",code:"invalid_type",input:n.value,inst:s}),n)});function wat(s,t,n){s.issues.length&&t.issues.push(...q4t(n,s.issues)),t.value[n]=s.value}const lfs=la("$ZodArray",(s,t)=>{Ef.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;lwat(d,n,l))):wat(c,n,l)}return i.length?Promise.all(i).then(()=>n):n}});function zke(s,t,n,r,a,i){const l=n in r;if(s.issues.length){if(a&&i&&!l)return;t.issues.push(...q4t(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 t3t(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=Nms(s.shape);return{...s,keys:t,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(n)}}function s3t(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(x=>zke(x,n,m,t,u,h))):zke(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 cfs=la("$ZodObject",(s,t)=>{Ef.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=QVe(()=>t3t(t));ch(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=Fke,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],x=p._zod.optin==="optional",g=p._zod.optout==="optional",y=p._zod.run({value:d[m],issues:[]},c);y instanceof Promise?u.push(y.then(b=>zke(b,o,m,d,x,g))):zke(y,o,m,d,x,g)}return i?s3t(u,d,o,c,r.value,s):u.length?Promise.all(u).then(()=>o):o}}),dfs=la("$ZodObjectJIT",(s,t)=>{cfs.init(s,t);const n=s._zod.parse,r=QVe(()=>t3t(t)),a=m=>{var N,C;const p=new Mps(["shape","payload","ctx"]),x=r.value,g=A=>{const T=bat(A);return`shape[${T}]._zod.run({ value: input[${T}], issues: [] }, ctx)`};p.write("const input = payload.value;");const y=Object.create(null);let b=0;for(const A of x.keys)y[A]=`key_${b++}`;p.write("const newResult = {};");for(const A of x.keys){const T=y[A],P=bat(A),M=m[A],I=((N=M==null?void 0:M._zod)==null?void 0:N.optin)==="optional",D=((C=M==null?void 0:M._zod)==null?void 0:C.optout)==="optional";p.write(`const ${T} = ${g(A)};`),I&&D?p.write(` if (${T}.issues.length) { if (${P} in input) { payload.issues = payload.issues.concat(${T}.issues.map(iss => ({ ...iss, path: iss.path ? [${P}, ...iss.path] : [${P}] }))); } } if (${T}.value === undefined) { if (${P} in input) { newResult[${P}] = undefined; } } else { newResult[${P}] = ${T}.value; } `):I?p.write(` if (${T}.issues.length) { payload.issues = payload.issues.concat(${T}.issues.map(iss => ({ ...iss, path: iss.path ? [${P}, ...iss.path] : [${P}] }))); } if (${T}.value === undefined) { if (${P} in input) { newResult[${P}] = undefined; } } else { newResult[${P}] = ${T}.value; } `):p.write(` const ${T}_present = ${P} in input; if (${T}.issues.length) { payload.issues = payload.issues.concat(${T}.issues.map(iss => ({ ...iss, path: iss.path ? [${P}, ...iss.path] : [${P}] }))); } if (!${T}_present && !${T}.issues.length) { payload.issues.push({ code: "invalid_type", expected: "nonoptional", input: undefined, path: [${P}] }); } if (${T}_present) { if (${T}.value === undefined) { newResult[${P}] = undefined; } else { newResult[${P}] = ${T}.value; } } `)}p.write("payload.value = newResult;"),p.write("return payload;");const v=p.compile();return(A,T)=>v(m,A,T)};let i;const l=Fke,o=!XVe.jitless,d=o&&wms.value,u=t.catchall;let h;s._zod.parse=(m,p)=>{h??(h=r.value);const x=m.value;return l(x)?o&&d&&(p==null?void 0:p.async)===!1&&p.jitless!==!0?(i||(i=a(t.shape)),m=i(m,p),u?s3t([],x,m,p,h,s):m):n(m,p):(m.issues.push({expected:"object",code:"invalid_type",input:x,inst:s}),m)}});function jat(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=>!$9(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=>lO(l,r,oO())))}),t)}const ufs=la("$ZodUnion",(s,t)=>{Ef.init(s,t),ch(s._zod,"optin",()=>t.options.some(r=>r._zod.optin==="optional")?"optional":void 0),ch(s._zod,"optout",()=>t.options.some(r=>r._zod.optout==="optional")?"optional":void 0),ch(s._zod,"values",()=>{if(t.options.every(r=>r._zod.values))return new Set(t.options.flatMap(r=>Array.from(r._zod.values)))}),ch(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=>eHe(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=>jat(o,r,s,a)):jat(l,r,s,a)}}),hfs=la("$ZodIntersection",(s,t)=>{Ef.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])=>Nat(n,c,d)):Nat(n,i,l)}});function _Fe(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($Z(s)&&$Z(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=_Fe(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}),$9(s))return s;const l=_Fe(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 mfs=la("$ZodEnum",(s,t)=>{Ef.init(s,t);const n=B4t(t.entries),r=new Set(n);s._zod.values=r,s._zod.pattern=new RegExp(`^(${n.filter(a=>jms.has(typeof a)).map(a=>typeof a=="string"?Q$(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}}),pfs=la("$ZodLiteral",(s,t)=>{if(Ef.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"?Q$(r):r?Q$(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}}),ffs=la("$ZodTransform",(s,t)=>{Ef.init(s,t),s._zod.optin="optional",s._zod.parse=(n,r)=>{if(r.direction==="backward")throw new z4t(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 tB;return n.value=a,n.fallback=!0,n}});function kat(s,t){return t===void 0&&(s.issues.length||s.fallback)?{issues:[],value:void 0}:s}const n3t=la("$ZodOptional",(s,t)=>{Ef.init(s,t),s._zod.optin="optional",s._zod.optout="optional",ch(s._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),ch(s._zod,"pattern",()=>{const n=t.innerType._zod.pattern;return n?new RegExp(`^(${eHe(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=>kat(l,a)):kat(i,a)}return n.value===void 0?n:t.innerType._zod.run(n,r)}}),xfs=la("$ZodExactOptional",(s,t)=>{n3t.init(s,t),ch(s._zod,"values",()=>t.innerType._zod.values),ch(s._zod,"pattern",()=>t.innerType._zod.pattern),s._zod.parse=(n,r)=>t.innerType._zod.run(n,r)}),gfs=la("$ZodNullable",(s,t)=>{Ef.init(s,t),ch(s._zod,"optin",()=>t.innerType._zod.optin),ch(s._zod,"optout",()=>t.innerType._zod.optout),ch(s._zod,"pattern",()=>{const n=t.innerType._zod.pattern;return n?new RegExp(`^(${eHe(n.source)}|null)$`):void 0}),ch(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)}),yfs=la("$ZodDefault",(s,t)=>{Ef.init(s,t),s._zod.optin="optional",ch(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=>Sat(i,t)):Sat(a,t)}});function Sat(s,t){return s.value===void 0&&(s.value=t.defaultValue),s}const vfs=la("$ZodPrefault",(s,t)=>{Ef.init(s,t),s._zod.optin="optional",ch(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))}),bfs=la("$ZodNonOptional",(s,t)=>{Ef.init(s,t),ch(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=>Cat(i,s)):Cat(a,s)}});function Cat(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 _fs=la("$ZodCatch",(s,t)=>{Ef.init(s,t),s._zod.optin="optional",ch(s._zod,"optout",()=>t.innerType._zod.optout),ch(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=>lO(l,r,oO()))},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=>lO(i,r,oO()))},input:n.value}),n.issues=[],n.fallback=!0),n)}}),wfs=la("$ZodPipe",(s,t)=>{Ef.init(s,t),ch(s._zod,"values",()=>t.in._zod.values),ch(s._zod,"optin",()=>t.in._zod.optin),ch(s._zod,"optout",()=>t.out._zod.optout),ch(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=>bne(l,t.in,r)):bne(i,t.in,r)}const a=t.in._zod.run(n,r);return a instanceof Promise?a.then(i=>bne(i,t.out,r)):bne(a,t.out,r)}});function bne(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 jfs=la("$ZodReadonly",(s,t)=>{Ef.init(s,t),ch(s._zod,"propValues",()=>t.innerType._zod.propValues),ch(s._zod,"values",()=>t.innerType._zod.values),ch(s._zod,"optin",()=>{var n,r;return(r=(n=t.innerType)==null?void 0:n._zod)==null?void 0:r.optin}),ch(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(Aat):Aat(a)}});function Aat(s){return s.value=Object.freeze(s.value),s}const Nfs=la("$ZodCustom",(s,t)=>{qb.init(s,t),Ef.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=>Eat(i,n,r,s));Eat(a,n,r,s)}});function Eat(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(UZ(a))}}var Tat;class kfs{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 Sfs(){return new kfs}(Tat=globalThis).__zod_globalRegistry??(Tat.__zod_globalRegistry=Sfs());const fW=globalThis.__zod_globalRegistry;function Cfs(s,t){return new s({type:"string",...Bo(t)})}function Afs(s,t){return new s({type:"string",format:"email",check:"string_format",abort:!1,...Bo(t)})}function Mat(s,t){return new s({type:"string",format:"guid",check:"string_format",abort:!1,...Bo(t)})}function Efs(s,t){return new s({type:"string",format:"uuid",check:"string_format",abort:!1,...Bo(t)})}function Tfs(s,t){return new s({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...Bo(t)})}function Mfs(s,t){return new s({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...Bo(t)})}function Lfs(s,t){return new s({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...Bo(t)})}function Pfs(s,t){return new s({type:"string",format:"url",check:"string_format",abort:!1,...Bo(t)})}function Ifs(s,t){return new s({type:"string",format:"emoji",check:"string_format",abort:!1,...Bo(t)})}function Dfs(s,t){return new s({type:"string",format:"nanoid",check:"string_format",abort:!1,...Bo(t)})}function Rfs(s,t){return new s({type:"string",format:"cuid",check:"string_format",abort:!1,...Bo(t)})}function Ofs(s,t){return new s({type:"string",format:"cuid2",check:"string_format",abort:!1,...Bo(t)})}function Ffs(s,t){return new s({type:"string",format:"ulid",check:"string_format",abort:!1,...Bo(t)})}function zfs(s,t){return new s({type:"string",format:"xid",check:"string_format",abort:!1,...Bo(t)})}function Bfs(s,t){return new s({type:"string",format:"ksuid",check:"string_format",abort:!1,...Bo(t)})}function $fs(s,t){return new s({type:"string",format:"ipv4",check:"string_format",abort:!1,...Bo(t)})}function Ufs(s,t){return new s({type:"string",format:"ipv6",check:"string_format",abort:!1,...Bo(t)})}function qfs(s,t){return new s({type:"string",format:"cidrv4",check:"string_format",abort:!1,...Bo(t)})}function Vfs(s,t){return new s({type:"string",format:"cidrv6",check:"string_format",abort:!1,...Bo(t)})}function Hfs(s,t){return new s({type:"string",format:"base64",check:"string_format",abort:!1,...Bo(t)})}function Gfs(s,t){return new s({type:"string",format:"base64url",check:"string_format",abort:!1,...Bo(t)})}function Wfs(s,t){return new s({type:"string",format:"e164",check:"string_format",abort:!1,...Bo(t)})}function Kfs(s,t){return new s({type:"string",format:"jwt",check:"string_format",abort:!1,...Bo(t)})}function Yfs(s,t){return new s({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...Bo(t)})}function Zfs(s,t){return new s({type:"string",format:"date",check:"string_format",...Bo(t)})}function Xfs(s,t){return new s({type:"string",format:"time",check:"string_format",precision:null,...Bo(t)})}function Qfs(s,t){return new s({type:"string",format:"duration",check:"string_format",...Bo(t)})}function Jfs(s,t){return new s({type:"number",checks:[],...Bo(t)})}function exs(s,t){return new s({type:"number",check:"number_format",abort:!1,format:"safeint",...Bo(t)})}function txs(s,t){return new s({type:"boolean",...Bo(t)})}function sxs(s){return new s({type:"unknown"})}function nxs(s,t){return new s({type:"never",...Bo(t)})}function Lat(s,t){return new X4t({check:"less_than",...Bo(t),value:s,inclusive:!1})}function OLe(s,t){return new X4t({check:"less_than",...Bo(t),value:s,inclusive:!0})}function Pat(s,t){return new Q4t({check:"greater_than",...Bo(t),value:s,inclusive:!1})}function FLe(s,t){return new Q4t({check:"greater_than",...Bo(t),value:s,inclusive:!0})}function Iat(s,t){return new vps({check:"multiple_of",...Bo(t),value:s})}function r3t(s,t){return new _ps({check:"max_length",...Bo(t),maximum:s})}function Bke(s,t){return new wps({check:"min_length",...Bo(t),minimum:s})}function a3t(s,t){return new jps({check:"length_equals",...Bo(t),length:s})}function rxs(s,t){return new Nps({check:"string_format",format:"regex",...Bo(t),pattern:s})}function axs(s){return new kps({check:"string_format",format:"lowercase",...Bo(s)})}function ixs(s){return new Sps({check:"string_format",format:"uppercase",...Bo(s)})}function oxs(s,t){return new Cps({check:"string_format",format:"includes",...Bo(t),includes:s})}function lxs(s,t){return new Aps({check:"string_format",format:"starts_with",...Bo(t),prefix:s})}function cxs(s,t){return new Eps({check:"string_format",format:"ends_with",...Bo(t),suffix:s})}function kq(s){return new Tps({check:"overwrite",tx:s})}function dxs(s){return kq(t=>t.normalize(s))}function uxs(){return kq(s=>s.trim())}function hxs(){return kq(s=>s.toLowerCase())}function mxs(){return kq(s=>s.toUpperCase())}function pxs(){return kq(s=>_ms(s))}function fxs(s,t,n){return new s({type:"array",element:t,...Bo(n)})}function xxs(s,t,n){return new s({type:"custom",check:"custom",fn:t,...Bo(n)})}function gxs(s,t){const n=yxs(r=>(r.addIssue=a=>{if(typeof a=="string")r.issues.push(UZ(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(UZ(i))}},s(r.value,r)),t);return n}function yxs(s,t){const n=new qb({check:"custom",...Bo(t)});return n._zod.check=s,n}function i3t(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)??fW,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 Ny(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 x=l.schema,g=t.processors[a.type];if(!g)throw new Error(`[toJSONSchema]: Non-representable type encountered: ${a.type}`);g(s,t,x,m)}const p=s._zod.parent;p&&(l.ref||(l.ref=p),Ny(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"&&qv(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 o3t(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 g;const h=s.target==="draft-2020-12"?"$defs":"definitions";if(s.external){const y=(g=s.external.registry.get(u[0]))==null?void 0:g.id,b=s.external.uri??(N=>N);if(y)return{ref:b(y)};const v=u[1].defId??u[1].schema.id??`schema${s.counter++}`;return u[1].defId=v,{defId:v,ref:`${b("__shared")}#/${h}/${v}`}}if(u[1]===n)return{ref:"#"};const p=`#/${h}/`,x=u[1].schema.id??`__schema${s.counter++}`;return{defId:x,ref:p+x}},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 x=h.schema;for(const g in x)delete x[g];x.$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 l3t(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,x={...p},g=m.ref;if(m.ref=null,g){r(g);const b=s.seen.get(g),v=b.schema;if(v.$ref&&(s.target==="draft-07"||s.target==="draft-04"||s.target==="openapi-3.0")?(p.allOf=p.allOf??[],p.allOf.push(v)):Object.assign(p,v),Object.assign(p,x),h._zod.parent===g)for(const C in p)C==="$ref"||C==="allOf"||C in x||delete p[C];if(v.$ref&&b.def)for(const C in p)C==="$ref"||C==="allOf"||C in b.def&&JSON.stringify(p[C])===JSON.stringify(b.def[C])&&delete p[C]}const y=h._zod.parent;if(y&&y!==g){r(y);const b=s.seen.get(y);if(b!=null&&b.schema.$ref&&(p.$ref=b.schema.$ref,b.def))for(const v in p)v==="$ref"||v==="allOf"||v in b.def&&JSON.stringify(p[v])===JSON.stringify(b.def[v])&&delete p[v]}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:$ke(t,"input",s.processors),output:$ke(t,"output",s.processors)}},enumerable:!1,writable:!1}),h}catch{throw new Error("Error converting schema to JSON.")}}function qv(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 qv(r.element,n);if(r.type==="set")return qv(r.valueType,n);if(r.type==="lazy")return qv(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 qv(r.innerType,n);if(r.type==="intersection")return qv(r.left,n)||qv(r.right,n);if(r.type==="record"||r.type==="map")return qv(r.keyType,n)||qv(r.valueType,n);if(r.type==="pipe")return s._zod.traits.has("$ZodCodec")?!0:qv(r.in,n)||qv(r.out,n);if(r.type==="object"){for(const a in r.shape)if(qv(r.shape[a],n))return!0;return!1}if(r.type==="union"){for(const a of r.options)if(qv(a,n))return!0;return!1}if(r.type==="tuple"){for(const a of r.items)if(qv(a,n))return!0;return!!(r.rest&&qv(r.rest,n))}return!1}const vxs=(s,t={})=>n=>{const r=i3t({...n,processors:t});return Ny(s,r),o3t(r,s),l3t(r,s)},$ke=(s,t,n={})=>r=>{const{libraryOptions:a,target:i}=r??{},l=i3t({...a??{},target:i,io:t,processors:n});return Ny(s,l),o3t(l,s),l3t(l,s)},bxs={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},_xs=(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=bxs[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}))])}},wxs=(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)},jxs=(s,t,n,r)=>{n.type="boolean"},Nxs=(s,t,n,r)=>{n.not={}},kxs=(s,t,n,r)=>{},Sxs=(s,t,n,r)=>{const a=s._zod.def,i=B4t(a.entries);i.every(l=>typeof l=="number")&&(n.type="number"),i.every(l=>typeof l=="string")&&(n.type="string"),n.enum=i},Cxs=(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},Axs=(s,t,n,r)=>{if(t.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema")},Exs=(s,t,n,r)=>{if(t.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema")},Txs=(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=Ny(i.element,t,{...r,path:[...r.path,"items"]})},Mxs=(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]=Ny(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=Ny(i.catchall,t,{...r,path:[...r.path,"additionalProperties"]})):t.io==="output"&&(a.additionalProperties=!1)},Lxs=(s,t,n,r)=>{const a=s._zod.def,i=a.inclusive===!1,l=a.options.map((o,c)=>Ny(o,t,{...r,path:[...r.path,i?"oneOf":"anyOf",c]}));i?n.oneOf=l:n.anyOf=l},Pxs=(s,t,n,r)=>{const a=s._zod.def,i=Ny(a.left,t,{...r,path:[...r.path,"allOf",0]}),l=Ny(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},Ixs=(s,t,n,r)=>{const a=s._zod.def,i=Ny(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"}]},Dxs=(s,t,n,r)=>{const a=s._zod.def;Ny(a.innerType,t,r);const i=t.seen.get(s);i.ref=a.innerType},Rxs=(s,t,n,r)=>{const a=s._zod.def;Ny(a.innerType,t,r);const i=t.seen.get(s);i.ref=a.innerType,n.default=JSON.parse(JSON.stringify(a.defaultValue))},Oxs=(s,t,n,r)=>{const a=s._zod.def;Ny(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)))},Fxs=(s,t,n,r)=>{const a=s._zod.def;Ny(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},zxs=(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;Ny(l,t,r);const o=t.seen.get(s);o.ref=l},Bxs=(s,t,n,r)=>{const a=s._zod.def;Ny(a.innerType,t,r);const i=t.seen.get(s);i.ref=a.innerType,n.readOnly=!0},c3t=(s,t,n,r)=>{const a=s._zod.def;Ny(a.innerType,t,r);const i=t.seen.get(s);i.ref=a.innerType},$xs=la("ZodISODateTime",(s,t)=>{Vps.init(s,t),Gp.init(s,t)});function Uxs(s){return Yfs($xs,s)}const qxs=la("ZodISODate",(s,t)=>{Hps.init(s,t),Gp.init(s,t)});function Vxs(s){return Zfs(qxs,s)}const Hxs=la("ZodISOTime",(s,t)=>{Gps.init(s,t),Gp.init(s,t)});function Gxs(s){return Xfs(Hxs,s)}const Wxs=la("ZodISODuration",(s,t)=>{Wps.init(s,t),Gp.init(s,t)});function Kxs(s){return Qfs(Wxs,s)}const d3t=(s,t)=>{H4t.init(s,t),s.name="ZodError",Object.defineProperties(s,{format:{value:n=>Dms(s,n)},flatten:{value:n=>Ims(s,n)},addIssue:{value:n=>{s.issues.push(n),s.message=JSON.stringify(s.issues,bFe,2)}},addIssues:{value:n=>{s.issues.push(...n),s.message=JSON.stringify(s.issues,bFe,2)}},isEmpty:{get(){return s.issues.length===0}}})},Yxs=la("ZodError",d3t),h2=la("ZodError",d3t,{Parent:Error}),Zxs=sHe(h2),Xxs=nHe(h2),Qxs=yCe(h2),Jxs=vCe(h2),egs=Fms(h2),tgs=zms(h2),sgs=Bms(h2),ngs=$ms(h2),rgs=Ums(h2),ags=qms(h2),igs=Vms(h2),ogs=Hms(h2),Dat=new WeakMap;function hee(s,t,n){const r=Object.getPrototypeOf(s);let a=Dat.get(r);if(a||(a=new Set,Dat.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 Tf=la("ZodType",(s,t)=>(Ef.init(s,t),Object.assign(s["~standard"],{jsonSchema:{input:$ke(s,"input"),output:$ke(s,"output")}}),s.toJSONSchema=vxs(s,{}),s.def=t,s.type=t.type,Object.defineProperty(s,"_def",{value:t}),s.parse=(n,r)=>Zxs(s,n,r,{callee:s.parse}),s.safeParse=(n,r)=>Qxs(s,n,r),s.parseAsync=async(n,r)=>Xxs(s,n,r,{callee:s.parseAsync}),s.safeParseAsync=async(n,r)=>Jxs(s,n,r),s.spa=s.safeParseAsync,s.encode=(n,r)=>egs(s,n,r),s.decode=(n,r)=>tgs(s,n,r),s.encodeAsync=async(n,r)=>sgs(s,n,r),s.decodeAsync=async(n,r)=>ngs(s,n,r),s.safeEncode=(n,r)=>rgs(s,n,r),s.safeDecode=(n,r)=>ags(s,n,r),s.safeEncodeAsync=async(n,r)=>igs(s,n,r),s.safeDecodeAsync=async(n,r)=>ogs(s,n,r),hee(s,"ZodType",{check(...n){const r=this.def;return this.clone(S6(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 C6(this,n,r)},brand(){return this},register(n,r){return n.add(this,r),this},refine(n,r){return this.check(s0s(n,r))},superRefine(n,r){return this.check(n0s(n,r))},overwrite(n){return this.check(kq(n))},optional(){return zat(this)},exactOptional(){return qgs(this)},nullable(){return Bat(this)},nullish(){return zat(Bat(this))},nonoptional(n){return Ygs(this,n)},array(){return Pgs(this)},or(n){return Rgs([this,n])},and(n){return Fgs(this,n)},transform(n){return $at(this,$gs(n))},default(n){return Ggs(this,n)},prefault(n){return Kgs(this,n)},catch(n){return Xgs(this,n)},pipe(n){return $at(this,n)},readonly(){return e0s(this)},describe(n){const r=this.clone();return fW.add(r,{description:n}),r},meta(...n){if(n.length===0)return fW.get(this);const r=this.clone();return fW.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=fW.get(s))==null?void 0:n.description},configurable:!0}),s)),u3t=la("_ZodString",(s,t)=>{rHe.init(s,t),Tf.init(s,t),s._zod.processJSONSchema=(r,a,i)=>_xs(s,r,a);const n=s._zod.bag;s.format=n.format??null,s.minLength=n.minimum??null,s.maxLength=n.maximum??null,hee(s,"_ZodString",{regex(...r){return this.check(rxs(...r))},includes(...r){return this.check(oxs(...r))},startsWith(...r){return this.check(lxs(...r))},endsWith(...r){return this.check(cxs(...r))},min(...r){return this.check(Bke(...r))},max(...r){return this.check(r3t(...r))},length(...r){return this.check(a3t(...r))},nonempty(...r){return this.check(Bke(1,...r))},lowercase(r){return this.check(axs(r))},uppercase(r){return this.check(ixs(r))},trim(){return this.check(uxs())},normalize(...r){return this.check(dxs(...r))},toLowerCase(){return this.check(hxs())},toUpperCase(){return this.check(mxs())},slugify(){return this.check(pxs())}})}),lgs=la("ZodString",(s,t)=>{rHe.init(s,t),u3t.init(s,t),s.email=n=>s.check(Afs(cgs,n)),s.url=n=>s.check(Pfs(dgs,n)),s.jwt=n=>s.check(Kfs(kgs,n)),s.emoji=n=>s.check(Ifs(ugs,n)),s.guid=n=>s.check(Mat(Rat,n)),s.uuid=n=>s.check(Efs(_ne,n)),s.uuidv4=n=>s.check(Tfs(_ne,n)),s.uuidv6=n=>s.check(Mfs(_ne,n)),s.uuidv7=n=>s.check(Lfs(_ne,n)),s.nanoid=n=>s.check(Dfs(hgs,n)),s.guid=n=>s.check(Mat(Rat,n)),s.cuid=n=>s.check(Rfs(mgs,n)),s.cuid2=n=>s.check(Ofs(pgs,n)),s.ulid=n=>s.check(Ffs(fgs,n)),s.base64=n=>s.check(Hfs(wgs,n)),s.base64url=n=>s.check(Gfs(jgs,n)),s.xid=n=>s.check(zfs(xgs,n)),s.ksuid=n=>s.check(Bfs(ggs,n)),s.ipv4=n=>s.check($fs(ygs,n)),s.ipv6=n=>s.check(Ufs(vgs,n)),s.cidrv4=n=>s.check(qfs(bgs,n)),s.cidrv6=n=>s.check(Vfs(_gs,n)),s.e164=n=>s.check(Wfs(Ngs,n)),s.datetime=n=>s.check(Uxs(n)),s.date=n=>s.check(Vxs(n)),s.time=n=>s.check(Gxs(n)),s.duration=n=>s.check(Kxs(n))});function rl(s){return Cfs(lgs,s)}const Gp=la("ZodStringFormat",(s,t)=>{op.init(s,t),u3t.init(s,t)}),cgs=la("ZodEmail",(s,t)=>{Dps.init(s,t),Gp.init(s,t)}),Rat=la("ZodGUID",(s,t)=>{Pps.init(s,t),Gp.init(s,t)}),_ne=la("ZodUUID",(s,t)=>{Ips.init(s,t),Gp.init(s,t)}),dgs=la("ZodURL",(s,t)=>{Rps.init(s,t),Gp.init(s,t)}),ugs=la("ZodEmoji",(s,t)=>{Ops.init(s,t),Gp.init(s,t)}),hgs=la("ZodNanoID",(s,t)=>{Fps.init(s,t),Gp.init(s,t)}),mgs=la("ZodCUID",(s,t)=>{zps.init(s,t),Gp.init(s,t)}),pgs=la("ZodCUID2",(s,t)=>{Bps.init(s,t),Gp.init(s,t)}),fgs=la("ZodULID",(s,t)=>{$ps.init(s,t),Gp.init(s,t)}),xgs=la("ZodXID",(s,t)=>{Ups.init(s,t),Gp.init(s,t)}),ggs=la("ZodKSUID",(s,t)=>{qps.init(s,t),Gp.init(s,t)}),ygs=la("ZodIPv4",(s,t)=>{Kps.init(s,t),Gp.init(s,t)}),vgs=la("ZodIPv6",(s,t)=>{Yps.init(s,t),Gp.init(s,t)}),bgs=la("ZodCIDRv4",(s,t)=>{Zps.init(s,t),Gp.init(s,t)}),_gs=la("ZodCIDRv6",(s,t)=>{Xps.init(s,t),Gp.init(s,t)}),wgs=la("ZodBase64",(s,t)=>{Qps.init(s,t),Gp.init(s,t)}),jgs=la("ZodBase64URL",(s,t)=>{efs.init(s,t),Gp.init(s,t)}),Ngs=la("ZodE164",(s,t)=>{tfs.init(s,t),Gp.init(s,t)}),kgs=la("ZodJWT",(s,t)=>{nfs.init(s,t),Gp.init(s,t)}),h3t=la("ZodNumber",(s,t)=>{e3t.init(s,t),Tf.init(s,t),s._zod.processJSONSchema=(r,a,i)=>wxs(s,r,a),hee(s,"ZodNumber",{gt(r,a){return this.check(Pat(r,a))},gte(r,a){return this.check(FLe(r,a))},min(r,a){return this.check(FLe(r,a))},lt(r,a){return this.check(Lat(r,a))},lte(r,a){return this.check(OLe(r,a))},max(r,a){return this.check(OLe(r,a))},int(r){return this.check(Oat(r))},safe(r){return this.check(Oat(r))},positive(r){return this.check(Pat(0,r))},nonnegative(r){return this.check(FLe(0,r))},negative(r){return this.check(Lat(0,r))},nonpositive(r){return this.check(OLe(0,r))},multipleOf(r,a){return this.check(Iat(r,a))},step(r,a){return this.check(Iat(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 pY(s){return Jfs(h3t,s)}const Sgs=la("ZodNumberFormat",(s,t)=>{rfs.init(s,t),h3t.init(s,t)});function Oat(s){return exs(Sgs,s)}const Cgs=la("ZodBoolean",(s,t)=>{afs.init(s,t),Tf.init(s,t),s._zod.processJSONSchema=(n,r,a)=>jxs(s,n,r)});function Ags(s){return txs(Cgs,s)}const Egs=la("ZodUnknown",(s,t)=>{ifs.init(s,t),Tf.init(s,t),s._zod.processJSONSchema=(n,r,a)=>kxs()});function Fat(){return sxs(Egs)}const Tgs=la("ZodNever",(s,t)=>{ofs.init(s,t),Tf.init(s,t),s._zod.processJSONSchema=(n,r,a)=>Nxs(s,n,r)});function Mgs(s){return nxs(Tgs,s)}const Lgs=la("ZodArray",(s,t)=>{lfs.init(s,t),Tf.init(s,t),s._zod.processJSONSchema=(n,r,a)=>Txs(s,n,r,a),s.element=t.element,hee(s,"ZodArray",{min(n,r){return this.check(Bke(n,r))},nonempty(n){return this.check(Bke(1,n))},max(n,r){return this.check(r3t(n,r))},length(n,r){return this.check(a3t(n,r))},unwrap(){return this.element}})});function Pgs(s,t){return fxs(Lgs,s,t)}const Igs=la("ZodObject",(s,t)=>{dfs.init(s,t),Tf.init(s,t),s._zod.processJSONSchema=(n,r,a)=>Mxs(s,n,r,a),ch(s,"shape",()=>t.shape),hee(s,"ZodObject",{keyof(){return aHe(Object.keys(this._zod.def.shape))},catchall(n){return this.clone({...this._zod.def,catchall:n})},passthrough(){return this.clone({...this._zod.def,catchall:Fat()})},loose(){return this.clone({...this._zod.def,catchall:Fat()})},strict(){return this.clone({...this._zod.def,catchall:Mgs()})},strip(){return this.clone({...this._zod.def,catchall:void 0})},extend(n){return Ams(this,n)},safeExtend(n){return Ems(this,n)},merge(n){return Tms(this,n)},pick(n){return Sms(this,n)},omit(n){return Cms(this,n)},partial(...n){return Mms(m3t,this,n[0])},required(...n){return Lms(p3t,this,n[0])}})});function tk(s,t){const n={type:"object",shape:s??{},...Bo(t)};return new Igs(n)}const Dgs=la("ZodUnion",(s,t)=>{ufs.init(s,t),Tf.init(s,t),s._zod.processJSONSchema=(n,r,a)=>Lxs(s,n,r,a),s.options=t.options});function Rgs(s,t){return new Dgs({type:"union",options:s,...Bo(t)})}const Ogs=la("ZodIntersection",(s,t)=>{hfs.init(s,t),Tf.init(s,t),s._zod.processJSONSchema=(n,r,a)=>Pxs(s,n,r,a)});function Fgs(s,t){return new Ogs({type:"intersection",left:s,right:t})}const wFe=la("ZodEnum",(s,t)=>{mfs.init(s,t),Tf.init(s,t),s._zod.processJSONSchema=(r,a,i)=>Sxs(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 wFe({...t,checks:[],...Bo(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 wFe({...t,checks:[],...Bo(a),entries:i})}});function aHe(s,t){const n=Array.isArray(s)?Object.fromEntries(s.map(r=>[r,r])):s;return new wFe({type:"enum",entries:n,...Bo(t)})}const zgs=la("ZodLiteral",(s,t)=>{pfs.init(s,t),Tf.init(s,t),s._zod.processJSONSchema=(n,r,a)=>Cxs(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 Sx(s,t){return new zgs({type:"literal",values:Array.isArray(s)?s:[s],...Bo(t)})}const Bgs=la("ZodTransform",(s,t)=>{ffs.init(s,t),Tf.init(s,t),s._zod.processJSONSchema=(n,r,a)=>Exs(s,n),s._zod.parse=(n,r)=>{if(r.direction==="backward")throw new z4t(s.constructor.name);n.addIssue=i=>{if(typeof i=="string")n.issues.push(UZ(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(UZ(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 $gs(s){return new Bgs({type:"transform",transform:s})}const m3t=la("ZodOptional",(s,t)=>{n3t.init(s,t),Tf.init(s,t),s._zod.processJSONSchema=(n,r,a)=>c3t(s,n,r,a),s.unwrap=()=>s._zod.def.innerType});function zat(s){return new m3t({type:"optional",innerType:s})}const Ugs=la("ZodExactOptional",(s,t)=>{xfs.init(s,t),Tf.init(s,t),s._zod.processJSONSchema=(n,r,a)=>c3t(s,n,r,a),s.unwrap=()=>s._zod.def.innerType});function qgs(s){return new Ugs({type:"optional",innerType:s})}const Vgs=la("ZodNullable",(s,t)=>{gfs.init(s,t),Tf.init(s,t),s._zod.processJSONSchema=(n,r,a)=>Ixs(s,n,r,a),s.unwrap=()=>s._zod.def.innerType});function Bat(s){return new Vgs({type:"nullable",innerType:s})}const Hgs=la("ZodDefault",(s,t)=>{yfs.init(s,t),Tf.init(s,t),s._zod.processJSONSchema=(n,r,a)=>Rxs(s,n,r,a),s.unwrap=()=>s._zod.def.innerType,s.removeDefault=s.unwrap});function Ggs(s,t){return new Hgs({type:"default",innerType:s,get defaultValue(){return typeof t=="function"?t():U4t(t)}})}const Wgs=la("ZodPrefault",(s,t)=>{vfs.init(s,t),Tf.init(s,t),s._zod.processJSONSchema=(n,r,a)=>Oxs(s,n,r,a),s.unwrap=()=>s._zod.def.innerType});function Kgs(s,t){return new Wgs({type:"prefault",innerType:s,get defaultValue(){return typeof t=="function"?t():U4t(t)}})}const p3t=la("ZodNonOptional",(s,t)=>{bfs.init(s,t),Tf.init(s,t),s._zod.processJSONSchema=(n,r,a)=>Dxs(s,n,r,a),s.unwrap=()=>s._zod.def.innerType});function Ygs(s,t){return new p3t({type:"nonoptional",innerType:s,...Bo(t)})}const Zgs=la("ZodCatch",(s,t)=>{_fs.init(s,t),Tf.init(s,t),s._zod.processJSONSchema=(n,r,a)=>Fxs(s,n,r,a),s.unwrap=()=>s._zod.def.innerType,s.removeCatch=s.unwrap});function Xgs(s,t){return new Zgs({type:"catch",innerType:s,catchValue:typeof t=="function"?t:()=>t})}const Qgs=la("ZodPipe",(s,t)=>{wfs.init(s,t),Tf.init(s,t),s._zod.processJSONSchema=(n,r,a)=>zxs(s,n,r,a),s.in=t.in,s.out=t.out});function $at(s,t){return new Qgs({type:"pipe",in:s,out:t})}const Jgs=la("ZodReadonly",(s,t)=>{jfs.init(s,t),Tf.init(s,t),s._zod.processJSONSchema=(n,r,a)=>Bxs(s,n,r,a),s.unwrap=()=>s._zod.def.innerType});function e0s(s){return new Jgs({type:"readonly",innerType:s})}const t0s=la("ZodCustom",(s,t)=>{Nfs.init(s,t),Tf.init(s,t),s._zod.processJSONSchema=(n,r,a)=>Axs(s,n)});function s0s(s,t={}){return xxs(t0s,s,t)}function n0s(s,t){return gxs(s,t)}var r0s="Label",f3t=j.forwardRef((s,t)=>e.jsx(Ka.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())}}));f3t.displayName=r0s;var x3t=f3t;const a0s=GO("text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"),se=j.forwardRef(({className:s,...t},n)=>e.jsx(x3t,{ref:n,className:Tt(a0s(),s),...t}));se.displayName=x3t.displayName;const _Ce=Jhs,g3t=j.createContext({}),Cp=({...s})=>e.jsx(g3t.Provider,{value:{name:s.name},children:e.jsx(nms,{...s})}),wCe=()=>{const s=j.useContext(g3t),t=j.useContext(y3t),{getFieldState:n,formState:r}=fCe(),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}},y3t=j.createContext({}),Ym=j.forwardRef(({className:s,...t},n)=>{const r=j.useId();return e.jsx(y3t.Provider,{value:{id:r},children:e.jsx("div",{ref:n,className:Tt("space-y-2",s),...t})})});Ym.displayName="FormItem";const Zm=j.forwardRef(({className:s,...t},n)=>{const{error:r,formItemId:a}=wCe();return e.jsx(se,{ref:n,className:Tt(r&&"text-destructive",s),htmlFor:a,...t})});Zm.displayName="FormLabel";const Xm=j.forwardRef(({...s},t)=>{const{error:n,formItemId:r,formDescriptionId:a,formMessageId:i}=wCe();return e.jsx(Jqe,{ref:t,id:r,"aria-describedby":n?`${a} ${i}`:`${a}`,"aria-invalid":!!n,...s})});Xm.displayName="FormControl";const g2e=j.forwardRef(({className:s,...t},n)=>{const{formDescriptionId:r}=wCe();return e.jsx("p",{ref:n,id:r,className:Tt("text-sm text-muted-foreground",s),...t})});g2e.displayName="FormDescription";const a1=j.forwardRef(({className:s,children:t,...n},r)=>{const{error:a,formMessageId:i}=wCe(),l=a?String(a==null?void 0:a.message):t;return l?e.jsx("p",{ref:r,id:i,className:Tt("text-sm font-medium text-destructive",s),...n,children:l}):null});a1.displayName="FormMessage";const be=j.forwardRef(({className:s,type:t,...n},r)=>e.jsx("input",{type:t,className:Tt("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}));be.displayName="Input";function mee(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 i0s=[" ","Enter","ArrowUp","ArrowDown"],o0s=[" ","Enter"],cO="Select",[jCe,NCe,l0s]=uq(cO),[Sq,PXn]=ip(cO,[l0s,M5]),kCe=M5(),[c0s,A6]=Sq(cO),[d0s,u0s]=Sq(cO),v3t=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:x}=s,g=kCe(t),[y,b]=j.useState(null),[v,N]=j.useState(null),[C,A]=j.useState(!1),T=jC(d),[P,M]=Ux({prop:r,defaultProp:a??!1,onChange:i,caller:cO}),[I,D]=Ux({prop:l,defaultProp:o,onChange:c,caller:cO}),B=j.useRef(null),q=y?x||!!y.closest("form"):!0,[W,V]=j.useState(new Set),K=Array.from(W).map(Q=>Q.props.value).join(";");return e.jsx(eee,{...g,children:e.jsxs(c0s,{required:p,scope:t,trigger:y,onTriggerChange:b,valueNode:v,onValueNodeChange:N,valueNodeHasChildren:C,onValueNodeHasChildrenChange:A,contentId:Fx(),value:I,onValueChange:D,open:P,onOpenChange:M,dir:T,triggerPointerDownPosRef:B,disabled:m,children:[e.jsx(jCe.Provider,{scope:t,children:e.jsx(d0s,{scope:s.__scopeSelect,onNativeOptionAdd:j.useCallback(Q=>{V(J=>new Set(J).add(Q))},[]),onNativeOptionRemove:j.useCallback(Q=>{V(J=>{const ce=new Set(J);return ce.delete(Q),ce})},[]),children:n})}),q?e.jsxs(q3t,{"aria-hidden":!0,required:p,tabIndex:-1,name:u,autoComplete:h,value:I,onChange:Q=>D(Q.target.value),disabled:m,form:x,children:[I===void 0?e.jsx("option",{value:""}):null,Array.from(W)]},K):null]})})};v3t.displayName=cO;var b3t="SelectTrigger",_3t=j.forwardRef((s,t)=>{const{__scopeSelect:n,disabled:r=!1,...a}=s,i=kCe(n),l=A6(b3t,n),o=l.disabled||r,c=Po(t,l.onTriggerChange),d=NCe(n),u=j.useRef("touch"),[h,m,p]=H3t(g=>{const y=d().filter(N=>!N.disabled),b=y.find(N=>N.value===l.value),v=G3t(y,g,b);v!==void 0&&l.onValueChange(v.value)}),x=g=>{o||(l.onOpenChange(!0),p()),g&&(l.triggerPointerDownPosRef.current={x:Math.round(g.pageX),y:Math.round(g.pageY)})};return e.jsx(yq,{asChild:!0,...i,children:e.jsx(Ka.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":V3t(l.value)?"":void 0,...a,ref:c,onClick:xa(a.onClick,g=>{g.currentTarget.focus(),u.current!=="mouse"&&x(g)}),onPointerDown:xa(a.onPointerDown,g=>{u.current=g.pointerType;const y=g.target;y.hasPointerCapture(g.pointerId)&&y.releasePointerCapture(g.pointerId),g.button===0&&g.ctrlKey===!1&&g.pointerType==="mouse"&&(x(g),g.preventDefault())}),onKeyDown:xa(a.onKeyDown,g=>{const y=h.current!=="";!(g.ctrlKey||g.altKey||g.metaKey)&&g.key.length===1&&m(g.key),!(y&&g.key===" ")&&i0s.includes(g.key)&&(x(),g.preventDefault())})})})});_3t.displayName=b3t;var w3t="SelectValue",j3t=j.forwardRef((s,t)=>{const{__scopeSelect:n,className:r,style:a,children:i,placeholder:l="",...o}=s,c=A6(w3t,n),{onValueNodeHasChildrenChange:d}=c,u=i!==void 0,h=Po(t,c.onValueNodeChange);return Sf(()=>{d(u)},[d,u]),e.jsx(Ka.span,{...o,ref:h,style:{pointerEvents:"none"},children:V3t(c.value)?e.jsx(e.Fragment,{children:l}):i})});j3t.displayName=w3t;var h0s="SelectIcon",N3t=j.forwardRef((s,t)=>{const{__scopeSelect:n,children:r,...a}=s;return e.jsx(Ka.span,{"aria-hidden":!0,...a,ref:t,children:r||"▼"})});N3t.displayName=h0s;var m0s="SelectPortal",k3t=s=>e.jsx(hq,{asChild:!0,...s});k3t.displayName=m0s;var dO="SelectContent",S3t=j.forwardRef((s,t)=>{const n=A6(dO,s.__scopeSelect),[r,a]=j.useState();if(Sf(()=>{a(new DocumentFragment)},[]),!n.open){const i=r;return i?n1.createPortal(e.jsx(C3t,{scope:s.__scopeSelect,children:e.jsx(jCe.Slot,{scope:s.__scopeSelect,children:e.jsx("div",{children:s.children})})}),i):null}return e.jsx(A3t,{...s,ref:t})});S3t.displayName=dO;var W2=10,[C3t,E6]=Sq(dO),p0s="SelectContentImpl",f0s=QT("SelectContent.RemoveScroll"),A3t=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:x,hideWhenDetached:g,avoidCollisions:y,...b}=s,v=A6(dO,n),[N,C]=j.useState(null),[A,T]=j.useState(null),P=Po(t,je=>C(je)),[M,I]=j.useState(null),[D,B]=j.useState(null),q=NCe(n),[W,V]=j.useState(!1),K=j.useRef(!1);j.useEffect(()=>{if(N)return z3e(N)},[N]),O3e();const Q=j.useCallback(je=>{const[Ee,...Me]=q().map(ke=>ke.ref.current),[De]=Me.slice(-1),ze=document.activeElement;for(const ke of je)if(ke===ze||(ke==null||ke.scrollIntoView({block:"nearest"}),ke===Ee&&A&&(A.scrollTop=0),ke===De&&A&&(A.scrollTop=A.scrollHeight),ke==null||ke.focus(),document.activeElement!==ze))return},[q,A]),J=j.useCallback(()=>Q([M,N]),[Q,M,N]);j.useEffect(()=>{W&&J()},[W,J]);const{onOpenChange:ce,triggerPointerDownPosRef:ue}=v;j.useEffect(()=>{if(N){let je={x:0,y:0};const Ee=De=>{var ze,ke;je={x:Math.abs(Math.round(De.pageX)-(((ze=ue.current)==null?void 0:ze.x)??0)),y:Math.abs(Math.round(De.pageY)-(((ke=ue.current)==null?void 0:ke.y)??0))}},Me=De=>{je.x<=10&&je.y<=10?De.preventDefault():N.contains(De.target)||ce(!1),document.removeEventListener("pointermove",Ee),ue.current=null};return ue.current!==null&&(document.addEventListener("pointermove",Ee),document.addEventListener("pointerup",Me,{capture:!0,once:!0})),()=>{document.removeEventListener("pointermove",Ee),document.removeEventListener("pointerup",Me,{capture:!0})}}},[N,ce,ue]),j.useEffect(()=>{const je=()=>ce(!1);return window.addEventListener("blur",je),window.addEventListener("resize",je),()=>{window.removeEventListener("blur",je),window.removeEventListener("resize",je)}},[ce]);const[ne,ee]=H3t(je=>{const Ee=q().filter(ze=>!ze.disabled),Me=Ee.find(ze=>ze.ref.current===document.activeElement),De=G3t(Ee,je,Me);De&&setTimeout(()=>De.ref.current.focus())}),le=j.useCallback((je,Ee,Me)=>{const De=!K.current&&!Me;(v.value!==void 0&&v.value===Ee||De)&&(I(je),De&&(K.current=!0))},[v.value]),he=j.useCallback(()=>N==null?void 0:N.focus(),[N]),ve=j.useCallback((je,Ee,Me)=>{const De=!K.current&&!Me;(v.value!==void 0&&v.value===Ee||De)&&B(je)},[v.value]),ge=r==="popper"?jFe:E3t,fe=ge===jFe?{side:o,sideOffset:c,align:d,alignOffset:u,arrowPadding:h,collisionBoundary:m,collisionPadding:p,sticky:x,hideWhenDetached:g,avoidCollisions:y}:{};return e.jsx(C3t,{scope:n,content:N,viewport:A,onViewportChange:T,itemRefCallback:le,selectedItem:M,onItemLeave:he,itemTextRefCallback:ve,focusSelectedItem:J,selectedItemText:D,position:r,isPositioned:W,searchRef:ne,children:e.jsx(KJ,{as:f0s,allowPinchZoom:!0,children:e.jsx(WJ,{asChild:!0,trapped:v.open,onMountAutoFocus:je=>{je.preventDefault()},onUnmountAutoFocus:xa(a,je=>{var Ee;(Ee=v.trigger)==null||Ee.focus({preventScroll:!0}),je.preventDefault()}),children:e.jsx(j6,{asChild:!0,disableOutsidePointerEvents:!0,onEscapeKeyDown:i,onPointerDownOutside:l,onFocusOutside:je=>je.preventDefault(),onDismiss:()=>v.onOpenChange(!1),children:e.jsx(ge,{role:"listbox",id:v.contentId,"data-state":v.open?"open":"closed",dir:v.dir,onContextMenu:je=>je.preventDefault(),...b,...fe,onPlaced:()=>V(!0),ref:P,style:{display:"flex",flexDirection:"column",outline:"none",...b.style},onKeyDown:xa(b.onKeyDown,je=>{const Ee=je.ctrlKey||je.altKey||je.metaKey;if(je.key==="Tab"&&je.preventDefault(),!Ee&&je.key.length===1&&ee(je.key),["ArrowUp","ArrowDown","Home","End"].includes(je.key)){let De=q().filter(ze=>!ze.disabled).map(ze=>ze.ref.current);if(["ArrowUp","End"].includes(je.key)&&(De=De.slice().reverse()),["ArrowUp","ArrowDown"].includes(je.key)){const ze=je.target,ke=De.indexOf(ze);De=De.slice(ke+1)}setTimeout(()=>Q(De)),je.preventDefault()}})})})})})})});A3t.displayName=p0s;var x0s="SelectItemAlignedPosition",E3t=j.forwardRef((s,t)=>{const{__scopeSelect:n,onPlaced:r,...a}=s,i=A6(dO,n),l=E6(dO,n),[o,c]=j.useState(null),[d,u]=j.useState(null),h=Po(t,P=>u(P)),m=NCe(n),p=j.useRef(!1),x=j.useRef(!0),{viewport:g,selectedItem:y,selectedItemText:b,focusSelectedItem:v}=l,N=j.useCallback(()=>{if(i.trigger&&i.valueNode&&o&&d&&g&&y&&b){const P=i.trigger.getBoundingClientRect(),M=d.getBoundingClientRect(),I=i.valueNode.getBoundingClientRect(),D=b.getBoundingClientRect();if(i.dir!=="rtl"){const ze=D.left-M.left,ke=I.left-ze,Xe=P.left-ke,Se=P.width+Xe,Re=Math.max(Se,M.width),Ae=window.innerWidth-W2,Be=BZ(ke,[W2,Math.max(W2,Ae-Re)]);o.style.minWidth=Se+"px",o.style.left=Be+"px"}else{const ze=M.right-D.right,ke=window.innerWidth-I.right-ze,Xe=window.innerWidth-P.right-ke,Se=P.width+Xe,Re=Math.max(Se,M.width),Ae=window.innerWidth-W2,Be=BZ(ke,[W2,Math.max(W2,Ae-Re)]);o.style.minWidth=Se+"px",o.style.right=Be+"px"}const B=m(),q=window.innerHeight-W2*2,W=g.scrollHeight,V=window.getComputedStyle(d),K=parseInt(V.borderTopWidth,10),Q=parseInt(V.paddingTop,10),J=parseInt(V.borderBottomWidth,10),ce=parseInt(V.paddingBottom,10),ue=K+Q+W+ce+J,ne=Math.min(y.offsetHeight*5,ue),ee=window.getComputedStyle(g),le=parseInt(ee.paddingTop,10),he=parseInt(ee.paddingBottom,10),ve=P.top+P.height/2-W2,ge=q-ve,fe=y.offsetHeight/2,je=y.offsetTop+fe,Ee=K+Q+je,Me=ue-Ee;if(Ee<=ve){const ze=B.length>0&&y===B[B.length-1].ref.current;o.style.bottom="0px";const ke=d.clientHeight-g.offsetTop-g.offsetHeight,Xe=Math.max(ge,fe+(ze?he:0)+ke+J),Se=Ee+Xe;o.style.height=Se+"px"}else{const ze=B.length>0&&y===B[0].ref.current;o.style.top="0px";const Xe=Math.max(ve,K+g.offsetTop+(ze?le:0)+fe)+Me;o.style.height=Xe+"px",g.scrollTop=Ee-ve+g.offsetTop}o.style.margin=`${W2}px 0`,o.style.minHeight=ne+"px",o.style.maxHeight=q+"px",r==null||r(),requestAnimationFrame(()=>p.current=!0)}},[m,i.trigger,i.valueNode,o,d,g,y,b,i.dir,r]);Sf(()=>N(),[N]);const[C,A]=j.useState();Sf(()=>{d&&A(window.getComputedStyle(d).zIndex)},[d]);const T=j.useCallback(P=>{P&&x.current===!0&&(N(),v==null||v(),x.current=!1)},[N,v]);return e.jsx(y0s,{scope:n,contentWrapper:o,shouldExpandOnScrollRef:p,onScrollButtonChange:T,children:e.jsx("div",{ref:c,style:{display:"flex",flexDirection:"column",position:"fixed",zIndex:C},children:e.jsx(Ka.div,{...a,ref:h,style:{boxSizing:"border-box",maxHeight:"100%",...a.style}})})})});E3t.displayName=x0s;var g0s="SelectPopperPosition",jFe=j.forwardRef((s,t)=>{const{__scopeSelect:n,align:r="start",collisionPadding:a=W2,...i}=s,l=kCe(n);return e.jsx(tee,{...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)"}})});jFe.displayName=g0s;var[y0s,iHe]=Sq(dO,{}),NFe="SelectViewport",T3t=j.forwardRef((s,t)=>{const{__scopeSelect:n,nonce:r,...a}=s,i=E6(NFe,n),l=iHe(NFe,n),o=Po(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(jCe.Slot,{scope:n,children:e.jsx(Ka.div,{"data-radix-select-viewport":"",role:"presentation",...a,ref:o,style:{position:"relative",flex:1,overflow:"hidden auto",...a.style},onScroll:xa(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 x=window.innerHeight-W2*2,g=parseFloat(h.style.minHeight),y=parseFloat(h.style.height),b=Math.max(g,y);if(b0?C:0,h.style.justifyContent="flex-end")}}}c.current=u.scrollTop})})})]})});T3t.displayName=NFe;var M3t="SelectGroup",[v0s,b0s]=Sq(M3t),_0s=j.forwardRef((s,t)=>{const{__scopeSelect:n,...r}=s,a=Fx();return e.jsx(v0s,{scope:n,id:a,children:e.jsx(Ka.div,{role:"group","aria-labelledby":a,...r,ref:t})})});_0s.displayName=M3t;var L3t="SelectLabel",P3t=j.forwardRef((s,t)=>{const{__scopeSelect:n,...r}=s,a=b0s(L3t,n);return e.jsx(Ka.div,{id:a.id,...r,ref:t})});P3t.displayName=L3t;var Uke="SelectItem",[w0s,I3t]=Sq(Uke),D3t=j.forwardRef((s,t)=>{const{__scopeSelect:n,value:r,disabled:a=!1,textValue:i,...l}=s,o=A6(Uke,n),c=E6(Uke,n),d=o.value===r,[u,h]=j.useState(i??""),[m,p]=j.useState(!1),x=Po(t,v=>{var N;return(N=c.itemRefCallback)==null?void 0:N.call(c,v,r,a)}),g=Fx(),y=j.useRef("touch"),b=()=>{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(w0s,{scope:n,value:r,disabled:a,textId:g,isSelected:d,onItemTextChange:j.useCallback(v=>{h(N=>N||((v==null?void 0:v.textContent)??"").trim())},[]),children:e.jsx(jCe.ItemSlot,{scope:n,value:r,disabled:a,textValue:u,children:e.jsx(Ka.div,{role:"option","aria-labelledby":g,"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:x,onFocus:xa(l.onFocus,()=>p(!0)),onBlur:xa(l.onBlur,()=>p(!1)),onClick:xa(l.onClick,()=>{y.current!=="mouse"&&b()}),onPointerUp:xa(l.onPointerUp,()=>{y.current==="mouse"&&b()}),onPointerDown:xa(l.onPointerDown,v=>{y.current=v.pointerType}),onPointerMove:xa(l.onPointerMove,v=>{var N;y.current=v.pointerType,a?(N=c.onItemLeave)==null||N.call(c):y.current==="mouse"&&v.currentTarget.focus({preventScroll:!0})}),onPointerLeave:xa(l.onPointerLeave,v=>{var N;v.currentTarget===document.activeElement&&((N=c.onItemLeave)==null||N.call(c))}),onKeyDown:xa(l.onKeyDown,v=>{var C;((C=c.searchRef)==null?void 0:C.current)!==""&&v.key===" "||(o0s.includes(v.key)&&b(),v.key===" "&&v.preventDefault())})})})})});D3t.displayName=Uke;var xW="SelectItemText",R3t=j.forwardRef((s,t)=>{const{__scopeSelect:n,className:r,style:a,...i}=s,l=A6(xW,n),o=E6(xW,n),c=I3t(xW,n),d=u0s(xW,n),[u,h]=j.useState(null),m=Po(t,b=>h(b),c.onItemTextChange,b=>{var v;return(v=o.itemTextRefCallback)==null?void 0:v.call(o,b,c.value,c.disabled)}),p=u==null?void 0:u.textContent,x=j.useMemo(()=>e.jsx("option",{value:c.value,disabled:c.disabled,children:p},c.value),[c.disabled,c.value,p]),{onNativeOptionAdd:g,onNativeOptionRemove:y}=d;return Sf(()=>(g(x),()=>y(x)),[g,y,x]),e.jsxs(e.Fragment,{children:[e.jsx(Ka.span,{id:c.textId,...i,ref:m}),c.isSelected&&l.valueNode&&!l.valueNodeHasChildren?n1.createPortal(i.children,l.valueNode):null]})});R3t.displayName=xW;var O3t="SelectItemIndicator",F3t=j.forwardRef((s,t)=>{const{__scopeSelect:n,...r}=s;return I3t(O3t,n).isSelected?e.jsx(Ka.span,{"aria-hidden":!0,...r,ref:t}):null});F3t.displayName=O3t;var kFe="SelectScrollUpButton",z3t=j.forwardRef((s,t)=>{const n=E6(kFe,s.__scopeSelect),r=iHe(kFe,s.__scopeSelect),[a,i]=j.useState(!1),l=Po(t,r.onScrollButtonChange);return Sf(()=>{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($3t,{...s,ref:l,onAutoScroll:()=>{const{viewport:o,selectedItem:c}=n;o&&c&&(o.scrollTop=o.scrollTop-c.offsetHeight)}}):null});z3t.displayName=kFe;var SFe="SelectScrollDownButton",B3t=j.forwardRef((s,t)=>{const n=E6(SFe,s.__scopeSelect),r=iHe(SFe,s.__scopeSelect),[a,i]=j.useState(!1),l=Po(t,r.onScrollButtonChange);return Sf(()=>{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($3t,{...s,ref:l,onAutoScroll:()=>{const{viewport:o,selectedItem:c}=n;o&&c&&(o.scrollTop=o.scrollTop+c.offsetHeight)}}):null});B3t.displayName=SFe;var $3t=j.forwardRef((s,t)=>{const{__scopeSelect:n,onAutoScroll:r,...a}=s,i=E6("SelectScrollButton",n),l=j.useRef(null),o=NCe(n),c=j.useCallback(()=>{l.current!==null&&(window.clearInterval(l.current),l.current=null)},[]);return j.useEffect(()=>()=>c(),[c]),Sf(()=>{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(Ka.div,{"aria-hidden":!0,...a,ref:t,style:{flexShrink:0,...a.style},onPointerDown:xa(a.onPointerDown,()=>{l.current===null&&(l.current=window.setInterval(r,50))}),onPointerMove:xa(a.onPointerMove,()=>{var d;(d=i.onItemLeave)==null||d.call(i),l.current===null&&(l.current=window.setInterval(r,50))}),onPointerLeave:xa(a.onPointerLeave,()=>{c()})})}),j0s="SelectSeparator",U3t=j.forwardRef((s,t)=>{const{__scopeSelect:n,...r}=s;return e.jsx(Ka.div,{"aria-hidden":!0,...r,ref:t})});U3t.displayName=j0s;var CFe="SelectArrow",N0s=j.forwardRef((s,t)=>{const{__scopeSelect:n,...r}=s,a=kCe(n),i=A6(CFe,n),l=E6(CFe,n);return i.open&&l.position==="popper"?e.jsx(see,{...a,...r,ref:t}):null});N0s.displayName=CFe;var k0s="SelectBubbleInput",q3t=j.forwardRef(({__scopeSelect:s,value:t,...n},r)=>{const a=j.useRef(null),i=Po(r,a),l=mee(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(Ka.select,{...n,style:{...H2t,...n.style},ref:i,defaultValue:t})});q3t.displayName=k0s;function V3t(s){return s===""||s===void 0}function H3t(s){const t=bf(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 G3t(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=S0s(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 S0s(s,t){return s.map((n,r)=>s[(t+r)%s.length])}var C0s=v3t,W3t=_3t,A0s=j3t,E0s=N3t,T0s=k3t,K3t=S3t,M0s=T3t,Y3t=P3t,Z3t=D3t,L0s=R3t,P0s=F3t,X3t=z3t,Q3t=B3t,J3t=U3t;const vs=C0s,bs=A0s,gs=j.forwardRef(({className:s,children:t,...n},r)=>e.jsxs(W3t,{ref:r,className:Tt("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(E0s,{asChild:!0,children:e.jsx(_o,{className:"h-4 w-4 opacity-50"})})]}));gs.displayName=W3t.displayName;const eCt=j.forwardRef(({className:s,...t},n)=>e.jsx(X3t,{ref:n,className:Tt("flex cursor-default items-center justify-center py-1",s),...t,children:e.jsx(jg,{className:"h-4 w-4"})}));eCt.displayName=X3t.displayName;const tCt=j.forwardRef(({className:s,...t},n)=>e.jsx(Q3t,{ref:n,className:Tt("flex cursor-default items-center justify-center py-1",s),...t,children:e.jsx(_o,{className:"h-4 w-4"})}));tCt.displayName=Q3t.displayName;const ys=j.forwardRef(({className:s,children:t,position:n="popper",...r},a)=>e.jsx(T0s,{children:e.jsxs(K3t,{ref:a,className:Tt("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(eCt,{}),e.jsx(M0s,{className:Tt("p-1",n==="popper"&&"h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)]"),children:t}),e.jsx(tCt,{})]})}));ys.displayName=K3t.displayName;const I0s=j.forwardRef(({className:s,...t},n)=>e.jsx(Y3t,{ref:n,className:Tt("py-1.5 pl-8 pr-2 text-sm font-semibold",s),...t}));I0s.displayName=Y3t.displayName;const Ye=j.forwardRef(({className:s,children:t,...n},r)=>e.jsxs(Z3t,{ref:r,className:Tt("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(P0s,{children:e.jsx(oa,{className:"h-4 w-4"})})}),e.jsx(L0s,{children:t})]}));Ye.displayName=Z3t.displayName;const D0s=j.forwardRef(({className:s,...t},n)=>e.jsx(J3t,{ref:n,className:Tt("-mx-1 my-1 h-px bg-muted",s),...t}));D0s.displayName=J3t.displayName;const R0s=tk({category:aHe(["general","technology","crm","marketing"]),subject:rl().min(5,"Subject must be at least 5 characters").max(200),description:rl().min(20,"Please provide more details (at least 20 characters)").max(2e3)}),O0s={general:"General Support",technology:"Technology Support",crm:"CRM Support",marketing:"Marketing Support"};function AFe({trigger:s}){const[t,n]=j.useState(!1),[r,a]=j.useState(!1),{user:i}=_s(),l=xCe({resolver:gCe(R0s),defaultValues:{category:"general",subject:"",description:""}}),o=async c=>{if(!i){ae.error("You must be logged in to submit a ticket");return}a(!0);try{const{error:d}=await U.from("support_tickets").insert({user_id:i.id,category:c.category,subject:c.subject,description:c.description});if(d)throw d;try{await U.functions.invoke("support-ticket-notify",{body:{category:O0s[c.category],subject:c.subject}})}catch(u){console.log("Notification send attempted:",u)}ae.success("Support ticket submitted successfully!"),l.reset(),n(!1)}catch(d){console.error("Error submitting ticket:",d),ae.error("Failed to submit ticket. Please try again.")}finally{a(!1)}};return e.jsxs(Os,{open:t,onOpenChange:n,children:[e.jsx(Ko,{asChild:!0,children:s||e.jsxs($,{variant:"ghost",size:"icon",className:"relative",children:[e.jsx(Ez,{className:"h-5 w-5"}),e.jsx("span",{className:"sr-only",children:"Support"})]})}),e.jsxs(Rs,{className:"sm:max-w-[500px]",children:[e.jsxs(Us,{children:[e.jsx(zs,{children:"Need Help?"}),e.jsx(Sr,{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(ya,{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(_Ce,{...l,children:e.jsxs("form",{onSubmit:l.handleSubmit(o),className:"space-y-4",children:[e.jsx(Cp,{control:l.control,name:"category",render:({field:c})=>e.jsxs(Ym,{children:[e.jsx(Zm,{children:"Category"}),e.jsxs(vs,{onValueChange:c.onChange,defaultValue:c.value,children:[e.jsx(Xm,{children:e.jsx(gs,{children:e.jsx(bs,{placeholder:"Select a category"})})}),e.jsxs(ys,{children:[e.jsx(Ye,{value:"general",children:"General Support"}),e.jsx(Ye,{value:"technology",children:"Technology Support"}),e.jsx(Ye,{value:"crm",children:"CRM Support"}),e.jsx(Ye,{value:"marketing",children:"Marketing Support"})]})]}),e.jsx(a1,{})]})}),e.jsx(Cp,{control:l.control,name:"subject",render:({field:c})=>e.jsxs(Ym,{children:[e.jsx(Zm,{children:"Subject"}),e.jsx(Xm,{children:e.jsx(be,{placeholder:"Brief description of your issue",...c})}),e.jsx(a1,{})]})}),e.jsx(Cp,{control:l.control,name:"description",render:({field:c})=>e.jsxs(Ym,{children:[e.jsx(Zm,{children:"Description"}),e.jsx(Xm,{children:e.jsx(Is,{placeholder:"Please describe your issue in detail...",className:"min-h-[120px]",...c})}),e.jsx(a1,{})]})}),e.jsxs("div",{className:"flex justify-end gap-2 pt-4",children:[e.jsx($,{type:"button",variant:"outline",onClick:()=>n(!1),children:"Cancel"}),e.jsx($,{type:"submit",disabled:r,children:r?"Submitting...":"Submit Ticket"})]})]})})]})]})}function Qi(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 Gu(s,t){return s instanceof Date?new s.constructor(t):new Date(t)}function Bd(s,t){const n=Qi(s);return isNaN(t)?Gu(s,NaN):(t&&n.setDate(n.getDate()+t),n)}function zx(s,t){const n=Qi(s);if(isNaN(t))return Gu(s,NaN);if(!t)return n;const r=n.getDate(),a=Gu(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 sCt(s,t){const n=+Qi(s);return Gu(s,n+t)}const oHe=6048e5,F0s=864e5,SCe=6e4,CCe=36e5,z0s=1e3,wne=43200,Uat=1440;function qat(s,t){return sCt(s,t*CCe)}let B0s={};function T6(){return B0s}function Tg(s,t){var o,c,d,u;const n=T6(),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=Qi(s),i=a.getDay(),l=(i=a.getTime()?n+1:t.getTime()>=l.getTime()?n:n-1}function ep(s){const t=Qi(s);return t.setHours(0,0,0,0),t}function n6(s){const t=Qi(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 av(s,t){const n=ep(s),r=ep(t),a=+n-n6(n),i=+r-n6(r);return Math.round((a-i)/F0s)}function $0s(s){const t=nCt(s),n=Gu(s,0);return n.setFullYear(t,0,4),n.setHours(0,0,0,0),dC(n)}function Vat(s,t){return sCt(s,t*SCe)}function P3(s,t){const n=t*7;return Bd(s,n)}function U0s(s,t){return zx(s,t*12)}function q0s(s){let t;return s.forEach(function(n){const r=Qi(n);(t===void 0||t{const r=Qi(n);(!t||t>r||isNaN(+r))&&(t=r)}),t||new Date(NaN)}function y2e(s,t){const n=Qi(s),r=Qi(t),a=n.getTime()-r.getTime();return a<0?-1:a>0?1:a}function ACe(s){return Gu(s,Date.now())}function hu(s,t){const n=ep(s),r=ep(t);return+n==+r}function lHe(s){return s instanceof Date||typeof s=="object"&&Object.prototype.toString.call(s)==="[object Date]"}function EFe(s){if(!lHe(s)&&typeof s!="number")return!1;const t=Qi(s);return!isNaN(Number(t))}function J$(s,t){const n=Qi(s),r=Qi(t),a=n.getFullYear()-r.getFullYear(),i=n.getMonth()-r.getMonth();return a*12+i}function H0s(s,t,n){const r=Tg(s,n),a=Tg(t,n),i=+r-n6(r),l=+a-n6(a);return Math.round((i-l)/oHe)}function r2(s,t){const n=Qi(s),r=Qi(t),a=Hat(n,r),i=Math.abs(av(n,r));n.setDate(n.getDate()-a*i);const l=+(Hat(n,r)===-a),o=a*(i-l);return o===0?0:o}function Hat(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 G0s(s){return t=>{const r=(s?Math[s]:Math.trunc)(t);return r===0?0:r}}function W0s(s,t){return+Qi(s)-+Qi(t)}function K0s(s){const t=Qi(s);return t.setHours(23,59,59,999),t}function e1(s){const t=Qi(s),n=t.getMonth();return t.setFullYear(t.getFullYear(),n+1,0),t.setHours(23,59,59,999),t}function Y0s(s){const t=Qi(s);return+K0s(t)==+e1(t)}function Z0s(s,t){const n=Qi(s),r=Qi(t),a=y2e(n,r),i=Math.abs(J$(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=y2e(n,r)===-a;Y0s(Qi(s))&&i===1&&y2e(s,r)===1&&(o=!1),l=a*(i-Number(o))}return l===0?0:l}function X0s(s,t,n){const r=W0s(s,t)/1e3;return G0s(n==null?void 0:n.roundingMethod)(r)}function TFe(s,t){const n=Qi(s.start),r=Qi(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(Qi(l)),l.setDate(l.getDate()+o),l.setHours(0,0,0,0);return a?c.reverse():c}function Hu(s){const t=Qi(s);return t.setDate(1),t.setHours(0,0,0,0),t}function rCt(s){const t=Qi(s),n=Gu(s,0);return n.setFullYear(t.getFullYear(),0,1),n.setHours(0,0,0,0),n}function eU(s,t){var o,c,d,u;const n=T6(),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=Qi(s),i=a.getDay(),l=(i{let r;const a=Q0s[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 zLe(s){return(t={})=>{const n=t.width?String(t.width):s.defaultWidth;return s.formats[n]||s.formats[s.defaultWidth]}}const eys={full:"EEEE, MMMM do, y",long:"MMMM do, y",medium:"MMM d, y",short:"MM/dd/yyyy"},tys={full:"h:mm:ss a zzzz",long:"h:mm:ss a z",medium:"h:mm:ss a",short:"h:mm a"},sys={full:"{{date}} 'at' {{time}}",long:"{{date}} 'at' {{time}}",medium:"{{date}}, {{time}}",short:"{{date}}, {{time}}"},nys={date:zLe({formats:eys,defaultWidth:"full"}),time:zLe({formats:tys,defaultWidth:"full"}),dateTime:zLe({formats:sys,defaultWidth:"full"})},rys={lastWeek:"'last' eeee 'at' p",yesterday:"'yesterday at' p",today:"'today at' p",tomorrow:"'tomorrow at' p",nextWeek:"eeee 'at' p",other:"P"},ays=(s,t,n,r)=>rys[s];function ZH(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 iys={narrow:["B","A"],abbreviated:["BC","AD"],wide:["Before Christ","Anno Domini"]},oys={narrow:["1","2","3","4"],abbreviated:["Q1","Q2","Q3","Q4"],wide:["1st quarter","2nd quarter","3rd quarter","4th quarter"]},lys={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"]},cys={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"]},dys={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"}},uys={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"}},hys=(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"},mys={ordinalNumber:hys,era:ZH({values:iys,defaultWidth:"wide"}),quarter:ZH({values:oys,defaultWidth:"wide",argumentCallback:s=>s-1}),month:ZH({values:lys,defaultWidth:"wide"}),day:ZH({values:cys,defaultWidth:"wide"}),dayPeriod:ZH({values:dys,defaultWidth:"wide",formattingValues:uys,defaultFormattingWidth:"wide"})};function XH(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)?fys(o,h=>h.test(l)):pys(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 pys(s,t){for(const n in s)if(Object.prototype.hasOwnProperty.call(s,n)&&t(s[n]))return n}function fys(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 gys=/^(\d+)(th|st|nd|rd)?/i,yys=/\d+/i,vys={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},bys={any:[/^b/i,/^(a|c)/i]},_ys={narrow:/^[1234]/i,abbreviated:/^q[1234]/i,wide:/^[1234](th|st|nd|rd)? quarter/i},wys={any:[/1/i,/2/i,/3/i,/4/i]},jys={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},Nys={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]},kys={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},Sys={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]},Cys={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},Ays={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}},Eys={ordinalNumber:xys({matchPattern:gys,parsePattern:yys,valueCallback:s=>parseInt(s,10)}),era:XH({matchPatterns:vys,defaultMatchWidth:"wide",parsePatterns:bys,defaultParseWidth:"any"}),quarter:XH({matchPatterns:_ys,defaultMatchWidth:"wide",parsePatterns:wys,defaultParseWidth:"any",valueCallback:s=>s+1}),month:XH({matchPatterns:jys,defaultMatchWidth:"wide",parsePatterns:Nys,defaultParseWidth:"any"}),day:XH({matchPatterns:kys,defaultMatchWidth:"wide",parsePatterns:Sys,defaultParseWidth:"any"}),dayPeriod:XH({matchPatterns:Cys,defaultMatchWidth:"any",parsePatterns:Ays,defaultParseWidth:"any"})},ECe={code:"en-US",formatDistance:J0s,formatLong:nys,formatRelative:ays,localize:mys,match:Eys,options:{weekStartsOn:0,firstWeekContainsDate:1}};function Tys(s){const t=Qi(s);return av(t,rCt(t))+1}function cHe(s){const t=Qi(s),n=+dC(t)-+$0s(t);return Math.round(n/oHe)+1}function dHe(s,t){var u,h,m,p;const n=Qi(s),r=n.getFullYear(),a=T6(),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=Gu(s,0);l.setFullYear(r+1,0,i),l.setHours(0,0,0,0);const o=Tg(l,t),c=Gu(s,0);c.setFullYear(r,0,i),c.setHours(0,0,0,0);const d=Tg(c,t);return n.getTime()>=o.getTime()?r+1:n.getTime()>=d.getTime()?r:r-1}function Mys(s,t){var o,c,d,u;const n=T6(),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=dHe(s,t),i=Gu(s,0);return i.setFullYear(a,0,r),i.setHours(0,0,0,0),Tg(i,t)}function uHe(s,t){const n=Qi(s),r=+Tg(n,t)-+Mys(n,t);return Math.round(r/oHe)+1}function Uu(s,t){const n=s<0?"-":"",r=Math.abs(s).toString().padStart(t,"0");return n+r}const sA={y(s,t){const n=s.getFullYear(),r=n>0?n:1-n;return Uu(t==="yy"?r%100:r,t.length)},M(s,t){const n=s.getMonth();return t==="M"?String(n+1):Uu(n+1,2)},d(s,t){return Uu(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 Uu(s.getHours()%12||12,t.length)},H(s,t){return Uu(s.getHours(),t.length)},m(s,t){return Uu(s.getMinutes(),t.length)},s(s,t){return Uu(s.getSeconds(),t.length)},S(s,t){const n=t.length,r=s.getMilliseconds(),a=Math.trunc(r*Math.pow(10,n-3));return Uu(a,t.length)}},y7={am:"am",pm:"pm",midnight:"midnight",noon:"noon",morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"},Gat={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 sA.y(s,t)},Y:function(s,t,n,r){const a=dHe(s,r),i=a>0?a:1-a;if(t==="YY"){const l=i%100;return Uu(l,2)}return t==="Yo"?n.ordinalNumber(i,{unit:"year"}):Uu(i,t.length)},R:function(s,t){const n=nCt(s);return Uu(n,t.length)},u:function(s,t){const n=s.getFullYear();return Uu(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 Uu(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 Uu(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 sA.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 Uu(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=uHe(s,r);return t==="wo"?n.ordinalNumber(a,{unit:"week"}):Uu(a,t.length)},I:function(s,t,n){const r=cHe(s);return t==="Io"?n.ordinalNumber(r,{unit:"week"}):Uu(r,t.length)},d:function(s,t,n){return t==="do"?n.ordinalNumber(s.getDate(),{unit:"date"}):sA.d(s,t)},D:function(s,t,n){const r=Tys(s);return t==="Do"?n.ordinalNumber(r,{unit:"dayOfYear"}):Uu(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 Uu(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 Uu(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 Uu(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=y7.noon:r===0?a=y7.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=y7.evening:r>=12?a=y7.afternoon:r>=4?a=y7.morning:a=y7.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 sA.h(s,t)},H:function(s,t,n){return t==="Ho"?n.ordinalNumber(s.getHours(),{unit:"hour"}):sA.H(s,t)},K:function(s,t,n){const r=s.getHours()%12;return t==="Ko"?n.ordinalNumber(r,{unit:"hour"}):Uu(r,t.length)},k:function(s,t,n){let r=s.getHours();return r===0&&(r=24),t==="ko"?n.ordinalNumber(r,{unit:"hour"}):Uu(r,t.length)},m:function(s,t,n){return t==="mo"?n.ordinalNumber(s.getMinutes(),{unit:"minute"}):sA.m(s,t)},s:function(s,t,n){return t==="so"?n.ordinalNumber(s.getSeconds(),{unit:"second"}):sA.s(s,t)},S:function(s,t){return sA.S(s,t)},X:function(s,t,n){const r=s.getTimezoneOffset();if(r===0)return"Z";switch(t){case"X":return Kat(r);case"XXXX":case"XX":return r8(r);case"XXXXX":case"XXX":default:return r8(r,":")}},x:function(s,t,n){const r=s.getTimezoneOffset();switch(t){case"x":return Kat(r);case"xxxx":case"xx":return r8(r);case"xxxxx":case"xxx":default:return r8(r,":")}},O:function(s,t,n){const r=s.getTimezoneOffset();switch(t){case"O":case"OO":case"OOO":return"GMT"+Wat(r,":");case"OOOO":default:return"GMT"+r8(r,":")}},z:function(s,t,n){const r=s.getTimezoneOffset();switch(t){case"z":case"zz":case"zzz":return"GMT"+Wat(r,":");case"zzzz":default:return"GMT"+r8(r,":")}},t:function(s,t,n){const r=Math.trunc(s.getTime()/1e3);return Uu(r,t.length)},T:function(s,t,n){const r=s.getTime();return Uu(r,t.length)}};function Wat(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+Uu(i,2)}function Kat(s,t){return s%60===0?(s>0?"-":"+")+Uu(Math.abs(s)/60,2):r8(s,t)}function r8(s,t=""){const n=s>0?"-":"+",r=Math.abs(s),a=Uu(Math.trunc(r/60),2),i=Uu(r%60,2);return n+a+t+i}const Yat=(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"})}},iCt=(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"})}},Lys=(s,t)=>{const n=s.match(/(P+)(p+)?/)||[],r=n[1],a=n[2];if(!a)return Yat(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}}",Yat(r,t)).replace("{{time}}",iCt(a,t))},MFe={p:iCt,P:Lys},Pys=/^D+$/,Iys=/^Y+$/,Dys=["D","DD","YY","YYYY"];function oCt(s){return Pys.test(s)}function lCt(s){return Iys.test(s)}function LFe(s,t,n){const r=Rys(s,t,n);if(console.warn(r),Dys.includes(s))throw new RangeError(r)}function Rys(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 Oys=/[yYQqMLwIdDecihHKkms]o|(\w)\1*|''|'(''|[^'])+('|$)|./g,Fys=/P+p+|P+|p+|''|'(''|[^'])+('|$)|./g,zys=/^'([^]*?)'?$/,Bys=/''/g,$ys=/[a-zA-Z]/;function Hs(s,t,n){var u,h,m,p,x,g,y,b;const r=T6(),a=(n==null?void 0:n.locale)??r.locale??ECe,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)??((g=(x=n==null?void 0:n.locale)==null?void 0:x.options)==null?void 0:g.weekStartsOn)??r.weekStartsOn??((b=(y=r.locale)==null?void 0:y.options)==null?void 0:b.weekStartsOn)??0,o=Qi(s);if(!EFe(o))throw new RangeError("Invalid time value");let c=t.match(Fys).map(v=>{const N=v[0];if(N==="p"||N==="P"){const C=MFe[N];return C(v,a.formatLong)}return v}).join("").match(Oys).map(v=>{if(v==="''")return{isToken:!1,value:"'"};const N=v[0];if(N==="'")return{isToken:!1,value:Uys(v)};if(Gat[N])return{isToken:!0,value:v};if(N.match($ys))throw new RangeError("Format string contains an unescaped latin alphabet character `"+N+"`");return{isToken:!1,value:v}});a.localize.preprocessor&&(c=a.localize.preprocessor(o,c));const d={firstWeekContainsDate:i,weekStartsOn:l,locale:a};return c.map(v=>{if(!v.isToken)return v.value;const N=v.value;(!(n!=null&&n.useAdditionalWeekYearTokens)&&lCt(N)||!(n!=null&&n.useAdditionalDayOfYearTokens)&&oCt(N))&&LFe(N,t,String(s));const C=Gat[N[0]];return C(o,N,a.localize,d)}).join("")}function Uys(s){const t=s.match(zys);return t?t[1].replace(Bys,"'"):s}function qys(s,t,n){const r=T6(),a=(n==null?void 0:n.locale)??r.locale??ECe,i=2520,l=y2e(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=Qi(t),d=Qi(s)):(c=Qi(s),d=Qi(t));const u=X0s(d,c),h=(n6(d)-n6(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 aw(s,t){const n=Qi(s),r=Qi(t);return+n<+r}function Zys(s){return+Qi(s)>Date.now()}function Xys(s,t){const n=t instanceof Date?Gu(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 Qys=10;class cCt{constructor(){Lr(this,"subPriority",0)}validate(t,n){return!0}}class Jys extends cCt{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 evs extends cCt{constructor(){super(...arguments);Lr(this,"priority",Qys);Lr(this,"subPriority",-1)}set(n,r){return r.timestampIsSet?n:Gu(n,Xys(n,Date))}}class xu{run(t,n,r,a){const i=this.parse(t,n,r,a);return i?{setter:new Jys(i.value,this.validate,this.set,this.priority,this.subPriority),rest:i.rest}:null}validate(t,n,r){return!0}}class tvs extends xu{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 sx={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}/},DS={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 nx(s,t){return s&&{value:t(s.value),rest:s.rest}}function Ip(s,t){const n=t.match(s);return n?{value:parseInt(n[0],10),rest:t.slice(n[0].length)}:null}function RS(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*CCe+i*SCe+l*z0s),rest:t.slice(n[0].length)}}function dCt(s){return Ip(sx.anyDigitsSigned,s)}function Cf(s,t){switch(s){case 1:return Ip(sx.singleDigit,t);case 2:return Ip(sx.twoDigits,t);case 3:return Ip(sx.threeDigits,t);case 4:return Ip(sx.fourDigits,t);default:return Ip(new RegExp("^\\d{1,"+s+"}"),t)}}function qke(s,t){switch(s){case 1:return Ip(sx.singleDigitSigned,t);case 2:return Ip(sx.twoDigitsSigned,t);case 3:return Ip(sx.threeDigitsSigned,t);case 4:return Ip(sx.fourDigitsSigned,t);default:return Ip(new RegExp("^-?\\d{1,"+s+"}"),t)}}function hHe(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 uCt(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 hCt(s){return s%400===0||s%4===0&&s%100!==0}class svs extends xu{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 nx(Cf(4,n),i);case"yo":return nx(a.ordinalNumber(n,{unit:"year"}),i);default:return nx(Cf(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=uCt(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 nvs extends xu{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 nx(Cf(4,n),i);case"Yo":return nx(a.ordinalNumber(n,{unit:"year"}),i);default:return nx(Cf(r.length,n),i)}}validate(n,r){return r.isTwoDigitYear||r.year>0}set(n,r,a,i){const l=dHe(n,i);if(a.isTwoDigitYear){const c=uCt(a.year,l);return n.setFullYear(c,0,i.firstWeekContainsDate),n.setHours(0,0,0,0),Tg(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),Tg(n,i)}}class rvs extends xu{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 qke(r==="R"?4:r.length,n)}set(n,r,a){const i=Gu(n,0);return i.setFullYear(a,0,4),i.setHours(0,0,0,0),dC(i)}}class avs extends xu{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 qke(r==="u"?4:r.length,n)}set(n,r,a){return n.setFullYear(a,0,1),n.setHours(0,0,0,0),n}}class ivs extends xu{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 Cf(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 ovs extends xu{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 Cf(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 lvs extends xu{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 nx(Ip(sx.month,n),i);case"MM":return nx(Cf(2,n),i);case"Mo":return nx(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 cvs extends xu{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 nx(Ip(sx.month,n),i);case"LL":return nx(Cf(2,n),i);case"Lo":return nx(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 dvs(s,t,n){const r=Qi(s),a=uHe(r,n)-t;return r.setDate(r.getDate()-a*7),r}class uvs extends xu{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 Ip(sx.week,n);case"wo":return a.ordinalNumber(n,{unit:"week"});default:return Cf(r.length,n)}}validate(n,r){return r>=1&&r<=53}set(n,r,a,i){return Tg(dvs(n,a,i),i)}}function hvs(s,t){const n=Qi(s),r=cHe(n)-t;return n.setDate(n.getDate()-r*7),n}class mvs extends xu{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 Ip(sx.week,n);case"Io":return a.ordinalNumber(n,{unit:"week"});default:return Cf(r.length,n)}}validate(n,r){return r>=1&&r<=53}set(n,r,a){return dC(hvs(n,a))}}const pvs=[31,28,31,30,31,30,31,31,30,31,30,31],fvs=[31,29,31,30,31,30,31,31,30,31,30,31];class xvs extends xu{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 Ip(sx.date,n);case"do":return a.ordinalNumber(n,{unit:"date"});default:return Cf(r.length,n)}}validate(n,r){const a=n.getFullYear(),i=hCt(a),l=n.getMonth();return i?r>=1&&r<=fvs[l]:r>=1&&r<=pvs[l]}set(n,r,a){return n.setDate(a),n.setHours(0,0,0,0),n}}class gvs extends xu{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 Ip(sx.dayOfYear,n);case"Do":return a.ordinalNumber(n,{unit:"date"});default:return Cf(r.length,n)}}validate(n,r){const a=n.getFullYear();return hCt(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 mHe(s,t,n){var h,m,p,x;const r=T6(),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??((x=(p=r.locale)==null?void 0:p.options)==null?void 0:x.weekStartsOn)??0,i=Qi(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 Bd(i,u)}class yvs extends xu{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=mHe(n,a,i),n.setHours(0,0,0,0),n}}class vvs extends xu{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 nx(Cf(r.length,n),l);case"eo":return nx(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=mHe(n,a,i),n.setHours(0,0,0,0),n}}class bvs extends xu{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 nx(Cf(r.length,n),l);case"co":return nx(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=mHe(n,a,i),n.setHours(0,0,0,0),n}}function _vs(s,t){const n=Qi(s),r=Gys(n),a=t-r;return Bd(n,a)}class wvs extends xu{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 Cf(r.length,n);case"io":return a.ordinalNumber(n,{unit:"day"});case"iii":return nx(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 nx(a.day(n,{width:"narrow",context:"formatting"}),i);case"iiiiii":return nx(a.day(n,{width:"short",context:"formatting"})||a.day(n,{width:"narrow",context:"formatting"}),i);case"iiii":default:return nx(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=_vs(n,a),n.setHours(0,0,0,0),n}}class jvs extends xu{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(hHe(a),0,0,0),n}}class Nvs extends xu{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(hHe(a),0,0,0),n}}class kvs extends xu{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(hHe(a),0,0,0),n}}class Svs extends xu{constructor(){super(...arguments);Lr(this,"priority",70);Lr(this,"incompatibleTokens",["H","K","k","t","T"])}parse(n,r,a){switch(r){case"h":return Ip(sx.hour12h,n);case"ho":return a.ordinalNumber(n,{unit:"hour"});default:return Cf(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 Cvs extends xu{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 Ip(sx.hour23h,n);case"Ho":return a.ordinalNumber(n,{unit:"hour"});default:return Cf(r.length,n)}}validate(n,r){return r>=0&&r<=23}set(n,r,a){return n.setHours(a,0,0,0),n}}class Avs extends xu{constructor(){super(...arguments);Lr(this,"priority",70);Lr(this,"incompatibleTokens",["h","H","k","t","T"])}parse(n,r,a){switch(r){case"K":return Ip(sx.hour11h,n);case"Ko":return a.ordinalNumber(n,{unit:"hour"});default:return Cf(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 Evs extends xu{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 Ip(sx.hour24h,n);case"ko":return a.ordinalNumber(n,{unit:"hour"});default:return Cf(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 Tvs extends xu{constructor(){super(...arguments);Lr(this,"priority",60);Lr(this,"incompatibleTokens",["t","T"])}parse(n,r,a){switch(r){case"m":return Ip(sx.minute,n);case"mo":return a.ordinalNumber(n,{unit:"minute"});default:return Cf(r.length,n)}}validate(n,r){return r>=0&&r<=59}set(n,r,a){return n.setMinutes(a,0,0),n}}class Mvs extends xu{constructor(){super(...arguments);Lr(this,"priority",50);Lr(this,"incompatibleTokens",["t","T"])}parse(n,r,a){switch(r){case"s":return Ip(sx.second,n);case"so":return a.ordinalNumber(n,{unit:"second"});default:return Cf(r.length,n)}}validate(n,r){return r>=0&&r<=59}set(n,r,a){return n.setSeconds(a,0),n}}class Lvs extends xu{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 nx(Cf(r.length,n),a)}set(n,r,a){return n.setMilliseconds(a),n}}class Pvs extends xu{constructor(){super(...arguments);Lr(this,"priority",10);Lr(this,"incompatibleTokens",["t","T","x"])}parse(n,r){switch(r){case"X":return RS(DS.basicOptionalMinutes,n);case"XX":return RS(DS.basic,n);case"XXXX":return RS(DS.basicOptionalSeconds,n);case"XXXXX":return RS(DS.extendedOptionalSeconds,n);case"XXX":default:return RS(DS.extended,n)}}set(n,r,a){return r.timestampIsSet?n:Gu(n,n.getTime()-n6(n)-a)}}class Ivs extends xu{constructor(){super(...arguments);Lr(this,"priority",10);Lr(this,"incompatibleTokens",["t","T","X"])}parse(n,r){switch(r){case"x":return RS(DS.basicOptionalMinutes,n);case"xx":return RS(DS.basic,n);case"xxxx":return RS(DS.basicOptionalSeconds,n);case"xxxxx":return RS(DS.extendedOptionalSeconds,n);case"xxx":default:return RS(DS.extended,n)}}set(n,r,a){return r.timestampIsSet?n:Gu(n,n.getTime()-n6(n)-a)}}class Dvs extends xu{constructor(){super(...arguments);Lr(this,"priority",40);Lr(this,"incompatibleTokens","*")}parse(n){return dCt(n)}set(n,r,a){return[Gu(n,a*1e3),{timestampIsSet:!0}]}}class Rvs extends xu{constructor(){super(...arguments);Lr(this,"priority",20);Lr(this,"incompatibleTokens","*")}parse(n){return dCt(n)}set(n,r,a){return[Gu(n,a),{timestampIsSet:!0}]}}const Ovs={G:new tvs,y:new svs,Y:new nvs,R:new rvs,u:new avs,Q:new ivs,q:new ovs,M:new lvs,L:new cvs,w:new uvs,I:new mvs,d:new xvs,D:new gvs,E:new yvs,e:new vvs,c:new bvs,i:new wvs,a:new jvs,b:new Nvs,B:new kvs,h:new Svs,H:new Cvs,K:new Avs,k:new Evs,m:new Tvs,s:new Mvs,S:new Lvs,X:new Pvs,x:new Ivs,t:new Dvs,T:new Rvs},Fvs=/[yYQqMLwIdDecihHKkms]o|(\w)\1*|''|'(''|[^'])+('|$)|./g,zvs=/P+p+|P+|p+|''|'(''|[^'])+('|$)|./g,Bvs=/^'([^]*?)'?$/,$vs=/''/g,Uvs=/\S/,qvs=/[a-zA-Z]/;function pHe(s,t,n,r){var g,y,b,v;const a=Hys(),i=a.locale??ECe,l=a.firstWeekContainsDate??((y=(g=a.locale)==null?void 0:g.options)==null?void 0:y.firstWeekContainsDate)??1,o=a.weekStartsOn??((v=(b=a.locale)==null?void 0:b.options)==null?void 0:v.weekStartsOn)??0;if(t==="")return s===""?Qi(n):Gu(n,NaN);const c={firstWeekContainsDate:l,weekStartsOn:o,locale:i},d=[new evs],u=t.match(zvs).map(N=>{const C=N[0];if(C in MFe){const A=MFe[C];return A(N,i.formatLong)}return N}).join("").match(Fvs),h=[];for(let N of u){lCt(N)&&LFe(N,t,s),oCt(N)&&LFe(N,t,s);const C=N[0],A=Ovs[C];if(A){const{incompatibleTokens:T}=A;if(Array.isArray(T)){const M=h.find(I=>T.includes(I.token)||I.token===C);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:C,fullToken:N});const P=A.run(s,N,i.match,c);if(!P)return Gu(n,NaN);d.push(P.setter),s=P.rest}else{if(C.match(qvs))throw new RangeError("Format string contains an unescaped latin alphabet character `"+C+"`");if(N==="''"?N="'":C==="'"&&(N=Vvs(N)),s.indexOf(N)===0)s=s.slice(N.length);else return Gu(n,NaN)}}if(s.length>0&&Uvs.test(s))return Gu(n,NaN);const m=d.map(N=>N.priority).sort((N,C)=>C-N).filter((N,C,A)=>A.indexOf(N)===C).map(N=>d.filter(C=>C.priority===N).sort((C,A)=>A.subPriority-C.subPriority)).map(N=>N[0]);let p=Qi(n);if(isNaN(p.getTime()))return Gu(n,NaN);const x={};for(const N of m){if(!N.validate(p,c))return Gu(n,NaN);const C=N.set(p,x,c);Array.isArray(C)?(p=C[0],Object.assign(x,C[1])):p=C}return Gu(n,p)}function Vvs(s){return s.match(Bvs)[1].replace($vs,"'")}function d5(s){return+Qi(s)i-l);return n>=r&&n<=a}function fY(s,t){return Bd(s,-t)}function Lp(s,t){const r=Qvs(s);let a;if(r.date){const c=Jvs(r.date,2);a=e1s(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=t1s(r.time),isNaN(l)))return new Date(NaN);if(r.timezone){if(o=s1s(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 jne={dateTimeDelimiter:/[T ]/,timeZoneDelimiter:/[Z ]/i,timezone:/([Z+-].*)$/},Yvs=/^-?(?:(\d{3})|(\d{2})(?:-?(\d{2}))?|W(\d{2})(?:-?(\d{1}))?|)$/,Zvs=/^(\d{2}(?:[.,]\d*)?)(?::?(\d{2}(?:[.,]\d*)?))?(?::?(\d{2}(?:[.,]\d*)?))?$/,Xvs=/^([+-])(\d{2})(?::?(\d{2}))?$/;function Qvs(s){const t={},n=s.split(jne.dateTimeDelimiter);let r;if(n.length>2)return t;if(/:/.test(n[0])?r=n[0]:(t.date=n[0],r=n[1],jne.timeZoneDelimiter.test(t.date)&&(t.date=s.split(jne.timeZoneDelimiter)[0],r=s.substr(t.date.length,s.length))),r){const a=jne.timezone.exec(r);a?(t.time=r.replace(a[1],""),t.timezone=a[1]):t.time=r}return t}function Jvs(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 e1s(s,t){if(t===null)return new Date(NaN);const n=s.match(Yvs);if(!n)return new Date(NaN);const r=!!n[4],a=QH(n[1]),i=QH(n[2])-1,l=QH(n[3]),o=QH(n[4]),c=QH(n[5])-1;if(r)return o1s(t,o,c)?n1s(t,o,c):new Date(NaN);{const d=new Date(0);return!a1s(t,i,l)||!i1s(t,a)?new Date(NaN):(d.setUTCFullYear(t,i,Math.max(a,l)),d)}}function QH(s){return s?parseInt(s):1}function t1s(s){const t=s.match(Zvs);if(!t)return NaN;const n=BLe(t[1]),r=BLe(t[2]),a=BLe(t[3]);return l1s(n,r,a)?n*CCe+r*SCe+a*1e3:NaN}function BLe(s){return s&&parseFloat(s.replace(",","."))||0}function s1s(s){if(s==="Z")return 0;const t=s.match(Xvs);if(!t)return 0;const n=t[1]==="+"?-1:1,r=parseInt(t[2]),a=t[3]&&parseInt(t[3])||0;return c1s(r,a)?n*(r*CCe+a*SCe):NaN}function n1s(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 r1s=[31,null,31,30,31,30,31,31,30,31,30,31];function mCt(s){return s%400===0||s%4===0&&s%100!==0}function a1s(s,t,n){return t>=0&&t<=11&&n>=1&&n<=(r1s[t]||(mCt(s)?29:28))}function i1s(s,t){return t>=1&&t<=(mCt(s)?366:365)}function o1s(s,t,n){return t>=1&&t<=53&&n>=0&&n<=6}function l1s(s,t,n){return s===24?t===0&&n===0:n>=0&&n<60&&t>=0&&t<60&&s>=0&&s<25}function c1s(s,t){return t>=0&&t<=59}function $Le(s,t){const n=Qi(s),r=n.getFullYear(),a=n.getDate(),i=Gu(s,0);i.setFullYear(r,t,15),i.setHours(0,0,0,0);const l=Vys(i);return n.setMonth(t,Math.min(a,l)),n}function pCt(s,t){const n=Qi(s);return n.setHours(t),n}function fCt(s,t){const n=Qi(s);return n.setMinutes(t),n}function Xat(s,t){const n=Qi(s);return isNaN(+n)?Gu(s,NaN):(n.setFullYear(t),n)}function T8(s,t){return zx(s,-t)}const d1s=()=>{const{user:s}=_s(),t=Vn(),[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 g=`notification_last_read_${s.id}`,y=localStorage.getItem(g);y&&!u.current&&(u.current=y,d(y));const b=`nb_cache_${s.id}`,v=60*1e3,N=async()=>{try{const M=sessionStorage.getItem(b);if(M){const I=JSON.parse(M);if(I.ts&&Date.now()-I.ts{r(T);const P=u.current?new Date(u.current):null,M=T.filter(I=>P?new Date(I.created_at)>P:!0);i(M.length)};N();const A=U.channel("push-notifications").on("postgres_changes",{event:"INSERT",schema:"public",table:"push_notifications"},T=>{const P=T.new;r(I=>{const D=[P,...I].slice(0,20);try{sessionStorage.setItem(b,JSON.stringify({ts:Date.now(),data:D}))}catch{}return D});const M=u.current?new Date(u.current):null;(!M||new Date(P.created_at)>M)&&i(I=>I+1),Notification.permission==="granted"&&new Notification(P.title,{body:P.body,icon:"/favicon.ico"})}).subscribe();return()=>{U.removeChannel(A)}},[s]);const h=g=>{const y=g.toLowerCase();return y.includes("community")||y.includes("post")?Ji:y.includes("academy")||y.includes("video")?Xr:y.includes("template")?Rc:y.includes("event")?ia:y.includes("newsletter")?Gj:y.includes("brokerage")?ix:y.includes("swag")||y.includes("social")?Co:y.includes("toolbox")||y.includes("tool")?c5:y.includes("brief")?dn:Ji},m=g=>{o(!1),g.url&&g.url!=="/"&&t(g.url)},p=()=>{if(!s)return;const g=new Date().toISOString(),y=`notification_last_read_${s.id}`;localStorage.setItem(y,g),d(g),i(0)},x=g=>{o(g),g&&a>0&&p()};return e.jsxs(Hd,{open:l,onOpenChange:x,children:[e.jsx(Gd,{asChild:!0,children:e.jsxs($,{variant:"ghost",size:"icon",className:"relative",children:[e.jsx(Dx,{className:"h-5 w-5"}),a>0&&e.jsx($e,{variant:"destructive",className:"absolute -top-1 -right-1 h-5 w-5 flex items-center justify-center p-0 text-xs",children:a>9?"9+":a})]})}),e.jsxs(Md,{align:"end",className:"w-80",children:[e.jsxs("div",{className:"flex items-center justify-between px-3 py-2 border-b",children:[e.jsx("span",{className:"font-semibold",children:"Notifications"}),n.length>0&&e.jsx($,{variant:"ghost",size:"sm",className:"text-xs h-6",onClick:p,children:"Mark all read"})]}),e.jsx(Oi,{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(g=>{const y=h(g.title);return e.jsxs(Na,{className:"group flex items-start gap-3 p-3 cursor-pointer data-[highlighted]:bg-accent data-[highlighted]:text-accent-foreground",onClick:()=>m(g),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:g.title}),e.jsx("span",{className:"text-xs text-muted-foreground line-clamp-2 group-data-[highlighted]:text-accent-foreground/80",children:g.body}),e.jsx("span",{className:"text-xs text-muted-foreground group-data-[highlighted]:text-accent-foreground/80",children:fc(new Date(g.created_at),{addSuffix:!0})})]})]},g.id)})})]})]})};function u1s(s){return s!=null&&s.length?s.find(t=>t.is_active&&t.mls_provider_id&&!t.no_mls_mode)||s[0]:null}function Mf(){const{user:s}=_s(),{data:t,isLoading:n}=ht({queryKey:["agent-lead-site",s==null?void 0:s.id],queryFn:async()=>{const{data:r,error:a}=await U.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 u1s(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 TCe(s=!0){const{user:t}=_s(),{data:n,isLoading:r}=ht({queryKey:["free-lead-site-offer",t==null?void 0:t.id],enabled:!!t&&s,staleTime:5*60*1e3,queryFn:async()=>{const{data:a}=await U.from("profiles").select("brokerage_id").eq("id",t.id).maybeSingle();if(!(a!=null&&a.brokerage_id))return null;const{data:i}=await U.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 h1s="coaching_access";function xCt(){const{user:s,loading:t,isAdmin:n,isCoach:r}=_s(),{data:a,isLoading:i}=ht({queryKey:["coaching-access",s==null?void 0:s.id],enabled:!!s,staleTime:5*60*1e3,queryFn:async()=>{const[l,o]=await Promise.all([U.from("coaching_assignments").select("id").eq("agent_id",s.id).eq("status","active").limit(1),U.from("feature_entitlements").select("enabled, expires_at").eq("user_id",s.id).eq("feature_key",h1s).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 MCe=[{id:"home",label:"Home",icon:gR,route:"/dashboard",accent:"nav-home"},{id:"crm",label:"CRM",icon:fo,description:"Contacts and follow-up",accent:"nav-crm"},{id:"deals",label:"Deals",icon:a5,description:"Pipeline, transactions and tasks",accent:"nav-deals"},{id:"listings",label:"Listings",icon:Ai,description:"Win and market listings",accent:"nav-listings"},{id:"marketing",label:"Marketing",icon:Eh,description:"Content, email and video",accent:"nav-marketing"},{id:"websites",label:"Websites",icon:Gl,description:"Your site and add-ons",accent:"nav-websites"},{id:"academy",label:"Learn",icon:Ph,description:"Training, programs and coaching",accent:"nav-academy"},{id:"events",label:"Events",icon:CR,route:"/events",accent:"nav-events"},{id:"apps",label:"Apps",icon:R_,route:"/apps",accent:"nav-apps"},{id:"brokerage",label:"Brokerage",icon:jz,description:"Your brokerage, teams and recruiting",accent:"nav-brokerage",visible:s=>!s.isAdmin&&(!!s.brokerageId||s.isBrokerageManager||s.isOnTeam)},{id:"more",label:"More",icon:p0,description:"Community, marketplace and help",accent:"nav-more"}],Q1=s=>t=>t.hasPermission(s),m1s=[{id:"mission-control",label:"Mission Control",route:"/mission-control",icon:t5,description:"Your daily relationship command center",primaryCategory:"crm",section:"Overview",visible:Q1("contacts"),searchKeywords:["agent os","mission control","dashboard"],displayOrder:10},{id:"client-portals",label:"Client Portals",route:"/mission-control/client-portals",icon:dn,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:qn,description:"Every contact in your database",primaryCategory:"crm",section:"Contacts",visible:Q1("contacts"),searchKeywords:["contacts","database","sphere","people"],displayOrder:30},{id:"relationship-report",label:"Relationship Report",route:"/mission-control/relationship-scorecard",icon:zp,description:"See who needs attention next",primaryCategory:"crm",section:"Contacts",visible:Q1("contacts"),searchKeywords:["relationship","scorecard","report"],displayOrder:40},{id:"sphere-gaps",label:"Sphere Gaps",route:"/mission-control/sphere-gaps",icon:GK,description:"Find missing info across your sphere",primaryCategory:"crm",section:"Contacts",visible:Q1("contacts"),searchKeywords:["gaps","missing data"],displayOrder:50},{id:"sent-emails",label:"Sent Emails",route:"/mission-control/sent-emails",icon:Br,description:"History of everything you have sent",primaryCategory:"crm",section:"Contacts",visible:Q1("contacts"),searchKeywords:["sent","email history"],displayOrder:60},{id:"connect-page",label:"Connect Page",route:"/mission-control/connect-page",icon:Dc,description:"Your shareable intake and link page",primaryCategory:"crm",section:"Contacts",visible:Q1("contacts"),searchKeywords:["connect","link in bio","intake"],displayOrder:70},{id:"touchplans",label:"TouchPlans",route:"/mission-control/plans",icon:Nl,description:"Structured touch plans for your people",primaryCategory:"crm",section:"Follow-Up",visible:Q1("contacts"),searchKeywords:["touch plan","follow up plan"],displayOrder:80},{id:"smart-drips",label:"Smart Drips",route:"/mission-control/smart-drips",icon:ox,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:nn,description:"Reusable email templates",primaryCategory:"crm",section:"Follow-Up",searchKeywords:["email template"],displayOrder:100},{id:"signals",label:"Signals",route:"/mission-control/signals",icon:Dz,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:Co,description:"Plan and log in-person pop-bys",primaryCategory:"crm",section:"Follow-Up",visible:Q1("popbys"),searchKeywords:["pop by","gifts","drop off"],displayOrder:120},{id:"pipeline",label:"Deal Pipeline",route:"/mission-control/pipeline",icon:a5,description:"Track every deal from lead to close",primaryCategory:"deals",section:"Pipeline",visible:Q1("pipeline"),searchKeywords:["pipeline","deals","kanban"],displayOrder:130},{id:"transactions",label:"Transactions",route:"/mission-control/transactions",icon:n5,description:"Closed and in-progress transactions",primaryCategory:"deals",section:"Pipeline",visible:Q1("pipeline"),searchKeywords:["transactions","closings"],displayOrder:140},{id:"tasks",label:"Tasks",route:"/mission-control/tasks",icon:TS,description:"Everything on your plate today",primaryCategory:"deals",section:"Pipeline",visible:Q1("pipeline"),searchKeywords:["tasks","to do"],displayOrder:150},{id:"scorecard",label:"Scorecard",route:"/mission-control/scorecard",icon:ml,description:"Your production numbers at a glance",primaryCategory:"deals",section:"Pipeline",visible:Q1("scorecard"),searchKeywords:["scorecard","production","goals"],displayOrder:160},{id:"my-calendar",label:"My Calendar",route:"/mission-control/calendar",icon:Nl,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:Nl,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:Ai,description:"Publish and browse member listings",primaryCategory:"listings",section:"Manage Listings",visible:Q1("listings"),searchKeywords:["listings","exchange","my listings"],displayOrder:10},{id:"listing-presentation-studio",label:"Listing Presentation Studio",route:"/apps/listing-presentation-studio",icon:by,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:yd,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:sa,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:s5,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:n5,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:Jl,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:Rc,description:"Ready-to-edit Canva templates",primaryCategory:"marketing",section:"Create",searchKeywords:["templates","canva","graphics"],displayOrder:10},{id:"marketing-studio",label:"Marketing Studio",route:"/marketing-studio",icon:Jl,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:dv,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:dv,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:lh,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:Gj,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:nn,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:Br,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:Co,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:Xr,description:"All of your recorded videos",primaryCategory:"marketing",section:"Video",visible:Q1("videos"),searchKeywords:["videos","library"],displayOrder:90},{id:"quickvid",label:"QuickVid",route:"/mission-control/video/record",icon:Xr,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:lh,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:w0,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:Dc,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:Gl,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:Gl,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:ga,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:Ya,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:sa,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:ml,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:zp,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:dv,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:dn,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:Ph,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:wf,description:"On-demand training videos",primaryCategory:"academy",section:"Learn",searchKeywords:["academy","videos","training"],displayOrder:20},{id:"toolbox",label:"Toolbox",route:"/toolbox",icon:c5,description:"Scripts, checklists and downloads",primaryCategory:"academy",section:"Learn",searchKeywords:["toolbox","scripts","downloads"],displayOrder:30},{id:"events",label:"Events",route:"/events",icon:CR,description:"Live trainings and member events",primaryCategory:"events",section:"Events",searchKeywords:["events","live","webinar"],displayOrder:10},{id:"programs",label:"Programs",route:"/programs",icon:w0,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:Ph,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:fo,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:Ji,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:i5,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:Tr,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:Bz,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:pl,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:Co,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:Nz,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:dn,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:Wj,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:Wj,description:"Install the LevelUp Chrome extension",primaryCategory:"more",section:"Help & Services",searchKeywords:["extension","chrome"],displayOrder:100},{id:"attract",label:"LevelUp Attract",route:"/attract",icon:dn,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:Ad,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:Ai,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:ES,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:wf,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:qn,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:pc,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:qn,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:Eh,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:IN,description:"Preferred vendor directory",primaryCategory:"brokerage",section:"Manage Brokerage",visible:s=>s.isBrokerageManager&&!s.isAdmin,searchKeywords:["vendors"],displayOrder:200},{id:"brokerage-resources",label:"Brokerage Resources",route:"/brokerage-resources",icon:ix,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:dn,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:v0,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 gCt(s,t){return typeof s.route=="function"?s.route(t):s.route}function yCt(){const{user:s,isAdmin:t,isBrokerageManager:n,isCoach:r,brokerageId:a}=_s(),{hasPermission:i}=aee(),{isInnerCircleEnabled:l,isMarketplaceEnabled:o}=zVe(),{hasAccess:c}=uCe(),{data:d}=Nw(),{leadSite:u,hasLeadSite:h,siteUrl:m}=Mf(),{hasOffer:p}=TCe(!h),x=ek(),{hasAccess:g}=xCt(),y=ts(),{data:b}=ht({queryKey:["my-coach-nav",s==null?void 0:s.id],enabled:!!(s!=null&&s.id),staleTime:5*60*1e3,queryFn:async()=>{const{data:V}=await U.from("coaching_assignments").select("id").eq("agent_id",s.id).eq("status","active").limit(1);return(V||[]).length>0}}),{data:v}=ht({queryKey:["user-tool-favorites",s==null?void 0:s.id],enabled:!!(s!=null&&s.id),staleTime:60*1e3,queryFn:async()=>{const{data:V}=await U.from("user_tool_favorites").select("tool_id").eq("user_id",s.id);return(V||[]).map(K=>K.tool_id)}}),N=j.useMemo(()=>new Set(v||[]),[v]),C=yt({mutationFn:async V=>{s!=null&&s.id&&(N.has(V)?await U.from("user_tool_favorites").delete().eq("user_id",s.id).eq("tool_id",V):await U.from("user_tool_favorites").insert({user_id:s.id,tool_id:V}))},onSuccess:()=>{y.invalidateQueries({queryKey:["user-tool-favorites"]}),y.invalidateQueries({queryKey:["app-catalog"]})}}),A=j.useMemo(()=>{var V,K;return{isAdmin:!!t,isBrokerageManager:!!n,isCoach:!!r,isOnTeam:!!d,hasCoach:!!b,brokerageId:a??null,hasPermission:i,isInnerCircleEnabled:!!l,isMarketplaceEnabled:!!o,hasWeeklyReels:!!c,hasLeadSite:!!h,hasLeadSiteMLS:!!(u!=null&&u.mls_provider_id),hasFreeSiteOffer:!!p,leadSiteId:(u==null?void 0:u.id)??null,siteUrl:m??null,email:(s==null?void 0:s.email)??null,isPartnershipMember:x.isMember,hasCoachingOnboarding:x.isMember&&!!((V=x.pkg)!=null&&V.includes_coaching),hasCoachingAccess:!!g||x.isMember&&!!((K=x.pkg)!=null&&K.includes_coaching)}},[t,n,r,d,b,a,i,l,o,c,h,u,p,m,s==null?void 0:s.email,x.isMember,x.pkg,g]),T=j.useMemo(()=>m1s.filter(V=>V.visible?V.visible(A):!0).map(V=>{if(!x.isRestricted)return V;const K=jhs(V);return!K||x.hasFeature(K)?V:{...V,locked:!0,route:`/upgrade/${K}`}}).sort((V,K)=>V.displayOrder-K.displayOrder),[A,x.isRestricted,x.features]),P=j.useMemo(()=>MCe.filter(V=>V.visible?V.visible(A):!0),[A]),M=j.useMemo(()=>P.filter(V=>!V.route).map(V=>{const K=T.filter(ce=>ce.primaryCategory===V.id),Q=[],J=new Map;for(const ce of K)J.has(ce.section)||(J.set(ce.section,[]),Q.push(ce.section)),J.get(ce.section).push(ce);return{id:V.id,label:V.label,sections:Q.map(ce=>({title:ce,items:J.get(ce)}))}}),[T,P]),I=j.useMemo(()=>new Map(M.map(V=>[V.id,V])),[M]),D=V=>V.toolId||`nav:${V.id}`,B=V=>N.has(D(V));return{ctx:A,categories:M,railCategories:P,categoryMap:I,destinations:T,favorites:N,isFavorite:B,favoritesFor:V=>T.filter(K=>K.primaryCategory===V&&B(K)),favoriteKey:D,toggleFavorite:V=>C.mutate(V),searchDestinations:V=>{const K=V.trim().toLowerCase();return K?T.map(J=>{const ce=J.label.toLowerCase(),ue=(J.description||"").toLowerCase(),ne=(J.searchKeywords||[]).join(" ").toLowerCase();let ee=0;return ce===K?ee=100:ce.startsWith(K)?ee=80:ce.includes(K)?ee=60:ne.includes(K)?ee=40:ue.includes(K)?ee=20:J.section.toLowerCase().includes(K)&&(ee=10),ee&&B(J)&&(ee+=5),{d:J,score:ee}}).filter(J=>J.score>0).sort((J,ce)=>ce.score-J.score).map(J=>J.d):[]},routeFor:V=>gCt(V,A)}}var Qat=1,p1s=.9,f1s=.8,x1s=.17,ULe=.1,qLe=.999,g1s=.9999,y1s=.99,v1s=/[\\\/_+.#"@\[\(\{&]/,b1s=/[\\\/_+.#"@\[\(\{&]/g,_1s=/[\s-]/,vCt=/[\s-]/g;function PFe(s,t,n,r,a,i,l){if(i===t.length)return a===s.length?Qat:y1s;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,x;d>=0;)h=PFe(s,t,n,r,d+1,i+1,l),h>u&&(d===a?h*=Qat:v1s.test(s.charAt(d-1))?(h*=f1s,p=s.slice(a,d-1).match(b1s),p&&a>0&&(h*=Math.pow(qLe,p.length))):_1s.test(s.charAt(d-1))?(h*=p1s,x=s.slice(a,d-1).match(vCt),x&&a>0&&(h*=Math.pow(qLe,x.length))):(h*=x1s,a>0&&(h*=Math.pow(qLe,d-a))),s.charAt(d)!==t.charAt(i)&&(h*=g1s)),(hh&&(h=m*ULe)),h>u&&(u=h),d=n.indexOf(c,d+1);return l[o]=u,u}function Jat(s){return s.toLowerCase().replace(vCt," ")}function w1s(s,t,n){return s=n&&n.length>0?`${s+" "+n.join(" ")}`:s,PFe(s,t,Jat(s),Jat(t),0,0,{})}var JH='[cmdk-group=""]',VLe='[cmdk-group-items=""]',j1s='[cmdk-group-heading=""]',bCt='[cmdk-item=""]',eit=`${bCt}:not([aria-disabled="true"])`,IFe="cmdk-item-select",l9="data-value",N1s=(s,t,n)=>w1s(s,t,n),_Ct=j.createContext(void 0),pee=()=>j.useContext(_Ct),wCt=j.createContext(void 0),fHe=()=>j.useContext(wCt),jCt=j.createContext(void 0),NCt=j.forwardRef((s,t)=>{let n=c9(()=>{var le,he;return{search:"",value:(he=(le=s.value)!=null?le:s.defaultValue)!=null?he:"",selectedItemId:void 0,filtered:{count:0,items:new Map,groups:new Set}}}),r=c9(()=>new Set),a=c9(()=>new Map),i=c9(()=>new Map),l=c9(()=>new Set),o=kCt(s),{label:c,children:d,value:u,onValueChange:h,filter:m,shouldFilter:p,loop:x,disablePointerSelection:g=!1,vimBindings:y=!0,...b}=s,v=Fx(),N=Fx(),C=Fx(),A=j.useRef(null),T=D1s();uO(()=>{if(u!==void 0){let le=u.trim();n.current.value=le,P.emit()}},[u]),uO(()=>{T(6,W)},[]);let P=j.useMemo(()=>({subscribe:le=>(l.current.add(le),()=>l.current.delete(le)),snapshot:()=>n.current,setState:(le,he,ve)=>{var ge,fe,je,Ee;if(!Object.is(n.current[le],he)){if(n.current[le]=he,le==="search")q(),D(),T(1,B);else if(le==="value"){if(document.activeElement.hasAttribute("cmdk-input")||document.activeElement.hasAttribute("cmdk-root")){let Me=document.getElementById(C);Me?Me.focus():(ge=document.getElementById(v))==null||ge.focus()}if(T(7,()=>{var Me;n.current.selectedItemId=(Me=V())==null?void 0:Me.id,P.emit()}),ve||T(5,W),((fe=o.current)==null?void 0:fe.value)!==void 0){let Me=he??"";(Ee=(je=o.current).onValueChange)==null||Ee.call(je,Me);return}}P.emit()}},emit:()=>{l.current.forEach(le=>le())}}),[]),M=j.useMemo(()=>({value:(le,he,ve)=>{var ge;he!==((ge=i.current.get(le))==null?void 0:ge.value)&&(i.current.set(le,{value:he,keywords:ve}),n.current.filtered.items.set(le,I(he,ve)),T(2,()=>{D(),P.emit()}))},item:(le,he)=>(r.current.add(le),he&&(a.current.has(he)?a.current.get(he).add(le):a.current.set(he,new Set([le]))),T(3,()=>{q(),D(),n.current.value||B(),P.emit()}),()=>{i.current.delete(le),r.current.delete(le),n.current.filtered.items.delete(le);let ve=V();T(4,()=>{q(),(ve==null?void 0:ve.getAttribute("id"))===le&&B(),P.emit()})}),group:le=>(a.current.has(le)||a.current.set(le,new Set),()=>{i.current.delete(le),a.current.delete(le)}),filter:()=>o.current.shouldFilter,label:c||s["aria-label"],getDisablePointerSelection:()=>o.current.disablePointerSelection,listId:v,inputId:C,labelId:N,listInnerRef:A}),[]);function I(le,he){var ve,ge;let fe=(ge=(ve=o.current)==null?void 0:ve.filter)!=null?ge:N1s;return le?fe(le,n.current.search,he):0}function D(){if(!n.current.search||o.current.shouldFilter===!1)return;let le=n.current.filtered.items,he=[];n.current.filtered.groups.forEach(ge=>{let fe=a.current.get(ge),je=0;fe.forEach(Ee=>{let Me=le.get(Ee);je=Math.max(Me,je)}),he.push([ge,je])});let ve=A.current;K().sort((ge,fe)=>{var je,Ee;let Me=ge.getAttribute("id"),De=fe.getAttribute("id");return((je=le.get(De))!=null?je:0)-((Ee=le.get(Me))!=null?Ee:0)}).forEach(ge=>{let fe=ge.closest(VLe);fe?fe.appendChild(ge.parentElement===fe?ge:ge.closest(`${VLe} > *`)):ve.appendChild(ge.parentElement===ve?ge:ge.closest(`${VLe} > *`))}),he.sort((ge,fe)=>fe[1]-ge[1]).forEach(ge=>{var fe;let je=(fe=A.current)==null?void 0:fe.querySelector(`${JH}[${l9}="${encodeURIComponent(ge[0])}"]`);je==null||je.parentElement.appendChild(je)})}function B(){let le=K().find(ve=>ve.getAttribute("aria-disabled")!=="true"),he=le==null?void 0:le.getAttribute(l9);P.setState("value",he||void 0)}function q(){var le,he,ve,ge;if(!n.current.search||o.current.shouldFilter===!1){n.current.filtered.count=r.current.size;return}n.current.filtered.groups=new Set;let fe=0;for(let je of r.current){let Ee=(he=(le=i.current.get(je))==null?void 0:le.value)!=null?he:"",Me=(ge=(ve=i.current.get(je))==null?void 0:ve.keywords)!=null?ge:[],De=I(Ee,Me);n.current.filtered.items.set(je,De),De>0&&fe++}for(let[je,Ee]of a.current)for(let Me of Ee)if(n.current.filtered.items.get(Me)>0){n.current.filtered.groups.add(je);break}n.current.filtered.count=fe}function W(){var le,he,ve;let ge=V();ge&&(((le=ge.parentElement)==null?void 0:le.firstChild)===ge&&((ve=(he=ge.closest(JH))==null?void 0:he.querySelector(j1s))==null||ve.scrollIntoView({block:"nearest"})),ge.scrollIntoView({block:"nearest"}))}function V(){var le;return(le=A.current)==null?void 0:le.querySelector(`${bCt}[aria-selected="true"]`)}function K(){var le;return Array.from(((le=A.current)==null?void 0:le.querySelectorAll(eit))||[])}function Q(le){let he=K()[le];he&&P.setState("value",he.getAttribute(l9))}function J(le){var he;let ve=V(),ge=K(),fe=ge.findIndex(Ee=>Ee===ve),je=ge[fe+le];(he=o.current)!=null&&he.loop&&(je=fe+le<0?ge[ge.length-1]:fe+le===ge.length?ge[0]:ge[fe+le]),je&&P.setState("value",je.getAttribute(l9))}function ce(le){let he=V(),ve=he==null?void 0:he.closest(JH),ge;for(;ve&&!ge;)ve=le>0?P1s(ve,JH):I1s(ve,JH),ge=ve==null?void 0:ve.querySelector(eit);ge?P.setState("value",ge.getAttribute(l9)):J(le)}let ue=()=>Q(K().length-1),ne=le=>{le.preventDefault(),le.metaKey?ue():le.altKey?ce(1):J(1)},ee=le=>{le.preventDefault(),le.metaKey?Q(0):le.altKey?ce(-1):J(-1)};return j.createElement(Ka.div,{ref:t,tabIndex:-1,...b,"cmdk-root":"",onKeyDown:le=>{var he;(he=b.onKeyDown)==null||he.call(b,le);let ve=le.nativeEvent.isComposing||le.keyCode===229;if(!(le.defaultPrevented||ve))switch(le.key){case"n":case"j":{y&&le.ctrlKey&&ne(le);break}case"ArrowDown":{ne(le);break}case"p":case"k":{y&&le.ctrlKey&&ee(le);break}case"ArrowUp":{ee(le);break}case"Home":{le.preventDefault(),Q(0);break}case"End":{le.preventDefault(),ue();break}case"Enter":{le.preventDefault();let ge=V();if(ge){let fe=new Event(IFe);ge.dispatchEvent(fe)}}}}},j.createElement("label",{"cmdk-label":"",htmlFor:M.inputId,id:M.labelId,style:O1s},c),LCe(s,le=>j.createElement(wCt.Provider,{value:P},j.createElement(_Ct.Provider,{value:M},le))))}),k1s=j.forwardRef((s,t)=>{var n,r;let a=Fx(),i=j.useRef(null),l=j.useContext(jCt),o=pee(),c=kCt(s),d=(r=(n=c.current)==null?void 0:n.forceMount)!=null?r:l==null?void 0:l.forceMount;uO(()=>{if(!d)return o.item(a,l==null?void 0:l.id)},[d]);let u=SCt(a,i,[s.value,s.children,i],s.keywords),h=fHe(),m=r6(T=>T.value&&T.value===u.current),p=r6(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(IFe,x),()=>T.removeEventListener(IFe,x)},[p,s.onSelect,s.disabled]);function x(){var T,P;g(),(P=(T=c.current).onSelect)==null||P.call(T,u.current)}function g(){h.setState("value",u.current,!0)}if(!p)return null;let{disabled:y,value:b,onSelect:v,forceMount:N,keywords:C,...A}=s;return j.createElement(Ka.div,{ref:oC(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:g,onClick:y?void 0:x},s.children)}),S1s=j.forwardRef((s,t)=>{let{heading:n,children:r,forceMount:a,...i}=s,l=Fx(),o=j.useRef(null),c=j.useRef(null),d=Fx(),u=pee(),h=r6(p=>a||u.filter()===!1?!0:p.search?p.filtered.groups.has(l):!0);uO(()=>u.group(l),[]),SCt(l,o,[s.value,s.heading,c]);let m=j.useMemo(()=>({id:l,forceMount:a}),[a]);return j.createElement(Ka.div,{ref:oC(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),LCe(s,p=>j.createElement("div",{"cmdk-group-items":"",role:"group","aria-labelledby":n?d:void 0},j.createElement(jCt.Provider,{value:m},p))))}),C1s=j.forwardRef((s,t)=>{let{alwaysRender:n,...r}=s,a=j.useRef(null),i=r6(l=>!l.search);return!n&&!i?null:j.createElement(Ka.div,{ref:oC(a,t),...r,"cmdk-separator":"",role:"separator"})}),A1s=j.forwardRef((s,t)=>{let{onValueChange:n,...r}=s,a=s.value!=null,i=fHe(),l=r6(d=>d.search),o=r6(d=>d.selectedItemId),c=pee();return j.useEffect(()=>{s.value!=null&&i.setState("search",s.value)},[s.value]),j.createElement(Ka.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)}})}),E1s=j.forwardRef((s,t)=>{let{children:n,label:r="Suggestions",...a}=s,i=j.useRef(null),l=j.useRef(null),o=r6(d=>d.selectedItemId),c=pee();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(Ka.div,{ref:oC(i,t),...a,"cmdk-list":"",role:"listbox",tabIndex:-1,"aria-activedescendant":o,"aria-label":r,id:c.listId},LCe(s,d=>j.createElement("div",{ref:oC(l,c.listInnerRef),"cmdk-list-sizer":""},d)))}),T1s=j.forwardRef((s,t)=>{let{open:n,onOpenChange:r,overlayClassName:a,contentClassName:i,container:l,...o}=s;return j.createElement($3e,{open:n,onOpenChange:r},j.createElement(U3e,{container:l},j.createElement(pq,{"cmdk-overlay":"",className:a}),j.createElement(fq,{"aria-label":s.label,"cmdk-dialog":"",className:i},j.createElement(NCt,{ref:t,...o}))))}),M1s=j.forwardRef((s,t)=>r6(n=>n.filtered.count===0)?j.createElement(Ka.div,{ref:t,...s,"cmdk-empty":"",role:"presentation"}):null),L1s=j.forwardRef((s,t)=>{let{progress:n,children:r,label:a="Loading...",...i}=s;return j.createElement(Ka.div,{ref:t,...i,"cmdk-loading":"",role:"progressbar","aria-valuenow":n,"aria-valuemin":0,"aria-valuemax":100,"aria-label":a},LCe(s,l=>j.createElement("div",{"aria-hidden":!0},l)))}),Vb=Object.assign(NCt,{List:E1s,Item:k1s,Input:A1s,Group:S1s,Separator:C1s,Dialog:T1s,Empty:M1s,Loading:L1s});function P1s(s,t){let n=s.nextElementSibling;for(;n;){if(n.matches(t))return n;n=n.nextElementSibling}}function I1s(s,t){let n=s.previousElementSibling;for(;n;){if(n.matches(t))return n;n=n.previousElementSibling}}function kCt(s){let t=j.useRef(s);return uO(()=>{t.current=s}),t}var uO=typeof window>"u"?j.useEffect:j.useLayoutEffect;function c9(s){let t=j.useRef();return t.current===void 0&&(t.current=s()),t}function r6(s){let t=fHe(),n=()=>s(t.snapshot());return j.useSyncExternalStore(t.subscribe,n,n)}function SCt(s,t,n,r=[]){let a=j.useRef(),i=pee();return uO(()=>{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(l9,o),a.current=o}),a}var D1s=()=>{let[s,t]=j.useState(),n=c9(()=>new Map);return uO(()=>{n.current.forEach(r=>r()),n.current=new Map},[s]),(r,a)=>{n.current.set(r,a),t({})}};function R1s(s){let t=s.type;return typeof t=="function"?t(s.props):"render"in t?t.render(s.props):s}function LCe({asChild:s,children:t},n){return s&&j.isValidElement(t)?j.cloneElement(R1s(t),{ref:t.ref},n(t.props.children)):n(t)}var O1s={position:"absolute",width:"1px",height:"1px",padding:"0",margin:"-1px",overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",borderWidth:"0"};const pw=j.forwardRef(({className:s,...t},n)=>e.jsx(Vb,{ref:n,className:Tt("flex h-full w-full flex-col overflow-hidden rounded-md bg-popover text-popover-foreground",s),...t}));pw.displayName=Vb.displayName;const F1s=({children:s,...t})=>e.jsx(Os,{...t,children:e.jsx(Rs,{className:"overflow-hidden p-0 shadow-lg",children:e.jsx(pw,{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})})}),fw=j.forwardRef(({className:s,...t},n)=>e.jsxs("div",{className:"flex items-center border-b px-3","cmdk-input-wrapper":"",children:[e.jsx(Vr,{className:"mr-2 h-4 w-4 shrink-0 opacity-50"}),e.jsx(Vb.Input,{ref:n,className:Tt("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})]}));fw.displayName=Vb.Input.displayName;const xw=j.forwardRef(({className:s,...t},n)=>e.jsx(Vb.List,{ref:n,className:Tt("max-h-[300px] overflow-y-auto overflow-x-hidden",s),...t}));xw.displayName=Vb.List.displayName;const gw=j.forwardRef((s,t)=>e.jsx(Vb.Empty,{ref:t,className:"py-6 text-center text-sm",...s}));gw.displayName=Vb.Empty.displayName;const $b=j.forwardRef(({className:s,...t},n)=>e.jsx(Vb.Group,{ref:n,className:Tt("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}));$b.displayName=Vb.Group.displayName;const z1s=j.forwardRef(({className:s,...t},n)=>e.jsx(Vb.Separator,{ref:n,className:Tt("-mx-1 h-px bg-border",s),...t}));z1s.displayName=Vb.Separator.displayName;const iv=j.forwardRef(({className:s,...t},n)=>e.jsx(Vb.Item,{ref:n,className:Tt("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}));iv.displayName=Vb.Item.displayName;const B1s={event:{label:"Events",icon:Nl,color:"bg-blue-500/10 text-blue-600"},template:{label:"Templates",icon:Rc,color:"bg-purple-500/10 text-purple-600"},academy:{label:"Academy",icon:Ph,color:"bg-amber-500/10 text-amber-600"},toolbox:{label:"Toolbox",icon:c5,color:"bg-green-500/10 text-green-600"},"social-swag":{label:"Social Swag",icon:dn,color:"bg-fuchsia-500/10 text-fuchsia-600"}},tit=()=>{const[s,t]=j.useState(!1),[n,r]=j.useState(""),[a,i]=j.useState([]),[l,o]=j.useState(!1),c=Vn(),{searchDestinations:d,isFavorite:u,routeFor:h}=yCt(),m=n.trim()?d(n).slice(0,6):[];j.useEffect(()=>{const y=b=>{b.key==="k"&&(b.metaKey||b.ctrlKey)&&(b.preventDefault(),t(v=>!v))};return document.addEventListener("keydown",y),()=>document.removeEventListener("keydown",y)},[]);const p=j.useCallback(async y=>{if(!y.trim()){i([]);return}o(!0);const b=`%${y}%`;try{const[v,N,C,A,T]=await Promise.all([U.from("events").select("id, title, description, event_date").eq("is_published",!0).or(`title.ilike.${b},description.ilike.${b}`).limit(5),U.from("canva_templates").select("id, name, description, publish_date").or(`name.ilike.${b},description.ilike.${b}`).limit(5),U.from("academy_videos").select("id, title, description, publish_date").eq("is_published",!0).or(`title.ilike.${b},description.ilike.${b}`).limit(5),U.from("resource_kits").select("id, name, description, publish_date").eq("is_published",!0).or(`name.ilike.${b},description.ilike.${b}`).limit(5),U.from("social_swag").select("id, title, description, publish_date").eq("is_published",!0).or(`title.ilike.${b},description.ilike.${b}`).limit(5)]),P=[];v.data&&v.data.forEach(M=>{P.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=>{P.push({id:M.id,title:M.name,description:M.description,type:"template",date:M.publish_date,path:`/templates/${M.id}`})}),C.data&&C.data.forEach(M=>{P.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=>{P.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=>{P.push({id:M.id,title:M.title,description:M.description,type:"social-swag",date:M.publish_date,path:`/social-swag/${M.id}`})}),i(P)}catch(v){console.error("Search error:",v)}finally{o(!1)}},[]);j.useEffect(()=>{const y=setTimeout(()=>{p(n)},300);return()=>clearTimeout(y)},[n,p]);const x=y=>{t(!1),r(""),c(y)},g=a.reduce((y,b)=>(y[b.type]||(y[b.type]=[]),y[b.type].push(b),y),{});return e.jsxs(e.Fragment,{children:[e.jsxs($,{variant:"outline",className:"relative h-9 w-9 p-0 xl:h-9 xl:w-60 xl:justify-start xl:px-3 xl:py-2",onClick:()=>t(!0),children:[e.jsx(Vr,{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(F1s,{open:s,onOpenChange:t,children:[e.jsx(fw,{placeholder:"Search events, templates, academy, toolbox, social swag...",value:n,onValueChange:r}),e.jsxs(xw,{children:[m.length>0&&e.jsx($b,{heading:"Go to",children:m.map(y=>{const b=y.icon;return e.jsxs(iv,{value:`nav-${y.id}-${y.label}`,onSelect:()=>{const v=h(y);y.external||y.openInNewTab?(t(!1),r(""),window.open(v,"_blank","noopener,noreferrer")):x(v)},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(b,{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(wg,{className:"h-3 w-3 fill-current text-primary"})]}),y.description&&e.jsx("div",{className:"text-sm text-muted-foreground truncate",children:y.description})]}),e.jsx($e,{variant:"secondary",className:"text-xs shrink-0",children:y.section})]},`nav-${y.id}`)})}),l&&e.jsx("div",{className:"py-6 text-center text-sm text-muted-foreground",children:"Searching..."}),!l&&n&&a.length===0&&m.length===0&&e.jsxs(gw,{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(g).map(([y,b])=>{const v=B1s[y],N=v.icon;return e.jsx($b,{heading:v.label,children:b.map(C=>e.jsxs(iv,{value:`${C.type}-${C.id}-${C.title}`,onSelect:()=>x(C.path),className:"flex items-start gap-3 py-3 cursor-pointer",children:[e.jsx("div",{className:`p-2 rounded-md ${v.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:C.title}),C.description&&e.jsx("div",{className:"text-sm text-muted-foreground truncate group-data-[selected=true]:text-primary-foreground/80",children:C.description})]}),e.jsxs("div",{className:"flex flex-col items-end gap-1 shrink-0",children:[e.jsx($e,{variant:"secondary",className:"text-xs",children:v.label}),e.jsx("span",{className:"text-xs text-muted-foreground",children:fc(new Date(C.date),{addSuffix:!0})})]})]},`${C.type}-${C.id}`))},y)})]})]})]})},$1s=({expiresAt:s,className:t,showUpgradeButton:n=!0})=>{const[r,a]=j.useState(null),i=Vn();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 x=Math.floor(p/(1e3*60*60*24)),g=Math.floor(p%(1e3*60*60*24)/(1e3*60*60)),y=Math.floor(p%(1e3*60*60)/(1e3*60));a({days:x,hours:g,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:Tt("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(mc,{className:"h-4 w-4 text-destructive"}),e.jsx("span",{className:"text-sm font-medium text-destructive",children:"Your free trial has expired"})]}),n&&e.jsxs($,{size:"sm",onClick:()=>i("/subscription"),className:"bg-primary hover:bg-primary/90 text-xs h-7 px-3",children:[e.jsx(dn,{className:"h-3 w-3 mr-1"}),"Upgrade Now"]})]}):e.jsxs("div",{className:Tt("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(Hr,{className:Tt("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:Tt("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:Tt("text-sm font-bold",o?"text-destructive":c?"text-amber-600":"text-primary"),children:[r.days,"d"]}),e.jsxs("span",{className:Tt("text-sm font-bold",o?"text-destructive":c?"text-amber-600":"text-primary"),children:[r.hours,"h"]}),e.jsxs("span",{className:Tt("text-sm font-bold",o?"text-destructive":c?"text-amber-600":"text-primary"),children:[r.minutes,"m"]}),e.jsx("span",{className:Tt("text-xs",o?"text-destructive/70":c?"text-amber-600/70":"text-primary/70"),children:"remaining"})]})]})]}),n&&e.jsxs($,{size:"sm",onClick:()=>i("/subscription"),variant:o?"destructive":c?"default":"outline",className:Tt("text-xs h-7 px-3",c&&"bg-amber-500 hover:bg-amber-600 text-white"),children:[e.jsx(dn,{className:"h-3 w-3 mr-1"}),"Upgrade"]})]})},U1s=()=>{const s=Vn();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(_e,{className:"w-full max-w-2xl shadow-2xl border-destructive/20 my-8",children:[e.jsxs(Bt,{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(mc,{className:"h-8 w-8 text-destructive"})}),e.jsx(Ut,{className:"text-2xl",children:"Your Free Trial Has Ended"}),e.jsx(vr,{className:"text-base",children:"Your 7-day free trial has expired. Upgrade now to continue accessing all the powerful tools and resources LevelUp has to offer!"})]}),e.jsxs(Oe,{className:"space-y-6",children:[e.jsxs("div",{className:"grid sm:grid-cols-2 gap-4",children:[e.jsx(_e,{className:"border-2 border-primary/20 hover:border-primary/50 transition-colors cursor-pointer",onClick:()=>s("/subscription"),children:e.jsxs(Oe,{className:"p-5 text-center",children:[e.jsx("div",{className:"mx-auto mb-3 h-12 w-12 rounded-full bg-primary/10 flex items-center justify-center",children:e.jsx(qn,{className:"h-6 w-6 text-primary"})}),e.jsx("h3",{className:"font-semibold text-lg mb-1",children:"Individual Agent"}),e.jsxs("p",{className:"text-2xl font-bold text-primary mb-2",children:["$39",e.jsx("span",{className:"text-sm font-normal text-muted-foreground",children:"/mo"})]}),e.jsx("p",{className:"text-sm text-muted-foreground mb-4",children:"Perfect for solo agents ready to level up"}),e.jsxs($,{className:"w-full",onClick:t=>{t.stopPropagation(),s("/subscription")},children:[e.jsx(dn,{className:"h-4 w-4 mr-2"}),"Choose Individual"]})]})}),e.jsx(_e,{className:"border-2 border-amber-500/20 hover:border-amber-500/50 transition-colors cursor-pointer",onClick:()=>s("/subscription"),children:e.jsxs(Oe,{className:"p-5 text-center",children:[e.jsx("div",{className:"mx-auto mb-3 h-12 w-12 rounded-full bg-amber-500/10 flex items-center justify-center",children:e.jsx(Ai,{className:"h-6 w-6 text-amber-600"})}),e.jsx("h3",{className:"font-semibold text-lg mb-1",children:"Brokerage"}),e.jsxs("p",{className:"text-2xl font-bold text-amber-600 mb-2",children:["$299",e.jsx("span",{className:"text-sm font-normal text-muted-foreground",children:"/mo"})]}),e.jsx("p",{className:"text-sm text-muted-foreground mb-4",children:"For teams and brokerages"}),e.jsxs($,{variant:"outline",className:"w-full border-amber-500 text-amber-600 hover:bg-amber-50",onClick:t=>{t.stopPropagation(),s("/subscription")},children:[e.jsx(Ai,{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(ya,{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(nn,{className:"h-4 w-4"}),e.jsx("span",{children:"support@relevelup.com"})]})]})]})]})]})})},q1s=({hasUnseenBrief:s,onClick:t,className:n})=>e.jsxs(Mx,{children:[e.jsx(Lx,{asChild:!0,children:e.jsxs($,{variant:"ghost",size:"icon",onClick:t,className:Tt("relative transition-colors",s&&"text-primary hover:text-primary",n),children:[e.jsx(Eh,{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(tx,{children:e.jsx("p",{children:"The LevelUp Brief"})})]});var PCe="Checkbox",[V1s,IXn]=ip(PCe),[H1s,xHe]=V1s(PCe);function G1s(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]=Ux({prop:n,defaultProp:a??!1,onChange:c,caller:PCe}),[x,g]=j.useState(null),[y,b]=j.useState(null),v=j.useRef(!1),N=x?!!l||!!x.closest("form"):!0,C={checked:m,disabled:i,setChecked:p,control:x,setControl:g,name:o,form:l,value:u,hasConsumerStoppedPropagationRef:v,required:d,defaultChecked:OT(a)?!1:a,isFormControl:N,bubbleInput:y,setBubbleInput:b};return e.jsx(H1s,{scope:t,...C,children:W1s(h)?h(C):r})}var CCt="CheckboxTrigger",ACt=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:x}=xHe(CCt,s),g=Po(a,u),y=j.useRef(c);return j.useEffect(()=>{const b=i==null?void 0:i.form;if(b){const v=()=>h(y.current);return b.addEventListener("reset",v),()=>b.removeEventListener("reset",v)}},[i,h]),e.jsx(Ka.button,{type:"button",role:"checkbox","aria-checked":OT(c)?"mixed":c,"aria-required":d,"data-state":PCt(c),"data-disabled":o?"":void 0,disabled:o,value:l,...r,ref:g,onKeyDown:xa(t,b=>{b.key==="Enter"&&b.preventDefault()}),onClick:xa(n,b=>{h(v=>OT(v)?!0:!v),x&&p&&(m.current=b.isPropagationStopped(),m.current||b.stopPropagation())})})});ACt.displayName=CCt;var gHe=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(G1s,{__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(ACt,{...h,ref:t,__scopeCheckbox:n}),m&&e.jsx(LCt,{__scopeCheckbox:n})]})})});gHe.displayName=PCe;var ECt="CheckboxIndicator",TCt=j.forwardRef((s,t)=>{const{__scopeCheckbox:n,forceMount:r,...a}=s,i=xHe(ECt,n);return e.jsx(dx,{present:r||OT(i.checked)||i.checked===!0,children:e.jsx(Ka.span,{"data-state":PCt(i.checked),"data-disabled":i.disabled?"":void 0,...a,ref:t,style:{pointerEvents:"none",...s.style}})})});TCt.displayName=ECt;var MCt="CheckboxBubbleInput",LCt=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}=xHe(MCt,s),x=Po(n,p),g=mee(i),y=JJ(r);j.useEffect(()=>{const v=m;if(!v)return;const N=window.HTMLInputElement.prototype,A=Object.getOwnPropertyDescriptor(N,"checked").set,T=!a.current;if(g!==i&&A){const P=new Event("click",{bubbles:T});v.indeterminate=OT(i),A.call(v,OT(i)?!1:i),v.dispatchEvent(P)}},[m,g,i,a]);const b=j.useRef(OT(i)?!1:i);return e.jsx(Ka.input,{type:"checkbox","aria-hidden":!0,defaultChecked:l??b.current,required:o,disabled:c,name:d,value:u,form:h,...t,tabIndex:-1,ref:x,style:{...t.style,...y,position:"absolute",pointerEvents:"none",opacity:0,margin:0,transform:"translateX(-100%)"}})});LCt.displayName=MCt;function W1s(s){return typeof s=="function"}function OT(s){return s==="indeterminate"}function PCt(s){return OT(s)?"indeterminate":s?"checked":"unchecked"}const ui=j.forwardRef(({className:s,...t},n)=>e.jsx(gHe,{ref:n,className:Tt("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(TCt,{className:Tt("flex items-center justify-center text-current"),children:e.jsx(oa,{className:"h-4 w-4"})})}));ui.displayName=gHe.displayName;var yHe="Radio",[K1s,ICt]=ip(yHe),[Y1s,Z1s]=K1s(yHe),DCt=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=Po(t,y=>m(y)),x=j.useRef(!1),g=h?d||!!h.closest("form"):!0;return e.jsxs(Y1s,{scope:n,checked:a,disabled:l,children:[e.jsx(Ka.button,{type:"button",role:"radio","aria-checked":a,"data-state":zCt(a),"data-disabled":l?"":void 0,disabled:l,value:o,...u,ref:p,onClick:xa(s.onClick,y=>{a||c==null||c(),g&&(x.current=y.isPropagationStopped(),x.current||y.stopPropagation())})}),g&&e.jsx(FCt,{control:h,bubbles:!x.current,name:r,value:o,checked:a,required:i,disabled:l,form:d,style:{transform:"translateX(-100%)"}})]})});DCt.displayName=yHe;var RCt="RadioIndicator",OCt=j.forwardRef((s,t)=>{const{__scopeRadio:n,forceMount:r,...a}=s,i=Z1s(RCt,n);return e.jsx(dx,{present:r||i.checked,children:e.jsx(Ka.span,{"data-state":zCt(i.checked),"data-disabled":i.disabled?"":void 0,...a,ref:t})})});OCt.displayName=RCt;var X1s="RadioBubbleInput",FCt=j.forwardRef(({__scopeRadio:s,control:t,checked:n,bubbles:r=!0,...a},i)=>{const l=j.useRef(null),o=Po(l,i),c=mee(n),d=JJ(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 x=new Event("click",{bubbles:r});p.call(u,n),u.dispatchEvent(x)}},[c,n,r]),e.jsx(Ka.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}})});FCt.displayName=X1s;function zCt(s){return s?"checked":"unchecked"}var Q1s=["ArrowUp","ArrowDown","ArrowLeft","ArrowRight"],ICe="RadioGroup",[J1s,DXn]=ip(ICe,[k6,ICt]),BCt=k6(),$Ct=ICt(),[ebs,tbs]=J1s(ICe),UCt=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=BCt(n),x=jC(d),[g,y]=Ux({prop:i,defaultProp:a??null,onChange:h,caller:ICe});return e.jsx(ebs,{scope:n,name:r,required:l,disabled:o,value:g,onValueChange:y,children:e.jsx(iCe,{asChild:!0,...p,orientation:c,dir:x,loop:u,children:e.jsx(Ka.div,{role:"radiogroup","aria-required":l,"aria-orientation":c,"data-disabled":o?"":void 0,dir:x,...m,ref:t})})})});UCt.displayName=ICe;var qCt="RadioGroupItem",VCt=j.forwardRef((s,t)=>{const{__scopeRadioGroup:n,disabled:r,...a}=s,i=tbs(qCt,n),l=i.disabled||r,o=BCt(n),c=$Ct(n),d=j.useRef(null),u=Po(t,d),h=i.value===a.value,m=j.useRef(!1);return j.useEffect(()=>{const p=g=>{Q1s.includes(g.key)&&(m.current=!0)},x=()=>m.current=!1;return document.addEventListener("keydown",p),document.addEventListener("keyup",x),()=>{document.removeEventListener("keydown",p),document.removeEventListener("keyup",x)}},[]),e.jsx(oCe,{asChild:!0,...o,focusable:!l,active:h,children:e.jsx(DCt,{disabled:l,required:i.required,checked:h,...c,...a,name:i.name,ref:u,onCheck:()=>i.onValueChange(a.value),onKeyDown:xa(p=>{p.key==="Enter"&&p.preventDefault()}),onFocus:xa(a.onFocus,()=>{var p;m.current&&((p=d.current)==null||p.click())})})})});VCt.displayName=qCt;var sbs="RadioGroupIndicator",HCt=j.forwardRef((s,t)=>{const{__scopeRadioGroup:n,...r}=s,a=$Ct(n);return e.jsx(OCt,{...a,...r,ref:t})});HCt.displayName=sbs;var GCt=UCt,WCt=VCt,nbs=HCt;const wb=j.forwardRef(({className:s,...t},n)=>e.jsx(GCt,{className:Tt("grid gap-2",s),...t,ref:n}));wb.displayName=GCt.displayName;const rh=j.forwardRef(({className:s,...t},n)=>e.jsx(WCt,{ref:n,className:Tt("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(nbs,{className:"flex items-center justify-center",children:e.jsx(Bp,{className:"h-2.5 w-2.5 fill-current text-current"})})}));rh.displayName=WCt.displayName;const rbs=({brief:s,open:t,onClose:n,onDismiss:r})=>{const{user:a}=_s(),[i,l]=j.useState({}),[o,c]=j.useState({}),[d,u]=j.useState([]);j.useEffect(()=>{t&&a&&s.polls.length>0&&h()},[t,a,s.polls]);const h=async()=>{if(!a)return;const y=s.polls.map(v=>v.id),{data:b}=await U.from("levelup_brief_poll_responses").select("poll_id, option_id").eq("user_id",a.id).in("poll_id",y);if(b){const v={};b.forEach(N=>{v[N.poll_id]||(v[N.poll_id]=[]),v[N.poll_id].push(N.option_id)}),c(v)}},m=(y,b)=>{l(v=>({...v,[y]:b}))},p=(y,b,v)=>{l(N=>{const C=N[y]||[];return v?{...N,[y]:[...C,b]}:{...N,[y]:C.filter(A=>A!==b)}})},x=async y=>{if(!a)return;const b=i[y];if(!b||Array.isArray(b)&&b.length===0){ae.error("Please select an option");return}u(v=>[...v,y]);try{await U.from("levelup_brief_poll_responses").delete().eq("poll_id",y).eq("user_id",a.id);const v=Array.isArray(b)?b:[b],N=v.map(A=>({poll_id:y,option_id:A,user_id:a.id})),{error:C}=await U.from("levelup_brief_poll_responses").insert(N);if(C)throw C;c(A=>({...A,[y]:v})),ae.success("Response submitted!")}catch(v){console.error("Error submitting poll response:",v),ae.error("Failed to submit response")}finally{u(v=>v.filter(N=>N!==y))}},g=y=>(y.includes("mediadelivery.net")||y.includes("bunny"),y);return e.jsx(Os,{open:t,onOpenChange:y=>!y&&n(),children:e.jsxs(Rs,{className:"max-w-2xl max-h-[90vh] p-0 overflow-hidden [&>button]:hidden",children:[e.jsxs("div",{className:"bg-gradient-to-r from-primary to-primary/80 p-4 pr-12 text-primary-foreground relative",children:[e.jsx("button",{onClick:n,className:"absolute top-3 right-3 p-1.5 rounded-full bg-white/30 hover:bg-white/50 transition-colors","aria-label":"Close",children:e.jsx(pr,{className:"h-5 w-5 text-white"})}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-2 bg-white/20 rounded-lg",children:e.jsx(Eh,{className:"h-6 w-6"})}),e.jsxs("div",{children:[e.jsx($e,{variant:"secondary",className:"mb-1 bg-white/20 text-white border-0",children:"The LevelUp Brief"}),e.jsx(zs,{className:"text-xl font-bold text-white",children:s.brief.title})]})]})]}),e.jsx(Oi,{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:g(s.brief.video_url),className:"absolute inset-0 w-full h-full",allow:"autoplay; fullscreen; picture-in-picture",allowFullScreen:!0})}),s.brief.graphic_url&&!s.brief.video_url&&e.jsx("div",{className:"rounded-lg overflow-hidden bg-muted",children:s.brief.graphic_link_url?e.jsx("a",{href:s.brief.graphic_link_url,target:"_blank",rel:"noopener noreferrer",className:"block",children:e.jsx("img",{src:s.brief.graphic_url,alt:"Brief graphic",className:"w-full object-contain cursor-pointer hover:opacity-90 transition-opacity"})}):e.jsx("img",{src:s.brief.graphic_url,alt:"Brief graphic",className:"w-full object-contain"})}),s.links.length>0&&e.jsxs("div",{className:"space-y-3",children:[e.jsx("h4",{className:"font-semibold text-foreground",children:"Quick Links"}),e.jsx("div",{className:"flex flex-wrap gap-2",children:s.links.map(y=>e.jsxs($,{variant:"outline",size:"sm",onClick:()=>window.open(y.url,"_blank"),className:"gap-2",children:[e.jsx(Tr,{className:"h-4 w-4"}),y.title]},y.id))})]}),s.polls.map(y=>{var N,C;const b=((N=o[y.id])==null?void 0:N.length)>0,v=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}),b&&e.jsxs($e,{variant:"secondary",className:"gap-1",children:[e.jsx(Fr,{className:"h-3 w-3"}),"Responded"]})]}),y.poll_type==="single"?e.jsx(wb,{value:i[y.id]||((C=o[y.id])==null?void 0:C[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(rh,{value:A.id,id:A.id}),e.jsx(se,{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 P=(i[y.id]||o[y.id]||[]).includes(A.id);return e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(ui,{id:A.id,checked:P,onCheckedChange:M=>p(y.id,A.id,M)}),e.jsx(se,{htmlFor:A.id,className:"cursor-pointer",children:A.option_text})]},A.id)})}),e.jsx($,{size:"sm",onClick:()=>x(y.id),disabled:v,children:v?"Submitting...":b?"Update Response":"Submit"})]},y.id)})]})}),e.jsxs("div",{className:"p-4 pb-[calc(1rem+env(safe-area-inset-bottom))] border-t bg-muted/30 flex flex-col items-center gap-2 sticky bottom-0 z-10",children:[e.jsx($,{onClick:n,className:"w-full max-w-xs",children:"Got it!"}),e.jsx($,{variant:"ghost",size:"sm",onClick:r,children:"Don't show again"})]})]})})},abs=()=>{const{user:s}=_s(),[t,n]=j.useState(null),[r,a]=j.useState(!1),[i,l]=j.useState(!0),[o,c]=j.useState(!1),d=j.useCallback(async()=>{if(!s){l(!1);return}try{const{data:x,error:g}=await U.from("levelup_briefs").select("*").eq("is_published",!0).lte("publish_date",new Date().toISOString()).order("publish_date",{ascending:!1}).limit(1).single();if(g||!x){l(!1);return}const{data:y}=await U.from("levelup_brief_views").select("*").eq("brief_id",x.id).eq("user_id",s.id).maybeSingle(),[b,v]=await Promise.all([U.from("levelup_brief_links").select("*").eq("brief_id",x.id).order("sort_order"),U.from("levelup_brief_polls").select("*").eq("brief_id",x.id).order("sort_order")]),N=[];if(v.data)for(const M of v.data){const{data:I}=await U.from("levelup_brief_poll_options").select("*").eq("poll_id",M.id).order("sort_order");N.push({...M,options:I||[]})}const C={brief:x,links:b.data||[],polls:N};n(C);const A=!!y,T=(y==null?void 0:y.dismissed_at)!=null,P=localStorage.getItem(`brief-dismissed-${x.id}`)==="true";if(T||P)c(!1),a(!1);else if(!A)a(!0),c(!0);else if(x.show_frequency==="every_login")a(!0),c(!0);else if(x.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(x){console.error("Error fetching brief:",x)}finally{l(!1)}},[s]);j.useEffect(()=>{d()},[d]);const u=async()=>{if(!(!s||!t))try{const{data:x}=await U.from("levelup_brief_views").select("id").eq("brief_id",t.brief.id).eq("user_id",s.id).maybeSingle();x?await U.from("levelup_brief_views").update({viewed_at:new Date().toISOString()}).eq("id",x.id):await U.from("levelup_brief_views").insert({brief_id:t.brief.id,user_id:s.id})}catch(x){console.error("Error marking brief as viewed:",x)}};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:x,error:g}=await U.from("levelup_brief_views").select("id").eq("brief_id",t.brief.id).eq("user_id",s.id).maybeSingle();if(g&&console.error("Error checking existing brief view:",g),x){const{error:y}=await U.from("levelup_brief_views").update({dismissed_at:new Date().toISOString()}).eq("id",x.id).eq("user_id",s.id);y&&console.error("Error updating brief dismiss:",y)}else{const{error:y}=await U.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(x){console.error("Error dismissing brief:",x),t&&localStorage.setItem(`brief-dismissed-${t.brief.id}`,"true")}}},refetch:d}};function ibs(){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(di,{className:"h-5 w-5"})}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"font-medium text-sm",children:"Add LevelUp to your home screen"}),n?e.jsxs("p",{className:"text-xs opacity-80 flex items-center gap-1",children:["Tap ",e.jsx(WK,{className:"h-3 w-3 inline"}),' then "Add to Home Screen"']}):e.jsx("p",{className:"text-xs opacity-80",children:"Quick access anytime"})]})]}),e.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0",children:[!n&&a&&e.jsx($,{size:"sm",variant:"secondary",onClick:o,className:"text-xs",children:"Install"}),e.jsx("button",{onClick:l,className:"p-1.5 hover:bg-primary-foreground/10 rounded-full transition-colors","aria-label":"Dismiss",children:e.jsx(pr,{className:"h-4 w-4"})})]})]})}):null}const obs=({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=ts(),h=80,m=120,p=j.useCallback(v=>{const N=c.current;N&&N.scrollTop<=0&&(d.current=v.touches[0].clientY,r(!0))},[]),x=j.useCallback(v=>{if(!n||l)return;const N=c.current;if(!N||N.scrollTop>0){r(!1),i(0);return}const A=v.touches[0].clientY-d.current;if(A>0){const P=Math.min(A*.5,m);i(P),P>10&&v.preventDefault()}},[n,l]),g=j.useCallback(async()=>{if(n)if(r(!1),a>=h&&!l){o(!0),i(h);try{t?await t():await u.invalidateQueries()}catch(v){console.error("Refresh failed:",v)}finally{o(!1),i(0)}}else i(0)},[n,a,l,t,u]),y=Math.min(a/h,1),b=y*180;return e.jsxs("div",{ref:c,className:"h-full overflow-auto",onTouchStart:p,onTouchMove:x,onTouchEnd:g,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(${b}deg)`,transition:l?void 0:"transform 0.1s ease-out"},children:e.jsx(Wi,{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})]})},KCt=()=>{const{user:s}=_s(),[t,n]=j.useState(!1),[r,a]=j.useState(!1),[i,l]=j.useState(0),[o,c]=j.useState(!0);j.useEffect(()=>{(async()=>{if(!s){c(!1);return}try{const{data:p}=await U.from("membership_reviews").select("id").eq("user_id",s.id).maybeSingle();if(p){a(!0),n(!1),c(!1);return}const{data:x}=await U.from("profiles").select("login_count").eq("id",s.id).single(),g=(x==null?void 0:x.login_count)||0;l(g);const y=sessionStorage.getItem("review-prompt-dismissed");n(g>=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:x}=await U.from("membership_reviews").insert({user_id:s.id,rating:m,review_text:p});if(x)throw x;return a(!0),n(!1),{success:!0,pointsAwarded:25}}catch(x){return console.error("Error submitting review:",x),{success:!1,error:x.message}}},[s]),h=j.useCallback(async()=>{if(s)try{await U.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}},lbs="https://search.google.com/local/writereview?placeid=ChIJM73ERQD1QogRPxupMFObuck&source=g.page.m.ia._&laa=nmx-review-solicitation-ia2",cbs=()=>{const{shouldShowPrompt:s,isLoading:t,dismissPrompt:n,submitReview:r,markPostedToGoogle:a}=KCt(),[i,l]=j.useState(!1),[o,c]=j.useState("review"),[d,u]=j.useState(0),[h,m]=j.useState(0),[p,x]=j.useState(""),[g,y]=j.useState(!1),[b,v]=j.useState(!1);if(t||!s&&!b)return null;const N=async()=>{if(d===0){ja({title:"Please select a rating",variant:"destructive"});return}y(!0);const T=await r(d,p);y(!1),T.success?(v(!0),ja({title:"Thank you for your feedback!",description:"Your review helps us improve."}),c("google")):ja({title:"Error submitting review",description:T.error,variant:"destructive"})},C=async T=>{T&&(await navigator.clipboard.writeText(p||`${d} star rating for LevelUp!`),ja({title:"Review copied!",description:"Paste it on Google Reviews."}),await a(),window.open(lbs,"_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(Qa,{className:"h-3.5 w-3.5 fill-current"}),e.jsx("span",{className:"hidden sm:inline",children:"Leave a Review"})]}),e.jsx(Os,{open:i,onOpenChange:A,children:e.jsx(Rs,{className:"sm:max-w-md",children:o==="review"?e.jsxs(e.Fragment,{children:[e.jsxs(Us,{children:[e.jsx(zs,{className:"text-center",children:"How are you enjoying LevelUp?"}),e.jsx(Sr,{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(Qa,{className:Tt("h-8 w-8 transition-colors",(h||d)>=T?"fill-yellow-400 text-yellow-400":"text-muted-foreground")})},T))}),e.jsx(Is,{placeholder:"Tell us about your experience (optional)",value:p,onChange:T=>x(T.target.value),rows:4,className:"resize-none"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx($,{variant:"outline",onClick:A,className:"flex-1",children:"Maybe Later"}),e.jsx($,{onClick:N,disabled:g||d===0,className:"flex-1",children:g?"Submitting...":"Submit Review"})]})]})]}):e.jsxs(e.Fragment,{children:[e.jsxs(Us,{children:[e.jsx(zs,{className:"text-center",children:"🎉 Thank you!"}),e.jsx(Sr,{className:"text-center",children:"Would you mind sharing your review on Google? It really helps other agents discover LevelUp!"})]}),e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsx("p",{className:"text-center text-sm text-muted-foreground",children:"We'll copy your review so you can easily paste it."}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx($,{variant:"outline",onClick:()=>C(!1),className:"flex-1",children:"No Thanks"}),e.jsx($,{onClick:()=>C(!0),className:"flex-1",children:"Yes, Open Google"})]})]})]})})})]})};function dbs(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 g="vapid_public_key";let y=localStorage.getItem(g);if(!y){const{data:N,error:C}=await U.functions.invoke("get-vapid-public-key",{body:{}});if(C)throw C;if(y=(N==null?void 0:N.vapidPublicKey)??null,!y)throw new Error("Missing VAPID public key");localStorage.setItem(g,y)}u(y);const b=await navigator.serviceWorker.register("/push-sw.js",{scope:"/push-notifications/"});c(b),n(Notification.permission);const v=await b.pushManager.getSubscription();a(!!v)}catch(g){console.error("Error initializing push notifications:",g)}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 ae.error("Push notifications are not ready yet. Please try again in a moment."),!1;try{l(!0);const x=await o.pushManager.getSubscription();if(x){try{await x.unsubscribe()}catch(C){console.warn("Failed to unsubscribe existing push subscription:",C)}const{error:N}=await U.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"?ae.error("Notifications blocked. Please enable them in your browser settings (click the lock icon in the address bar)."):ae.error("Notification permission was dismissed. Please try again."),!1}const g=dbs(d);let y;try{y=await o.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:g})}catch(N){console.error("PushManager.subscribe() failed:",N);const C=(N==null?void 0:N.message)||String(N);return C.includes("permission")?ae.error("Push permission denied. Check your browser notification settings."):C.includes("key")||C.includes("VAPID")?ae.error("Push configuration error. Please contact support."):C.includes("AbortError")?ae.error("Push subscription was cancelled. Please try again."):ae.error(`Failed to subscribe: ${C}`),!1}const b=y.toJSON(),{error:v}=await U.from("push_subscriptions").upsert({user_id:s.id,endpoint:b.endpoint,p256dh_key:b.keys.p256dh,auth_key:b.keys.auth},{onConflict:"user_id,endpoint"});if(v)throw console.error("Error saving subscription:",v),ae.error("Failed to save notification preferences. Please try again."),v;return a(!0),ae.success("Push notifications enabled!"),!0}catch(x){if(console.error("Error subscribing to push notifications:",x),!(x instanceof Error&&x.message.includes("toast"))){const g=x instanceof Error?x.message:"Unknown error";ae.error("Failed to enable push notifications: "+g)}return!1}finally{l(!1)}},[h,o,s,d]),p=j.useCallback(async()=>{if(!o||!s)return!1;try{l(!0);const x=await o.pushManager.getSubscription();return x&&await x.unsubscribe(),await U.from("push_subscriptions").delete().eq("user_id",s.id),a(!1),ae.success("Push notifications disabled"),!0}catch(x){console.error("Error unsubscribing:",x);const g=x instanceof Error?x.message:"Unknown error";return ae.error("Failed to disable push notifications: "+g),!1}finally{l(!1)}},[o,s]);return{isSupported:h,permission:t,isSubscribed:r,isLoading:i,vapidPublicKey:d,subscribe:m,unsubscribe:p}}const HLe="push_notification_prompt_dismissed",ubs=["/dashboard","/admin"],hbs=()=>{const{user:s}=_s(),{isSupported:t,isSubscribed:n,isLoading:r,subscribe:a}=YCt(),i=Wd(),[l,o]=j.useState(!1),[c,d]=j.useState(!1),u=ubs.some(p=>i.pathname===p||i.pathname.startsWith(`${p}/`));j.useEffect(()=>{if(u){o(!1);return}if(!s||!t||n||r||localStorage.getItem(`${HLe}_${s.id}`))return;const x=setTimeout(()=>{o(!0)},2e3);return()=>clearTimeout(x)},[s,t,n,r,u]);const h=async()=>{d(!0);const p=await a();d(!1),p&&(s&&localStorage.setItem(`${HLe}_${s.id}`,"true"),o(!1))},m=()=>{s&&localStorage.setItem(`${HLe}_${s.id}`,"true"),o(!1)};return!t||n||u?null:e.jsx(Os,{open:l,onOpenChange:p=>!p&&m(),children:e.jsxs(Rs,{className:"sm:max-w-md",children:[e.jsxs(Us,{children:[e.jsx("div",{className:"mx-auto mb-4 flex h-12 w-12 items-center justify-center rounded-full bg-primary/10",children:e.jsx(Dx,{className:"h-6 w-6 text-primary"})}),e.jsx(zs,{className:"text-center",children:"Stay in the Loop!"}),e.jsx(Sr,{className:"text-center",children:"Enable push notifications to get alerted when:"})]}),e.jsxs("ul",{className:"my-4 space-y-2 text-sm text-muted-foreground",children:[e.jsxs("li",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-primary",children:"•"})," New events go live"]}),e.jsxs("li",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-primary",children:"•"})," Fresh templates are added"]}),e.jsxs("li",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-primary",children:"•"})," New toolbox resources drop"]}),e.jsxs("li",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-primary",children:"•"})," Social swag updates"]}),e.jsxs("li",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-primary",children:"•"})," New newsletters arrive"]}),e.jsxs("li",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-primary",children:"•"})," Posts in your community groups"]})]}),e.jsxs("div",{className:"flex flex-col gap-2",children:[e.jsx($,{onClick:h,disabled:c,className:"w-full",children:c?"Enabling...":"Enable Notifications"}),e.jsx($,{variant:"ghost",onClick:m,className:"w-full",children:"Not Now"})]}),e.jsx("p",{className:"text-center text-xs text-muted-foreground",children:"You can always change this in your Profile settings."})]})})},sit=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},mbs=s=>s?sit(s):sit,pbs=s=>s;function fbs(s,t=pbs){const n=It.useSyncExternalStore(s.subscribe,It.useCallback(()=>t(s.getState()),[s,t]),It.useCallback(()=>t(s.getInitialState()),[s,t]));return It.useDebugValue(n),n}const nit=s=>{const t=mbs(s),n=r=>fbs(t,r);return Object.assign(n,t),n},xbs=s=>s?nit(s):nit;function gbs(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 DFe=s=>t=>{try{const n=s(t);return n instanceof Promise?n:{then(r){return DFe(r)(n)},catch(r){return this}}}catch(n){return{then(r){return this},catch(r){return DFe(r)(n)}}}},ybs=(s,t)=>(n,r,a)=>{let i={storage:gbs(()=>window.localStorage),partialize:y=>y,version:0,merge:(y,b)=>({...b,...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,b)=>(m(y,b),h());const p=s((...y)=>(n(...y),h()),r,a);a.getInitialState=()=>p;let x;const g=()=>{var y,b;if(!u)return;const v=++o;l=!1,c.forEach(C=>{var A;return C((A=r())!=null?A:p)});const N=((b=i.onRehydrateStorage)==null?void 0:b.call(i,(y=r())!=null?y:p))||void 0;return DFe(u.getItem.bind(u))(i.name).then(C=>{if(C)if(typeof C.version=="number"&&C.version!==i.version){if(i.migrate){const A=i.migrate(C.state,C.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,C.state];return[!1,void 0]}).then(C=>{var A;if(v!==o)return;const[T,P]=C;if(x=i.merge(P,(A=r())!=null?A:p),n(x,!0),T)return h()}).then(()=>{v===o&&(N==null||N(r(),void 0),x=r(),l=!0,d.forEach(C=>C(x)))}).catch(C=>{v===o&&(N==null||N(void 0,C))})};return a.persist={setOptions:y=>{i={...i,...y},y.storage&&(u=y.storage)},clearStorage:()=>{u==null||u.removeItem(i.name)},getOptions:()=>i,rehydrate:()=>g(),hasHydrated:()=>l,onHydrate:y=>(c.add(y),()=>{c.delete(y)}),onFinishHydration:y=>(d.add(y),()=>{d.delete(y)})},i.skipHydration||g(),x||p},vbs=ybs,DCe=xbs()(vbs((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 bbs({activeCategory:s,currentCategory:t,onSelect:n,onHover:r,badgeCounts:a,categories:i=MCe}){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:Tt("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 _bs({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=x=>{x.key==="Escape"&&r()},p=x=>{var y;if(!u.current)return;const g=x.target;!u.current.contains(g)&&!((y=g==null?void 0:g.closest)!=null&&y.call(g,"[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,x=m.badgeKey?(d==null?void 0:d[m.badgeKey])??0:0;return e.jsxs("div",{className:Tt("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(Ad,{className:"h-3 w-3 text-muted-foreground","aria-label":"Upgrade required"}),x>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:x>9?"9+":x})]}),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:g=>{g.stopPropagation(),o(m)},className:Tt("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(wg,{className:Tt("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(wg,{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 wbs({categories:s,railCategories:t=MCe,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:Tt("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(g=>g.id===h.id),x=d===h.id;return e.jsxs("div",{children:[e.jsxs("button",{type:"button","aria-expanded":x,onClick:()=>u(x?null:h.id),className:Tt("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(_o,{className:Tt("ml-auto h-4 w-4 transition-transform",x&&"rotate-180")})]}),x&&p&&e.jsx("div",{className:"space-y-3 pb-3 pl-4 pr-1",children:p.sections.map(g=>e.jsxs("div",{children:[e.jsx("p",{className:"px-2 py-1 text-[11px] font-semibold uppercase tracking-wider text-muted-foreground",children:g.title}),g.items.map(y=>{const b=y.icon,v=y.badgeKey?(l==null?void 0:l[y.badgeKey])??0:0,N=(o==null?void 0:o(y))??!1;return e.jsxs("div",{className:Tt("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(b,{className:"h-4 w-4 shrink-0"}),e.jsx("span",{className:"truncate",children:y.label}),v>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:v>9?"9+":v})]}),c&&e.jsx("button",{type:"button","aria-label":N?`Remove ${y.label} from favorites`:`Add ${y.label} to favorites`,onClick:()=>c(y),className:Tt("rounded p-2",N?"text-primary":"text-muted-foreground/60"),children:e.jsx(wg,{className:Tt("h-4 w-4",N&&"fill-current")})})]},y.id)})]},g.title))})]},h.id)})})}function ZCt(){const s=Vn(),t=Wd(),n=yCt(),r=j.useCallback(o=>gCt(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 jbs({communityUnreadCount:s=0,wishlistOpenCount:t=0,flyoutTop:n=64,flyoutLeft:r=80}){const{nav:a,navigate:i,currentCategory:l,isCurrent:o,go:c}=ZCt(),[d,u]=j.useState(null),h=j.useRef(null),m=g=>{const y=MCe.find(b=>b.id===g);if(y!=null&&y.route){u(null),i(y.route);return}u(b=>b===g?null:g)},p=d?a.categoryMap.get(d):void 0,x={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(bbs,{activeCategory:d,currentCategory:l,onSelect:m,categories:a.railCategories,badgeCounts:x}),p&&e.jsx(_bs,{category:p,top:n,left:r,onClose:()=>u(null),onNavigate:g=>{u(null),c(g)},isFavorite:a.isFavorite,favorites:a.favoritesFor(p.id),onToggleFavorite:g=>a.toggleFavorite(a.favoriteKey(g)),isCurrent:o,badgeCounts:{community:s,wishlist:t}})]})}function Nbs({communityUnreadCount:s=0,wishlistOpenCount:t=0,onNavigated:n}){const{nav:r,navigate:a,currentCategory:i,isCurrent:l,go:o}=ZCt();return e.jsx(wbs,{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 Ks=({children:s,title:t})=>{var Ee;const{user:n,signOut:r,isAdmin:a,isBrokerageManager:i,isCoach:l,brokerageId:o}=_s(),{isAssistant:c,actingAsAgent:d,hasPermission:u}=aee();uCe();const{isImpersonating:h}=aCe(),p=(c&&!!d?40:0)+(h?40:0),{avatarUrl:x}=c4t(n==null?void 0:n.id),{isTrial:g,isExpired:y,expiresAt:b}=Ehs(n==null?void 0:n.id),{isInnerCircleEnabled:v,isMarketplaceEnabled:N}=zVe(),{currentBrief:C,shouldShowPopup:A,hasUnseenBrief:T,openBrief:P,closeBrief:M,dismissBrief:I}=abs(),{unreadCount:D}=Ths(),{openCount:B}=Mhs();Nw();const W=DCe(Me=>Me.cartItems).reduce((Me,De)=>Me+De.quantity,0),{leadSite:V,hasLeadSite:K,siteUrl:Q}=Mf();TCe(!K);const J=Vn(),ce=Wd(),[ue,ne]=j.useState(null);j.useEffect(()=>{n!=null&&n.id&&U.from("profiles").select("name").eq("id",n.id).single().then(({data:Me})=>{Me!=null&&Me.name&&ne(Me.name)})},[n==null?void 0:n.id]);const ee=ue||((Ee=n==null?void 0:n.user_metadata)==null?void 0:Ee.name)||(n==null?void 0:n.email)||"User",[le,he]=j.useState(!1),ve=Me=>Me.split(" ").map(De=>De[0]).join("").toUpperCase().slice(0,2),ge=Me=>ce.pathname===Me,fe=()=>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:()=>J("/dashboard"),"aria-label":"LevelUp home",children:e.jsx("img",{src:Yhs,alt:"LevelUp",className:"h-8 w-auto"})})}),e.jsxs(Oi,{className:"flex-1 [&_[data-radix-scroll-area-scrollbar]]:w-1.5",children:[e.jsx(jbs,{communityUnreadCount:D,wishlistOpenCount:B,flyoutTop:p+64,flyoutLeft:80}),g&&!y&&e.jsx("div",{className:"p-2",children:e.jsxs("button",{type:"button",onClick:()=>J("/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(dn,{className:"h-4 w-4"}),"Upgrade"]})})]})]}),je=({onNavigated:Me})=>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:Khs,alt:"LevelUp",className:"h-8 w-auto"})}),e.jsxs(Oi,{className:"flex-1",children:[g&&!y&&e.jsx("div",{className:"p-2",children:e.jsx("button",{type:"button",onClick:()=>{J("/subscription"),Me==null||Me()},className:Tt("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(dn,{className:"h-4 w-4 text-amber-500"}),e.jsx("span",{className:"flex-1 text-left",children:"Ready to Upgrade?"}),b&&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(b).getTime()-Date.now())/864e5)),"d left"]})]})})}),e.jsx(Nbs,{communityUnreadCount:D,wishlistOpenCount:B,onNavigated:Me})]}),e.jsxs("div",{className:"border-t border-sidebar-border p-3",children:[e.jsxs($,{variant:"ghost",size:"sm",className:Tt("w-full justify-start gap-2 text-sidebar-foreground hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",ge("/profile")&&"bg-sidebar-accent text-sidebar-accent-foreground"),onClick:()=>{J("/profile"),Me==null||Me()},children:[e.jsx(Lo,{className:"h-4 w-4"}),"Profile"]}),e.jsxs($,{variant:"ghost",size:"sm",className:"w-full justify-start gap-2 text-sidebar-foreground hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",onClick:r,children:[e.jsx(vR,{className:"h-4 w-4"}),"Sign Out"]})]})]});return e.jsx(JN,{children:e.jsxs("div",{className:"min-h-screen bg-background flex",children:[g&&y&&ce.pathname!=="/subscription"&&e.jsx(U1s,{}),typeof document<"u"&&n1.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(fe,{})}),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(Ub,{open:le,onOpenChange:he,children:[e.jsx(cee,{asChild:!0,children:e.jsx($,{variant:"ghost",size:"icon",className:"md:hidden",children:e.jsx(jT,{className:"h-5 w-5"})})}),e.jsx(T1,{side:"left",className:"w-72 p-0 bg-card",children:e.jsx(je,{onNavigated:()=>he(!1)})})]}),e.jsx("div",{className:"flex-1 md:hidden",children:e.jsx("img",{src:Zhs,alt:"LevelUp",className:"h-8 w-auto"})}),e.jsx("div",{className:"hidden md:flex flex-1 justify-center",children:e.jsx(tit,{})}),e.jsxs("div",{className:"flex items-center gap-3 ml-auto",children:[g&&!y&&b&&e.jsx($1s,{expiresAt:b,className:"hidden lg:flex"}),e.jsx("div",{className:"md:hidden",children:e.jsx(tit,{})}),C&&e.jsx(q1s,{hasUnseenBrief:T,onClick:P}),N&&e.jsxs($,{variant:"ghost",size:"icon",className:"relative",onClick:()=>J("/marketplace/cart"),children:[e.jsx(ON,{className:"h-5 w-5"}),W>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:W>99?"99+":W})]}),e.jsx($,{variant:"ghost",size:"icon","aria-label":"My Calendar",title:"My Calendar",onClick:()=>J("/mission-control/calendar"),children:e.jsx(Nl,{className:"h-5 w-5"})}),e.jsx(d1s,{}),e.jsx(AFe,{}),e.jsxs("span",{className:"hidden sm:block text-sm font-medium text-foreground",children:["Hello, ",ee.split(" ")[0],"!"]}),e.jsxs(Hd,{children:[e.jsx(Gd,{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(ki,{src:x||void 0}),e.jsx(Ta,{className:"bg-primary text-primary-foreground font-medium text-sm",children:ve(ee)})]})})}),e.jsxs(Md,{align:"end",className:"w-48",children:[e.jsxs(Na,{onClick:()=>J("/profile"),className:"cursor-pointer",children:[e.jsx(Lo,{className:"h-4 w-4 mr-2"}),"Profile"]}),e.jsxs(Na,{onClick:()=>J("/mission-control/integrations"),className:"cursor-pointer",children:[e.jsx(Wj,{className:"h-4 w-4 mr-2"}),"Integrations"]}),e.jsxs(Na,{onClick:()=>J("/mission-control/browser-extension"),className:"cursor-pointer",children:[e.jsx(Wj,{className:"h-4 w-4 mr-2"}),"Browser Extension"]}),e.jsx(S0,{}),e.jsxs(Na,{onClick:r,className:"cursor-pointer text-destructive focus:text-destructive",children:[e.jsx(vR,{className:"h-4 w-4 mr-2"}),"Sign Out"]})]})]})]})]})}),e.jsx(obs,{children:e.jsx("main",{className:"p-4 sm:p-6 lg:p-8 overflow-x-hidden",children:s})}),C&&e.jsx(rbs,{brief:C,open:A,onClose:M,onDismiss:I}),e.jsx(ibs,{}),e.jsx(cbs,{}),e.jsx(hbs,{})]})]})})},yn=({children:s,requireAdmin:t=!1,requireBrokerageManager:n=!1})=>{const{user:r,loading:a,rolesLoading:i,isAdmin:l,isBrokerageManager:o}=_s(),c=Wd(),d=ek();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(r1,{to:"/auth",replace:!0})}if(t&&!l)return e.jsx(r1,{to:"/dashboard",replace:!0});if(n&&!o&&!l)return e.jsx(r1,{to:"/dashboard",replace:!0});if(d.isRestricted&&!d.isLoading){const u=o4t(c.pathname);if(u&&!d.hasFeature(u))return e.jsx(Ks,{title:"Upgrade required",children:e.jsx(Ahs,{featureKey:u})})}return e.jsx(e.Fragment,{children:s})};var vHe={};(function s(t,n,r,a){var i=!!(t.Worker&&t.Blob&&t.Promise&&t.OffscreenCanvas&&t.OffscreenCanvasRenderingContext2D&&t.HTMLCanvasElement&&t.HTMLCanvasElement.prototype.transferControlToOffscreen&&t.URL&&t.URL.createObjectURL),l=typeof Path2D=="function"&&typeof DOMMatrix=="function",o=function(){if(!t.OffscreenCanvas)return!1;try{var ne=new OffscreenCanvas(1,1),ee=ne.getContext("2d");ee.fillRect(0,0,1,1);var le=ne.transferToImageBitmap();ee.createPattern(le,"no-repeat")}catch{return!1}return!0}();function c(){}function d(ne){var ee=n.exports.Promise,le=ee!==void 0?ee:t.Promise;return typeof le=="function"?new le(ne):(ne(c,c),null)}var u=function(ne,ee){return{transform:function(le){if(ne)return le;if(ee.has(le))return ee.get(le);var he=new OffscreenCanvas(le.width,le.height),ve=he.getContext("2d");return ve.drawImage(le,0,0),ee.set(le,he),he},clear:function(){ee.clear()}}}(o,new Map),h=function(){var ne=Math.floor(16.666666666666668),ee,le,he={},ve=0;return typeof requestAnimationFrame=="function"&&typeof cancelAnimationFrame=="function"?(ee=function(ge){var fe=Math.random();return he[fe]=requestAnimationFrame(function je(Ee){ve===Ee||ve+ne-1{const{data:t,error:n}=await U.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 Sbs(){const s=ts();return yt({mutationFn:async t=>{const{error:n}=await U.from("celebration_queue").update({seen_at:new Date().toISOString()}).eq("id",t);if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["celebrations"]})}})}function Cbs(){const s=ts(),{user:t}=_s();return yt({mutationFn:async n=>{const{error:r}=await U.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 Abs={points_earned:pl,listing_created:sa,deal_closed:qd,custom:Qa},ait={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"},iit=()=>{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 Ebs(){const{user:s}=_s(),t=ts(),{data:n}=kbs(),r=Sbs(),[a,i]=j.useState(null),[l,o]=j.useState(!1),c=j.useCallback(()=>{const p=Date.now()+3e3,x={startVelocity:30,spread:360,ticks:60,zIndex:9999},g=(b,v)=>Math.random()*(v-b)+b,y=setInterval(()=>{const b=p-Date.now();if(b<=0){clearInterval(y);return}const v=50*(b/3e3);rit({...x,particleCount:v,origin:{x:g(.1,.3),y:Math.random()-.2},colors:["#ff6b6b","#feca57","#48dbfb","#ff9ff3","#54a0ff","#5f27cd"]}),rit({...x,particleCount:v,origin:{x:g(.7,.9),y:Math.random()-.2},colors:["#ff6b6b","#feca57","#48dbfb","#ff9ff3","#54a0ff","#5f27cd"]})},250)},[]);j.useEffect(()=>{iit()||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(x=>x.id!==m))??[]),await r.mutateAsync(m)}};if(iit()||!a)return null;const u=Abs[a.celebration_type]||Qa,h=ait[a.celebration_type]||ait.custom;return e.jsx(Os,{open:l,onOpenChange:m=>!m&&d(),children:e.jsxs(Rs,{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(dn,{className:"w-5 h-5 text-yellow-500 animate-pulse"}),e.jsx(dn,{className:"w-5 h-5 text-yellow-500 animate-pulse delay-75"}),e.jsx(dn,{className:"w-5 h-5 text-yellow-500 animate-pulse delay-150"})]}),e.jsxs("h2",{className:"text-2xl font-bold mb-2 bg-gradient-to-r from-primary to-secondary bg-clip-text text-transparent",children:["🎉 ",a.title]}),a.points_amount&&a.points_amount>0&&e.jsxs("div",{className:"text-4xl font-bold text-primary mb-2",children:["+",a.points_amount," points!"]}),a.message&&e.jsx("p",{className:"text-muted-foreground mb-6",children:a.message}),e.jsx($,{onClick:d,className:"w-full",size:"lg",children:"Awesome! 🙌"}),n&&n.length>1&&e.jsxs("p",{className:"text-sm text-muted-foreground mt-3",children:["+",n.length-1," more celebration",n.length>2?"s":""," waiting"]})]})]})})}function on({className:s,...t}){return e.jsx("div",{className:Tt("animate-pulse rounded-md bg-muted",s),...t})}var RCe="Tabs",[Tbs,RXn]=ip(RCe,[k6]),XCt=k6(),[Mbs,bHe]=Tbs(RCe),QCt=j.forwardRef((s,t)=>{const{__scopeTabs:n,value:r,onValueChange:a,defaultValue:i,orientation:l="horizontal",dir:o,activationMode:c="automatic",...d}=s,u=jC(o),[h,m]=Ux({prop:r,onChange:a,defaultProp:i??"",caller:RCe});return e.jsx(Mbs,{scope:n,baseId:Fx(),value:h,onValueChange:m,orientation:l,dir:u,activationMode:c,children:e.jsx(Ka.div,{dir:u,"data-orientation":l,...d,ref:t})})});QCt.displayName=RCe;var JCt="TabsList",eAt=j.forwardRef((s,t)=>{const{__scopeTabs:n,loop:r=!0,...a}=s,i=bHe(JCt,n),l=XCt(n);return e.jsx(iCe,{asChild:!0,...l,orientation:i.orientation,dir:i.dir,loop:r,children:e.jsx(Ka.div,{role:"tablist","aria-orientation":i.orientation,...a,ref:t})})});eAt.displayName=JCt;var tAt="TabsTrigger",sAt=j.forwardRef((s,t)=>{const{__scopeTabs:n,value:r,disabled:a=!1,...i}=s,l=bHe(tAt,n),o=XCt(n),c=aAt(l.baseId,r),d=iAt(l.baseId,r),u=r===l.value;return e.jsx(oCe,{asChild:!0,...o,focusable:!a,active:u,children:e.jsx(Ka.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:xa(s.onMouseDown,h=>{!a&&h.button===0&&h.ctrlKey===!1?l.onValueChange(r):h.preventDefault()}),onKeyDown:xa(s.onKeyDown,h=>{[" ","Enter"].includes(h.key)&&l.onValueChange(r)}),onFocus:xa(s.onFocus,()=>{const h=l.activationMode!=="manual";!u&&!a&&h&&l.onValueChange(r)})})})});sAt.displayName=tAt;var nAt="TabsContent",rAt=j.forwardRef((s,t)=>{const{__scopeTabs:n,value:r,forceMount:a,children:i,...l}=s,o=bHe(nAt,n),c=aAt(o.baseId,r),d=iAt(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(dx,{present:a||u,children:({present:m})=>e.jsx(Ka.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})})});rAt.displayName=nAt;function aAt(s,t){return`${s}-trigger-${t}`}function iAt(s,t){return`${s}-content-${t}`}var Lbs=QCt,oAt=eAt,lAt=sAt,cAt=rAt;const ua=Lbs,ha=j.forwardRef(({className:s,...t},n)=>e.jsx(oAt,{ref:n,className:Tt("inline-flex h-10 items-center justify-center rounded-md bg-muted p-1 text-muted-foreground",s),...t}));ha.displayName=oAt.displayName;const Qt=j.forwardRef(({className:s,...t},n)=>e.jsx(lAt,{ref:n,className:Tt("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}));Qt.displayName=lAt.displayName;const Jt=j.forwardRef(({className:s,...t},n)=>e.jsx(cAt,{ref:n,className:Tt("mt-2 ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",s),...t}));Jt.displayName=cAt.displayName;const qZ="#0d0d0d",Vke="#1a1a1a",my="#c9a84c",fee="#f0d78c",b5={captured:"lup_lead_captured_v1",stickyDismissed:"lup_sticky_dismissed_v1",exitShown:"lup_exit_shown_v1",savedListings:"lup_saved_listings_v1"};async function OCe(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 U.functions.invoke("public-site-lead",{body:t});if(r)throw r;try{localStorage.setItem(b5.captured,JSON.stringify({email:s.email,ts:Date.now()}))}catch{}return n}function _He(){try{return!!localStorage.getItem(b5.captured)}catch{return!1}}function Pbs(){try{const s=localStorage.getItem(b5.captured);return s?JSON.parse(s).email??null:null}catch{return null}}function wHe({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?n1.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, ${Vke} 0%, ${qZ} 100%)`,border:`1px solid ${my}33`,boxShadow:`0 30px 80px rgba(0,0,0,0.6), 0 0 0 1px ${my}22 inset`},children:[e.jsx("button",{onClick:t,className:"absolute right-4 top-4 z-10 rounded-full p-2 text-white/60 hover:text-white hover:bg-white/10 transition","aria-label":"Close",children:e.jsx(pr,{className:"h-4 w-4"})}),n]})}),document.body):null}function jHe(){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 NHe({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(Lo,{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(nn,{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(ya,{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(ai,{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 kHe({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, ${fee} 0%, ${my} 100%)`,color:qZ,boxShadow:`0 8px 24px ${my}55`},children:s})}function oit({open:s,onClose:t,initialCriteria:n}){const{values:r,setValues:a,loading:i,setLoading:l,honeypot:o,setHoneypot:c}=jHe(),[d,u]=j.useState(!1),h=async m=>{if(m.preventDefault(),!!r.email){l(!0);try{await OCe({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(b5.stickyDismissed,"1")}catch{}setTimeout(t,2200)}catch{ae.error("Something went wrong. Please try again.")}finally{l(!1)}}};return e.jsx(wHe,{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(Dx,{className:"h-4 w-4",style:{color:my}}),e.jsx("span",{className:"text-xs uppercase tracking-[0.2em]",style:{color:fee},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:`${my}22`,border:`1px solid ${my}55`},children:e.jsx(dn,{className:"h-5 w-5",style:{color:my}})}),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(NHe,{values:r,setValues:a,honeypot:o,setHoneypot:c}),e.jsx(kHe,{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 Ibs(){const[s,t]=j.useState(!0),[n,r]=j.useState(!1);j.useEffect(()=>{try{const i=!!localStorage.getItem(b5.stickyDismissed)||_He();t(i)}catch{t(!1)}},[]);const a=()=>{t(!0);try{localStorage.setItem(b5.stickyDismissed,"1")}catch{}};return s?e.jsx(oit,{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, ${Vke} 0%, ${qZ} 100%)`,borderTop:`1px solid ${my}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:`${my}22`,border:`1px solid ${my}55`},children:e.jsx(Dx,{className:"h-4 w-4",style:{color:my}})}),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, ${fee} 0%, ${my} 100%)`,color:qZ},children:"Get Alerts"}),e.jsx("button",{onClick:a,className:"p-2 text-white/50 hover:text-white transition","aria-label":"Dismiss",children:e.jsx(pr,{className:"h-4 w-4"})})]})}),e.jsx(oit,{open:n,onClose:()=>r(!1)})]})}function Dbs(){const[s,t]=j.useState(!1),n=j.useRef(!1);j.useEffect(()=>{try{if(sessionStorage.getItem(b5.exitShown)||_He())return}catch{}const m=setTimeout(()=>{n.current=!0},8e3),p=x=>{if(n.current&&!(x.clientY>0)){t(!0);try{sessionStorage.setItem(b5.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}=jHe(),[d,u]=j.useState(!1),h=async m=>{if(m.preventDefault(),!!r.email){l(!0);try{await OCe({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{ae.error("Something went wrong. Please try again.")}finally{l(!1)}}};return e.jsx(wHe,{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, ${qZ} 0%, ${Vke} 60%, ${my} 130%)`},children:e.jsx("div",{className:"absolute top-4 left-6",children:e.jsx("span",{className:"text-[10px] uppercase tracking-[0.25em]",style:{color:fee},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:Vke,border:`1px solid ${my}55`,boxShadow:"0 8px 24px rgba(0,0,0,0.5)"},children:e.jsx(dn,{className:"h-6 w-6",style:{color:my}})}),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(NHe,{values:r,setValues:a,honeypot:o,setHoneypot:c,showPhone:!1}),e.jsx(kHe,{type:"submit",disabled:i||!r.email,children:i?"Sending…":"Send My List"})]})]})]})})}function Rbs(){const[s,t]=j.useState([]);j.useEffect(()=>{try{const o=localStorage.getItem(b5.savedListings);o&&t(JSON.parse(o))}catch{}},[]);const n=o=>{t(o);try{localStorage.setItem(b5.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 Obs({listingId:s,listingAddress:t,className:n}){const{has:r,add:a,remove:i}=Rbs(),l=r(s),[o,c]=j.useState(!1),d=()=>{if(l){i(s);return}if(_He()){a(s),ae.success("Saved to your favorites"),OCe({lead_type:"saved_listing",email:Pbs()||"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(fo,{className:`h-5 w-5 ${l?"fill-current":""}`})}),e.jsx(Fbs,{open:o,onClose:()=>c(!1),listingId:s,listingAddress:t,onSaved:()=>a(s)})]})}function Fbs({open:s,onClose:t,listingId:n,listingAddress:r,onSaved:a}){const{values:i,setValues:l,loading:o,setLoading:c,honeypot:d,setHoneypot:u}=jHe(),h=async m=>{if(m.preventDefault(),!!i.email){c(!0);try{await OCe({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(),ae.success("Saved to your favorites"),t()}catch{ae.error("Something went wrong. Please try again.")}finally{c(!1)}}};return e.jsx(wHe,{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(fo,{className:"h-4 w-4",style:{color:my}}),e.jsx("span",{className:"text-xs uppercase tracking-[0.2em]",style:{color:fee},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(NHe,{values:i,setValues:l,honeypot:d,setHoneypot:u}),e.jsx(kHe,{type:"submit",disabled:o||!i.email,children:o?"Saving…":"Save Home"})]})]})})}var dAt=["PageUp","PageDown"],uAt=["ArrowUp","ArrowDown","ArrowLeft","ArrowRight"],hAt={"from-left":["Home","PageDown","ArrowDown","ArrowLeft"],"from-right":["Home","PageDown","ArrowDown","ArrowRight"],"from-bottom":["Home","PageDown","ArrowDown","ArrowLeft"],"from-top":["Home","PageDown","ArrowUp","ArrowLeft"]},Aq="Slider",[RFe,zbs,Bbs]=uq(Aq),[mAt,OXn]=ip(Aq,[Bbs]),[$bs,FCe]=mAt(Aq),pAt=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:x,...g}=s,y=j.useRef(new Set),b=j.useRef(0),N=l==="horizontal"?Ubs:qbs,[C=[],A]=Ux({prop:u,defaultProp:d,onChange:B=>{var W;(W=[...y.current][b.current])==null||W.focus(),h(B)}}),T=j.useRef(C);function P(B){const q=Kbs(C,B);D(B,q)}function M(B){D(B,b.current)}function I(){const B=T.current[b.current];C[b.current]!==B&&m(C)}function D(B,q,{commit:W}={commit:!1}){const V=Qbs(i),K=Jbs(Math.round((B-r)/i)*i+r,V),Q=BZ(K,[r,a]);A((J=[])=>{const ce=Gbs(J,Q,q);if(Xbs(ce,c*i)){b.current=ce.indexOf(Q);const ue=String(ce)!==String(J);return ue&&W&&m(ce),ue?ce:J}else return J})}return e.jsx($bs,{scope:s.__scopeSlider,name:n,disabled:o,min:r,max:a,valueIndexToChangeRef:b,thumbs:y.current,values:C,orientation:l,form:x,children:e.jsx(RFe.Provider,{scope:s.__scopeSlider,children:e.jsx(RFe.Slot,{scope:s.__scopeSlider,children:e.jsx(N,{"aria-disabled":o,"data-disabled":o?"":void 0,...g,ref:t,onPointerDown:xa(g.onPointerDown,()=>{o||(T.current=C)}),min:r,max:a,inverted:p,onSlideStart:o?void 0:P,onSlideMove:o?void 0:M,onSlideEnd:o?void 0:I,onHomeKeyDown:()=>!o&&D(r,0,{commit:!0}),onEndKeyDown:()=>!o&&D(a,C.length-1,{commit:!0}),onStepKeyDown:({event:B,direction:q})=>{if(!o){const K=dAt.includes(B.key)||B.shiftKey&&uAt.includes(B.key)?10:1,Q=b.current,J=C[Q],ce=i*K*q;D(J+ce,Q,{commit:!0})}}})})})})});pAt.displayName=Aq;var[fAt,xAt]=mAt(Aq,{startEdge:"left",endEdge:"right",size:"width",direction:1}),Ubs=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=Po(t,N=>m(N)),x=j.useRef(void 0),g=jC(a),y=g==="ltr",b=y&&!i||!y&&i;function v(N){const C=x.current||h.getBoundingClientRect(),A=[0,C.width],P=SHe(A,b?[n,r]:[r,n]);return x.current=C,P(N-C.left)}return e.jsx(fAt,{scope:s.__scopeSlider,startEdge:b?"left":"right",endEdge:b?"right":"left",direction:b?1:-1,size:"width",children:e.jsx(gAt,{dir:g,"data-orientation":"horizontal",...u,ref:p,style:{...u.style,"--radix-slider-thumb-transform":"translateX(-50%)"},onSlideStart:N=>{const C=v(N.clientX);l==null||l(C)},onSlideMove:N=>{const C=v(N.clientX);o==null||o(C)},onSlideEnd:()=>{x.current=void 0,c==null||c()},onStepKeyDown:N=>{const A=hAt[b?"from-left":"from-right"].includes(N.key);d==null||d({event:N,direction:A?-1:1})}})})}),qbs=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=Po(t,u),m=j.useRef(void 0),p=!a;function x(g){const y=m.current||u.current.getBoundingClientRect(),b=[0,y.height],N=SHe(b,p?[r,n]:[n,r]);return m.current=y,N(g-y.top)}return e.jsx(fAt,{scope:s.__scopeSlider,startEdge:p?"bottom":"top",endEdge:p?"top":"bottom",size:"height",direction:p?1:-1,children:e.jsx(gAt,{"data-orientation":"vertical",...d,ref:h,style:{...d.style,"--radix-slider-thumb-transform":"translateY(50%)"},onSlideStart:g=>{const y=x(g.clientY);i==null||i(y)},onSlideMove:g=>{const y=x(g.clientY);l==null||l(y)},onSlideEnd:()=>{m.current=void 0,o==null||o()},onStepKeyDown:g=>{const b=hAt[p?"from-bottom":"from-top"].includes(g.key);c==null||c({event:g,direction:b?-1:1})}})})}),gAt=j.forwardRef((s,t)=>{const{__scopeSlider:n,onSlideStart:r,onSlideMove:a,onSlideEnd:i,onHomeKeyDown:l,onEndKeyDown:o,onStepKeyDown:c,...d}=s,u=FCe(Aq,n);return e.jsx(Ka.span,{...d,ref:t,onKeyDown:xa(s.onKeyDown,h=>{h.key==="Home"?(l(h),h.preventDefault()):h.key==="End"?(o(h),h.preventDefault()):dAt.concat(uAt).includes(h.key)&&(c(h),h.preventDefault())}),onPointerDown:xa(s.onPointerDown,h=>{const m=h.target;m.setPointerCapture(h.pointerId),h.preventDefault(),u.thumbs.has(m)?m.focus():r(h)}),onPointerMove:xa(s.onPointerMove,h=>{h.target.hasPointerCapture(h.pointerId)&&a(h)}),onPointerUp:xa(s.onPointerUp,h=>{const m=h.target;m.hasPointerCapture(h.pointerId)&&(m.releasePointerCapture(h.pointerId),i(h))})})}),yAt="SliderTrack",vAt=j.forwardRef((s,t)=>{const{__scopeSlider:n,...r}=s,a=FCe(yAt,n);return e.jsx(Ka.span,{"data-disabled":a.disabled?"":void 0,"data-orientation":a.orientation,...r,ref:t})});vAt.displayName=yAt;var OFe="SliderRange",bAt=j.forwardRef((s,t)=>{const{__scopeSlider:n,...r}=s,a=FCe(OFe,n),i=xAt(OFe,n),l=j.useRef(null),o=Po(t,l),c=a.values.length,d=a.values.map(m=>jAt(m,a.min,a.max)),u=c>1?Math.min(...d):0,h=100-Math.max(...d);return e.jsx(Ka.span,{"data-orientation":a.orientation,"data-disabled":a.disabled?"":void 0,...r,ref:o,style:{...s.style,[i.startEdge]:u+"%",[i.endEdge]:h+"%"}})});bAt.displayName=OFe;var FFe="SliderThumb",_At=j.forwardRef((s,t)=>{const n=zbs(s.__scopeSlider),[r,a]=j.useState(null),i=Po(t,o=>a(o)),l=j.useMemo(()=>r?n().findIndex(o=>o.ref.current===r):-1,[n,r]);return e.jsx(Vbs,{...s,ref:i,index:l})}),Vbs=j.forwardRef((s,t)=>{const{__scopeSlider:n,index:r,name:a,...i}=s,l=FCe(FFe,n),o=xAt(FFe,n),[c,d]=j.useState(null),u=Po(t,v=>d(v)),h=c?l.form||!!c.closest("form"):!0,m=JJ(c),p=l.values[r],x=p===void 0?0:jAt(p,l.min,l.max),g=Wbs(r,l.values.length),y=m==null?void 0:m[o.size],b=y?Ybs(y,x,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(${x}% + ${b}px)`},children:[e.jsx(RFe.ItemSlot,{scope:s.__scopeSlider,children:e.jsx(Ka.span,{role:"slider","aria-label":s["aria-label"]||g,"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:xa(s.onFocus,()=>{l.valueIndexToChangeRef.current=r})})}),h&&e.jsx(wAt,{name:a??(l.name?l.name+(l.values.length>1?"[]":""):void 0),form:l.form,value:p},r)]})});_At.displayName=FFe;var Hbs="RadioBubbleInput",wAt=j.forwardRef(({__scopeSlider:s,value:t,...n},r)=>{const a=j.useRef(null),i=Po(a,r),l=mee(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(Ka.input,{style:{display:"none"},...n,ref:i,defaultValue:t})});wAt.displayName=Hbs;function Gbs(s=[],t,n){const r=[...s];return r[n]=t,r.sort((a,i)=>a-i)}function jAt(s,t,n){const i=100/(n-t)*(s-t);return BZ(i,[0,100])}function Wbs(s,t){return t>2?`Value ${s+1} of ${t}`:t===2?["Minimum","Maximum"][s]:void 0}function Kbs(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 Ybs(s,t,n){const r=s/2,i=SHe([0,50],[0,r]);return(r-i(t)*n)*n}function Zbs(s){return s.slice(0,-1).map((t,n)=>s[n+1]-t)}function Xbs(s,t){if(t>0){const n=Zbs(s);return Math.min(...n)>=t}return!0}function SHe(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 Qbs(s){return(String(s).split(".")[1]||"").length}function Jbs(s,t){const n=Math.pow(10,t);return Math.round(s*n)/n}var NAt=pAt,e_s=vAt,t_s=bAt,s_s=_At;const rx=j.forwardRef(({className:s,...t},n)=>e.jsxs(NAt,{ref:n,className:Tt("relative flex w-full touch-none select-none items-center",s),...t,children:[e.jsx(e_s,{className:"relative h-2 w-full grow overflow-hidden rounded-full bg-secondary",children:e.jsx(t_s,{className:"absolute h-full bg-primary"})}),e.jsx(s_s,{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"})]}));rx.displayName=NAt.displayName;const n_s=s=>ht({queryKey:["public-listings",s],queryFn:async()=>{let t=U.from("listings").select(` id, slug, agent_id, property_address, city, state, neighborhood, price, property_type, status, bedrooms, bathrooms, square_footage, lot_size, year_built, has_hoa, description, latitude, longitude, created_at, updated_at, photos:listing_photos(id, photo_url, is_primary), agent:profiles!listings_agent_id_fkey(id, name, email, phone, avatar_url, brokerage_name, brokerage:brokerages(name)) `).eq("is_approved",!0).eq("is_public",!0).order("created_at",{ascending:!1});if(s!=null&&s.status&&(t=t.eq("status",s.status)),s!=null&&s.propertyType&&(t=t.eq("property_type",s.propertyType)),s!=null&&s.city){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}}),r_s=()=>ht({queryKey:["public-listings-search-index"],staleTime:5*60*1e3,queryFn:async()=>{const{data:s,error:t}=await U.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)}}}),a_s=s=>ht({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=U.from("listings").select(` id, slug, agent_id, property_address, city, state, neighborhood, price, property_type, status, bedrooms, bathrooms, square_footage, lot_size, year_built, has_hoa, description, agent_notes, agent_notes_public, mls_link, video_link, video_id, latitude, longitude, 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;return r},enabled:!!s}),i_s=()=>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:b}=await U.from("listing_shares").select("id, sharing_agent_id").eq("share_token",l).eq("listing_id",s).maybeSingle();b&&(m=b.id,p=b.sharing_agent_id)}const{data:x,error:g}=await U.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(g)throw g;const{error:y}=await U.functions.invoke("process-listing-lead",{body:{leadId:x.id}});return y&&console.error("Error processing lead:",y),x}}),o_s=()=>yt({mutationFn:async s=>{const{error:t}=await U.rpc("increment_listing_share_click",{p_share_token:s});if(t)throw t}}),lit="/assets/levelup-logo-color-BeKd2k_g.png",l_s={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"},c_s={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"},cit={single_family:"Single Family",condo:"Condo",townhouse:"Townhouse",land:"Land",multi_family:"Multi-Family",luxury:"Luxury",commercial:"Commercial",other:"Other"},Nne=s=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(s),eG=s=>new Intl.NumberFormat("en-US").format(s);function kAt({slugOverride:s}={}){var Mt,Ft,Ts,js,zt;const t=Vi(),n=s||t.slugOrId,[r]=oc(),{data:a,isLoading:i}=a_s(n||""),l=i_s(),o=o_s(),c=r.get("ref"),[d,u]=j.useState(""),[h,m]=j.useState(""),[p,x]=j.useState(""),[g,y]=j.useState(""),[b,v]=j.useState(""),[N,C]=j.useState(""),[A,T]=j.useState(""),[P,M]=j.useState("in_person"),[I,D]=j.useState("info"),[B,q]=j.useState(!1),[W,V]=j.useState(!1),[K,Q]=j.useState(null),[J,ce]=j.useState(!1);j.useState(!1);const[ue,ne]=j.useState(!1),[ee,le]=j.useState(20),[he,ve]=j.useState(6.5),[ge,fe]=j.useState(30),je=j.useRef(null),[Ee,Me]=j.useState(!1);j.useEffect(()=>{const Nt=()=>Me(window.scrollY>300);return window.addEventListener("scroll",Nt,{passive:!0}),()=>window.removeEventListener("scroll",Nt)},[]),j.useEffect(()=>{c&&o.mutate(c)},[c]),j.useEffect(()=>{window.scrollTo({top:0,left:0,behavior:"auto"})},[n]);const De=(a==null?void 0:a.photos)||[],ze=De.find(Nt=>Nt.is_primary)||De[0],ke=j.useMemo(()=>{if(!(a!=null&&a.price))return 0;const Nt=a.price*(1-ee/100),Ds=he/100/12,_t=ge*12;return Ds===0?Nt/_t:Nt*Ds/(1-Math.pow(1+Ds,-_t))},[a==null?void 0:a.price,ee,he,ge]),Xe=async()=>{const Nt=window.location.href;if(navigator.share)try{await navigator.share({title:document.title,url:Nt})}catch{}else await navigator.clipboard.writeText(Nt),ae.success("Link copied to clipboard")},Se=async Nt=>{if(Nt.preventDefault(),!d.trim()||!p.trim()||!a)return;const Ds=I==="showing";if(Ds&&!N){ae.error("Please pick a preferred date for your showing");return}q(!0);try{await l.mutateAsync({listingId:a.id,agentId:a.agent_id,firstName:d.trim(),lastName:h.trim(),email:p.trim(),phone:g.trim(),shareToken:c,leadType:Ds?"showing_request":"info_request",preferredDate:Ds?N:null,preferredTime:Ds&&A||null,showingMode:Ds?P:null,message:b.trim()||null}),V(!0),ae.success(Ds?"Showing request sent! The agent will confirm details shortly.":"Thanks! The agent will be in touch soon.")}catch(_t){console.error("Lead submission error:",_t),ae.error(`Failed to submit: ${_t.message||"Please try again"}`)}finally{q(!1)}},Re=()=>{K!==null&&Q(K===0?De.length-1:K-1)},Ae=()=>{K!==null&&Q(K===De.length-1?0:K+1)};if(i)return e.jsx("div",{className:"min-h-screen bg-neutral-950",children:e.jsx(on,{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(Wn,{to:"/public/listings",className:"flex items-center gap-2",children:e.jsx("img",{src:lit,alt:"LevelUp",className:"h-8"})})})}),e.jsxs("div",{className:"container mx-auto px-4 py-24 text-center",children:[e.jsx(sa,{className:"h-16 w-16 mx-auto text-muted-foreground mb-4"}),e.jsx("h1",{className:"text-2xl font-bold mb-2",children:"Listing Not Found"}),e.jsx("p",{className:"text-muted-foreground mb-6",children:"This listing may no longer be available."}),e.jsx($,{asChild:!0,children:e.jsx(Wn,{to:typeof window<"u"&&window.location.host==="listings.relevelup.com"?"/":"/public/listings",children:"Browse All Listings"})})]})]});const Be=a.property_address?`${a.property_address} — ${a.city}, ${a.state}`:`${a.city}, ${a.state} Home for Sale`,qe=((Ft=(Mt=a.agent)==null?void 0:Mt.brokerage)==null?void 0:Ft.name)||((Ts=a.agent)==null?void 0:Ts.brokerage_name),Ke=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,et=ue||!Ue?Ze:Ze.slice(0,420).trimEnd()+"…",Qe=a.page_config||{},Ge=Nt=>{var Ds;return(((Ds=Qe.sections)==null?void 0:Ds[Nt])??!0)!==!1},nt=Array.isArray(Qe.addons)?Qe.addons:[],ft=Qe.custom_note||"",lt=Qe.accent_color||null;return e.jsxs(e.Fragment,{children:[e.jsxs(Ul,{children:[e.jsxs("title",{children:[Be," | LevelUp Listings"]}),e.jsx("meta",{name:"description",content:`${Nne(a.price)} · ${a.bedrooms||""}BD ${a.bathrooms||""}BA ${a.square_footage?a.square_footage.toLocaleString()+" sqft · ":""}${cit[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:Be}),e.jsx("meta",{property:"og:description",content:`${Nne(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}`}),ze&&e.jsx("meta",{property:"og:image",content:ze.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:Be}),e.jsx("meta",{name:"twitter:description",content:`${Nne(a.price)} · ${a.city}, ${a.state}`}),ze&&e.jsx("meta",{name:"twitter:image",content:ze.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:De.map(Nt=>Nt.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 ${Ee?"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(Wn,{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(ka,{className:"h-4 w-4"}),e.jsx("span",{className:"text-sm font-medium hidden sm:inline",children:"All Listings"})]}),Ee&&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(([Nt,Ds])=>e.jsx("a",{href:`#${Nt}`,className:"px-3 py-1.5 rounded-full text-white/70 hover:text-white hover:bg-white/10 transition",children:Ds},Nt))}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Obs,{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:Xe,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(vd,{className:"h-4 w-4 text-white"})}),e.jsx($,{size:"sm",onClick:()=>ce(!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:je,id:"overview",className:"relative h-[100svh] min-h-[620px] w-full overflow-hidden",children:[ze?e.jsx("img",{src:ze.photo_url,alt:a.property_address||`${a.city}, ${a.state}`,className:"absolute inset-0 h-full w-full object-cover kb-zoom"}):e.jsx("div",{className:"absolute inset-0 bg-gradient-to-br from-neutral-800 to-neutral-950"}),e.jsx("div",{className:"absolute inset-0 bg-gradient-to-t from-black via-black/50 to-black/20"}),e.jsx("div",{className:"absolute inset-0 bg-gradient-to-r from-black/40 via-transparent to-transparent"}),e.jsxs("div",{className:"absolute top-24 right-4 sm:right-8 z-10 flex flex-col items-end gap-2",children:[e.jsx($e,{className:`${l_s[a.status]} text-white border-0 uppercase tracking-widest text-[10px] px-3 py-1 rounded-full shadow-lg`,children:c_s[a.status]}),De.length>0&&e.jsxs("button",{onClick:()=>Q(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(y0,{className:"h-3.5 w-3.5"}),De.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:Nne(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:eG(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(Lo,{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}),qe&&e.jsx("p",{className:"text-xs text-white/60",children:qe})]}),e.jsx($,{size:"sm",onClick:()=>ce(!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"]})]})})]}),Ge("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:tw,label:"Bedrooms",value:a.bedrooms},a.bathrooms&&{icon:_g,label:"Bathrooms",value:a.bathrooms},a.square_footage&&{icon:Lb,label:"Interior",value:`${eG(a.square_footage)} sqft`},a.lot_size&&{icon:o5,label:"Lot Size",value:a.lot_size},a.year_built&&{icon:ia,label:"Year Built",value:a.year_built},!a.year_built&&a.square_footage&&{icon:s5,label:"Price / sqft",value:`$${eG(Math.round(a.price/a.square_footage))}`}].filter(Boolean).slice(0,5).map((Nt,Ds)=>e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:"h-10 w-10 rounded-full bg-white/5 border border-white/10 flex items-center justify-center shrink-0",children:e.jsx(Nt.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:Nt.label}),e.jsx("p",{className:"font-display text-2xl text-white font-light",children:Nt.value})]})]},Ds))})}),e.jsxs("div",{className:"max-w-7xl mx-auto px-4 sm:px-8 py-16 grid lg:grid-cols-3 gap-12",children:[e.jsxs("div",{className:"lg:col-span-2 space-y-20",children:[Ge("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:et})}),Ue&&e.jsx("button",{onClick:()=>ne(!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($e,{variant:"outline",className:"border-white/20 text-white/80 bg-white/5",children:[e.jsx(Ai,{className:"h-3 w-3 mr-1.5"}),cit[a.property_type]]}),a.has_hoa&&e.jsx($e,{variant:"outline",className:"border-white/20 text-white/80 bg-white/5",children:"HOA"}),a.mls_link&&e.jsx($,{variant:"outline",size:"sm",asChild:!0,className:"ml-2 border-white/20 bg-white/5 text-white hover:bg-white/15",children:e.jsxs("a",{href:a.mls_link,target:"_blank",rel:"noopener noreferrer",children:[e.jsx(Tr,{className:"h-3.5 w-3.5 mr-1.5"})," MLS"]})})]}),(ft||a.agent_notes&&a.agent_notes_public)&&e.jsxs("div",{className:"mt-10 rounded-2xl border border-white/10 bg-white/5 p-6",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[e.jsx(dn,{className:"h-4 w-4 text-amber-300"}),e.jsx("p",{className:"text-[11px] uppercase tracking-[0.25em] text-white/60",children:"A note from the agent"})]}),e.jsxs("p",{className:"text-white/80 whitespace-pre-wrap leading-relaxed italic font-display",children:['"',ft||a.agent_notes,'"']})]})]}),Ge("gallery")&&De.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:()=>Q(0),className:"text-sm text-white/60 hover:text-white underline underline-offset-4 hidden sm:inline",children:["View all ",De.length]})]}),e.jsx("div",{className:"grid grid-cols-4 gap-2 sm:gap-3",children:De.slice(0,7).map((Nt,Ds)=>{const _t=["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"],Xs=Ds===6&&De.length>7;return e.jsxs("button",{onClick:()=>Q(Ds),className:`${_t[Ds]} relative rounded-xl overflow-hidden group bg-neutral-900`,children:[e.jsx("img",{src:Nt.photo_url,alt:`Photo ${Ds+1}`,className:"absolute inset-0 h-full w-full object-cover group-hover:scale-[1.04] transition-transform duration-500"}),Xs&&e.jsxs("div",{className:"absolute inset-0 bg-black/60 flex flex-col items-center justify-center text-white",children:[e.jsx(y0,{className:"h-6 w-6 mb-1"}),e.jsxs("span",{className:"font-medium",children:["+",De.length-7," more"]})]})]},Nt.id)})})]}),Ge("video")&&((js=a.video)==null?void 0:js.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"})})]}),Ge("map")&&Ke&&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:Ke,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(ai,{className:"h-4 w-4"}),a.property_address?`${a.property_address}, `:"",a.city,", ",a.state]})]}),Ge("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:["$",eG(Math.round(ke))]}),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(se,{className:"text-white/70 text-xs uppercase tracking-widest",children:"Down Payment"}),e.jsxs("span",{className:"text-white font-medium",children:[ee,"%"]})]}),e.jsx(rx,{value:[ee],onValueChange:Nt=>le(Nt[0]),min:0,max:50,step:1}),e.jsxs("p",{className:"text-xs text-white/50 mt-2",children:["$",eG(Math.round(a.price*ee/100))," down"]})]}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx(se,{className:"text-white/70 text-xs uppercase tracking-widest",children:"Interest Rate"}),e.jsxs("span",{className:"text-white font-medium",children:[he.toFixed(2),"%"]})]}),e.jsx(rx,{value:[he],onValueChange:Nt=>ve(Nt[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(se,{className:"text-white/70 text-xs uppercase tracking-widest",children:"Loan Term"}),e.jsxs("span",{className:"text-white font-medium",children:[ge," yr"]})]}),e.jsx(rx,{value:[ge],onValueChange:Nt=>fe(Nt[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."})]})]}),nt.map(Nt=>{const Ds=Nt.type,_t=Nt.data||{};if(Ds==="extra_video"&&_t.url){const Xs=String(_t.url).includes("youtu")?`https://www.youtube.com/embed/${String(_t.url).split(/[/=]/).pop()}`:_t.url;return e.jsxs("section",{children:[e.jsx("p",{className:"text-[11px] uppercase tracking-[0.3em] text-white/40 mb-2",children:_t.eyebrow||"Featured Video"}),e.jsx("h2",{className:"font-display text-3xl sm:text-4xl font-light text-white mb-6",children:_t.title||"Watch"}),e.jsx("div",{className:"relative rounded-2xl overflow-hidden bg-black shadow-2xl aspect-video",children:e.jsx("iframe",{src:Xs,className:"absolute inset-0 h-full w-full",allowFullScreen:!0,title:_t.title||"Video"})})]},Nt.id)}return Ds==="3d_tour"&&_t.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:_t.title||"Step inside"}),e.jsx("div",{className:"relative rounded-2xl overflow-hidden bg-black shadow-2xl aspect-video",children:e.jsx("iframe",{src:_t.url,className:"absolute inset-0 h-full w-full",allowFullScreen:!0,title:"3D Tour"})})]},Nt.id):Ds==="floor_plan"&&_t.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:_t.title||"Layout"}),e.jsx("img",{src:_t.image_url,alt:"Floor plan",className:"w-full rounded-2xl border border-white/10"})]},Nt.id):Ds==="testimonial"&&_t.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:['"',_t.quote,'"']}),_t.author&&e.jsxs("p",{className:"mt-4 text-sm text-white/60",children:["— ",_t.author]})]},Nt.id):Ds==="custom_cta"&&_t.label?e.jsxs("section",{className:"rounded-2xl p-8 text-center",style:{background:lt?`${lt}22`:"rgba(255,255,255,0.05)",border:`1px solid ${lt||"rgba(255,255,255,0.1)"}`},children:[_t.title&&e.jsx("h3",{className:"font-display text-3xl text-white mb-4",children:_t.title}),e.jsx($,{asChild:!0,size:"lg",style:lt?{background:lt}:void 0,children:e.jsx("a",{href:_t.url||"#agent",children:_t.label})})]},Nt.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(Lo,{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}),qe&&e.jsx("p",{className:"text-sm text-white/60 mt-0.5",children:qe})]})]}),e.jsxs("div",{className:"mt-4 grid grid-cols-2 gap-2",children:[a.agent.phone&&e.jsx($,{asChild:!0,variant:"outline",size:"sm",className:"border-white/20 bg-white/5 text-white hover:bg-white/15",children:e.jsxs("a",{href:`tel:${a.agent.phone}`,children:[e.jsx(ya,{className:"h-3.5 w-3.5 mr-1.5"}),"Call"]})}),a.agent.email&&e.jsx($,{asChild:!0,variant:"outline",size:"sm",className:"border-white/20 bg-white/5 text-white hover:bg-white/15",children:e.jsxs("a",{href:`mailto:${a.agent.email}`,children:[e.jsx(nn,{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(Lo,{className:"h-7 w-7 text-white/70"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-[10px] uppercase tracking-widest text-white/50",children:"Co-Listing Agent"}),e.jsx("p",{className:"font-display text-xl text-white font-medium leading-tight",children:a.co_agent_name}),a.co_agent_brokerage&&e.jsx("p",{className:"text-sm text-white/60 mt-0.5",children:a.co_agent_brokerage})]})]}),(a.co_agent_phone||a.co_agent_email)&&e.jsxs("div",{className:"mt-4 grid grid-cols-2 gap-2",children:[a.co_agent_phone&&e.jsx($,{asChild:!0,variant:"outline",size:"sm",className:"border-white/20 bg-white/5 text-white hover:bg-white/15",children:e.jsxs("a",{href:`tel:${a.co_agent_phone}`,children:[e.jsx(ya,{className:"h-3.5 w-3.5 mr-1.5"}),"Call"]})}),a.co_agent_email&&e.jsx($,{asChild:!0,variant:"outline",size:"sm",className:"border-white/20 bg-white/5 text-white hover:bg-white/15",children:e.jsxs("a",{href:`mailto:${a.co_agent_email}`,children:[e.jsx(nn,{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(dit,{submitted:W,activeTab:I,setActiveTab:D,firstName:d,setFirstName:u,lastName:h,setLastName:m,email:p,setEmail:x,phone:g,setPhone:y,message:b,setMessage:v,preferredDate:N,setPreferredDate:C,preferredTime:A,setPreferredTime:T,showingMode:P,setShowingMode:M,isSubmitting:B,onSubmit:Se})})]})]}),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($,{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(ya,{className:"h-4 w-4 mr-1.5"}),"Call"]})}),e.jsxs($,{onClick:()=>ce(!0),className:"bg-white text-neutral-900 hover:bg-white/90 flex-[2] font-medium",children:[e.jsx(Xu,{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:lit,alt:"LevelUp",className:"h-6 opacity-80"}),e.jsxs("span",{children:["© ",new Date().getFullYear()," LevelUp"]})]}),e.jsx("a",{href:"https://relevelup.com",target:"_blank",rel:"noopener noreferrer",className:"hover:text-white",children:"relevelup.com"})]})}),e.jsx(Os,{open:K!==null,onOpenChange:()=>Q(null),children:e.jsxs(Rs,{className:"max-w-6xl p-0 bg-black/95 border-0",children:[e.jsx(Us,{className:"sr-only",children:e.jsx(zs,{children:"Photo Gallery"})}),e.jsx("button",{onClick:()=>Q(null),className:"absolute right-4 top-4 z-50 rounded-full bg-white/10 hover:bg-white/20 p-2 text-white",children:e.jsx(pr,{className:"h-5 w-5"})}),K!==null&&De[K]&&e.jsxs("div",{className:"relative",children:[e.jsx("img",{src:De[K].photo_url,alt:`Photo ${K+1}`,className:"w-full max-h-[85vh] object-contain"}),De.length>1&&e.jsxs(e.Fragment,{children:[e.jsx("button",{onClick:Re,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(Ic,{className:"h-6 w-6"})}),e.jsx("button",{onClick:Ae,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(Ja,{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," / ",De.length]})]})]})]})}),e.jsx(Os,{open:J,onOpenChange:ce,children:e.jsxs(Rs,{className:"max-w-md p-0 bg-white text-neutral-900",children:[e.jsx(Us,{className:"sr-only",children:e.jsx(zs,{children:"Contact the agent"})}),e.jsx("div",{className:"p-6",children:e.jsx(dit,{submitted:W,activeTab:I,setActiveTab:D,firstName:d,setFirstName:u,lastName:h,setLastName:m,email:p,setEmail:x,phone:g,setPhone:y,message:b,setMessage:v,preferredDate:N,setPreferredDate:C,preferredTime:A,setPreferredTime:T,showingMode:P,setShowingMode:M,isSubmitting:B,onSubmit:Se})})]})})]})]})}function dit(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:x,setPreferredDate:g,preferredTime:y,setPreferredTime:b,showingMode:v,setShowingMode:N,isSubmitting:C,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(oa,{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(ua,{value:n,onValueChange:T=>r(T),children:[e.jsxs(ha,{className:"grid w-full grid-cols-2 mb-4",children:[e.jsxs(Qt,{value:"info",className:"gap-1.5",children:[e.jsx(Ji,{className:"h-3.5 w-3.5"})," Get Info"]}),e.jsxs(Qt,{value:"showing",className:"gap-1.5",children:[e.jsx(Xu,{className:"h-3.5 w-3.5"})," Request Tour"]})]}),e.jsxs("form",{onSubmit:A,className:"space-y-3",children:[e.jsxs(Jt,{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(se,{htmlFor:"preferredDate",children:"Preferred Date *"}),e.jsx(be,{id:"preferredDate",type:"date",value:x,onChange:T=>g(T.target.value),min:new Date().toISOString().split("T")[0],required:n==="showing"})]}),e.jsxs("div",{children:[e.jsx(se,{htmlFor:"preferredTime",children:"Preferred Time"}),e.jsxs(vs,{value:y,onValueChange:b,children:[e.jsx(gs,{id:"preferredTime",children:e.jsx(bs,{placeholder:"Any time"})}),e.jsxs(ys,{children:[e.jsx(Ye,{value:"morning",children:"Morning (9am–12pm)"}),e.jsx(Ye,{value:"afternoon",children:"Afternoon (12pm–5pm)"}),e.jsx(Ye,{value:"evening",children:"Evening (5pm–8pm)"})]})]})]})]}),e.jsxs("div",{children:[e.jsx(se,{htmlFor:"showingMode",children:"Tour Type"}),e.jsxs(vs,{value:v,onValueChange:T=>N(T),children:[e.jsx(gs,{id:"showingMode",children:e.jsx(bs,{})}),e.jsxs(ys,{children:[e.jsx(Ye,{value:"in_person",children:"🏡 In-person showing"}),e.jsx(Ye,{value:"video",children:"📱 Video tour (FaceTime/Zoom)"}),e.jsx(Ye,{value:"either",children:"Either works for me"})]})]})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(se,{htmlFor:"firstName",children:"First Name *"}),e.jsx(be,{id:"firstName",value:a,onChange:T=>i(T.target.value),required:!0})]}),e.jsxs("div",{children:[e.jsx(se,{htmlFor:"lastName",children:"Last Name"}),e.jsx(be,{id:"lastName",value:l,onChange:T=>o(T.target.value)})]})]}),e.jsxs("div",{children:[e.jsx(se,{htmlFor:"email",children:"Email *"}),e.jsx(be,{id:"email",type:"email",value:c,onChange:T=>d(T.target.value),required:!0})]}),e.jsxs("div",{children:[e.jsxs(se,{htmlFor:"phone",children:["Phone ",n==="showing"&&"*"]}),e.jsx(be,{id:"phone",type:"tel",value:u,onChange:T=>h(T.target.value),required:n==="showing"})]}),e.jsxs("div",{children:[e.jsx(se,{htmlFor:"message",children:n==="showing"?"Anything else?":"Message (optional)"}),e.jsx(Is,{id:"message",value:m,onChange:T=>p(T.target.value),rows:2})]}),e.jsx($,{type:"submit",disabled:C,className:"w-full bg-neutral-900 hover:bg-neutral-800 text-white h-11",children:C?"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 Hke="/assets/levelup-logo-white-C2RAgAoG.png",d_s="/assets/listings-hero-noir-BHCJrhvU.jpg";var SAt={exports:{}};(function(s,t){(function(n,r){s.exports=r()})(Sm,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,f){var _=f[0],S=f[1],L=f[2],O=f[3],z=_*O-L*S;return z?(k[0]=O*(z=1/z),k[1]=-S*z,k[2]=-L*z,k[3]=_*z,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,f){var _=f[0],S=f[1],L=f[2],O=f[3],z=f[4],G=f[5],Y=f[6],re=f[7],me=f[8];return k[0]=z*me-G*re,k[1]=L*re-S*me,k[2]=S*G-L*z,k[3]=G*Y-O*me,k[4]=_*me-L*Y,k[5]=L*O-_*G,k[6]=O*re-z*Y,k[7]=S*Y-_*re,k[8]=_*z-S*O,k}function p(k,f,_){var S=f[0],L=f[1],O=f[2],z=f[3],G=f[4],Y=f[5],re=f[6],me=f[7],ye=f[8],we=_[0],Te=_[1],Ie=_[2],Ve=_[3],Je=_[4],rt=_[5],xt=_[6],ut=_[7],St=_[8];return k[0]=we*S+Te*z+Ie*re,k[1]=we*L+Te*G+Ie*me,k[2]=we*O+Te*Y+Ie*ye,k[3]=Ve*S+Je*z+rt*re,k[4]=Ve*L+Je*G+rt*me,k[5]=Ve*O+Je*Y+rt*ye,k[6]=xt*S+ut*z+St*re,k[7]=xt*L+ut*G+St*me,k[8]=xt*O+ut*Y+St*ye,k}function x(){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 g(k){var f=new d(16);return f[0]=k[0],f[1]=k[1],f[2]=k[2],f[3]=k[3],f[4]=k[4],f[5]=k[5],f[6]=k[6],f[7]=k[7],f[8]=k[8],f[9]=k[9],f[10]=k[10],f[11]=k[11],f[12]=k[12],f[13]=k[13],f[14]=k[14],f[15]=k[15],f}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 b(k,f){var _=f[0],S=f[1],L=f[2],O=f[3],z=f[4],G=f[5],Y=f[6],re=f[7],me=f[8],ye=f[9],we=f[10],Te=f[11],Ie=f[12],Ve=f[13],Je=f[14],rt=f[15],xt=_*G-S*z,ut=_*Y-L*z,St=_*re-O*z,Pt=S*Y-L*G,Rt=S*re-O*G,ws=L*re-O*Y,ns=me*Ve-ye*Ie,xs=me*Je-we*Ie,us=me*rt-Te*Ie,hs=ye*Je-we*Ve,pn=ye*rt-Te*Ve,bn=we*rt-Te*Je,An=xt*bn-ut*pn+St*hs+Pt*us-Rt*xs+ws*ns;return An?(k[0]=(G*bn-Y*pn+re*hs)*(An=1/An),k[1]=(L*pn-S*bn-O*hs)*An,k[2]=(Ve*ws-Je*Rt+rt*Pt)*An,k[3]=(we*Rt-ye*ws-Te*Pt)*An,k[4]=(Y*us-z*bn-re*xs)*An,k[5]=(_*bn-L*us+O*xs)*An,k[6]=(Je*St-Ie*ws-rt*ut)*An,k[7]=(me*ws-we*St+Te*ut)*An,k[8]=(z*pn-G*us+re*ns)*An,k[9]=(S*us-_*pn-O*ns)*An,k[10]=(Ie*Rt-Ve*St+rt*xt)*An,k[11]=(ye*St-me*Rt-Te*xt)*An,k[12]=(G*xs-z*hs-Y*ns)*An,k[13]=(_*hs-S*xs+L*ns)*An,k[14]=(Ve*ut-Ie*Pt-Je*xt)*An,k[15]=(me*Pt-ye*ut+we*xt)*An,k):null}function v(k,f,_){var S=f[0],L=f[1],O=f[2],z=f[3],G=f[4],Y=f[5],re=f[6],me=f[7],ye=f[8],we=f[9],Te=f[10],Ie=f[11],Ve=f[12],Je=f[13],rt=f[14],xt=f[15],ut=_[0],St=_[1],Pt=_[2],Rt=_[3];return k[0]=ut*S+St*G+Pt*ye+Rt*Ve,k[1]=ut*L+St*Y+Pt*we+Rt*Je,k[2]=ut*O+St*re+Pt*Te+Rt*rt,k[3]=ut*z+St*me+Pt*Ie+Rt*xt,k[4]=(ut=_[4])*S+(St=_[5])*G+(Pt=_[6])*ye+(Rt=_[7])*Ve,k[5]=ut*L+St*Y+Pt*we+Rt*Je,k[6]=ut*O+St*re+Pt*Te+Rt*rt,k[7]=ut*z+St*me+Pt*Ie+Rt*xt,k[8]=(ut=_[8])*S+(St=_[9])*G+(Pt=_[10])*ye+(Rt=_[11])*Ve,k[9]=ut*L+St*Y+Pt*we+Rt*Je,k[10]=ut*O+St*re+Pt*Te+Rt*rt,k[11]=ut*z+St*me+Pt*Ie+Rt*xt,k[12]=(ut=_[12])*S+(St=_[13])*G+(Pt=_[14])*ye+(Rt=_[15])*Ve,k[13]=ut*L+St*Y+Pt*we+Rt*Je,k[14]=ut*O+St*re+Pt*Te+Rt*rt,k[15]=ut*z+St*me+Pt*Ie+Rt*xt,k}function N(k,f,_){var S,L,O,z,G,Y,re,me,ye,we,Te,Ie,Ve=_[0],Je=_[1],rt=_[2];return f===k?(k[12]=f[0]*Ve+f[4]*Je+f[8]*rt+f[12],k[13]=f[1]*Ve+f[5]*Je+f[9]*rt+f[13],k[14]=f[2]*Ve+f[6]*Je+f[10]*rt+f[14],k[15]=f[3]*Ve+f[7]*Je+f[11]*rt+f[15]):(L=f[1],O=f[2],z=f[3],G=f[4],Y=f[5],re=f[6],me=f[7],ye=f[8],we=f[9],Te=f[10],Ie=f[11],k[0]=S=f[0],k[1]=L,k[2]=O,k[3]=z,k[4]=G,k[5]=Y,k[6]=re,k[7]=me,k[8]=ye,k[9]=we,k[10]=Te,k[11]=Ie,k[12]=S*Ve+G*Je+ye*rt+f[12],k[13]=L*Ve+Y*Je+we*rt+f[13],k[14]=O*Ve+re*Je+Te*rt+f[14],k[15]=z*Ve+me*Je+Ie*rt+f[15]),k}function C(k,f,_){var S=_[0],L=_[1],O=_[2];return k[0]=f[0]*S,k[1]=f[1]*S,k[2]=f[2]*S,k[3]=f[3]*S,k[4]=f[4]*L,k[5]=f[5]*L,k[6]=f[6]*L,k[7]=f[7]*L,k[8]=f[8]*O,k[9]=f[9]*O,k[10]=f[10]*O,k[11]=f[11]*O,k[12]=f[12],k[13]=f[13],k[14]=f[14],k[15]=f[15],k}function A(k,f,_){var S=Math.sin(_),L=Math.cos(_),O=f[4],z=f[5],G=f[6],Y=f[7],re=f[8],me=f[9],ye=f[10],we=f[11];return f!==k&&(k[0]=f[0],k[1]=f[1],k[2]=f[2],k[3]=f[3],k[12]=f[12],k[13]=f[13],k[14]=f[14],k[15]=f[15]),k[4]=O*L+re*S,k[5]=z*L+me*S,k[6]=G*L+ye*S,k[7]=Y*L+we*S,k[8]=re*L-O*S,k[9]=me*L-z*S,k[10]=ye*L-G*S,k[11]=we*L-Y*S,k}function T(k,f,_){var S=Math.sin(_),L=Math.cos(_),O=f[0],z=f[1],G=f[2],Y=f[3],re=f[8],me=f[9],ye=f[10],we=f[11];return f!==k&&(k[4]=f[4],k[5]=f[5],k[6]=f[6],k[7]=f[7],k[12]=f[12],k[13]=f[13],k[14]=f[14],k[15]=f[15]),k[0]=O*L-re*S,k[1]=z*L-me*S,k[2]=G*L-ye*S,k[3]=Y*L-we*S,k[8]=O*S+re*L,k[9]=z*S+me*L,k[10]=G*S+ye*L,k[11]=Y*S+we*L,k}function P(k,f,_){var S=Math.sin(_),L=Math.cos(_),O=f[0],z=f[1],G=f[2],Y=f[3],re=f[4],me=f[5],ye=f[6],we=f[7];return f!==k&&(k[8]=f[8],k[9]=f[9],k[10]=f[10],k[11]=f[11],k[12]=f[12],k[13]=f[13],k[14]=f[14],k[15]=f[15]),k[0]=O*L+re*S,k[1]=z*L+me*S,k[2]=G*L+ye*S,k[3]=Y*L+we*S,k[4]=re*L-O*S,k[5]=me*L-z*S,k[6]=ye*L-G*S,k[7]=we*L-Y*S,k}function M(k,f){return k[0]=f[0],k[1]=0,k[2]=0,k[3]=0,k[4]=0,k[5]=f[1],k[6]=0,k[7]=0,k[8]=0,k[9]=0,k[10]=f[2],k[11]=0,k[12]=0,k[13]=0,k[14]=0,k[15]=1,k}function I(k,f,_){var S,L,O,z=_[0],G=_[1],Y=_[2],re=Math.sqrt(z*z+G*G+Y*Y);return re0&&(O=1/Math.sqrt(O)),k[0]=f[0]*O,k[1]=f[1]*O,k[2]=f[2]*O,k}function De(k,f){return k[0]*f[0]+k[1]*f[1]+k[2]*f[2]}function ze(k,f,_){var S=f[0],L=f[1],O=f[2],z=_[0],G=_[1],Y=_[2];return k[0]=L*Y-O*G,k[1]=O*z-S*Y,k[2]=S*G-L*z,k}function ke(k,f,_,S){var L=f[0],O=f[1],z=f[2];return k[0]=L+S*(_[0]-L),k[1]=O+S*(_[1]-O),k[2]=z+S*(_[2]-z),k}function Xe(k,f,_){var S=f[0],L=f[1],O=f[2],z=_[3]*S+_[7]*L+_[11]*O+_[15];return k[0]=(_[0]*S+_[4]*L+_[8]*O+_[12])/(z=z||1),k[1]=(_[1]*S+_[5]*L+_[9]*O+_[13])/z,k[2]=(_[2]*S+_[6]*L+_[10]*O+_[14])/z,k}function Se(k,f,_){var S=f[0],L=f[1],O=f[2];return k[0]=S*_[0]+L*_[3]+O*_[6],k[1]=S*_[1]+L*_[4]+O*_[7],k[2]=S*_[2]+L*_[5]+O*_[8],k}function Re(k,f,_){var S=_[0],L=_[1],O=_[2],z=_[3],G=f[0],Y=f[1],re=f[2],me=L*re-O*Y,ye=O*G-S*re,we=S*Y-L*G;return k[0]=G+z*(me+=me)+L*(we+=we)-O*(ye+=ye),k[1]=Y+z*ye+O*me-S*we,k[2]=re+z*we+S*ye-L*me,k}function Ae(k){return k[0]=0,k[1]=0,k[2]=0,k}function Be(k,f){return k[0]===f[0]&&k[1]===f[1]&&k[2]===f[2]}var qe=ue,Ke=ne,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 et(k,f,_){return k[0]=f[0]*_,k[1]=f[1]*_,k[2]=f[2]*_,k[3]=f[3]*_,k}function Qe(k,f){var _=f[0],S=f[1],L=f[2],O=f[3],z=_*_+S*S+L*L+O*O;return z>0&&(z=1/Math.sqrt(z)),k[0]=_*z,k[1]=S*z,k[2]=L*z,k[3]=O*z,k}function Ge(k,f){return k[0]*f[0]+k[1]*f[1]+k[2]*f[2]+k[3]*f[3]}function nt(k,f,_){var S=f[0],L=f[1],O=f[2],z=f[3];return k[0]=_[0]*S+_[4]*L+_[8]*O+_[12]*z,k[1]=_[1]*S+_[5]*L+_[9]*O+_[13]*z,k[2]=_[2]*S+_[6]*L+_[10]*O+_[14]*z,k[3]=_[3]*S+_[7]*L+_[11]*O+_[15]*z,k}function ft(){var k=new d(4);return d!=Float32Array&&(k[0]=0,k[1]=0,k[2]=0),k[3]=1,k}function lt(k){return k[0]=0,k[1]=0,k[2]=0,k[3]=1,k}function Mt(k,f,_){_*=.5;var S=f[0],L=f[1],O=f[2],z=f[3],G=Math.sin(_),Y=Math.cos(_);return k[0]=S*Y+z*G,k[1]=L*Y+O*G,k[2]=O*Y-L*G,k[3]=z*Y-S*G,k}function Ft(k,f,_){_*=.5;var S=f[0],L=f[1],O=f[2],z=f[3],G=Math.sin(_),Y=Math.cos(_);return k[0]=S*Y-O*G,k[1]=L*Y+z*G,k[2]=O*Y+S*G,k[3]=z*Y-L*G,k}W(),Ue();var Ts,js,zt,Nt=Qe,Ds=(Ts=W(),js=Q(1,0,0),zt=Q(0,1,0),function(k,f,_){var S=De(f,_);return S<-.999999?(ze(Ts,js,f),Ze(Ts)<1e-6&&ze(Ts,zt,f),Me(Ts,Ts),function(L,O,z){z*=.5;var G=Math.sin(z);L[0]=G*O[0],L[1]=G*O[1],L[2]=G*O[2],L[3]=Math.cos(z)}(k,Ts,Math.PI),k):S>.999999?(k[0]=0,k[1]=0,k[2]=0,k[3]=1,k):(ze(Ts,f,_),k[0]=Ts[0],k[1]=Ts[1],k[2]=Ts[2],k[3]=1+S,Nt(k,k))});function _t(){var k=new d(2);return d!=Float32Array&&(k[0]=0,k[1]=0),k}function Xs(k,f){var _=new d(2);return _[0]=k,_[1]=f,_}function rn(k,f,_){return k[0]=f,k[1]=_,k}function Ps(k,f,_){return k[0]=f[0]+_[0],k[1]=f[1]+_[1],k}function _n(k,f,_){return k[0]=f[0]-_[0],k[1]=f[1]-_[1],k}function Zs(k,f,_){return k[0]=f[0]*_,k[1]=f[1]*_,k}function gr(k){var f=k[0],_=k[1];return Math.sqrt(f*f+_*_)}function Un(k,f){var _=f[0],S=f[1],L=_*_+S*S;return L>0&&(L=1/Math.sqrt(L)),k[0]=f[0]*L,k[1]=f[1]*L,k}function In(k,f){return k[0]*f[0]+k[1]*f[1]}ft(),ft(),h();var Ar,or,qs=_n;function yr(k){return k&&k.__esModule&&Object.prototype.hasOwnProperty.call(k,"default")?k.default:k}_t();var fn=function(){if(or)return Ar;function k(f,_,S,L){this.cx=3*f,this.bx=3*(S-f)-this.cx,this.ax=1-this.cx-this.bx,this.cy=3*_,this.by=3*(L-_)-this.cy,this.ay=1-this.cy-this.by,this.p1x=f,this.p1y=_,this.p2x=S,this.p2y=L}return or=1,Ar=k,k.prototype={sampleCurveX:function(f){return((this.ax*f+this.bx)*f+this.cx)*f},sampleCurveY:function(f){return((this.ay*f+this.by)*f+this.cy)*f},sampleCurveDerivativeX:function(f){return(3*this.ax*f+2*this.bx)*f+this.cx},solveCurveX:function(f,_){if(_===void 0&&(_=1e-6),f<0)return 0;if(f>1)return 1;for(var S=f,L=0;L<8;L++){var O=this.sampleCurveX(S)-f;if(Math.abs(O)<_)return S;var z=this.sampleCurveDerivativeX(S);if(Math.abs(z)<1e-6)break;S-=O/z}var G=0,Y=1;for(S=f,L=0;L<20&&(O=this.sampleCurveX(S),!(Math.abs(O-f)<_));L++)f>O?G=S:Y=S,S=.5*(Y-G)+G;return S},solve:function(f,_){return this.sampleCurveY(this.solveCurveX(f,_))}},Ar}(),Zn=yr(fn);function Xt(k,f){this.x=k,this.y=f}function rr(k,f){if(Array.isArray(k)){if(!Array.isArray(f)||k.length!==f.length)return!1;for(let _=0;_=1)return 1;const f=k*k,_=f*k;return 4*(k<.5?_:3*(k-f)+_-.75)}function ms(k,f,_,S){const L=new Zn(k,f,_,S);return function(O){return L.solve(O)}}const ot=ms(.25,.1,.25,1);function pt(k,f,_){return Math.min(_,Math.max(f,k))}function vt(k,f,_){return(_=pt((_-k)/(f-k),0,1))*_*(3-2*_)}function At(k,f,_){const S=_-f,L=((k-f)%S+S)%S+f;return L===f?_:L}function Zt(k,f,_){if(!k.length)return _(null,[]);let S=k.length;const L=new Array(k.length);let O=null;k.forEach((z,G)=>{f(z,(Y,re)=>{Y&&(O=Y),L[G]=re,--S===0&&_(O,L)})})}let as=1;function Ls(){return as++}function cs(k){return k<=1?1:Math.pow(2,Math.ceil(Math.log2(k)))}function qt(k,f){k.forEach(_=>{f[_]&&(f[_]=f[_].bind(f))})}function Gs(k,f,_){const S={};for(const L in k)S[L]=f.call(this,k[L],L,k);return S}function Vs(k,f,_){const S={};for(const L in k)f.call(this,k[L],L,k)&&(S[L]=k[L]);return S}function Hn(k){return Array.isArray(k)?k.map(Hn):typeof k=="object"&&k?Gs(k,Hn):k}function Kr(k,f){for(let _=0;_=0)return!0;return!1}const ma={};function Or(k){ma[k]||(typeof console<"u"&&console.warn(k),ma[k]=!0)}function ta(k,f,_){return(_.y-k.y)*(f.x-k.x)>(f.y-k.y)*(_.x-k.x)}function da(k){let f=0;for(let _,S,L=0,O=k.length,z=O-1;L@\,;\:\\"\/\[\]\?\=\{\}\x7F]+)(?:\=(?:([^\x00-\x20\(\)<>@\,;\:\\"\/\[\]\?\=\{\}\x7F]+)|(?:\"((?:[^"\\]|\\.)*)\")))?/g,(_,S,L,O)=>{const z=L||O;return f[S]=!z||z.toLowerCase(),""}),f["max-age"]){const _=parseInt(f["max-age"],10);isNaN(_)?delete f["max-age"]:f["max-age"]=_}return f}let Oo,Ei=null;function Wa(k,f){return[k[4*f],k[4*f+1],k[4*f+2],k[4*f+3]]}function wo(k,f,_,S){for(;f<_;){const L=f+_>>1;k[L]>1;k[L]<=S?f=L+1:_=L}return f}function is(k){return k>0?1/(1.001-k):1+k}function zr(k){return k>0?1-1/(1.001-k):-k}function Sa(k,f,_){return(k-f.min)*(_.max-_.min)/(f.max-f.min)+_.min}const Kn={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(!Kn.API_URL)return null;try{const k=new URL(Kn.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 wn(){return new URL(Kn.DRACO_URL,Kn.API_URL).href}function Ur(){if(typeof WebAssembly!="object")throw new Error("WebAssembly not supported, cannot instantiate meshoptimizer");return new URL(function(){if(Oo===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]);Oo=WebAssembly.validate(k)}return Oo}()?Kn.MESHOPT_SIMD_URL:Kn.MESHOPT_URL,Kn.API_URL).href}function ca(){return new URL(Kn.BUILDING_GEN_URL,Kn.API_URL).href}function yo(k){return Kn.API_URL_REGEX.test(k)}function vo(k){return Kn.API_SPRITE_REGEX.test(k)}let Vo,Xc,uo,bo,od,Ju;function Ld(){return Vo==null&&(Vo=self.OffscreenCanvas&&new OffscreenCanvas(1,1).getContext("2d")&&typeof self.createImageBitmap=="function"),Vo}const bd={now:()=>bo!==void 0?bo:performance.now(),setNow(k){bo=k},restoreNow(){bo=void 0},frame(k){const f=requestAnimationFrame(k);return{cancel:()=>cancelAnimationFrame(f)}},getImageData(k,f=0){const{width:_,height:S}=k;od||(od=document.createElement("canvas"));const L=od.getContext("2d",{willReadFrequently:!0});if(!L)throw new Error("failed to create canvas 2d context");return(_>od.width||S>od.height)&&(od.width=_,od.height=S),L.clearRect(-f,-f,_+2*f,S+2*f),L.drawImage(k,0,0,_,S),L.getImageData(-f,-f,_+2*f,S+2*f)},resolveURL:k=>(Xc||(Xc=document.createElement("a")),Xc.href=k,Xc.href),get devicePixelRatio(){return window.devicePixelRatio},get prefersReducedMotion(){return!!window.matchMedia&&(uo==null&&(uo=window.matchMedia("(prefers-reduced-motion: reduce)")),uo.matches)},hasCanvasFingerprintNoise(){if(Ju!==void 0)return Ju;if(!Ld())return Ju=!1,!1;const k=new OffscreenCanvas(85,1),f=k.getContext("2d",{willReadFrequently:!0});let _=0;for(let L=0;L0?`?${O}`:""}`}const Kp="mapbox-tiles";let Dg=500,Em=50;const Lf=["language","worldview","jobid"];let eh;function L0(){try{return caches}catch{}}function jo(){const k=L0();k&&eh==null&&(eh=k.open(Kp))}let Zi=1/0;const Ey={supported:!1,testSupport:function(k){!Rg&&If&&(ql?Lu(k):Pf=k)}};let Pf,If,Rg=!1,ql=!1;const Df=typeof self<"u"?self:{};function Lu(k){const f=k.createTexture();k.bindTexture(k.TEXTURE_2D,f);try{if(k.texImage2D(k.TEXTURE_2D,0,k.RGBA,k.RGBA,k.UNSIGNED_BYTE,If),k.isContextLost())return;Ey.supported=!0}catch{}k.deleteTexture(f),Rg=!0}Df.document&&(If=Df.document.createElement("img"),If.onload=function(){Pf&&Lu(Pf),Pf=null,ql=!0},If.onerror=function(){Rg=!0,Pf=null},If.src="data:image/webp;base64,UklGRh4AAABXRUJQVlA4TBEAAAAvAQAAAAfQ//73v/+BiOh/AAA=");const lp={Unknown:"Unknown",Style:"Style",Source:"Source",Tile:"Tile",Glyphs:"Glyphs",SpriteImage:"SpriteImage",SpriteJSON:"SpriteJSON",Iconset:"Iconset",Image:"Image",Model:"Model"};Object.freeze(lp);class Ty extends Error{constructor(f,_,S){_===401&&yo(S)&&(f+=": you may have provided an invalid Mapbox access token. See https://docs.mapbox.com/api/overview/#access-tokens-and-token-scopes"),super(f),this.status=_,this.url=S}toString(){return`${this.name}: ${this.message} (${this.status}): ${this.url}`}}function Kd(k){return typeof k=="object"&&k!==null&&"status"in k&&k.status===404}const Ti=hi()?()=>self.worker.referrer:()=>(location.protocol==="blob:"?parent:self).location.href,rm=function(k,f){return/^file:/.test(_=k.url)||/^file:/.test(Ti())&&!/^\w+:/.test(_)?function(S,L){const O=new XMLHttpRequest;O.open(S.method||"GET",S.url,!0),S.type==="arrayBuffer"&&(O.responseType="arraybuffer");for(const z in S.headers)O.setRequestHeader(z,S.headers[z]);return S.type==="json"&&(O.responseType="text",O.setRequestHeader("Accept","application/json")),O.withCredentials=S.credentials==="include",O.onerror=()=>{L(new Error(O.statusText))},O.onload=()=>{if((O.status>=200&&O.status<300||O.status===0)&&O.response!==null){let z=O.response;if(S.type==="json")try{z=JSON.parse(O.response)}catch(Y){return L(Y)}const G=new Headers;O.getAllResponseHeaders().trim().split(/[\r\n]+/).forEach(Y=>{const re=Y.split(": "),me=re.shift(),ye=re.join(": ");G.append(me,ye)}),L(null,z,G)}else L(new Ty(O.statusText,O.status,S.url))},O.send(S.body),{cancel:()=>O.abort()}}(k,f):function(S,L){const O=new AbortController,z=new Request(S.url,{method:S.method||"GET",body:S.body,credentials:S.credentials,headers:S.headers,referrer:Ti(),referrerPolicy:S.referrerPolicy,signal:O.signal});let G=!1,Y=!1;const re=(me=z.url).indexOf("sku=")>0&&yo(me);var me;S.type==="json"&&z.headers.set("Accept","application/json");const ye=(Te,Ie,Ve)=>{if(Y)return;if(Te&&Te.message!=="SecurityError"&&Or(Te.toString()),Ie&&Ve)return we(Ie);const Je=Date.now();fetch(z).then(rt=>{if(rt.ok){const xt=re?rt.clone():null;return we(rt,xt,Je)}return L(new Ty(rt.statusText,rt.status,S.url))}).catch(rt=>{rt.name!=="AbortError"&&L(new Error(`${rt.message} ${S.url}`))})},we=(Te,Ie,Ve)=>{(S.type==="arrayBuffer"?Te.arrayBuffer():S.type==="json"?Te.json():Te.text()).then(Je=>{Y||(Ie&&Ve&&function(rt,xt,ut){if(jo(),eh==null)return;const St=el(xt.headers.get("cache-control")||"");if(St["no-store"])return;const Pt={status:xt.status,statusText:xt.statusText,headers:new Headers};xt.headers.forEach((us,hs)=>Pt.headers.set(hs,us)),St["max-age"]&&Pt.headers.set("Expires",new Date(ut+1e3*St["max-age"]).toUTCString());const Rt=Pt.headers.get("expires");if(!Rt||new Date(Rt).getTime()-ut<42e4)return;let ws=Ay(rt.url,{persistentParams:Lf});if(xt.status===206){const us=rt.headers.get("Range");if(!us)return;Pt.status=200,ws=hx(ws,{range:us})}const ns=new Response((xs=xt.status)!==200&&xs!==404&&[101,103,204,205,304].includes(xs)?null:xt.body,Pt);var xs;jo(),eh!=null&&eh.then(us=>us.put(ws,ns)).catch(us=>Or(us.message))}(z,Ie,Ve),G=!0,L(null,Je,Te.headers))}).catch(Je=>{Y||L(new Error(Je.message))})};return re?function(Te,Ie){if(jo(),eh==null)return Ie(null);eh.then(Ve=>{let Je=Ay(Te.url,{persistentParams:Lf});const rt=Te.headers.get("Range");rt&&(Je=hx(Je,{range:rt})),Ve.match(Je).then(xt=>{const ut=function(St){if(!St)return!1;const Pt=new Date(St.headers.get("expires")||0),Rt=el(St.headers.get("cache-control")||"");return Number(Pt)>Date.now()&&!Rt["no-cache"]}(xt);Ve.delete(Je).catch(Ie),ut&&Ve.put(Je,xt.clone()).catch(Ie),Ie(null,xt,ut)}).catch(Ie)}).catch(Ie)}(z,ye):ye(null,null),{cancel:()=>{Y=!0,G||O.abort()}}}(k,f);var _},mh=function(k,f){return rm(Object.assign(k,{type:"arrayBuffer"}),f)};function Tm(k){const f=document.createElement("a");return f.href=k,f.protocol===location.protocol&&f.host===location.host}let Yp,ph;Yp=[],ph=0;const am=function(k,f){if(Ey.supported&&(k.headers||(k.headers={}),k.headers.accept="image/webp,*/*"),ph>=Kn.MAX_PARALLEL_IMAGE_REQUESTS){const O={requestParameters:k,callback:f,cancelled:!1,cancel(){this.cancelled=!0}};return Yp.push(O),O}ph++;let _=!1;const S=()=>{if(!_)for(_=!0,ph--;Yp.length&&ph{S(),O?f(O):z&&function(Y,re){const me=new Blob([new Uint8Array(Y)],{type:"image/png"});createImageBitmap(me).then(ye=>{re(null,ye)}).catch(ye=>{re(new Error(`Could not load image because of ${ye.message}. Please make sure to use a supported image type such as PNG or JPEG. Note that SVGs are not supported.`))})}(z,(Y,re)=>f(Y,re,G))});return{cancel:()=>{L.cancel(),S()}}};var Og,Fg,Mm,im={exports:{}},Vx={exports:{}},mx={exports:{}},P0=function(){if(Mm)return im.exports;Mm=1;var k=(Og||(Og=1,Vx.exports=function(_,S){var L,O,z,G,Y,re,me,ye;for(O=_.length-(L=3&_.length),z=S,Y=3432918353,re=461845907,ye=0;ye>>16)*Y&65535)<<16)&4294967295)<<15|me>>>17))*re+(((me>>>16)*re&65535)<<16)&4294967295)<<13|z>>>19))+((5*(z>>>16)&65535)<<16)&4294967295))+(((G>>>16)+58964&65535)<<16);switch(me=0,L){case 3:me^=(255&_.charCodeAt(ye+2))<<16;case 2:me^=(255&_.charCodeAt(ye+1))<<8;case 1:z^=me=(65535&(me=(me=(65535&(me^=255&_.charCodeAt(ye)))*Y+(((me>>>16)*Y&65535)<<16)&4294967295)<<15|me>>>17))*re+(((me>>>16)*re&65535)<<16)&4294967295}return z^=_.length,z=2246822507*(65535&(z^=z>>>16))+((2246822507*(z>>>16)&65535)<<16)&4294967295,z=3266489909*(65535&(z^=z>>>13))+((3266489909*(z>>>16)&65535)<<16)&4294967295,(z^=z>>>16)>>>0}),Vx.exports),f=(Fg||(Fg=1,mx.exports=function(_,S){for(var L,O=_.length,z=S^O,G=0;O>=4;)L=1540483477*(65535&(L=255&_.charCodeAt(G)|(255&_.charCodeAt(++G))<<8|(255&_.charCodeAt(++G))<<16|(255&_.charCodeAt(++G))<<24))+((1540483477*(L>>>16)&65535)<<16),z=1540483477*(65535&z)+((1540483477*(z>>>16)&65535)<<16)^(L=1540483477*(65535&(L^=L>>>24))+((1540483477*(L>>>16)&65535)<<16)),O-=4,++G;switch(O){case 3:z^=(255&_.charCodeAt(G+2))<<16;case 2:z^=(255&_.charCodeAt(G+1))<<8;case 1:z=1540483477*(65535&(z^=255&_.charCodeAt(G)))+((1540483477*(z>>>16)&65535)<<16)}return z=1540483477*(65535&(z^=z>>>13))+((1540483477*(z>>>16)&65535)<<16),(z^=z>>>15)>>>0}),mx.exports);return im.exports=k,im.exports.murmur3=k,im.exports.murmur2=f,im.exports}(),ld=yr(P0);class Oc{constructor(f,..._){Object.assign(this,_[0]||{}),this.type=f}}class cp extends Oc{constructor(f,_={}){super("error",Object.assign({error:f},_))}}function _d(k,f,_){_[k]&&_[k].indexOf(f)!==-1||(_[k]=_[k]||[],_[k].push(f))}function dp(k,f,_){if(_&&_[k]){const S=_[k].indexOf(f);S!==-1&&_[k].splice(S,1)}}class om{on(f,_){return this._listeners=this._listeners||{},_d(f,_,this._listeners),this}off(f,_){return dp(f,_,this._listeners),dp(f,_,this._oneTimeListeners),this}once(f,_){return _?(this._oneTimeListeners=this._oneTimeListeners||{},_d(f,_,this._oneTimeListeners),this):new Promise(S=>{this.once(f,S)})}fire(f,_){const S=typeof f=="string"?new Oc(f,_):f,L=S.type;if(this.listens(L)){S.target=this;const O=this._listeners&&this._listeners[L]?this._listeners[L].slice():[];for(const Y of O)Y.call(this,S);const z=this._oneTimeListeners&&this._oneTimeListeners[L]?this._oneTimeListeners[L].slice():[];for(const Y of z)dp(L,Y,this._oneTimeListeners),Y.call(this,S);const G=this._eventedParent;if(G){const Y=typeof this._eventedParentData=="function"?this._eventedParentData():this._eventedParentData;Object.assign(S,Y),G.fire(S)}}else S instanceof cp&&console.error(S.error);return this}listens(f){return!!(this._listeners&&this._listeners[f]&&this._listeners[f].length>0||this._oneTimeListeners&&this._oneTimeListeners[f]&&this._oneTimeListeners[f].length>0||this._eventedParent&&this._eventedParent.listens(f))}setEventedParent(f,_){return this._eventedParent=f,this._eventedParentData=_,this}}class Rh{constructor(f){typeof f=="string"?this.name=f:(this.name=f.name,this.iconsetId=f.iconsetId)}static from(f){return new Rh(f)}static toString(f){return f.iconsetId?`${f.name}${f.iconsetId}`:f.name}static parse(f){const[_,S]=f.split("");return new Rh({name:_,iconsetId:S})}static isEqual(f,_){return f.name===_.name&&f.iconsetId===_.iconsetId}toString(){return Rh.toString(this)}serialize(){return{name:this.name,iconsetId:this.iconsetId}}}var at,Wt={},Bs=function(){if(at)return Wt;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 f(O){return(O=Math.round(O))<0?0:O>255?255:O}function _(O){return f(O[O.length-1]==="%"?parseFloat(O)/100*255:parseInt(O))}function S(O){return(z=O[O.length-1]==="%"?parseFloat(O)/100:parseFloat(O))<0?0:z>1?1:z;var z}function L(O,z,G){return G<0?G+=1:G>1&&(G-=1),6*G<1?O+(z-O)*G*6:2*G<1?z:3*G<2?O+(z-O)*(2/3-G)*6:O}try{Wt.parseCSSColor=function(O){var z,G=O.replace(/ /g,"").toLowerCase();if(G in k)return k[G].slice();if(G[0]==="#")return G.length===4?(z=parseInt(G.substr(1),16))>=0&&z<=4095?[(3840&z)>>4|(3840&z)>>8,240&z|(240&z)>>4,15&z|(15&z)<<4,1]:null:G.length===7&&(z=parseInt(G.substr(1),16))>=0&&z<=16777215?[(16711680&z)>>16,(65280&z)>>8,255&z,1]:null;var Y=G.indexOf("("),re=G.indexOf(")");if(Y!==-1&&re+1===G.length){var me=G.substr(0,Y),ye=G.substr(Y+1,re-(Y+1)).split(","),we=1;switch(me){case"rgba":if(ye.length!==4)return null;we=S(ye.pop());case"rgb":return ye.length!==3?null:[_(ye[0]),_(ye[1]),_(ye[2]),we];case"hsla":if(ye.length!==4)return null;we=S(ye.pop());case"hsl":if(ye.length!==3)return null;var Te=(parseFloat(ye[0])%360+360)%360/360,Ie=S(ye[1]),Ve=S(ye[2]),Je=Ve<=.5?Ve*(Ie+1):Ve+Ie-Ve*Ie,rt=2*Ve-Je;return[f(255*L(rt,Je,Te+1/3)),f(255*L(rt,Je,Te)),f(255*L(rt,Je,Te-1/3)),we];default:return null}}return null}}catch{}return Wt}();class Ys{constructor(f,_,S,L=1){this.r=f,this.g=_,this.b=S,this.a=L}static parse(f){if(!f)return;if(f instanceof Ys)return f;if(typeof f!="string")return;const _=Bs.parseCSSColor(f);return _?new Ys(_[0]/255,_[1]/255,_[2]/255,_[3]):void 0}toString(){const[f,_,S,L]=[this.r,this.g,this.b,this.a];return`rgba(${Math.round(255*f)},${Math.round(255*_)},${Math.round(255*S)},${L})`}toNonPremultipliedRenderColor(f){const{r:_,g:S,b:L,a:O}=this;return new Ir(f,_,S,L,O)}toPremultipliedRenderColor(f){const{r:_,g:S,b:L,a:O}=this;return new kt(f,_*O,S*O,L*O,O)}clone(){return new Ys(this.r,this.g,this.b,this.a)}}class jn{constructor(f,_,S,L,O,z=!1){if(this.premultiplied=!1,this.premultiplied=z,f){const G=f.image.height,Y=G*G;this.premultiplied?(_=O===0?0:_/O*(G-1),S=O===0?0:S/O*(G-1),L=O===0?0:L/O*(G-1)):(_*=G-1,S*=G-1,L*=G-1),_=Math.max(0,Math.min(G-1,_)),S=Math.max(0,Math.min(G-1,S)),L=Math.max(0,Math.min(G-1,L));const re=Math.floor(_),me=Math.floor(S),ye=Math.floor(L),we=Math.ceil(_),Te=Math.ceil(S),Ie=Math.ceil(L),Ve=_-re,Je=S-me,rt=L-ye,xt=f.image.data,ut=4*(re+me*Y+ye*G),St=4*(re+me*Y+Ie*G),Pt=4*(re+Te*Y+ye*G),Rt=4*(re+Te*Y+Ie*G),ws=4*(we+me*Y+ye*G),ns=4*(we+me*Y+Ie*G),xs=4*(we+Te*Y+ye*G),us=4*(we+Te*Y+Ie*G);this.r=Cs(Cs(Cs(xt[ut],xt[St],rt),Cs(xt[Pt],xt[Rt],rt),Je),Cs(Cs(xt[ws],xt[ns],rt),Cs(xt[xs],xt[us],rt),Je),Ve)/255*(this.premultiplied?O:1),this.g=Cs(Cs(Cs(xt[ut+1],xt[St+1],rt),Cs(xt[Pt+1],xt[Rt+1],rt),Je),Cs(Cs(xt[ws+1],xt[ns+1],rt),Cs(xt[xs+1],xt[us+1],rt),Je),Ve)/255*(this.premultiplied?O:1),this.b=Cs(Cs(Cs(xt[ut+2],xt[St+2],rt),Cs(xt[Pt+2],xt[Rt+2],rt),Je),Cs(Cs(xt[ws+2],xt[ns+2],rt),Cs(xt[xs+2],xt[us+2],rt),Je),Ve)/255*(this.premultiplied?O:1),this.a=O}else this.r=_,this.g=S,this.b=L,this.a=O}toArray(){const{r:f,g:_,b:S,a:L}=this;return[255*f,255*_,255*S,L]}toHslaArray(){let{r:f,g:_,b:S,a:L}=this;if(this.premultiplied){if(L===0)return[0,0,0,0];const Ie=1/L;f*=Ie,_*=Ie,S*=Ie}const O=Math.min(Math.max(f,0),1),z=Math.min(Math.max(_,0),1),G=Math.min(Math.max(S,0),1),Y=Math.min(O,z,G),re=Math.max(O,z,G),me=re-Y,ye=.5*(Y+re);if(me===0)return[0,0,100*ye,L];const we=ye>.5?me/(2-re-Y):me/(re+Y);let Te;switch(re){case O:Te=60*((z-G)/me+(zCs(S,f[L],_))}Ys.black=new Ys(0,0,0,1),Ys.white=new Ys(1,1,1,1),Ys.transparent=new Ys(0,0,0,0),Ys.red=new Ys(1,0,0,1),Ys.blue=new Ys(0,0,1,1);var Rr=Object.freeze({__proto__:null,array:xn,color:function(k,f,_){return new Ys(Cs(k.r,f.r,_),Cs(k.g,f.g,_),Cs(k.b,f.b,_),Cs(k.a,f.a,_))},number:Cs});class Dr extends Error{constructor(f,_){super(_),this.message=_,this.key=f}}class Aa{constructor(f,_=[]){this.parent=f,this.bindings={};for(const[S,L]of _)this.bindings[S]=L}concat(f){return new Aa(this,f)}get(f){if(this.bindings[f])return this.bindings[f];if(this.parent)return this.parent.get(f);throw new Error(`${f} not found in scope.`)}has(f){return!!this.bindings[f]||!!this.parent&&this.parent.has(f)}}const Ua={kind:"null"},sr={kind:"number"},Ra={kind:"string"},ri={kind:"boolean"},Ho={kind:"color"},Kl={kind:"object"},Hi={kind:"value"},lm={kind:"collator"},zg={kind:"formatted"},Bg={kind:"resolvedImage"};function gu(k,f){return{kind:"array",itemType:k,N:f}}function tc(k){if(k.kind==="array"){const f=tc(k.itemType);return typeof k.N=="number"?`array<${f}, ${k.N}>`:k.itemType.kind==="value"?"array":`array<${f}>`}return k.kind}const L1=[Ua,sr,Ra,ri,Ho,zg,Kl,gu(Hi),Bg];function Hx(k,f){if(f.kind==="error")return null;if(k.kind==="array"){if(f.kind==="array"&&(f.N===0&&f.itemType.kind==="value"||!Hx(k.itemType,f.itemType))&&(typeof k.N!="number"||k.N===f.N))return null}else{if(k.kind===f.kind)return null;if(k.kind==="value"){for(const _ of L1)if(!Hx(_,f))return null}}return`Expected ${tc(k)} but found ${tc(f)} instead.`}function I0(k,f){return f.some(_=>_.kind===k.kind)}function Yd(k,f){return f.some(_=>_==="null"?k===null:_==="array"?Array.isArray(k):_==="object"?k&&!Array.isArray(k)&&typeof k=="object":_===typeof k)}function up(k,f){return k.kind==="array"&&f.kind==="array"?k.N===f.N&&up(k.itemType,f.itemType):k.kind===f.kind}class D0{constructor(f,_,S){this.sensitivity=f?_?"variant":"case":_?"accent":"base",this.locale=S,this.collator=new Intl.Collator(this.locale?this.locale:[],{sensitivity:this.sensitivity,usage:"search"})}compare(f,_){return this.collator.compare(f,_)}resolvedLocale(){return new Intl.Collator(this.locale?this.locale:[]).resolvedOptions().locale}}class My{constructor(f,_,S,L,O){this.text=f.normalize?f.normalize():f,this.image=_,this.scale=S,this.fontStack=L,this.textColor=O}}class cd{constructor(f){this.sections=f}static fromString(f){return new cd([new My(f,null,null,null,null)])}isEmpty(){return this.sections.length===0||!this.sections.some(f=>f.text.length!==0||!!f.image&&f.image.hasPrimary())}static factory(f){return f instanceof cd?f:cd.fromString(f)}toString(){return this.sections.length===0?"":this.sections.map(f=>f.text).join("")}serialize(){const f=["format"];for(const _ of this.sections){if(_.image){const L=_.image.getPrimary().id.toString();f.push(["image",L]);continue}f.push(_.text);const S={};_.fontStack&&(S["text-font"]=["literal",_.fontStack.split(",")]),_.scale&&(S["font-scale"]=_.scale),_.textColor&&(S["text-color"]=["rgba"].concat(_.textColor.toNonPremultipliedRenderColor(null).toArray())),f.push(S)}return f}}class wd{constructor(f,_={}){this.id=Rh.from(f),this.params=_.params,this.sx=_.sx||1,this.sy=_.sy||1}toString(){return JSON.stringify(this)}static parse(f){let _,S,L,O;try{({id:_,params:S,sx:L,sy:O}=JSON.parse(f)||{})}catch{return null}return _?new wd(_,{params:S,sx:L,sy:O}):null}scaleSelf(f,_=f){return this.sx*=f,this.sy*=_,this}}class Pu{constructor(f,_,S,L,O=!1){this.primaryId=Rh.from(f),this.primaryOptions=_,S&&(this.secondaryId=Rh.from(S)),this.secondaryOptions=L,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 wd(this.primaryId,this.primaryOptions)}hasSecondary(){return!!this.secondaryId}getSecondary(){return this.secondaryId?new wd(this.secondaryId,this.secondaryOptions):null}static from(f){return typeof f=="string"?Pu.build({name:f}):f}static build(f,_,S,L){return!f||typeof f=="object"&&!("name"in f)?null:new Pu(f,S,_,L)}}function Lm(k,f,_,S){return typeof k=="number"&&k>=0&&k<=255&&typeof f=="number"&&f>=0&&f<=255&&typeof _=="number"&&_>=0&&_<=255?S===void 0||typeof S=="number"&&S>=0&&S<=1?null:`Invalid rgba value [${[k,f,_,S].join(", ")}]: 'a' must be between 0 and 1.`:`Invalid rgba value [${(typeof S=="number"?[k,f,_,S]:[k,f,_]).join(", ")}]: 'r', 'g', and 'b' must be between 0 and 255.`}function Rf(k){if(k===null||typeof k=="string"||typeof k=="boolean"||typeof k=="number"||k instanceof Ys||k instanceof D0||k instanceof cd||k instanceof Pu)return!0;if(Array.isArray(k)){for(const f of k)if(!Rf(f))return!1;return!0}if(typeof k=="object"){for(const f in k)if(!Rf(k[f]))return!1;return!0}return!1}function kl(k){if(k===null)return Ua;if(typeof k=="string")return Ra;if(typeof k=="boolean")return ri;if(typeof k=="number")return sr;if(k instanceof Ys)return Ho;if(k instanceof D0)return lm;if(k instanceof cd)return zg;if(k instanceof Pu)return Bg;if(Array.isArray(k)){const f=k.length;let _;for(const S of k){const L=kl(S);if(_){if(_===L)continue;_=Hi;break}_=L}return gu(_||Hi,f)}return Kl}function Ma(k){const f=typeof k;return k===null?"":f==="string"||f==="number"||f==="boolean"?String(k):k instanceof cd||k instanceof Pu||k instanceof Ys?k.toString():JSON.stringify(k)}class qr{constructor(f,_){this.type=f,this.value=_}static parse(f,_){if(f.length!==2)return _.error(`'literal' expression requires exactly one argument, but found ${f.length-1} instead.`);if(!Rf(f[1]))return _.error("invalid value");const S=f[1];let L=kl(S);const O=_.expectedType;return L.kind!=="array"||L.N!==0||!O||O.kind!=="array"||typeof O.N=="number"&&O.N!==0||(L=O),new qr(L,S)}evaluate(){return this.value}eachChild(){}outputDefined(){return!0}serialize(){return this.type.kind==="array"||this.type.kind==="object"?["literal",this.value]:this.value instanceof Ys?["rgba"].concat(this.value.toNonPremultipliedRenderColor(null).toArray()):this.value instanceof cd?this.value.serialize():this.value}}class Yl{constructor(f){this.name="ExpressionEvaluationError",this.message=f}toJSON(){return this.message}}const La={string:Ra,number:sr,boolean:ri,object:Kl};class Pm{constructor(f,_){this.type=f,this.args=_}static parse(f,_){if(f.length<2)return _.error("Expected at least one argument.");let S,L=1;const O=f[0];if(O==="array"){let G,Y;if(f.length>2){const re=f[1];if(typeof re!="string"||!(re in La)||re==="object")return _.error('The item type argument of "array" must be one of string, number, boolean',1);G=La[re],L++}else G=Hi;if(f.length>3){if(f[2]!==null&&(typeof f[2]!="number"||f[2]<0||f[2]!==Math.floor(f[2])))return _.error('The length argument to "array" must be a positive integer literal',2);Y=f[2],L++}S=gu(G,Y)}else S=La[O];const z=[];for(;Lf.outputDefined())}serialize(){const f=this.type,_=[f.kind];if(f.kind==="array"){const S=f.itemType;if(S.kind==="string"||S.kind==="number"||S.kind==="boolean"){_.push(S.kind);const L=f.N;(typeof L=="number"||this.args.length>1)&&_.push(L)}}return _.concat(this.args.map(S=>S.serialize()))}}class dd{constructor(f){this.type=zg,this.sections=f}static parse(f,_){if(f.length<2)return _.error("Expected at least one argument.");const S=f[1];if(!Array.isArray(S)&&typeof S=="object")return _.error("First argument must be an image or text section.");const L=[];let O=!1;for(let z=1;z<=f.length-1;++z){const G=f[z];if(O&&typeof G=="object"&&!Array.isArray(G)){O=!1;let Y=null;if(G["font-scale"]&&(Y=_.parseObjectValue(G["font-scale"],z,"font-scale",sr),!Y))return null;let re=null;if(G["text-font"]&&(re=_.parseObjectValue(G["text-font"],z,"text-font",gu(Ra)),!re))return null;let me=null;if(G["text-color"]&&(me=_.parseObjectValue(G["text-color"],z,"text-color",Ho),!me))return null;const ye=L[L.length-1];ye.scale=Y,ye.font=re,ye.textColor=me}else{const Y=_.parse(f[z],z,Hi);if(!Y)return null;const re=Y.type.kind;if(re!=="string"&&re!=="value"&&re!=="null"&&re!=="resolvedImage")return _.error("Formatted text type must be 'string', 'value', 'image' or 'null'.");O=!0,L.push({content:Y,scale:null,font:null,textColor:null})}}return new dd(L)}evaluate(f){return new cd(this.sections.map(_=>{const S=_.content.evaluate(f);return up(kl(S),Bg)?new My("",S,null,null,null):new My(Ma(S),null,_.scale?_.scale.evaluate(f):null,_.font?_.font.evaluate(f).join(","):null,_.textColor?_.textColor.evaluate(f):null)}))}eachChild(f){for(const _ of this.sections)f(_.content),_.scale&&f(_.scale),_.font&&f(_.font),_.textColor&&f(_.textColor)}outputDefined(){return!1}serialize(){const f=["format"];for(const _ of this.sections){f.push(_.content.serialize());const S={};_.scale&&(S["font-scale"]=_.scale.serialize()),_.font&&(S["text-font"]=_.font.serialize()),_.textColor&&(S["text-color"]=_.textColor.serialize()),f.push(S)}return f}}class pa{constructor(f,_,S,L){this._imageWarnHistory={},this.type=Bg,this.namePrimary=f,this.nameSecondary=_,S&&(this.paramsPrimary=S.params,this.iconsetIdPrimary=S.iconset?S.iconset.id:void 0),L&&(this.paramsSecondary=L.params,this.iconsetIdSecondary=L.iconset?L.iconset.id:void 0)}static parse(f,_){if(f.length<2)return _.error("Expected two or more arguments.");let S=1;const L=[];function O(){if(SRh.isEqual(z,O)),L.available){const z=L.getSecondary()?L.getSecondary().id:null;z&&(L.available=f.availableImages.some(G=>Rh.isEqual(G,z)))}}return L}eachChild(f){if(f(this.namePrimary),this.paramsPrimary)for(const _ in this.paramsPrimary)this.paramsPrimary[_]&&f(this.paramsPrimary[_]);if(this.nameSecondary&&(f(this.nameSecondary),this.paramsSecondary))for(const _ in this.paramsSecondary)this.paramsSecondary[_]&&f(this.paramsSecondary[_])}outputDefined(){return!1}serializeOptions(f,_){const S={};if(_&&(S.iconset={id:_}),f){S.params={};for(const L in f)f[L]&&(S.params[L]=f[L].serialize())}return Object.keys(S).length>0?S:void 0}serialize(){const f=["image",this.namePrimary.serialize()];if(this.paramsPrimary||this.iconsetIdPrimary){const _=this.serializeOptions(this.paramsPrimary,this.iconsetIdPrimary);_&&f.push(_)}if(this.nameSecondary&&(f.push(this.nameSecondary.serialize()),this.paramsSecondary||this.iconsetIdSecondary)){const _=this.serializeOptions(this.paramsSecondary,this.iconsetIdSecondary);_&&f.push(_)}return f}}function Gx(k){return px(k)?"string":R0(k)?"number":Of(k)?"boolean":Array.isArray(k)?"array":k===null?"null":$g(k)?"object":typeof k}function $g(k){return k!=null&&!Array.isArray(k)&&typeof k!="function"&&!(k instanceof String||k instanceof Number||k instanceof Boolean)&&typeof k=="object"}function px(k){return typeof k=="string"||k instanceof String}function R0(k){return typeof k=="number"||k instanceof Number}function Of(k){return typeof k=="boolean"||k instanceof Boolean}const qc={"to-boolean":ri,"to-color":Ho,"to-number":sr,"to-string":Ra};class hp{constructor(f,_){this.type=f,this.args=_}static parse(f,_){if(f.length<2)return _.error("Expected at least one argument.");const S=f[0],L=[];let O=Ua;if(S==="to-array"){if(!Array.isArray(f[1]))return null;const z=f[1].length;if(_.expectedType){if(_.expectedType.kind!=="array")return _.error(`Expected ${_.expectedType.kind} but found array.`);O=gu(_.expectedType.itemType,z)}else{if(!(z>0&&Rf(f[1][0])))return null;O=gu(kl(f[1][0]),z)}for(let G=0;G4?`Invalid rbga value ${JSON.stringify(_)}: expected an array containing either three or four numeric values.`:Lm(_[0],_[1],_[2],_[3]),!S))return new Ys(_[0]/255,_[1]/255,_[2]/255,_[3])}throw new Yl(S||`Could not parse color from value '${typeof _=="string"?_:String(JSON.stringify(_))}'`)}if(this.type.kind==="number"){let _=null;for(const S of this.args){if(_=S.evaluate(f),_===null)return 0;const L=Number(_);if(!isNaN(L))return L}throw new Yl(`Could not convert ${JSON.stringify(_)} to number.`)}return this.type.kind==="formatted"?cd.fromString(Ma(this.args[0].evaluate(f))):this.type.kind==="resolvedImage"?Pu.build(Ma(this.args[0].evaluate(f))):this.type.kind==="array"?this.args.map(_=>_.evaluate(f)):Ma(this.args[0].evaluate(f))}eachChild(f){this.args.forEach(f)}outputDefined(){return this.args.every(f=>f.outputDefined())}serialize(){if(this.type.kind==="formatted")return new dd([{content:this.args[0],scale:null,font:null,textColor:null}]).serialize();if(this.type.kind==="resolvedImage")return new pa(this.args[0]).serialize();const f=this.type.kind==="array"?[]:[`to-${this.type.kind}`];return this.eachChild(_=>{f.push(_.serialize())}),f}}const fh=["Unknown","Point","LineString","Polygon"];class yu{constructor(f,_,S){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=f,this.options=_,this.iconImageUseTheme=S}id(){return this.feature&&this.feature.id!==void 0?this.feature.id:null}geometryType(){return this.feature?typeof this.feature.type=="number"?fh[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(f){return this.globals.brightness||0}distanceFromCenter(){if(this.featureTileCoord&&this.featureDistanceData){const f=this.featureDistanceData.center,_=this.featureDistanceData.scale,{x:S,y:L}=this.featureTileCoord;return this.featureDistanceData.bearing[0]*(S*_-f[0])+this.featureDistanceData.bearing[1]*(L*_-f[1])}return 0}parseColor(f){let _=this._parseColorCache[f];return _||(_=this._parseColorCache[f]=Ys.parse(f)),_}getConfig(f){return this.options?this.options.get(f):null}}class Qc{constructor(f,_,S,L,O){this.name=f,this.type=_,this._evaluate=S,this.args=L,this._overloadIndex=O}evaluate(f){if(!this._evaluate){const _=Qc.definitions[this.name];this._evaluate=Array.isArray(_)?_[2]:_.overloads[this._overloadIndex][1]}return this._evaluate(f,this.args)}eachChild(f){this.args.forEach(f)}outputDefined(){return!1}serialize(){return[this.name].concat(this.args.map(f=>f.serialize()))}static parse(f,_){const S=f[0],L=Qc.definitions[S];if(!L)return _.error(`Unknown expression "${S}". If you wanted a literal array, use ["literal", [...]].`,0);const O=Array.isArray(L)?L[0]:L.type,z=Array.isArray(L)?[[L[1],L[2]]]:L.overloads,G=[];let Y=null,re=-1;for(const[me,ye]of z){if(Array.isArray(me)&&me.length!==f.length-1)continue;G.push(me),re++,Y=new k2(_.registry,_.path,null,_.scope,void 0,_._scope,_.options,_.iconImageUseTheme);const we=[];let Te=!1;for(let Ie=1;Iewe)).map(mp).join(" | "),ye=[];for(let we=1;we_;){if(S-_>600){const Y=S-_+1,re=f-_+1,me=Math.log(Y),ye=.5*Math.exp(2*me/3),we=.5*Math.sqrt(me*ye*(Y-ye)/Y)*(re-Y/2<0?-1:1);kv(k,f,Math.max(_,Math.floor(f-re*ye/Y+we)),Math.min(S,Math.floor(f+(Y-re)*ye/Y+we)),L)}const O=k[f];let z=_,G=S;for(Ac(k,_,f),L(k[S],O)>0&&Ac(k,_,S);z0;)G--}L(k[_],O)===0?Ac(k,_,G):(G++,Ac(k,G,S)),G<=f&&(_=G+1),f<=G&&(S=G-1)}}function Ac(k,f,_){const S=k[f];k[f]=k[_],k[_]=S}function Wx(k,f){return kf?1:0}function O0(k){let f=0;for(let _,S,L=0,O=k.length,z=O-1;L=f[2]||k[1]<=f[1]||k[3]>=f[3])}function P1(k,f,_){const S=k[0]-f[0],L=k[1]-f[1],O=k[0]-_[0],z=k[1]-_[1];return S*z-O*L===0&&S*O<=0&&L*z<=0}function vu(k,f,_){return f[1]>k[1]!=_[1]>k[1]&&k[0]<(_[0]-f[0])*(k[1]-f[1])/(_[1]-f[1])+f[0]}function Zl(k,f,_=!1){let S=!1;for(let L=0,O=f.length;L0&&G<0||z<0&&G>0}function Go(k,f,_,S){return(L=[S[0]-_[0],S[1]-_[1]])[0]*(O=[f[0]-k[0],f[1]-k[1]])[1]-L[1]*O[0]!==0&&!(!tl(k,f,_,S)||!tl(_,S,k,f));var L,O}function Zd(k){const f=new Xt(Number.POSITIVE_INFINITY,Number.POSITIVE_INFINITY),_=new Xt(Number.NEGATIVE_INFINITY,Number.NEGATIVE_INFINITY);for(const S of k[0])f.x>S.x&&(f.x=S.x),f.y>S.y&&(f.y=S.y),_.x_[2]){const L=.5*S;let O=k[0]-_[0]>L?-S:_[0]-k[0]>L?S:0;O===0&&(O=k[0]-_[2]>L?-S:_[2]-k[0]>L?S:0),k[0]+=O}xh(f,k)}function z0(k,f,_,S){const L=Math.pow(2,S.z)*Jc,O=[S.x*Jc,S.y*Jc],z=[];if(!k)return z;for(const G of k)for(const Y of G){const re=[Y.x+O[0],Y.y+O[1]];bu(re,f,_,L),z.push(re)}return z}function Mw(k,f,_,S){const L=Math.pow(2,S.z)*Jc,O=[S.x*Jc,S.y*Jc],z=[];if(!k)return z;for(const Y of k){const re=[];for(const me of Y){const ye=[me.x+O[0],me.y+O[1]];xh(f,ye),re.push(ye)}z.push(re)}if(f[2]-f[0]<=L/2){(G=f)[0]=G[1]=1/0,G[2]=G[3]=-1/0;for(const Y of z)for(const re of Y)bu(re,f,_,L)}var G;return z}class B0{constructor(f,_){this.type=ri,this.geojson=f,this.geometries=_}static parse(f,_){if(f.length!==2)return _.error(`'within' expression requires exactly one argument, but found ${f.length-1} instead.`);if(Rf(f[1])){const S=f[1];if(S.type==="FeatureCollection")for(let L=0;L_)return e_(O,z,(_-(S-G))/G)}return f[f.length-1]}pointToSegmentDistance(f,_,S){let[L,O]=_,z=pp(S[0]-L)*this.kx,G=(S[1]-O)*this.ky;if(z!==0||G!==0){const Y=(pp(f[0]-L)*this.kx*z+(f[1]-O)*this.ky*G)/(z*z+G*G);Y>1?(L=S[0],O=S[1]):Y>0&&(L+=z/this.kx*Y,O+=G/this.ky*Y)}return z=pp(f[0]-L)*this.kx,G=(f[1]-O)*this.ky,Math.sqrt(z*z+G*G)}pointOnLine(f,_){let S=1/0,L=f[0][0],O=f[0][1],z=0,G=0;for(let Y=0;Y1?(re=f[Y+1][0],me=f[Y+1][1]):Te>0&&(re+=ye/this.kx*Te,me+=we/this.ky*Te)),ye=pp(_[0]-re)*this.kx,we=(_[1]-me)*this.ky;const Ie=ye*ye+we*we;IeO.index||L.index===O.index&&L.t>O.t){const re=L;L=O,O=re}const z=[L.point],G=L.index+1,Y=O.index;!w2(S[G],z[0])&&G<=Y&&z.push(S[G]);for(let re=G+1;re<=Y;re++)z.push(S[re]);return w2(S[Y],O.point)||z.push(O.point),z}lineSliceAlong(f,_,S){let L=0;const O=[];for(let z=0;zf&&O.length===0&&O.push(e_(G,Y,(f-(L-re))/re)),L>=_)return O.push(e_(G,Y,(_-(L-re))/re)),O;L>f&&O.push(Y)}return O}bufferPoint(f,_){const S=_/this.ky,L=_/this.kx;return[f[0]-L,f[1]-S,f[0]+L,f[1]+S]}bufferBBox(f,_){const S=_/this.ky,L=_/this.kx;return[f[0]-L,f[1]-S,f[2]+L,f[3]+S]}insideBBox(f,_){return pp(f[0]-_[0])>=0&&pp(f[0]-_[2])<=0&&f[1]>=_[1]&&f[1]<=_[3]}}function w2(k,f){return k[0]===f[0]&&k[1]===f[1]}function e_(k,f,_){const S=pp(f[0]-k[0]);return[k[0]+S*_,k[1]+(f[1]-k[1])*_]}function pp(k){for(;k<-180;)k+=360;for(;k>180;)k-=360;return k}class yh{constructor(f=[],_=(S,L)=>SL?1:0){if(this.data=f,this.length=this.data.length,this.compare=_,this.length>0)for(let S=(this.length>>1)-1;S>=0;S--)this._down(S)}push(f){this.data.push(f),this._up(this.length++)}pop(){if(this.length===0)return;const f=this.data[0],_=this.data.pop();return--this.length>0&&(this.data[0]=_,this._down(0)),f}peek(){return this.data[0]}_up(f){const{data:_,compare:S}=this,L=_[f];for(;f>0;){const O=f-1>>1,z=_[O];if(S(L,z)>=0)break;_[f]=z,f=O}_[f]=L}_down(f){const{data:_,compare:S}=this,L=this.length>>1,O=_[f];for(;f=0)break;_[f]=_[z],f=z}_[f]=O}}var lr=8192;function R1(k,f){return f.dist-k.dist}function O1(k){const f=[1/0,1/0,-1/0,-1/0];if(f.length!==k.length)return!1;for(let _=0;_=k[0]&&k[1]k[1])return[null,null];const _=Sv(k);if(f){if(_===2)return[k,null];const S=Math.floor(_/2);return[[k[0],k[0]+S],[k[0]+S,k[1]]]}{if(_===1)return[k,null];const S=Math.floor(_/2)-1;return[[k[0],k[0]+S],[k[0]+S+1,k[1]]]}}function $0(k,f){const _=[1/0,1/0,-1/0,-1/0];if(!Zp(f,k.length))return _;for(let S=f[0];S<=f[1];++S)xh(_,k[S]);return _}function t_(k){const f=[1/0,1/0,-1/0,-1/0];for(let _=0;_f[2]&&(S=k[0]-f[2]),k[1]>f[3]&&(L=k[1]-f[3]),k[3]=S)return S;if(Ff(L,O)){if(s_(k,f))return 0}else if(s_(f,k))return 0;let z=S;for(const G of k)for(let Y=0,re=G.length,me=re-1;Y=O)continue;const me=re.range1;if(Sv(me)<=G){if(!Zp(me,k.length))return NaN;if(f){const ye=Ec(k,me,_,S);if((O=Math.min(O,ye))===0)return O}else for(let ye=me[0];ye<=me[1];++ye){const we=MC(k[ye],_,S);if((O=Math.min(O,we))===0)return O}}else{const ye=Ly(me,f);if(ye[0]!==null){const we=Cv($0(k,ye[0]),Y,S);we=z)continue;const ye=me.range1,we=me.range2;if(Sv(ye)<=Y&&Sv(we)<=re){if(!Zp(ye,k.length)||!Zp(we,_.length))return NaN;if(f&&S?z=Math.min(z,rM(k,ye,_,we,L)):f||S?f&&!S?z=Math.min(z,mk(_,we,k,ye,L)):!f&&S&&(z=Math.min(z,mk(k,ye,_,we,L))):z=Math.min(z,Y5(k,ye,_,we,L)),z===0)return z}else{const Te=Ly(ye,f),Ie=Ly(we,S);F1(G,z,L,k,_,Te[0],Ie[0]),F1(G,z,L,k,_,Te[0],Ie[1]),F1(G,z,L,k,_,Te[1],Ie[0]),F1(G,z,L,k,_,Te[1],Ie[1])}}return z}function Pw(k,f,_,S,L=1/0){let O=L;const z=$0(k,[0,k.length-1]);for(const G of _)if(!(O!==1/0&&Cv(z,$0(G,[0,G.length-1]),S)>=O)&&(O=Math.min(O,qg(k,f,G,!0,S,O)),O===0))return O;return O}function n_(k,f,_,S,L=1/0){let O=L;const z=$0(k,[0,k.length-1]);for(const G of _){if(O!==1/0&&Cv(z,t_(G),S)>=O)continue;const Y=aM(k,f,G,S,O);if(isNaN(Y))return Y;if((O=Math.min(O,Y))===0)return O}return O}function pk(k){return k==="Point"||k==="MultiPoint"||k==="LineString"||k==="MultiLineString"||k==="Polygon"||k==="MultiPolygon"}class z1{constructor(f,_){this.type=sr,this.geojson=f,this.geometries=_}static parse(f,_){if(f.length!==2)return _.error(`'distance' expression requires either one argument, but found ' ${f.length-1} instead.`);if(Rf(f[1])){const S=f[1];if(S.type==="FeatureCollection"){for(let L=0;L{f&&!B1(_)&&(f=!1)}),f}function zf(k){if(k instanceof Qc&&k.name==="feature-state")return!1;let f=!0;return k.eachChild(_=>{f&&!zf(_)&&(f=!1)}),f}function eu(k,f){if(k instanceof Qc&&f.indexOf(k.name)>=0)return!1;let _=!0;return k.eachChild(S=>{_&&!eu(S,f)&&(_=!1)}),_}function Vg(k,f,_){return[k,f,_].filter(Boolean).join("")}function N2(k,f){switch(k){case"string":return Ma(f);case"number":return+f;case"boolean":return!!f;case"color":return Ys.parse(f);case"formatted":return cd.fromString(Ma(f));case"resolvedImage":return Pu.build(Ma(f))}return f}function X5(k,f,_,S){return S!==void 0&&(k=S*Math.round(k/S)),f!==void 0&&k_&&(k=_),k}class fx{constructor(f,_,S,L=!1){this.type=f,this.key=_,this.scope=S,this.featureConstant=L}static parse(f,_){let S=_.expectedType;if(S==null&&(S=Hi),f.length<2||f.length>3)return _.error("Invalid number of arguments for 'config' expression.");const L=_.parse(f[1],1);if(!(L instanceof qr))return _.error("Key name of 'config' expression must be a string literal.");let O,z=!0;const G=Ma(L.value);if(f.length>=3){const Y=_.parse(f[2],2);if(!(Y instanceof qr))return _.error("Scope of 'config' expression must be a string literal.");O=Ma(Y.value)}if(_.options){const Y=Vg(G,O,_._scope),re=_.options.get(Y);re&&(z=B1(re.value||re.default))}return new fx(S,G,O,z)}evaluate(f){const _=Vg(this.key,this.scope,f.scope),S=f.getConfig(_);if(!S)return null;const{type:L,value:O,values:z,minValue:G,maxValue:Y,stepValue:re}=S,me=S.default.evaluate(f);let ye=me;if(O){const we=f.scope;f.scope=(we||"").split("").slice(1).join(""),ye=O.evaluate(f),f.scope=we}return L&&(ye=N2(L,ye)),ye===void 0||G===void 0&&Y===void 0&&re===void 0||(typeof ye=="number"?ye=X5(ye,G,Y,re):Array.isArray(ye)&&(ye=ye.map(we=>typeof we=="number"?X5(we,G,Y,re):we))),O!==void 0&&ye!==void 0&&z&&!z.includes(ye)&&(ye=me,L&&(ye=N2(L,ye))),(L&&L!==this.type||ye!==void 0&&!up(kl(ye),this.type))&&(ye=N2(this.type.kind,ye)),ye}eachChild(){}outputDefined(){return!1}serialize(){const f=["config",this.key];return this.scope&&f.concat(this.scope),f}}class Xp{constructor(f,_){this.type=_.type,this.name=f,this.boundExpression=_}static parse(f,_){if(f.length!==2||typeof f[1]!="string")return _.error("'var' expression requires exactly one string literal argument.");const S=f[1];return _.scope.has(S)?new Xp(S,_.scope.get(S)):_.error(`Unknown variable "${S}". Make sure "${S}" has been bound in an enclosing "let" expression before using it.`,1)}evaluate(f){return this.boundExpression.evaluate(f)}eachChild(){}outputDefined(){return!1}serialize(){return["var",this.name]}}class k2{constructor(f,_=[],S,L=new Aa,O=[],z,G,Y){this.registry=f,this.path=_,this.key=_.map(re=>typeof re=="string"?`['${re}']`:`[${re}]`).join(""),this.scope=L,this.errors=O,this.expectedType=S,this._scope=z,this.options=G,this.iconImageUseTheme=Y}parse(f,_,S,L,O={}){return _||S?this.concat(_,null,S,L)._parse(f,O):this._parse(f,O)}parseObjectValue(f,_,S,L,O,z={}){return this.concat(_,S,L,O)._parse(f,z)}_parse(f,_){function S(L,O,z){return z==="assert"?new Pm(O,[L]):z==="coerce"?new hp(O,[L]):L}if(f!==null&&typeof f!="string"&&typeof f!="boolean"&&typeof f!="number"||(f=["literal",f]),Array.isArray(f)){if(f.length===0)return this.error('Expected an array with at least one element. If you wanted a literal array, use ["literal", []].');const L=typeof f[0]=="string"?this.registry[f[0]]:void 0;if(L){let O=L.parse(f,this);if(!O)return null;if(this.expectedType){const z=this.expectedType,G=O.type;if(z.kind!=="string"&&z.kind!=="number"&&z.kind!=="boolean"&&z.kind!=="object"&&z.kind!=="array"||G.kind!=="value")if(z.kind!=="color"&&z.kind!=="formatted"&&z.kind!=="resolvedImage"||G.kind!=="value"&&G.kind!=="string"){if(this.checkSubtype(z,G))return null}else O=S(O,z,_.typeAnnotation||"coerce");else O=S(O,z,_.typeAnnotation||"assert")}if(!(O instanceof qr)&&O.type.kind!=="resolvedImage"&&fk(O)){const z=new yu(this._scope,this.options,this.iconImageUseTheme);try{O=new qr(O.type,O.evaluate(z))}catch(G){return this.error(G.message),null}}return O}return hp.parse(["to-array",f],this)}return this.error(f===void 0?"'undefined' value invalid. Use null instead.":typeof f=="object"?'Bare objects invalid. Use ["literal", {...}] instead.':`Expected an array, but found ${typeof f} instead.`)}concat(f,_,S,L){let O=typeof f=="number"?this.path.concat(f):this.path;O=typeof _=="string"?O.concat(_):O;const z=L?this.scope.concat(L):this.scope;return new k2(this.registry,O,S||null,z,this.errors,this._scope,this.options,this.iconImageUseTheme)}error(f,..._){const S=`${this.key}${_.map(L=>`[${L}]`).join("")}`;this.errors.push(new Dr(S,f))}checkSubtype(f,_){const S=Hx(f,_);return S&&this.error(S),S}}function fk(k){if(k instanceof Xp)return fk(k.boundExpression);if(k instanceof Qc&&k.name==="error"||k instanceof Nv||k instanceof B0||k instanceof z1||k instanceof fx)return!1;const f=k instanceof hp||k instanceof Pm;let _=!0;return k.eachChild(S=>{_=f?_&&fk(S):_&&S instanceof qr}),!!_&&B1(k)&&eu(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 Iw(k,f){const _=k.length-1;let S,L,O=0,z=_,G=0;for(;O<=z;)if(G=Math.floor((O+z)/2),S=k[G],L=k[G+1],S<=f){if(G===_||ff))throw new Yl("Input is not a number.");z=G-1}return 0}class Dw{constructor(f,_,S){this.type=f,this.input=_,this.labels=[],this.outputs=[];for(const[L,O]of S)this.labels.push(L),this.outputs.push(O)}static parse(f,_){if(f.length-1<4)return _.error(`Expected at least 4 arguments, but found only ${f.length-1}.`);if((f.length-1)%2!=0)return _.error("Expected an even number of arguments.");const S=_.parse(f[1],1,sr);if(!S)return null;const L=[];let O=null;_.expectedType&&_.expectedType.kind!=="value"&&(O=_.expectedType);for(let z=1;z=G)return _.error('Input/output pairs for "step" expressions must be arranged with input values in strictly ascending order.',re);const ye=_.parse(Y,me,O);if(!ye)return null;O=O||ye.type,L.push([G,ye])}return new Dw(O,S,L)}evaluate(f){const _=this.labels,S=this.outputs;if(_.length===1)return S[0].evaluate(f);const L=this.input.evaluate(f);if(L<=_[0])return S[0].evaluate(f);const O=_.length;return L>=_[O-1]?S[O-1].evaluate(f):S[Iw(_,L)].evaluate(f)}eachChild(f){f(this.input);for(const _ of this.outputs)f(_)}outputDefined(){return this.outputs.every(f=>f.outputDefined())}serialize(){const f=["step",this.input.serialize()];for(let _=0;_0&&f.push(this.labels[_]),f.push(this.outputs[_].serialize());return f}}const Qp=.95047,fp=1.08883,Q5=4/29,Py=6/29,Rw=3*Py*Py,Ow=Py*Py*Py,xk=Math.PI/180,gk=180/Math.PI;function yk(k){return k>Ow?Math.pow(k,1/3):k/Rw+Q5}function Fw(k){return k>Py?k*k*k:Rw*(k-Q5)}function zw(k){return 255*(k<=.0031308?12.92*k:1.055*Math.pow(k,1/2.4)-.055)}function r_(k){return(k/=255)<=.04045?k/12.92:Math.pow((k+.055)/1.055,2.4)}function S2(k){const f=r_(k.r),_=r_(k.g),S=r_(k.b),L=yk((.4124564*f+.3575761*_+.1804375*S)/Qp),O=yk((.2126729*f+.7151522*_+.072175*S)/1);return{l:116*O-16,a:500*(L-O),b:200*(O-yk((.0193339*f+.119192*_+.9503041*S)/fp)),alpha:k.a}}function vk(k){let f=(k.l+16)/116,_=isNaN(k.a)?f:f+k.a/500,S=isNaN(k.b)?f:f-k.b/200;return f=1*Fw(f),_=Qp*Fw(_),S=fp*Fw(S),new Ys(zw(3.2404542*_-1.5371385*f-.4985314*S),zw(-.969266*_+1.8760108*f+.041556*S),zw(.0556434*_-.2040259*f+1.0572252*S),k.alpha)}function LC(k,f,_){const S=f-k;return k+_*(S>180||S<-180?S-360*Math.round(S/360):S)}const a_={forward:S2,reverse:vk,interpolate:function(k,f,_){return{l:Cs(k.l,f.l,_),a:Cs(k.a,f.a,_),b:Cs(k.b,f.b,_),alpha:Cs(k.alpha,f.alpha,_)}}},Iy={forward:function(k){const{l:f,a:_,b:S}=S2(k),L=Math.atan2(S,_)*gk;return{h:L<0?L+360:L,c:Math.sqrt(_*_+S*S),l:f,alpha:k.a}},reverse:function(k){const f=k.h*xk,_=k.c;return vk({l:k.l,a:Math.cos(f)*_,b:Math.sin(f)*_,alpha:k.alpha})},interpolate:function(k,f,_){return{h:LC(k.h,f.h,_),c:Cs(k.c,f.c,_),l:Cs(k.l,f.l,_),alpha:Cs(k.alpha,f.alpha,_)}}};var Bw=Object.freeze({__proto__:null,hcl:Iy,lab:a_});class cm{constructor(f,_,S,L,O){this.type=f,this.operator=_,this.interpolation=S,this.input=L,this.labels=[],this.outputs=[];for(const[z,G]of O)this.labels.push(z),this.outputs.push(G)}static interpolationFactor(f,_,S,L){let O=0;if(f.name==="exponential")O=$w(_,f.base,S,L);else if(f.name==="linear")O=$w(_,1,S,L);else if(f.name==="cubic-bezier"){const z=f.controlPoints;O=new Zn(z[0],z[1],z[2],z[3]).solve($w(_,1,S,L))}return O}static parse(f,_){let[S,L,O,...z]=f;if(!Array.isArray(L)||L.length===0)return _.error("Expected an interpolation type expression.",1);if(L[0]==="linear")L={name:"linear"};else if(L[0]==="exponential"){const re=L[1];if(typeof re!="number")return _.error("Exponential interpolation requires a numeric base.",1,1);L={name:"exponential",base:re}}else{if(L[0]!=="cubic-bezier")return _.error(`Unknown interpolation type ${String(L[0])}`,1,0);{const re=L.slice(1);if(re.length!==4||re.some(me=>typeof me!="number"||me<0||me>1))return _.error("Cubic bezier interpolation requires four numeric arguments with values between 0 and 1.",1);L={name:"cubic-bezier",controlPoints:re}}}if(f.length-1<4)return _.error(`Expected at least 4 arguments, but found only ${f.length-1}.`);if(f.length-1>3&&(f.length-1)%2!=0)return _.error("Expected an even number of arguments.");if(O=_.parse(O,2,sr),!O)return null;const G=[];let Y=null;S==="interpolate-hcl"||S==="interpolate-lab"?Y=Ho:_.expectedType&&_.expectedType.kind!=="value"&&(Y=_.expectedType);for(let re=0;re=me)return _.error('Input/output pairs for "interpolate" expressions must be arranged with input values in strictly ascending order.',we);const Ie=_.parse(ye,Te,Y);if(!Ie)return null;Y=Y||Ie.type,G.push([me,Ie])}return Y.kind==="number"||Y.kind==="color"||Y.kind==="array"&&Y.itemType.kind==="number"&&typeof Y.N=="number"?new cm(Y,S,L,O,G):_.error(`Type ${tc(Y)} is not interpolatable.`)}evaluate(f){const _=this.labels,S=this.outputs;if(_.length===1)return S[0].evaluate(f);const L=this.input.evaluate(f);if(L<=_[0])return S[0].evaluate(f);const O=_.length;if(L>=_[O-1])return S[O-1].evaluate(f);const z=Iw(_,L),G=cm.interpolationFactor(this.interpolation,L,_[z],_[z+1]),Y=S[z].evaluate(f),re=S[z+1].evaluate(f);return this.operator==="interpolate"?Rr[this.type.kind.toLowerCase()](Y,re,G):this.operator==="interpolate-hcl"?Iy.reverse(Iy.interpolate(Iy.forward(Y),Iy.forward(re),G)):a_.reverse(a_.interpolate(a_.forward(Y),a_.forward(re),G))}eachChild(f){f(this.input);for(const _ of this.outputs)f(_)}outputDefined(){return this.outputs.every(f=>f.outputDefined())}serialize(){let f;f=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,f,this.input.serialize()];for(let S=0;SHx(L,G.type));return new i_(z?Hi:S,O)}evaluate(f){let _,S=null,L=0;for(const O of this.args){if(L++,S=O.evaluate(f),S&&S instanceof Pu&&!S.available&&(_||(_=S),S=null,L===this.args.length))return _;if(S!==null)break}return S}eachChild(f){this.args.forEach(f)}outputDefined(){return this.args.every(f=>f.outputDefined())}serialize(){const f=["coalesce"];return this.eachChild(_=>{f.push(_.serialize())}),f}}class Ce{constructor(f,_){this.type=_.type,this.bindings=[].concat(f),this.result=_}evaluate(f){return this.result.evaluate(f)}eachChild(f){for(const _ of this.bindings)f(_[1]);f(this.result)}static parse(f,_){if(f.length<4)return _.error(`Expected at least 3 arguments, but found ${f.length-1} instead.`);const S=[];for(let O=1;O=S.length)throw new Yl("Array index out of bounds: index exceeds array size");if(_!==Math.floor(_))throw new Yl("Array index must be an integer. Use at-interpolated for fractional indices");return S[_]}eachChild(f){f(this.index),f(this.input)}outputDefined(){return!1}serialize(){return["at",this.index.serialize(),this.input.serialize()]}}class mt{constructor(f,_,S){this.type=f,this.index=_,this.input=S}static parse(f,_){if(f.length!==3)return _.error(`Expected 2 arguments, but found ${f.length-1} instead.`);const S=_.parse(f[1],1,sr),L=_.parse(f[2],2,gu(_.expectedType||Hi));return S&&L?new mt(L.type.itemType,S,L):null}evaluate(f){const _=this.index.evaluate(f),S=this.input.evaluate(f);if(_<0)throw new Yl(`Array index out of bounds: ${_} < 0.`);if(_>S.length-1)throw new Yl(`Array index out of bounds: ${_} > ${S.length-1}.`);if(_===Math.floor(_))return S[_];const L=Math.floor(_),O=Math.ceil(_),z=S[L],G=S[O];if(typeof z!="number"||typeof G!="number")throw new Yl(`Cannot interpolate between non-number values at index ${_}.`);const Y=_-L;return z*(1-Y)+G*Y}eachChild(f){f(this.index),f(this.input)}outputDefined(){return!1}serialize(){return["at-interpolated",this.index.serialize(),this.input.serialize()]}}class bt{constructor(f,_){this.type=ri,this.needle=f,this.haystack=_}static parse(f,_){if(f.length!==3)return _.error(`Expected 2 arguments, but found ${f.length-1} instead.`),null;const S=_.parse(f[1],1,Hi),L=_.parse(f[2],2,Hi);return S&&L?I0(S.type,[ri,Ra,sr,Ua,Hi])?new bt(S,L):(_.error(`Expected first argument to be of type boolean, string, number or null, but found ${tc(S.type)} instead`),null):null}evaluate(f){const _=this.needle.evaluate(f),S=this.haystack.evaluate(f);if(S==null)return!1;if(!Yd(_,["boolean","string","number","null"]))throw new Yl(`Expected first argument to be of type boolean, string, number or null, but found ${tc(kl(_))} instead.`);if(!Yd(S,["string","array"]))throw new Yl(`Expected second argument to be of type array or string, but found ${tc(kl(S))} instead.`);return S.indexOf(_)>=0}eachChild(f){f(this.needle),f(this.haystack)}outputDefined(){return!0}serialize(){return["in",this.needle.serialize(),this.haystack.serialize()]}}class Yt{constructor(f,_,S){this.type=sr,this.needle=f,this.haystack=_,this.fromIndex=S}static parse(f,_){if(f.length<=2||f.length>=5)return _.error(`Expected 3 or 4 arguments, but found ${f.length-1} instead.`),null;const S=_.parse(f[1],1,Hi),L=_.parse(f[2],2,Hi);if(!S||!L)return null;if(!I0(S.type,[ri,Ra,sr,Ua,Hi]))return _.error(`Expected first argument to be of type boolean, string, number or null, but found ${tc(S.type)} instead`),null;if(f.length===4){const O=_.parse(f[3],3,sr);return O?new Yt(S,L,O):null}return new Yt(S,L)}evaluate(f){const _=this.needle.evaluate(f),S=this.haystack.evaluate(f);if(!Yd(_,["boolean","string","number","null"]))throw new Yl(`Expected first argument to be of type boolean, string, number or null, but found ${tc(kl(_))} instead.`);if(!Yd(S,["string","array"]))throw new Yl(`Expected second argument to be of type array or string, but found ${tc(kl(S))} instead.`);if(this.fromIndex){const L=this.fromIndex.evaluate(f);return S.indexOf(_,L)}return S.indexOf(_)}eachChild(f){f(this.needle),f(this.haystack),this.fromIndex&&f(this.fromIndex)}outputDefined(){return!1}serialize(){if(this.fromIndex!=null&&this.fromIndex!==void 0){const f=this.fromIndex.serialize();return["index-of",this.needle.serialize(),this.haystack.serialize(),f]}return["index-of",this.needle.serialize(),this.haystack.serialize()]}}class ls{constructor(f,_,S,L,O,z){this.inputType=f,this.type=_,this.input=S,this.cases=L,this.outputs=O,this.otherwise=z}static parse(f,_){if(f.length<5)return _.error(`Expected at least 4 arguments, but found only ${f.length-1}.`);if(f.length%2!=1)return _.error("Expected an even number of arguments.");let S,L;_.expectedType&&_.expectedType.kind!=="value"&&(L=_.expectedType);const O={},z=[];for(let re=2;reNumber.MAX_SAFE_INTEGER)return we.error(`Branch labels must be integers no larger than ${Number.MAX_SAFE_INTEGER}.`);if(typeof Ie=="number"&&Math.floor(Ie)!==Ie)return we.error("Numeric branch labels must be integer values.");if(S){if(we.checkSubtype(S,kl(Ie)))return null}else S=kl(Ie);if(O[String(Ie)]!==void 0)return we.error("Branch labels must be unique.");O[String(Ie)]=z.length}const Te=_.parse(ye,re,L);if(!Te)return null;L=L||Te.type,z.push(Te)}const G=_.parse(f[1],1,Hi);if(!G)return null;const Y=_.parse(f[f.length-1],f.length-1,L);return Y?G.type.kind!=="value"&&_.concat(1).checkSubtype(S,G.type)?null:new ls(S,L,G,O,z,Y):null}evaluate(f){const _=this.input.evaluate(f);return(up(kl(_),this.inputType)&&this.outputs[this.cases[_]]||this.otherwise).evaluate(f)}eachChild(f){f(this.input),this.outputs.forEach(f),f(this.otherwise)}outputDefined(){return this.outputs.every(f=>f.outputDefined())&&this.otherwise.outputDefined()}serialize(){const f=["match",this.input.serialize()],_=Object.keys(this.cases).sort(),S=[],L={};for(const z of _){const G=L[this.cases[z]];G===void 0?(L[this.cases[z]]=S.length,S.push([this.cases[z],[z]])):S[G][1].push(z)}const O=z=>this.inputType.kind==="number"?Number(z):z;for(const[z,G]of S)f.push(G.length===1?O(G[0]):G.map(O)),f.push(this.outputs[z].serialize());return f.push(this.otherwise.serialize()),f}}class ps{constructor(f,_,S){this.type=f,this.branches=_,this.otherwise=S}static parse(f,_){if(f.length<4)return _.error(`Expected at least 3 arguments, but found only ${f.length-1}.`),null;if(f.length%2!=0)return _.error("Expected an odd number of arguments."),null;let S;_.expectedType&&_.expectedType.kind!=="value"&&(S=_.expectedType);const L=[];for(let z=1;z_.outputDefined())&&this.otherwise.outputDefined()}serialize(){const f=["case"];return this.eachChild(_=>{f.push(_.serialize())}),f}}class Ss{constructor(f,_,S,L){this.type=f,this.input=_,this.beginIndex=S,this.endIndex=L}static parse(f,_){if(f.length<=2||f.length>=5)return _.error(`Expected 3 or 4 arguments, but found ${f.length-1} instead.`),null;const S=_.parse(f[1],1,Hi),L=_.parse(f[2],2,sr);if(!S||!L)return null;if(!I0(S.type,[gu(Hi),Ra,Hi]))return _.error(`Expected first argument to be of type array or string, but found ${tc(S.type)} instead`),null;if(f.length===4){const O=_.parse(f[3],3,sr);return O?new Ss(S.type,S,L,O):null}return new Ss(S.type,S,L)}evaluate(f){const _=this.input.evaluate(f),S=this.beginIndex.evaluate(f);if(!Yd(_,["string","array"]))throw new Yl(`Expected first argument to be of type array or string, but found ${tc(kl(_))} instead.`);if(this.endIndex){const L=this.endIndex.evaluate(f);return _.slice(S,L)}return _.slice(S)}eachChild(f){f(this.input),f(this.beginIndex),this.endIndex&&f(this.endIndex)}outputDefined(){return!1}serialize(){if(this.endIndex!=null&&this.endIndex!==void 0){const f=this.endIndex.serialize();return["slice",this.input.serialize(),this.beginIndex.serialize(),f]}return["slice",this.input.serialize(),this.beginIndex.serialize()]}}class Es{constructor(f,_){this.type=gu(Ra),this.str=f,this.delimiter=_}static parse(f,_){if(f.length!==3)return _.error(`Expected 2 arguments, but found ${f.length-1} instead.`);const S=_.parse(f[1],1,Ra),L=_.parse(f[2],2,Ra);return S&&L?new Es(S,L):void 0}evaluate(f){const _=this.str.evaluate(f),S=this.delimiter.evaluate(f);return _.split(S)}eachChild(f){f(this.str),f(this.delimiter)}outputDefined(){return!1}serialize(){return["split",this.str.serialize(),this.delimiter.serialize()]}}function Qs(k,f){return k==="=="||k==="!="?f.kind==="boolean"||f.kind==="string"||f.kind==="number"||f.kind==="null"||f.kind==="value":f.kind==="string"||f.kind==="number"||f.kind==="value"}function Cn(k,f,_,S){return S.compare(f,_)===0}function Xn(k,f,_){const S=k!=="=="&&k!=="!=";return class CAt{constructor(O,z,G){this.type=ri,this.lhs=O,this.rhs=z,this.collator=G,this.hasUntypedArgument=O.type.kind==="value"||z.type.kind==="value"}static parse(O,z){if(O.length!==3&&O.length!==4)return z.error("Expected two or three arguments.");const G=O[0];let Y=z.parse(O[1],1,Hi);if(!Y)return null;if(!Qs(G,Y.type))return z.concat(1).error(`"${G}" comparisons are not supported for type '${tc(Y.type)}'.`);let re=z.parse(O[2],2,Hi);if(!re)return null;if(!Qs(G,re.type))return z.concat(2).error(`"${G}" comparisons are not supported for type '${tc(re.type)}'.`);if(Y.type.kind!==re.type.kind&&Y.type.kind!=="value"&&re.type.kind!=="value")return z.error(`Cannot compare types '${tc(Y.type)}' and '${tc(re.type)}'.`);S&&(Y.type.kind==="value"&&re.type.kind!=="value"?Y=new Pm(re.type,[Y]):Y.type.kind!=="value"&&re.type.kind==="value"&&(re=new Pm(Y.type,[re])));let me=null;if(O.length===4){if(Y.type.kind!=="string"&&re.type.kind!=="string"&&Y.type.kind!=="value"&&re.type.kind!=="value")return z.error("Cannot use collator to compare non-string types.");if(me=z.parse(O[3],3,lm),!me)return null}return new CAt(Y,re,me)}evaluate(O){const z=this.lhs.evaluate(O),G=this.rhs.evaluate(O);if(S&&this.hasUntypedArgument){const Y=kl(z),re=kl(G);if(Y.kind!==re.kind||Y.kind!=="string"&&Y.kind!=="number")throw new Yl(`Expected arguments for "${k}" to be (string, string) or (number, number), but found (${Y.kind}, ${re.kind}) instead.`)}if(this.collator&&!S&&this.hasUntypedArgument){const Y=kl(z),re=kl(G);if(Y.kind!=="string"||re.kind!=="string")return f(O,z,G)}return this.collator?_(O,z,G,this.collator.evaluate(O)):f(O,z,G)}eachChild(O){O(this.lhs),O(this.rhs),this.collator&&O(this.collator)}outputDefined(){return!0}serialize(){const O=[k];return this.eachChild(z=>{O.push(z.serialize())}),O}}}const Js=Xn("==",function(k,f,_){return f===_},Cn),On=Xn("!=",function(k,f,_){return f!==_},function(k,f,_,S){return!Cn(0,f,_,S)}),nr=Xn("<",function(k,f,_){return f<_},function(k,f,_,S){return S.compare(f,_)<0}),Mr=Xn(">",function(k,f,_){return f>_},function(k,f,_,S){return S.compare(f,_)>0}),xr=Xn("<=",function(k,f,_){return f<=_},function(k,f,_,S){return S.compare(f,_)<=0}),Fn=Xn(">=",function(k,f,_){return f>=_},function(k,f,_,S){return S.compare(f,_)>=0});class $r{constructor(f,_,S,L,O,z){this.type=Ra,this.number=f,this.locale=_,this.currency=S,this.unit=L,this.minFractionDigits=O,this.maxFractionDigits=z}static parse(f,_){if(f.length!==3)return _.error("Expected two arguments.");const S=_.parse(f[1],1,sr);if(!S)return null;const L=f[2];if(typeof L!="object"||Array.isArray(L))return _.error("NumberFormat options argument must be an object.");let O=null;if(L.locale&&(O=_.parseObjectValue(L.locale,2,"locale",Ra),!O))return null;let z=null;if(L.currency&&(z=_.parseObjectValue(L.currency,2,"currency",Ra),!z))return null;let G=null;if(L.unit&&(G=_.parseObjectValue(L.unit,2,"unit",Ra),!G))return null;let Y=null;if(L["min-fraction-digits"]&&(Y=_.parseObjectValue(L["min-fraction-digits"],2,"min-fraction-digits",sr),!Y))return null;let re=null;return L["max-fraction-digits"]&&(re=_.parseObjectValue(L["max-fraction-digits"],2,"max-fraction-digits",sr),!re)?null:new $r(S,O,z,G,Y,re)}evaluate(f){return new Intl.NumberFormat(this.locale?this.locale.evaluate(f):[],{style:(this.currency?"currency":this.unit&&"unit")||"decimal",currency:this.currency?this.currency.evaluate(f):void 0,unit:this.unit?this.unit.evaluate(f):void 0,minimumFractionDigits:this.minFractionDigits?this.minFractionDigits.evaluate(f):void 0,maximumFractionDigits:this.maxFractionDigits?this.maxFractionDigits.evaluate(f):void 0}).format(this.number.evaluate(f))}eachChild(f){f(this.number),this.locale&&f(this.locale),this.currency&&f(this.currency),this.unit&&f(this.unit),this.minFractionDigits&&f(this.minFractionDigits),this.maxFractionDigits&&f(this.maxFractionDigits)}outputDefined(){return!1}serialize(){const f={};return this.locale&&(f.locale=this.locale.serialize()),this.currency&&(f.currency=this.currency.serialize()),this.unit&&(f.unit=this.unit.serialize()),this.minFractionDigits&&(f["min-fraction-digits"]=this.minFractionDigits.serialize()),this.maxFractionDigits&&(f["max-fraction-digits"]=this.maxFractionDigits.serialize()),["number-format",this.number.serialize(),f]}}class ba{constructor(f){this.type=sr,this.input=f}static parse(f,_){if(f.length!==2)return _.error(`Expected 1 argument, but found ${f.length-1} instead.`),null;const S=_.parse(f[1],1);return S?S.type.kind!=="array"&&S.type.kind!=="string"&&S.type.kind!=="value"?(_.error(`Expected argument of type string or array, but found ${tc(S.type)} instead.`),null):new ba(S):null}evaluate(f){const _=this.input.evaluate(f);if(typeof _=="string"||Array.isArray(_))return _.length;throw new Yl(`Expected value to be of type string or array, but found ${tc(kl(_))} instead.`)}eachChild(f){f(this.input)}outputDefined(){return!1}serialize(){const f=["length"];return this.eachChild(_=>{f.push(_.serialize())}),f}}function fa(k){return function(){k=1831565813+(k|=0)|0;let f=Math.imul(k^k>>>15,1|k);return f=f+Math.imul(f^f>>>7,61|f)^f,((f^f>>>14)>>>0)/4294967296}}const Fi={"==":Js,"!=":On,">":Mr,"<":nr,">=":Fn,"<=":xr,array:Pm,at:Fe,"at-interpolated":mt,boolean:Pm,case:ps,coalesce:i_,collator:Nv,format:dd,image:pa,in:bt,"index-of":Yt,interpolate:cm,"interpolate-hcl":cm,"interpolate-lab":cm,length:ba,let:Ce,literal:qr,match:ls,number:Pm,"number-format":$r,object:Pm,slice:Ss,step:Dw,string:Pm,"to-boolean":hp,"to-color":hp,"to-number":hp,"to-string":hp,var:Xp,within:B0,distance:z1,config:fx,split:Es};function bi(k,[f,_,S,L]){f=f.evaluate(k),_=_.evaluate(k),S=S.evaluate(k);const O=L?L.evaluate(k):1,z=Lm(f,_,S,O);if(z)throw new Yl(z);return new Ys(f/255,_/255,S/255,O)}function sl(k,[f,_,S,L]){f=f.evaluate(k),_=_.evaluate(k),S=S.evaluate(k);const O=L?L.evaluate(k):1,z=function(re,me,ye,we){return typeof re=="number"&&re>=0&&re<=360?typeof me=="number"&&me>=0&&me<=100&&typeof ye=="number"&&ye>=0&&ye<=100?we===void 0||typeof we=="number"&&we>=0&&we<=1?null:`Invalid hsla value [${[re,me,ye,we].join(", ")}]: 'a' must be between 0 and 1.`:`Invalid hsla value [${(typeof we=="number"?[re,me,ye,we]:[re,me,ye]).join(", ")}]: 's', and 'l' must be between 0 and 100.`:`Invalid hsla value [${(typeof we=="number"?[re,me,ye,we]:[re,me,ye]).join(", ")}]: 'h' must be between 0 and 360.`}(f,_,S,O);if(z)throw new Yl(z);const G=`hsla(${f}, ${_}%, ${S}%, ${O})`,Y=Ys.parse(G);if(!Y)throw new Yl(`Failed to parse HSLA color: ${G}`);return Y}function Li(k,f){return k in f}function Dl(k,f){const _=f[k];return _===void 0?null:_}function Pd(k){return{type:k}}function nl(k){if(k instanceof fx)return new Set([k.key]);let f=new Set;return k.eachChild(_=>{f=new Set([...f,...nl(_)])}),f}function Di(k){if(k instanceof Qc&&k.name==="is-active-floor")return!0;let f=!1;return k.eachChild(_=>{!f&&Di(_)&&(f=!0)}),f}function ti(k){return{result:"success",value:k}}function ol(k){return{result:"error",value:k}}function co(k,f){return!!k&&!!k.parameters&&k.parameters.indexOf(f)>-1}function Yo(k){return k["property-type"]==="data-driven"}function jd(k){return co(k.expression,"measure-light")}function Oh(k){return co(k.expression,"zoom")}function Nd(k){return!!k.expression&&k.expression.interpolated}function tu(k){return typeof k=="object"&&k!==null&&!Array.isArray(k)}function Xd(k){return k}function Jp(k,f){const _=f.type==="color",S=k.stops&&typeof k.stops[0][0]=="object",L=S||!(S||k.property!==void 0),O=k.type||(Nd(f)?"exponential":"interval");if(_&&((k=Object.assign({},k)).stops&&(k.stops=k.stops.map(re=>[re[0],Ys.parse(re[1])])),k.default=Ys.parse(k.default?k.default:f.default)),k.colorSpace&&k.colorSpace!=="rgb"&&!Bw[k.colorSpace])throw new Error(`Unknown color space: ${k.colorSpace}`);let z,G,Y;if(O==="exponential")z=_u;else if(O==="interval")z=ed;else if(O==="categorical"){z=gc,G=Object.create(null);for(const re of k.stops)G[re[0]]=re[1];Y=typeof k.stops[0][0]}else{if(O!=="identity")throw new Error(`Unknown function type "${O}"`);z=Tc}if(S){const re={},me=[];for(let Te=0;TeTe[0]),evaluate:({zoom:Te},Ie)=>_u({stops:ye,base:k.base},f,Te).evaluate(Te,Ie)}}if(L){const re=O==="exponential"?{name:"exponential",base:k.base!==void 0?k.base:1}:null;return{kind:"camera",interpolationType:re,interpolationFactor:cm.interpolationFactor.bind(void 0,re),zoomStops:k.stops.map(me=>me[0]),evaluate:({zoom:me})=>z(k,f,me,G,Y)}}return{kind:"source",evaluate(re,me){const ye=me&&me.properties?me.properties[k.property]:void 0;return ye===void 0?ud(k.default,f.default):z(k,f,ye,G,Y)}}}function ud(k,f,_){return k!==void 0?k:f!==void 0?f:_!==void 0?_:void 0}function gc(k,f,_,S,L){return ud(typeof _===L?S[_]:void 0,k.default,f.default)}function ed(k,f,_){if(!R0(_))return ud(k.default,f.default);const S=k.stops.length;if(S===1||_<=k.stops[0][0])return k.stops[0][1];if(_>=k.stops[S-1][0])return k.stops[S-1][1];const L=Iw(k.stops.map(O=>O[0]),_);return k.stops[L][1]}function _u(k,f,_){const S=k.base!==void 0?k.base:1;if(!R0(_))return ud(k.default,f.default);const L=k.stops.length;if(L===1||_<=k.stops[0][0])return k.stops[0][1];if(_>=k.stops[L-1][0])return k.stops[L-1][1];const O=Iw(k.stops.map(me=>me[0]),_),z=function(me,ye,we,Te){const Ie=Te-we,Ve=me-we;return Ie===0?0:ye===1?Ve/Ie:(Math.pow(ye,Ve)-1)/(Math.pow(ye,Ie)-1)}(_,S,k.stops[O][0],k.stops[O+1][0]),G=k.stops[O][1],Y=k.stops[O+1][1];let re=Rr[f.type]||Xd;if(k.colorSpace&&k.colorSpace!=="rgb"){const me=Bw[k.colorSpace];re=(ye,we)=>me.reverse(me.interpolate(me.forward(ye),me.forward(we),z))}return typeof G.evaluate=="function"?{evaluate(...me){const ye=G.evaluate.apply(void 0,me),we=Y.evaluate.apply(void 0,me);if(ye!==void 0&&we!==void 0)return re(ye,we,z)}}:re(G,Y,z)}function Tc(k,f,_){return f.type==="color"?_=Ys.parse(_):f.type==="formatted"?_=cd.fromString(_.toString()):f.type==="resolvedImage"?_=Pu.build(_.toString()):Gx(_)===f.type||f.type==="enum"&&f.values[_]||(_=void 0),ud(_,k.default,f.default)}Qc.register(Fi,{error:[{kind:"error"},[Ra],(k,[f])=>{throw new Yl(f.evaluate(k))}],typeof:[Ra,[Hi],(k,[f])=>tc(kl(f.evaluate(k)))],"to-rgba":[gu(sr,4),[Ho],(k,[f])=>f.evaluate(k).toNonPremultipliedRenderColor(null).toArray()],"to-hsla":[gu(sr,4),[Ho],(k,[f])=>f.evaluate(k).toNonPremultipliedRenderColor(null).toHslaArray()],rgb:[Ho,[sr,sr,sr],bi],rgba:[Ho,[sr,sr,sr,sr],bi],hsl:[Ho,[sr,sr,sr],sl],hsla:[Ho,[sr,sr,sr,sr],sl],has:{type:ri,overloads:[[[Ra],(k,[f])=>Li(f.evaluate(k),k.properties())],[[Ra,Kl],(k,[f,_])=>Li(f.evaluate(k),_.evaluate(k))]]},get:{type:Hi,overloads:[[[Ra],(k,[f])=>Dl(f.evaluate(k),k.properties())],[[Ra,Kl],(k,[f,_])=>Dl(f.evaluate(k),_.evaluate(k))]]},"feature-state":[Hi,[Ra],(k,[f])=>Dl(f.evaluate(k),k.featureState||{})],properties:[Kl,[],k=>k.properties()],"geometry-type":[Ra,[],k=>k.geometryType()],worldview:[Ra,[],k=>k.globals.worldview||""],"is-active-floor":[ri,Pd(Ra),(k,f)=>{if(!(k.globals&&k.globals.activeFloors&&k.globals.activeFloors.size>0))return!1;if(f.length===0)return!0;const _=k.globals.activeFloors;return f.some(S=>{const L=S.evaluate(k);return _.has(L)})}],id:[Hi,[],k=>k.id()],zoom:[sr,[],k=>k.globals.zoom],pitch:[sr,[],k=>k.globals.pitch||0],"distance-from-center":[sr,[],k=>k.distanceFromCenter()],"measure-light":[sr,[Ra],(k,[f])=>k.measureLight(f.evaluate(k))],"heatmap-density":[sr,[],k=>k.globals.heatmapDensity||0],"line-progress":[sr,[],k=>k.globals.lineProgress||0],"raster-value":[sr,[],k=>k.globals.rasterValue||0],"raster-particle-speed":[sr,[],k=>k.globals.rasterParticleSpeed||0],"sky-radial-progress":[sr,[],k=>k.globals.skyRadialProgress||0],accumulated:[Hi,[],k=>k.globals.accumulated===void 0?null:k.globals.accumulated],"+":[sr,Pd(sr),(k,f)=>{let _=0;for(const S of f)_+=S.evaluate(k);return _}],"*":[sr,Pd(sr),(k,f)=>{let _=1;for(const S of f)_*=S.evaluate(k);return _}],"-":{type:sr,overloads:[[[sr,sr],(k,[f,_])=>f.evaluate(k)-_.evaluate(k)],[[sr],(k,[f])=>-f.evaluate(k)]]},"/":[sr,[sr,sr],(k,[f,_])=>f.evaluate(k)/_.evaluate(k)],"%":[sr,[sr,sr],(k,[f,_])=>f.evaluate(k)%_.evaluate(k)],ln2:[sr,[],()=>Math.LN2],pi:[sr,[],()=>Math.PI],e:[sr,[],()=>Math.E],"^":[sr,[sr,sr],(k,[f,_])=>Math.pow(f.evaluate(k),_.evaluate(k))],sqrt:[sr,[sr],(k,[f])=>Math.sqrt(f.evaluate(k))],log10:[sr,[sr],(k,[f])=>Math.log(f.evaluate(k))/Math.LN10],ln:[sr,[sr],(k,[f])=>Math.log(f.evaluate(k))],log2:[sr,[sr],(k,[f])=>Math.log2(f.evaluate(k))],sin:[sr,[sr],(k,[f])=>Math.sin(f.evaluate(k))],cos:[sr,[sr],(k,[f])=>Math.cos(f.evaluate(k))],tan:[sr,[sr],(k,[f])=>Math.tan(f.evaluate(k))],asin:[sr,[sr],(k,[f])=>Math.asin(f.evaluate(k))],acos:[sr,[sr],(k,[f])=>Math.acos(f.evaluate(k))],atan:[sr,[sr],(k,[f])=>Math.atan(f.evaluate(k))],min:[sr,Pd(sr),(k,f)=>Math.min(...f.map(_=>_.evaluate(k)))],max:[sr,Pd(sr),(k,f)=>Math.max(...f.map(_=>_.evaluate(k)))],abs:[sr,[sr],(k,[f])=>Math.abs(f.evaluate(k))],round:[sr,[sr],(k,[f])=>{const _=f.evaluate(k);return _<0?-Math.round(-_):Math.round(_)}],floor:[sr,[sr],(k,[f])=>Math.floor(f.evaluate(k))],ceil:[sr,[sr],(k,[f])=>Math.ceil(f.evaluate(k))],"filter-==":[ri,[Ra,Hi],(k,[f,_])=>k.properties()[f.value]===_.value],"filter-id-==":[ri,[Hi],(k,[f])=>k.id()===f.value],"filter-type-==":[ri,[Ra],(k,[f])=>k.geometryType()===f.value],"filter-<":[ri,[Ra,Hi],(k,[f,_])=>{const S=k.properties()[f.value],L=_.value;return typeof S==typeof L&&S{const _=k.id(),S=f.value;return typeof _==typeof S&&_":[ri,[Ra,Hi],(k,[f,_])=>{const S=k.properties()[f.value],L=_.value;return typeof S==typeof L&&S>L}],"filter-id->":[ri,[Hi],(k,[f])=>{const _=k.id(),S=f.value;return typeof _==typeof S&&_>S}],"filter-<=":[ri,[Ra,Hi],(k,[f,_])=>{const S=k.properties()[f.value],L=_.value;return typeof S==typeof L&&S<=L}],"filter-id-<=":[ri,[Hi],(k,[f])=>{const _=k.id(),S=f.value;return typeof _==typeof S&&_<=S}],"filter->=":[ri,[Ra,Hi],(k,[f,_])=>{const S=k.properties()[f.value],L=_.value;return typeof S==typeof L&&S>=L}],"filter-id->=":[ri,[Hi],(k,[f])=>{const _=k.id(),S=f.value;return typeof _==typeof S&&_>=S}],"filter-has":[ri,[Hi],(k,[f])=>f.value in k.properties()],"filter-has-id":[ri,[],k=>k.id()!==null&&k.id()!==void 0],"filter-type-in":[ri,[gu(Ra)],(k,[f])=>f.value.indexOf(k.geometryType())>=0],"filter-id-in":[ri,[gu(Hi)],(k,[f])=>f.value.indexOf(k.id())>=0],"filter-in-small":[ri,[Ra,gu(Hi)],(k,[f,_])=>_.value.indexOf(k.properties()[f.value])>=0],"filter-in-large":[ri,[Ra,gu(Hi)],(k,[f,_])=>function(S,L,O,z){for(;O<=z;){const G=O+z>>1;if(L[G]===S)return!0;L[G]>S?z=G-1:O=G+1}return!1}(k.properties()[f.value],_.value,0,_.value.length-1)],all:{type:ri,overloads:[[[ri,ri],(k,[f,_])=>f.evaluate(k)&&_.evaluate(k)],[Pd(ri),(k,f)=>{for(const _ of f)if(!_.evaluate(k))return!1;return!0}]]},any:{type:ri,overloads:[[[ri,ri],(k,[f,_])=>f.evaluate(k)||_.evaluate(k)],[Pd(ri),(k,f)=>{for(const _ of f)if(_.evaluate(k))return!0;return!1}]]},"!":[ri,[ri],(k,[f])=>!f.evaluate(k)],"is-supported-script":[ri,[Ra],(k,[f])=>{const _=k.globals&&k.globals.isSupportedScript;return!_||_(f.evaluate(k))}],upcase:[Ra,[Ra],(k,[f])=>f.evaluate(k).toUpperCase()],downcase:[Ra,[Ra],(k,[f])=>f.evaluate(k).toLowerCase()],concat:[Ra,Pd(Hi),(k,f)=>f.map(_=>Ma(_.evaluate(k))).join("")],"resolved-locale":[Ra,[lm],(k,[f])=>f.evaluate(k).resolvedLocale()],random:[sr,[sr,sr,Hi],(k,f)=>{const[_,S,L]=f.map(z=>z.evaluate(k));if(_>S||_===S)return _;let O;if(typeof L=="string")O=function(z){let G=0;if(z.length===0)return G;for(let Y=0;YJSON.stringify(ye)).join(", ")}, but found ${JSON.stringify(me)} instead.`);return me}catch(me){const ye=me;return this._warningHistory[ye.message]||(this._warningHistory[ye.message]=!0,typeof console<"u"&&console.warn(`Failed to evaluate expression "${JSON.stringify(this.expression.serialize())}". ${ye.message}`)),this._defaultValue}}}function Im(k){return Array.isArray(k)&&k.length>0&&typeof k[0]=="string"&&k[0]in Fi}function Vc(k,f,_,S,L){const O=new k2(Fi,[],f?function(G){const Y={color:Ho,string:Ra,number:sr,enum:Ra,boolean:ri,formatted:zg,resolvedImage:Bg};return G.type==="array"?gu(Y[G.value]||Hi,G.length):Y[G.type]}(f):void 0,void 0,void 0,_,S,L),z=O.parse(k,void 0,void 0,void 0,f&&f.type==="string"?{typeAnnotation:"coerce"}:void 0);return z?ti(new Iu(z,f,_,S,L)):ol(O.errors)}class th{constructor(f,_,S,L){this.kind=f,this._styleExpression=_,this.isLightConstant=S,this.isLineProgressConstant=L,this.isStateDependent=f!=="constant"&&!zf(_.expression),this.configDependencies=nl(_.expression),this.isIndoorDependent=Di(_.expression)}evaluateWithoutErrorHandling(f,_,S,L,O,z){return this._styleExpression.evaluateWithoutErrorHandling(f,_,S,L,O,z)}evaluate(f,_,S,L,O,z,G){return this._styleExpression.evaluate(f,_,S,L,O,z,void 0,void 0,G)}}class Xl{constructor(f,_,S,L,O,z){this.kind=f,this.zoomStops=S,this._styleExpression=_,this.isStateDependent=f!=="camera"&&!zf(_.expression),this.isIndoorDependent=Di(_.expression),this.isLightConstant=O,this.isLineProgressConstant=z,this.configDependencies=nl(_.expression),this.interpolationType=L}evaluateWithoutErrorHandling(f,_,S,L,O,z){return this._styleExpression.evaluateWithoutErrorHandling(f,_,S,L,O,z)}evaluate(f,_,S,L,O,z){return this._styleExpression.evaluate(f,_,S,L,O,z)}interpolationFactor(f,_,S){return this.interpolationType?cm.interpolationFactor(this.interpolationType,f,_,S):0}}function Du(k,f,_,S,L){if((k=Vc(k,f,_,S,L)).result==="error")return k;const O=k.value.expression,z=B1(O);if(!z&&!Yo(f))return ol([new Dr("","data expressions not supported")]);const G=eu(O,["zoom","pitch","distance-from-center"]);if(!G&&!Oh(f))return ol([new Dr("","zoom expressions not supported")]);const Y=eu(O,["measure-light"]);if(!Y&&!jd(f))return ol([new Dr("","measure-light expression not supported")]);const re=eu(O,["line-progress"]);if(!re&&!function(we){return co(we.expression,"line-progress")}(f))return ol([new Dr("","line-progress expression not supported")]);const me=f.expression&&f.expression.relaxZoomRestriction,ye=Id(O);return ye||G||me?ye instanceof Dr?ol([ye]):ye instanceof cm&&!Nd(f)?ol([new Dr("",'"interpolate" expressions cannot be used with this property')]):ti(ye?new Xl(z&&re?"camera":"composite",k.value,ye.labels,ye instanceof cm?ye.interpolation:void 0,Y,re):new th(z&&re?"constant":"source",k.value,Y,re)):ol([new Dr("",'"zoom" expression may only be used as input to a top-level "step" or "interpolate" expression, or in the properties of atmosphere.')])}class Dm{constructor(f,_){this._parameters=f,this._specification=_,Object.assign(this,Jp(this._parameters,this._specification))}static deserialize(f){return new Dm(f._parameters,f._specification)}static serialize(f){return{_parameters:f._parameters,_specification:f._specification}}}function Id(k){let f=null;if(k instanceof Ce)f=Id(k.result);else if(k instanceof i_){for(const _ of k.args)if(f=Id(_),f)break}else(k instanceof Dw||k instanceof cm)&&k.input instanceof Qc&&k.input.name==="zoom"&&(f=k);return f instanceof Dr||k.eachChild(_=>{const S=Id(_);S instanceof Dr?f=S:f&&S&&f!==S&&(f=new Dr("",'Only one zoom-based "step" or "interpolate" subexpression may be used in an expression.'))}),f}var ef,tf,Rm=function(){if(tf)return ef;tf=1,ef=f;var k=3;function f(_,S,L){var O=this.cells=[];if(_ instanceof ArrayBuffer){this.arrayBuffer=_;var z=new Int32Array(this.arrayBuffer);_=z[0],this.d=(S=z[1])+2*(L=z[2]);for(var G=0;G=we[Ve+0]&&O>=we[Ve+1])?(Y[Ie]=!0,G.push(ye[Ie])):Y[Ie]=!1}}},f.prototype._forEachCell=function(_,S,L,O,z,G,Y,re){for(var me=this._convertToCellCoord(_),ye=this._convertToCellCoord(S),we=this._convertToCellCoord(L),Te=this._convertToCellCoord(O),Ie=me;Ie<=we;Ie++)for(var Ve=ye;Ve<=Te;Ve++){var Je=this.d*Ve+Ie;if((!re||re(this._convertFromCellCoord(Ie),this._convertFromCellCoord(Ve),this._convertFromCellCoord(Ie+1),this._convertFromCellCoord(Ve+1)))&&z.call(this,_,S,L,O,Je,G,Y,re))return}},f.prototype._convertFromCellCoord=function(_){return(_-this.padding)/this.scale},f.prototype._convertToCellCoord=function(_){return Math.max(0,Math.min(this.d-1,Math.floor(_*this.scale)+this.padding))},f.prototype.toArrayBuffer=function(){if(this.arrayBuffer)return this.arrayBuffer;for(var _=this.cells,S=k+this.cells.length+1+1,L=0,O=0;O=0||(L[O]=Fc(k[O],f)));k instanceof Error&&(L.message=k.message)}if(L.$name)throw new Error("$name property is reserved for worker serialization logic.");return S!=="Object"&&(L.$name=S),L}throw new Error("can't serialize object of type "+typeof k)}function lc(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||No(k)||k instanceof ImageBitmap||ArrayBuffer.isView(k)||k instanceof ImageData)return k;if(Array.isArray(k))return k.map(lc);if(typeof k=="object"){const f=k.$name||"Object";if(f==="Map"){const L=k.entries||[],O=new Map;for(let z=0;zk>=1536&&k<=1791,dm=k=>k>=1872&&k<=1919,U0=k=>k>=2208&&k<=2303,su=k=>k>=11904&&k<=12031,xp=k=>k>=12032&&k<=12255,Av=k=>k>=12272&&k<=12287,$1=k=>k>=12288&&k<=12351,Ev=k=>k>=12352&&k<=12447,Om=k=>k>=12448&&k<=12543,sf=k=>k>=12544&&k<=12591,Uw=k=>k>=12704&&k<=12735,Hg=k=>k>=12736&&k<=12783,q0=k=>k>=12784&&k<=12799,Dy=k=>k>=12800&&k<=13055,qw=k=>k>=13056&&k<=13311,Vw=k=>k>=13312&&k<=19903,xx=k=>k>=19968&&k<=40959,Ry=k=>k>=40960&&k<=42127,gx=k=>k>=42128&&k<=42191,o_=k=>k>=44032&&k<=55215,U1=k=>k>=63744&&k<=64255,q1=k=>k>=64336&&k<=65023,Hw=k=>k>=65040&&k<=65055,V1=k=>k>=65072&&k<=65103,wu=k=>k>=65104&&k<=65135,V0=k=>k>=65136&&k<=65279,Bf=k=>k>=65280&&k<=65519;function nf(k){for(const f of k)if(bk(f.charCodeAt(0)))return!0;return!1}function J5(k){for(const f of k)if(!H1(f.charCodeAt(0)))return!1;return!0}function H1(k){return!(vc(k)||dm(k)||U0(k)||q1(k)||V0(k))}function e4(k){return!(k<11904||!(Uw(k)||sf(k)||V1(k)||U1(k)||qw(k)||su(k)||Hg(k)||$1(k)||Vw(k)||xx(k)||Dy(k)||Bf(k)||Ev(k)||Av(k)||xp(k)||q0(k)||Om(k)||Hw(k)||gx(k)||Ry(k)))}function bk(k){return!(k!==746&&k!==747&&(k<4352||!(Uw(k)||sf(k)||V1(k)&&!(k>=65097&&k<=65103)||U1(k)||qw(k)||su(k)||Hg(k)||!(!$1(k)||k>=12296&&k<=12305||k>=12308&&k<=12319||k===12336)||Vw(k)||xx(k)||Dy(k)||(f=>f>=12592&&f<=12687)(k)||(f=>f>=43360&&f<=43391)(k)||(f=>f>=55216&&f<=55295)(k)||(f=>f>=4352&&f<=4607)(k)||o_(k)||Ev(k)||Av(k)||(f=>f>=12688&&f<=12703)(k)||xp(k)||q0(k)||Om(k)&&k!==12540||!(!Bf(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)||!(!wu(k)||k>=65112&&k<=65118||k>=65123&&k<=65126)||(f=>f>=5120&&f<=5759)(k)||(f=>f>=6320&&f<=6399)(k)||Hw(k)||(f=>f>=19904&&f<=19967)(k)||Ry(k)||gx(k))))}function Tv(k){return k===12312||k===12313||k===12316||k===12540||k===12448}function Mv(k){return!(bk(k)||function(f){return!!((_=>_>=128&&_<=255)(f)&&(f===167||f===169||f===174||f===177||f===188||f===189||f===190||f===215||f===247)||(_=>_>=8192&&_<=8303)(f)&&(f===8214||f===8224||f===8225||f===8240||f===8241||f===8251||f===8252||f===8258||f===8263||f===8264||f===8265||f===8273)||(_=>_>=8448&&_<=8527)(f)||(_=>_>=8528&&_<=8591)(f)||(_=>_>=8960&&_<=9215)(f)&&(f>=8960&&f<=8967||f>=8972&&f<=8991||f>=8996&&f<=9e3||f===9003||f>=9085&&f<=9114||f>=9150&&f<=9165||f===9167||f>=9169&&f<=9179||f>=9186&&f<=9215)||(_=>_>=9216&&_<=9279)(f)&&f!==9251||(_=>_>=9280&&_<=9311)(f)||(_=>_>=9312&&_<=9471)(f)||(_=>_>=9632&&_<=9727)(f)||(_=>_>=9728&&_<=9983)(f)&&!(f>=9754&&f<=9759)||(_=>_>=11008&&_<=11263)(f)&&(f>=11026&&f<=11055||f>=11088&&f<=11097||f>=11192&&f<=11243)||$1(f)||Om(f)||(_=>_>=57344&&_<=63743)(f)||V1(f)||wu(f)||Bf(f)||f===8734||f===8756||f===8757||f>=9984&&f<=10087||f>=10102&&f<=10131||f===65532||f===65533)}(k))}function t4(k){return vc(k)||dm(k)||U0(k)||q1(k)||V0(k)}function Lv(k){return k>=1424&&k<=2303||q1(k)||V0(k)}function Gg(k,f){return!(!f&&Lv(k)||k>=2304&&k<=3583||k>=3840&&k<=4255||(_=>_>=6016&&_<=6143)(k))}function C2(k){for(const f of k)if(Lv(f.charCodeAt(0)))return!0;return!1}const Ru={unavailable:"unavailable",deferred:"deferred",loading:"loading",parsing:"parsing",parsed:"parsed",loaded:"loaded",error:"error"};let um=null,Dd=Ru.unavailable,rf=null;const _k=function(k){k&&typeof k=="string"&&k.indexOf("NetworkError")>-1&&(Dd=Ru.error),um&&um(k)};function A2(){wk.fire(new Oc("pluginStateChange",{pluginStatus:Dd,pluginURL:rf}))}const wk=new om,H0=function(){return Dd},jk=function(){if(Dd!==Ru.deferred||!rf)throw new Error("rtl-text-plugin cannot be downloaded unless a pluginURL is specified");Dd=Ru.loading,A2(),rf&&mh({url:rf},k=>{k?_k(k):(Dd=Ru.loaded,A2())})},Zx={applyArabicShaping:null,processBidirectionalText:null,processStyledBidirectionalText:null,isLoaded:()=>Dd===Ru.loaded||Zx.applyArabicShaping!=null,isLoading:()=>Dd===Ru.loading,setState(k){Dd=k.pluginStatus,rf=k.pluginURL},isParsing:()=>Dd===Ru.parsing,isParsed:()=>Dd===Ru.parsed,getPluginURL:()=>rf},iM=function(){Zx.isLoading()||Zx.isLoaded()||H0()!=="deferred"||jk()};class Si{constructor(f,_){this.zoom=f,_?(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(f){return function(_,S){for(const L of _)if(!Gg(L.charCodeAt(0),S))return!1;return!0}(f,Zx.isLoaded())}}class Nk{constructor(f,_,S,L,O){this.property=f,this.value=_,this.expression=function(z,G,Y,re,me){if(tu(z))return new Dm(z,G);if(Im(z)||Array.isArray(z)&&z.length>0){const ye=Du(z,G,Y,re,me);if(ye.result==="error")throw new Error(ye.value.map(we=>`${we.key}: ${we.message}`).join(", "));return ye.value}{let ye=z;return typeof z=="string"&&G.type==="color"&&(ye=Ys.parse(z)),{kind:"constant",configDependencies:new Set,isIndoorDependent:!1,evaluate:()=>ye}}}(_===void 0?f.specification.default:_,f.specification,S,L,O)}isIndoorDependent(){return this.expression.isIndoorDependent}isDataDriven(){return this.expression.kind==="source"||this.expression.kind==="composite"}possiblyEvaluate(f,_,S,L){return this.property.possiblyEvaluate(this,f,_,S,L)}}class s4{constructor(f,_,S,L){this.property=f,this.value=new Nk(f,void 0,_,S,L)}transitioned(f,_){return new kk(this.property,this.value,_,Object.assign({},f.transition,this.transition),f.now)}untransitioned(){return new kk(this.property,this.value,null,{},0)}}class PC{constructor(f,_,S,L){this._properties=f,this._values=Object.create(f.defaultTransitionablePropertyValues),this._scope=_,this._options=S,this._iconImageUseTheme=L,this._isIndoorDependent=!1,this.configDependencies=new Set}getValue(f){return Hn(this._values[f].value.value)}setValue(f,_){this._values.hasOwnProperty(f)||(this._values[f]=new s4(this._values[f].property,this._scope,this._options,this._iconImageUseTheme)),this._values[f].value=new Nk(this._values[f].property,_===null?void 0:Hn(_),this._scope,this._options,this._iconImageUseTheme),this._values[f].value.expression.configDependencies&&(this.configDependencies=new Set([...this.configDependencies,...this._values[f].value.expression.configDependencies]),this._isIndoorDependent=this._isIndoorDependent||this._values[f].value.isIndoorDependent())}setTransitionOrValue(f,_){_&&(this._options=_);const S=this._properties.properties;if(f)for(const L in f){const O=f[L];if(L.endsWith("-transition")){const z=L.slice(0,-11);S[z]&&this.setTransition(z,O)}else S.hasOwnProperty(L)&&this.setValue(L,O)}}getTransition(f){return Hn(this._values[f].transition)}setTransition(f,_){this._values.hasOwnProperty(f)||(this._values[f]=new s4(this._values[f].property)),this._values[f].transition=Hn(_)||void 0}serialize(){const f={};for(const _ of Object.keys(this._values)){const S=this.getValue(_);S!==void 0&&(f[_]=S);const L=this.getTransition(_);L!==void 0&&(f[`${_}-transition`]=L)}return f}transitioned(f,_){const S=new IC(this._properties);for(const L of Object.keys(this._values))S._values[L]=this._values[L].transitioned(f,_._values[L]);return S}untransitioned(){const f=new IC(this._properties);for(const _ of Object.keys(this._values))f._values[_]=this._values[_].untransitioned();return f}isIndoorDependent(){return this._isIndoorDependent}}class kk{constructor(f,_,S,L,O){const z=L.delay||0,G=L.duration||0;O=O||0,this.property=f,this.value=_,this.begin=O+z,this.end=this.begin+G,f.specification.transition&&(L.delay||L.duration)&&(this.prior=S)}possiblyEvaluate(f,_,S){const L=f.now||0,O=this.value.possiblyEvaluate(f,_,S),z=this.prior;if(z){if(L>this.end)return this.prior=null,O;if(this.value.isDataDriven())return this.prior=null,O;if(L":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 n4(k){return k instanceof Number||k instanceof String||k instanceof Boolean?k.valueOf():k}function Sk(k){if(Array.isArray(k))return k.map(Sk);if(k instanceof Object&&!(k instanceof Number||k instanceof String||k instanceof Boolean)){const f={};for(const _ in k)f[_]=Sk(k[_]);return f}return n4(k)}function r4(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 f of k.slice(1))if(!r4(f)&&typeof f!="boolean")return!1;return!0;default:return!0}}function RC(k,f="",_=null,S="fill"){if(k==null)return{filter:()=>!0,needGeometry:!1,needFeature:!1};r4(k)||(k=FC(k));const L=k;let O=!0;try{O=function(me){if(!T2(me))return me;let ye=Sk(me);return lM(ye),ye=oM(ye),ye}(L)}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(L,null,2)} `)}let z=null,G=null;if(S!=="background"&&S!=="sky"&&S!=="slot"){G=$s[`filter_${S}`];const me=Vc(O,G,f,_);if(me.result==="error")throw new Error(me.value.map(ye=>`${ye.key}: ${ye.message}`).join(", "));z=(ye,we,Te)=>me.value.evaluate(ye,we,{},Te)}let Y=null,re=null;if(O!==L){const me=Vc(L,G,f,_);if(me.result==="error")throw new Error(me.value.map(ye=>`${ye.key}: ${ye.message}`).join(", "));Y=(ye,we,Te,Ie,Ve)=>me.value.evaluate(ye,we,{},Te,void 0,void 0,Ie,Ve),re=!B1(me.value.expression)}return{filter:z,dynamicFilter:Y||void 0,needGeometry:SF(O),needFeature:!!re}}function oM(k){if(!Array.isArray(k))return k;const f=function(_){if(cM.has(_[0])){for(let S=1;S<_.length;S++)if(T2(_[S]))return!0}return _}(k);return f===!0?f:f.map(_=>oM(_))}function lM(k){let f=!1;const _=[];if(k[0]==="case"){for(let S=1;S",">=","<","<=","to-boolean"]);function OC(k,f){return kf?1:0}function SF(k){if(!Array.isArray(k))return!1;if(k[0]==="within"||k[0]==="distance")return!0;for(let f=1;f"||f==="<="||f===">="?te(k[1],k[2],f):f==="any"?(_=k.slice(1),["any"].concat(_.map(FC))):f==="all"?["all"].concat(k.slice(1).map(FC)):f==="none"?["all"].concat(k.slice(1).map(FC).map(st)):f==="in"?ie(k[1],k.slice(2)):f==="!in"?st(ie(k[1],k.slice(2))):f==="has"?Pe(k[1]):f!=="!has"||st(Pe(k[1]));var _}function te(k,f,_){switch(k){case"$type":return[`filter-type-${_}`,f];case"$id":return[`filter-id-${_}`,f];default:return[`filter-${_}`,k,f]}}function ie(k,f){if(f.length===0)return!1;switch(k){case"$type":return["filter-type-in",["literal",f]];case"$id":return["filter-id-in",["literal",f]];default:return f.length>200&&!f.some(_=>typeof _!=typeof f[0])?["filter-in-large",k,["literal",f.sort(OC)]]:["filter-in-small",k,["literal",f]]}}function Pe(k){switch(k){case"$type":return!0;case"$id":return["filter-has-id"];default:return["filter-has",k]}}function st(k){return["!",k]}const ct="";function Et(k,f){return f?`${k}${ct}${f}`:k}function Fs(k){const f=k.indexOf(ct);return f>=0?k.slice(f+1):""}let Yn;const Pr=()=>Yn||(Yn=new bc({"icon-size":new ar($s.layout_symbol["icon-size"]),"icon-image":new ar($s.layout_symbol["icon-image"]),"icon-rotate":new ar($s.layout_symbol["icon-rotate"]),"icon-offset":new ar($s.layout_symbol["icon-offset"]),"text-size":new ar($s.layout_symbol["text-size"]),"text-rotate":new ar($s.layout_symbol["text-rotate"]),"text-offset":new ar($s.layout_symbol["text-offset"])}));let Pa;const Ri=()=>Pa||(Pa=new bc({"icon-opacity":new ar($s.paint_symbol["icon-opacity"]),"icon-occlusion-opacity":new ar($s.paint_symbol["icon-occlusion-opacity"]),"icon-emissive-strength":new ar($s.paint_symbol["icon-emissive-strength"]),"text-emissive-strength":new ar($s.paint_symbol["text-emissive-strength"]),"icon-color":new ar($s.paint_symbol["icon-color"]),"icon-halo-color":new ar($s.paint_symbol["icon-halo-color"]),"icon-halo-width":new ar($s.paint_symbol["icon-halo-width"]),"icon-halo-blur":new ar($s.paint_symbol["icon-halo-blur"]),"icon-translate":new ar($s.paint_symbol["icon-translate"]),"text-opacity":new ar($s.paint_symbol["text-opacity"]),"text-occlusion-opacity":new ar($s.paint_symbol["text-occlusion-opacity"]),"text-color":new ar($s.paint_symbol["text-color"],{runtimeType:Ho,getOverride:k=>k.textColor,hasOverride:k=>!!k.textColor}),"text-halo-color":new ar($s.paint_symbol["text-halo-color"]),"text-halo-width":new ar($s.paint_symbol["text-halo-width"]),"text-halo-blur":new ar($s.paint_symbol["text-halo-blur"]),"text-translate":new ar($s.paint_symbol["text-translate"]),"symbol-z-offset":new ar($s.paint_symbol["symbol-z-offset"]),"icon-color-use-theme":new ar({type:"string",default:"default","property-type":"data-driven"}),"icon-halo-color-use-theme":new ar({type:"string",default:"default","property-type":"data-driven"}),"text-color-use-theme":new ar({type:"string",default:"default","property-type":"data-driven"}),"text-halo-color-use-theme":new ar({type:"string",default:"default","property-type":"data-driven"})}));class Sl{constructor(f,_,S,L,O,z){this._conditionSpec=f,this._propertiesSpec=S;const G=Vc(f,$s.appearance.condition);if(G.result==="success"&&(this.condition=G.value),this.name=_,S){this.layoutProperties=new Fm(Pr()),this.unevaluatedLayout=new DC(Pr(),L,O,z),this.paintProperties=new Fm(Ri()),this.unevaluatedPaint=new DC(Ri(),L,O,"");for(const Y in S)Y in this.unevaluatedLayout._values?this.unevaluatedLayout.setValue(Y,S[Y]):Y in this.unevaluatedPaint._values&&this.unevaluatedPaint.setValue(Y,S[Y])}}isActive(f){return!(this.condition||!f.isHidden||this.name!=="hidden")||this.condition.evaluate(f.globals,f.feature,f.featureState,f.canonical)}getCondition(){return this.condition}getName(){return this.name}getLayoutProperty(f){return this.layoutProperties.get(f)}getPaintProperty(f){return this.paintProperties.get(f)}getUnevaluatedLayoutProperties(){return this.unevaluatedLayout}getUnevaluatedLayoutProperty(f){return this.unevaluatedLayout._values[f]}getUnevaluatedPaintProperty(f){return this.unevaluatedPaint._values[f]}recalculate(f,_,S){this.unevaluatedLayout&&(this.layoutProperties=this.unevaluatedLayout.possiblyEvaluate(f,void 0,_,S)),this.unevaluatedPaint&&(this.paintProperties=this.unevaluatedPaint.possiblyEvaluate(f,void 0,_,""))}serialize(){const f={};f.condition=this.condition.expression.serialize(),this.name&&(f.name=this.name);const _=this.unevaluatedLayout?this.unevaluatedLayout.serialize():{},S=this.unevaluatedPaint?this.unevaluatedPaint.serialize():{},L=Object.assign({},_,S);return Object.keys(L).length>0&&(f.properties=L),f}hasIconLayoutProperties(){const f=this.hasLayoutProperty("icon-image"),_=this.hasLayoutProperty("icon-size"),S=this.hasLayoutProperty("icon-offset"),L=this.hasLayoutProperty("icon-rotate");return f||_||S||L}hasTextLayoutProperties(){const f=this.hasLayoutProperty("text-size"),_=this.hasLayoutProperty("text-offset"),S=this.hasLayoutProperty("text-rotate");return f||_||S}hasIconPaintProperties(){return!!this.unevaluatedPaint&&Object.keys(this.unevaluatedPaint._values).filter(f=>!f.endsWith("-use-theme")).some(f=>(f.startsWith("icon-")||f==="symbol-z-offset")&&this.hasPaintProperty(f))}hasTextPaintProperties(){return!!this.unevaluatedPaint&&Object.keys(this.unevaluatedPaint._values).filter(f=>!f.endsWith("-use-theme")).some(f=>(f.startsWith("text-")||f==="symbol-z-offset")&&this.hasPaintProperty(f))}hasLayoutProperty(f){return this.unevaluatedLayout&&this.unevaluatedLayout._values[f].value!==void 0}hasPaintProperty(f){return this.unevaluatedPaint&&this.unevaluatedPaint._values[f].value!==void 0}}const yi="-transition",Ou=new Set(["fill","line","background","hillshade","raster"]);class Cl extends om{constructor(f,_,S,L,O,z){if(super(),this.id=f.id,this.fqid=Et(this.id,S),this.type=f.type,this.scope=S,this.lut=L,this.options=O,this.iconImageUseTheme=z,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},f.type!=="custom"){if(this.metadata=f.metadata,this.minzoom=f.minzoom,this.maxzoom=f.maxzoom,f.type&&f.type!=="background"&&f.type!=="sky"&&f.type!=="slot"){this.source=f.source,this.sourceLayer=f["source-layer"],this.filter=f.filter;const G=Vc(this.filter,$s[`filter_${f.type}`]);G.result!=="error"&&(this.expressionDependencies.configDependencies=new Set([...this.expressionDependencies.configDependencies,...G.value.configDependencies]),this.expressionDependencies.isIndoorDependent=this.expressionDependencies.isIndoorDependent||G.value.isIndoorDependent)}if(f.slot&&(this.slot=f.slot),f.appearances&&this.setAppearances(f.appearances),_.layout&&(this._unevaluatedLayout=new DC(_.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 PC(_.paint,this.scope,O);for(const G in f.paint)this.setPaintProperty(G,f.paint[G]);for(const G in f.layout)this.setLayoutProperty(G,f.layout[G]);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 Fm(_.paint)}}}onAdd(f){}onRemove(f){}isDraped(f){return!this.is3D(!0)&&Ou.has(this.type)}getLayoutProperty(f){return f==="visibility"?this.visibility:this._unevaluatedLayout.getValue(f)}setLayoutProperty(f,_){if(this.type==="custom"&&f==="visibility")return void(this.visibility=_);const S=this._unevaluatedLayout;S._properties.properties[f]&&(S.setValue(f,_),this.expressionDependencies.configDependencies=new Set([...this.expressionDependencies.configDependencies,...S.configDependencies]),this.expressionDependencies.isIndoorDependent=this.expressionDependencies.isIndoorDependent||S.isIndoorDependent(),f==="visibility"&&this.possiblyEvaluateVisibility())}setAppearances(f){this.appearances=[],f.forEach(_=>{this.appearances.push(new Sl(_.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(f){return f.endsWith(yi)?this._transitionablePaint.getTransition(f.slice(0,-11)):this._transitionablePaint.getValue(f)}isPaintProperty(f){return!!this._transitionablePaint._properties.properties[f]}setPaintProperty(f,_){const S=this._transitionablePaint,L=S._properties.properties;if(f.endsWith(yi)){const ye=f.slice(0,-11);return L[ye]&&S.setTransition(ye,_||void 0),!1}if(!L[f])return!1;const O=S._values[f],z=O.value.isDataDriven(),G=O.value;S.setValue(f,_),this.expressionDependencies.configDependencies=new Set([...this.expressionDependencies.configDependencies,...S.configDependencies]),this.expressionDependencies.isIndoorDependent=this.expressionDependencies.isIndoorDependent||S.isIndoorDependent(),this._handleSpecialPaintPropertyUpdate(f);const Y=S._values[f].value,re=Y.isDataDriven(),me=f.endsWith("pattern")||f==="line-dasharray";return re||z||me||this._handleOverridablePaintPropertyUpdate(f,G,Y)}_handleSpecialPaintPropertyUpdate(f){}getProgramIds(){return null}getDefaultProgramParams(f,_,S){return null}_handleOverridablePaintPropertyUpdate(f,_,S){return!1}isHidden(f){return!!(this.minzoom&&f=this.maxzoom)||this.visibility==="none"}updateTransitions(f){this._transitioningPaint=this._transitionablePaint.transitioned(f,this._transitioningPaint)}hasTransition(){return this._transitioningPaint.hasTransition()}recalculate(f,_){this._unevaluatedLayout&&(this.layout=this._unevaluatedLayout.possiblyEvaluate(f,void 0,_,this.iconImageUseTheme)),this.paint=this._transitioningPaint.possiblyEvaluate(f,void 0,_)}serialize(){const f={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&&(f.appearances=this.appearances.map(_=>_.serialize())),Vs(f,(_,S)=>!(_===void 0||S==="layout"&&!Object.keys(_).length||S==="paint"&&!Object.keys(_).length))}is3D(f){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 f in this.paint._values){const _=this.paint.get(f);if(_ instanceof E2&&Yo(_.property.specification)&&(_.value.kind==="source"||_.value.kind==="composite")&&_.value.isStateDependent)return!0}for(const f of this.appearances)if(!zf(f.condition.expression))return!0;return!1}compileFilter(f){this._filterCompiled||(this._featureFilter=RC(this.filter,this.scope,f),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(f){this._stats&&(f.renderPass==="shadow"?this._stats.numRenderedVerticesInShadowPass=0:this._stats.numRenderedVerticesInTransparentPass=0)}getAppearances(){return this.appearances}queryRenderedFeatures(f,_,S){return{}}queryRadius(f){}queryIntersectsFeature(f,_,S,L,O,z,G,Y,re,me){}}const $f={Int8:Int8Array,Uint8:Uint8Array,Int16:Int16Array,Uint16:Uint16Array,Int32:Int32Array,Uint32:Uint32Array,Float32:Float32Array};class W0{constructor(f,_){this._structArray=f,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 Nn{constructor(){this._reallocCount=0,this.capacity=0,this.length=0}static serialize(f,_){return f._trim(),_&&f.arrayBuffer&&_.add(f.arrayBuffer),{length:f.length,arrayBuffer:f.arrayBuffer}}static deserialize(f){const _=Object.create(this.prototype);return _.arrayBuffer=f.arrayBuffer,_.length=f.length,f.arrayBuffer?_.capacity=f.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(f){this.reserve(f),this.length=f}reserve(f){if(f>this.capacity){this._reallocCount++,this.capacity=Math.max(f,Math.floor(5*this.capacity),128),this.arrayBuffer=new ArrayBuffer(this.capacity*this.bytesPerElement);const _=this.uint8;this._refreshViews(),_&&this.uint8.set(_)}}reserveForAdditional(f){this.reserve(this.length+f)}_refreshViews(){throw new Error("StructArray#_refreshViews() must be implemented by each concrete StructArray layout")}emplace(...f){throw new Error("StructArray#emplace() must be implemented by each concrete StructArray layout")}emplaceBack(...f){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 zn(k,f=1){let _=0,S=0;return{members:k.map(L=>{const O=$f[L.type].BYTES_PER_ELEMENT,z=_=Ci(_,Math.max(f,O)),G=L.components||1;return S=Math.max(S,O),_+=O*G,{name:L.name,type:L.type,components:G,offset:z}}),size:Ci(_,Math.max(S,f)),alignment:f}}function Ci(k,f){return Math.ceil(k/f)*f}class zi extends Nn{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer)}emplaceBack(f,_){const S=this.length;return this.resize(S+1),this.emplace(S,f,_)}emplace(f,_,S){const L=2*f;return this.int16[L+0]=_,this.int16[L+1]=S,f}}zi.prototype.bytesPerElement=4,br(zi,"StructArrayLayout2i4");class Wo extends Nn{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer)}emplaceBack(f,_,S){const L=this.length;return this.resize(L+1),this.emplace(L,f,_,S)}emplace(f,_,S,L){const O=3*f;return this.int16[O+0]=_,this.int16[O+1]=S,this.int16[O+2]=L,f}}Wo.prototype.bytesPerElement=6,br(Wo,"StructArrayLayout3i6");class so extends Nn{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer)}emplaceBack(f,_,S,L){const O=this.length;return this.resize(O+1),this.emplace(O,f,_,S,L)}emplace(f,_,S,L,O){const z=4*f;return this.int16[z+0]=_,this.int16[z+1]=S,this.uint16[z+2]=L,this.uint16[z+3]=O,f}}so.prototype.bytesPerElement=8,br(so,"StructArrayLayout2i2ui8");class xl extends Nn{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(f){const _=this.length;return this.resize(_+1),this.emplace(_,f)}emplace(f,_){return this.float32[1*f+0]=_,f}}xl.prototype.bytesPerElement=4,br(xl,"StructArrayLayout1f4");class zm extends Nn{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(f,_,S){const L=this.length;return this.resize(L+1),this.emplace(L,f,_,S)}emplace(f,_,S,L){const O=4*f,z=2*f;return this.int16[O+0]=_,this.int16[O+1]=S,this.float32[z+1]=L,f}}zm.prototype.bytesPerElement=8,br(zm,"StructArrayLayout2i1f8");class zc extends Nn{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer)}emplaceBack(f,_,S){const L=this.length;return this.resize(L+1),this.emplace(L,f,_,S)}emplace(f,_,S,L){const O=4*f;return this.int16[O+0]=_,this.int16[O+1]=S,this.int16[O+2]=L,f}}zc.prototype.bytesPerElement=8,br(zc,"StructArrayLayout3i8");class G1 extends Nn{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer)}emplaceBack(f,_,S,L){const O=this.length;return this.resize(O+1),this.emplace(O,f,_,S,L)}emplace(f,_,S,L,O){const z=4*f;return this.int16[z+0]=_,this.int16[z+1]=S,this.int16[z+2]=L,this.int16[z+3]=O,f}}G1.prototype.bytesPerElement=8,br(G1,"StructArrayLayout4i8");class dM extends Nn{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer)}emplaceBack(f,_,S,L,O){const z=this.length;return this.resize(z+1),this.emplace(z,f,_,S,L,O)}emplace(f,_,S,L,O,z){const G=5*f;return this.int16[G+0]=_,this.int16[G+1]=S,this.int16[G+2]=L,this.int16[G+3]=O,this.int16[G+4]=z,f}}dM.prototype.bytesPerElement=10,br(dM,"StructArrayLayout5i10");class uM extends Nn{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(f,_,S,L,O,z,G){const Y=this.length;return this.resize(Y+1),this.emplace(Y,f,_,S,L,O,z,G)}emplace(f,_,S,L,O,z,G,Y){const re=6*f,me=12*f,ye=3*f;return this.int16[re+0]=_,this.int16[re+1]=S,this.uint8[me+4]=L,this.uint8[me+5]=O,this.uint8[me+6]=z,this.uint8[me+7]=G,this.float32[ye+2]=Y,f}}uM.prototype.bytesPerElement=12,br(uM,"StructArrayLayout2i4ub1f12");class W1 extends Nn{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(f,_,S){const L=this.length;return this.resize(L+1),this.emplace(L,f,_,S)}emplace(f,_,S,L){const O=3*f;return this.float32[O+0]=_,this.float32[O+1]=S,this.float32[O+2]=L,f}}W1.prototype.bytesPerElement=12,br(W1,"StructArrayLayout3f12");class Gw extends Nn{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(f,_,S,L,O){const z=this.length;return this.resize(z+1),this.emplace(z,f,_,S,L,O)}emplace(f,_,S,L,O,z){const G=6*f,Y=3*f;return this.uint16[G+0]=_,this.uint16[G+1]=S,this.uint16[G+2]=L,this.uint16[G+3]=O,this.float32[Y+2]=z,f}}Gw.prototype.bytesPerElement=12,br(Gw,"StructArrayLayout4ui1f12");class zC extends Nn{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer)}emplaceBack(f,_,S,L){const O=this.length;return this.resize(O+1),this.emplace(O,f,_,S,L)}emplace(f,_,S,L,O){const z=4*f;return this.uint16[z+0]=_,this.uint16[z+1]=S,this.uint16[z+2]=L,this.uint16[z+3]=O,f}}zC.prototype.bytesPerElement=8,br(zC,"StructArrayLayout4ui8");class CF extends Nn{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer)}emplaceBack(f,_,S,L,O,z){const G=this.length;return this.resize(G+1),this.emplace(G,f,_,S,L,O,z)}emplace(f,_,S,L,O,z,G){const Y=6*f;return this.int16[Y+0]=_,this.int16[Y+1]=S,this.int16[Y+2]=L,this.int16[Y+3]=O,this.int16[Y+4]=z,this.int16[Y+5]=G,f}}CF.prototype.bytesPerElement=12,br(CF,"StructArrayLayout6i12");class IV extends Nn{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer)}emplaceBack(f,_,S,L,O,z,G,Y,re,me,ye,we){const Te=this.length;return this.resize(Te+1),this.emplace(Te,f,_,S,L,O,z,G,Y,re,me,ye,we)}emplace(f,_,S,L,O,z,G,Y,re,me,ye,we,Te){const Ie=12*f;return this.int16[Ie+0]=_,this.int16[Ie+1]=S,this.int16[Ie+2]=L,this.int16[Ie+3]=O,this.uint16[Ie+4]=z,this.uint16[Ie+5]=G,this.uint16[Ie+6]=Y,this.uint16[Ie+7]=re,this.int16[Ie+8]=me,this.int16[Ie+9]=ye,this.int16[Ie+10]=we,this.int16[Ie+11]=Te,f}}IV.prototype.bytesPerElement=24,br(IV,"StructArrayLayout4i4ui4i24");class DV extends Nn{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(f,_,S,L,O,z){const G=this.length;return this.resize(G+1),this.emplace(G,f,_,S,L,O,z)}emplace(f,_,S,L,O,z,G){const Y=10*f,re=5*f;return this.int16[Y+0]=_,this.int16[Y+1]=S,this.int16[Y+2]=L,this.float32[re+2]=O,this.float32[re+3]=z,this.float32[re+4]=G,f}}DV.prototype.bytesPerElement=20,br(DV,"StructArrayLayout3i3f20");class M2 extends Nn{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(f,_,S,L){const O=this.length;return this.resize(O+1),this.emplace(O,f,_,S,L)}emplace(f,_,S,L,O){const z=4*f;return this.float32[z+0]=_,this.float32[z+1]=S,this.float32[z+2]=L,this.float32[z+3]=O,f}}M2.prototype.bytesPerElement=16,br(M2,"StructArrayLayout4f16");class hM extends Nn{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint32=new Uint32Array(this.arrayBuffer)}emplaceBack(f){const _=this.length;return this.resize(_+1),this.emplace(_,f)}emplace(f,_){return this.uint32[1*f+0]=_,f}}hM.prototype.bytesPerElement=4,br(hM,"StructArrayLayout1ul4");class K1 extends Nn{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer)}emplaceBack(f,_){const S=this.length;return this.resize(S+1),this.emplace(S,f,_)}emplace(f,_,S){const L=2*f;return this.uint16[L+0]=_,this.uint16[L+1]=S,f}}K1.prototype.bytesPerElement=4,br(K1,"StructArrayLayout2ui4");class AF extends Nn{_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(f,_,S,L,O,z,G,Y,re,me,ye,we,Te){const Ie=this.length;return this.resize(Ie+1),this.emplace(Ie,f,_,S,L,O,z,G,Y,re,me,ye,we,Te)}emplace(f,_,S,L,O,z,G,Y,re,me,ye,we,Te,Ie){const Ve=20*f,Je=10*f;return this.int16[Ve+0]=_,this.int16[Ve+1]=S,this.int16[Ve+2]=L,this.int16[Ve+3]=O,this.int16[Ve+4]=z,this.float32[Je+3]=G,this.float32[Je+4]=Y,this.float32[Je+5]=re,this.float32[Je+6]=me,this.int16[Ve+14]=ye,this.uint32[Je+8]=we,this.uint16[Ve+18]=Te,this.uint16[Ve+19]=Ie,f}}AF.prototype.bytesPerElement=40,br(AF,"StructArrayLayout5i4f1i1ul2ui40");class mM extends Nn{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer)}emplaceBack(f,_,S,L,O,z,G){const Y=this.length;return this.resize(Y+1),this.emplace(Y,f,_,S,L,O,z,G)}emplace(f,_,S,L,O,z,G,Y){const re=8*f;return this.int16[re+0]=_,this.int16[re+1]=S,this.int16[re+2]=L,this.int16[re+4]=O,this.int16[re+5]=z,this.int16[re+6]=G,this.int16[re+7]=Y,f}}mM.prototype.bytesPerElement=16,br(mM,"StructArrayLayout3i2i2i16");class RV extends Nn{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer)}emplaceBack(f,_,S,L,O){const z=this.length;return this.resize(z+1),this.emplace(z,f,_,S,L,O)}emplace(f,_,S,L,O,z){const G=4*f,Y=8*f;return this.float32[G+0]=_,this.float32[G+1]=S,this.float32[G+2]=L,this.int16[Y+6]=O,this.int16[Y+7]=z,f}}RV.prototype.bytesPerElement=16,br(RV,"StructArrayLayout2f1f2i16");class pM extends Nn{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(f,_,S,L,O,z){const G=this.length;return this.resize(G+1),this.emplace(G,f,_,S,L,O,z)}emplace(f,_,S,L,O,z,G){const Y=20*f,re=5*f;return this.uint8[Y+0]=_,this.uint8[Y+1]=S,this.float32[re+1]=L,this.float32[re+2]=O,this.float32[re+3]=z,this.float32[re+4]=G,f}}pM.prototype.bytesPerElement=20,br(pM,"StructArrayLayout2ub4f20");class nu extends Nn{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer)}emplaceBack(f,_,S){const L=this.length;return this.resize(L+1),this.emplace(L,f,_,S)}emplace(f,_,S,L){const O=3*f;return this.uint16[O+0]=_,this.uint16[O+1]=S,this.uint16[O+2]=L,f}}nu.prototype.bytesPerElement=6,br(nu,"StructArrayLayout3ui6");class EF extends Nn{_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(f,_,S,L,O,z,G,Y,re,me,ye,we,Te,Ie,Ve,Je,rt,xt,ut,St,Pt){const Rt=this.length;return this.resize(Rt+1),this.emplace(Rt,f,_,S,L,O,z,G,Y,re,me,ye,we,Te,Ie,Ve,Je,rt,xt,ut,St,Pt)}emplace(f,_,S,L,O,z,G,Y,re,me,ye,we,Te,Ie,Ve,Je,rt,xt,ut,St,Pt,Rt){const ws=30*f,ns=15*f,xs=60*f;return this.int16[ws+0]=_,this.int16[ws+1]=S,this.int16[ws+2]=L,this.float32[ns+2]=O,this.float32[ns+3]=z,this.uint16[ws+8]=G,this.uint16[ws+9]=Y,this.uint32[ns+5]=re,this.uint32[ns+6]=me,this.uint32[ns+7]=ye,this.uint16[ws+16]=we,this.uint16[ws+17]=Te,this.uint16[ws+18]=Ie,this.float32[ns+10]=Ve,this.float32[ns+11]=Je,this.uint8[xs+48]=rt,this.uint8[xs+49]=xt,this.uint8[xs+50]=ut,this.uint32[ns+13]=St,this.int16[ws+28]=Pt,this.uint8[xs+58]=Rt,f}}EF.prototype.bytesPerElement=60,br(EF,"StructArrayLayout3i2f2ui3ul3ui2f3ub1ul1i1ub60");class OV extends Nn{_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(f,_,S,L,O,z,G,Y,re,me,ye,we,Te,Ie,Ve,Je,rt,xt,ut,St,Pt,Rt,ws,ns,xs,us,hs,pn,bn,An,Ln,En,Jn){const un=this.length;return this.resize(un+1),this.emplace(un,f,_,S,L,O,z,G,Y,re,me,ye,we,Te,Ie,Ve,Je,rt,xt,ut,St,Pt,Rt,ws,ns,xs,us,hs,pn,bn,An,Ln,En,Jn)}emplace(f,_,S,L,O,z,G,Y,re,me,ye,we,Te,Ie,Ve,Je,rt,xt,ut,St,Pt,Rt,ws,ns,xs,us,hs,pn,bn,An,Ln,En,Jn,un){const Mn=20*f,Rn=40*f,er=80*f;return this.float32[Mn+0]=_,this.float32[Mn+1]=S,this.int16[Rn+4]=L,this.int16[Rn+5]=O,this.int16[Rn+6]=z,this.int16[Rn+7]=G,this.int16[Rn+8]=Y,this.int16[Rn+9]=re,this.int16[Rn+10]=me,this.int16[Rn+11]=ye,this.int16[Rn+12]=we,this.uint16[Rn+13]=Te,this.uint16[Rn+14]=Ie,this.uint16[Rn+15]=Ve,this.uint16[Rn+16]=Je,this.uint16[Rn+17]=rt,this.uint16[Rn+18]=xt,this.uint16[Rn+19]=ut,this.uint16[Rn+20]=St,this.uint16[Rn+21]=Pt,this.uint16[Rn+22]=Rt,this.uint16[Rn+23]=ws,this.uint16[Rn+24]=ns,this.uint16[Rn+25]=xs,this.uint16[Rn+26]=us,this.uint16[Rn+27]=hs,this.uint32[Mn+14]=pn,this.float32[Mn+15]=bn,this.float32[Mn+16]=An,this.float32[Mn+17]=Ln,this.float32[Mn+18]=En,this.uint8[er+76]=Jn,this.uint16[Rn+39]=un,f}}OV.prototype.bytesPerElement=80,br(OV,"StructArrayLayout2f9i15ui1ul4f1ub1ui80");class TF extends Nn{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(f,_,S,L,O,z){const G=this.length;return this.resize(G+1),this.emplace(G,f,_,S,L,O,z)}emplace(f,_,S,L,O,z,G){const Y=6*f;return this.float32[Y+0]=_,this.float32[Y+1]=S,this.float32[Y+2]=L,this.float32[Y+3]=O,this.float32[Y+4]=z,this.float32[Y+5]=G,f}}TF.prototype.bytesPerElement=24,br(TF,"StructArrayLayout6f24");class a4 extends Nn{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(f,_,S,L,O){const z=this.length;return this.resize(z+1),this.emplace(z,f,_,S,L,O)}emplace(f,_,S,L,O,z){const G=5*f;return this.float32[G+0]=_,this.float32[G+1]=S,this.float32[G+2]=L,this.float32[G+3]=O,this.float32[G+4]=z,f}}a4.prototype.bytesPerElement=20,br(a4,"StructArrayLayout5f20");class fM extends Nn{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(f,_,S,L,O,z,G){const Y=this.length;return this.resize(Y+1),this.emplace(Y,f,_,S,L,O,z,G)}emplace(f,_,S,L,O,z,G,Y){const re=7*f;return this.float32[re+0]=_,this.float32[re+1]=S,this.float32[re+2]=L,this.float32[re+3]=O,this.float32[re+4]=z,this.float32[re+5]=G,this.float32[re+6]=Y,f}}fM.prototype.bytesPerElement=28,br(fM,"StructArrayLayout7f28");class FV extends Nn{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(f,_,S,L,O,z,G,Y,re,me,ye){const we=this.length;return this.resize(we+1),this.emplace(we,f,_,S,L,O,z,G,Y,re,me,ye)}emplace(f,_,S,L,O,z,G,Y,re,me,ye,we){const Te=11*f;return this.float32[Te+0]=_,this.float32[Te+1]=S,this.float32[Te+2]=L,this.float32[Te+3]=O,this.float32[Te+4]=z,this.float32[Te+5]=G,this.float32[Te+6]=Y,this.float32[Te+7]=re,this.float32[Te+8]=me,this.float32[Te+9]=ye,this.float32[Te+10]=we,f}}FV.prototype.bytesPerElement=44,br(FV,"StructArrayLayout11f44");class zV extends Nn{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(f,_,S,L,O,z,G,Y,re){const me=this.length;return this.resize(me+1),this.emplace(me,f,_,S,L,O,z,G,Y,re)}emplace(f,_,S,L,O,z,G,Y,re,me){const ye=9*f;return this.float32[ye+0]=_,this.float32[ye+1]=S,this.float32[ye+2]=L,this.float32[ye+3]=O,this.float32[ye+4]=z,this.float32[ye+5]=G,this.float32[ye+6]=Y,this.float32[ye+7]=re,this.float32[ye+8]=me,f}}zV.prototype.bytesPerElement=36,br(zV,"StructArrayLayout9f36");class i4 extends Nn{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(f,_){const S=this.length;return this.resize(S+1),this.emplace(S,f,_)}emplace(f,_,S){const L=2*f;return this.float32[L+0]=_,this.float32[L+1]=S,f}}i4.prototype.bytesPerElement=8,br(i4,"StructArrayLayout2f8");class BV extends Nn{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint32=new Uint32Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer)}emplaceBack(f,_,S,L){const O=this.length;return this.resize(O+1),this.emplace(O,f,_,S,L)}emplace(f,_,S,L,O){const z=6*f;return this.uint32[3*f+0]=_,this.uint16[z+2]=S,this.uint16[z+3]=L,this.uint16[z+4]=O,f}}BV.prototype.bytesPerElement=12,br(BV,"StructArrayLayout1ul3ui12");class o4 extends Nn{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer)}emplaceBack(f){const _=this.length;return this.resize(_+1),this.emplace(_,f)}emplace(f,_){return this.uint16[1*f+0]=_,f}}o4.prototype.bytesPerElement=2,br(o4,"StructArrayLayout1ui2");class $V extends Nn{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(f,_,S,L,O,z,G,Y,re,me,ye,we,Te,Ie,Ve,Je){const rt=this.length;return this.resize(rt+1),this.emplace(rt,f,_,S,L,O,z,G,Y,re,me,ye,we,Te,Ie,Ve,Je)}emplace(f,_,S,L,O,z,G,Y,re,me,ye,we,Te,Ie,Ve,Je,rt){const xt=16*f;return this.float32[xt+0]=_,this.float32[xt+1]=S,this.float32[xt+2]=L,this.float32[xt+3]=O,this.float32[xt+4]=z,this.float32[xt+5]=G,this.float32[xt+6]=Y,this.float32[xt+7]=re,this.float32[xt+8]=me,this.float32[xt+9]=ye,this.float32[xt+10]=we,this.float32[xt+11]=Te,this.float32[xt+12]=Ie,this.float32[xt+13]=Ve,this.float32[xt+14]=Je,this.float32[xt+15]=rt,f}}$V.prototype.bytesPerElement=64,br($V,"StructArrayLayout16f64");class MF extends Nn{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(f,_,S,L,O,z,G){const Y=this.length;return this.resize(Y+1),this.emplace(Y,f,_,S,L,O,z,G)}emplace(f,_,S,L,O,z,G,Y){const re=10*f,me=5*f;return this.uint16[re+0]=_,this.uint16[re+1]=S,this.uint16[re+2]=L,this.uint16[re+3]=O,this.float32[me+2]=z,this.float32[me+3]=G,this.float32[me+4]=Y,f}}MF.prototype.bytesPerElement=20,br(MF,"StructArrayLayout4ui3f20");class LF extends Nn{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer)}emplaceBack(f){const _=this.length;return this.resize(_+1),this.emplace(_,f)}emplace(f,_){return this.int16[1*f+0]=_,f}}LF.prototype.bytesPerElement=2,br(LF,"StructArrayLayout1i2");class PF extends Nn{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer)}emplaceBack(f){const _=this.length;return this.resize(_+1),this.emplace(_,f)}emplace(f,_){return this.uint8[1*f+0]=_,f}}PF.prototype.bytesPerElement=1,br(PF,"StructArrayLayout1ub1");class jte extends W0{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]}}jte.prototype.size=40;class UV extends AF{get(f){return new jte(this,f)}}br(UV,"CollisionBoxArray");class Nte extends W0{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(f){this._structArray.uint8[this._pos1+49]=f}get hidden(){return this._structArray.uint8[this._pos1+50]}set hidden(f){this._structArray.uint8[this._pos1+50]=f}get crossTileID(){return this._structArray.uint32[this._pos4+13]}set crossTileID(f){this._structArray.uint32[this._pos4+13]=f}get associatedIconIndex(){return this._structArray.int16[this._pos2+28]}get flipState(){return this._structArray.uint8[this._pos1+58]}set flipState(f){this._structArray.uint8[this._pos1+58]=f}}Nte.prototype.size=60;class kte extends EF{get(f){return new Nte(this,f)}}br(kte,"PlacedSymbolArray");class xM extends W0{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(f){this._structArray.uint32[this._pos4+14]=f}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(f){this._structArray.float32[this._pos4+18]=f}get hasIconTextFit(){return this._structArray.uint8[this._pos1+76]}get elevationFeatureIndex(){return this._structArray.uint16[this._pos2+39]}}xM.prototype.size=80;class Ste extends OV{get(f){return new xM(this,f)}}br(Ste,"SymbolInstanceArray");class Cte extends xl{getoffsetX(f){return this.float32[1*f+0]}}br(Cte,"GlyphOffsetArray");class gM extends zi{getx(f){return this.int16[2*f+0]}gety(f){return this.int16[2*f+1]}}br(gM,"SymbolLineVertexArray");class Ate extends W0{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]}}Ate.prototype.size=12;class qV extends BV{get(f){return new Ate(this,f)}}br(qV,"FeatureIndexArray");class Ete extends K1{geta_centroid_pos0(f){return this.uint16[2*f+0]}geta_centroid_pos1(f){return this.uint16[2*f+1]}}br(Ete,"FillExtrusionCentroidArray");class VV extends W0{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]}}VV.prototype.size=6;class HV extends Wo{get(f){return new VV(this,f)}}br(HV,"FillExtrusionWallArray");const Tte=zn([{name:"a_pos",components:2,type:"Int16"}],4),ZTe=zn([{name:"a_circle_z_offset",components:1,type:"Float32"}],4),XTe=zn([{name:"a_pos_3",components:3,type:"Int16"},{name:"a_pos_normal_3",components:3,type:"Int16"}]);class sc{constructor(f=[]){this.segments=f}_prepareSegment(f,_,S,L,O){let z=this.segments[this.segments.length-1];return f>sc.MAX_VERTEX_ARRAY_LENGTH&&Or(`Max vertices per segment is ${sc.MAX_VERTEX_ARRAY_LENGTH}: bucket requested ${f}`),(!z||z.vertexLength+f>sc.MAX_VERTEX_ARRAY_LENGTH||z.sortKey!==L||O!==void 0&&z&&z.batchIndex!==void 0&&z.batchIndex!==O)&&(z={vertexOffset:_,primitiveOffset:S,vertexLength:0,primitiveLength:0},L!==void 0&&(z.sortKey=L),O!==void 0&&(z.batchIndex=O),this.segments.push(z)),z}prepareSegment(f,_,S,L,O){return this._prepareSegment(f,_.length,S.length,L,O)}get(){return this.segments}destroy(){for(const f of this.segments)for(const _ in f.vaos)f.vaos[_].destroy()}static simpleSegment(f,_,S,L){return new sc([{vertexOffset:f,primitiveOffset:_,vertexLength:S,primitiveLength:L,vaos:{},sortKey:0}])}}function IF(k,f){return 256*(k=pt(Math.floor(k),0,255))+pt(Math.floor(f),0,255)}sc.MAX_VERTEX_ARRAY_LENGTH=Math.pow(2,16)-1,br(sc,"SegmentVector");const QTe=zn([{name:"a_pattern",components:4,type:"Uint16"},{name:"a_pixel_ratio",components:1,type:"Float32"}]),JTe=zn([{name:"a_pattern_b",components:4,type:"Uint16"}]),e6e=zn([{name:"a_dash",components:4,type:"Uint16"}]);class yM{constructor(){this.ids=[],this.uniqueIds=[],this.positions=[],this.indexed=!1}add(f,_,S,L){this.ids.push(GV(f)),this.positions.push(_,S,L)}eachPosition(f,_){const S=GV(f);let L=0,O=this.ids.length-1;for(;L>1;this.ids[z]>=S?O=z:L=z+1}for(;this.ids[L]===S;)_(this.positions[3*L],this.positions[3*L+1],this.positions[3*L+2]),L++}static serialize(f,_){const S=new Float64Array(f.ids),L=new Uint32Array(f.positions);return vM(S,L,0,S.length-1),_&&(_.add(S.buffer),_.add(L.buffer)),{ids:S,positions:L}}static deserialize(f){const _=new yM;let S;_.ids=f.ids,_.positions=f.positions;for(const L of _.ids)L!==S&&_.uniqueIds.push(L),S=L;return _.indexed=!0,_}}function GV(k){const f=+k;return Number.isSafeInteger(f)?f:ld(String(k))}function vM(k,f,_,S){for(;_>1];let O=_-1,z=S+1;for(;;){do O++;while(k[O]L);if(O>=z)break;Pv(k,O,z),Pv(f,3*O,3*z),Pv(f,3*O+1,3*z+1),Pv(f,3*O+2,3*z+2)}z-_`u_${O}`),this.type=S,this.context=L}setUniform(f,_,S,L,O){const z=L.constantOr(this.value);_.set(f,O,z instanceof Ys?z.toPremultipliedRenderColor(this.lutExpression&&this.lutExpression.kind==="constant"&&this.lutExpression.value==="none"?null:this.context.lut):z)}getBinding(f,_){return this.type==="color"?new s6e(f):new Fh(f)}}class xe{constructor(f,_){this.uniformNames=_.map(S=>`u_${S}`),this.pattern=null,this.patternTransition=null,this.pixelRatio=1}setConstantPatternPositions(f,_){this.pixelRatio=f.pixelRatio||1,this.pattern=f.tl.concat(f.br),this.patternTransition=_?_.tl.concat(_.br):this.pattern}setUniform(f,_,S,L,O){let z=null;O!=="u_pattern"&&O!=="u_dash"||(z=this.pattern),O==="u_pattern_b"&&(z=this.patternTransition),O==="u_pixel_ratio"&&(z=this.pixelRatio),z&&_.set(f,O,z)}getBinding(f,_){return _==="u_pattern"||_==="u_pattern_b"||_==="u_dash"?new t6e(f):new Fh(f)}}class Ne{constructor(f,_,S,L){this.expression=f,this.type=S,this.maxValue=0,this.paintVertexAttributes=_.map(O=>({name:`a_${O}`,type:"Float32",components:S==="color"?2:1,offset:0})),this.paintVertexArray=new L}populatePaintArray(f,_,S,L,O,z,G,Y){const re=this.paintVertexArray.length,me=this.expression.kind==="composite"||this.expression.kind==="source"?this.expression.evaluate(new Si(0,{brightness:z,worldview:Y}),_,{},O,L,G):this.expression.kind==="constant"&&this.expression.value,ye=X(this.lutExpression,_,{},L,O,z,G,Y);this.paintVertexArray.resize(f),this._setPaintValue(re,f,me,ye?null:this.context.lut)}updatePaintArray(f,_,S,L,O,z,G,Y){const re=this.expression.kind==="composite"||this.expression.kind==="source"?this.expression.evaluate({zoom:0,brightness:G,worldview:Y},S,L,void 0,O):this.expression.kind==="constant"&&this.expression.value,me=X(this.lutExpression,S,L,O,void 0,G,void 0,Y);this._setPaintValue(f,_,re,me?null:this.context.lut)}_setPaintValue(f,_,S,L){if(this.type==="color"){const O=Z(S.toPremultipliedRenderColor(L));for(let z=f;z<_;z++)this.paintVertexArray.emplace(z,O[0],O[1])}else{for(let O=f;O<_;O++)this.paintVertexArray.emplace(O,S);this.maxValue=Math.max(this.maxValue,Math.abs(S))}}upload(f){this.paintVertexArray&&this.paintVertexArray.arrayBuffer&&(this.paintVertexBuffer&&this.paintVertexBuffer.buffer?this.paintVertexBuffer.updateData(this.paintVertexArray):this.paintVertexBuffer=f.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(f,_,S,L,O,z){this.expression=f,this.uniformNames=_.map(G=>`u_${G}_t`),this.type=S,this.useIntegerZoom=L,this.context=O,this.maxValue=0,this.paintVertexAttributes=_.map(G=>({name:`a_${G}`,type:"Float32",components:S==="color"?4:2,offset:0})),this.paintVertexArray=new z}populatePaintArray(f,_,S,L,O,z,G,Y){const re=this.expression.evaluate(new Si(this.context.zoom,{brightness:z,worldview:Y}),_,{},O,L,G),me=this.expression.evaluate(new Si(this.context.zoom+1,{brightness:z,worldview:Y}),_,{},O,L,G),ye=X(this.lutExpression,_,{},L,O,z,G,Y),we=this.paintVertexArray.length;this.paintVertexArray.resize(f),this._setPaintValue(we,f,re,me,ye?null:this.context.lut)}updatePaintArray(f,_,S,L,O,z,G,Y){const re=this.expression.evaluate({zoom:this.context.zoom,brightness:G,worldview:Y},S,L,void 0,O),me=this.expression.evaluate({zoom:this.context.zoom+1,brightness:G,worldview:Y},S,L,void 0,O),ye=X(this.lutExpression,S,L,O,void 0,G,void 0,Y);this._setPaintValue(f,_,re,me,ye?null:this.context.lut)}_setPaintValue(f,_,S,L,O){if(this.type==="color"){const z=Z(S.toPremultipliedRenderColor(O)),G=Z(L.toPremultipliedRenderColor(O));for(let Y=f;Y<_;Y++)this.paintVertexArray.emplace(Y,z[0],z[1],G[0],G[1])}else{for(let z=f;z<_;z++)this.paintVertexArray.emplace(z,S,L);this.maxValue=Math.max(this.maxValue,Math.abs(S),Math.abs(L))}}upload(f){this.paintVertexArray&&this.paintVertexArray.arrayBuffer&&(this.paintVertexBuffer&&this.paintVertexBuffer.buffer?this.paintVertexBuffer.updateData(this.paintVertexArray):this.paintVertexBuffer=f.createVertexBuffer(this.paintVertexArray,this.paintVertexAttributes,this.expression.isStateDependent||!this.expression.isLightConstant))}destroy(){this.paintVertexBuffer&&this.paintVertexBuffer.destroy()}setUniform(f,_,S,L,O){const z=this.useIntegerZoom?Math.floor(S.zoom):S.zoom,G=pt(this.expression.interpolationFactor(z,this.context.zoom,this.context.zoom+1),0,1);_.set(f,O,G)}getBinding(f,_){return new Fh(f)}}class We{constructor(f,_,S,L,O){this.expression=f,this.layerId=O,this.paintVertexAttributes=(S==="array"?e6e:QTe).members;for(let z=0;z<_.length;++z);this.paintVertexArray=new L,this.paintTransitionVertexArray=new zC}populatePaintArray(f,_,S,L){const O=this.paintVertexArray.length;this.paintVertexArray.resize(f),this._setPaintValues(O,f,_.patterns&&_.patterns[this.layerId],S)}updatePaintArray(f,_,S,L,O,z,G){this._setPaintValues(f,_,S.patterns&&S.patterns[this.layerId],z)}_setPaintValues(f,_,S,L){if(!L||!S)return;const O=L[S[0]],z=L[S[1]];if(O){if(O){const{tl:G,br:Y,pixelRatio:re}=O;for(let me=f;me<_;me++)this.paintVertexArray.emplace(me,G[0],G[1],Y[0],Y[1],re)}if(z){this.paintTransitionVertexArray.resize(this.paintVertexArray.length);const{tl:G,br:Y}=z;for(let re=f;re<_;re++)this.paintTransitionVertexArray.emplace(re,G[0],G[1],Y[0],Y[1])}}}upload(f){const _=this.expression.isStateDependent||!this.expression.isLightConstant;this.paintVertexArray&&this.paintVertexArray.arrayBuffer&&(this.paintVertexBuffer=f.createVertexBuffer(this.paintVertexArray,this.paintVertexAttributes,_)),this.paintTransitionVertexArray&&this.paintTransitionVertexArray.length&&(this.paintTransitionVertexBuffer=f.createVertexBuffer(this.paintTransitionVertexArray,JTe.members,_))}destroy(){this.paintVertexBuffer&&this.paintVertexBuffer.destroy(),this.paintTransitionVertexBuffer&&this.paintTransitionVertexBuffer.destroy()}}class He{constructor(f,_,S=()=>!0){this.binders={},this._buffers=[],this.context=_;const L=[],O=f;for(const z in f.paint._values){const G=O.paint.get(z);if(z.endsWith("-use-theme")||!S(z)||!(G instanceof E2&&Yo(G.property.specification)))continue;const Y=it(z,f.type),re=G.value,me=G.property.specification.type,ye=!!G.property.useIntegerZoom,we=z==="line-dasharray"||z.endsWith("pattern"),Te=O.paint.get(`${z}-use-theme`),Ie=z==="line-dasharray"&&O.layout.get("line-cap").value.kind!=="constant"||Te&&Te.value.kind!=="constant";if(re.kind!=="constant"||Ie)if(re.kind==="source"||Ie||we){const Ve=Ot(z,me,"source");this.binders[z]=we?new We(re,Y,me,Ve,f.id):new Ne(re,Y,me,Ve),L.push(`/a_${z}`)}else{const Ve=Ot(z,me,"composite");this.binders[z]=new Le(re,Y,me,ye,_,Ve),L.push(`/z_${z}`)}else this.binders[z]=we?new xe(re.value,Y):new oe(re.value,Y,me,_),L.push(`/u_${z}`);Te&&(this.binders[z].lutExpression=Te.value)}this.cacheKey=L.sort().join("")}getMaxValue(f){const _=this.binders[f];return _ instanceof Ne||_ instanceof Le?_.maxValue:0}populatePaintArrays(f,_,S,L,O,z,G,Y){for(const re in this.binders){const me=this.binders[re];me.context=this.context,(me instanceof Ne||me instanceof Le||me instanceof We)&&me.populatePaintArray(f,_,S,L,O,z,G,Y)}}setConstantPatternPositions(f,_){for(const S in this.binders){const L=this.binders[S];L instanceof xe&&L.setConstantPatternPositions(f,_)}}getPatternTransitionVertexBuffer(f){const _=this.binders[f];return _ instanceof We?_.paintTransitionVertexBuffer:null}updatePaintArrays(f,_,S,L,O,z,G,Y,re,me){let ye=!1;const we=Object.keys(f),Te=we.length!==0&&!Y,Ie=Te?we:_.uniqueIds;this.context.lut=O.lut;for(const Ve in this.binders){const Je=this.binders[Ve];if(Je.context=this.context,(Je instanceof Ne||Je instanceof Le||Je instanceof We)&&Je.expression&&Je.expression.kind&&Je.expression.kind!=="constant"&&(Je.expression.isStateDependent===!0||Je.expression.isLightConstant===!1)){const rt=O.paint.get(Ve);Je.expression=rt.value;for(const xt of Ie){const ut=f[xt.toString()];_.eachPosition(xt,(St,Pt,Rt)=>{const ws=L.feature(St);Je.updatePaintArray(Pt,Rt,ws,ut,z,G,re,me)})}if(!Te)for(const xt of S.uniqueIds){const ut=f[xt.toString()];S.eachPosition(xt,(St,Pt,Rt)=>{const ws=L.feature(St);Je.updatePaintArray(Pt,Rt,ws,ut,z,G,re,me)})}ye=!0}}return ye}defines(){const f=[];for(const _ in this.binders){const S=this.binders[_];(S instanceof oe||S instanceof xe)&&f.push(...S.uniformNames.map(L=>`#define HAS_UNIFORM_${L}`))}return f}getPaintVertexBuffers(){return this._buffers}getUniforms(f){const _=[];for(const S in this.binders){const L=this.binders[S];if(L instanceof oe||L instanceof xe||L instanceof Le)for(const O of L.uniformNames)_.push({name:O,property:S,binding:L.getBinding(f,O)})}return _}setUniforms(f,_,S,L,O){for(const{name:z,property:G,binding:Y}of S)this.binders[G].setUniform(f,Y,O,L.get(G),z)}updatePaintBuffers(){this._buffers=[];for(const f in this.binders){const _=this.binders[f];(_ instanceof Ne||_ instanceof Le||_ instanceof We)&&_.paintVertexBuffer&&this._buffers.push(_.paintVertexBuffer),_ instanceof We&&_.paintTransitionVertexBuffer&&this._buffers.push(_.paintTransitionVertexBuffer)}}upload(f){for(const _ in this.binders){const S=this.binders[_];(S instanceof Ne||S instanceof Le||S instanceof We)&&S.upload(f)}this.updatePaintBuffers()}destroy(){for(const f in this.binders){const _=this.binders[f];(_ instanceof Ne||_ instanceof Le||_ instanceof We)&&_.destroy()}}}class tt{constructor(f,_,S=()=>!0){this.programConfigurations={};for(const L of f)this.programConfigurations[L.id]=new He(L,_,S);this.needsUpload=!1,this._featureMap=new yM,this._featureMapWithoutIds=new yM,this._bufferOffset=0,this._idlessCounter=0}populatePaintArrays(f,_,S,L,O,z,G,Y,re){for(const me in this.programConfigurations)this.programConfigurations[me].populatePaintArrays(f,_,L,O,z,G,Y,re);_.id!==void 0?this._featureMap.add(_.id,S,this._bufferOffset,f):(this._featureMapWithoutIds.add(this._idlessCounter,S,this._bufferOffset,f),this._idlessCounter+=1),this._bufferOffset=f,this.needsUpload=!0}updatePaintArrays(f,_,S,L,O,z,G,Y){for(const re of S)this.needsUpload=this.programConfigurations[re.id].updatePaintArrays(f,this._featureMap,this._featureMapWithoutIds,_,re,L,O,z,G||0,Y)||this.needsUpload}get(f){return this.programConfigurations[f]}upload(f){if(this.needsUpload){for(const _ in this.programConfigurations)this.programConfigurations[_].upload(f);this.needsUpload=!1}}destroy(){for(const f in this.programConfigurations)this.programConfigurations[f].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,f){return dt[k]||[k.replace(`${f}-`,"").replace(/-/g,"_")]}const jt={"line-pattern":{source:Gw,composite:Gw},"fill-pattern":{source:Gw,composite:Gw},"fill-extrusion-pattern":{source:Gw,composite:Gw},"line-dasharray":{source:zC,composite:zC}},wt={color:{source:i4,composite:M2},number:{source:xl,composite:i4}};function Ot(k,f,_){const S=jt[k];return S&&S[_]||wt[f][_]}br(oe,"ConstantBinder"),br(xe,"PatternConstantBinder"),br(Ne,"SourceExpressionBinder"),br(We,"PatternCompositeBinder"),br(Le,"CompositeExpressionBinder"),br(He,"ProgramConfiguration",{omit:["_buffers"]}),br(tt,"ProgramConfigurationSet");const Vt=lr/Math.PI/2,Ct=64,ks=[Ct,32,16],ss=-Vt,Ns=Vt;function Gt(k,f,_,S=Vt){return _=$n(_),[k*Math.sin(_)*S,-f*S,k*Math.cos(_)*S]}function es(k,f,_){return Gt(Math.cos($n(k)),Math.sin($n(k)),f,_)}const fs=63710088e-1,Ws=2*Math.PI*fs;class As{constructor(f,_){if(isNaN(f)||isNaN(_))throw new Error(`Invalid LngLat object: (${f}, ${_})`);if(this.lng=+f,this.lat=+_,this.lat>90||this.lat<-90)throw new Error("Invalid LngLat latitude value: must be between -90 and 90")}wrap(){return new As(At(this.lng,-180,180),this.lat)}toArray(){return[this.lng,this.lat]}toString(){return`LngLat(${this.lng}, ${this.lat})`}distanceTo(f){const _=Math.PI/180,S=this.lat*_,L=f.lat*_,O=Math.sin(S)*Math.sin(L)+Math.cos(S)*Math.cos(L)*Math.cos((f.lng-this.lng)*_);return fs*Math.acos(Math.min(O,1))}toBounds(f=0){const _=360*f/40075017,S=_/Math.cos(Math.PI/180*this.lat);return new gn({lng:this.lng-S,lat:this.lat-_},{lng:this.lng+S,lat:this.lat+_})}toEcef(f){return es(this.lat,this.lng,Vt+f*Vt/fs)}static convert(f){if(f instanceof As)return f;if(Array.isArray(f)&&(f.length===2||f.length===3))return new As(Number(f[0]),Number(f[1]));if(!Array.isArray(f)&&typeof f=="object"&&f!==null)return new As(Number("lng"in f?f.lng:f.lon),Number(f.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 gn{constructor(f,_){f&&(_?this.setSouthWest(f).setNorthEast(_):Array.isArray(f)&&f.length===4?this.setSouthWest([f[0],f[1]]).setNorthEast([f[2],f[3]]):this.setSouthWest(f[0]).setNorthEast(f[1]))}setNorthEast(f){return this._ne=f instanceof As?new As(f.lng,f.lat):As.convert(f),this}setSouthWest(f){return this._sw=f instanceof As?new As(f.lng,f.lat):As.convert(f),this}extend(f){const _=this._sw,S=this._ne;let L,O;if(f instanceof As)L=f,O=f;else{if(!(f instanceof gn))return Array.isArray(f)?f.length===4||f.every(Array.isArray)?this.extend(gn.convert(f)):this.extend(As.convert(f)):typeof f=="object"&&f!==null&&f.hasOwnProperty("lat")&&(f.hasOwnProperty("lon")||f.hasOwnProperty("lng"))?this.extend(As.convert(f)):this;if(L=f._sw,O=f._ne,!L||!O)return this}return _||S?(_.lng=Math.min(L.lng,_.lng),_.lat=Math.min(L.lat,_.lat),S.lng=Math.max(O.lng,S.lng),S.lat=Math.max(O.lat,S.lat)):(this._sw=new As(L.lng,L.lat),this._ne=new As(O.lng,O.lat)),this}getCenter(){return new As((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 As(this.getWest(),this.getNorth())}getSouthEast(){return new As(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(f){const{lng:_,lat:S}=As.convert(f);let L=this._sw.lng<=_&&_<=this._ne.lng;return this._sw.lng>this._ne.lng&&(L=this._sw.lng>=_&&_>=this._ne.lng),this._sw.lat<=S&&S<=this._ne.lat&&L}static convert(f){if(f)return f instanceof gn?f:new gn(f)}}function an(k){return Ws*Math.cos(k*Math.PI/180)}function Dn(k){return(180+k)/360}function Gn(k){return(180-180/Math.PI*Math.log(Math.tan(Math.PI/4+k*Math.PI/360)))/360}function en(k,f){return k/an(f)}function Ms(k){return 360*k-180}function mn(k){return 360/Math.PI*Math.atan(Math.exp((180-360*k)*Math.PI/180))-90}function vn(k,f){return k*an(mn(f))}const kn=85.051129;function _r(k){return Math.cos($n(pt(k,-85.051129,kn)))}function cr(k,f){const _=pt(f,0,25.5),S=Math.pow(2,_);return _r(k)*Ws/(512*S)}function dr(k){return 1/Math.cos(k*Math.PI/180)}function Bn(k,f=0){const _=Math.exp(Math.PI*(1-(k.y+f/lr)/(1<=Y?(wa(k,f,_,re,me,O,ye,G,Y),wa(k,re,me,S,L,ye,z,G,Y)):k.push(z)}function Yr(k,f,_){let S=k[0],L=S.x,O=S.y;f(S);const z=[S];for(let G=1;Gk.x+1||Sk.y+1)&&Or("Geometry exceeds allowed extent, reduce your vector tile buffer size"),k}function Oa(k,f,_){const S=k.loadGeometry(),L=k.extent,O=lr/L;if(f&&_&&_.projection.isReprojectedInTileSpace){const z=1<{const Te=Ms((f.x+we.x/L)/z),Ie=mn((f.y+we.y/L)/z),Ve=me.project(Te,Ie);we.x=(Ve.x*G-Y)*L,we.y=(Ve.y*G-re)*L};for(let we=0;we=L||Ie.y<0||Ie.y>=L||(ye(Ie),Te.push(Ie));S[we]=Te}}for(const z of S)for(const G of z)Bi(G,O);return S}function $i(k,f){return{type:k.type,id:k.id,properties:k.properties,geometry:f?Oa(k):[]}}class li{constructor(f,_,S,L,O){this.properties={},this.extent=S,this.type=0,this.id=void 0,this._pbf=f,this._geometry=-1,this._keys=L,this._values=O,f.readFields(Fo,this,_)}loadGeometry(){const f=this._pbf;f.pos=this._geometry;const _=f.readVarint()+f.pos,S=[];let L,O=1,z=0,G=0,Y=0;for(;f.pos<_;){if(z<=0){const re=f.readVarint();O=7&re,z=re>>3}if(z--,O===1||O===2)G+=f.readSVarint(),Y+=f.readSVarint(),O===1&&(L&&S.push(L),L=[]),L&&L.push(new Xt(G,Y));else{if(O!==7)throw new Error(`unknown command ${O}`);L&&L.push(L[0].clone())}}return L&&S.push(L),S}bbox(){const f=this._pbf;f.pos=this._geometry;const _=f.readVarint()+f.pos;let S=1,L=0,O=0,z=0,G=1/0,Y=-1/0,re=1/0,me=-1/0;for(;f.pos<_;){if(L<=0){const ye=f.readVarint();S=7&ye,L=ye>>3}if(L--,S===1||S===2)O+=f.readSVarint(),z+=f.readSVarint(),OY&&(Y=O),zme&&(me=z);else if(S!==7)throw new Error(`unknown command ${S}`)}return[G,re,Y,me]}toGeoJSON(f,_,S){const L=this.extent*Math.pow(2,S),O=this.extent*f,z=this.extent*_,G=this.loadGeometry();function Y(we){return[360*(we.x+O)/L-180,360/Math.PI*Math.atan(Math.exp((1-2*(we.y+z)/L)*Math.PI))-90]}function re(we){return we.map(Y)}let me;if(this.type===1){const we=[];for(const Ie of G)we.push(Ie[0]);const Te=re(we);me=we.length===1?{type:"Point",coordinates:Te[0]}:{type:"MultiPoint",coordinates:Te}}else if(this.type===2){const we=G.map(re);me=we.length===1?{type:"LineString",coordinates:we[0]}:{type:"MultiLineString",coordinates:we}}else{if(this.type!==3)throw new Error("unknown feature type");{const we=function(Ie){const Ve=Ie.length;if(Ve<=1)return[Ie];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[f];const _=this._pbf.readVarint()+this._pbf.pos;return new li(this._pbf,_,this.extent,this._keys,this._values)}}function nc(k,f,_){k===15?f.version=_.readVarint():k===1?f.name=_.readString():k===5?f.extent=_.readVarint():k===2?f._features.push(_.pos):k===3?f._keys.push(_.readString()):k===4&&f._values.push(function(S){let L=null;const O=S.readVarint()+S.pos;for(;S.pos>3;L=z===1?S.readString():z===2?S.readFloat():z===3?S.readDouble():z===4?S.readVarint64():z===5?S.readVarint():z===6?S.readSVarint():z===7?S.readBoolean():null}if(L==null)throw new Error("unknown feature value");return L}(_))}class Zo{constructor(f,_){this.layers=f.readFields(Pi,{},_)}}function Pi(k,f,_){if(k===3){const S=new td(_,_.readVarint()+_.pos);S.length&&(f[S.name]=S)}}const Ii="3d_elevation_id",rc="level";class hd{constructor(){this._valid=!1}reset(f){return this.feature=f,this._valid=!0,this._geometry=f.loadGeometry(),this._geometry.length!==0&&this._geometry[0].length!==0||(this._valid=!1),this}geometry(f,_){return this._valid&&f(_(this._geometry)),this}require(f,_,S){return this.get(f,!0,_,S)}optional(f,_,S){return this.get(f,!1,_,S)}success(){return this._valid}get(f,_,S,L){const O=this.feature.properties.hasOwnProperty(f)?+this.feature.properties[f]:void 0;return this._valid&&O!==void 0&&!Number.isNaN(O)?S(L?L(O):O):_&&(this._valid=!1),this}}class Xo{constructor(f,_){this.featureFunc=f,this.vertexFunc=_}parseFeature(f,_,S){return this.featureFunc(f,_,S)}parseVertex(f,_,S){return this.vertexFunc(f,_,S)}}const vi=new Xo((k,f,_)=>k.reset(f).require(Ii,S=>{_.id=S}).optional("fixed_height_relative",S=>{_.constantHeight=S},Ol.decodeRelativeHeight).geometry(S=>{_.bounds=S},Zd).success(),(k,f,_)=>k.reset(f).require(Ii,S=>{_.id=S}).require("elevation_idx",S=>{_.idx=S}).require("extent",S=>{_.extent=S}).require("height_relative",S=>{_.height=S},Ol.decodeRelativeHeight).geometry(S=>{_.position=S},Ol.getPoint).success()),Hc=new Xo((k,f,_)=>k.reset(f).require(Ii,S=>{_.id=S}).optional("fixed_height",S=>{_.constantHeight=S},Ol.decodeMetricHeight).geometry(S=>{_.bounds=S},Zd).success(),(k,f,_)=>k.reset(f).require(Ii,S=>{_.id=S}).require("elevation_idx",S=>{_.idx=S}).require("extent",S=>{_.extent=S}).require("height",S=>{_.height=S},Ol.decodeMetricHeight).geometry(S=>{_.position=S},Ol.getPoint).success());class Ol{static getPoint(f){return Xs(f[0][0].x,f[0][0].y)}static decodeRelativeHeight(f){return 1e-4*f*5}static decodeMetricHeight(f){return 1e-4*f}static getVersionSchema(f){return f?f==="1.0.1"?Hc:void 0:vi}static parse(f){const _=[],S=[],L=f.length,O=new hd;for(let z=0;z=0);if(O===0)return 0;O!==f.length&&(_=!1)}return _?2:1}function zh(k,f){for(const _ of k.projections){const S=bh(f,k.points[0],_.axis);if(_.projection[1]S[1])return 0}return 1}function gp(k,f){let _=0;const S=[0,0,0,0];for(let L=0;L=0&&_++;return _}class Oy{constructor(f,_){this.points=f||new Array(8).fill([0,0,0]),this.planes=_||new Array(6).fill([0,0,0,0]),this.bounds=ul.fromPoints(this.points),this.projections=[],this.frustumEdges=[qe([],this.points[2],this.points[3]),qe([],this.points[0],this.points[3]),qe([],this.points[4],this.points[0]),qe([],this.points[5],this.points[1]),qe([],this.points[6],this.points[2]),qe([],this.points[7],this.points[3])];for(const S of this.frustumEdges){const L=[0,-S[2],S[1]],O=[S[2],0,-S[0]];this.projections.push({axis:L,projection:bh(this.points,this.points[0],L)}),this.projections.push({axis:O,projection:bh(this.points,this.points[0],O)})}}static fromInvProjectionMatrix(f,_,S,L){const O=Math.pow(2,S),z=[[-1,1,-1,1],[1,1,-1,1],[1,-1,-1,1],[-1,-1,-1,1],[-1,1,1,1],[1,1,1,1],[1,-1,1,1],[-1,-1,1,1]].map(re=>{const me=nt([],re,f),ye=1/me[3]/_*O;return(we=me)[0]=(Te=me)[0]*(Ie=[ye,ye,L?1/me[3]:ye,ye])[0],we[1]=Te[1]*Ie[1],we[2]=Te[2]*Ie[2],we[3]=Te[3]*Ie[3],we;var we,Te,Ie}),G=[[0,1,2],[6,5,4],[0,3,7],[2,1,5],[3,2,6],[0,4,5]].map(re=>{const me=Me([],ze([],qe([],z[re[0]],z[re[1]]),qe([],z[re[2]],z[re[1]]))),ye=-De(me,z[re[1]]);return me.concat(ye)}),Y=[];for(let re=0;rere[1]||re[0]>Y[1])return 0}return 1}containsPoint(f){for(const _ of this.planes){const S=_[3];if(De([_[0],_[1],_[2]],f)+S<0)return!1}return!0}}class ul{static fromPoints(f){const _=[1/0,1/0,1/0],S=[-1/0,-1/0,-1/0];for(const L of f)ee(_,_,L),le(S,S,L);return new ul(_,S)}static fromTileIdAndHeight(f,_,S){const L=1<f.max[_]||f.min[_]>this.max[_])return!1;return!0}intersectsAabbXY(f){return!(this.min[0]>f.max[0]||f.min[0]>this.max[0]||this.min[1]>f.max[1]||f.min[1]>this.max[1])}encapsulate(f){for(let _=0;_<3;_++)this.min[_]=Math.min(this.min[_],f.min[_]),this.max[_]=Math.max(this.max[_],f.max[_])}encapsulatePoint(f){for(let _=0;_<3;_++)this.min[_]=Math.min(this.min[_],f[_]),this.max[_]=Math.max(this.max[_],f[_])}closestPoint(f){return[Math.max(Math.min(this.max[0],f[0]),this.min[0]),Math.max(Math.min(this.max[1],f[1]),this.min[1]),Math.max(Math.min(this.max[2],f[2]),this.min[2])]}}br(ul,"Aabb");class Iv{constructor(f,_){this.feature=f,this.metersToTile=_,this.index=0}get(){const f=this.feature.vertices[this.index],_=this.feature.vertexProps[this.index].dir,S=_[1],L=-_[0],O=(f.extent+1)*this.metersToTile;return[new Xt(Math.trunc(f.position[0]+S*O),Math.trunc(f.position[1]+L*O)),new Xt(Math.trunc(f.position[0]-S*O),Math.trunc(f.position[1]-L*O))]}next(){this.index++}valid(){return this.index{return G.a0?he(Y,Y,1/re):J(Y,0,0,1)}getSafeArea(){return this.safeArea}isTunnel(){return this.heightRange.max<=-5}getClosestEdge(f){if(this.edges.length===0)return;let _=0,S=Number.POSITIVE_INFINITY,L=0;const[O,z,G,Y,re,me,ye]=this._tmpVec2;rn(ye,f.x,f.y);const we=new Fu(ye,null);for(let Te=0;Te0?In(Y,G)/St:0,Rt=pt(Pt,0,1),ws=Math.abs((Pt-Rt)*this.edgeProps[Te].len);_n(re,ye,Je),rn(me,Ve[1],-Ve[0]);const ns=ws+Math.abs(In(re,me));ns=0;--z){const G=this.edges[z].a,Y=this.edges[z].b,{position:re,height:me,extent:ye}=this.vertices[G],{position:we,height:Te,extent:Ie}=this.vertices[Y],Ve=this.vertexProps[G].dir,Je=this.vertexProps[Y].dir;if(J(_,re[0]/f,re[1]/f,me),J(S,we[0]/f,we[1]/f,Te),J(L,Ve[1],-Ve[0],0),he(L,L,ye),J(O,Je[1],-Je[0],0),he(O,O,Ie),this.distSqLines(Q(_[0]+.5*L[0],_[1]+.5*L[1],_[2]+.5*L[2]),Q(S[0]-.5*O[0],S[1]-.5*O[1],S[2]-.5*O[2]),Q(_[0]-.5*L[0],_[1]-.5*L[1],_[2]-.5*L[2]),Q(S[0]+.5*O[0],S[1]+.5*O[1],S[2]+.5*O[2]))<=.0025000000000000005)continue;const rt=this.vertices.length,xt=Ps(_t(),re,we);this.vertices.push({position:Zs(xt,xt,.5),height:.5*(me+Te),extent:.5*(ye+Ie)});const ut=Ps(_t(),Ve,Je);this.vertexProps.push({dir:Un(ut,ut)}),this.edges.splice(z,1),this.edgeProps.splice(z,1),this.edges.push({a:G,b:rt}),this.edges.push({a:rt,b:Y});const St=_n(_t(),this.vertices[rt].position,re),Pt=gr(St),Rt={vec:St,dir:Zs(_t(),St,1/Pt),len:Pt};this.edgeProps.push(Rt),this.edgeProps.push(Rt)}}distSqLines(f,_,S,L){const O=ue(W(),_,f),z=ue(W(),L,S),G=ue(W(),f,S),Y=De(O,O),re=De(O,z),me=De(O,G),ye=De(z,z),we=De(z,G),Te=Y*ye-re*re;if(Te===0)return fe(ke(O,S,L,De(G,z)/De(z,z)),f);const Ie=(Y*we-re*me)/Te;return fe(ke(O,f,_,(re*we-me*ye)/Te),ke(z,S,L,Ie))}}class cc{static parseFrom(f,_){const S=Ol.parse(f);if(!S)return[];let{vertices:L,features:O}=S;const z=1/Bn(_);O.sort((me,ye)=>me.id-ye.id),L.sort((me,ye)=>me.id-ye.id||me.idx-ye.idx),L=L.filter((me,ye,we)=>ye===we.findIndex(Te=>Te.id===me.id&&Te.idx===me.idx));const G=new Array;let Y=0;const re=L.length;for(const me of O){if(me.constantHeight){G.push(new Dv(me.id,me.bounds,me.constantHeight));continue}for(;Y!==re&&L[Y].idL.id===S)}}class _c{constructor(f,_){this.zScale=1,this.xOffset=0,this.yOffset=0,f.equals(_)||(this.zScale=Math.pow(2,_.z-f.z),this.xOffset=(f.x*this.zScale-_.x)*lr,this.yOffset=(f.y*this.zScale-_.y)*lr)}constantElevation(f,_){if(f.constantHeight!=null)return this.computeBiasedHeight(f.constantHeight,_)}pointElevation(f,_,S){const L=this.constantElevation(_,S);return L??(f.x=f.x*this.zScale+this.xOffset,f.y=f.y*this.zScale+this.yOffset,this.computeBiasedHeight(_.pointElevation(f),S))}computeBiasedHeight(f,_){return _<=0?f:f+_*vt(0,_,f>=0?f:Math.abs(.5*f))}}br(Dv,"ElevationFeature");class Al{constructor(f){this.zoom=f.zoom,this.overscaling=f.overscaling,this.layers=f.layers,this.layerIds=this.layers.map(_=>_.fqid),this.index=f.index,this.hasPattern=!1,this.projection=f.projection,this.layoutVertexArray=new zi,this.indexArray=new nu,this.segments=new sc,this.programConfigurations=new tt(f.layers,{zoom:f.zoom,lut:f.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 xl),this.worldview=f.worldview,this.hasAppearances=null}updateFootprints(f,_){}updateAppearances(f,_,S,L){return{hasLayoutChanges:!1,hasUboChanges:!1}}populate(f,_,S,L){const O=this.layers[0],z=[];let G=null;O.type==="circle"&&(G=O.layout.get("circle-sort-key"));for(const{feature:re,id:me,index:ye,sourceLayerIndex:we}of f){const Te=this.layers[0]._featureFilter.needGeometry,Ie=$i(re,Te);if(!this.layers[0]._featureFilter.filter(new Si(this.zoom,{worldview:this.worldview,activeFloors:_.activeFloors}),Ie,S))continue;const Ve=G?G.evaluate(Ie,{},S):void 0,Je={id:me,properties:re.properties,type:re.type,sourceLayerIndex:we,index:ye,geometry:Te?Ie.geometry:Oa(re,S,L),patterns:{},sortKey:Ve};z.push(Je)}G&&z.sort((re,me)=>re.sortKey-me.sortKey);let Y=null;L.projection.name==="globe"&&(this.globeExtVertexArray=new CF,Y=L.projection);for(const re of z){const{geometry:me,index:ye,sourceLayerIndex:we}=re,Te=f[ye].feature;this.addFeature(re,me,ye,_.availableImages,S,Y,_.brightness,_.elevationFeatures),_.featureIndex.insert(Te,me,ye,we,this.index)}this.hasElevation||(this.elevatedLayoutVertexArray=void 0)}update(f,_,S,L,O,z,G){this.programConfigurations.updatePaintArrays(f,_,O,S,L,z,G,this.worldview)}isEmpty(){return this.layoutVertexArray.length===0}uploadPending(){return!this.uploaded||this.programConfigurations.needsUpload}upload(f){this.uploaded||(this.layoutVertexBuffer=f.createVertexBuffer(this.layoutVertexArray,Tte.members),this.indexBuffer=f.createIndexBuffer(this.indexArray),this.globeExtVertexArray&&(this.globeExtVertexBuffer=f.createVertexBuffer(this.globeExtVertexArray,XTe.members)),this.elevatedLayoutVertexArray&&(this.elevatedLayoutVertexBuffer=f.createVertexBuffer(this.elevatedLayoutVertexArray,ZTe.members))),this.programConfigurations.upload(f),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(f,_,S,L,O,z,G,Y){let re;this.elevationMode!=="none"&&(re=cc.getElevationFeature(f,Y));for(const me of _)for(const ye of me){const we=ye.x,Te=ye.y;if(we<0||we>=lr||Te<0||Te>=lr)continue;if(z){const Je=z.projectTilePoint(we,Te,O),rt=z.upVector(O,we,Te);this.addGlobeExtVertex(Je,rt),this.addGlobeExtVertex(Je,rt),this.addGlobeExtVertex(Je,rt),this.addGlobeExtVertex(Je,rt)}const Ie=this.segments.prepareSegment(4,this.layoutVertexArray,this.indexArray,f.sortKey),Ve=Ie.vertexLength;if(this.addCircleVertex(we,Te,-1,-1),this.addCircleVertex(we,Te,1,-1),this.addCircleVertex(we,Te,1,1),this.addCircleVertex(we,Te,-1,1),this.elevationMode!=="none"){const Je=re?re.pointElevation(new Xt(we,Te)):0;this.hasElevation=this.hasElevation||Je!==0;for(let rt=0;rt<4;rt++)this.elevatedLayoutVertexArray.emplaceBack(Je)}this.indexArray.emplaceBack(Ve,Ve+1,Ve+2),this.indexArray.emplaceBack(Ve,Ve+2,Ve+3),Ie.vertexLength+=4,Ie.primitiveLength+=2}this.programConfigurations.populatePaintArrays(this.layoutVertexArray.length,f,S,{},L,O,G,void 0,this.worldview)}addCircleVertex(f,_,S,L){this.layoutVertexArray.emplaceBack(2*f+(S+1)/2,2*_+(L+1)/2)}addGlobeExtVertex(f,_){this.globeExtVertexArray.emplaceBack(f.x,f.y,f.z,_[0]*16384,_[1]*16384,_[2]*16384)}}function ju(k,f){for(let _=0;_1){if(Ck(k,f))return!0;for(let S=0;S1?_:_.sub(f)._mult(L)._add(f))}function $C(k,f){let _,S,L,O=!1;for(let z=0;zf.y!=L.y>f.y&&f.x<(L.x-S.x)*(f.y-S.y)/(L.y-S.y)+S.x&&(O=!O)}return O}function K0(k,f){let _=!1;for(let S=0,L=k.length-1;Sf.y!=z.y>f.y&&f.x<(z.x-O.x)*(f.y-O.y)/(z.y-O.y)+O.x&&(_=!_)}return _}function Ak(k,f,_,S,L){for(const z of k)if(f<=z.x&&_<=z.y&&S>=z.x&&L>=z.y)return!0;const O=[new Xt(f,_),new Xt(f,L),new Xt(S,L),new Xt(S,_)];if(k.length>2){for(const z of O)if(K0(k,z))return!0}for(let z=0;zL.x&&f.x>L.x||k.yL.y&&f.y>L.y)return!1;const O=ta(k,f,_[0]);return O!==ta(k,f,_[1])||O!==ta(k,f,_[2])||O!==ta(k,f,_[3])}function Tk(k,f,_,S,L,O){let z=f.y-k.y,G=k.x-f.x;if(O=O||0){const Y=z*z+G*G;if(Y===0)return!0;const re=Math.sqrt(Y);z/=re,G/=re}return!((_.x-k.x)*z+(_.y-k.y)*G-O<0||(S.x-k.x)*z+(S.y-k.y)*G-O<0||(L.x-k.x)*z+(L.y-k.y)*G-O<0)}function RF(k,f,_,S,L,O,z){return!(Tk(k,f,S,L,O,z)||Tk(f,_,S,L,O,z)||Tk(_,k,S,L,O,z)||Tk(S,L,k,f,_,z)||Tk(L,O,k,f,_,z)||Tk(O,S,k,f,_,z))}function UC(k,f,_){const S=f.paint.get(k).value;return S.kind==="constant"?S.value:_.programConfigurations.get(f.id).getMaxValue(k)}function Mte(k){return Math.sqrt(k[0]*k[0]+k[1]*k[1])}function bQe(k,f,_,S,L){if(!f[0]&&!f[1])return k;const O=Xt.convert(f)._mult(L);_==="viewport"&&O._rotate(-S);const z=[];for(let G=0;G>_&&f.y===this.y>>_}url(f,_){const S=function(O,z,G){const Y=2**G,re=2*Math.PI*6378137,me=re*(O/Y-.5),ye=re*(.5-(z+1)/Y);return`${me},${ye},${me+re/Y},${ye+re/Y}`}(this.x,this.y,this.z),L=function(O,z,G){let Y,re="";for(let me=O;me>0;me--)Y=1<this.canonical.z?new Wg(f,this.wrap,this.canonical.z,this.canonical.x,this.canonical.y):new Wg(f,this.wrap,f,this.canonical.x>>_,this.canonical.y>>_)}calculateScaledKey(f,_=!0){if(this.overscaledZ===f&&_)return this.key;if(f>this.canonical.z)return OF(this.wrap*+_,f,this.canonical.z,this.canonical.x,this.canonical.y);{const S=this.canonical.z-f;return OF(this.wrap*+_,f,f,this.canonical.x>>S,this.canonical.y>>S)}}isChildOf(f){if(f.wrap!==this.wrap)return!1;const _=this.canonical.z-f.canonical.z;return f.overscaledZ===0||f.overscaledZ>_&&f.canonical.y===this.canonical.y>>_}children(f){if(this.overscaledZ>=f)return[new Wg(this.overscaledZ+1,this.wrap,this.canonical.z,this.canonical.x,this.canonical.y)];const _=this.canonical.z+1,S=2*this.canonical.x,L=2*this.canonical.y;return[new Wg(_,this.wrap,_,S,L),new Wg(_,this.wrap,_,S+1,L),new Wg(_,this.wrap,_,S,L+1),new Wg(_,this.wrap,_,S+1,L+1)]}isLessThan(f){return this.wrapf.wrap)&&(this.overscaledZf.overscaledZ)&&(this.canonical.xf.canonical.x)&&this.canonical.y{let f=k.canonical.x-1,_=k.wrap;return f<0&&(f=(1<{let f=k.canonical.x+1,_=k.wrap;return f===1<new Wg(k.overscaledZ,k.wrap,k.canonical.z,k.canonical.x,(k.canonical.y===0?1<new Wg(k.overscaledZ,k.wrap,k.canonical.z,k.canonical.x,k.canonical.y===(1<1?null:function(S,L,O,z){const G=Math.sin(O);return S*(Math.sin((1-z)*O)/G)+L*(Math.sin(z*O)/G)}(k.a[f],k.b[f],k.angle,pt(_,0,1))+k.center[f]}function Mk(k){if(k.z<=1)return SKt[k.z+2*k.y+k.x];const f=r6e(Ite(k));return ul.fromPoints(f)}function d4(k,f,_){return he(k,k,1-_),ve(k,k,f,_)}function CQe(k,f){const _=u4(f.zoom);if(_===0)return Mk(k);const S=Ite(k),L=r6e(S),O=Dn(S.getWest())*f.worldSize,z=Dn(S.getEast())*f.worldSize,G=Gn(S.getNorth())*f.worldSize,Y=Gn(S.getSouth())*f.worldSize,re=[O,G,0],me=[z,G,0],ye=[O,Y,0],we=[z,Y,0],Te=b([],f.globeMatrix);return Xe(re,re,Te),Xe(me,me,Te),Xe(ye,ye,Te),Xe(we,we,Te),L[0]=d4(L[0],ye,_),L[1]=d4(L[1],we,_),L[2]=d4(L[2],me,_),L[3]=d4(L[3],re,_),ul.fromPoints(L)}function AQe(k,f,_){for(const S of k)Xe(S,S,f),he(S,S,_)}function EQe(k,f,_,S){const L=f/k.worldSize,O=k.globeMatrix;if(_.z<=1){const xs=Mk(_).getCorners();return AQe(xs,O,L),ul.fromPoints(xs)}const z=Ite(_,S),G=r6e(z,Vt+Pte(k._tileCoverLift));AQe(G,O,L);const Y=Number.MAX_VALUE,re=[-Y,-Y,-Y],me=[Y,Y,Y];if(z.contains(k.center)){for(const hs of G)ee(me,me,hs),le(re,re,hs);re[2]=0;const xs=k.point,us=[xs.x*L,xs.y*L,0];return ee(me,me,us),le(re,re,us),new ul(me,re)}if(k._tileCoverLift>0){for(const xs of G)ee(me,me,xs),le(re,re,xs);return new ul(me,re)}const ye=[O[12]*L,O[13]*L,O[14]*L],we=z.getCenter(),Te=pt(k.center.lat,-85.051129,kn),Ie=pt(we.lat,-85.051129,kn),Ve=Dn(k.center.lng),Je=Gn(Te);let rt=Ve-Dn(we.lng);const xt=Je-Gn(Ie);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,ve(ye,ye,[O[4]*L,O[5]*L,O[6]*L],-Math.sin($n(xt>=0?z.getSouth():z.getNorth()))*Vt));const St=G[ut],Pt=G[(ut+1)%4],Rt=new CKt(St,Pt,ye),ws=[n6e(Rt,0)||St[0],n6e(Rt,1)||St[1],n6e(Rt,2)||St[2]],ns=u4(k.zoom);if(ns>0){const xs=function({x:hs,y:pn,z:bn},An,Ln,En,Jn){const un=1/(1<.5?Zr=-1:Nr<-.5&&(Zr=1),Mn=((Mn+Zr)*An-(En*=An))*Ln+En,Rn=((Rn+Zr)*An-En)*Ln+En,er=(er*An-(Jn*=An))*Ln+Jn,ur=(ur*An-Jn)*Ln+Jn,[[Mn,ur,0],[Rn,ur,0],[Rn,er,0],[Mn,er,0]]}(_,f,k._pixelsPerMercatorPixel,Ve,Je);for(let hs=0;hsMath.PI/2*1.01}const IQe=$n(85),AKt=Math.cos(IQe),EKt=Math.sin(IQe),TKt=x(),DQe=k=>{const f=[];return k.paint.get("circle-pitch-alignment")==="map"&&f.push("PITCH_WITH_MAP"),k.paint.get("circle-pitch-scale")==="map"&&f.push("SCALE_WITH_MAP"),f};function RQe(k,f,_,S,L,O,z,G,Y){if(O&&k.queryGeometry.isAboveHorizon)return!1;O&&(Y*=k.pixelToTileUnitsFactor);const re=k.tileID.canonical,me=_.projection.upVectorScale(re,_.center.lat,_.worldSize).metersToTile;for(const ye of f)for(const we of ye){const Te=we.add(G),Ie=L&&_.elevation?_.elevation.exaggeration()*L.getElevationAt(Te.x,Te.y,!0):0,Ve=_.projection.projectTilePoint(Te.x,Te.y,re);if(Ie>0){const ut=_.projection.upVector(re,Te.x,Te.y);Ve.x+=ut[0]*me*Ie,Ve.y+=ut[1]*me*Ie,Ve.z+=ut[2]*me*Ie}const Je=O?Te:MKt(Ve.x,Ve.y,Ve.z,S),rt=O?k.tilespaceRays.map(ut=>PKt(ut,Ie)):k.queryGeometry.screenGeometry,xt=nt([],[Ve.x,Ve.y,Ve.z,1],S);if(!z&&O?Y*=xt[3]/_.cameraToCenterDistance:z&&!O&&(Y*=_.cameraToCenterDistance/xt[3]),O){const ut=mn((we.y/lr+re.y)/(1<k.width||L.height>k.height||_.x>k.width-L.width||_.y>k.height-L.height)throw new RangeError("out of range source coordinates for image copy");if(L.width>f.width||L.height>f.height||S.x>f.width-L.width||S.y>f.height-L.height)throw new RangeError("out of range destination coordinates for image copy");const Y=k.data,re=f.data,me=O===4&&G;for(let ye=0;ye{f[k.evaluationKey]=Y;const re=k.expression.evaluate(f),me=re?re.toNonPremultipliedRenderColor(null):null;me&&(L.data[z+G+0]=Math.floor(255*me.r),L.data[z+G+1]=Math.floor(255*me.g),L.data[z+G+2]=Math.floor(255*me.b),L.data[z+G+3]=Math.floor(255*me.a))};if(k.clips)for(let z=0,G=0;z80*_){G=k[0],Y=k[1];let me=G,ye=Y;for(let we=_;weme&&(me=Te),Ie>ye&&(ye=Ie)}re=Math.max(me-G,ye-Y),re=re!==0?32767/re:0}return XV(O,z,_,G,Y,re,0),z}function GQe(k,f,_,S,L){let O;if(L===function(z,G,Y,re){let me=0;for(let ye=G,we=Y-re;ye0)for(let z=f;z<_;z+=S)O=ZQe(z/S|0,k[z],k[z+1],O);else for(let z=_-S;z>=f;z-=S)O=ZQe(z/S|0,k[z],k[z+1],O);return O&&zF(O,O.next)&&(eH(O),O=O.next),O}function jM(k,f){if(!k)return k;f||(f=k);let _,S=k;do if(_=!1,S.steiner||!zF(S,S.next)&&yp(S.prev,S,S.next)!==0)S=S.next;else{if(eH(S),S=f=S.prev,S===S.next)break;_=!0}while(_||S!==f);return f}function XV(k,f,_,S,L,O,z){if(!k)return;!z&&O&&function(Y,re,me,ye){let we=Y;do we.z===0&&(we.z=c6e(we.x,we.y,re,me,ye)),we.prevZ=we.prev,we.nextZ=we.next,we=we.next;while(we!==Y);we.prevZ.nextZ=null,we.prevZ=null,function(Te){let Ie,Ve=1;do{let Je,rt=Te;Te=null;let xt=null;for(Ie=0;rt;){Ie++;let ut=rt,St=0;for(let Rt=0;Rt0||Pt>0&&ut;)St!==0&&(Pt===0||!ut||rt.z<=ut.z)?(Je=rt,rt=rt.nextZ,St--):(Je=ut,ut=ut.nextZ,Pt--),xt?xt.nextZ=Je:Te=Je,Je.prevZ=xt,xt=Je;rt=ut}xt.nextZ=null,Ve*=2}while(Ie>1)}(we)}(k,S,L,O);let G=k;for(;k.prev!==k.next;){const Y=k.prev,re=k.next;if(O?zKt(k,S,L,O):FKt(k))f.push(Y.i,k.i,re.i),eH(k),k=re.next,G=re.next;else if((k=re)===G){z?z===1?XV(k=BKt(jM(k),f),f,_,S,L,O,2):z===2&&$Kt(k,f,_,S,L,O):XV(jM(k),f,_,S,L,O,1);break}}}function FKt(k){const f=k.prev,_=k,S=k.next;if(yp(f,_,S)>=0)return!1;const L=f.x,O=_.x,z=S.x,G=f.y,Y=_.y,re=S.y,me=Math.min(L,O,z),ye=Math.min(G,Y,re),we=Math.max(L,O,z),Te=Math.max(G,Y,re);let Ie=S.next;for(;Ie!==f;){if(Ie.x>=me&&Ie.x<=we&&Ie.y>=ye&&Ie.y<=Te&&QV(L,G,O,Y,z,re,Ie.x,Ie.y)&&yp(Ie.prev,Ie,Ie.next)>=0)return!1;Ie=Ie.next}return!0}function zKt(k,f,_,S){const L=k.prev,O=k,z=k.next;if(yp(L,O,z)>=0)return!1;const G=L.x,Y=O.x,re=z.x,me=L.y,ye=O.y,we=z.y,Te=Math.min(G,Y,re),Ie=Math.min(me,ye,we),Ve=Math.max(G,Y,re),Je=Math.max(me,ye,we),rt=c6e(Te,Ie,f,_,S),xt=c6e(Ve,Je,f,_,S);let ut=k.prevZ,St=k.nextZ;for(;ut&&ut.z>=rt&&St&&St.z<=xt;){if(ut.x>=Te&&ut.x<=Ve&&ut.y>=Ie&&ut.y<=Je&&ut!==L&&ut!==z&&QV(G,me,Y,ye,re,we,ut.x,ut.y)&&yp(ut.prev,ut,ut.next)>=0||(ut=ut.prevZ,St.x>=Te&&St.x<=Ve&&St.y>=Ie&&St.y<=Je&&St!==L&&St!==z&&QV(G,me,Y,ye,re,we,St.x,St.y)&&yp(St.prev,St,St.next)>=0))return!1;St=St.nextZ}for(;ut&&ut.z>=rt;){if(ut.x>=Te&&ut.x<=Ve&&ut.y>=Ie&&ut.y<=Je&&ut!==L&&ut!==z&&QV(G,me,Y,ye,re,we,ut.x,ut.y)&&yp(ut.prev,ut,ut.next)>=0)return!1;ut=ut.prevZ}for(;St&&St.z<=xt;){if(St.x>=Te&&St.x<=Ve&&St.y>=Ie&&St.y<=Je&&St!==L&&St!==z&&QV(G,me,Y,ye,re,we,St.x,St.y)&&yp(St.prev,St,St.next)>=0)return!1;St=St.nextZ}return!0}function BKt(k,f){let _=k;do{const S=_.prev,L=_.next.next;!zF(S,L)&&KQe(S,_,_.next,L)&&JV(S,L)&&JV(L,S)&&(f.push(S.i,_.i,L.i),eH(_),eH(_.next),_=k=L),_=_.next}while(_!==k);return jM(_)}function $Kt(k,f,_,S,L,O){let z=k;do{let G=z.next.next;for(;G!==z.prev;){if(z.i!==G.i&&GKt(z,G)){let Y=YQe(z,G);return z=jM(z,z.next),Y=jM(Y,Y.next),XV(z,f,_,S,L,O,0),void XV(Y,f,_,S,L,O,0)}G=G.next}z=z.next}while(z!==k)}function UKt(k,f){let _=k.x-f.x;return _===0&&(_=k.y-f.y,_===0)&&(_=(k.next.y-k.y)/(k.next.x-k.x)-(f.next.y-f.y)/(f.next.x-f.x)),_}function qKt(k,f){const _=function(L,O){let z=O;const G=L.x,Y=L.y;let re,me=-1/0;if(zF(L,z))return z;do{if(zF(L,z.next))return z.next;if(Y<=z.y&&Y>=z.next.y&&z.next.y!==z.y){const Ve=z.x+(Y-z.y)*(z.next.x-z.x)/(z.next.y-z.y);if(Ve<=G&&Ve>me&&(me=Ve,re=z.x=z.x&&z.x>=we&&G!==z.x&&WQe(Yre.x||z.x===re.x&&VKt(re,z)))&&(re=z,Ie=Ve)}z=z.next}while(z!==ye);return re}(k,f);if(!_)return f;const S=YQe(_,k);return jM(S,S.next),jM(_,_.next)}function VKt(k,f){return yp(k.prev,k,f.prev)<0&&yp(f.next,k,k.next)<0}function c6e(k,f,_,S,L){return(k=1431655765&((k=858993459&((k=252645135&((k=16711935&((k=(k-_)*L|0)|k<<8))|k<<4))|k<<2))|k<<1))|(f=1431655765&((f=858993459&((f=252645135&((f=16711935&((f=(f-S)*L|0)|f<<8))|f<<4))|f<<2))|f<<1))<<1}function HKt(k){let f=k,_=k;do(f.x<_.x||f.x===_.x&&f.y<_.y)&&(_=f),f=f.next;while(f!==k);return _}function WQe(k,f,_,S,L,O,z,G){return(L-z)*(f-G)>=(k-z)*(O-G)&&(k-z)*(S-G)>=(_-z)*(f-G)&&(_-z)*(O-G)>=(L-z)*(S-G)}function QV(k,f,_,S,L,O,z,G){return!(k===z&&f===G)&&WQe(k,f,_,S,L,O,z,G)}function GKt(k,f){return k.next.i!==f.i&&k.prev.i!==f.i&&!function(_,S){let L=_;do{if(L.i!==_.i&&L.next.i!==_.i&&L.i!==S.i&&L.next.i!==S.i&&KQe(L,L.next,_,S))return!0;L=L.next}while(L!==_);return!1}(k,f)&&(JV(k,f)&&JV(f,k)&&function(_,S){let L=_,O=!1;const z=(_.x+S.x)/2,G=(_.y+S.y)/2;do L.y>G!=L.next.y>G&&L.next.y!==L.y&&z<(L.next.x-L.x)*(G-L.y)/(L.next.y-L.y)+L.x&&(O=!O),L=L.next;while(L!==_);return O}(k,f)&&(yp(k.prev,k,f.prev)||yp(k,f.prev,f))||zF(k,f)&&yp(k.prev,k,k.next)>0&&yp(f.prev,f,f.next)>0)}function yp(k,f,_){return(f.y-k.y)*(_.x-f.x)-(f.x-k.x)*(_.y-f.y)}function zF(k,f){return k.x===f.x&&k.y===f.y}function KQe(k,f,_,S){const L=Ote(yp(k,f,_)),O=Ote(yp(k,f,S)),z=Ote(yp(_,S,k)),G=Ote(yp(_,S,f));return L!==O&&z!==G||!(L!==0||!Rte(k,_,f))||!(O!==0||!Rte(k,S,f))||!(z!==0||!Rte(_,k,S))||!(G!==0||!Rte(_,f,S))}function Rte(k,f,_){return f.x<=Math.max(k.x,_.x)&&f.x>=Math.min(k.x,_.x)&&f.y<=Math.max(k.y,_.y)&&f.y>=Math.min(k.y,_.y)}function Ote(k){return k>0?1:k<0?-1:0}function JV(k,f){return yp(k.prev,k,k.next)<0?yp(k,f,k.next)>=0&&yp(k,k.prev,f)>=0:yp(k,f,k.prev)<0||yp(k,k.next,f)<0}function YQe(k,f){const _=d6e(k.i,k.x,k.y),S=d6e(f.i,f.x,f.y),L=k.next,O=f.prev;return k.next=f,f.prev=k,_.next=L,L.prev=_,S.next=_,_.prev=S,O.next=S,S.prev=O,S}function ZQe(k,f,_,S){const L=d6e(k,f,_);return S?(L.next=S.next,L.prev=S,S.next.prev=L,S.next=L):(L.prev=L,L.next=L),L}function eH(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 d6e(k,f,_){return{i:k,x:f,y:_,prev:null,next:null,z:0,prevZ:null,nextZ:null,steiner:!1}}function tH(k,f){const _=k.length;if(_<=1)return[k];const S=[];let L,O;for(let z=0;z<_;z++){const G=da(k[z]);G!==0&&(k[z].area=Math.abs(G),O===void 0&&(O=G<0),O===G<0?(L&&S.push(L),L=[k[z]]):L.push(k[z]))}if(L&&S.push(L),f>1)for(let z=0;z=lr&&_>=lr}static evaluate(f){if(f.length===0)return new h4;let _=[];for(const Y of f)_.push(...Y.portals);if(_.length===0)return new h4;for(const Y of _){const re=Y.va,me=Y.vb;(h4.isOnBorder(re.x,me.x)||h4.isOnBorder(re.y,me.y))&&(Y.type="border")}const S=_.filter(Y=>Y.type!=="unevaluated"),L=_.filter(Y=>Y.type==="unevaluated");if(L.length===0)return new h4;L.sort((Y,re)=>Y.hash===re.hash?Y.isTunnel===re.isTunnel?0:Y.isTunnel?-1:1:Y.hashY.hashO!=="fill-tunnel-structure-color"),this.tunnelProgramConfigurations=new tt(_,{zoom:S,lut:L},O=>O!=="fill-bridge-guard-rail-color")}addVertices(f,_){const S=this.unevalVertices.length;for(let L=0;L=O.min.x&&ye.x<=O.max.x&&ye.y>=O.min.y&&ye.y<=O.max.y||we.x>=O.min.x&&we.x<=O.max.x&&we.y>=O.min.y&&we.y<=O.max.y||Ek(ye,we,G))||this.isOnBorder(ye.x,we.x)||this.isOnBorder(ye.y,we.y))continue;const Te=Rv.computeEdgeHash(this.unevalVertices[re],this.unevalVertices[me]);let Ie,Ve=this.vertexHashLookup.get(Rv.computePosHash(ye));Ve!=null?Ie=Ve.next:(Ve=this.vertexHashLookup.get(Rv.computePosHash(we)),Ie=Ve!=null?Ve.prev:Te),this.unevalEdges.push({polygonIdx:f,a:re,b:me,hash:Te,portalHash:Ie,isTunnel:L,type:"unevaluated",featureInfo:z})}}addPortalCandidates(f,_,S,L,O){if(_.length!==0){this.vertexHashLookup.clear();for(const z of _){if(z.length===0)continue;const G=z[0];let Y=Rv.computeEdgeHash(G[G.length-2],G[G.length-1]);for(let re=0;re({vertexOffset:0,primitiveOffset:this.indexArray.length}),S=we=>{we.primitiveLength=this.indexArray.length-we.primitiveOffset},L=new KKt(this.vertexPositions,this.vertexNormals,this.indexArray);this.prepareEdges(f.portals,this.unevalEdges);const O=_(),z=_(),G=_(),Y=(we,Te)=>{we.sort((Ve,Je)=>Ve.type===Te&&Je.type!==Te?-1:Ve.type!==Te&&Je.type===Te?1:0);const Ie=we.findIndex(Ve=>Ve.type!==Te);return Ie>=0?Ie:we.length};let re=0;this.unevalEdges.length>0&&(re=Y(this.unevalEdges,"none"),this.constructBridgeStructures(L,this.unevalVertices,this.unevalHeights,this.unevalEdges,{min:0,max:re},this.tileToMeters)),S(G);const me=_(),ye=_();if(this.unevalEdges.length>0){const we=this.unevalEdges.splice(re),Te=Y(we,"tunnel")+re;this.unevalEdges.push(...we),this.constructTunnelStructures(L,this.unevalVertices,this.unevalHeights,this.unevalEdges,{min:0,max:re},{min:re,max:Te})}S(me),L.addTriangles(this.unevalTriangles,this.unevalVertices,this.unevalHeights),S(ye),L.addTriangles(this.unevalTunnelTriangles,this.unevalVertices,this.unevalHeights),S(z),L.addTriangles(this.unevalTunnelTriangles,this.unevalVertices,[-.1]),S(O),this.maskSegments=sc.simpleSegment(0,ye.primitiveOffset,0,ye.primitiveLength),this.depthSegments=sc.simpleSegment(0,z.primitiveOffset,0,z.primitiveLength),this.renderableBridgeSegments=sc.simpleSegment(0,G.primitiveOffset,0,G.primitiveLength),this.renderableTunnelSegments=sc.simpleSegment(0,me.primitiveOffset,0,me.primitiveLength),this.shadowCasterSegments=sc.simpleSegment(0,O.primitiveOffset,0,O.primitiveLength)}update(f,_,S,L,O,z,G,Y){this.bridgeProgramConfigurations.updatePaintArrays(f,_,O,S,L,z,G,Y),this.tunnelProgramConfigurations.updatePaintArrays(f,_,O,S,L,z,G,Y)}upload(f){this.vertexBuffer||this.vertexPositions.length===0||this.vertexNormals.length===0||this.indexArray.length===0||(this.vertexBuffer=f.createVertexBuffer(this.vertexPositions,RKt.members),this.vertexBufferNormal=f.createVertexBuffer(this.vertexNormals,OKt.members),this.indexBuffer=f.createIndexBuffer(this.indexArray),this.bridgeProgramConfigurations.upload(f),this.tunnelProgramConfigurations.upload(f))}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(f,_,S,L,O){const z=(G,Y)=>{for(let re=0;reJ(Ln,_[En].x,_[En].y,S[En]*Y),ye=W(),we=W(),Te=W(),Ie=W(),Ve=W(),Je=(Ln,En)=>{const Jn=G.get(Rv.computePosHash(_[En])),un=Jn.from,Mn=Jn.to;if(!un||!Mn)return;me(ye,un),me(we,En),me(Te,Mn),Ae(Ie),Be(ye,we)||(qe(Ve,we,ye),Me(Ie,Ve)),Be(Te,we)||(qe(Ve,Te,we),ce(Ie,Ie,Me(Ve,Ve)));const Rn=Ze(Ie);return Rn>0?he(Ln,Ie,1/Rn):void 0};let rt=Number.POSITIVE_INFINITY;this.sortSubarray(L,O.min,O.max,(Ln,En)=>Ln.featureInfo.featureIndex-En.featureInfo.featureIndex);const xt=W(),ut=W(),St=W(),Pt=W(),Rt=W(),ws=W(),ns=W(),xs=W(),us=W(),hs=[W(),W(),W(),W()],pn=[W(),W(),W(),W()],bn=[{coord:new Xt(0,0),height:0},{coord:new Xt(0,0),height:0}],An=(Ln,En)=>Ln>En;for(let Ln=O.min;Lnrt.featureInfo.featureIndex-xt.featureInfo.featureIndex;this.sortSubarray(L,O.min,O.max,Y),this.sortSubarray(L,z.min,z.max,Y);const re=rt=>Me(rt,rt),me=[{coord:new Xt(0,0),height:0},{coord:new Xt(0,0),height:0}],ye=(rt,xt)=>rtG.hash===Y.hash?Y.polygonIdx-G.polygonIdx:Y.hash>G.hash?1:-1);let S=0,L=0,O=0,z=_[S].polygonIdx;do L++,(L===_.length||_[S].hash!==_[L].hash)&&((L-S===1||_[L-1].polygonIdx!==z)&&(Ore.portalHashme.hash?G++:me.hash>re.portalHash?Y++:(re.type=me.type,G++)}}}isOnBorder(f,_){return f<=0&&_<=0||f>=lr&&_>=lr}addFeatureSection(f,_,S,L){return f!==_&&(_=f,S.push({featureIndex:f,vertexStart:L.getVertexCount()}),L.clearVertexLookup()),_}sortSubarray(f,_,S,L){const O=f.slice(_,S);O.sort(L),f.splice(_,O.length,...O)}static computeEdgeHash(f,_){return(f.y===_.y&&f.x>_.x||f.y>_.y)&&([f,_]=[_,f]),BigInt(Rv.computePosHash(f))<<32n|BigInt(Rv.computePosHash(_))}static computePosHash(f){return((65535&f.x)<<16|65535&f.y)>>>0}}function YKt(k,f){return k>f?1:k0))return _;_=_.left}}return null}contains(f){for(var _=this._root,S=this._compare;_;){var L=S(f,_.key);if(L===0)return!0;_=L<0?_.left:_.right}return!1}remove(f){var _=this.find(f);if(!_)return!1;if(this.splay(_),_.left)if(_.right){var S=this.minNode(_.right);S.parent!==_&&(this.replace(S,S.right),S.right=_.right,S.right.parent=S),this.replace(_,S),S.left=_.left,S.left.parent=S}else this.replace(_,_.left);else this.replace(_,_.right);return this._size--,!0}removeNode(f){if(!f)return!1;if(this.splay(f),f.left)if(f.right){var _=this.minNode(f.right);_.parent!==f&&(this.replace(_,_.right),_.right=f.right,_.right.parent=_),this.replace(f,_),_.left=f.left,_.left.parent=_}else this.replace(f,f.left);else this.replace(f,f.right);return this._size--,!0}erase(f){var _=this.find(f);if(_){this.splay(_);var S=_.left,L=_.right,O=null;S&&(S.parent=null,O=this.maxNode(S),this.splay(O),this._root=O),L&&(S?O.right=L:this._root=L,L.parent=O),this._size--}}pop(){var f=this._root,_=null;if(f){for(;f.left;)f=f.left;_={key:f.key,data:f.data},this.remove(f.key)}return _}next(f){var _=f;if(_)if(_.right)for(_=_.right;_&&_.left;)_=_.left;else for(_=f.parent;_&&_.right===f;)f=_,_=_.parent;return _}prev(f){var _=f;if(_)if(_.left)for(_=_.left;_&&_.right;)_=_.right;else for(_=f.parent;_&&_.left===f;)f=_,_=_.parent;return _}forEach(f){for(var _=this._root,S=[],L=!1,O=0;!L;)_?(S.push(_),_=_.left):S.length>0?(f(_=S.pop(),O++),_=_.right):L=!0;return this}range(f,_,S,L){const O=[],z=this._compare;let G,Y=this._root;for(;O.length!==0||Y;)if(Y)O.push(Y),Y=Y.left;else{if(Y=O.pop(),G=z(Y.key,_),G>0)break;if(z(Y.key,f)>=0&&S.call(L,Y))return this;Y=Y.right}return this}keys(){for(var f=this._root,_=[],S=[],L=!1;!L;)f?(_.push(f),f=f.left):_.length>0?(f=_.pop(),S.push(f.key),f=f.right):L=!0;return S}values(){for(var f=this._root,_=[],S=[],L=!1;!L;)f?(_.push(f),f=f.left):_.length>0?(f=_.pop(),S.push(f.data),f=f.right):L=!0;return S}at(f){for(var _=this._root,S=[],L=!1,O=0;!L;)if(_)S.push(_),_=_.left;else if(S.length>0){if(_=S.pop(),O===f)return _;O++,_=_.right}else L=!0;return null}load(f=[],_=[],S=!1){if(this._size!==0)throw new Error("bulk-load: tree is not empty");const L=f.length;return S&&f6e(f,_,0,L-1,this._compare),this._root=p6e(null,f,_,0,L),this._size=L,this}min(){var f=this.minNode(this._root);return f?f.key:null}max(){var f=this.maxNode(this._root);return f?f.key:null}isEmpty(){return this._root===null}get size(){return this._size}static createTree(f,_,S,L,O){return new m6e(S,O).load(f,_,L)}}function p6e(k,f,_,S,L){const O=L-S;if(O>0){const z=S+Math.floor(O/2),G={key:f[z],data:_[z],parent:k};return G.left=p6e(G,f,_,S,z),G.right=p6e(G,f,_,z+1,L),G}return null}function f6e(k,f,_,S,L){if(_>=S)return;const O=k[_+S>>1];let z=_-1,G=S+1;for(;;){do z++;while(L(k[z],O)<0);do G--;while(L(k[G],O)>0);if(z>=G)break;let Y=k[z];k[z]=k[G],k[G]=Y,Y=f[z],f[z]=f[G],f[G]=Y}f6e(k,f,_,G,L),f6e(k,f,G+1,S,L)}const QQe=11102230246251565e-32,zy=134217729,ZKt=(3+8*QQe)*QQe;function x6e(k,f,_,S,L){let O,z,G,Y,re=f[0],me=S[0],ye=0,we=0;me>re==me>-re?(O=re,re=f[++ye]):(O=me,me=S[++we]);let Te=0;if(yere==me>-re?(z=re+O,G=O-(z-re),re=f[++ye]):(z=me+O,G=O-(z-me),me=S[++we]),O=z,G!==0&&(L[Te++]=G);yere==me>-re?(z=O+re,Y=z-O,G=O-(z-Y)+(re-Y),re=f[++ye]):(z=O+me,Y=z-O,G=O-(z-Y)+(me-Y),me=S[++we]),O=z,G!==0&&(L[Te++]=G);for(;ye0:(S[0]-f[0])*(_[1]-f[1])-(_[0]-f[0])*(S[1]-f[1])>0}isAbove(f){return!this.isBelow(f)}isVertical(){return this.point[0]===this.otherEvent.point[0]}get inResult(){return this.resultTransition!==0}clone(){const f=new $F(this.point,this.left,this.otherEvent,this.isSubject,this.type);return f.contourId=this.contourId,f.resultTransition=this.resultTransition,f.prevInResult=this.prevInResult,f.isExteriorRing=this.isExteriorRing,f.inOut=this.inOut,f.otherInOut=this.otherInOut,f}}function Lk(k,f){return k[0]===f[0]&&k[1]===f[1]}function g6e(k,f,_){const S=function(L,O,z,G,Y,re){const me=(O-re)*(z-Y),ye=(L-Y)*(G-re),we=me-ye;if(me===0||ye===0||me>0!=ye>0)return we;const Te=Math.abs(me+ye);return Math.abs(we)>=33306690738754716e-32*Te?we:-function(Ie,Ve,Je,rt,xt,ut,St){let Pt,Rt,ws,ns,xs,us,hs,pn,bn,An,Ln,En,Jn,un,Mn,Rn,er,ur;const Zr=Ie-xt,Nr=Je-xt,wr=Ve-ut,hr=rt-ut;un=Zr*hr,us=zy*Zr,hs=us-(us-Zr),pn=Zr-hs,us=zy*hr,bn=us-(us-hr),An=hr-bn,Mn=pn*An-(un-hs*bn-pn*bn-hs*An),Rn=wr*Nr,us=zy*wr,hs=us-(us-wr),pn=wr-hs,us=zy*Nr,bn=us-(us-Nr),An=Nr-bn,er=pn*An-(Rn-hs*bn-pn*bn-hs*An),Ln=Mn-er,xs=Mn-Ln,BF[0]=Mn-(Ln+xs)+(xs-er),En=un+Ln,xs=En-un,Jn=un-(En-xs)+(Ln-xs),Ln=Jn-Rn,xs=Jn-Ln,BF[1]=Jn-(Ln+xs)+(xs-Rn),ur=En+Ln,xs=ur-En,BF[2]=En-(ur-xs)+(Ln-xs),BF[3]=ur;let Gr=function(To,wi){let Do=wi[0];for(let Ui=1;Ui<4;Ui++)Do+=wi[Ui];return Do}(0,BF),aa=22204460492503146e-32*St;if(Gr>=aa||-Gr>=aa||(xs=Ie-Zr,Pt=Ie-(Zr+xs)+(xs-xt),xs=Je-Nr,ws=Je-(Nr+xs)+(xs-xt),xs=Ve-wr,Rt=Ve-(wr+xs)+(xs-ut),xs=rt-hr,ns=rt-(hr+xs)+(xs-ut),Pt===0&&Rt===0&&ws===0&&ns===0)||(aa=11093356479670487e-47*St+ZKt*Math.abs(Gr),Gr+=Zr*ns+hr*Pt-(wr*ws+Nr*Rt),Gr>=aa||-Gr>=aa))return Gr;un=Pt*hr,us=zy*Pt,hs=us-(us-Pt),pn=Pt-hs,us=zy*hr,bn=us-(us-hr),An=hr-bn,Mn=pn*An-(un-hs*bn-pn*bn-hs*An),Rn=Rt*Nr,us=zy*Rt,hs=us-(us-Rt),pn=Rt-hs,us=zy*Nr,bn=us-(us-Nr),An=Nr-bn,er=pn*An-(Rn-hs*bn-pn*bn-hs*An),Ln=Mn-er,xs=Mn-Ln,Ov[0]=Mn-(Ln+xs)+(xs-er),En=un+Ln,xs=En-un,Jn=un-(En-xs)+(Ln-xs),Ln=Jn-Rn,xs=Jn-Ln,Ov[1]=Jn-(Ln+xs)+(xs-Rn),ur=En+Ln,xs=ur-En,Ov[2]=En-(ur-xs)+(Ln-xs),Ov[3]=ur;const Da=x6e(4,BF,4,Ov,JQe);un=Zr*ns,us=zy*Zr,hs=us-(us-Zr),pn=Zr-hs,us=zy*ns,bn=us-(us-ns),An=ns-bn,Mn=pn*An-(un-hs*bn-pn*bn-hs*An),Rn=wr*ws,us=zy*wr,hs=us-(us-wr),pn=wr-hs,us=zy*ws,bn=us-(us-ws),An=ws-bn,er=pn*An-(Rn-hs*bn-pn*bn-hs*An),Ln=Mn-er,xs=Mn-Ln,Ov[0]=Mn-(Ln+xs)+(xs-er),En=un+Ln,xs=En-un,Jn=un-(En-xs)+(Ln-xs),Ln=Jn-Rn,xs=Jn-Ln,Ov[1]=Jn-(Ln+xs)+(xs-Rn),ur=En+Ln,xs=ur-En,Ov[2]=En-(ur-xs)+(Ln-xs),Ov[3]=ur;const _a=x6e(Da,JQe,4,Ov,eJe);un=Pt*ns,us=zy*Pt,hs=us-(us-Pt),pn=Pt-hs,us=zy*ns,bn=us-(us-ns),An=ns-bn,Mn=pn*An-(un-hs*bn-pn*bn-hs*An),Rn=Rt*ws,us=zy*Rt,hs=us-(us-Rt),pn=Rt-hs,us=zy*ws,bn=us-(us-ws),An=ws-bn,er=pn*An-(Rn-hs*bn-pn*bn-hs*An),Ln=Mn-er,xs=Mn-Ln,Ov[0]=Mn-(Ln+xs)+(xs-er),En=un+Ln,xs=En-un,Jn=un-(En-xs)+(Ln-xs),Ln=Jn-Rn,xs=Jn-Ln,Ov[1]=Jn-(Ln+xs)+(xs-Rn),ur=En+Ln,xs=ur-En,Ov[2]=En-(ur-xs)+(Ln-xs),Ov[3]=ur;const _i=x6e(_a,eJe,4,Ov,tJe);return tJe[_i-1]}(L,O,z,G,Y,re,Te)}(k[0],k[1],f[0],f[1],_[0],_[1]);return S>0?-1:S<0?1:0}function VC(k,f){const _=k.point,S=f.point;return _[0]>S[0]?1:_[0]S[1]?1:-1:function(L,O,z){return L.left!==O.left?L.left?1:-1:g6e(z,L.otherEvent.point,O.otherEvent.point)!==0?L.isBelow(O.otherEvent.point)?-1:1:!L.isSubject&&O.isSubject?1:-1}(k,f,_)}function HC(k,f,_){const S=new $F(f,!1,k,k.isSubject),L=new $F(f,!0,k.otherEvent,k.isSubject);return Lk(k.point,k.otherEvent.point)&&console.warn("what is that, a collapsed segment?",k),S.contourId=L.contourId=k.contourId,VC(L,k.otherEvent)>0&&(k.otherEvent.left=!0,L.left=!1),k.otherEvent.otherEvent=L,k.otherEvent=S,_.push(L),_.push(S),_}function Fte(k,f){return k[0]*f[1]-k[1]*f[0]}function y6e(k,f){return k[0]*f[0]+k[1]*f[1]}function v6e(k,f,_){const S=function(Y,re,me,ye){const we=[re[0]-Y[0],re[1]-Y[1]],Te=[ye[0]-me[0],ye[1]-me[1]];function Ie(ws,ns,xs){return[ws[0]+ns*xs[0],ws[1]+ns*xs[1]]}const Ve=[me[0]-Y[0],me[1]-Y[1]];let Je=Fte(we,Te),rt=Je*Je;const xt=y6e(we,we);if(rt>0){const ws=Fte(Ve,Te)/Je;if(ws<0||ws>1)return null;const ns=Fte(Ve,we)/Je;return ns<0||ns>1?null:ws===0||ws===1?[Ie(Y,ws,we)]:ns===0||ns===1?[Ie(me,ns,Te)]:[Ie(Y,ws,we)]}if(Je=Fte(Ve,we),rt=Je*Je,rt>0)return null;const ut=y6e(we,Ve)/xt,St=ut+y6e(we,Te)/xt,Pt=Math.min(ut,St),Rt=Math.max(ut,St);return Pt<=1&&Rt>=0?Pt===1?[Ie(Y,Pt>0?Pt:0,we)]:Rt===0?[Ie(Y,Rt<1?Rt:1,we)]:[Ie(Y,Pt>0?Pt:0,we),Ie(Y,Rt<1?Rt:1,we)]:null}(k.point,k.otherEvent.point,f.point,f.otherEvent.point),L=S?S.length:0;if(L===0||L===1&&(Lk(k.point,f.point)||Lk(k.otherEvent.point,f.otherEvent.point))||L===2&&k.isSubject===f.isSubject)return 0;if(L===1)return!Lk(k.point,S[0])&&!Lk(k.otherEvent.point,S[0])&&HC(k,S[0],_),!Lk(f.point,S[0])&&!Lk(f.otherEvent.point,S[0])&&HC(f,S[0],_),1;const O=[];let z=!1,G=!1;return Lk(k.point,f.point)?z=!0:VC(k,f)===1?O.push(f,k):O.push(k,f),Lk(k.otherEvent.point,f.otherEvent.point)?G=!0:VC(k.otherEvent,f.otherEvent)===1?O.push(f.otherEvent,k.otherEvent):O.push(k.otherEvent,f.otherEvent),z&&G||z?(f.type=1,k.type=f.inOut===k.inOut?2:3,z&&!G&&HC(O[1].otherEvent,O[0].point,_),2):G?(HC(O[0],O[1].point,_),3):O[0]!==O[3].otherEvent?(HC(O[0],O[1].point,_),HC(O[1],O[2].point,_),3):(HC(O[0],O[1].point,_),HC(O[3].otherEvent,O[2].point,_),3)}function XKt(k,f){if(k===f)return 0;if(g6e(k.point,k.otherEvent.point,f.point)!==0||g6e(k.point,k.otherEvent.point,f.otherEvent.point)!==0)return Lk(k.point,f.point)?k.isBelow(f.otherEvent.point)?-1:1:k.point[0]===f.point[0]?k.point[1](f.contourId??0)?1:-1}return VC(k,f)===1?1:-1}class QKt{constructor(){this.points=[],this.holeIds=[],this.holeOf=null,this.depth=null}isExterior(){return this.holeOf==null}}function JKt(k,f,_,S){let L,O=k+1,z=f[k].point;const G=f.length;for(OS;)O--;return O}function eYt(k,f,_){const S=new QKt;if(k.prevInResult!=null){const L=k.prevInResult,O=L.outputContourId;if(L.resultTransition>0){const z=f[O];if(z.holeOf!=null){const G=z.holeOf;f[G].holeIds.push(_),S.holeOf=G,S.depth=f[O].depth}else f[O].holeIds.push(_),S.holeOf=O,S.depth=f[O].depth+1}else S.holeOf=null,S.depth=f[O].depth}else S.holeOf=null,S.depth=0;return S}const nJe=Math.max,rJe=Math.min;let zte=0;function aJe(k,f,_,S,L,O){let z,G,Y,re,me,ye;for(z=0,G=k.length-1;z0?ye.left=!0:me.left=!0;const we=Y[0],Te=Y[1];L[0]=rJe(L[0],we),L[1]=rJe(L[1],Te),L[2]=nJe(L[2],we),L[3]=nJe(L[3],Te),S.push(me),S.push(ye)}}const Bte=[];function iJe(k,f,_){let S=k,L=f;typeof k[0][0][0]=="number"&&(S=[k]),typeof f[0][0][0]=="number"&&(L=[f]);let O=function(we,Te,Ie){let Ve=null;return we.length*Te.length===0&&(Ie===0?Ve=Bte:Ie===2?Ve=we:(Ie===1||Ie===3)&&(Ve=we.length===0?Te:we)),Ve}(S,L,_);if(O)return O===Bte?null:O;const z=[1/0,1/0,-1/0,-1/0],G=[1/0,1/0,-1/0,-1/0],Y=function(we,Te,Ie,Ve,Je){const rt=new yh(void 0,VC);let xt,ut,St,Pt,Rt,ws;for(St=0,Pt=we.length;StVe[2]||Ve[0]>Ie[2]||Ie[1]>Ve[3]||Ve[1]>Ie[3])&&(Je===0?rt=Bte:Je===2?rt=we:(Je===1||Je===3)&&(rt=we.concat(Te))),rt}(S,L,z,G,_),O)return O===Bte?null:O;const re=function(we,Te,Ie,Ve,Je,rt){const xt=new m6e(XKt),ut=[],St=Math.min(Ve[2],Je[2]);let Pt,Rt,ws;for(;we.length!==0;){let ns=we.pop();if(ut.push(ns),rt===0&&ns.point[0]>St||rt===2&&ns.point[0]>Ve[2])break;if(ns.left){Rt=Pt=xt.insert(ns),ws=xt.minNode(),Pt=Pt!==ws?xt.prev(Pt):null,Rt=xt.next(Rt);const xs=Pt?Pt.key:null;let us;if(nH(ns,xs,rt),Rt&&v6e(ns,Rt.key,we)===2&&(nH(ns,xs,rt),nH(Rt.key,ns,rt)),Pt&&v6e(Pt.key,ns,we)===2){let hs=Pt;hs=hs!==ws?xt.prev(hs):null,us=hs?hs.key:null,nH(xs,us,rt),nH(ns,xs,rt)}}else ns=ns.otherEvent,Rt=Pt=xt.find(ns),Pt&&Rt&&(Pt=Pt!==ws?xt.prev(Pt):null,Rt=xt.next(Rt),xt.remove(ns),Rt&&Pt&&v6e(Pt.key,Rt.key,we))}return ut}(Y,0,0,z,G,_),me=function(we){let Te,Ie;const Ve=function(xt){let ut,St,Pt,Rt,ws;const ns=[];for(St=0,Pt=xt.length;St{Je[ws]=!0,ws=Ve.length)&&Ve[Pt];);rt.push(ut)}return rt}(re),ye=[];for(let we=0;we{z.push(new Xt(ye,Y+(ye-G)/(re-G)*(me-Y)))}:(z,G,Y,re,me,ye)=>{z.push(new Xt(G+(ye-Y)/(me-Y)*(re-G),ye))};for(const z of k){const G=[];for(const Y of z){if(Y.length<=2)continue;const re=[];for(let we=0;wef&&O(re,Te,Ie,Ve,Je,f):rt>_?xt<_&&O(re,Te,Ie,Ve,Je,_):re.push(Y[we]),xt=f&&O(re,Te,Ie,Ve,Je,f),xt>_&&rt<=_&&O(re,Te,Ie,Ve,Je,_)}let me=Y[Y.length-1];const ye=S===0?me.x:me.y;ye>=f&&ye<=_&&re.push(me),re.length&&(me=re[re.length-1],re[0].x===me.x&&re[0].y===me.y||re.push(re[0]),G.push(re))}G.length&&L.push(G)}return L}function tYt(k,f){const _=iJe(b6e(k),b6e([f]),0);return _==null?[]:oJe(_)}function sYt(k,f,_=0){let L=b6e(k,65536);const O=[];for(;f.valid();f.next()){const[z,G]=f.get();let Y=z.x*65536,re=z.y*65536,me=G.x*65536,ye=G.y*65536;const we=me-Y,Te=ye-re,Ie=Math.hypot(we,Te);if(Ie===0)continue;Y-=we*_,re-=Te*_,me+=we*_,ye+=Te*_;const Ve=Math.trunc(Te/Ie*3),Je=-Math.trunc(we/Ie*3);O.push([[[Y,re],[me,ye],[me+Ve,ye+Je],[Y+Ve,re+Je],[Y,re]]])}return O.length>0&&(L=iJe(L,O,2)),oJe(L,1/65536,128)}function b6e(k,f=1){return[k.map(_=>_.map(S=>[S.x*f,S.y*f]))]}function oJe(k,f=1,_){return k.map(S=>S.map((L,O)=>{const z=L.map(G=>{let Y=G[0],re=G[1];return _&&(Y=Math.round(Y/_)*_,re=Math.round(re/_)*_),new Xt(Y*f,re*f)._round()});return O>0&&z.reverse(),z}))}class _6e{constructor(f,_){this.layoutVertexArray=new zi,this.indexArray=new nu,this.lineIndexArray=new K1,this.triangleSegments=new sc,this.lineSegments=new sc,this.programConfigurations=new tt(f.layers,{zoom:f.zoom,lut:f.lut}),this.uploaded=!1,_&&(this.elevatedLayoutVertexArray=new xl)}update(f,_,S,L,O,z,G,Y){this.programConfigurations.updatePaintArrays(f,_,O,S,L,z,G,Y)}isEmpty(){return this.layoutVertexArray.length===0}needsUpload(){return this.programConfigurations.needsUpload}upload(f){this.uploaded||(this.layoutVertexBuffer=f.createVertexBuffer(this.layoutVertexArray,IKt.members),this.indexBuffer=f.createIndexBuffer(this.indexArray),this.lineIndexBuffer=f.createIndexBuffer(this.lineIndexArray),this.elevatedLayoutVertexArray&&this.elevatedLayoutVertexArray.length>0&&(this.elevatedLayoutVertexBuffer=f.createVertexBuffer(this.elevatedLayoutVertexArray,DKt.members))),this.programConfigurations.upload(f),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(f,_,S,L,O,z,G){this.programConfigurations.populatePaintArrays(this.layoutVertexArray.length,f,_,S,L,O,z,void 0,G)}}class Ute{constructor(f){this.zoom=f.zoom,this.pixelRatio=f.pixelRatio,this.overscaling=f.overscaling,this.layers=f.layers,this.layerIds=this.layers.map(_=>_.fqid),this.index=f.index,this.hasPattern=!1,this.patternFeatures=[],this.lut=f.lut,this.bufferData=new _6e(f,!1),this.elevationBufferData=new _6e(f,!0),this.stateDependentLayerIds=this.layers.filter(_=>_.isStateDependent()).map(_=>_.id),this.projection=f.projection,this.elevationMode=this.layers[0].layout.get("fill-elevation-reference"),this.sourceLayerIndex=f.sourceLayerIndex,this.worldview=f.worldview,this.hasAppearances=null}updateFootprints(f,_){}updateAppearances(f,_,S,L){return{hasLayoutChanges:!1,hasUboChanges:!1}}populate(f,_,S,L){this.hasPattern=u6e("fill",this.layers,this.pixelRatio,_);const O=this.layers[0].layout.get("fill-sort-key"),z=[];for(const{feature:G,id:Y,index:re,sourceLayerIndex:me}of f){const ye=this.layers[0]._featureFilter.needGeometry,we=$i(G,ye);if(!this.layers[0]._featureFilter.filter(new Si(this.zoom,{worldview:this.worldview,activeFloors:_.activeFloors}),we,S))continue;const Te=O?O.evaluate(we,{},S,_.availableImages):void 0,Ie={id:Y,properties:G.properties,type:G.type,sourceLayerIndex:me,index:re,geometry:ye?we.geometry:Oa(G,S,L),patterns:{},sortKey:Te};z.push(Ie)}O&&z.sort((G,Y)=>G.sortKey-Y.sortKey);for(const G of z){const{geometry:Y,index:re,sourceLayerIndex:me}=G;if(this.hasPattern){const ye=h6e("fill",this.layers,G,this.zoom,this.pixelRatio,_);this.patternFeatures.push(ye)}else this.addFeature(G,Y,re,S,{},_.availableImages,_.brightness,_.elevationFeatures);_.featureIndex.insert(f[re].feature,Y,re,me,this.index)}}update(f,_,S,L,O,z,G){this.bufferData.update(f,_,S,L,O,z,G,this.worldview),this.elevationBufferData.update(f,_,S,L,O,z,G,this.worldview),this.elevatedStructures&&this.elevatedStructures.update(f,_,S,L,O,z,G,this.worldview)}addFeatures(f,_,S,L,O,z){for(const G of this.patternFeatures)this.addFeature(G,G.geometry,G.index,_,S,L,z,f.elevationFeatures)}isEmpty(){return this.bufferData.isEmpty()&&this.elevationBufferData.isEmpty()}uploadPending(){return!this.uploaded||this.bufferData.needsUpload()||this.elevationBufferData.needsUpload()}upload(f){this.bufferData.upload(f),this.elevationBufferData.upload(f),this.elevatedStructures&&this.elevatedStructures.upload(f)}destroy(){this.bufferData.destroy(),this.elevationBufferData.destroy(),this.elevatedStructures&&this.elevatedStructures.destroy()}addFeature(f,_,S,L,O,z=[],G,Y){const re=tH(_,500);this.elevationMode!=="none"?this.addElevatedRoadFeature(f,re,L,S,Y):this.addGeometry(re,this.bufferData),this.bufferData.populatePaintArrays(f,S,O,z,L,G,this.worldview),this.elevationBufferData.populatePaintArrays(f,S,O,z,L,G,this.worldview)}getUnevaluatedPortalGraph(){return this.elevatedStructures?this.elevatedStructures.unevaluatedPortals:void 0}setEvaluatedPortalGraph(f,_,S,L,O){this.elevatedStructures&&(this.elevatedStructures.construct(f),this.elevatedStructures.populatePaintArrays(_,S,L,O,this.worldview))}addElevatedRoadFeature(f,_,S,L,O){const z=new Array,G=cc.getElevationFeature(f,O);if(!G)return void this.addGeometry(_,this.bufferData);{const re=this.clipPolygonsToTile(_,1);re.length>0&&z.push({polygons:re,elevationFeature:G,elevationTileID:S})}const Y={guardRailEnabled:this.layers[0].layout.get("fill-construct-bridge-guard-rail").evaluate(f,{},S),featureIndex:L};for(const re of z)if(re.elevationFeature){if(this.elevationMode==="hd-road-base"){this.elevatedStructures||(this.elevatedStructures=new Rv(re.elevationTileID,this.layers,this.zoom,this.lut));const ye=re.elevationFeature.isTunnel();let we=0;f.properties.hasOwnProperty(rc)&&(we=+f.properties[rc]),this.elevatedStructures.addPortalCandidates(re.elevationFeature.id,re.polygons,ye,re.elevationFeature,we)}re.elevationFeature.constantHeight==null&&(re.polygons=this.prepareElevatedPolygons(re.polygons,re.elevationFeature,re.elevationTileID));const me=new _c(S,re.elevationTileID);this.addElevatedGeometry(re.polygons,me,re.elevationFeature,this.elevationMode==="hd-road-base"?0:.05,L,Y)}}addElevatedGeometry(f,_,S,L,O,z){const G={elevation:S,elevationSampler:_,bias:L,index:O,featureInfo:z},[Y,re]=this.addGeometry(f,this.elevationBufferData,G);this.elevationBufferData.heightRange==null?this.elevationBufferData.heightRange={min:Y,max:re}:(this.elevationBufferData.heightRange.min=Math.min(this.elevationBufferData.heightRange.min,Y),this.elevationBufferData.heightRange.max=Math.max(this.elevationBufferData.heightRange.max,re))}addGeometry(f,_,S){let L=Number.POSITIVE_INFINITY,O=Number.NEGATIVE_INFINITY,z=null;S&&(z=S.elevationSampler.constantElevation(S.elevation,S.bias),z!=null&&(L=z,O=z));const G=(Y,re,me)=>{if(S!=null)if(re.push(Y),z!=null)_.elevatedLayoutVertexArray.emplaceBack(z),me.push(z);else{const ye=S.elevationSampler.pointElevation(Y,S.elevation,S.bias);_.elevatedLayoutVertexArray.emplaceBack(ye),me.push(ye),L=Math.min(L,ye),O=Math.max(O,ye)}};for(const Y of f){let re=0;for(const ut of Y)re+=ut.length;const me=_.triangleSegments.prepareSegment(re,_.layoutVertexArray,_.indexArray),ye=me.vertexLength,we=[],Te=[],Ie=[],Ve=[],Je=[],rt=_.layoutVertexArray.length;for(const ut of Y){if(ut.length===0)continue;ut!==Y[0]&&Te.push(we.length/2);const St=_.lineSegments.prepareSegment(ut.length,_.layoutVertexArray,_.lineIndexArray),Pt=St.vertexLength;S&&Je.push(_.layoutVertexArray.length-rt),G(ut[0],Ie,Ve),_.layoutVertexArray.emplaceBack(ut[0].x,ut[0].y),_.lineIndexArray.emplaceBack(Pt+ut.length-1,Pt),we.push(ut[0].x),we.push(ut[0].y);for(let Rt=1;Rt0&&S&&this.elevationMode==="hd-road-base"){const ut=S.elevation.isTunnel(),St=S.elevation.safeArea,Pt=this.elevatedStructures.addVertices(Ie,Ve);this.elevatedStructures.addTriangles(xt,Pt,ut);const Rt=Je.length;if(Rt>0){for(let ws=0;ws=S&&Te.max.x<=O&&Te.min.y>=L&&Te.max.y<=z?Y:re).push(we)}if(Y.length===f.length)return f;const me=[new Xt(S,L),new Xt(O,L),new Xt(O,z),new Xt(S,z),new Xt(S,L)],ye=Y;for(const we of re)ye.push(...tYt(we,me));return ye}}let lJe,cJe,dJe,uJe;br(Ute,"FillBucket",{omit:["layers","patternFeatures"]}),br(_6e,"FillBufferData"),br(Rv,"ElevatedStructures");class qte{constructor(f,_,S,L){if(this.triangleCount=_.length/3,this.min=new Xt(0,0),this.max=new Xt(0,0),this.xScale=0,this.yScale=0,this.cellsX=0,this.cellsY=0,this.cells=[],this.payload=[],this.triangleCount===0||f.length===0)return;const[O,z]=[f[0].clone(),f[0].clone()];for(let ye=1;yeye.cellIdx-we.cellIdx||ye.triIdx-we.triIdx);let me=0;for(;methis.max.x||this.min.x>f.x||f.y>this.max.y||this.min.y>f.y)return;const S=Pk(f.x-this.min.x,this.xScale,this.cellsX),L=Pk(f.y-this.min.y,this.yScale,this.cellsY),O=this.cells[L*this.cellsX+S];if(O){this._lazyInitLookup();for(let z=0;zthis.max.x||this.min.x>_.x||f.y>this.max.y||this.min.y>_.y)return;this._lazyInitLookup();const L=Pk(f.x-this.min.x,this.xScale,this.cellsX),O=Pk(_.x-this.min.x,this.xScale,this.cellsX),z=Pk(f.y-this.min.y,this.yScale,this.cellsY),G=Pk(_.y-this.min.y,this.yScale,this.cellsY);for(let Y=z;Y<=G;Y++)for(let re=L;re<=O;re++){const me=this.cells[Y*this.cellsX+re];if(me)for(let ye=0;ye_.fqid),this.index=f.index,this.hasPattern=!1,this.stateDependentLayerIds=this.layers.filter(_=>_.isStateDependent()).map(_=>_.id),this.footprints=[],this.worldview=f.worldview,this.hasAppearances=null}updateFootprints(f,_){for(const S of this.footprints)_.push({footprint:S,id:f})}updateAppearances(f,_,S,L){return{hasLayoutChanges:!1,hasUboChanges:!1}}populate(f,_,S,L){const O=[];for(const{feature:z,id:G,index:Y,sourceLayerIndex:re}of f){const me=this.layers[0]._featureFilter.needGeometry,ye=$i(z,me);if(!this.layers[0]._featureFilter.filter(new Si(this.zoom,{worldview:this.worldview,activeFloors:_.activeFloors}),ye,S))continue;const we={id:G,properties:z.properties,type:z.type,sourceLayerIndex:re,index:Y,geometry:me?ye.geometry:Oa(z,S,L),patterns:{}};O.push(we)}for(const z of O){const{geometry:G,index:Y,sourceLayerIndex:re}=z;this.addFeature(z,G,Y,S,{},_.availableImages,_.brightness),_.featureIndex.insert(f[Y].feature,G,Y,re,this.index)}}isEmpty(){return this.footprints.length===0}uploadPending(){return!1}upload(f){}update(f,_,S,L,O,z,G){}destroy(){}addFeature(f,_,S,L,O,z=[],G){for(const Y of tH(_,2)){const re=[],me=[],ye=[],we=new Xt(1/0,1/0),Te=new Xt(-1/0,-1/0);for(const Je of Y)if(Je.length!==0){Je!==Y[0]&&ye.push(me.length/2);for(let rt=0;rtf.max.x||k.max.xf.max.y||k.max.ynew Xt((Y.x+O.x*lr)*G-z.x*lr,(Y.y+O.y*lr)*G-z.y*lr))}return j6e(_,L,k.indices,0,k.indices.length,0,0)}function gJe(k,f,_,S){const L=Math.pow(2,S.z-_.z);return new Xt((k+_.x*lr)*L-S.x*lr,(f+_.y*lr)*L-S.y*lr)}function yJe(k,f){const _=[];f.grid.queryPoint(k,_);const S=f.indices,L=f.vertices;for(let O=0;O<_.length;O++){const z=_[O];if(K0([L[S[3*z+0]],L[S[3*z+1]],L[S[3*z+2]]],k))return!0}return!1}const Gte={None:0,Model:1,Symbol:2,FillExtrusion:4},N6e=[new Xt(0,0),new Xt(lr,0),new Xt(lr,lr),new Xt(0,lr)];function vJe(k,f){const _=[];let S=[];if(!f||k.length<2)return[k];if(k.length===2)return Ek(k[0],k[1],N6e)?[k]:[];for(let L=0;L0&&(S.length>1&&_.push(S),S=[])}return S.length>1&&_.push(S),_}const k6e=li.types,mYt=["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"],pYt=["fill-extrusion-flood-light-ground-radius"],fYt=Math.pow(2,13),xYt=Math.pow(2,15)-1,Wte=new Xt(0,1),m4=2147483648,Kte=1073741824;function aH(k,f,_,S,L,O,z,G){k.emplaceBack((f<<1)+z,(_<<1)+O,(Math.floor(S*fYt)<<1)+L,Math.round(G))}function iH(k,f,_){k.emplaceBack(f.x*lr,f.y*lr,_?1:0)}function Yte(k,f,_,S,L,O){k.emplaceBack(f.x,f.y,(_.x<<1)+S,(_.y<<1)+L,O)}function oH(k,f,_){k.emplaceBack(f.x,f.y,f.z,_[0]*16384,_[1]*16384,_[2]*16384)}class bJe{constructor(){this.vertexOffset=0,this.vertexCount=0,this.indexOffset=0,this.indexCount=0}}class S6e{constructor(){this.centroidXY=new Xt(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 Xt(Number.MAX_VALUE,Number.MAX_VALUE),this.max=new Xt(-Number.MAX_VALUE,-Number.MAX_VALUE),this.height=0,this.buildingId=0,this.groupCentroidPos=new Xt(0,0)}span(){return new Xt(this.max.x-this.min.x,this.max.y-this.min.y)}}class C6e{constructor(){this.acc=new Xt(0,0),this.accCount=0,this.centroidDataIndex=0}startRing(f,_){f.min.x===Number.MAX_VALUE&&(f.min.x=f.max.x=_.x,f.min.y=f.max.y=_.y)}appendEdge(f,_,S){this.accCount++,this.acc._add(_);let L=!!this.borders;_.xf.max.x&&(f.max.x=_.x,L=!0),_.yf.max.y&&(f.max.y=_.y,L=!0),((_.x===0||_.x===lr)&&_.x===S.x)!=((_.y===0||_.y===lr)&&_.y===S.y)&&this.processBorderOverlap(_,S),L&&this.checkBorderIntersection(_,S)}checkBorderIntersection(f,_){_.x<0!=f.x<0&&this.addBorderIntersection(0,Cs(_.y,f.y,(0-_.x)/(f.x-_.x))),_.x>lr!=f.x>lr&&this.addBorderIntersection(1,Cs(_.y,f.y,(lr-_.x)/(f.x-_.x))),_.y<0!=f.y<0&&this.addBorderIntersection(2,Cs(_.x,f.x,(0-_.y)/(f.y-_.y))),_.y>lr!=f.y>lr&&this.addBorderIntersection(3,Cs(_.x,f.x,(lr-_.y)/(f.y-_.y)))}addBorderIntersection(f,_){this.borders||(this.borders=[[Number.MAX_VALUE,-Number.MAX_VALUE],[Number.MAX_VALUE,-Number.MAX_VALUE],[Number.MAX_VALUE,-Number.MAX_VALUE],[Number.MAX_VALUE,-Number.MAX_VALUE]]);const S=this.borders[f];_S[1]&&(S[1]=_)}processBorderOverlap(f,_){if(f.x===_.x){if(f.y===_.y)return;const S=f.x===0?0:1;this.addBorderIntersection(S,_.y),this.addBorderIntersection(S,f.y)}else{const S=f.y===0?2:3;this.addBorderIntersection(S,_.x),this.addBorderIntersection(S,f.x)}}centroid(){return this.accCount===0?new Xt(0,0):new Xt(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((f,_)=>f+ +(_[0]!==Number.MAX_VALUE),0):0}}function _Je(k,f){const _=k.add(f)._unit(),S=pt(k.x*_.x+k.y*_.y,-1,1);var L,O,z;return z=Math.acos(S),Math.min(4,Math.max(-4,Math.tan(z)))/4*xYt*((L=k).x*(O=f).y-L.y*O.x<0?-1:1)}const gYt=[k=>k.x<0,k=>k.x>lr,k=>k.y<0,k=>k.y>lr];function yYt(k,f,_,S){const L=[4];if(S===0)return L;_._mult(S);const O=k.sub(_),z=f.sub(_),G=[k,f,O,z];for(let Y=0;Y<4;Y++)for(const re of G)if(gYt[Y](re)){L.push(Y);break}return L}class A6e{constructor(f){this.groundRadiusArray=null,this.groundRadiusBuffer=null,this.vertexArray=new dM,this.indexArray=new nu,this.programConfigurations=new tt(f.layers,{zoom:f.zoom,lut:f.lut},_=>pYt.includes(_)),this._segments=new sc,this.hiddenByLandmarkVertexArray=new PF,this._segmentToGroundQuads={},this._segmentToGroundQuads[0]=[],this._segmentToRegionTriCounts={},this._segmentToRegionTriCounts[0]=[0,0,0,0,0],this.regionSegments={},this.regionSegments[4]=new sc}getDefaultSegment(){return this.regionSegments[4]}hasData(){return this.vertexArray.length!==0}addData(f,_,S,L=!1){const O=f.length;if(O>2){let z=Math.max(0,this._segments.get().length-1);const G=this._segments._prepareSegment(4*O,this.vertexArray.length,2*this._segmentToGroundQuads[z].length);let Y;z!==this._segments.get().length-1&&(z++,this._segmentToGroundQuads[z]=[],this._segmentToRegionTriCounts[z]=[0,0,0,0,0]);{const re=f[0],me=f[1];Y=_Je(re.sub(f[O-1])._perp()._unit(),me.sub(re)._perp()._unit())}for(let re=0;reL.region-O.region);for(let S=0;S<_;S++){const L=this._segmentToGroundQuads[S],O=f[S],z=this._segmentToRegionTriCounts[S];z.reduce((Y,re)=>Y+re,0);let G=0;for(let Y=0;Y<=4;Y++){const re=z[Y];if(re!==0){let me=this.regionSegments[Y];me||(me=this.regionSegments[Y]=new sc);const ye={vertexOffset:O.vertexOffset,primitiveOffset:O.primitiveOffset+G,vertexLength:O.vertexLength,primitiveLength:re};me.get().push(ye)}G+=re}for(let Y=0;Y0?this.hiddenByLandmarkVertexBuffer=f.createVertexBuffer(this.hiddenByLandmarkVertexArray,lYt.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 f=0;f<=4;f++){const _=this.regionSegments[f];_&&_.destroy()}}}}class Zte{constructor(f){this.zoom=f.zoom,this.canonical=f.canonical,this.overscaling=f.overscaling,this.layers=f.layers,this.pixelRatio=f.pixelRatio,this.layerIds=this.layers.map(_=>_.fqid),this.index=f.index,this.hasPattern=!1,this.edgeRadius=0,this.projection=f.projection,this.activeReplacements=[],this.replacementUpdateTime=0,this.centroidData=[],this.footprintIndices=new nu,this.footprintVertices=new zi,this.footprintSegments=[],this.layoutVertexArray=new G1,this.centroidVertexArray=new Ete,this.wallVertexArray=new HV,this.indexArray=new nu,this.programConfigurations=new tt(f.layers,{zoom:f.zoom,lut:f.lut},_=>mYt.includes(_)),this.segments=new sc,this.stateDependentLayerIds=this.layers.filter(_=>_.isStateDependent()).map(_=>_.id),this.groundEffect=new A6e(f),this.maxHeight=0,this.partLookup={},this.triangleSubSegments=[],this.polygonSegments=[],this.buildingGroups=new Map,this.worldview=f.worldview,this.hasAppearances=null}updateFootprints(f,_){}updateAppearances(f,_,S,L){return{hasLayoutChanges:!1,hasUboChanges:!1}}populate(f,_,S,L){this.features=[],this.hasPattern=u6e("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=Bn(S),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:z,index:G,sourceLayerIndex:Y}of f){const re=this.layers[0]._featureFilter.needGeometry,me=$i(O,re);if(!this.layers[0]._featureFilter.filter(new Si(this.zoom,{worldview:this.worldview,activeFloors:_.activeFloors}),me,S))continue;const ye={id:z,sourceLayerIndex:Y,index:G,geometry:re?me.geometry:Oa(O,S,L),properties:O.properties,type:O.type,patterns:{}},we=this.layoutVertexArray.length,Te=k6e[ye.type]==="Polygon";if(this.hasPattern)this.features.push({featureId:O.id,feature:h6e("fill-extrusion",this.layers,ye,this.zoom,this.pixelRatio,_)});else if(this.wallMode)for(const Ie of ye.geometry)for(const Ve of vJe(Ie,Te))this.addFeature(O.id,ye,[Ve],G,S,{},_.availableImages,L,_.brightness);else this.addFeature(O.id,ye,ye.geometry,G,S,{},_.availableImages,L,_.brightness);_.featureIndex.insert(O,ye.geometry,G,Y,this.index,we)}this._finalizeBuildingGroups(),this.sortBorders(),this.projection.name==="mercator"&&this.splitToSubtiles(),this.groundEffect.prepareBorderSegments(),this.polygonSegments.length=0}addFeatures(f,_,S,L,O,z){for(const{featureId:G,feature:Y}of this.features){const re=k6e[Y.type]==="Polygon",{geometry:me}=Y;if(this.wallMode)for(const ye of me)for(const we of vJe(ye,re))this.addFeature(G,Y,[we],Y.index,_,S,L,O,z);else this.addFeature(G,Y,me,Y.index,_,S,L,O,z)}this._finalizeBuildingGroups(),this.sortBorders(),this.projection.name==="mercator"&&this.splitToSubtiles()}update(f,_,S,L,O,z,G){this.programConfigurations.updatePaintArrays(f,_,O,S,L,z,G,this.worldview),this.groundEffect.update(f,_,O,S,L,z,G,this.worldview)}isEmpty(){return this.layoutVertexArray.length===0}uploadPending(){return!this.uploaded||this.programConfigurations.needsUpload||this.groundEffect.programConfigurations.needsUpload}upload(f){this.uploaded||(this.layoutVertexBuffer=f.createVertexBuffer(this.layoutVertexArray,dYt),this.indexBuffer=f.createIndexBuffer(this.indexArray),this.wallVertexBuffer=f.createVertexBuffer(this.wallVertexArray,oYt.members),this.layoutVertexExtArray&&(this.layoutVertexExtBuffer=f.createVertexBuffer(this.layoutVertexExtArray,cYt.members,!0)),this.groundEffect.upload(f)),this.groundEffect.uploadPaintProperties(f),this.programConfigurations.upload(f),this.uploaded=!0}uploadCentroid(f){this.groundEffect.uploadHiddenByLandmark(f),this.needsCentroidUpdate&&(!this.centroidVertexBuffer&&this.centroidVertexArray.length>0?this.centroidVertexBuffer=f.createVertexBuffer(this.centroidVertexArray,iYt.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(f,_,S,L,O,z,G,Y,re){const me=this.layers[0].paint.get("fill-extrusion-flood-light-ground-radius").evaluate(_,{})/this.tileToMeter,ye=[new Xt(0,0),new Xt(lr,lr)],we=Y.projection,Te=we.name==="globe",Ie=this.wallMode||k6e[_.type]==="Polygon",Ve=new C6e;Ve.centroidDataIndex=this.centroidData.length;const Je=new S6e;Je.buildingId=f,_.properties&&_.properties.hasOwnProperty("building_id")&&(Je.buildingId=Number(_.properties.building_id)),Ve.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,Te&&!this.layoutVertexExtArray&&(this.layoutVertexExtArray=new CF),this.wallMode){if(Te)return void Or("Non zero fill-extrusion-line-width is not yet supported on globe.");if(S.length!==1)return;ut=function(us){const hs=us[0].x===us[us.length-1].x&&us[0].y===us[us.length-1].y;(function(wr){let hr=0;const Gr=wr.length;for(let aa=0;aa=0})(us)||(us=us.reverse());const bn={geometry:[],joinNormals:[],indices:[]},An=[],Ln=[],En=[];let Jn=us.length;for(;Jn>=2&&us[Jn-1].equals(us[Jn-2]);)Jn--;if(Jn<(hs?3:2))return bn;let un,Mn,Rn,er,ur,Zr=0;for(;Zr0;let _a="miter";const _i=2;_a==="miter"&&aa>_i&&(_a="bevel"),_a==="bevel"&&(aa>100&&(_a="flipbevel"),aa<_i&&(_a="miter"));const To=(wi,Do,Ui,Od)=>{const ll=new Xt(wi.x,wi.y),$o=new Xt(wi.x,wi.y);ll.x+=Do.x*Od,ll.y+=Do.y*Od,$o.x-=Do.x*Math.max(Ui,1),$o.y-=Do.y*Math.max(Ui,1),En.push(Do),An.push(ll),Ln.push($o)};if(_a==="miter")hr._mult(aa),To(un,hr,0,0);else if(_a==="flipbevel")hr=ur.mult(-1),To(un,hr,0,0),To(un,hr.mult(-1),0,0);else{const wi=-Math.sqrt(aa*aa-1),Do=Da?wi:0,Ui=Da?0:wi;Mn&&To(un,er,Do,Ui),Rn&&To(un,ur,Do,Ui)}}bn.geometry=[...An,...Ln.reverse(),An[0]],bn.joinNormals=[...En,...En.reverse(),En[En.length-1]];const Nr=bn.geometry.length-1;for(let wr=0;wrus<(hs.length-1)/2||us===hs.length-1,Pt=this.wallMode?[S]:tH(S,500);for(let us=Pt.length-1;us>=0;us--){const hs=Pt[us];(hs.length===0||bYt(hs[0]))&&Pt.splice(us,1)}let Rt;if(Te)Rt=AJe(Pt,ye,O);else{Rt=[];for(const us of Pt)Rt.push({polygon:us,bounds:ye})}const ws=Ie?this.edgeRadius:0,ns=ws>0&&this.zoom<17,xs=(us,hs)=>{if(us.length===0)return!1;const pn=us[us.length-1];return hs.x===pn.x&&hs.y===pn.y};for(const{polygon:us,bounds:hs}of Rt){let pn=0,bn=0;for(const Jn of us)Ie&&!Jn[0].equals(Jn[Jn.length-1])&&Jn.push(Jn[0]),bn+=Ie?Jn.length-1:Jn.length;const An=this.segments.prepareSegment((Ie?5:4)*bn,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},En=new bJe;if(En.vertexOffset=this.footprintVertices.length,En.indexOffset=3*this.footprintIndices.length,En.ringIndices=[],Ie){const Jn=[],un=[];pn=An.vertexLength;for(let Rn=0;Rn4&&kJe(un[un.length-2],un[0],un[1]),Rn=ws?vYt(un[un.length-2],un[0],un[1],ws):0;const er=[];let ur,Zr,Nr;Zr=un[1].sub(un[0])._perp()._unit();let wr=!0;for(let hr=1,Gr=0;hr0?1:0,Do=aa.dist(Da);if(Gr+Do>32768&&(Gr=0),ws){Nr=_a.sub(Da)._perp()._unit();let $o=jJe(aa,Da,_a,wJe(Zr,Nr),ws);isNaN($o)&&($o=0);const ac=Da.sub(aa)._unit();aa=aa.add(ac.mult(Rn))._round(),Da=Da.add(ac.mult(-$o))._round(),Rn=$o,Zr=Nr,rt&&this.zoom>=17&&(xs(er,aa)||er.push(aa),xs(er,Da)||er.push(Da))}const Ui=An.vertexLength,Od=un.length>4&&kJe(aa,Da,_a);let ll=SJe(Gr,Mn,wr);if(aH(this.layoutVertexArray,aa.x,aa.y,To,wi,0,0,ll),aH(this.layoutVertexArray,aa.x,aa.y,To,wi,0,1,ll),this.wallMode){const $o=St(hr-1,un),ac=ut.joinNormals[hr-1];iH(this.wallVertexArray,ac,$o),iH(this.wallVertexArray,ac,$o)}if(Gr+=Do,ll=SJe(Gr,Od,!wr),Mn=Od,aH(this.layoutVertexArray,Da.x,Da.y,To,wi,0,0,ll),aH(this.layoutVertexArray,Da.x,Da.y,To,wi,0,1,ll),this.wallMode){const $o=St(hr,un),ac=ut.joinNormals[hr];iH(this.wallVertexArray,ac,$o),iH(this.wallVertexArray,ac,$o)}if(An.vertexLength+=4,this.indexArray.emplaceBack(Ui+0,Ui+1,Ui+2),this.indexArray.emplaceBack(Ui+1,Ui+3,Ui+2),An.primitiveLength+=2,ws){const $o=pn+(hr===1?un.length-2:hr-2),ac=hr===1?pn:$o+1;if(this.indexArray.emplaceBack(Ui+1,$o,Ui+3),this.indexArray.emplaceBack($o,ac,Ui+3),An.primitiveLength+=2,ur===void 0&&(ur=Ui),!E6e(_a,un[hr],hs)){const kd=hr===un.length-1?ur:An.vertexLength;this.indexArray.emplaceBack(Ui+2,Ui+3,kd),this.indexArray.emplaceBack(Ui+3,kd+1,kd),this.indexArray.emplaceBack(Ui+3,ac,kd+1),An.primitiveLength+=3}wr=!wr}if(Te){const $o=this.layoutVertexExtArray,ac=we.projectTilePoint(aa.x,aa.y,O),kd=we.projectTilePoint(Da.x,Da.y,O),$m=we.upVector(O,aa.x,aa.y),Sd=we.upVector(O,Da.x,Da.y);oH($o,ac,$m),oH($o,ac,$m),oH($o,kd,Sd),oH($o,kd,Sd)}}Ie&&(pn+=un.length-1),rt&&ws&&this.zoom>=17&&(er.length!==0&&xs(er,er[0])&&er.pop(),this.groundEffect.addData(er,hs,me,ws>0))}this.footprintSegments.push(En),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=Ve.borders?Wte:this.encodeCentroid(Ve,Je),_.properties&&_.properties.hasOwnProperty("building_id")){const us=Je.buildingId;let hs=this.buildingGroups.get(us);hs||(hs={accX:0,accY:0,accCount:0,mergedMin:new Xt(Number.MAX_VALUE,Number.MAX_VALUE),mergedMax:new Xt(-Number.MAX_VALUE,-Number.MAX_VALUE),partIndices:[]},this.buildingGroups.set(us,hs)),hs.accX+=Ve.acc.x,hs.accY+=Ve.acc.y,hs.accCount+=Ve.accCount,hs.mergedMin.x=Math.min(hs.mergedMin.x,Je.min.x),hs.mergedMin.y=Math.min(hs.mergedMin.y,Je.min.y),hs.mergedMax.x=Math.max(hs.mergedMax.x,Je.max.x),hs.mergedMax.y=Math.max(hs.mergedMax.y,Je.max.y),hs.partIndices.push(this.centroidData.length)}if(this.centroidData.push(Je),Ve.borders){this.featuresOnBorder.push(Ve);const us=this.featuresOnBorder.length-1;for(let hs=0;hsthis.featuresOnBorder[_].borders[f][0]-this.featuresOnBorder[S].borders[f][0])}splitToSubtiles(){const f=[];for(let G=0;Glr),me=2*re+(+(Y.min.x+Y.max.x>lr)^re);for(let ye=0;yeG.triangleSegmentIdx===Y.triangleSegmentIdx?G.subtile-Y.subtile:G.triangleSegmentIdx-Y.triangleSegmentIdx);let S=0,L=0,O=0;for(const G of f){if(G.triangleSegmentIdx!==S)break;O++}const z=f.length;for(;L!==f.length;){S=f[L].triangleSegmentIdx;let G=0,Y=L,re=L;for(let me=Y;me0&&this.triangleSubSegments.push({segment:Te,min:ye,max:we}),Y=re;for(let Ie=Y;Ie[Ve[0]*(1-rt[0])+Je[0]*rt[0],Ve[1]*(1-rt[1])+Je[1]*rt[1]],Te=[],Ie=[];for(const Ve of this.triangleSubSegments){Te[0]=Ve.min.x/lr,Te[1]=Ve.min.y/lr,Ie[0]=Ve.max.x/lr,Ie[1]=Ve.max.y/lr;const Je=we(me,ye,Te),rt=we(me,ye,Ie);if(new ul([Je[0],Je[1],O],[rt[0],rt[1],z]).intersectsPrecise(S)===0){re&&(L.segments.push(re),re=void 0);continue}const xt=Ve.segment;re&&re.vertexOffset!==xt.vertexOffset&&(L.segments.push(re),re=void 0),re?(re.vertexLength+=xt.vertexLength,re.primitiveLength+=xt.primitiveLength):re={vertexOffset:xt.vertexOffset,primitiveLength:xt.primitiveLength,vertexLength:xt.vertexLength,primitiveOffset:xt.primitiveOffset,sortKey:void 0,vaos:{}}}return re&&L.segments.push(re),L}encodeCentroid(f,_){const S=f.centroid(),L=_.span(),O=Math.min(7,Math.round(L.x*this.tileToMeter/10)),z=Math.min(6,Math.round(L.y*this.tileToMeter/10));return new Xt(pt(S.x,1,8191)<<3|O,pt(S.y,1,8191)<<3|z)}encodeBorderCentroid(f){if(!f.borders)return new Xt(0,0);const _=f.borders,S=Number.MAX_VALUE;if(_[0][0]!==S||_[1][0]!==S){const L=_[0][0]!==S?0:1;return new Xt(6|(_[0][0]!==S?0:65528),(_[L][0]+_[L][1])/2<<3|6)}{const L=_[2][0]!==S?2:3;return new Xt((_[L][0]+_[L][1])/2<<3|6,6|(_[2][0]!==S?0:65528))}}showCentroid(f){const _=this.centroidData[f.centroidDataIndex];if(_.flags&=m4,_.groupCentroidPos.x!==0||_.groupCentroidPos.y!==0){const S=_.span(),L=Math.min(7,Math.round(S.x*this.tileToMeter/10)),O=Math.min(6,Math.round(S.y*this.tileToMeter/10));_.centroidXY=new Xt(pt(_.groupCentroidPos.x,1,8191)<<3|L,pt(_.groupCentroidPos.y,1,8191)<<3|O)}else _.centroidXY=new Xt(0,0);this.writeCentroidToBuffer(_)}writeCentroidToBuffer(f){this.groundEffect.updateHiddenByLandmark(f);const _=f.vertexArrayOffset,S=f.vertexCount+f.vertexArrayOffset,L=-1073741824&f.flags?Wte:f.centroidXY,O=this.centroidVertexArray.geta_centroid_pos0(_);if(this.centroidVertexArray.geta_centroid_pos1(_)!==L.y||O!==L.x){for(let z=_;zY.max.x||Y.min.x>z.max.x||z.min.y>Y.max.y||Y.min.y>z.max.y||z.footprint.buildingIds.has(Y.buildingId)&&(Y.flags|=z.clipMask!==Gte.None?-1073741824:m4);else for(const Y of this.centroidData)if(!(Y.flags&m4||Y.flags&Kte||z.min.x>Y.max.x||Y.min.x>z.max.x||z.min.y>Y.max.y||Y.min.y>z.max.y))for(let re=0;re_!=Te>_&&f<(this.footprintVertices.int16[2*(me+z.vertexOffset)+0]-ye)*(_-we)/(Te-we)+ye&&(L=!L)}G=Y}}return L}getHeightAtTileCoord(f,_){let S=Number.NEGATIVE_INFINITY,L=!0;const O=4*(f+lr)*lr+(_+lr);if(this.partLookup.hasOwnProperty(O)){const z=this.partLookup[O];return z?{height:z.height,hidden:!!(z.flags&m4)}:void 0}for(const z of this.centroidData)f>z.max.x||z.min.x>f||_>z.max.y||z.min.y>_||z.height<=S||this.footprintContainsPoint(f,_,z)&&(S=z.height,this.partLookup[O]=z,L=!!(z.flags&m4));if(S!==Number.NEGATIVE_INFINITY)return{height:S,hidden:L};this.partLookup[O]=void 0}}function wJe(k,f){const _=k.add(f)._unit();return k.x*_.x+k.y*_.y}function vYt(k,f,_,S){const L=f.sub(k)._perp()._unit(),O=_.sub(f)._perp()._unit();return jJe(k,f,_,wJe(L,O),S)}function jJe(k,f,_,S,L){const O=Math.sqrt(1-S*S);return Math.min(k.dist(f)/3,f.dist(_)/3,L*O/S)}function E6e(k,f,_){return k.x<_[0].x&&f.x<_[0].x||k.x>_[1].x&&f.x>_[1].x||k.y<_[0].y&&f.y<_[0].y||k.y>_[1].y&&f.y>_[1].y}function NJe(k,f){return k.xf[1].x||k.yf[1].y}function bYt(k){return k.every(f=>f.x<=0)||k.every(f=>f.x>=lr)||k.every(f=>f.y<=0)||k.every(f=>f.y>=lr)}function kJe(k,f,_){if(k.x<0||k.x>=lr||f.x<0||f.x>=lr||_.x<0||_.x>=lr)return!1;const S=_.sub(f),L=S.perp(),O=k.sub(f);return(S.x*O.x+S.y*O.y)/Math.sqrt((S.x*S.x+S.y*S.y)*(O.x*O.x+O.y*O.y))>-.866&&L.x*O.x+L.y*O.y<0}function SJe(k,f,_){const S=f?2|k:-3&k;return _?1|S:-2&S}function CJe(){const k=Math.PI/32,f=Math.tan(k),_=fs;return _*Math.sqrt(1+2*f*f)-_}function AJe(k,f,_){const S=1<<_.z,L=Ms(_.x/S),O=Ms((_.x+1)/S),z=mn(_.y/S),G=mn((_.y+1)/S);return function(Y,re,me,ye,we=0,Te){const Ie=[];if(!Y.length||!me||!ye)return Ie;const Ve=(Rt,ws)=>{for(const ns of Rt)Ie.push({polygon:ns,bounds:ws})},Je=Math.ceil(Math.log2(me)),rt=Math.ceil(Math.log2(ye)),xt=Je-rt,ut=[];for(let Rt=0;Rt0?0:1);for(let Rt=0;Rtws+1?Pt.push({polygons:An,bounds:En,depth:ws+1}):Ve(An,En)}if(Ln.length){const En=[new Xt(ns===0?bn:xs.x,ns===1?bn:xs.y),us];ut.length>ws+1?Pt.push({polygons:Ln,bounds:En,depth:ws+1}):Ve(Ln,En)}}return Ie}(k,f,Math.ceil((O-L)/11.25),Math.ceil((z-G)/11.25),1,(Y,re,me)=>{if(Y===0)return .5*(re+me);{const ye=mn((_.y+re/lr)/S);return(Gn(.5*(mn((_.y+me/lr)/S)+ye))*S-_.y)*lr}})}function _Yt(k,f,_,S,L,O){const z=Math.pow(2,S.z-L.z);for(let G=0;G<_;G++){let Y=k.int16[2*(G+f)+0],re=k.int16[2*(G+f)+1];Y=(Y+L.x*lr)*z-S.x*lr,re=(re+L.y*lr)*z-S.y*lr,O.push(new Xt(Y,re))}}let EJe,TJe;br(Zte,"FillExtrusionBucket",{omit:["layers","features"]}),br(S6e,"PartData"),br(bJe,"FootprintSegment"),br(C6e,"BorderCentroidData"),br(A6e,"GroundEffect");class NM extends Xt{constructor(f,_,S){super(f,_),this.z=S}}class MJe extends NM{constructor(f,_,S,L){super(f,_,S),this.w=L}}function LJe(k,f,_,S){const L=_==="x"?"y":"x",O=(S-k[_])/(f[_]-k[_]);k[L]=Math.round(k[L]+(f[L]-k[L])*O),k[_]=S,k.hasOwnProperty("z")&&(k.z=Cs(k.z,f.z,O)),k.hasOwnProperty("w")&&(k.w=Cs(k.w,f.w,O))}function PJe(k,f,_,S){const L=_,O=S;for(const z of["x","y"]){let G=k,Y=f;G[z]>=Y[z]&&(G=f,Y=k),G[z]L&&LJe(G,Y,z,L),G[z]O&&LJe(Y,G,z,O)}}function Xte(k,f,_,S,L,O){const z=[];for(let G=0;G=S&&Ie.x>=S||(Te.x>=S?Te=new Xt(S,Te.y+(S-Te.x)/(Ie.x-Te.x)*(Ie.y-Te.y))._round():Ie.x>=S&&(Ie=new Xt(S,Te.y+(S-Te.x)/(Ie.x-Te.x)*(Ie.y-Te.y))._round()),Te.y>=L&&Ie.y>=L||(Te.y>=L?Te=new Xt(Te.x+(L-Te.y)/(Ie.y-Te.y)*(Ie.x-Te.x),L)._round():Ie.y>=L&&(Ie=new Xt(Te.x+(L-Te.y)/(Ie.y-Te.y)*(Ie.x-Te.x),L)._round()),re&&Te.equals(re[re.length-1])||(re=[Te],z.push(re),O&&O.push({progress:{min:Je+IJe(rt,xt,Te)*Ve,max:1},parentIndex:G,prevPoint:rt,nextPoint:xt})),re.push(Ie),O&&(O[O.length-1].progress.max=Je+IJe(rt,xt,Ie)*Ve,O[O.length-1].nextPoint=xt)))))}if(O&&ye>0)for(let we=me;were.t-me.t);let z=0,G=0,Y=[];for(S.push(Y);z!==k.length;){if(G===O.length){for(;z!==k.length;)Y.length!==0&&Y[Y.length-1].equals(k[z])||Y.push(k[z]),z++;break}O[G].t<=z?(Y.length!==0&&Y[Y.length-1].equals(O[G].point)||Y.push(O[G].point),Math.trunc(O[G].t),G++):(Y.length!==0&&Y[Y.length-1].equals(k[z])||Y.push(k[z]),z++)}}function IJe(k,f,_){return k.x!==f.x?(_.x-k.x)/(f.x-k.x):k.y!==f.y?(_.y-k.y)/(f.y-k.y):0}function lH(k,f){return k.x*f.x+k.y*f.y}function DJe(k,f){if(k.length===1){let _=0;const S=f[_++];let L;for(;!L||S.equals(L);)if(L=f[_++],!L)return 1/0;for(;_{bn[0]=An,bn[1]=Ln,bn[2]=En,bn[3]=1},pn=CJe();Te>0&&(Te+=pn),Ie+=pn;for(const bn of we){const An=[],Ln=[];for(const En of bn){const Jn=En.x+Ve.x,un=En.y+Ve.y,Mn=ye.projection.projectTilePoint(Jn,un,Pt),Rn=ye.projection.upVector(Pt,En.x,En.y);let er=Te,ur=Ie;if(rt){const Zr=FJe(Jn,un,Te,Ie,rt,xt,ut,St);er+=Zr.base,ur+=Zr.top}Te!==0?hs(xs,Mn.x+Rn[0]*ns*er,Mn.y+Rn[1]*ns*er,Mn.z+Rn[2]*ns*er):hs(xs,Mn.x,Mn.y,Mn.z),hs(us,Mn.x+Rn[0]*ns*ur,Mn.y+Rn[1]*ns*ur,Mn.z+Rn[2]*ns*ur),Xe(xs,xs,Je),Xe(us,us,Je),An.push(new NM(xs[0],xs[1],xs[2])),Ln.push(new NM(us[0],us[1],us[2]))}Rt.push(An),ws.push(Ln)}return[Rt,ws]}(k,f,_,S,L,O,z,G,Y,re,me):z?function(ye,we,Te,Ie,Ve,Je,rt,xt,ut){const St=[],Pt=[],Rt=[0,0,0,1];for(const ws of ye){const ns=[],xs=[];for(const us of ws){const hs=us.x+Ie.x,pn=us.y+Ie.y,bn=FJe(hs,pn,we,Te,Je,rt,xt,ut);Rt[0]=hs,Rt[1]=pn,Rt[2]=bn.base,Rt[3]=1,nt(Rt,Rt,Ve),Rt[3]=Math.max(Rt[3],1e-5);const An=new NM(Rt[0]/Rt[3],Rt[1]/Rt[3],Rt[2]/Rt[3]);Rt[0]=hs,Rt[1]=pn,Rt[2]=bn.top,Rt[3]=1,nt(Rt,Rt,Ve),Rt[3]=Math.max(Rt[3],1e-5);const Ln=new NM(Rt[0]/Rt[3],Rt[1]/Rt[3],Rt[2]/Rt[3]);ns.push(An),xs.push(Ln)}St.push(ns),Pt.push(xs)}return[St,Pt]}(f,_,S,L,O,z,G,Y,re):function(ye,we,Te,Ie,Ve){const Je=[],rt=[],xt=Ve[8]*we,ut=Ve[9]*we,St=Ve[10]*we,Pt=Ve[11]*we,Rt=Ve[8]*Te,ws=Ve[9]*Te,ns=Ve[10]*Te,xs=Ve[11]*Te;for(const us of ye){const hs=[],pn=[];for(const bn of us){const An=bn.x+Ie.x,Ln=bn.y+Ie.y,En=Ve[0]*An+Ve[4]*Ln+Ve[12],Jn=Ve[1]*An+Ve[5]*Ln+Ve[13],un=Ve[2]*An+Ve[6]*Ln+Ve[14],Mn=Ve[3]*An+Ve[7]*Ln+Ve[15],Rn=En+xt,er=Jn+ut,ur=un+St,Zr=Math.max(Mn+Pt,1e-5),Nr=En+Rt,wr=Jn+ws,hr=un+ns,Gr=Math.max(Mn+xs,1e-5);hs.push(new NM(Rn/Zr,er/Zr,ur/Zr)),pn.push(new NM(Nr/Gr,wr/Gr,hr/Gr))}Je.push(hs),rt.push(pn)}return[Je,rt]}(f,_,S,L,O)}function FJe(k,f,_,S,L,O,z,G){const Y=z*L.getElevationAt(k,f,!0,!0),re=O[0]!==0,me=re?O[1]===0?z*(O[0]/7-450):z*function(ye,we,Te){const Ie=Math.floor(we[0]/8),Ve=Math.floor(we[1]/8),Je=10*(we[0]-8*Ie),rt=10*(we[1]-8*Ve),xt=ye.getElevationAt(Ie,Ve,!0,!0),ut=ye.getMeterToDEM(Te),St=Math.floor(.5*(Je*ut-1)),Pt=Math.floor(.5*(rt*ut-1)),Rt=ye.tileCoordToPixel(Ie,Ve),ws=2*St+1,ns=2*Pt+1,xs=function(Ln,En,Jn,un,Mn){return[Ln.getElevationAtPixel(En,Jn,!0),Ln.getElevationAtPixel(En+Mn,Jn,!0),Ln.getElevationAtPixel(En,Jn+Mn,!0),Ln.getElevationAtPixel(En+un,Jn+Mn,!0)]}(ye,Rt.x-St,Rt.y-Pt,ws,ns),us=Math.abs(xs[0]-xs[1]),hs=Math.abs(xs[2]-xs[3]),pn=Math.abs(xs[0]-xs[2])+Math.abs(xs[1]-xs[3]),bn=Math.min(.25,.5*ut*(us+hs)/ws),An=Math.min(.25,.5*ut*pn/ns);return xt+Math.max(bn*Je,An*rt)}(L,O,G):Y;return{base:Y+(_===0?-1:_),top:re?Math.max(me+S,Y+_+2):Y+S}}const T6e=4096;class jYt{constructor(f){this.module=f,this.memoryStack=this.module.malloc(T6e),this.memoryStackNextFree=this.memoryStack}createIntArray(f){const _=this.memoryStackNextFree;return this.memoryStackNextFree+=f.length*Int32Array.BYTES_PER_ELEMENT,this.memoryStackNextFree-this.memoryStack>T6e?-1:(new Int32Array(this.module.heap32.buffer,_,f.length).set(f),_)}createFloatArray(f){const _=this.memoryStackNextFree;return this.memoryStackNextFree+=f.length*Float32Array.BYTES_PER_ELEMENT,this.memoryStackNextFree-this.memoryStack>T6e?-1:(new Float32Array(this.module.heapF32.buffer,_,f.length).set(f),_)}readStringBuffer(f){let _="";for(;this.module.heapU8[f]!==0;)_+=String.fromCharCode(this.module.heapU8[f]),++f;return _}setStyle(f){const _=f.normalScale;this.module.setStyle(_[0],_[1],_[2],f.tileToMeters)}setAOOptions(f,_){this.module.setAOOptions(f?1:0,_)}setMetricOptions(f,_){this.module.setMetricOptions(f?1:0,_)}setStructuralOptions(f){this.module.setStructuralOptions(f?1:0)}setFacadeOptions(f,_){this.module.setFacadeOptions(f,_?1:0)}setFauxFacadeOptions(f,_,S){this.module.setFauxFacadeOptions(f?1:0,_?1:0,S)}setFacadeClassifierOptions(f){this.module.setFacadeClassifierOptions(f)}generateMesh(f,_){this.memoryStackNextFree=this.memoryStack;for(const G of f){const Y=this.createIntArray(G.ringIndices),re=this.createFloatArray(G.coordinates);if(Y===-1||re===-1)return`building_gen: Out of stack memory: ${this.memoryStackNextFree-this.memoryStack}/4096`;this.module.addFeature(G.id,G.sourceId,G.minHeight,G.height,G.roofType,re,Y,G.ringIndices.length-1)}for(const G of _){let Y;Y=G.entrances?JSON.parse(G.entrances):[];const re=this.createFloatArray(Y),me=this.createFloatArray(G.coordinates);if(re===-1||me===-1)return`building_gen: Out of stack memory: ${this.memoryStackNextFree-this.memoryStack}/4096`;this.module.addFacade(G.sourceId,G.crossPerc,G.distanceToRoad,re,Y.length,me,G.coordinates.length)}if(!this.module.generateMesh()){const G=this.module.getLastError();return this.readStringBuffer(G)}const S=this.module.getMeshCount(),L=new Array(S);for(let G=0;G>2)-3,Je=Te[Ie++]>>2;if(Ie++,L.json=JSON.parse(KJe.decode(Te.subarray(Ie,Ie+Je))),Ie+=Je,Ie>>0,Math.ceil(1.2*St)),Rt=Math.ceil((Pt-St)/65536);try{return Ve.grow(Rt),Je(),!0}catch{return!1}},b:rt}};return(WebAssembly.instantiateStreaming?WebAssembly.instantiateStreaming(Te,xt):Te.then(ut=>ut.arrayBuffer()).then(ut=>WebAssembly.instantiate(ut,xt))).then(ut=>{const{Rb:St,Qb:Pt,P:Rt,T:ws,X:ns,Ja:xs,La:us,Qa:hs,Va:pn,Wa:bn,eb:An,jb:Ln,f:En,e:Jn,yb:un,zb:Mn,Ab:Rn,Bb:er,Db:ur,Gb:Zr}=ut.instance.exports;Ve=Jn;const Nr=(()=>{let wr=0,hr=0,Gr=0,aa=0;return Da=>{Gr&&(St(aa),St(wr),hr+=Gr,Gr=wr=0),wr||(hr+=128,wr=Pt(hr));const _a=Da.length+7&-8;let _i=wr;_a>=hr&&(Gr=_a,_i=aa=Pt(_a));for(let To=0;To{P2=Te,cH=void 0}))}()),we&&me.push(function(){if(M6e)return;const Te=function(Ie){let Ve;const Je=WebAssembly.instantiateStreaming(Ie,{}).then(ut=>{Ve=ut.instance,Ve.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,Pt,Rt,ws,ns){(function(xs,us,hs,pn,bn,An,Ln){const En=xs.exports.sbrk,Jn=pn+3&-4,un=En(Jn*bn),Mn=En(An.length),Rn=new Uint8Array(xs.exports.memory.buffer);Rn.set(An,Mn);const er=us(un,pn,bn,Mn,An.length);if(er===0&&Ln&&Ln(un,Jn,bn),hs.set(Rn.subarray(un,un+pn*bn)),En(un-En(0)),er!==0)throw new Error(`Malformed buffer data: ${er}`)})(Ve,Ve.exports[xt[ws]],ut,St,Pt,Rt,Ve.exports[rt[ns]])}}}(fetch(Ur()));return Te.ready.then(()=>{M6e=Te})}()),z)for(let Te=0;Te{const G=rm(S,(Y,re)=>{Y?z(Y):O(re)});L&&L.addEventListener("abort",()=>{G.cancel(),z(new DOMException("Aborted","AbortError"))},{once:!0})})}({url:k,type:"arrayBuffer"},f);return XJe(_,0,k,f)}function P6e(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 I6e(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 Ik{constructor(f,_,S,L){this.context=f,this.format=S,this.useMipmap=L&&L.useMipmap,this.texture=f.gl.createTexture(),this.update(_,{premultiply:L&&L.premultiply})}update(f,_){const S=f&&f instanceof HTMLVideoElement&&f.width===0?f.videoWidth:f.width,L=f&&f instanceof HTMLVideoElement&&f.height===0?f.videoHeight:f.height,{context:O}=this,{gl:z}=O,{x:G,y:Y}=_&&_.position?_.position:{x:0,y:0},re=G+S,me=Y+L;this.size&&(this.size[0]!==re||this.size[1]!==me)&&(!_||_.recreateWhenResize===void 0||_.recreateWhenResize)&&(z.bindTexture(z.TEXTURE_2D,null),z.deleteTexture(this.texture),this.texture=z.createTexture(),this.size=null),z.bindTexture(z.TEXTURE_2D,this.texture),O.pixelStoreUnpackFlipY.set(!1),O.pixelStoreUnpack.set(1),O.pixelStoreUnpackPremultiplyAlpha.set(this.format===z.RGBA8&&(!_||_.premultiply!==!1));const ye=f instanceof HTMLImageElement||f instanceof HTMLCanvasElement||f instanceof HTMLVideoElement||f instanceof ImageData||ImageBitmap&&f instanceof ImageBitmap;if(!this.size&&re>0&&me>0){const we=this.useMipmap?Math.floor(Math.log2(Math.max(re,me)))+1:1;z.texStorage2D(z.TEXTURE_2D,we,this.format,re,me),this.size=[re,me]}this.size&&(ye?z.texSubImage2D(z.TEXTURE_2D,0,G,Y,P6e(this.format),I6e(this.format),f):"data"in f&&f.data&&z.texSubImage2D(z.TEXTURE_2D,0,G,Y,S,L,P6e(this.format),I6e(this.format),f.data)),this.useMipmap&&z.generateMipmap(z.TEXTURE_2D)}bind(f,_,S=!1){const{context:L}=this,{gl:O}=L;O.bindTexture(O.TEXTURE_2D,this.texture),f!==this.minFilter&&(O.texParameteri(O.TEXTURE_2D,O.TEXTURE_MAG_FILTER,f),O.texParameteri(O.TEXTURE_2D,O.TEXTURE_MIN_FILTER,this.useMipmap&&!S?f===O.NEAREST?O.NEAREST_MIPMAP_NEAREST:O.LINEAR_MIPMAP_LINEAR:f),this.minFilter=f),_!==this.wrapS&&(O.texParameteri(O.TEXTURE_2D,O.TEXTURE_WRAP_S,_),O.texParameteri(O.TEXTURE_2D,O.TEXTURE_WRAP_T,_),this.wrapS=_)}bindExtraParam(f,_,S,L,O){const{context:z}=this,{gl:G}=z;G.bindTexture(G.TEXTURE_2D,this.texture),_!==this.magFilter&&(G.texParameteri(G.TEXTURE_2D,G.TEXTURE_MAG_FILTER,_),this.magFilter=_),f!==this.minFilter&&(G.texParameteri(G.TEXTURE_2D,G.TEXTURE_MIN_FILTER,this.useMipmap?f===G.NEAREST?G.NEAREST_MIPMAP_NEAREST:G.LINEAR_MIPMAP_LINEAR:f),this.minFilter=f),S!==this.wrapS&&(G.texParameteri(G.TEXTURE_2D,G.TEXTURE_WRAP_S,S),this.wrapS=S),L!==this.wrapT&&(G.texParameteri(G.TEXTURE_2D,G.TEXTURE_WRAP_T,L),this.wrapT=L),O!==this.compareMode&&(O?(G.texParameteri(G.TEXTURE_2D,G.TEXTURE_COMPARE_MODE,G.COMPARE_REF_TO_TEXTURE),G.texParameteri(G.TEXTURE_2D,G.TEXTURE_COMPARE_FUNC,O)):G.texParameteri(G.TEXTURE_2D,G.TEXTURE_COMPARE_MODE,G.NONE),this.compareMode=O)}destroy(){const{gl:f}=this.context;f.deleteTexture(this.texture),this.texture=null}}class uH{constructor(f,_){this.context=f,this.texture=_}bind(f,_){const{context:S}=this,{gl:L}=S;L.bindTexture(L.TEXTURE_2D,this.texture),f!==this.minFilter&&(L.texParameteri(L.TEXTURE_2D,L.TEXTURE_MAG_FILTER,f),L.texParameteri(L.TEXTURE_2D,L.TEXTURE_MIN_FILTER,f),this.minFilter=f),_!==this.wrapS&&(L.texParameteri(L.TEXTURE_2D,L.TEXTURE_WRAP_S,_),L.texParameteri(L.TEXTURE_2D,L.TEXTURE_WRAP_T,_),this.wrapS=_)}}const TYt=zn([{name:"a_pos_3f",components:3,type:"Float32"}]),MYt=zn([{name:"a_color_3f",components:3,type:"Float32"}]),LYt=zn([{name:"a_color_4f",components:4,type:"Float32"}]),PYt=zn([{name:"a_uv_2f",components:2,type:"Float32"}]),IYt=zn([{name:"a_normal_3f",components:3,type:"Float32"}]),DYt=zn([{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"}]),RYt=zn([{name:"a_pbr",components:4,type:"Uint16"},{name:"a_heightBasedEmissiveStrength",components:3,type:"Float32"}]);function JJe(k,f){const _=tse(k.projection,k.zoom,k.width,k.height),S=function(O,z,G,Y,re){const me=new As(G.lng-180*GC,G.lat),ye=new As(G.lng+180*GC,G.lat),we=O.project(me.lng,me.lat),Te=O.project(ye.lng,ye.lat),Ie=-Math.atan2(Te.y-we.y,Te.x-we.x),Ve=ra.fromLngLat(G);Ve.y=pt(Ve.y,-1+GC,1-GC);const Je=Ve.toLngLat(),rt=O.project(Je.lng,Je.lat),xt=ra.fromLngLat(Je);xt.x+=GC;const ut=xt.toLngLat(),St=O.project(ut.lng,ut.lat),Pt=tet(St.x-rt.x,St.y-rt.y,Ie),Rt=ra.fromLngLat(Je);Rt.y+=GC;const ws=Rt.toLngLat(),ns=O.project(ws.lng,ws.lat),xs=tet(ns.x-rt.x,ns.y-rt.y,Ie),us=Math.abs(Pt.x)/Math.abs(xs.y),hs=y([]);P(hs,hs,-Ie*(1-(re?0:Y)));const pn=y([]);return C(pn,pn,[1,1-(1-us)*Y,1]),pn[4]=-xs.x/xs.y*Y,P(pn,pn,Ie),v(pn,hs,pn),pn}(k.projection,0,k.center,_,f),L=eet(k);return C(S,S,[L,L,1]),S}function eet(k){const f=k.projection,_=tse(k.projection,k.zoom,k.width,k.height),S=D6e(f,k.center),L=D6e(f,As.convert(f.center));return Math.pow(2,S*_+(1-_)*L)}function tse(k,f,_,S,L=1/0){const O=k.range;if(!O)return 0;const z=Math.min(L,Math.max(_,S)),G=Math.log2(z/1024);return vt(O[0]+G,O[1]+G,f)}const GC=1/4e4;function D6e(k,f){const _=pt(f.lat,-85.051129,kn),S=new As(f.lng-180*GC,_),L=new As(f.lng+180*GC,_),O=k.project(S.lng,_),z=k.project(L.lng,_),G=ra.fromLngLat(S),Y=ra.fromLngLat(L),re=z.x-O.x,me=z.y-O.y,ye=Y.x-G.x,we=Y.y-G.y,Te=Math.sqrt((ye*ye+we*we)/(re*re+me*me));return Math.log2(Te)}function tet(k,f,_){const S=Math.cos(_),L=Math.sin(_);return{x:k*S-f*L,y:k*L+f*S}}function set(k,f,_){y(k),P(k,k,$n(f[2])),A(k,k,$n(f[0])),T(k,k,$n(f[1])),C(k,k,_),v(k,k,[1,0,0,0,0,0,1,0,0,1,0,0,0,0,0,1])}function sse(k,f,_,S,L,O,z,G){const Y=[_[0]-f[0],_[1]-f[1],0],re=[S[0]-f[0],S[1]-f[1],0];if(K(Y)<1e-12||K(re)<1e-12)return lt(k);const me=ze([],Y,re);Me(me,me),ue(re,S,f),Y[2]=(O-L)*G,re[2]=(z-L)*G;const ye=Y;return ze(ye,Y,re),Me(ye,ye),Ds(k,me,ye)}function nse(k,f,_=!1){const S=u4(f.zoom),L=function(O,z,G){const Y=z.worldSize,re=[O[12],O[13],O[14]],me=mn(re[1]/Y),ye=Ms(re[0]/Y),we=y([]),Te=en(1,me)*Y,Ie=en(1,0)*Y*cr(me,z.zoom),Ve=1/i6e(Y);let Je=Ie*Ve;if(G){const St=tse(z.projection,z.zoom,z.width,z.height,1024);Je=Ve*z.projection.pixelSpaceConversion(z.center.lat,Y,St)}const rt=es(me,ye);ce(rt,rt,he([],Me([],rt),Te*Je*re[2]));const xt=function(St){const Pt=[St[0],St[1],St[2]];let Rt=[0,1,0];const ws=ze([],Rt,Pt);return ze(Rt,Pt,ws),je(Rt)===0&&(Rt=[0,1,0],ze(ws,Pt,Rt)),Me(ws,ws),Me(Rt,Rt),Me(Pt,Pt),[ws[0],ws[1],ws[2],0,Rt[0],Rt[1],Rt[2],0,Pt[0],Pt[1],Pt[2],0,St[0],St[1],St[2],1]}(rt);C(we,we,[Je,Je,Je*Te]),N(we,we,[-re[0],-re[1],-re[2]]);const ut=v([],z.globeMatrix,xt);return v(ut,ut,we),v(ut,ut,O),ut}(k,f,_);if(S>0){const O=function(z,G){const Y=G.worldSize,re=en(1,0)*Y*cr(G.center.lat,G.zoom)/i6e(Y),me=en(1,G.center.lat)*Y,ye=y([]);T(ye,ye,$n(G.center.lng)),A(ye,ye,$n(G.center.lat)),N(ye,ye,[0,0,Vt]),C(ye,ye,[re,re,re*me]);const we=G.point;return N(ye,ye,[-we.x,-we.y,0]),v(ye,ye,z),v(ye,G.globeMatrix,ye)}(k,f);return function(z,G,Y){const re=(Ie,Ve,Je)=>{const rt=K(Ie),xt=K(Ve),ut=d4(Ie,Ve,Je);return he(ut,ut,1/K(ut)*Cs(rt,xt,Je))},me=re([z[0],z[1],z[2]],[G[0],G[1],G[2]],Y),ye=re([z[4],z[5],z[6]],[G[4],G[5],G[6]],Y),we=re([z[8],z[9],z[10]],[G[8],G[9],G[10]],Y),Te=d4([z[12],z[13],z[14]],[G[12],G[13],G[14]],Y);return[me[0],me[1],me[2],0,ye[0],ye[1],ye[2],0,we[0],we[1],we[2],0,Te[0],Te[1],Te[2],1]}(L,O,S)}return L}function R6e(k,f,_,S){const L=ul.projectAabbCorners(S,_);let O=Number.MAX_VALUE;for(let G=0;G0||Je===0&&Ie[0]*Ve[0]+Ie[1]*Ve[1]>=0&&Ie[0]*Ie[0]+Ie[1]*Ie[1]>Ve[0]*Ve[0]+Ve[1]*Ve[1])&&(me=Te)}ye=me}while(ye!==re);return Y.length>0&&Y.push(Y[0]),Y}(L);if(ju(k,z))return O}const kM=64,qF={CoordinateSpaceTile:1,HasMapboxMeshFeatures:4,HasMeshoptCompression:8};function rse(k,f,_,S,L,O,z,G,Y,re=!1){const me=_.zoom,ye=_.project(S),we=cr(S.lat,me),Te=1/we;y(k),N(k,k,[ye.x+z[0]*Te,ye.y+z[1]*Te,z[2]]);let Ie=1,Ve=1;const Je=_.worldSize;if(re){if(_.projection.name==="mercator"){let St=0;_.elevation&&(St=_.elevation.getAtPointOrZero(new ra(ye.x/Je,ye.y/Je),0));const Pt=nt([],[ye.x,ye.y,St,1],_.projMatrix)[3]/_.cameraToCenterDistance;Ie=Pt,Ve=Pt*cr(_.center.lat,me)}else if(_.projection.name==="globe"){const St=nse(k,_),Pt=[0,0,0,1];nt(Pt,Pt,v([],_.projMatrix,St));const Rt=Pt[3]/_.cameraToCenterDistance,ws=u4(me),ns=_.projection.pixelsPerMeter(S.lat,Je)*cr(S.lat,me),xs=_.projection.pixelsPerMeter(_.center.lat,Je)*cr(_.center.lat,me);Ie=Rt/Cs(ns,_r(_.center.lat),ws),Ve=Rt*we/ns,Ie*=xs,Ve*=xs}}else Ie=Te;C(k,k,[Ie,Ie,Ve]);const rt=[...k],xt=f.orientation,ut=[];if(set(ut,[xt[0]+(L?L[0]:0),xt[1]+(L?L[1]:0),xt[2]+(L?L[2]:0)],O),v(k,rt,ut),G&&_.elevation){let St=0;const Pt=[];if(Y&&_.elevation){St=function(ws,ns,xs,us,hs){const pn=ns.elevation;if(!pn)return 0;const bn=ul.projectAabbCorners(xs,us),An=en(1,hs.lat)*ns.worldSize,Ln=function(hr,Gr){const aa=[0,0,1],Da=[{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 _a of Da){const _i=hr[_a.corners[0]],To=hr[_a.corners[1]],wi=hr[_a.corners[2]],Do=[To[0]-_i[0],To[1]-_i[1],Gr*(To[2]-_i[2])],Ui=ze(Do,Do,[wi[0]-_i[0],wi[1]-_i[1],Gr*(wi[2]-_i[2])]);Me(Ui,Ui),_a.dotProductWithUp=De(Ui,aa)}return Da.sort((_a,_i)=>_a.dotProductWithUp-_i.dotProductWithUp),Da[0].corners}(bn,An),En=bn[Ln[0]],Jn=bn[Ln[1]],un=bn[Ln[2]],Mn=bn[Ln[3]],Rn=pn.getAtPointOrZero(new ra(En[0]/ns.worldSize,En[1]/ns.worldSize),0),er=pn.getAtPointOrZero(new ra(Jn[0]/ns.worldSize,Jn[1]/ns.worldSize),0),ur=pn.getAtPointOrZero(new ra(un[0]/ns.worldSize,un[1]/ns.worldSize),0),Zr=pn.getAtPointOrZero(new ra(Mn[0]/ns.worldSize,Mn[1]/ns.worldSize),0),Nr=(Rn+Zr)/2,wr=(er+ur)/2;return Nr>wr?er=f.gl.NEAREST_MIPMAP_NEAREST}),k.uploaded=!0,k.image=null)}function OYt(k,f,_){k.indexBuffer=f.createIndexBuffer(k.indexArray,!1,!0),k.vertexBuffer=f.createVertexBuffer(k.vertexArray,TYt.members,!1,!0),k.normalArray&&(k.normalBuffer=f.createVertexBuffer(k.normalArray,IYt.members,!1,!0)),k.texcoordArray&&(k.texcoordBuffer=f.createVertexBuffer(k.texcoordArray,PYt.members,!1,!0)),k.colorArray&&(k.colorBuffer=f.createVertexBuffer(k.colorArray,(k.colorArray.bytesPerElement===12?MYt:LYt).members,!1,!0)),k.featureArray&&(k.pbrBuffer=f.createVertexBuffer(k.featureArray,RYt.members,!0)),k.segments=sc.simpleSegment(0,0,k.vertexArray.length,k.indexArray.length);const S=k.material;S.pbrMetallicRoughness.baseColorTexture&&hH(S.pbrMetallicRoughness.baseColorTexture,f),S.pbrMetallicRoughness.metallicRoughnessTexture&&hH(S.pbrMetallicRoughness.metallicRoughnessTexture,f),S.normalTexture&&hH(S.normalTexture,f),S.occlusionTexture&&hH(S.occlusionTexture,f,_),S.emissionTexture&&hH(S.emissionTexture,f)}function O6e(k,f,_){if(k.meshes)for(const S of k.meshes)OYt(S,f,_);if(k.children)for(const S of k.children)O6e(S,f,_)}function ase(k){if(k.meshes)for(const f of k.meshes)f.indexArray.destroy(),f.vertexArray.destroy(),f.colorArray&&f.colorArray.destroy(),f.normalArray&&f.normalArray.destroy(),f.texcoordArray&&f.texcoordArray.destroy(),f.featureArray&&f.featureArray.destroy();if(k.children)for(const f of k.children)ase(f)}function FYt(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 F6e(k){if(k.meshes)for(const f of k.meshes)f.vertexBuffer&&(f.vertexBuffer.destroy(),f.indexBuffer.destroy(),f.normalBuffer&&f.normalBuffer.destroy(),f.texcoordBuffer&&f.texcoordBuffer.destroy(),f.colorBuffer&&f.colorBuffer.destroy(),f.pbrBuffer&&f.pbrBuffer.destroy(),f.segments.destroy(),f.material&&FYt(f.material));if(k.footprintDebugMesh&&(k.footprintDebugMesh.vertexBuffer.destroy(),k.footprintDebugMesh.indexBuffer.destroy(),k.footprintDebugMesh.segments.destroy()),k.children)for(const f of k.children)F6e(f)}function SM(k,f){const _=k.json.bufferViews[f.bufferView],S=Jte[f.componentType];return new S(k.buffers[_.buffer],(f.byteOffset||0)+(_.byteOffset||0),f.count*(_.byteStride&&_.byteStride!==dH[f.type]*S.BYTES_PER_ELEMENT?_.byteStride/S.BYTES_PER_ELEMENT:dH[f.type]))}function z6e(k,f,_,S){const L=Jte[f.componentType],O=function(me){switch(me){case Int8Array:return 1/127;case Uint8Array:return 1/255;case Int16Array:return 1/32767;case Uint16Array:return 1/65535;default:return 1}}(L),z=k.json.bufferViews[f.bufferView],G=z.byteStride?z.byteStride/L.BYTES_PER_ELEMENT:dH[f.type],Y=_.float32,re=Y.length/_.capacity;for(let me=0,ye=0;me0){for(let Je=0;Je0){O.texcoordArray=new i4;const we=f.json.accessors[L.TEXCOORD_0];O.texcoordArray.resize(we.count);const Te=SM(f,we);z6e(f,we,O.texcoordArray,Te)}if(L._FEATURE_ID_RGBA4444!==void 0){const we=f.json.accessors[L._FEATURE_ID_RGBA4444];f.json.extensionsUsed&&f.json.extensionsUsed.includes("EXT_meshopt_compression")&&(O.featureData=SM(f,we))}L._FEATURE_RGBA4444!==void 0&&(O.featureData=new Uint32Array(SM(f,f.json.accessors[L._FEATURE_RGBA4444]).buffer));const ye=k.material;return O.material=function(we,Te){const{emissiveFactor:Ie=[0,0,0],alphaMode:Ve="OPAQUE",alphaCutoff:Je=.5,normalTexture:rt,occlusionTexture:xt,emissiveTexture:ut,doubleSided:St,name:Pt}=we,{baseColorFactor:Rt=[1,1,1,1],metallicFactor:ws=1,roughnessFactor:ns=1,baseColorTexture:xs,metallicRoughnessTexture:us}=we.pbrMetallicRoughness||{},hs=xt?Te[xt.index]:void 0;if(xt&&xt.extensions&&xt.extensions.KHR_texture_transform&&hs){const pn=xt.extensions.KHR_texture_transform;hs.offsetScale=[pn.offset[0],pn.offset[1],pn.scale[0],pn.scale[1]]}return{name:Pt,pbrMetallicRoughness:{baseColorFactor:new Ys(...Rt),metallicFactor:ws,roughnessFactor:ns,baseColorTexture:xs?Te[xs.index]:void 0,metallicRoughnessTexture:us?Te[us.index]:void 0},doubleSided:St,emissiveFactor:new Ys(...Ie),alphaMode:Ve,alphaCutoff:Je,normalTexture:rt?Te[rt.index]:void 0,occlusionTexture:hs,emissionTexture:ut?Te[ut.index]:void 0,defined:we.defined===void 0}}(ye!==void 0?f.json.materials[ye]:{defined:!1},_),O}function ret(k,f,_){const{matrix:S,rotation:L,translation:O,scale:z,mesh:G,extras:Y,children:re,name:me}=k,ye={};if(ye.name=me,ye.localMatrix=S||function(we,Te,Ie,Ve){var Je=Te[0],rt=Te[1],xt=Te[2],ut=Te[3],St=Je+Je,Pt=rt+rt,Rt=xt+xt,ws=Je*St,ns=Je*Pt,xs=Je*Rt,us=rt*Pt,hs=rt*Rt,pn=xt*Rt,bn=ut*St,An=ut*Pt,Ln=ut*Rt,En=Ve[0],Jn=Ve[1],un=Ve[2];return we[0]=(1-(us+pn))*En,we[1]=(ns+Ln)*En,we[2]=(xs-An)*En,we[3]=0,we[4]=(ns-Ln)*Jn,we[5]=(1-(ws+pn))*Jn,we[6]=(hs+bn)*Jn,we[7]=0,we[8]=(xs+An)*un,we[9]=(hs-bn)*un,we[10]=(1-(ws+us))*un,we[11]=0,we[12]=Ie[0],we[13]=Ie[1],we[14]=Ie[2],we[15]=1,we}([],L||[0,0,0,1],O||[0,0,0],z||[1,1,1]),ye.globalMatrix=g(ye.localMatrix),G!==void 0){ye.meshes=_[G];const we=ye.anchor=[0,0];for(const Te of ye.meshes){const{min:Ie,max:Ve}=Te.aabb;we[0]+=Ie[0]+Ve[0],we[1]+=Ie[1]+Ve[1]}we[0]=Math.floor(we[0]/ye.meshes.length/2),we[1]=Math.floor(we[1]/ye.meshes.length/2)}if(Y&&(Y.id&&(ye.id=Y.id),Y.lights&&(ye.lights=function(we){if(!we.length)return[];const Te=function(xt){const ut=atob(xt),St=new Uint8Array(ut.length);for(let Pt=0;Pt1&&S[S.length-1].equals(S[0])&&S.pop();let L=0;for(let z=0;z0&&S.reverse();const O=FF(S.flatMap(z=>[z.x,z.y]),[]);return O.length===0?null:{vertices:S,indices:O}}function UYt(k,f){const _=[],S=[];let L=0;const O=[];for(const z of k){L=_.length;const G=z.vertexArray.float32,Y=z.indexArray.uint16;for(let re=0;re0&&([S[z+1],S[z+2]]=[S[z+2],S[z+1]])}return{vertices:_,indices:S}}function B6e(k){const f=function(Y,re){const me=[],ye=WebGL2RenderingContext;if(Y.json.textures)for(const we of Y.json.textures){const Te={magFilter:ye.LINEAR,minFilter:ye.NEAREST,wrapS:ye.REPEAT,wrapT:ye.REPEAT};we.sampler!==void 0&&Object.assign(Te,Y.json.samplers[we.sampler]),me.push({image:re[we.source],sampler:Te,uploaded:!1})}return me}(k,k.images),_=function(Y,re){const me=[];for(const ye of Y.json.meshes){const we=[];for(const Te of ye.primitives)we.push(zYt(Te,Y,re));me.push(we)}return me}(k,f),{scenes:S,scene:L,nodes:O}=k.json,z=S?S[L||0].nodes:[...O.keys()],G=[];for(const Y of z)G.push(ret(O[Y],k,_));return function(Y,re,me){const ye={},we=new Set;for(let Te=0;Te0){const Te=Array.from(we.values()).sort((Ie,Ve)=>Ie-Ve);for(let Ie=Te.length-1;Ie>=0;Ie--)Y.splice(Te[Ie],1)}}(G,z,k.json.nodes),G}function qYt(k){k.heightmap=new Float32Array(4096),k.heightmap.fill(-1);const f=k.vertexArray.float32,_=k.aabb.min[0]-1,S=k.aabb.min[1]-1,L=kM/(k.aabb.max[0]-_+2),O=kM/(k.aabb.max[1]-S+2);for(let z=0;zk.heightmap[re*kM+Y]&&(k.heightmap[re*kM+Y]=G)}}function aet(k,f,_,S,L){_.reserve(_.length+4*k.length),S.reserve(S.length+10*k.length),L.reserve(L.length+10*k.length);let O=S.length;for(const z of k){const G=Math.min(10,Math.max(4,1.3*z.height))*f,Y=[-z.normal[1],z.normal[0],0],re=Math.min(.29,.1*z.width/z.depth),me=z.width-2*z.depth*f*(re+.01),ye=ve([],z.pos,Y,me/2),we=ve([],z.pos,Y,-me/2),Te=[ye[0],ye[1],ye[2]+z.height],Ie=[we[0],we[1],we[2]+z.height],Ve=ve([],z.normal,Y,re);he(Ve,Ve,G);const Je=ve([],z.normal,Y,-re);he(Je,Je,G),ce(Ve,ye,Ve),ce(Je,we,Je),ye[2]+=.1,we[2]+=.1,S.emplaceBack(Ve[0],Ve[1],Ve[2]),S.emplaceBack(Je[0],Je[1],Je[2]),S.emplaceBack(ye[0],ye[1],ye[2]),S.emplaceBack(we[0],we[1],we[2]),S.emplaceBack(Te[0],Te[1],Te[2]),S.emplaceBack(Ie[0],Ie[1],Ie[2]),S.emplaceBack(ye[0],ye[1],ye[2]),S.emplaceBack(we[0],we[1],we[2]),S.emplaceBack(Ve[0],Ve[1],Ve[2]),S.emplaceBack(Je[0],Je[1],Je[2]);const rt=me/G/2;L.emplaceBack(-rt-re,-1,rt,.8),L.emplaceBack(rt+re,-1,rt,.8),L.emplaceBack(-rt,0,rt,1.3),L.emplaceBack(rt,0,rt,1.3),L.emplaceBack(rt+re,-.8,rt,.7),L.emplaceBack(rt+re,-.8,rt,.7),L.emplaceBack(0,0,rt,1.3),L.emplaceBack(0,0,rt,1.3),L.emplaceBack(rt+re,-1.2,rt,.8),L.emplaceBack(rt+re,-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 VYt(k,f){const _={};_.indexArray=new nu,_.vertexArray=new W1,_.colorArray=new M2,aet(k,f,_.indexArray,_.vertexArray,_.colorArray);const S={defined:!0};S.emissiveFactor=Ys.black;const L={};return L.baseColorFactor=Ys.white,S.pbrMetallicRoughness=L,_.material=S,_.aabb=new ul([1/0,1/0,1/0],[-1/0,-1/0,-1/0]),_}const iet=zn([{name:"a_pos_3f",components:3,type:"Float32"}]),HYt=zn([{name:"a_normal_3",components:3,type:"Int16"}]),GYt=zn([{name:"a_centroid_3",components:3,type:"Int16"}]),oet=zn([{name:"a_part_color_emissive",components:2,type:"Uint16"}]),WYt=zn([{name:"a_faux_facade_color_emissive",components:2,type:"Uint16"}]),KYt=zn([{name:"a_faux_facade_data",components:4,type:"Uint16"}]),YYt=zn([{name:"a_faux_facade_vertical_range",components:2,type:"Uint16"}]),ZYt=zn([{name:"a_bloom_attenuation",components:4,type:"Float32"}]),XYt=zn([{name:"a_flood_light_wall_radius_1i16",components:1,type:"Int16"}]),cet=li.types,ise=32767;function QYt(k,f){const _=lr+f;for(const S of k)for(const L of S)if(L.x<-f||L.x>_||L.y<-f||L.y>_)return!1;return!0}function JYt(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 $6e{constructor(){this.layoutVertexArray=new W1,this.layoutAttenuationArray=new M2,this.layoutColorArray=new K1,this.indexArray=new nu,this.indexArrayForConflation=new nu,this.segmentsBucket=new sc}}class U6e{constructor(f){this.layoutFacadePaintArray=null,this.layoutFacadeDataArray=null,this.layoutFacadeVerticalRangeArray=null,this.segmentsBucket=new sc,this.entranceBloom=new $6e;const _=66560;this.layoutVertexArray=new W1,this.layoutVertexArray.reserve(_),this.layoutNormalArray=new Wo,this.layoutNormalArray.reserve(_),this.layoutCentroidArray=new Wo,this.layoutCentroidArray.reserve(_),this.layoutColorArray=new K1,this.layoutColorArray.reserve(_),this.layoutFloodLightDataArray=new LF,this.layoutFloodLightDataArray.reserve(_),this.layoutAOArray=new PF,this.layoutAOArray.reserve(_),this.indexArray=new nu,this.indexArray.reserve(66560),this.indexArrayForConflation=new nu,this.segmentsBucket=new sc,this.entranceBloom=new $6e,f&&(this.layoutFacadePaintArray=new K1,this.layoutFacadeDataArray=new zC,this.layoutFacadeVerticalRangeArray=new K1)}reserve(f,_,S){this.layoutVertexArray.reserveForAdditional(f),this.layoutCentroidArray.reserveForAdditional(f),this.layoutFloodLightDataArray.reserveForAdditional(f),this.layoutNormalArray.reserveForAdditional(f),this.layoutAOArray.reserveForAdditional(f),this.layoutColorArray.reserveForAdditional(f),this.indexArray.reserveForAdditional(_),S&&(this.layoutFacadePaintArray.reserveForAdditional(f),this.layoutFacadeDataArray.reserveForAdditional(f),this.layoutFacadeVerticalRangeArray.reserveForAdditional(f))}}class det{constructor(f){this.colorBufferUploaded=!1,this.maxHeight=0,this.replacementUpdateTime=0,this.activeReplacements=[],this.footprints=[],this.footprintsVertices=new i4,this.footprintsIndices=new o4,this.footprintsMin=new Xt(1/0,1/0),this.footprintsMax=new Xt(-1/0,-1/0),this.featuresOnBorder=[],this.buildingWithoutFacade=new U6e(!1),this.buildingWithFacade=new U6e(!0),this.indexArrayForConflationUploaded=!1,this.featureFootprintLookup=new Map,this.buildingIds=new Set,this.footprintLookup={},this.zoom=f.zoom,this.canonical=f.canonical,this.layers=f.layers,this.layerIds=this.layers.map(_=>_.fqid),this.index=f.index,this.hasPattern=!1,this.worldview=f.worldview,this.lut=f.lut,this.programConfigurations=new tt(f.layers,{zoom:f.zoom,lut:f.lut}),this.stateDependentLayerIds=this.layers.filter(_=>_.isStateDependent()).map(_=>_.id),this.projection=f.projection,this.groundEffect=new A6e(f),this.groundEffect.groundRadiusArray=new xl,this.hasAppearances=null}updateFootprints(f,_){const S=new qte([],[],1),L={vertices:[],indices:new Uint32Array(0),grid:S,min:this.footprintsMin,max:this.footprintsMax,buildingIds:this.buildingIds};_.push({footprint:L,id:f})}updateAppearances(f,_,S,L){return{hasLayoutChanges:!1,hasUboChanges:!1}}prepare(){return function(){if(Qte!=null||zJe!=null)return null;if(UF!=null)return UF;const f=fetch(ca());return UF=function(_){let S,L,O,z,G;function Y(){S=new Uint8Array(G.buffer),L=new Int16Array(G.buffer),O=new Int32Array(G.buffer),z=new Float32Array(G.buffer)}function re(){throw new Error("Unexpected BuildingGen error.")}const me=()=>{},ye={a:{a:re,f:function(we){const Te=S.length,Ie=Math.max(we>>>0,Math.ceil(1.2*Te)),Ve=Math.ceil((Ie-Te)/65536);try{return G.grow(Ve),Y(),!0}catch{return!1}},g:re,b:me,c:me,d:me,e:me}};return(WebAssembly.instantiateStreaming?WebAssembly.instantiateStreaming(_,ye):_.then(we=>we.arrayBuffer()).then(we=>WebAssembly.instantiate(we,ye))).then(we=>{const Te=we.instance.exports;return(0,Te.g)(),G=Te.f,Y(),new jYt({setStyle:Te.h,setAOOptions:Te.i,setMetricOptions:Te.j,setStructuralOptions:Te.k,setFacadeOptions:Te.l,setFauxFacadeOptions:Te.m,setFacadeClassifierOptions:Te.n,addFeature:Te.o,addFacade:Te.p,generateMesh:Te.q,getLastError:Te.r,getOuterRingLength:Te.s,getMeshCount:Te.t,getPositionsPtr:Te.u,getPositionsLength:Te.v,getNormalsPtr:Te.w,getNormalsLength:Te.x,getAOPtr:Te.y,getAOLength:Te.z,getUVPtr:Te.A,getUVLength:Te.B,getFauxFacadePtr:Te.C,getFauxFacadeLength:Te.D,getIndicesPtr:Te.E,getIndicesLength:Te.F,getBuildingPart:Te.G,getRingCount:Te.H,getRingPtr:Te.I,getRingLength:Te.J,malloc:Te.K,free:Te.L,heapU8:S,heap16:L,heap32:O,heapF32:z})})}(f).then(_=>(UF=null,Qte=_,Qte)).catch(_=>{Or("Could not load building-gen"),UF=null,zJe=_ instanceof Error?_:new Error("Unknown error")}),UF}()}populate(f,_,S,L){const O=NYt();if(!O)return;const z=Bn(S);this.tileToMeter=z,this.brightness=_.brightness,O.setStyle({normalScale:[1,-1,z],tileToMeters:z}),O.setAOOptions(!1,.3),O.setMetricOptions(!1,16),O.setStructuralOptions(!0),O.setFacadeClassifierOptions(3);const G=new Map,Y=new Map;let re=0;for(const{feature:rt}of f){if(cet[rt.type]!=="LineString"){G.set(rt.id,rt.properties.source_id);continue}const xt=this.layers[0]._featureFilter.needGeometry;if(xt&&!this.layers[0]._featureFilter.filter(new Si(this.zoom),rt,S))continue;const ut=$i(rt,xt);if(!xt&&!this.layers[0]._featureFilter.filter(new Si(this.zoom),ut,S))continue;const St=xt?ut.geometry:Oa(rt,S,L),Pt=[];for(const xs of St)for(const us of xs)Pt.push(us.x),Pt.push(us.y);const Rt={coordinates:Pt,crossPerc:rt.properties.cross_perc,distanceToRoad:rt.properties.distance_to_road,entrances:rt.properties.entrances,sourceId:0},ws=rt.properties.source_id;let ns=Y.get(ws);ns||(ns=[],Y.set(ws,ns)),ns.push(Rt),++re}this.maxHeight=0;const me=new Array,ye=new Set,we=rt=>{rt!=null&&ye.add(rt)},Te=(rt,xt)=>{rt!=null&&me.push({buildingId:rt,footprintIndex:xt})},Ie=64*(f.length-re),Ve=Ie/2;this.buildingWithFacade.reserve(Ie,Ve,!0),this.buildingWithoutFacade.reserve(2*Ie,2*Ve,!1),this.footprintsIndices.reserve(16*(f.length-re)),this.footprintsVertices.reserve(8*(f.length-re));for(const{feature:rt,id:xt,index:ut,sourceLayerIndex:St}of f){if(cet[rt.type]==="LineString")continue;const Pt=this.layers[0]._featureFilter.needGeometry;if(Pt&&!this.layers[0]._featureFilter.filter(new Si(this.zoom),rt,S))continue;let Rt=null;if(rt.properties&&rt.properties.hasOwnProperty("building_id")&&(Rt=Number(rt.properties.building_id),ye.has(Rt)))continue;const ws=$i(rt,Pt);if(!Pt&&!this.layers[0]._featureFilter.filter(new Si(this.zoom),ws,S))continue;const ns=Pt?ws.geometry:Oa(rt,S,L),xs=tH(ns,500);let us=!1;for(const no of xs)if(no.length!==1){us=!0;break}if(us){we(Rt);continue}if(!QYt(ns,163)){we(Rt);continue}const hs=this.layers[0],pn=JYt(hs.layout.get("building-roof-shape").evaluate(rt,{},S)),bn=hs.layout.get("building-base").evaluate(rt,{},S),An=hs.layout.get("building-height").evaluate(rt,{},S),Ln=hs.layout.get("building-flood-light-ground-radius").evaluate(rt,{},S),En=hs.paint.get("building-ambient-occlusion-intensity"),Jn=Ln/this.tileToMeter;rt.properties["building-part"]="roof";const un=hs.paint.get("building-color").evaluate(rt,{},this.canonical).toPremultipliedRenderColor(this.lut),Mn=hs.paint.get("building-emissive-strength").evaluate(rt,{},this.canonical);rt.properties["building-part"]="wall";const Rn=hs.paint.get("building-color").evaluate(rt,{},this.canonical).toPremultipliedRenderColor(this.lut),er=hs.paint.get("building-emissive-strength").evaluate(rt,{},this.canonical);rt.properties["building-part"]="window";const ur=hs.paint.get("building-color").evaluate(rt,{},this.canonical).toPremultipliedRenderColor(this.lut),Zr=hs.paint.get("building-emissive-strength").evaluate(rt,{},this.canonical);rt.properties["building-part"]="door";const Nr=hs.paint.get("building-color").evaluate(rt,{},this.canonical).toPremultipliedRenderColor(this.lut),wr=hs.paint.get("building-emissive-strength").evaluate(rt,{},this.canonical);let hr=hs.layout.get("building-flood-light-wall-radius").evaluate(rt,{},S);hr=pt(hr,0,2048);const Gr=hr/2048*ise,aa=G.get(xt),Da=Y.get(aa)||[],_a=Da.length!==0&&hs.layout.get("building-facade").evaluate(rt,{},S);O.setFacadeOptions(4,!0),O.setFauxFacadeOptions(_a,!1,1);let _i=0,To=0,wi=0,Do=0,Ui=0,Od=0,ll=0,$o=0,ac=0,kd=0,$m=0;if(_a){let no=Math.round(hs.layout.get("building-facade-floors").evaluate(rt,{},S));if(bn===0){no=Math.max(1,no-(Da.length>0?1:0));let iu=4;if(An>100){const mm=[10,13,15];iu=mm[rt.id?rt.id%mm.length:0]}else An<=10&&(iu=3);O.setFacadeOptions(iu,!0),Ui=(An<15?1.3:1.61803)*iu/z}else Ui=bn/z;Od=An/z,Ui=Math.min(Ui,Od),wi=hs.layout.get("building-facade-unit-width").evaluate(rt,{},S)/z,Do=(Od-Ui)/no,O.setFauxFacadeOptions(!0,!0,wi);const _p=hs.layout.get("building-facade-window").evaluate(rt,{},S);_i=_p[0],To=_p[1],ll=Math.floor(65535*Math.min(1,Ui/lr)),$o=Math.floor(65535*Math.min(1,Od/lr)),ac=Math.floor(255*_i)<<8|Math.floor(255*To),kd=Math.floor(65535*Math.min(1,wi/lr)),$m=Math.floor(65535*Math.min(1,Do/lr))}const Sd=Array(xs.length),ru={x:1/0,y:1/0},sh={x:-1/0,y:-1/0},au={x:0,y:0};let qf=0;for(let no=0;no0){const iu=[],mm=Array(_p.length+1);mm[0]=0;for(let u_=0;u_<_p.length;u_++){const zv=_p[u_];for(let Bv=0;Bvlr||ru.y<0||sh.y>lr)&&this.featuresOnBorder.push({featureId:rt.id,footprintIndex:this.footprints.length});{const no=FF(g4,null,2);this.footprintsIndices.resize(this.footprintsIndices.length+no.length),this.footprintsIndices.uint16.set(no,s7),this.buildingIds.add(Rt??rt.id),this.footprintsMin.x=Math.min(this.footprintsMin.x,c_.x),this.footprintsMin.y=Math.min(this.footprintsMin.y,c_.y),this.footprintsMax.x=Math.max(this.footprintsMax.x,d_.x),this.footprintsMax.y=Math.max(this.footprintsMax.y,d_.y);const _p={footprintVertexOffset:x4,footprintVertexLength:this.footprintsVertices.length-x4,footprintIndexOffset:s7,footprintIndexLength:this.footprintsIndices.length-s7,min:c_,max:d_,hiddenFlags:0,indicesOffset:Dse,indicesLength:LMe,bloomIndicesOffset:Vf,bloomIndicesLength:Fd,groundEffectVertexOffset:PM,groundEffectVertexLength:n7,hasFauxFacade:_a,height:t7,promoteId:xt,feature:ws,parts:vp,buildingBloom:Yg},iu=this.footprints.length;rt.id!==void 0&&this.featureFootprintLookup.set(rt.id,iu),Te(Rt,iu),this.footprints.push(_p)}this.programConfigurations.populatePaintArrays(Xi.layoutVertexArray.length,rt,ut,{},_.availableImages,S,_.brightness),this.groundEffect.addPaintPropertiesData(rt,ut,{},_.availableImages,S,_.brightness),_.featureIndex.insert(rt,ns,ut,St,this.index,Xx)}me.forEach(({buildingId:rt,footprintIndex:xt})=>{ye.has(rt)&&(this.footprints[xt].hiddenFlags|=4)});const Je=new Set;this.buildingIds.forEach((rt,xt,ut)=>{ye.has(rt)||Je.add(rt)}),this.buildingIds=Je,this.groundEffect.prepareBorderSegments()}update(f,_,S,L,O,z,G){this.programConfigurations.updatePaintArrays(f,_,O,S,L,z,G),this.groundEffect.update(f,_,O,S,L,z,G),this.evaluate(this.layers[0],f),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(f){const _=S=>{S.layoutVertexBuffer=f.createVertexBuffer(S.layoutVertexArray,iet.members),S.layoutNormalBuffer=f.createVertexBuffer(S.layoutNormalArray,HYt.members),S.layoutCentroidBuffer=f.createVertexBuffer(S.layoutCentroidArray,GYt.members),S.layoutFloodLightDataBuffer=f.createVertexBuffer(S.layoutFloodLightDataArray,XYt.members),S.layoutFacadeDataArray&&S.layoutFacadeDataArray.length&&(S.layoutFacadeDataBuffer=f.createVertexBuffer(S.layoutFacadeDataArray,KYt.members)),S.layoutFacadeVerticalRangeArray&&S.layoutFacadeVerticalRangeArray.length&&(S.layoutFacadeVerticalRangeBuffer=f.createVertexBuffer(S.layoutFacadeVerticalRangeArray,YYt.members)),S.entranceBloom.layoutVertexArray.length&&(S.entranceBloom.layoutVertexBuffer=f.createVertexBuffer(S.entranceBloom.layoutVertexArray,iet.members),S.entranceBloom.layoutAttenuationBuffer=f.createVertexBuffer(S.entranceBloom.layoutAttenuationArray,ZYt.members)),this.uploadUpdatedColorBuffer(f),this.uploadUpdatedIndexBuffer(f)};this.uploaded||(_(this.buildingWithoutFacade),_(this.buildingWithFacade),this.groundEffect.upload(f)),this.groundEffect.uploadPaintProperties(f),this.programConfigurations.upload(f),this.uploaded=!0}destroy(){const f=_=>{_.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()))};f(this.buildingWithoutFacade),f(this.buildingWithFacade),this.groundEffect.destroy(),this.programConfigurations.destroy()}updateFootprintHiddenFlags(f,_,S=!0){let L=!1;const O=S?_:0,z=0|(S?-1:~_);this.groundEffect.hiddenByLandmarkVertexArray.length===0&&this.groundEffect.hiddenByLandmarkVertexArray.resize(this.groundEffect.vertexArray.length);for(const G of f){const Y=this.footprints[G],re=Y.hiddenFlags&z|O;Y.hiddenFlags!==re&&(Y.hiddenFlags=re,L=!0,this.groundEffect.updateHiddenByLandmarkRange(Y.groundEffectVertexOffset,Y.groundEffectVertexLength,Y.hiddenFlags!==0))}return L&&(this.indexArrayForConflationUploaded=!1),L}uploadUpdatedIndexBuffer(f){if(this.groundEffect.uploadHiddenByLandmark(f),this.indexArrayForConflationUploaded)return;const _=L=>{L.indexArray.length!==0&&(L.indexArrayForConflation.resize(L.indexArray.length),L.indexArrayForConflation.uint16.set(L.indexArray.uint16),L.entranceBloom.indexArrayForConflation.resize(L.entranceBloom.indexArray.length),L.entranceBloom.indexArrayForConflation.uint16.set(L.entranceBloom.indexArray.uint16))};_(this.buildingWithoutFacade),_(this.buildingWithFacade);for(const L of this.footprints){const O=L.hasFauxFacade?this.buildingWithFacade:this.buildingWithoutFacade,z=L.indicesOffset+L.indicesLength;if(L.hiddenFlags!==0){for(let Y=L.indicesOffset;Y{L.indexArray.length!==0&&(L.indexBuffer?L.indexBuffer.updateData(L.indexArrayForConflation):L.indexBuffer=f.createIndexBuffer(L.indexArrayForConflation,!0),L.entranceBloom.indexBuffer?L.entranceBloom.indexBuffer.updateData(L.entranceBloom.indexArrayForConflation):L.entranceBloom.indexBuffer=f.createIndexBuffer(L.entranceBloom.indexArrayForConflation,!0))};S(this.buildingWithoutFacade),S(this.buildingWithFacade),this.indexArrayForConflationUploaded=!0}uploadUpdatedColorBuffer(f){const _=S=>{S.layoutColorBuffer?S.layoutColorBuffer.updateData(S.layoutColorArray):S.layoutColorBuffer=f.createVertexBuffer(S.layoutColorArray,oet.members,!0),S.layoutFacadePaintArray&&(S.layoutFacadePaintBuffer?S.layoutFacadePaintBuffer.updateData(S.layoutFacadePaintArray):S.layoutFacadePaintBuffer=f.createVertexBuffer(S.layoutFacadePaintArray,WYt.members,!0)),S.entranceBloom.layoutColorBuffer?S.entranceBloom.layoutColorBuffer.updateData(S.entranceBloom.layoutColorArray):S.entranceBloom.layoutColorBuffer=f.createVertexBuffer(S.entranceBloom.layoutColorArray,oet.members,!0)};_(this.buildingWithoutFacade),_(this.buildingWithFacade),this.colorBufferUploaded=!0}evaluate(f,_){const S=f.paint.get("building-ambient-occlusion-intensity");for(const L of this.footprints){if(4&L.hiddenFlags)continue;const O=_[L.promoteId],z=L.feature;z.properties["building-part"]="roof";const G=f.paint.get("building-color").evaluate(z,O,this.canonical).toPremultipliedRenderColor(this.lut),Y=f.paint.get("building-emissive-strength").evaluate(z,O,this.canonical);z.properties["building-part"]="wall";const re=f.paint.get("building-color").evaluate(z,O,this.canonical).toPremultipliedRenderColor(this.lut),me=f.paint.get("building-emissive-strength").evaluate(z,O,this.canonical);z.properties["building-part"]="window";const ye=f.paint.get("building-color").evaluate(z,O,this.canonical).toPremultipliedRenderColor(this.lut),we=f.paint.get("building-emissive-strength").evaluate(z,O,this.canonical);z.properties["building-part"]="door";const Te=f.paint.get("building-color").evaluate(z,O,this.canonical).toPremultipliedRenderColor(this.lut),Ie=f.paint.get("building-emissive-strength").evaluate(z,O,this.canonical),Ve=L.hasFauxFacade?this.buildingWithFacade:this.buildingWithoutFacade;for(const rt of L.parts){let xt,ut=G;rt.part===1?(ut=G,xt=Y):rt.part===0?(ut=re,xt=me):rt.part===2?(ut=ye,xt=we):rt.part===3&&(ut=Te,xt=Ie),xt=pt(xt,0,1);for(let St=0;Stz.max.x||Y.max.xz.max.y||Y.max.yG.max.x||G.min.x>f||_>G.max.y||G.min.y>_||G.height<=S||eZt(z,this.footprintsVertices.float32.subarray(2*G.footprintVertexOffset,2*(G.footprintVertexOffset+G.footprintVertexLength)),this.footprintsIndices.uint16.subarray(G.footprintIndexOffset,G.footprintIndexOffset+G.footprintIndexLength))&&(S=G.height,this.footprintLookup[O]=G,L=G.hiddenFlags!==0);if(S!==Number.NEGATIVE_INFINITY)return{height:S,hidden:L};this.footprintLookup[O]=void 0}}function eZt(k,f,_){for(let S=0;S<_.length;S+=3){const L=_[S],O=_[S+1],z=_[S+2],G=f[2*L+0],Y=f[2*L+1],re=f[2*O+0],me=f[2*O+1],ye=f[2*z+0],we=f[2*z+1],Te=(G-ye)*(k.y-we)-(Y-we)*(k.x-ye),Ie=(re-G)*(k.y-Y)-(me-Y)*(k.x-G);if(Te<0!=Ie<0&&Te!==0&&Ie!==0)continue;const Ve=(ye-re)*(k.y-me)-(we-me)*(k.x-re);if(Ve===0||Ve<0==Te+Ie<=0)return!0}return!1}function tZt(k,f,_,S,L,O){const z=Math.pow(2,S.z-L.z);for(let G=0;G<_;G++){let Y=k.float32[2*(G+f)+0],re=k.float32[2*(G+f)+1];Y=(Y+L.x*lr)*z-S.x*lr,re=(re+L.y*lr)*z-S.y*lr,O.push(new Xt(Y,re))}}let uet,het;br(det,"BuildingBucket",{omit:["layers"]}),br(U6e,"BuildingGeometry"),br($6e,"BuildingBloomGeometry");const sZt=zn([{name:"a_pos_normal",components:2,type:"Int16"},{name:"a_data",components:4,type:"Uint8"},{name:"a_linesofar",components:1,type:"Float32"}],4),nZt=zn([{name:"a_z_offset_width",components:3,type:"Float32"}],4),rZt=zn([{name:"a_elevation_ground_scale",components:1,type:"Float32"}],4),{members:aZt}=sZt,iZt=zn([{name:"a_packed",components:3,type:"Float32"}]),{members:oZt}=iZt,lZt=zn([{name:"a_pattern_data",components:3,type:"Float32"}]),{members:cZt}=lZt;class met{constructor(f,_){this.width=f,this.height=_,this.nextRow=0,this.image=new qC({width:f,height:_}),this.positions={},this.uploaded=!1}getDash(f,_){const S=this.getKey(f,_);return this.positions[S]}trim(){const f=this.width,_=this.height=cs(this.nextRow);this.image.resize({width:f,height:_})}getKey(f,_){return f.join(",")+_}getDashRanges(f,_,S){const L=[];let O=f.length%2==1?-f[f.length-1]*S:0,z=f[0]*S,G=!0;L.push({left:O,right:z,isDash:G,zeroLength:f[0]===0});let Y=f[0];for(let re=1;re1&&(Y=f[++G]);const me=Math.abs(re-Y.left),ye=Math.abs(re-Y.right),we=Math.min(me,ye);let Te;const Ie=O/S*(L+1);if(Y.isDash){const Ve=L-Math.abs(Ie);Te=Math.sqrt(we*we+Ve*Ve)}else Te=L-Math.sqrt(we*we+Ie*Ie);this.image.data[z+re]=Math.max(0,Math.min(255,Te+128))}}}addRegularDash(f,_){for(let Y=f.length-1;Y>=0;--Y){const re=f[Y],me=f[Y+1];re.zeroLength?f.splice(Y,1):me&&me.isDash===re.isDash&&(me.left=re.left,f.splice(Y,1))}const S=f[0],L=f[f.length-1];S.isDash===L.isDash&&(S.left=L.left-this.width,L.right=S.right+this.width);const O=this.width*this.nextRow;let z=0,G=f[z];for(let Y=0;Y1&&(G=f[++z]);const re=Math.abs(Y-G.left),me=Math.abs(Y-G.right),ye=Math.min(re,me);this.image.data[O+Y]=Math.max(0,Math.min(255,(G.isDash?ye:-ye)+_+128))}}addDash(f,_){const S=this.getKey(f,_);if(this.positions[S])return this.positions[S];const L=_==="round",O=L?7:0,z=2*O+1;if(this.nextRow+z>this.height)return Or("LineAtlas out of space"),null;f.length===0&&f.push(1);let G=0;for(let ye=0;ye_.fqid),this.index=f.index,this.projection=f.projection,this.hasPattern=!1,this.hasCrossSlope=!1,this.patternFeatures=[],this.lineClipsArray=[],this.gradients={},this.layers.forEach(_=>{this.gradients[_.id]={}}),this.layoutVertexArray=new uM,this.layoutVertexArray2=new W1,this.patternVertexArray=new W1,this.indexArray=new nu,this.programConfigurations=new tt(f.layers,{zoom:f.zoom,lut:f.lut}),this.segments=new sc,this.maxLineLength=0,this.zOffsetVertexArray=new W1,this.elevationGroundScaleVertexArray=new xl,this.stateDependentLayerIds=this.layers.filter(_=>_.isStateDependent()).map(_=>_.id),this.tessellationStep=f.tessellationStep?f.tessellationStep:128,this.worldview=f.worldview,this.hasAppearances=null}updateFootprints(f,_){}updateAppearances(f,_,S,L){return{hasLayoutChanges:!1,hasUboChanges:!1}}populate(f,_,S,L){this.hasPattern=u6e("line",this.layers,this.pixelRatio,_);const O=this.layers[0].layout.get("line-sort-key");this.tileToMeter=Bn(S);const z=this.layers[0].layout.get("line-elevation-reference");if(z==="hd-road-markup")this.elevationType="road";else{const we=this.layers[0].layout.get("line-z-offset"),Te=we.isConstant()&&!we.constantOr(0);this.elevationType=z!=="sea"&&z!=="ground"&&Te?"none":"offset",this.elevationType==="offset"&&z==="none"&&Or(`line-elevation-reference: ground is used for the layer ${this.layerIds[0]} because non-zero line-z-offset value was found.`),this.isSeaLevelReference=z==="sea"}const G=this.layers[0].layout.get("line-cross-slope");this.hasCrossSlope=this.elevationType==="offset"&&G!==void 0;const Y=[];for(const{feature:we,id:Te,index:Ie,sourceLayerIndex:Ve}of f){const Je=this.layers[0]._featureFilter.needGeometry,rt=$i(we,Je);if(!this.layers[0]._featureFilter.filter(new Si(this.zoom,{worldview:this.worldview,activeFloors:_.activeFloors}),rt,S))continue;const xt=O?O.evaluate(rt,{},S):void 0,ut={id:Te,properties:we.properties,type:we.type,sourceLayerIndex:Ve,index:Ie,geometry:Je?rt.geometry:Oa(we,S,L),patterns:{},sortKey:xt};Y.push(ut)}O&&Y.sort((we,Te)=>we.sortKey-Te.sortKey);const{lineAtlas:re,featureIndex:me}=_,ye=this.addConstantDashes(re);for(const we of Y){const{geometry:Te,index:Ie,sourceLayerIndex:Ve}=we;if(ye&&this.addFeatureDashes(we,re),this.hasPattern){const Je=h6e("line",this.layers,we,this.zoom,this.pixelRatio,_);this.patternFeatures.push(Je)}else this.addFeature(we,Te,Ie,S,re.positions,_.availableImages,_.brightness,_.elevationFeatures);me.insert(f[Ie].feature,Te,Ie,Ve,this.index)}}addConstantDashes(f){let _=!1;for(const S of this.layers){const L=S.paint.get("line-dasharray").value,O=S.layout.get("line-cap").value;if(L.kind!=="constant"||O.kind!=="constant")_=!0;else{const z=O.value,G=L.value;if(!G)continue;f.addDash(G,z)}}return _}addFeatureDashes(f,_){const S=this.zoom;for(const L of this.layers){const O=L.paint.get("line-dasharray").value,z=L.layout.get("line-cap").value;if(O.kind==="constant"&&z.kind==="constant")continue;let G,Y;if(O.kind==="constant"){if(G=O.value,!G)continue}else G=O.evaluate({zoom:S},f);Y=z.kind==="constant"?z.value:z.evaluate({zoom:S},f),_.addDash(G,Y),f.patterns[L.id]=[_.getKey(G,Y)]}}update(f,_,S,L,O,z,G,Y,re){this.programConfigurations.updatePaintArrays(f,_,O,S,L,z,G,re)}addFeatures(f,_,S,L,O,z){for(const G of this.patternFeatures)this.addFeature(G,G.geometry,G.index,_,S,L,z,f.elevationFeatures)}isEmpty(){return this.layoutVertexArray.length===0}uploadPending(){return!this.uploaded||this.programConfigurations.needsUpload}upload(f){this.uploaded||(this.layoutVertexArray2.length!==0&&(this.layoutVertexBuffer2=f.createVertexBuffer(this.layoutVertexArray2,oZt)),this.patternVertexArray.length!==0&&(this.patternVertexBuffer=f.createVertexBuffer(this.patternVertexArray,cZt)),!this.zOffsetVertexBuffer&&this.zOffsetVertexArray.length>0&&(this.zOffsetVertexBuffer=f.createVertexBuffer(this.zOffsetVertexArray,nZt.members,!0)),!this.elevationGroundScaleVertexBuffer&&this.elevationGroundScaleVertexArray.length>0&&(this.elevationGroundScaleVertexBuffer=f.createVertexBuffer(this.elevationGroundScaleVertexArray,rZt.members,!0)),this.layoutVertexBuffer=f.createVertexBuffer(this.layoutVertexArray,aZt),this.indexBuffer=f.createIndexBuffer(this.indexArray)),this.programConfigurations.upload(f),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(f,_){let S,L;if(_&&_>0?(S=`mapbox_clip_start_${_}`,L=`mapbox_clip_end_${_}`):(S="mapbox_clip_start",L="mapbox_clip_end"),f.properties&&f.properties.hasOwnProperty(S)&&f.properties.hasOwnProperty(L))return{start:+f.properties[S],end:+f.properties[L]}}addFeature(f,_,S,L,O,z,G,Y){const re=this.layers[0].layout,me=re.get("line-join").evaluate(f,{}),ye=re.get("line-cap").evaluate(f,{}),we=re.get("line-miter-limit"),Te=re.get("line-round-limit");this.lineClips=this.lineFeatureClips(f),this.lineFeature=f;const Ie=!(!f.properties||!f.properties.hasOwnProperty("mapbox_line_metrics"))&&f.properties.mapbox_line_metrics;this.zOffsetValue=re.get("line-z-offset").value;const Ve=this.layers[0].paint.get("line-width").value;if(Ve.kind!=="constant"&&Ve.isLineProgressConstant===!1&&(this.variableWidthValue=Ve),this.isSeaLevelReference){const Je=re.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(f,_,L,Y,me,ye,we,Te)){const[rt,xt]=this.clipRuntimeLinesToTile(_,1);for(let ut=0;ut0?Pt.parentIndex:null)}this.fillNonElevatedRoadSegment(Je)}}else for(let Je=0;Je<_.length;Je++)this.addLine(_[Je],f,L,me,ye,we,Te,void 0,Ie&&Je>0?Je:null);this.programConfigurations.populatePaintArrays(this.layoutVertexArray.length,f,S,O,z,L,G,void 0,this.worldview)}computeSegNextDir(f,_){return f.nextPoint.sub(_.at(-2)).unit()}computeSegPrevDir(f,_){return _[1].sub(f.prevPoint).unit()}clipLinesToTile(f,_){return Xte(f,-_,-_,lr+_,lr+_)}clipRuntimeLinesToTile(f,_){const S=[];return[Xte(f,-_,-_,lr+_,lr+_,S),S]}addElevatedRoadFeature(f,_,S,L,O,z,G,Y){const re=[],me=cc.getElevationFeature(f,L);if(me){const ye=this.clipLinesToTile(_,1),we=this.prepareElevatedLines(ye,me,S);for(const Te of we)re.push({geometry:Te,elevation:me,elevationTileID:S,segment:{progress:{min:0,max:1},nextDir:void 0,prevDir:void 0}})}if(re.length===0)return!1;for(const ye of re){const we=this.layoutVertexArray.length;this.addLine(ye.geometry,f,S,O,z,G,Y);const Te=new _c(S,ye.elevationTileID);if(ye.elevation)for(let Ie=we;Ie>1,this.layoutVertexArray.int16[6*Ie+1]>>1),Je=Te.pointElevation(Ve,ye.elevation,.05);this.updateHeightRange(Je),this.zOffsetVertexArray.emplaceBack(Je,0,0)}else this.fillNonElevatedRoadSegment(we)}return!0}prepareElevatedLines(f,_,S){if(_.constantHeight!=null)return f;const L=[],O=1/Bn(S);for(const z of f)wYt(z,new Iv(_,O),0,L);return L}fillNonElevatedRoadSegment(f){for(let _=f;_0,we=Y&&Y.progress.max<1;if(this.lineClips){let xs={min:this.lineClips.start,max:this.lineClips.end},us=1;if(Y){const bn=this.lineClips.end-this.lineClips.start;xs=function(An,Ln,En){return{min:Sa(An.min,Ln,En),max:Sa(An.max,Ln,En)}}(Y.progress,{min:0,max:1},xs),bn>0&&(us=(xs.max-xs.min)/bn)}const hs=+_.properties.mapbox_clip_feature_len,pn=+_.properties.mapbox_clip_seg_len;if(Number.isNaN(hs)||Number.isNaN(pn)){for(let An=0;An=2&&f[Ie-1].equals(f[Ie-2]);)Ie--;let Ve=0;for(;Ve0,Mn=this.overscaling<=16?122880/(512*this.overscaling):0;if(us&&hs==="round"){if(Lnz&&(hs="bevel"),hs==="bevel"&&(Ln>2&&(hs="flipbevel"),Ln2*Mn){const ur=rt.sub(rt.sub(xt)._mult(Mn/Rn)._round());this.updateDistance(xt,ur),this.addCurrentVertex(ur,St,0,0,Je,ns),xt=ur}this.updateDistance(xt,rt),bn._mult(Ln),this.addCurrentVertex(rt,bn,0,0,Je,ns);const er=rt.dist(ut);if(er>2*Mn){const ur=rt.add(ut.sub(rt)._mult(Mn/er)._round());this.updateDistance(rt,ur),this.addCurrentVertex(ur,Pt,0,0,Je,ns),rt=ur}}else bn._mult(Ln),this.addCurrentVertex(rt,bn,0,0,Je,ns);else if(hs==="flipbevel"){if(Ln>100)bn=Pt.mult(-1);else{const Rn=Ln*St.add(Pt).mag()/St.sub(Pt).mag();bn._perp()._mult(Rn*(un?-1:1))}this.addCurrentVertex(rt,bn,0,0,Je,ns),this.addCurrentVertex(rt,bn.mult(-1),0,0,Je,ns)}else if(hs==="bevel"||hs==="fakeround"){const Rn=rt.dist(xt);let er=1;if(this.elevationType==="offset"&&hs==="bevel"&&this.currentLineJoinType!=="round"&&!this.patternJoinNone&&ns!=null&&xt&&ut){const Gr=4*Mn;Rn1){this.lineSoFar=f.w;const Ve=(_.x-f.x)/ye,Je=(_.y-f.y)/ye,rt=(_.z-f.z)/ye,xt=(_.w-f.w)/ye,ut=_.x-f.x,St=_.y-f.y,Pt=Math.sqrt(ut*ut+St*St);if(Pt===0)return;const Rt=-St/Pt,ws=ut/Pt,ns=Rt,xs=ws,us=-Rt,hs=-ws;for(let pn=1;pn=0&&this.e2>=0&&(this.indexArray.emplaceBack(this.e1,this.e2,me),Y.primitiveLength++),z?this.e2=me:this.e1=me,re!=null&&this.zOffsetVertexArray.emplaceBack(re.zOffset,re.variableWidth,re.variableWidth),this.elevationGroundScaleValue){const ye=re?re.elevationGroundScale:this.evaluateElevationGroundScale();this.elevationGroundScaleVertexArray.emplaceBack(ye)}}updateScaledDistance(){this.lineClips?(this.scaledDistance=this.distance/this.totalDistance,this.lineSoFar=this.totalFeatureLength*this.lineClips.start+this.distance):this.lineSoFar=this.distance}updateDistance(f,_){this.prevDistance=this.distance,this.distance+=f.dist(_),this.updateScaledDistance()}}function q6e(k,f,_){return k.x_||k.y_}let pet,fet;function xet(k,f,_){return f*(lr/(k.tileSize*Math.pow(2,_-k.tileID.overscaledZ)))}br(ose,"LineBucket",{omit:["layers","patternFeatures","currentVertex","currentVertexIsOutside"]});const get=(k,f,_)=>(1-_)*k+_*f;function yet(k,f){return 1/xet(k,1,f.tileZoom)}function vet(k,f,_,S){return k.translatePosMatrix(S||f.tileID.projMatrix,f,_.paint.get("line-translate"),_.paint.get("line-translate-anchor"))}const bet=k=>{const f=[];_et(k)&&f.push("RENDER_LINE_DASH"),k.paint.get("line-gradient")&&f.push("RENDER_LINE_GRADIENT"),k.paint.get("line-blend-mode")==="multiply"&&f.push("LINE_BLEND_MULTIPLY");const _=k.paint.get("line-trim-offset");_[0]===0&&_[1]===0||f.push("RENDER_LINE_TRIM_OFFSET"),k.paint.get("line-border-width").constantOr(1)!==0&&f.push("RENDER_LINE_BORDER");const S=k.layout.get("line-join").constantOr("miter")==="none",L=!!k.paint.get("line-pattern").constantOr(1);return S&&L&&f.push("LINE_JOIN_NONE"),f};function _et(k){const f=k.paint.get("line-dasharray").value;return f.kind!=="constant"||f.value}let V6e;const wet=()=>V6e||(V6e={layout:pet||(pet=new bc({"line-cap":new ar($s.layout_line["line-cap"]),"line-join":new ar($s.layout_line["line-join"]),"line-miter-limit":new ir($s.layout_line["line-miter-limit"]),"line-round-limit":new ir($s.layout_line["line-round-limit"]),"line-sort-key":new ar($s.layout_line["line-sort-key"]),"line-z-offset":new ar($s.layout_line["line-z-offset"]),"line-elevation-reference":new ir($s.layout_line["line-elevation-reference"]),"line-cross-slope":new ir($s.layout_line["line-cross-slope"]),visibility:new ir($s.layout_line.visibility),"line-width-unit":new ir($s.layout_line["line-width-unit"]),"line-elevation-ground-scale":new ar($s.layout_line["line-elevation-ground-scale"])})),paint:fet||(fet=new bc({"line-opacity":new ar($s.paint_line["line-opacity"]),"line-color":new ar($s.paint_line["line-color"]),"line-translate":new ir($s.paint_line["line-translate"]),"line-translate-anchor":new ir($s.paint_line["line-translate-anchor"]),"line-width":new ar($s.paint_line["line-width"]),"line-gap-width":new ar($s.paint_line["line-gap-width"]),"line-offset":new ar($s.paint_line["line-offset"]),"line-blur":new ar($s.paint_line["line-blur"]),"line-dasharray":new ar($s.paint_line["line-dasharray"]),"line-pattern":new ar($s.paint_line["line-pattern"]),"line-pattern-cross-fade":new ir($s.paint_line["line-pattern-cross-fade"]),"line-gradient":new G0($s.paint_line["line-gradient"]),"line-trim-offset":new ir($s.paint_line["line-trim-offset"]),"line-trim-fade-range":new ir($s.paint_line["line-trim-fade-range"]),"line-trim-color":new ir($s.paint_line["line-trim-color"]),"line-emissive-strength":new ar($s.paint_line["line-emissive-strength"]),"line-border-width":new ar($s.paint_line["line-border-width"]),"line-border-color":new ar($s.paint_line["line-border-color"]),"line-occlusion-opacity":new ir($s.paint_line["line-occlusion-opacity"]),"line-blend-mode":new ir($s.paint_line["line-blend-mode"]),"line-color-use-theme":new ar({type:"string",default:"default","property-type":"data-driven"}),"line-gradient-use-theme":new ar({type:"string",default:"default","property-type":"data-driven"}),"line-trim-color-use-theme":new ar({type:"string",default:"default","property-type":"data-driven"}),"line-border-color-use-theme":new ar({type:"string",default:"default","property-type":"data-driven"})}))},V6e);class mZt extends ar{possiblyEvaluate(f,_){return _=new Si(Math.floor(_.zoom),{now:_.now,fadeDuration:_.fadeDuration,transition:_.transition,worldview:_.worldview}),super.possiblyEvaluate(f,_)}evaluate(f,_,S,L){return _=Object.assign({},_,{zoom:Math.floor(_.zoom)}),super.evaluate(f,_,S,L)}}let mH;function jet(k,f){return f>0?f+2*k:k}const pZt=zn([{name:"a_pos_offset",components:4,type:"Int16"},{name:"a_tex_size",components:4,type:"Uint16"},{name:"a_pixeloffset",components:4,type:"Int16"}],4),fZt=zn([{name:"a_globe_anchor",components:3,type:"Int16"},{name:"a_globe_normal",components:3,type:"Float32"}],4),xZt=zn([{name:"a_projected_pos",components:4,type:"Float32"}],4);zn([{name:"a_fade_opacity",components:1,type:"Uint32"}],4);const gZt=zn([{name:"a_auto_z_offset",components:1,type:"Float32"}],4),yZt=zn([{name:"a_feature_index",components:1,type:"Float32"}],4),vZt=zn([{name:"a_x_axis",components:3,type:"Float32"},{name:"a_y_axis",components:3,type:"Float32"}]),bZt=zn([{name:"a_texb",components:2,type:"Uint16"}]),_Zt=zn([{name:"a_placed",components:2,type:"Uint8"},{name:"a_shift",components:2,type:"Float32"},{name:"a_elevation_from_sea",components:2,type:"Float32"}]),wZt=zn([{name:"a_size_scale",components:1,type:"Float32"},{name:"a_padding",components:2,type:"Float32"},{name:"a_auto_z_offset",components:1,type:"Float32"}]);zn([{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 Net=zn([{name:"a_pos",components:3,type:"Int16"},{name:"a_anchor_pos",components:2,type:"Int16"},{name:"a_extrude",components:2,type:"Int16"}],4),jZt=zn([{name:"a_pos_2f",components:2,type:"Float32"},{name:"a_radius",components:1,type:"Float32"},{name:"a_flags",components:2,type:"Int16"}],4);zn([{name:"triangle",components:3,type:"Uint16"}]),zn([{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"}]),zn([{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"}]),zn([{type:"Float32",name:"offsetX"}]),zn([{type:"Int16",name:"x"},{type:"Int16",name:"y"}]);const H6e=class v2e{constructor(f=null,_=0,S=4096){this.batchIndex=_,this.headerBuffer=null,this.propertiesBuffer=null,this.blockIndicesBuffer=null,this.context=f||null,this.propsDwords=S,this.totalBytes=4*this.propsDwords,this.headerData=new Uint32Array(v2e.HEADER_DWORDS),this.propertiesData=new Float32Array(this.propsDwords),this.blockIndicesData=new Uint32Array(this.propsDwords);for(let L=0;Lf.maxUniformBlockSize)throw new Error(`UBO size ${this.totalBytes} exceeds device limit ${f.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,v2e.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(f){const _=this.headerData;_[0]=f.dataDrivenMask,_[1]=f.zoomDependentMask,_[2]=f.dataDrivenBlockSizeVec4,_[3]=f.offsets[0],_[4]=f.offsets[1],_[5]=f.offsets[2],_[6]=f.offsets[3],_[7]=f.offsets[4],_[8]=f.offsets[5],_[9]=f.offsets[6],_[10]=f.offsets[7],_[11]=f.offsets[8]}writeDataDrivenBlock(f,_,S){const L=4*S.dataDrivenBlockSizeVec4;if(L===0)return;const O=_*L;if(O+L>this.propertiesData.length)throw new Error(`UBO write out of bounds: feature index ${_} exceeds propertiesData capacity`);for(let z=0;z<9;z++)S.dataDrivenMask&1<{if(!G)return;const re=S.getUniformBlockIndex(_,z);re!==S.INVALID_INDEX&&(S.uniformBlockBinding(_,re,Y),S.bindBufferBase(S.UNIFORM_BUFFER,Y,G))},O=3*this.batchIndex;L("SymbolPaintPropertiesHeaderUniform",this.headerBuffer,O),L("SymbolPaintPropertiesUniform",this.propertiesBuffer,O+1),L("SymbolPaintPropertiesIndexUniform",this.blockIndicesBuffer,O+2)}destroy(){if(this.context){const f=this.context.gl;this.headerBuffer&&(f.deleteBuffer(this.headerBuffer),this.headerBuffer=null),this.propertiesBuffer&&(f.deleteBuffer(this.propertiesBuffer),this.propertiesBuffer=null),this.blockIndicesBuffer&&(f.deleteBuffer(this.blockIndicesBuffer),this.blockIndicesBuffer=null)}}};H6e.HEADER_DWORDS=12,H6e.HEADER_BYTES=48;let G6e=H6e;function W6e(k,f,_,S){return[IF(255*k,255*f),IF(255*_,255*S)]}function ket(k,f,_,S,L,O,z,G){return!!k&&(k.kind==="constant"?k.value==="none":k.kind==="composite"||k.kind==="source"?k.evaluate({zoom:0,brightness:O,worldview:G},f,_,L,S,z)==="none":typeof k=="string"&&k==="none")}br(G6e,"SymbolPropertiesUBO",{omit:["headerBuffer","propertiesBuffer","blockIndicesBuffer"]});class K6e{constructor(f,_,S,L,O="",z,G){this.layer=f,this.zoom=_,this.lut=S,this.isText=L,this.propDefs=this._getPropDefs(),this.worldview=O,this.maxUniformBufferBindings=z||24,this.uboSizeDwords=G||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(f,L),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 f=this.isText?"text":"icon";return[{name:`${f}-color`,useThemeName:`${f}-color-use-theme`,isColor:!0},{name:`${f}-halo-color`,useThemeName:`${f}-halo-color-use-theme`,isColor:!0},{name:`${f}-opacity`,useThemeName:null,isColor:!1},{name:`${f}-halo-width`,useThemeName:null,isColor:!1},{name:`${f}-halo-blur`,useThemeName:null,isColor:!1},{name:`${f}-emissive-strength`,useThemeName:null,isColor:!1},{name:`${f}-occlusion-opacity`,useThemeName:null,isColor:!1},{name:"symbol-z-offset",useThemeName:null,isColor:!1},{name:`${f}-translate`,useThemeName:null,isColor:!1,isVec2:!0}]}buildHeader(){const f=this.layer.paint,_=this.propDefs;let S=0,L=0,O=0,z=0;const G=[0,0,0,0,0,0,0,0,0];for(let Y=0;Y<9;Y++){const{name:re,isColor:me,isVec2:ye}=_[Y],we=f.get(re),Te=!(!we||typeof we.isConstant!="function"||we.isConstant()),Ie=this._appearancesHavePaintProperties(re),Ve=Te||Ie,Je=!(!we||!we.value||we.value.kind!=="composite"),rt=this.layer._transitionablePaint._values[re],xt=!Ve&&(rt&&rt.value&&rt.value.expression&&rt.value.expression.kind)==="camera";Ve?(S|=1<_.hasPaintProperty(f):this.isText?_=>_.hasTextPaintProperties():_=>_.hasIconPaintProperties())}_checkIfAllPropertiesAreConstant(f,_){const S=f.paint,L=_?"text":"icon",O=[`${L}-color`,`${L}-halo-color`,`${L}-opacity`,`${L}-halo-width`,`${L}-halo-blur`,`${L}-emissive-strength`,`${L}-occlusion-opacity`,"symbol-z-offset",`${L}-translate`];for(const z of O){const G=S.get(z);if(G&&typeof G=="object"&&"isConstant"in G&&!G.isConstant())return!1}return!this._appearancesHavePaintProperties()}_hashDataDrivenValues(f,_){if(_.dataDrivenMask===0)return"";const S=[];for(let L=0;L<9;L++){if(!(_.dataDrivenMask&1<=Ie){Or(`Too many symbol features: batch ${we} requires binding points up to ${3*we+2}, device limit ${Ie}. 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[we]||(this.ubos[we]=new G6e(G,we,this.uboSizeDwords),this.ubos[we].writeHeader(re)),this.ubos[we].writeDataDrivenBlock(me,Te,re);const Ve={batchIndex:we,localFeatureIndex:Te,vtFeatureIndex:_,featureId:Y};return this.allFeatures.push(Ve),Y!=null&&(this.featureVertexRangesFromId.has(Y)||this.featureVertexRangesFromId.set(Y,[]),this.featureVertexRangesFromId.get(Y).push(Ve)),Te}updateFeatures(f,_,S,L,O,z,G){if(this.layer=_,this.cachedConstantUniforms=null,!this.cachedHeader)return;const Y=this.cachedHeader;for(const re of f){const me=this.featureVertexRangesFromId.get(re);if(!me)continue;const ye=z[re]||{};for(const we of me){if(!S)continue;const Te=S.feature(we.vtFeatureIndex);if(!Te)continue;const Ie={type:Te.type,id:re,properties:Te.properties||{},geometry:[]},Ve=this.activeAppearanceByVtIndex?this.activeAppearanceByVtIndex.get(we.vtFeatureIndex):void 0,Je=this.evaluateAllProperties(Ie,ye,L,O,G,void 0,Ve);this.ubos[we.batchIndex]&&this.ubos[we.batchIndex].writeDataDrivenBlock(Je,we.localFeatureIndex,Y)}}}updateDynamicExpressions(f,_,S,L,O,z){if(this.layer=f,this.cachedConstantUniforms=null,!this.cachedHeader)return;const G=this.cachedHeader;for(const Y of this.allFeatures){if(!_)continue;const re=_.feature(Y.vtFeatureIndex);if(!re)continue;const me=Y.featureId!=null&&O[Y.featureId]||{},ye={type:re.type,id:Y.featureId,properties:re.properties||{},geometry:[]},we=this.activeAppearanceByVtIndex?this.activeAppearanceByVtIndex.get(Y.vtFeatureIndex):void 0,Te=this.evaluateAllProperties(ye,me,S,L,z,void 0,we);this.ubos[Y.batchIndex]&&this.ubos[Y.batchIndex].writeDataDrivenBlock(Te,Y.localFeatureIndex,G)}}updateFeaturePaintForAppearance(f,_,S,L,O,z,G){if(!this.layer||(this.activeAppearanceByVtIndex||(this.activeAppearanceByVtIndex=new Map),this.activeAppearanceByVtIndex.set(f,G||null),!this.cachedHeader))return!1;const Y=this.cachedHeader;if(Y.dataDrivenMask===0)return!1;let re=!1;for(const me of this.allFeatures){if(me.vtFeatureIndex!==f)continue;const ye=this.evaluateAllProperties(_,S,L,O,z,void 0,G);this.ubos[me.batchIndex]&&(this.ubos[me.batchIndex].writeDataDrivenBlock(ye,me.localFeatureIndex,Y),re=!0)}return re}getConstantUniformValues(f,_){const S=this.cachedHeader,L=!(!S||!S.cameraMask);if(this.cachedConstantUniforms&&this.cachedConstantBrightness===_&&(!L||this.cachedConstantRenderZoom===f))return this.cachedConstantUniforms;const O=this.layer.paint,z=this.propDefs,G=L?new Si(f,{brightness:_,worldview:this.worldview}):null,Y={type:1,id:void 0,properties:{},geometry:[]},re=we=>{const Te=z[we],Ie=O.get(Te.name);if(!Ie)return[0,0,0,1];const Ve=Te.useThemeName?O.get(Te.useThemeName):void 0,Je=ket(Ve&&typeof Ve!="string"?Ve.value:void 0,Y,{},[],void 0,_,void 0,this.worldview)?null:this.lut;let rt;rt=S&&S.cameraMask&1<{const Ie=O.get(z[we].name);if(!Ie)return Te;if(S&&S.cameraMask&1<{S.text=function(L,O,z){const G=O.layout.get("text-transform").evaluate(z,{});return G==="uppercase"?L=L.toLocaleUpperCase():G==="lowercase"&&(L=L.toLocaleLowerCase()),Zx.applyArabicShaping&&(L=Zx.applyArabicShaping(L)),L}(S.text,f,_)}),k}const pH={"!":"︕","#":"#",$:"$","%":"%","&":"&","(":"︵",")":"︶","*":"*","+":"+",",":"︐","-":"︲",".":"・","/":"/",":":"︓",";":"︔","<":"︿","=":"=",">":"﹀","?":"︖","@":"@","[":"﹇","\\":"\","]":"﹈","^":"^",_:"︳","`":"`","{":"︷","|":"―","}":"︸","~":"~","¢":"¢","£":"£","¥":"¥","¦":"¦","¬":"¬","¯":" ̄","–":"︲","—":"︱","‘":"﹃","’":"﹄","“":"﹁","”":"﹂","…":"︙","‧":"・","₩":"₩","、":"︑","。":"︒","〈":"︿","〉":"﹀","《":"︽","》":"︾","「":"﹁","」":"﹂","『":"﹃","』":"﹄","【":"︻","】":"︼","〔":"︹","〕":"︺","〖":"︗","〗":"︘","!":"︕","(":"︵",")":"︶",",":"︐","-":"︲",".":"・",":":"︓",";":"︔","<":"︿",">":"﹀","?":"︖","[":"﹇","]":"﹈","_":"︳","{":"︷","|":"―","}":"︸","⦅":"︵","⦆":"︶","。":"︒","「":"﹁","」":"﹂","←":"↑","→":"↓"};function kZt(k){return k==="︶"||k==="﹈"||k==="︸"||k==="﹄"||k==="﹂"||k==="︾"||k==="︼"||k==="︺"||k==="︘"||k==="﹀"||k==="︐"||k==="︓"||k==="︔"||k==="`"||k===" ̄"||k==="︑"||k==="︒"}function SZt(k){return k==="︵"||k==="﹇"||k==="︷"||k==="﹃"||k==="﹁"||k==="︽"||k==="︻"||k==="︹"||k==="︗"||k==="︿"}const Y6e=4294967296,Cet=1/Y6e,Aet=typeof TextDecoder>"u"?null:new TextDecoder("utf-8");let lse=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,f,_=this.length){for(;this.pos<_;){const S=this.readVarint(),L=S>>3,O=this.pos;this.type=7&S,k(L,f,this),this.pos===O&&this.skip(S)}return f}readMessage(k,f){return this.readFields(k,f,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)*Y6e;return this.pos+=8,k}readSFixed64(){const k=this.dataView.getUint32(this.pos,!0)+this.dataView.getInt32(this.pos+4,!0)*Y6e;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 f=this.buf;let _,S;return S=f[this.pos++],_=127&S,S<128?_:(S=f[this.pos++],_|=(127&S)<<7,S<128?_:(S=f[this.pos++],_|=(127&S)<<14,S<128?_:(S=f[this.pos++],_|=(127&S)<<21,S<128?_:(S=f[this.pos],_|=(15&S)<<28,function(L,O,z){const G=z.buf;let Y,re;if(re=G[z.pos++],Y=(112&re)>>4,re<128||(re=G[z.pos++],Y|=(127&re)<<3,re<128)||(re=G[z.pos++],Y|=(127&re)<<10,re<128)||(re=G[z.pos++],Y|=(127&re)<<17,re<128)||(re=G[z.pos++],Y|=(127&re)<<24,re<128)||(re=G[z.pos++],Y|=(1&re)<<31,re<128))return VF(L,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,f=this.pos;return this.pos=k,k-f>=12&&Aet?Aet.decode(this.buf.subarray(f,k)):function(_,S,L){let O="",z=S;for(;z239?4:G>223?3:G>191?2:1;if(z+we>L)break;we===1?G<128&&(ye=G):we===2?(Y=_[z+1],(192&Y)==128&&(ye=(31&G)<<6|63&Y,ye<=127&&(ye=null))):we===3?(Y=_[z+1],re=_[z+2],(192&Y)==128&&(192&re)==128&&(ye=(15&G)<<12|(63&Y)<<6|63&re,(ye<=2047||ye>=55296&&ye<=57343)&&(ye=null))):we===4&&(Y=_[z+1],re=_[z+2],me=_[z+3],(192&Y)==128&&(192&re)==128&&(192&me)==128&&(ye=(15&G)<<18|(63&Y)<<12|(63&re)<<6|63&me,(ye<=65535||ye>=1114112)&&(ye=null))),ye===null?(ye=65533,we=1):ye>65535&&(ye-=65536,O+=String.fromCharCode(ye>>>10&1023|55296),ye=56320|1023&ye),O+=String.fromCharCode(ye),z+=we}return O}(this.buf,f,k)}readBytes(){const k=this.readVarint()+this.pos,f=this.buf.subarray(this.pos,k);return this.pos=k,f}readPackedVarint(k=[],f){const _=this.readPackedEnd();for(;this.pos<_;)k.push(this.readVarint(f));return k}readPackedSVarint(k=[]){const f=this.readPackedEnd();for(;this.pos127;);else if(f===2)this.pos=this.readVarint()+this.pos;else if(f===5)this.pos+=4;else{if(f!==1)throw new Error(`Unimplemented type: ${f}`);this.pos+=8}}writeTag(k,f){this.writeVarint(k<<3|f)}realloc(k){let f=this.length||16;for(;f268435455||k<0?function(f,_){let S,L;if(f>=0?(S=f%4294967296|0,L=f/4294967296|0):(S=~(-f%4294967296),L=~(-f/4294967296),4294967295^S?S=S+1|0:(S=0,L=L+1|0)),f>=18446744073709552e3||f<-18446744073709552e3)throw new Error("Given varint doesn't fit into 10 bytes");_.realloc(10),function(O,z,G){G.buf[G.pos++]=127&O|128,O>>>=7,G.buf[G.pos++]=127&O|128,O>>>=7,G.buf[G.pos++]=127&O|128,O>>>=7,G.buf[G.pos++]=127&O|128,G.buf[G.pos]=127&(O>>>=7)}(S,0,_),function(O,z){const G=(7&O)<<4;z.buf[z.pos++]|=G|((O>>>=3)?128:0),O&&(z.buf[z.pos++]=127&O|((O>>>=7)?128:0),O&&(z.buf[z.pos++]=127&O|((O>>>=7)?128:0),O&&(z.buf[z.pos++]=127&O|((O>>>=7)?128:0),O&&(z.buf[z.pos++]=127&O|((O>>>=7)?128:0),O&&(z.buf[z.pos++]=127&O)))))}(L,_)}(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 f=this.pos;this.pos=function(S,L,O){for(let z,G,Y=0;Y55295&&z<57344){if(!G){z>56319||Y+1===L.length?(S[O++]=239,S[O++]=191,S[O++]=189):G=z;continue}if(z<56320){S[O++]=239,S[O++]=191,S[O++]=189,G=z;continue}z=G-55296<<10|z-56320|65536,G=null}else G&&(S[O++]=239,S[O++]=191,S[O++]=189,G=null);z<128?S[O++]=z:(z<2048?S[O++]=z>>6|192:(z<65536?S[O++]=z>>12|224:(S[O++]=z>>18|240,S[O++]=z>>12&63|128),S[O++]=z>>6&63|128),S[O++]=63&z|128)}return O}(this.buf,k,this.pos);const _=this.pos-f;_>=128&&Eet(f,_,this),this.pos=f-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 f=k.length;this.writeVarint(f),this.realloc(f);for(let _=0;_=128&&Eet(_,S,this),this.pos=_-1,this.writeVarint(S),this.pos+=S}writeMessage(k,f,_){this.writeTag(k,2),this.writeRawMessage(f,_)}writePackedVarint(k,f){f.length&&this.writeMessage(k,CZt,f)}writePackedSVarint(k,f){f.length&&this.writeMessage(k,AZt,f)}writePackedBoolean(k,f){f.length&&this.writeMessage(k,MZt,f)}writePackedFloat(k,f){f.length&&this.writeMessage(k,EZt,f)}writePackedDouble(k,f){f.length&&this.writeMessage(k,TZt,f)}writePackedFixed32(k,f){f.length&&this.writeMessage(k,LZt,f)}writePackedSFixed32(k,f){f.length&&this.writeMessage(k,PZt,f)}writePackedFixed64(k,f){f.length&&this.writeMessage(k,IZt,f)}writePackedSFixed64(k,f){f.length&&this.writeMessage(k,DZt,f)}writeBytesField(k,f){this.writeTag(k,2),this.writeBytes(f)}writeFixed32Field(k,f){this.writeTag(k,5),this.writeFixed32(f)}writeSFixed32Field(k,f){this.writeTag(k,5),this.writeSFixed32(f)}writeFixed64Field(k,f){this.writeTag(k,1),this.writeFixed64(f)}writeSFixed64Field(k,f){this.writeTag(k,1),this.writeSFixed64(f)}writeVarintField(k,f){this.writeTag(k,0),this.writeVarint(f)}writeSVarintField(k,f){this.writeTag(k,0),this.writeSVarint(f)}writeStringField(k,f){this.writeTag(k,2),this.writeString(f)}writeFloatField(k,f){this.writeTag(k,5),this.writeFloat(f)}writeDoubleField(k,f){this.writeTag(k,1),this.writeDouble(f)}writeBooleanField(k,f){this.writeVarintField(k,+f)}};function VF(k,f,_){return _?4294967296*f+(k>>>0):4294967296*(f>>>0)+(k>>>0)}function Eet(k,f,_){const S=f<=16383?1:f<=2097151?2:f<=268435455?3:Math.floor(Math.log(f)/(7*Math.LN2));_.realloc(S);for(let L=_.pos-1;L>=k;L--)_.buf[L+S]=_.buf[L]}function CZt(k,f){for(let _=0;_=0&&S>=f&&cse[this.text.charCodeAt(S)];S--)_--;this.text=this.text.substring(f,_),this.sectionIndex=this.sectionIndex.slice(f,_)}substring(f,_){const S=new HF;return S.text=this.text.substring(f,_),S.sectionIndex=this.sectionIndex.slice(f,_),S.sections=this.sections,S}toString(){return this.text}getMaxScale(){return this.sectionIndex.reduce((f,_)=>Math.max(f,this.sections[_].scale),0)}addTextSection(f,_){this.text+=f.text,this.sections.push(fH.forText(f.scale,f.fontStack||_));const S=this.sections.length-1;for(let L=0;L=63743?null:++this.imageSectionID:(this.imageSectionID=57344,this.imageSectionID)}}function Z6e(k,f,_,S,L,O,z,G,Y,re,me,ye,we,Te,Ie,Ve=1,Je=1){const rt=HF.fromFeature(k,L,Ve,Je);ye===Fv.vertical&&rt.verticalizePunctuation(we);let xt=[];const ut=function(ns,xs,us,hs,pn,bn,An=1){if(!ns)return[];const Ln=[],En=function(Mn,Rn,er,ur,Zr,Nr,wr=1){let hr=0;for(let Gr=0;Gr=0;let un=0;for(let Mn=0;Mn0&&Xx>Ui&&(Ui=Xx)}else{const vp=us[kd.fontStack];if(!vp)continue;vp[Sd]&&(au=vp[Sd]);const Yg=xs[kd.fontStack];if(!Yg)continue;const Vf=Yg.glyphs[Sd];if(!Vf)continue;if(sh=Vf.metrics,Um=Sd!==8203?Bm:0,wr){const Fd=Yg.ascender!==void 0?Math.abs(Yg.ascender):0,Xx=Yg.descender!==void 0?Math.abs(Yg.descender):0,bp=(Fd+Xx)*ru;Od-_/2;){if(z--,z<0)return!1;G-=k[z].dist(O),O=k[z]}G+=k[z].dist(k[z+1]),z++;const Y=[];let re=0;for(;G<_/2;){const me=k[z],ye=k[z+1];if(!ye)return!1;let we=k[z-1].angleTo(me)-me.angleTo(ye);for(we=Math.abs((we+3*Math.PI)%(2*Math.PI)-Math.PI),Y.push({distance:G,angleDelta:we}),re+=we;G-Y[0].distance>S;)re-=Y.shift().angleDelta;if(re>L)return!1;z++,G+=me.dist(ye)}return!0}function zet(k){let f=0;for(let _=0;_re){const Ie=(re-Y)/Te,Ve=Cs(ye.x,we.x,Ie),Je=Cs(ye.y,we.y,Ie),rt=new f4(Ve,Je,0,we.angleTo(ye),me);return!z||Fet(k,rt,G,z,f)?rt:void 0}Y+=Te}}function UZt(k,f,_,S,L,O,z,G,Y){const re=Bet(S,O,z),me=$et(S,L),ye=me*z,we=k[0].x===0||k[0].x===Y||k[0].y===0||k[0].y===Y;return f-ye=0&&St=0&&Pt=0&&we+re<=me){const Rt=new f4(St,Pt,0,xt,Ie);S&&!Fet(k,Rt,O,S,L)||Te.push(Rt)}}ye+=rt}return G||Te.length||z||(Te=Uet(k,ye/2,_,S,L,O,z,!0,Y)),Te}function qet(k){let f=0,_=0;for(const z of k)f+=z.w*z.h,_=Math.max(_,z.w);k.sort((z,G)=>G.h-z.h);const S=[{x:0,y:0,w:Math.max(Math.ceil(Math.sqrt(f/.95)),_),h:1/0}];let L=0,O=0;for(const z of k)for(let G=S.length-1;G>=0;G--){const Y=S[G];if(!(z.w>Y.w||z.h>Y.h)){if(z.x=Y.x,z.y=Y.y,O=Math.max(O,z.y+z.h),L=Math.max(L,z.x+z.w),z.w===Y.w&&z.h===Y.h){const re=S.pop();re&&Gf.id?1:k.versionf.version?1:k.sxf.sx?1:k.syf.sy?1:0}function tMe(k){let f=0;for(let _=0;_0,Vet(f,S,this.iconDescriptors,O),Vet(_,S,this.patternDescriptors,O),this.iconDescriptors.sort(use),this.patternDescriptors.sort(use);let z=0;const G=L?L.data:"";G&&(z=I2(z,tMe(G))),z=I2(z,1);for(const Y of this.iconDescriptors)z=I2(z,tMe(Y.id)),z=I2(z,Y.version),z=I2(z,Y.sx),z=I2(z,Y.sy);z=I2(z,1);for(const Y of this.patternDescriptors)z=I2(z,tMe(Y.id)),z=I2(z,Y.version),z=I2(z,Y.sx),z=I2(z,Y.sy);this.hash=z}subsetOf(f){return this.isSubsetArray(this.iconDescriptors,f.iconDescriptors,use)&&this.isSubsetArray(this.patternDescriptors,f.patternDescriptors,use)}isSubsetArray(f,_,S){let L=0,O=0;if(f.length>_.length)return!1;for(;L{const z=L.variant.id.toString().localeCompare(O.variant.id.toString());return z!==0?z:L.variant.sx!==O.variant.sx?L.variant.sx-O.variant.sx:L.variant.sy!==O.variant.sy?L.variant.sy-O.variant.sy:0});const S=new Map;for(const L of _)S.set(L.key,L.value);return S}class Het{constructor(f){this.sourceAtlasHash=f}}class Get{constructor(f,_,S,L){const O=new Map,z=new Map;this.haveRenderCallbacks=[];const G=[],Y=L!==void 0,re=Y?new Map:void 0,me=Y?rMe(f,re):f,ye=Y?rMe(_,re):_;this.addImages(me,O,1,G),this.addImages(ye,z,2,G);const{w:we,h:Te}=qet(G),Ie=new vx({width:we||1,height:Te||1});for(const[Ve,Je]of me.entries()){const rt=O.get(Ve).paddedRect;vx.copy(Je.data,Ie,{x:0,y:0},{x:rt.x+1,y:rt.y+1},Je.data,null,Je.sdf)}for(const[Ve,Je]of ye.entries()){const rt=z.get(Ve),xt=rt.paddedRect;let ut=rt.padding;const St=xt.x+ut,Pt=xt.y+ut,Rt=Je.data.width,ws=Je.data.height;ut=ut>1?ut-1:ut,vx.copy(Je.data,Ie,{x:0,y:0},{x:St,y:Pt},Je.data,S),vx.copy(Je.data,Ie,{x:0,y:ws-ut},{x:St,y:Pt-ut},{width:Rt,height:ut},S),vx.copy(Je.data,Ie,{x:0,y:0},{x:St,y:Pt+ws},{width:Rt,height:ut},S),vx.copy(Je.data,Ie,{x:Rt-ut,y:0},{x:St-ut,y:Pt},{width:ut,height:ws},S),vx.copy(Je.data,Ie,{x:0,y:0},{x:St+Rt,y:Pt},{width:ut,height:ws},S),vx.copy(Je.data,Ie,{x:Rt-ut,y:ws-ut},{x:St-ut,y:Pt-ut},{width:ut,height:ut},S),vx.copy(Je.data,Ie,{x:0,y:ws-ut},{x:St+Rt,y:Pt-ut},{width:ut,height:ut},S),vx.copy(Je.data,Ie,{x:0,y:0},{x:St+Rt,y:Pt+ws},{width:ut,height:ut},S),vx.copy(Je.data,Ie,{x:Rt-ut,y:0},{x:St-ut,y:Pt+ws},{width:ut,height:ut},S)}this.lut=S,this.image=Ie,this.iconPositions=O,this.patternPositions=z,Y&&(this.contentDescriptor=new sMe(me,ye,L,S,re))}addImages(f,_,S,L){for(const[O,z]of f.entries()){const{bin:G,imagePosition:Y,imageVariant:re}=nMe(O,z,S);_.set(O,Y),L.push(G),z.hasRenderCallback&&this.haveRenderCallbacks.push(re.id)}}patchUpdatedImages(f,_,S,L){this.haveRenderCallbacks=this.haveRenderCallbacks.filter(O=>f.hasImage(O,S)),f.dispatchRenderCallbacks(this.haveRenderCallbacks,S);for(const O of f.getUpdatedImages(S)){for(const z of this.iconPositions.keys()){const G=wd.parse(z);if(Rh.isEqual(G.id,O)){const Y=f.getImage(O,S);this.patchUpdatedImage(this.iconPositions.get(z),Y,_,null)}}for(const z of this.patternPositions.keys()){const G=wd.parse(z);if(Rh.isEqual(G.id,O)){const Y=f.getImage(O,S);this.patchUpdatedImage(this.patternPositions.get(z),Y,_,L||this.lut)}}}}patchUpdatedImage(f,_,S,L=null){if(!f||!_||f.version===_.version)return;f.version=_.version;const[O,z]=f.tl,G=f.sdf;if(this.lut||G){const Y={width:_.data.width,height:_.data.height},re=new vx(Y);vx.copy(_.data,re,{x:0,y:0},{x:0,y:0},Y,L,G),S.update(re,{position:{x:O,y:z},recreateWhenResize:!1})}else S.update(_.data,{position:{x:O,y:z},recreateWhenResize:!1})}}br(xH,"ImagePosition"),br(Get,"ImageAtlas",{omit:["lut"]}),br(Het,"ImageAtlasReference");class gH{constructor(f){this.pendingRequests=new Map,this.cachedRanges=new Map,this.useServerFontComposition=!f||f.useServerFontComposition===void 0||f.useServerFontComposition}loadGlyphRange(f,_,S,L,O){if(this.useServerFontComposition)return void gH.loadGlyphRange(f,_,S,L,O);const z=f.split(",").map(G=>G.trim()).filter(G=>G.length>0);z.length!==0?z.length!==1?this._loadMultipleFonts(z,_,S,L,O):this._loadFont(z[0],_,S,L,O):O(new Error("Empty fontstack"))}_loadMultipleFonts(f,_,S,L,O){const z=f.map(()=>null),G={completed:0,firstError:null,callbackCalled:!1},Y=(re,me,ye)=>{if(!G.callbackCalled&&(me&&!G.firstError&&(G.firstError=me),ye&&(z[re]=ye),G.completed++,G.completed===f.length)){G.callbackCalled=!0;const we=z.filter(Ie=>Ie!==null);if(we.length===0)return void O(G.firstError||new Error("All fonts failed to load"));const Te=this._composeGlyphs(we);O(null,Te)}};for(let re=0;re{Y(re,me,ye)})}_loadFont(f,_,S,L,O){const z=`${f}:${_}`;if(this.cachedRanges.has(z)){const Y=this.cachedRanges.get(z);return void bd.frame(()=>O(null,Y))}const G=this.pendingRequests.get(z);G?G.push(O):(this.pendingRequests.set(z,[O]),gH.loadGlyphRange(f,_,S,L,(Y,re)=>{Y||this.cachedRanges.set(z,re||null);const me=this.pendingRequests.get(z);if(this.pendingRequests.delete(z),me)for(const ye of me)ye(Y,re)}))}_composeGlyphs(f){const _={};let S,L;for(const O of f)if(S===void 0&&O.ascender!==void 0&&(S=O.ascender),L===void 0&&O.descender!==void 0&&(L=O.descender),O.glyphs)for(const z in O.glyphs)_[z]===void 0&&(_[z]=O.glyphs[z]);return{glyphs:_,ascender:S,descender:L}}}gH.loadGlyphRange=function(k,f,_,S,L){const O=256*f,z=O+255,G=S.transformRequest(S.normalizeGlyphsURL(_).replace("{fontstack}",k).replace("{range}",`${O}-${z}`),lp.Glyphs);mh(G,(Y,re)=>{if(Y)L(Y);else if(re){const me={},ye=function(we){return new lse(we).readFields(RZt,{})}(re);for(const we of ye.glyphs)me[we.id]=we;L(null,{glyphs:me,ascender:ye.ascender,descender:ye.descender})}})};const yH=1e20;function Wet(k,f,_,S,L,O,z,G,Y){for(let re=f;re-1);Y++,O[Y]=G,z[Y]=re,z[Y+1]=yH}for(let G=0,Y=0;G{if(z){L.ascender=z.ascender,L.descender=z.descender;for(const G in z.glyphs)this._doesCharSupportLocalGlyph(+G)||(L.glyphs[+G]=z.glyphs[+G]);L.ranges[_]=!0}for(const G of L.requests[_]||[])G(O,z);delete L.requests[_]}))}getGlyphs(f,_){const S=[],L=this.url||Kn.GLYPHS_URL;for(const O in f)for(const z of f[O])S.push({stack:O,id:z});Zt(S,({stack:O,id:z},G)=>{let Y=this.entries[O];Y||(Y=this.entries[O]={glyphs:{},requests:{},ranges:{},ascender:void 0,descender:void 0});let re=Y.glyphs[z];if(re!==void 0)return void G(null,{stack:O,id:z,glyph:re});if(re=this._tinySDF(Y,O,z),re)return Y.glyphs[z]=re,void G(null,{stack:O,id:z,glyph:re});const me=Math.floor(z/256);if(256*me>65535)return Or("glyphs > 65535 not supported"),void G(null,{stack:O,id:z,glyph:re});if(Y.ranges[me])return void G(null,{stack:O,id:z,glyph:re});let ye=Y.requests[me];ye||(ye=Y.requests[me]=[],this.glyphLoader.loadGlyphRange(O,me,L,this.requestManager,(we,Te)=>{if(Te){Y.ascender=Te.ascender,Y.descender=Te.descender;for(const Ie in Te.glyphs)this._doesCharSupportLocalGlyph(+Ie)||(Y.glyphs[+Ie]=Te.glyphs[+Ie]);Y.ranges[me]=!0}for(const Ie of ye)Ie(we,Te);delete Y.requests[me]})),ye.push((we,Te)=>{we?G(we):Te&&G(null,{stack:O,id:z,glyph:Te.glyphs[z]||null})})},(O,z)=>{if(O)_(O);else if(z){const G={};for(const{stack:Y,id:re,glyph:me}of z)G[Y]===void 0&&(G[Y]={}),G[Y].glyphs===void 0&&(G[Y].glyphs={}),G[Y].glyphs[re]=me&&{id:me.id,bitmap:me.bitmap.clone(),metrics:me.metrics},G[Y].ascender=this.entries[Y].ascender,G[Y].descender=this.entries[Y].descender;_(null,G)}})}_doesCharSupportLocalGlyph(f){return this.localGlyphMode!==aMe.none&&(this.localGlyphMode===aMe.all?!!this.localFontFamily:!!this.localFontFamily&&(xx(f)||o_(f)||Ev(f)||Om(f)||$1(f)||Vw(f)||(_=f)>=131072&&_<=173791||(S=>S>=66736&&S<=66815)(f)));var _}_tinySDF(f,_,S){const L=this.localFontFamily;if(!L||!this._doesCharSupportLocalGlyph(S))return;let O=f.tinySDF;if(!O){let Je="400";/bold/i.test(_)?Je="900":/medium/i.test(_)?Je="500":/light/i.test(_)&&(Je="200"),O=f.tinySDF=new hse.TinySDF({fontFamily:L,fontWeight:Je,fontSize:48,buffer:6,radius:16}),O.fontWeight=Je}const z=O.fontWeight;if(this.localGlyphs[z][S])return this.localGlyphs[z][S];const G=String.fromCodePoint(S),{data:Y,width:re,height:me,glyphWidth:ye,glyphHeight:we,glyphLeft:Te,glyphTop:Ie,glyphAdvance:Ve}=O.draw(G);return this.localGlyphs[z][S]={id:S,bitmap:new qC({width:re,height:me},Y),metrics:{width:ye/2,height:we/2,left:Te/2,top:Ie/2-27,advance:Ve/2,localGlyph:!0}}}}function Yet(k,f){return k+f[1]-f[0]}function iMe(k,f,_,S,L=1){const O=[],z=k.imagePrimary,G=z.pixelRatio,Y=z.paddedRect.w-2,re=z.paddedRect.h-2,me=(k.right-k.left)*L,ye=(k.bottom-k.top)*L,we=z.stretchX||[[0,Y]],Te=z.stretchY||[[0,re]],Ie=we.reduce(Yet,0),Ve=Te.reduce(Yet,0),Je=Y-Ie,rt=re-Ve;let xt=0,ut=Ie,St=0,Pt=Ve,Rt=0,ws=Je,ns=0,xs=rt;if(z.content&&S){const hs=z.content;xt=mse(we,0,hs[0]),St=mse(Te,0,hs[1]),ut=mse(we,hs[0],hs[2]),Pt=mse(Te,hs[1],hs[3]),Rt=hs[0]-xt,ns=hs[1]-St,ws=hs[2]-hs[0]-ut,xs=hs[3]-hs[1]-Pt}const us=(hs,pn,bn,An)=>{const Ln=pse(hs.stretch-xt,ut,me,k.left*L),En=fse(hs.fixed-Rt,ws,hs.stretch,Ie),Jn=pse(pn.stretch-St,Pt,ye,k.top*L),un=fse(pn.fixed-ns,xs,pn.stretch,Ve),Mn=pse(bn.stretch-xt,ut,me,k.left*L),Rn=fse(bn.fixed-Rt,ws,bn.stretch,Ie),er=pse(An.stretch-St,Pt,ye,k.top*L),ur=fse(An.fixed-ns,xs,An.stretch,Ve),Zr=new Xt(Ln,Jn),Nr=new Xt(Mn,Jn),wr=new Xt(Mn,er),hr=new Xt(Ln,er),Gr=new Xt(En/G,un/G),aa=new Xt(Rn/G,ur/G),Da=f*Math.PI/180;if(Da){const Ui=Math.sin(Da),Od=Math.cos(Da),ll=[Od,-Ui,Ui,Od];Zr._matMult(ll),Nr._matMult(ll),hr._matMult(ll),wr._matMult(ll)}const _a=hs.stretch+hs.fixed,_i=bn.stretch+bn.fixed,To=pn.stretch+pn.fixed,wi=An.stretch+An.fixed,Do=k.imageSecondary;return{tl:Zr,tr:Nr,bl:hr,br:wr,texPrimary:{x:z.paddedRect.x+1+_a,y:z.paddedRect.y+1+To,w:_i-_a,h:wi-To},texSecondary:Do?{x:Do.paddedRect.x+1+_a,y:Do.paddedRect.y+1+To,w:_i-_a,h:wi-To}:void 0,writingMode:void 0,glyphOffset:[0,0],sectionIndex:0,pixelOffsetTL:Gr,pixelOffsetBR:aa,minFontScaleX:ws/G/me,minFontScaleY:xs/G/ye,isSDF:_}};if(z.stretchX||z.stretchY){const hs=Zet(we,Je,Ie),pn=Zet(Te,rt,Ve);for(let bn=0;bn0?[xt,-ut]:St<0?[-xt,ut]:xt===0?[ut,xt]:[ut,-xt]}(_);let Te=Math.abs(f.top-f.bottom);for(const rt of f.positionedLines)Te-=rt.lineOffset;const Ie=f.positionedLines.length,Ve=Te/Ie;let Je=f.top-_[1];for(let rt=0;rtO)&&(O=Ie.x),(!Te||Ie.y>z)&&(z=Ie.y)}const Y=Math.min(O-S,z-L);let re=Y/2;const me=new yh([],GZt);if(Y===0)return new Xt(S,L);for(let Te=S;Teye.d||!ye.d)&&(ye=Te,_&&console.log("found best %d after %d probes",Math.round(1e4*Te.d)/1e4,we)),Te.max-ye.d<=f||(re=Te.h/2,me.push(new WF(Te.p.x-re,Te.p.y-re,re,k)),me.push(new WF(Te.p.x+re,Te.p.y-re,re,k)),me.push(new WF(Te.p.x-re,Te.p.y+re,re,k)),me.push(new WF(Te.p.x+re,Te.p.y+re,re,k)),we+=4)}return _&&(console.log(`num probes: ${we}`),console.log(`best distance: ${ye.d}`)),ye.p}function GZt(k,f){return f.max-k.max}hse.TinySDF=class{constructor({fontSize:k=24,buffer:f=3,radius:_=8,cutoff:S=.25,fontFamily:L="sans-serif",fontWeight:O="normal",fontStyle:z="normal",lang:G=null}={}){this.buffer=f,this.cutoff=S,this.radius=_,this.lang=G;const Y=this.size=k+4*f,re=this._createCanvas(Y),me=this.ctx=re.getContext("2d",{willReadFrequently:!0});me.font=`${z} ${O} ${k}px ${L}`,me.textBaseline="alphabetic",me.textAlign="left",me.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 f=document.createElement("canvas");return f.width=f.height=k,f}draw(k){const{width:f,actualBoundingBoxAscent:_,actualBoundingBoxDescent:S,actualBoundingBoxLeft:L,actualBoundingBoxRight:O}=this.ctx.measureText(k),z=Math.ceil(_),G=Math.max(0,Math.min(this.size-this.buffer,Math.ceil(O-L))),Y=Math.min(this.size-this.buffer,z+Math.ceil(S)),re=G+2*this.buffer,me=Y+2*this.buffer,ye=Math.max(re*me,0),we=new Uint8ClampedArray(ye),Te={data:we,width:re,height:me,glyphWidth:G,glyphHeight:Y,glyphTop:z,glyphLeft:0,glyphAdvance:f};if(G===0||Y===0)return Te;const{ctx:Ie,buffer:Ve,gridInner:Je,gridOuter:rt}=this;this.lang&&(Ie.lang=this.lang),Ie.clearRect(Ve,Ve,G,Y),Ie.fillText(k,Ve,Ve+z);const xt=Ie.getImageData(Ve,Ve,G,Y);rt.fill(yH,0,ye),Je.fill(0,0,ye);for(let ut=0;ut0?ws*ws:0,Je[Rt]=ws<0?ws*ws:0}}Wet(rt,0,0,re,me,re,this.f,this.v,this.z),Wet(Je,Ve,Ve,G,Y,re,this.f,this.v,this.z);for(let ut=0;utO.y!=Ve.y>O.y&&O.x<(Ve.x-Ie.x)*(O.y-Ie.y)/(Ve.y-Ie.y)+Ie.x&&(G=!G),Y=Math.min(Y,Ww(O,Ie,Ve))}}return(G?1:-1)*Math.sqrt(Y)}(this.p,L),this.max=this.d+this.h*Math.SQRT2}}const WZt=Object.keys,oMe=Number.POSITIVE_INFINITY,KZt=Math.sqrt(2);function WC(k,f,_,S,L,O){const z=Q6e(k)&&k.collisionPadding?k.collisionPadding:[0,0,0,0],G={top:k.top-z[1],bottom:k.bottom+z[3],left:k.left-z[0],right:k.right+z[2],scaled:!1};return S!==void 0&&function(Y,re){Y.top*=re,Y.bottom*=re,Y.left*=re,Y.right*=re,Y.scaled=!0}(G,S),O&&(G.left+=O[0],G.right+=O[0],G.top+=O[1],G.bottom+=O[1]),_&&function(Y,re,me){if(!re)return;const ye=$n(re),we=new Xt(me?me[0]:0,me?me[1]:0),Te=new Xt(Y.left,Y.top),Ie=new Xt(Y.right,Y.top),Ve=new Xt(Y.left,Y.bottom),Je=new Xt(Y.right,Y.bottom);Te._rotateAround(ye,we),Ie._rotateAround(ye,we),Ve._rotateAround(ye,we),Je._rotateAround(ye,we),Y.left=Math.min(Te.x,Ie.x,Ve.x,Je.x),Y.right=Math.max(Te.x,Ie.x,Ve.x,Je.x),Y.top=Math.min(Te.y,Ie.y,Ve.y,Je.y),Y.bottom=Math.max(Te.y,Ie.y,Ve.y,Je.y)}(G,_,L),f?{top:Math.min(f.top,G.top),bottom:Math.max(f.bottom,G.bottom),left:Math.min(f.left,G.left),right:Math.max(f.right,G.right),scaled:f.scaled||G.scaled}:G}function Jet(k,[f,_]){let S=0,L=0;if(_===oMe){f<0&&(f=0);const O=f/KZt;switch(k){case"top-right":case"top-left":L=O-7;break;case"bottom-right":case"bottom-left":L=7-O;break;case"bottom":L=7-f;break;case"top":L=f-7}switch(k){case"top-right":case"bottom-right":S=-O;break;case"top-left":case"bottom-left":S=O;break;case"left":S=f;break;case"right":S=-f}}else{switch(f=Math.abs(f),_=Math.abs(_),k){case"top-right":case"top-left":case"top":L=_-7;break;case"bottom-right":case"bottom-left":case"bottom":L=7-_}switch(k){case"top-right":case"bottom-right":case"right":S=-f;break;case"top-left":case"bottom-left":case"left":S=f}}return[S,L]}function YZt(k,f,_,S,L,O,z,G,Y,re,me,ye,we,Te,Ie){const Ve=k.layers[0],Je=Ve.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:Pt}=function(ws,ns,xs){const us=ws.get("icon-rotate").evaluate(ns,{},xs),hs=ws.get("text-rotate").evaluate(ns,{},xs),[pn,bn]=ws.get("icon-size-scale-range");return{baseIconRotate:us,baseTextRotate:hs,iconScaleFactor:pt(1,pn,bn)}}(S,L,O);f&&(rt.iconBBox=WC(f,rt.iconBBox,ut),_)&&(rt.iconVerticalBBox=WC(_,rt.iconVerticalBBox,ut+90));const Rt=gse(ye.horizontal);Rt&&(xt.textBBox=WC(Rt,xt.textBBox,St,1,Te)),ye.vertical&&(xt.textVerticalBBox=WC(ye.vertical,xt.textVerticalBBox,St+90,1,Te));for(const ws of Je)ws.hasIconLayoutProperties()&&ZZt(rt,k,Ve,ws,L,O,G,ut,z,Y,f,re,Pt,me,Ie),ws.hasTextLayoutProperties()&&XZt(xt,Ve,ws,L,O,Te,St,we,Rt,ye.vertical);return{iconBBox:rt.iconBBox,iconVerticalBBox:rt.iconVerticalBBox,textBBox:xt.textBBox,textVerticalBBox:xt.textVerticalBBox}}function ZZt(k,f,_,S,L,O,z,G,Y,re,me,ye,we,Te,Ie){const{appearanceIconOffset:Ve,appearanceIconRotate:Je,appearanceIconSize:rt}=ett(S,_,L,O,z,G,Y,re.iconScaleFactor);let xt=null,ut=null,St=null;S.hasLayoutProperty("icon-image")?St=function(Rt,ws,ns,xs,us,hs,pn,bn){let An=null;const Ln=ws.getAppearanceValueAndResolveTokens(ns,"icon-image",xs,us,bn);if(Ln){const En=Rt.getResolvedImageFromTokens(Ln),Jn=ns.hasLayoutProperty("icon-size")?ns.getUnevaluatedLayoutProperty("icon-size"):ws._unevaluatedLayout._values["icon-size"],un=vH(En,CM(Rt.zoom,Jn,Rt.worldview,bn),Jn,us,Rt.zoom,xs,Rt.pixelRatio,pn,Rt.worldview,bn);An=hs.get(un.iconPrimary.toString())}return An}(f,_,S,L,O,ye,we,Ie):me&&(St=me.imagePrimary),St&&(xt=dse(St,null,Ve,Te),f.allowVerticalPlacement&&(ut=dse(St,null,Ve,Te)));const Pt=Y>0?rt/Y:1;xt&&(k.iconBBox=WC(xt,k.iconBBox,Je,Pt!==1?Pt:void 0)),ut&&(k.iconVerticalBBox=WC(ut,k.iconVerticalBBox,Je+90,Pt!==1?Pt:void 0))}function ett(k,f,_,S,L,O,z,G){const Y=k.hasLayoutProperty("icon-offset")?f.getAppearanceValueAndResolveTokens(k,"icon-offset",_,S,[]):null,re=Y&&Array.isArray(Y)?Y:L,me=k.hasLayoutProperty("icon-rotate")?f.getAppearanceValueAndResolveTokens(k,"icon-rotate",_,S,[]):null,ye=typeof me=="number"?me:O,we=k.hasLayoutProperty("icon-size")?f.getAppearanceValueAndResolveTokens(k,"icon-size",_,S,[]):null;return{appearanceIconOffset:re,appearanceIconRotate:ye,appearanceIconSize:typeof we=="number"?we*G:z}}function XZt(k,f,_,S,L,O,z,G,Y,re){const{appearanceTextOffset:me,appearanceTextRotate:ye,appearanceTextSize:we}=ttt(_,f,S,L,O,z,G),Te=we/G,Ie=[(me[0]-O[0])*Te,(me[1]-O[1])*Te],Ve=Ie[0]!==0||Ie[1]!==0;Y&&(k.textBBox=WC(Y,k.textBBox,ye,Te,me,Ve?Ie:void 0)),re&&(k.textVerticalBBox=WC(re,k.textVerticalBBox,ye+90,Te,me,Ve?Ie:void 0))}function ttt(k,f,_,S,L,O,z){const G=k.hasLayoutProperty("text-offset")?f.getAppearanceValueAndResolveTokens(k,"text-offset",_,S,[]):null,Y=G&&Array.isArray(G)?[G[0]*Bm,G[1]*Bm]:L,re=k.hasLayoutProperty("text-rotate")?f.getAppearanceValueAndResolveTokens(k,"text-rotate",_,S,[]):null,me=typeof re=="number"?re:O,ye=k.hasLayoutProperty("text-size")?f.getAppearanceValueAndResolveTokens(k,"text-size",_,S,[]):null;return{appearanceTextOffset:Y,appearanceTextRotate:me,appearanceTextSize:typeof ye=="number"?ye:z}}function xse(k,f,_,S,L,O,z,G,Y){if(!f||!f.usvg)return;const re=Oet(S),me=Oet(L),ye=O!=="both"&&O!=="width"||!Det(S)?1:me.width/re.width,we=O!=="both"&&O!=="height"||!Ret(S)?1:me.height/re.height;_.scaleSelf(ye,we);const Te=_.toString();z.set(Te,_),G.set(Te,f);const{imagePosition:Ie}=nMe(Te,f,1);Y.set(Te,Ie)}function stt(k,f,_,S,L,O,z,G,Y,re){if(!k)return;const me=function(ye,we,Te,Ie,Ve,Je,rt){if(ye.kind==="camera")return ye.maxSize;if(ye.kind==="composite"){const xt=we.possiblyEvaluate(new Si(ye.maxZoom,{worldview:Je}),Te,rt).evaluate(Ve,{},Te,rt),ut=we.possiblyEvaluate(new Si(ye.minZoom,{worldview:Je}),Te,rt).evaluate(Ve,{},Te,rt);return Math.max(xt,ut)}return we.possiblyEvaluate(new Si(Ie,{worldview:Je}),Te,rt).evaluate(Ve,{},Te,rt)}(f,_,S,L,O,Y,re);return k.scaleSelf(me*G*z)}function vH(k,f,_,S,L,O,z,G,Y,re){return{iconPrimary:stt(k.getPrimary(),f,_,S,L,O,z,G,Y,re),iconSecondary:stt(k.getSecondary(),f,_,S,L,O,z,G,Y,re)}}function QZt(k,f,_){if(!f)return;const S=_.get(k.toString()),L=_.get(f.toString());S&&L&&(S.paddedRect.w===L.paddedRect.w&&S.paddedRect.h===L.paddedRect.h||Or(`Mismatch in icon variant sizes: ${k.toString()} and ${f.toString()}`),S.usvg!==L.usvg&&Or(`Mismatch in icon variant image types: ${k.id} and ${f.id}`))}function ntt(k,f,_,S){if(!k)return;const L=f.get(_.toString());if(L&&(k.imagePrimary=L),S){const O=f.get(S.toString());k.imageSecondary=O}}function JZt(k,f){for(const _ in k.horizontal)rtt(k.horizontal[_],f);rtt(k.vertical,f)}function rtt(k,f){if(k){for(const _ of k.positionedLines)for(const S of _.positionedGlyphs)if(S.image!==null){const L=S.image.toString();S.rect=f.get(L).paddedRect}}}function lMe(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 eXt(k,f,_,S,L,O,z,G,Y){const re=gse(O.horizontal)||O.vertical,me=_.get("icon-text-fit-padding").evaluate(S,{},L);let ye,we=f;return f&&Y!=="none"&&(k.allowVerticalPlacement&&O.vertical&&(ye=J6e(f,O.vertical,Y,me,G,z)),re&&(we=J6e(f,re,Y,me,G,z))),{defaultShapedIcon:we,verticallyShapedIcon:ye}}function att(k,f){return k*f/24}function tXt(k,f,_,S,L,O,z,G,Y,re,me,ye,we,Te,Ie,Ve,Je,rt,xt,ut,St,Pt,Rt,ws){let ns=z.textMaxSize.evaluate(f,{},we);ns===void 0?ns=G*z.textScaleFactor:ns*=z.textScaleFactor;const xs=k.layers[0].layout,us=att(G,z.textScaleFactor),hs=gse(_.horizontal)||_.vertical,pn=k.hasAnyAppearanceLayoutProperty(["text-size","text-offset","text-rotate"]),bn=k.getAppearanceFeatureData(f.index);(Je!=="none"||pn)&&bn&&(bn.textShaping=hs,bn.iconTextFitPadding=xs.get("icon-text-fit-padding").evaluate(f,{},we),bn.fontScale=us,bn.textScaleFactor=z.textScaleFactor);const An=Te.name==="globe",Ln=k.tilePixelRatio*ns/24,En=(ur=k.overscaling,k.zoom>18&&ur>2&&(ur>>=1),Math.max(lr/(512*ur),1)*xs.get("symbol-spacing")),Jn=xs.get("text-padding")*k.tilePixelRatio,un=xs.get("icon-padding")*k.tilePixelRatio,Mn=$n(xs.get("text-max-angle")),Rn=xs.get("icon-rotation-alignment")==="map"&&ut!=="point",er=En/2;var ur;k.hasAnyIconTextFit===!1&&Je!=="none"&&(k.hasAnyIconTextFit=!0);const Zr=f.properties?+f.properties[Ii]:null,Nr=Zr&&k.elevationFeatureIdToIndex?k.elevationFeatureIdToIndex.get(Zr):65535,wr=(hr,Gr,aa)=>{if(Gr.x<0||Gr.x>=lr||Gr.y<0||Gr.y>=lr)return;let Da=null;if(An){const{x:_a,y:_i,z:To}=Te.projectTilePoint(Gr.x,Gr.y,aa);Da={anchor:new f4(_a,_i,To,0,void 0),up:Te.upVector(aa,Gr.x,Gr.y)}}(function(_a,_i,To,wi,Do,Ui,Od,ll,$o,ac,kd,$m,Sd,ru,sh,au,qf,Um,Xi,Kg,Nu,vp,Yg,Vf,Fd,Xx,bp,Dse,t7,Y0,LMe,s7){const x4=_a.addToLineVertexArray(_i,wi);let g4,c_,d_,PM,n7,no,_p,iu=0,mm=0,u_=0,zv=0,Bv=-1,$v=-1;const Zw={};let Rse=ld("");const F2=To?To.anchor:_i,r7=Dse!=="none";let a7=0,Bh=0;if($o._unevaluatedLayout.getValue("text-radial-offset")===void 0){const ku=$o.layout.get("text-offset").evaluate(Nu,{},Fd);a7=ku[0]*Bm,Bh=ku[1]*Bm}else a7=$o.layout.get("text-radial-offset").evaluate(Nu,{},Fd)*Bm,Bh=oMe;if(_a.allowVerticalPlacement&&Do.vertical){const ku=Do.vertical;if(sh)no=uMe(ku),ll&&(_p=uMe(ll));else{const Zg=$o.layout.get("text-rotate").evaluate(Nu,{},Fd)+90;d_=yse(ac,F2,_i,kd,$m,Sd,ku,ru,Zg,au,s7),ll&&(PM=yse(ac,F2,_i,kd,$m,Sd,ll,Um,Zg,null,LMe))}}if(Ui){const ku=$o.layout.get("icon-rotate").evaluate(Nu,{},Fd),Zg=iMe(Ui,ku,Yg,r7,vp.iconScaleFactor),Z0=ll?iMe(ll,ku,Yg,r7,vp.iconScaleFactor):void 0;c_=yse(ac,F2,_i,kd,$m,Sd,Ui,Um,ku,null,Y0);const Qw=function(z2,IH,i7,xQt,gQt,Sst,Cst,yQt,cXn,IMe){const Ast=z2.layers[0],Est=Ast.appearances;let o7=IH.length;if(i7&&(o7=Math.max(o7,i7.length)),Est.length===0)return o7;const[vQt,bQt]=xQt.get("icon-size-scale-range"),_Qt=pt(1,vQt,bQt);for(const Bse of Est)if(Bse.hasLayoutProperty("icon-image")){const Tst=Ast.getAppearanceValueAndResolveTokens(Bse,"icon-image",Sst,Cst,IMe);if(Tst){const Mst=z2.getResolvedImageFromTokens(Tst);if(Mst){const Lst=Bse.hasLayoutProperty("icon-size")?Bse.getUnevaluatedLayoutProperty("icon-size"):gQt._values["icon-size"],wQt=vH(Mst,CM(z2.zoom,Lst,z2.worldview,IMe),Lst,Cst,z2.zoom,Sst,z2.pixelRatio,_Qt,z2.worldview,IMe),Pst=yQt.get(wQt.iconPrimary.toString());Pst&&(o7=Math.max(o7,qZt(Pst)))}}}return o7}(_a,Zg,Z0,$o.layout,$o._unevaluatedLayout,Nu,Fd,_a.iconAtlasPositions,0,Vf);iu=4*Qw;const Ose=$o.layout.get("icon-size").evaluate(Nu,{},Fd,Vf),Fse=vp.compositeIconSizes?vp.compositeIconSizes[0].evaluate(Nu,{},Fd,Vf):0,PMe=vp.compositeIconSizes?vp.compositeIconSizes[1].evaluate(Nu,{},Fd,Vf):0,zse=dMe(_a.layerIds[0],_a.iconSizeData,Ose,vp.iconScaleFactor,Fse,PMe);_a.addSymbols(_a.icon,Zg,zse,Kg,Xi,Nu,void 0,To,_i,x4.lineStartIndex,x4.lineLength,-1,Vf,Fd,Xx,bp,_a.symbolInstances.length,Qw),Bv=_a.icon.placedSymbolArray.length-1,Z0&&(mm=4*Qw,_a.addSymbols(_a.icon,Z0,zse,Kg,Xi,Nu,Fv.vertical,To,_i,x4.lineStartIndex,x4.lineLength,-1,Vf,Fd,Xx,bp,_a.symbolInstances.length,Qw),$v=_a.icon.placedSymbolArray.length-1)}for(const ku in Do.horizontal){const Zg=ku,Z0=Do.horizontal[Zg];g4||(Rse=ld(Z0.text),sh?n7=uMe(Z0):g4=yse(ac,F2,_i,kd,$m,Sd,Z0,ru,$o.layout.get("text-rotate").evaluate(Nu,{},Fd),au,s7));const Qw=Z0.positionedLines.length===1;if(u_+=itt(_a,To,_i,Z0,Od,$o,sh,Nu,au,x4,Do.vertical?Fv.horizontal:Fv.horizontalOnly,Qw?WZt(Do.horizontal):[Zg],Zw,Bv,vp,Vf,Fd,_a.symbolInstances.length,Xx),Qw)break}Do.vertical&&(zv+=itt(_a,To,_i,Do.vertical,Od,$o,sh,Nu,au,x4,Fv.vertical,["vertical"],Zw,$v,vp,Vf,Fd,_a.symbolInstances.length,Xx));let _h=-1;const pm=(ku,Zg)=>ku?Math.max(ku,Zg):Zg;_h=pm(n7,_h),_h=pm(no,_h),_h=pm(_p,_h);const Xw=_h>-1?1:0;_a.glyphOffsetArray.length>=65535&&Or("Too many glyphs being rendered in a tile. See https://github.com/mapbox/mapbox-gl-js/issues/2907"),Nu.sortKey!==void 0&&_a.addToSortKeyRanges(_a.symbolInstances.length,Nu.sortKey),_a.symbolInstances.emplaceBack(_i.x,_i.y,F2.x,F2.y,F2.z,Zw.right>=0?Zw.right:-1,Zw.center>=0?Zw.center:-1,Zw.left>=0?Zw.left:-1,Zw.vertical>=0?Zw.vertical:-1,Bv,$v,Rse,g4!==void 0?g4:_a.collisionBoxArray.length,g4!==void 0?g4+1:_a.collisionBoxArray.length,d_!==void 0?d_:_a.collisionBoxArray.length,d_!==void 0?d_+1:_a.collisionBoxArray.length,c_!==void 0?c_:_a.collisionBoxArray.length,c_!==void 0?c_+1:_a.collisionBoxArray.length,PM||_a.collisionBoxArray.length,PM?PM+1:_a.collisionBoxArray.length,kd,u_,zv,iu,mm,Xw,0,a7,Bh,_h,0,r7?1:0,t7)})(k,Gr,Da,hr,_,S,O,L,k.layers[0],k.collisionBoxArray,f.index,f.sourceLayerIndex,k.index,Jn,xt,re,0,un,Rn,rt,f,z,me,ye,we,Ie,Ve,Je,Nr,St,Pt,Rt)};if(ut==="line")for(const hr of Xte(f.geometry,0,0,lr,lr)){const Gr=UZt(hr,En,Mn,_.vertical||hs,S,24,Ln,k.overscaling,lr);for(const aa of Gr)hs&&sXt(k,hs.text,er,aa)||wr(hr,aa,we)}else if(ut==="line-center"){for(const hr of f.geometry)if(hr.length>1){const Gr=$Zt(hr,Mn,_.vertical||hs,S,24,Ln);Gr&&wr(hr,Gr,we)}}else if(f.type==="Polygon")for(const hr of tH(f.geometry,0)){const Gr=HZt(hr,16);wr(hr[0],new f4(Gr.x,Gr.y,0,0,void 0),we)}else if(f.type==="LineString")for(const hr of f.geometry)wr(hr,new f4(hr[0].x,hr[0].y,0,0,void 0),we);else if(f.type==="Point")for(const hr of f.geometry)for(const Gr of hr)wr([Gr],new f4(Gr.x,Gr.y,0,0,void 0),we)}const cMe=255,AM=cMe*p4;function itt(k,f,_,S,L,O,z,G,Y,re,me,ye,we,Te,Ie,Ve,Je,rt,xt){const ut=Qet(0,S,Y,O,z,G,L,k.allowVerticalPlacement,void 0,Ie.textScaleFactor),St=O.layout.get("text-size").evaluate(G,{},Je),Pt=Ie.compositeTextSizes?Ie.compositeTextSizes[0].evaluate(G,{},Je):0,Rt=Ie.compositeTextSizes?Ie.compositeTextSizes[1].evaluate(G,{},Je):0,ws=dMe(k.layerIds[0],k.textSizeData,St,Ie.textScaleFactor,Pt,Rt);k.addSymbols(k.text,ut,ws,Y,z,G,me,f,_,re.lineStartIndex,re.lineLength,Te,Ve,Je,xt,!1,rt,ut.length);for(const ns of ye)we[ns]=k.text.placedSymbolArray.length-1;return 4*ut.length}function dMe(k,f,_,S,L,O){const z=f;let G=null;return z.kind==="source"?(G=[p4*_*S],G[0]>AM&&Or(`${k}: Value for "text-size" is >= ${cMe}. Reduce your "text-size".`)):z.kind==="composite"&&(G=[p4*L*S,p4*O*S],(G[0]>AM||G[1]>AM)&&Or(`${k}: Value for "text-size" is >= ${cMe}. Reduce your "text-size".`)),G}function gse(k){for(const f in k)return k[f];return null}function yse(k,f,_,S,L,O,z,G,Y,re,me){let ye,we,Te,Ie;if(ye=me?me.top:z.top,we=me?me.bottom:z.bottom,Te=me?me.left:z.left,Ie=me?me.right:z.right,Q6e(z)&&z.collisionPadding){const Ve=z.collisionPadding;Te-=Ve[0],ye-=Ve[1],Ie+=Ve[2],we+=Ve[3]}if(Y){const Ve=new Xt(Te,ye),Je=new Xt(Ie,ye),rt=new Xt(Te,we),xt=new Xt(Ie,we),ut=$n(Y);let St=new Xt(0,0);re&&(St=new Xt(re[0],re[1])),Ve._rotateAround(ut,St),Je._rotateAround(ut,St),rt._rotateAround(ut,St),xt._rotateAround(ut,St),Te=Math.min(Ve.x,Je.x,rt.x,xt.x),Ie=Math.max(Ve.x,Je.x,rt.x,xt.x),ye=Math.min(Ve.y,Je.y,rt.y,xt.y),we=Math.max(Ve.y,Je.y,rt.y,xt.y)}return k.emplaceBack(f.x,f.y,f.z,_.x,_.y,Te,ye,Ie,we,G,S,L,O),k.length-1}function uMe(k){Q6e(k)&&k.collisionPadding&&(k.top-=k.collisionPadding[1],k.bottom+=k.collisionPadding[3]);const f=k.bottom-k.top;return f>0?Math.max(10,f):null}function sXt(k,f,_,S){const L=k.compareText;if(f in L){const O=L[f];for(let z=O.length-1;z>=0;z--)if(S.dist(O[z])<_)return!0}else L[f]=[];return L[f].push(S),!1}function ott(k,f){const _=k.fovAboveCenter,S=k.elevation?k.elevation.getMinElevationBelowMSL()*f:0,L=Math.min(S,k.isOrthographic?-10*f:0),O=(k._camera.position[2]*k.worldSize-L)/Math.cos(k._pitch),z=Math.sin(_)*O/Math.sin(Math.max(Math.PI/2-k._pitch-_,.01));let G=Math.sin(k._pitch)*z+O;const Y=O*(1/k._horizonShift);if(!k.elevation||k.elevation.exaggeration()===0){let re=Math.max(k.zoom-17,0);k.isOrthographic&&(re/=10),G*=1+re}return Math.min(1.01*G,Y)}function EM(k,f){if(!f.isReprojectedInTileSpace)return{scale:1<ut&&(St(Rt,An,ns,xs,pn,bn),St(An,ws,pn,bn,us,hs))}St(ye,we,S,O,L,O),St(we,Te,L,O,L,z),St(Te,Ie,L,z,S,z),St(Ie,ye,S,z,S,O),Ve-=ut,Je-=ut,rt+=ut,xt+=ut;const Pt=1/Math.max(rt-Ve,xt-Je);return{scale:Pt,x:Ve*Pt,y:Je*Pt,x2:rt*Pt,y2:xt*Pt,projection:f}}function ltt(k,{x:f,y:_},S=0){return new Xt(((f-S)*k.scale-k.x)*lr,(_*k.scale-k.y)*lr)}const nXt=y(new Float32Array(16));class KC{constructor(f){this.spec=f,this.name=f.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(f,_){return{x:0,y:0,z:0}}unproject(f,_){return new As(0,0)}projectTilePoint(f,_,S){return{x:f,y:_,z:0}}locationPoint(f,_,S,L=!0){return f._coordinatePoint(f.locationCoordinate(_,S),L)}pixelsPerMeter(f,_){return en(1,f)*_}pixelSpaceConversion(f,_,S){return 1}farthestPixelDistance(f){return ott(f,f.pixelsPerMeter)}pointCoordinate(f,_,S,L){const O=f.horizonLineFromTop(!1),z=new Xt(_,Math.max(O,S));return f.rayIntersectionCoordinate(f.pointRayIntersection(z,L))}pointCoordinate3D(f,_,S){const L=new Xt(_,S);if(f.elevation)return f.elevation.pointCoordinate(L);{const O=this.pointCoordinate(f,L.x,L.y,0);return[O.x,O.y,O.z]}}isPointAboveHorizon(f,_){if(f.elevation&&f.elevation.visibleDemTiles.length)return!this.pointCoordinate3D(f,_.x,_.y);const S=f.horizonLineFromTop();return _.y0?_<-KF+S&&(_=-KF+S):_>KF-S&&(_=KF-S);const z=O/Math.pow(bse(_),L);let G=z*Math.sin(L*f),Y=O-z*Math.cos(L*f);return G=.5*(G/Math.PI+.5),Y=.5*(Y/Math.PI+.5),{x:G,y:this.southernCenter?Y:1-Y,z:0}}unproject(f,_){f=(2*f-.5)*Math.PI,this.southernCenter&&(_=1-_),_=(2*(1-_)-.5)*Math.PI;const{n:S,f:L}=this,O=L-_,z=Math.sign(O),G=Math.sign(S)*Math.sqrt(f*f+O*O);let Y=Math.atan2(f,Math.abs(O))*z;O*S<0&&(Y-=Math.PI*Math.sign(f)*z);const re=pt(tn(Y/S)+this.center[0],-180,180),me=pt(tn(2*Math.atan(Math.pow(L/G,1/S))-KF),-85.051129,kn);return new As(re,this.southernCenter?-me:me)}}class ctt extends KC{constructor(f){super(f),this.wrap=!0,this.supportsWorldCopies=!0,this.supportsTerrain=!0,this.supportsFog=!0,this.supportsFreeCamera=!0,this.isReprojectedInTileSpace=!1,this.unsupportedLayers=[],this.range=null}project(f,_){return{x:Dn(f),y:Gn(_),z:0}}unproject(f,_){const S=Ms(f),L=mn(_);return new As(S,L)}}const dtt=$n(kn);class lXt extends KC{project(f,_){const S=(_=$n(_))*_,L=S*S;return{x:.5*((f=$n(f))*(.8707-.131979*S+L*(L*(.003971*S-.001529*L)-.013791))/Math.PI+.5),y:1-.5*(_*(1.007226+S*(.015085+L*(.028874*S-.044475-.005916*L)))/Math.PI+1),z:0}}unproject(f,_){f=(2*f-.5)*Math.PI;let S=_=(2*(1-_)-1)*Math.PI,L=25,O=0,z=S*S;do{z=S*S;const re=z*z;O=(S*(1.007226+z*(.015085+re*(.028874*z-.044475-.005916*re)))-_)/(1.007226+z*(.045255+re*(.259866*z-.311325-.005916*11*re))),S=pt(S-O,-dtt,dtt)}while(Math.abs(O)>1e-6&&--L>0);z=S*S;const G=pt(tn(f/(.8707+z*(z*(z*z*z*(.003971-.001529*z)-.013791)-.131979))),-180,180),Y=tn(S);return new As(G,Y)}}const utt=$n(kn);class cXt extends KC{project(f,_){_=$n(_),f=$n(f);const S=Math.cos(_),L=2/Math.PI,O=Math.acos(S*Math.cos(f/2)),z=Math.sin(O)/O,G=.5*(f*L+2*S*Math.sin(f/2)/z)||0,Y=.5*(_+Math.sin(_)/z)||0;return{x:.5*(G/Math.PI+.5),y:1-.5*(Y/Math.PI+1),z:0}}unproject(f,_){let S=f=(2*f-.5)*Math.PI,L=_=(2*(1-_)-1)*Math.PI,O=25;const z=1e-6;let G=0,Y=0;do{const re=Math.cos(L),me=Math.sin(L),ye=2*me*re,we=me*me,Te=re*re,Ie=Math.cos(S/2),Ve=Math.sin(S/2),Je=2*Ie*Ve,rt=Ve*Ve,xt=1-Te*Ie*Ie,ut=xt?1/xt:0,St=xt?Math.acos(re*Ie)*Math.sqrt(1/xt):0,Pt=.5*(2*St*re*Ve+2*S/Math.PI)-f,Rt=.5*(St*me+L)-_,ws=.5*ut*(Te*rt+St*re*Ie*we)+1/Math.PI,ns=ut*(Je*ye/4-St*me*Ve),xs=.125*ut*(ye*Ve-St*me*Te*Je),us=.5*ut*(we*Ie+St*rt*re)+.5,hs=ns*xs-us*ws;G=(Rt*ns-Pt*us)/hs,Y=(Pt*xs-Rt*ws)/hs,S=pt(S-G,-Math.PI,Math.PI),L=pt(L-Y,-utt,utt)}while((Math.abs(G)>z||Math.abs(Y)>z)&&--O>0);return new As(tn(S),tn(L))}}class htt extends KC{constructor(f){super(f),this.center=f.center||[0,0],this.parallels=f.parallels||[0,0],this.cosPhi=Math.max(.01,Math.cos($n(this.parallels[0]))),this.scale=1/(2*Math.max(Math.PI*this.cosPhi,1/this.cosPhi)),this.wrap=!0,this.supportsWorldCopies=!0}project(f,_){const{scale:S,cosPhi:L}=this;return{x:$n(f)*L*S+.5,y:-Math.sin($n(_))/L*S+.5,z:0}}unproject(f,_){const{scale:S,cosPhi:L}=this,O=-(_-.5)/S,z=pt(tn((f-.5)/S)/L,-180,180),G=Math.asin(pt(O*L,-1,1)),Y=pt(tn(G),-85.051129,kn);return new As(z,Y)}}class dXt extends ctt{constructor(f){super(f),this.requiresDraping=!0,this.supportsWorldCopies=!1,this.supportsFog=!0,this.zAxisUnit="pixels",this.unsupportedLayers=["debug"],this.range=[3,5]}projectTilePoint(f,_,S){const L=KV(f,_,S);return Xe(L,L,YV(Mk(S))),{x:L[0],y:L[1],z:L[2]}}locationPoint(f,_,S){const L=es(_.lat,_.lng),O=Me([],L),z=S?f._centerAltitude+S:f.elevation?f.elevation.getAtPointOrZero(f.locationCoordinate(_),f._centerAltitude):f._centerAltitude;ve(L,L,O,en(1,0)*lr*z);const G=y(new Float64Array(16));return v(G,f.pixelMatrix,f.globeMatrix),Xe(L,L,G),new Xt(L[0],L[1])}pixelsPerMeter(f,_){return en(1,0)*_}pixelSpaceConversion(f,_,S){const L=en(1,f)*_,O=Cs(en(1,45)*_,L,S);return this.pixelsPerMeter(f,_)/O}createTileMatrix(f,_,S){const L=a6e(Mk(S.canonical));return v(new Float64Array(16),f.globeMatrix,L)}createInversionMatrix(f,_){const{center:S}=f,L=YV(Mk(_));return T(L,L,$n(S.lng)),A(L,L,$n(S.lat)),C(L,L,[f._pixelsPerMercatorPixel,f._pixelsPerMercatorPixel,1]),Float32Array.from(L)}pointCoordinate(f,_,S,L){return SQe(f,_,S,!0)||new ra(0,0)}pointCoordinate3D(f,_,S){const L=this.pointCoordinate(f,_,S,0);return[L.x,L.y,L.z]}isPointAboveHorizon(f,_){return!SQe(f,_.x,_.y,!1)}farthestPixelDistance(f){const _=function(L,O){const z=L.cameraToCenterDistance,G=L._centerAltitude*O,Y=L._camera,re=L._camera.forward(),me=ce([],he([],re,-z),[0,0,G]),ye=L.worldSize/(2*Math.PI),we=[0,0,-ye],Te=L.width/L.height,Ie=Math.tan(L.fovAboveCenter),Ve=he([],Y.up(),Ie),Je=he([],Y.right(),Ie*Te),rt=Me([],ce([],ce([],re,Ve),Je)),xt=[];let ut;if(new ro(me,rt).closestPointOnSphere(we,ye,xt)){const St=ce([],xt,we),Pt=qe([],St,me);ut=Math.cos(L.fovAboveCenter)*K(Pt)}else{const St=qe([],me,we),Pt=qe([],we,me);Me(Pt,Pt);const Rt=K(St)-ye;ut=Math.sqrt(Rt*(Rt+2*ye));const ws=Math.acos(ut/(ye+Rt))-Math.acos(De(re,Pt));ut*=Math.cos(ws)}return 1.01*ut}(f,this.pixelsPerMeter(f.center.lat,f.worldSize)),S=u4(f.zoom);if(S>0){const L=ott(f,en(1,f.center.lat)*f.worldSize),O=f.worldSize/(2*Math.PI),z=Math.max(f.width,f.height)/f.worldSize*Math.PI;return Cs(_,L+O*(1-Math.cos(z)),Math.pow(S,10))}return _}upVector(f,_,S){return KV(_,S,f,1)}upVectorScale(f){return{metersToTile:Pte(Dte(Mk(f)))}}}function mtt(k){const f=k.parallels,_=!!f&&Math.abs(f[0]+f[1])<.01;switch(k.name){case"mercator":return new ctt(k);case"equirectangular":return new iXt(k);case"naturalEarth":return new lXt(k);case"equalEarth":return new aXt(k);case"winkelTripel":return new cXt(k);case"albers":return _?new htt(k):new rXt(k);case"lambertConformalConic":return _?new htt(k):new oXt(k);case"globe":return new dXt(k)}throw new Error(`Invalid projection name: ${k.name}`)}class uXt{constructor(f,_){this.lastParams=null,this.lastAllFeaturesIndex=-2,this.appearancesVersion=_,this.appearances=f;const S=f.map(L=>function(O){if(!O.condition)return{featureDependent:!1,stateDependent:!1,zoomDependent:!1,pitchDependent:!1,brightnessDependent:!1,worldviewDependent:!1};const z=O.condition.expression;return{featureDependent:!B1(z),stateDependent:!zf(z),zoomDependent:!eu(z,["zoom"]),pitchDependent:!eu(z,["pitch"]),brightnessDependent:!eu(z,["brightness","measure-light"]),worldviewDependent:!eu(z,["worldview"])}}(L));this.anyFeatureDependent=S.some(L=>L.featureDependent),this.anyStateDependent=S.some(L=>L.stateDependent)}update(f,_){const S=this.lastParams,L=!S||S.zoom!==f.zoom||S.pitch!==(f.pitch||0)||S.brightness!==(f.brightness||0)||S.worldview!==f.worldview;this.lastParams={zoom:f.zoom,pitch:f.pitch||0,brightness:f.brightness||0,worldview:f.worldview};const O=_&&this.anyStateDependent;if(!L&&!O&&this.lastAllFeaturesIndex!==-2)return{kind:"no-changes"};if(!this.anyFeatureDependent&&!O){const z=this.evaluateAllFeatures(f);return z===this.lastAllFeaturesIndex?{kind:"no-changes"}:(this.lastAllFeaturesIndex=z,{kind:"all-features",appearanceIndex:z})}return{kind:"per-feature"}}evaluateAllFeatures(f){for(let _=0;_{for(let L=0;Lz-G),O=new Map;for(const z of L){const G=S.get(z);O.set(z,new sc(G))}return _&&(this.cachedBatchIndices=L,this.cachedBatchSegments=O),{batchIndices:L,batchSegments:O}}snapshotSymbolVertexData(f,_){const S=f*ZF;return this.layoutVertexArray.uint16.slice(S,S+_*ZF)}restoreSymbolVertexData(f,_){this.layoutVertexArray.uint16.set(_,f*ZF)}updateSymbolVertexData(f,_,S,L,O,z,G,Y,re,me,ye,we,Te){const Ie=this.layoutVertexArray.uint16,Ve=f*ZF;Ie[Ve]=_,Ie[Ve+1]=S,Ie[Ve+2]=L,Ie[Ve+3]=O,Ie[Ve+4]=z,Ie[Ve+5]=G,Ie[Ve+6]=Y,Ie[Ve+7]=re,Ie[Ve+8]=me,Ie[Ve+9]=ye,Ie[Ve+10]=we,Ie[Ve+11]=Te}upload(f,_,S,L,O,z){this.isEmpty()||(S&&(this.cachedBatchIndices=null,this.cachedBatchSegments=null,this.layoutVertexBuffer=f.createVertexBuffer(this.layoutVertexArray,pZt.members,!!z),this.indexBuffer=f.createIndexBuffer(this.indexArray,_),this.dynamicLayoutVertexBuffer=f.createVertexBuffer(this.dynamicLayoutVertexArray,xZt.members,!0),this.opacityVertexBuffer=f.createVertexBuffer(this.opacityVertexArray,mXt,!0),this.iconTransitioningVertexArray.length>0&&(this.iconTransitioningVertexBuffer=f.createVertexBuffer(this.iconTransitioningVertexArray,bZt.members,!0)),this.globeExtVertexArray.length>0&&(this.globeExtVertexBuffer=f.createVertexBuffer(this.globeExtVertexArray,fZt.members,!0)),!this.zOffsetVertexBuffer&&(this.zOffsetVertexArray.length>0||O)&&(this.zOffsetVertexBuffer=f.createVertexBuffer(this.zOffsetVertexArray,gZt.members,!0)),!this.orientationVertexBuffer&&this.orientationVertexArray&&this.orientationVertexArray.length>0&&(this.orientationVertexBuffer=f.createVertexBuffer(this.orientationVertexArray,vZt.members,!0)),this.opacityVertexBuffer.itemSize=1,this.featureIdArray&&this.featureIdArray.length>0&&(this.featureIdBuffer=f.createVertexBuffer(this.featureIdArray,yZt.members,!1))),(S||L)&&(this.programConfigurations.upload(f),this.uboBinder&&this.uboBinder.upload(f)))}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())}}br(hMe,"SymbolBuffers",{omit:["cachedBatchIndices","cachedBatchSegments"]});class mMe{constructor(f,_,S){this.layoutVertexArray=new f,this.layoutAttributes=_,this.indexArray=new S,this.segments=new sc,this.collisionVertexArray=new pM,this.collisionVertexArrayExt=new M2}upload(f){this.layoutVertexBuffer=f.createVertexBuffer(this.layoutVertexArray,this.layoutAttributes),this.indexBuffer=f.createIndexBuffer(this.indexArray),this.collisionVertexBuffer=f.createVertexBuffer(this.collisionVertexArray,_Zt.members,!0),this.collisionVertexBufferExt=f.createVertexBuffer(this.collisionVertexArrayExt,wZt.members,!0)}destroy(){this.layoutVertexBuffer&&(this.layoutVertexBuffer.destroy(),this.indexBuffer.destroy(),this.segments.destroy(),this.collisionVertexBuffer.destroy(),this.collisionVertexBufferExt.destroy())}}br(mMe,"CollisionBuffers");class D2{constructor(f){this.collisionBoxArray=f.collisionBoxArray,this.zoom=f.zoom,this.overscaling=f.overscaling,this.layers=f.layers,this.layerIds=this.layers.map(z=>z.fqid),this.index=f.index,this.pixelRatio=f.pixelRatio,this.sourceLayerIndex=f.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=f.worldview,this.localizable=f.localizable,this.maxUniformBufferBindings=f.maxUniformBufferBindings,this.maxUniformBlockSizeDwords=f.maxUniformBlockSizeDwords,this.disableSymbolUBO=f.disableSymbolUBO,this.textSizeData=CM(this.zoom,_["text-size"],this.worldview,f.availableImages),this.iconSizeData=CM(this.zoom,_["icon-size"],this.worldview,f.availableImages);const S=this.layers[0].layout,L=S.get("symbol-sort-key"),O=S.get("symbol-z-order");this.lut=f.lut,this.canOverlap=S.get("text-allow-overlap")||S.get("icon-allow-overlap")||S.get("text-ignore-placement")||S.get("icon-ignore-placement"),this.sortFeaturesByKey=O!=="viewport-y"&&L.constantOr(1)!==void 0,this.sortFeaturesByY=(O==="viewport-y"||O==="auto"&&!this.sortFeaturesByKey)&&this.canOverlap,this.writingModes=S.get("text-writing-mode").map(z=>Fv[z]),this.stateDependentLayerIds=this.layers.filter(z=>z.isStateDependent()).map(z=>z.id),this.sourceID=f.sourceID,this.projection=f.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(f){const _=this.layers[0].getAppearances();if(!_||_.length===0)return!1;const S=Array.isArray(f)?f:[f];return _.some(L=>S.some(O=>L.hasLayoutProperty(O)))}getAppearanceFeatureData(f){return this.featureAppearanceData.get(f)}createArrays(){this.text=new hMe(new tt(this.layers,{zoom:this.zoom,lut:this.lut},f=>f.startsWith("text")||f.startsWith("symbol"))),this.icon=new hMe(new tt(this.layers,{zoom:this.zoom,lut:this.lut},f=>f.startsWith("icon")||f.startsWith("symbol"))),this.disableSymbolUBO||(this.text.uboBinder=new K6e(this.layers[0],this.zoom,this.lut,!0,"",this.maxUniformBufferBindings,this.maxUniformBlockSizeDwords),this.icon.uboBinder=new K6e(this.layers[0],this.zoom,this.lut,!1,"",this.maxUniformBufferBindings,this.maxUniformBlockSizeDwords)),this.glyphOffsetArray=new Cte,this.lineVertexArray=new gM,this.symbolInstances=new Ste}calculateGlyphDependencies(f,_,S,L,O){for(const z of f){const G=z.codePointAt(0);if(G===void 0)break;if(_[G]=!0,L&&O&&G<=65535){const Y=pH[z];Y&&(_[Y.charCodeAt(0)]=!0)}}}calculateEffectiveAppearanceIconSize(f,_,S,L,O,z,G){if(!f.hasLayoutProperty("icon-size"))return G*z;let Y=1;const re=f.getUnevaluatedLayoutProperty("icon-size"),me=CM(this.zoom,re,this.worldview,O),ye=GF(me,_);if(me.kind!=="constant"&&me.kind!=="camera"||(Y=ye.uSize),me.kind==="composite"){const{minZoom:we,maxZoom:Te}=me,Ie=re.possiblyEvaluate(new Si(we,{worldview:this.worldview}),L),Ve=re.possiblyEvaluate(new Si(Te,{worldview:this.worldview}),L),Je=Ie.evaluate(S,{},L,O);Y=Je+(Ve.evaluate(S,{},L,O)-Je)*ye.uSizeT}return me.kind==="source"&&(Y=re.possiblyEvaluate(new Si(this.zoom,{worldview:this.worldview}),L).evaluate(S,{},L,O)),Y*z}updateFootprints(f,_){}updateReplacement(f,_){if(_.updateTime===this.replacementUpdateTime)return!1;this.replacementUpdateTime=_.updateTime;const S=_.getReplacementRegionsForTile(f.toUnwrapped(),!0);return!Hte(this.activeReplacements,S)&&(this.activeReplacements=S,!0)}getResolvedImageFromTokens(f){return typeof f=="string"?Pu.build(f):f}populate(f,_,S,L){const O=this.layers[0],z=O.layout,G=this.projection.name==="globe",Y=z.get("text-font"),re=z.get("text-field"),me=z.get("icon-image"),[ye,we]=z.get("icon-size-scale-range"),Te=pt(_.scaleFactor||1,ye,we),[Ie,Ve]=z.get("text-size-scale-range"),Je=pt(_.scaleFactor||1,Ie,Ve),rt=(re.value.kind!=="constant"||re.value.value instanceof cd&&!re.value.value.isEmpty()||re.value.value.toString().length>0)&&(Y.value.kind!=="constant"||Y.value.value.length>0),xt=me.value.kind!=="constant"||!!me.value.value||Object.keys(me.parameters).length>0,ut=this.hasAnyAppearanceLayoutProperty("icon-image"),St=z.get("symbol-sort-key");if(this.features=[],this.featureAppearanceData=new Map,!rt&&!xt&&!ut)return;const Pt=_.iconDependencies,Rt=_.glyphDependencies,ws=_.availableImages,ns=new Si(this.zoom,{worldview:this.worldview,activeFloors:_.activeFloors}),xs=us=>{const hs=us.id.toString();Pt.has(hs)?Pt.get(hs).push(us):Pt.set(hs,[us])};for(const us of f){const{feature:hs,id:pn,index:bn,sourceLayerIndex:An}=us,Ln=O._featureFilter.needGeometry,En=$i(hs,Ln);if(!O._featureFilter.filter(ns,En,S))continue;if(Ln||(En.geometry=Oa(hs,S,L)),G&&hs.type!==1&&S.z<=5){const Nr=En.geometry,wr=.98078528056,hr=(Gr,aa)=>De(KV(Gr.x,Gr.y,S,1),KV(aa.x,aa.y,S,1)){if(!Nr.getLayoutProperty("icon-image"))return;const wr=this.getCombinedIconPrimary(Nr,Mn,En,S,ws,ur,Te);wr&&xs(wr)}),Jn){const Nr=Y.evaluate(En,{},S).join(","),wr=z.get("text-rotation-alignment")==="map"&&z.get("symbol-placement")!=="point";this.allowVerticalPlacement=this.writingModes&&this.writingModes.indexOf(Fv.vertical)>=0;for(const hr of Jn.sections)if(hr.image){const Gr=hr.image.getPrimary().scaleSelf(this.pixelRatio*Je),aa=Gr.id.toString(),Da=Pt.get(aa)||[];Da.push(Gr),Pt.set(aa,Da)}else{const Gr=nf(Jn.toString()),aa=hr.fontStack||Nr,Da=Rt[aa]=Rt[aa]||{};this.calculateGlyphDependencies(hr.text,Da,wr,this.allowVerticalPlacement,Gr)}}}if(z.get("symbol-placement")==="line"&&(this.features=function(us){const hs={},pn={},bn=[];let An=0;function Ln(Mn){bn.push(us[Mn]),An++}function En(Mn,Rn,er){const ur=pn[Mn];return delete pn[Mn],pn[Rn]=ur,bn[ur].geometry[0].pop(),bn[ur].geometry[0]=bn[ur].geometry[0].concat(er[0]),ur}function Jn(Mn,Rn,er){const ur=hs[Rn];return delete hs[Rn],hs[Mn]=ur,bn[ur].geometry[0].shift(),bn[ur].geometry[0]=er[0].concat(bn[ur].geometry[0]),ur}function un(Mn,Rn,er){const ur=er?Rn[0][Rn[0].length-1]:Rn[0][0];return`${Mn}:${ur.x}:${ur.y}`}for(let Mn=0;MnMn.geometry)}(this.features)),z.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 us of _.elevationFeatures)this.elevationFeatureIdToIndex.set(us.id,this.elevationFeatures.length),this.elevationFeatures.push(us)}}else z.get("symbol-z-elevate")&&(this.elevationType="offset");this.elevationType!=="none"&&(this.zOffsetBuffersNeedUpload=!0),this.sortFeaturesByKey&&this.features.sort((us,hs)=>us.sortKey-hs.sortKey)}getCombinedIconPrimary(f,_,S,L,O,z,G){let Y,re;if(f.hasLayoutProperty("icon-image")){const me=_.getAppearanceValueAndResolveTokens(f,"icon-image",S,L,O);Y=this.getResolvedImageFromTokens(me)}else{const me=_.getValueAndResolveTokens("icon-image",S,L,O);Y=this.getResolvedImageFromTokens(me)}if(Y){const me=f.hasLayoutProperty("icon-size")?f.getUnevaluatedLayoutProperty("icon-size"):_._unevaluatedLayout._values["icon-size"];re=vH(Y,CM(this.zoom,me,this.worldview,O),me,L,this.zoom,z,this.pixelRatio,G,this.worldview,O).iconPrimary}return re}updateSymbolInstanceIconVertices(f,_,S,L,O,z){const{canonical:G,availableImages:Y,globalProperties:re,layer:me,iconScaleFactor:ye,featureState:we,layoutIconOffset:Te,layoutIconSize:Ie,layoutIconRotate:Ve}=z;if(f.placedIconSymbolIndex<0)return{vertexOffsetDelta:0,hasChanges:!1};if(_.activeAppearanceIndex===S)return{vertexOffsetDelta:f.numIconVertices,hasChanges:!1};const Je=S>=0?me.appearances[S]:null;if(Je){const rt=this.getCombinedIconPrimary(Je,me,L,G,Y,{sortKey:void 0,text:void 0,icon:null,index:f.featureIndex,sourceLayerIndex:f.featureIndex,geometry:[],properties:_.properties,type:"Point",id:_.id},ye);if(!rt)return{vertexOffsetDelta:0,hasChanges:!1};const xt=rt.toString(),ut=this.iconAtlasPositions&&this.iconAtlasPositions.get(xt);if(ut){const{appearanceIconOffset:St,appearanceIconRotate:Pt}=ett(Je,me,L,G,Te,Ve,Ie,ye);let Rt=dse(ut,void 0,St,me.layout.get("icon-anchor").evaluate(L,we,G));const ws=ut.sdf,ns=me.layout.get("icon-text-fit").constantOr("none");ns!=="none"&&_.textShaping&&_.iconTextFitPadding&&_.fontScale&&(Rt=J6e(Rt,_.textShaping,ns,_.iconTextFitPadding,St,_.fontScale));const xs=this.calculateEffectiveAppearanceIconSize(Je,re.zoom,L,G,Y,ye,Ie),us=0,hs=1+(Math.min(AM,Math.round(xs*p4))<<1),pn=iMe(Rt,Pt,ws,ns!=="none",ye);_.isUsingAppearanceIconVertexData||(_.isUsingAppearanceIconVertexData=!0,_.layoutBasedIconVertexData=this.icon.snapshotSymbolVertexData(O,f.numIconVertices));const bn=Math.floor(f.numIconVertices/4),An=Math.min(pn.length,bn);let Ln=O;for(let Jn=0;Jn0||f.numVerticalGlyphVertices>0;if(!St)return{vertexOffsetDelta:St?f.numHorizontalGlyphVertices+f.numVerticalGlyphVertices:0,hasChanges:!1};if(_.activeAppearanceIndex===S)return{vertexOffsetDelta:f.numHorizontalGlyphVertices+f.numVerticalGlyphVertices,hasChanges:!1};const Pt=S>=0?Y.appearances[S]:null;if(Pt&&_.textShaping){const{appearanceTextOffset:Rt,appearanceTextRotate:ws,appearanceTextSize:ns}=ttt(Pt,Y,L,G,we,Ie,Te);_.fontScale=att(ns,_.textScaleFactor);const xs=Pt.getUnevaluatedLayoutProperty("text-size");let us=this.textSizeData,hs=rt,pn=xt;Pt.hasLayoutProperty("text-size")&&(us=CM(this.zoom,xs,this.worldview,ut),hs=this.textSizeData.kind==="composite"?this.textSizeData.minZoom:0,pn=this.textSizeData.kind==="composite"?this.textSizeData.maxZoom:0);const bn=_.textShaping.bottom-we[1],An=_.textShaping.left-we[0],Ln=_.textShaping.right-we[0];_.textShaping.top=Rt[1]+(_.textShaping.top-we[1]),_.textShaping.bottom=Rt[1]+bn,_.textShaping.left=Rt[0]+An,_.textShaping.right=Rt[0]+Ln;const En=Qet(0,_.textShaping,Rt,Y,!1,L,me,this.allowVerticalPlacement,ws),Jn=ns&&us.kind==="composite"?xs.possiblyEvaluate(new Si(hs,{}),G).evaluate(L,ye,G):Ve,un=ns&&us.kind==="composite"?xs.possiblyEvaluate(new Si(pn,{}),G).evaluate(L,ye,G):Je,Mn=dMe(Pt.name,us,ns,re,Jn,un),Rn=Array.isArray(Mn)?Mn[1]:ns,er=0,ur=1+(Math.min(AM,Math.round(Rn*p4))<<1);_.isUsingAppearanceTextVertexData||(_.isUsingAppearanceTextVertexData=!0,_.layoutBasedTextVertexData=this.text.snapshotSymbolVertexData(O,f.numHorizontalGlyphVertices+f.numVerticalGlyphVertices));for(let Zr=0;Zr0){const re=new Set(Object.keys(f).map(me=>{const ye=Number(me);return!isNaN(ye)&&Number.isSafeInteger(ye)&&String(ye)===me?ye:me}));this.text.uboBinder&&this.text.uboBinder.updateFeatures(re,O[0],_,Y,S,f,G),this.icon.uboBinder&&this.icon.uboBinder.updateFeatures(re,O[0],_,Y,S,f,G)}}}updateRoadElevation(f){if(this.elevationType!=="road"||!this.elevationFeatures||this.elevationStateComplete)return;this.elevationStateComplete=!0,this.hasAnyZOffset=!1;let _=!1;const S=Bn(f),L=1/S;let O=!1,z=!1;for(let G=0;G0||we>0,Je=Te>0,rt=this.elevationFeatures[Y.elevationFeatureIndex];if(rt){const xt=new Xt(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,L),Pt=Ds(ft(),Q(0,0,1),St);Re(re,re,Pt),Re(me,me,Pt),re[2]*=S,me[2]*=S,re[0]===1&&re[1]===0&&re[2]===0&&me[0]===0&&me[1]===1&&me[2]===0||(O=O||Ve,z=z||Je)}if(Ve&&(_se(this.text.orientationVertexArray,ye,re,me),_se(this.text.orientationVertexArray,we,re,me)),Je){const{placedIconSymbolIndex:xt,verticalPlacedIconSymbolIndex:ut}=Y;xt>=0&&_se(this.icon.orientationVertexArray,Te,re,me),ut>=0&&_se(this.icon.orientationVertexArray,Ie,re,me)}}O||(this.text.orientationVertexArray=void 0),z||(this.icon.orientationVertexArray=void 0),_&&(this.zOffsetBuffersNeedUpload=!0,this.zOffsetSortDirty=!0)}updateZOffset(){const f=(O,z,G)=>{S+=z,S>O.length&&O.resize(S);for(let Y=-z;Y<0;Y++)O.emplace(Y+S,G)},_=(O,z,G)=>{L+=z,L>O.length&&O.resize(L);for(let Y=-z;Y<0;Y++)O.emplace(Y+L,G)};if(!this.zOffsetBuffersNeedUpload)return;this.zOffsetBuffersNeedUpload=!1;let S=0,L=0;for(let O=0;O0;if((G>0||Y>0)&&(f(this.text.zOffsetVertexArray,G,me),f(this.text.zOffsetVertexArray,Y,me)),ye){const{placedIconSymbolIndex:we,verticalPlacedIconSymbolIndex:Te}=z;we>=0&&_(this.icon.zOffsetVertexArray,re,me),Te>=0&&_(this.icon.zOffsetVertexArray,z.numVerticalIconVertices,me)}}this.text.zOffsetVertexBuffer&&this.text.zOffsetVertexBuffer.updateData(this.text.zOffsetVertexArray),this.icon.zOffsetVertexBuffer&&this.icon.zOffsetVertexBuffer.updateData(this.icon.zOffsetVertexArray)}isEmpty(){return this.symbolInstances.length===0&&!this.hasRTLText}uploadPending(){return!this.uploaded||this.text.programConfigurations.needsUpload||this.icon.programConfigurations.needsUpload}upload(f,_,S,L,O){!this.uploaded&&this.hasDebugData()&&(this.textCollisionBox.upload(f),this.iconCollisionBox.upload(f)),this.text.upload(f,this.sortFeaturesByY,!this.uploaded,this.text.programConfigurations.needsUpload,this.zOffsetBuffersNeedUpload,this.hasAppearances),this.hasAppearances===null&&(this.hasAppearances=this.layers.some(z=>z.appearances&&z.appearances.length>0)),this.icon.upload(f,this.sortFeaturesByY,!this.uploaded,this.icon.programConfigurations.needsUpload,this.zOffsetBuffersNeedUpload,this.hasAppearances),this.uploaded=!0}updateAppearances(f,_,S,L,O,z=!1){const G={hasLayoutChanges:!1,hasUboChanges:!1};if(!f||!S||!this.featureAppearanceData)return G;const Y=_||{},re=this.icon.layoutVertexArray&&this.icon.layoutVertexArray.length>0&&this.icon.layoutVertexArray.arrayBuffer,me=this.text.layoutVertexArray&&this.text.layoutVertexArray.length>0&&this.text.layoutVertexArray.arrayBuffer;if(!re&&!me)return G;const ye=this.layers[0],we=ye.layout;this.featureAppearances&&this.featureAppearances.appearancesVersion===ye.appearancesVersion||(this.featureAppearances=new uXt(ye.appearances,ye.appearancesVersion));const Te=this.featureAppearances.update(L,z);if(Te.kind==="no-changes")return G;let Ie=1,Ve=0,Je=!1,rt=!1;if(re){const[Rt,ws]=we.get("icon-size-scale-range");Ie=pt(1,Rt,ws)}let xt=1,ut=0,St=!1;if(me){const[Rt,ws]=we.get("text-size-scale-range");xt=pt(1,Rt,ws)}const Pt=new Map;if(O&&S)for(const Rt of S){const ws=O.getImage(Rt,ye.scope);if(ws){const ns=new wd(Rt.toString());Pt.set(ns.toString(),ws)}}for(let Rt=0;RtLn.isActive({globals:L,feature:hs,canonical:f,featureState:us})):-1;pn=An>=0?An:-1}const bn=ns.activeAppearanceIndex!==pn;if(me){const An=we.get("text-size"),Ln=this.textSizeData.kind==="composite"?this.textSizeData.minZoom:0,En=this.textSizeData.kind==="composite"?this.textSizeData.maxZoom:0,Jn={canonical:f,layer:ye,featureState:us,availableImages:S,textScaleFactor:xt,imageMap:Pt,layoutTextOffset:we.get("text-offset").evaluate(hs,us,f).map(Mn=>Mn*Bm),layoutTextSize:An.evaluate(hs,us,f),layoutTextRotate:we.get("text-rotate").evaluate(hs,us,f),layoutMinZoomSize:An.evaluate(hs,{zoom:Ln},f),layoutMaxZoomSize:An.evaluate(hs,{zoom:En},f),layoutTextSizeMinZoom:Ln,layoutTextSizeMaxZoom:En},un=this.updateSymbolInstanceTextVertices(ws,ns,pn,hs,ut,Jn);ut+=un.vertexOffsetDelta,St=St||un.hasChanges}if(re){const An={canonical:f,layer:ye,featureState:us,availableImages:S,globalProperties:L,iconScaleFactor:Ie,layoutIconOffset:we.get("icon-offset").evaluate(hs,us,f),layoutIconSize:we.get("icon-size").evaluate(hs,us,f,S),layoutIconRotate:we.get("icon-rotate").evaluate(hs,us,f)},Ln=this.updateSymbolInstanceIconVertices(ws,ns,pn,hs,Ve,An);Ve+=Ln.vertexOffsetDelta,Je=Je||Ln.hasChanges}if(bn){const An=ws.featureIndex,Ln=L?L.brightness:null,En=us||{},Jn=pn>=0?ye.appearances[pn]:null;this.text.uboBinder&&(this.text.uboBinder.layer=ye,rt=this.text.uboBinder.updateFeaturePaintForAppearance(An,hs,En,f,S,Ln,Jn)||rt),this.icon.uboBinder&&(this.icon.uboBinder.layer=ye,rt=this.icon.uboBinder.updateFeaturePaintForAppearance(An,hs,En,f,S,Ln,Jn)||rt)}ns.activeAppearanceIndex=pn}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=mtt(this.projection)),this.projectionInstance}destroy(){this.text.destroy(),this.icon.destroy(),this.hasDebugData()&&this.destroyDebugData()}addToLineVertexArray(f,_){const S=this.lineVertexArray.length;if(f.segment!==void 0)for(const{x:L,y:O}of _)this.lineVertexArray.emplaceBack(L,O);return{lineStartIndex:S,lineLength:this.lineVertexArray.length-S}}addSymbols(f,_,S,L,O,z,G,Y,re,me,ye,we,Te,Ie,Ve,Je,rt,xt){const ut=f.indexArray,St=f.layoutVertexArray,Pt=f.globeExtVertexArray,Rt=xt,ws=f.uboBinder?f.uboBinder.getCurrentBatchIndex():void 0,ns=f.segments.prepareSegment(4*Rt,St,ut,this.canOverlap?z.sortKey:void 0,ws),xs=this.glyphOffsetArray.length,us=ns.vertexLength,hs=this.allowVerticalPlacement&&G===Fv.vertical?Math.PI/2:0,pn=z.text&&z.text.sections;let bn=St.length,An=-1;for(let Jn=0;Jn<_.length;Jn++){const{tl:un,tr:Mn,bl:Rn,br:er,texPrimary:ur,texSecondary:Zr,pixelOffsetTL:Nr,pixelOffsetBR:wr,minFontScaleX:hr,minFontScaleY:Gr,glyphOffset:aa,isSDF:Da,sectionIndex:_a}=_[Jn],_i=ns.vertexLength,To=aa[1];if(NH(St,re.x,re.y,un.x,To+un.y,ur.x,ur.y,S,Da,Nr.x,Nr.y,hr,Gr),NH(St,re.x,re.y,Mn.x,To+Mn.y,ur.x+ur.w,ur.y,S,Da,wr.x,Nr.y,hr,Gr),NH(St,re.x,re.y,Rn.x,To+Rn.y,ur.x,ur.y+ur.h,S,Da,Nr.x,wr.y,hr,Gr),NH(St,re.x,re.y,er.x,To+er.y,ur.x+ur.w,ur.y+ur.h,S,Da,wr.x,wr.y,hr,Gr),Y){const{x:wi,y:Do,z:Ui}=Y.anchor,[Od,ll,$o]=Y.up;SH(Pt,wi,Do,Ui,Od,ll,$o),SH(Pt,wi,Do,Ui,Od,ll,$o),SH(Pt,wi,Do,Ui,Od,ll,$o),SH(Pt,wi,Do,Ui,Od,ll,$o),YF(f.dynamicLayoutVertexArray,wi,Do,Ui,hs)}else YF(f.dynamicLayoutVertexArray,re.x,re.y,re.z,hs);if(Je){const wi=Zr||ur;kH(f.iconTransitioningVertexArray,wi.x,wi.y),kH(f.iconTransitioningVertexArray,wi.x+wi.w,wi.y),kH(f.iconTransitioningVertexArray,wi.x,wi.y+wi.h),kH(f.iconTransitioningVertexArray,wi.x+wi.w,wi.y+wi.h)}if(ut.emplaceBack(_i,_i+1,_i+2),ut.emplaceBack(_i+1,_i+2,_i+3),ns.vertexLength+=4,ns.primitiveLength+=2,this.glyphOffsetArray.emplaceBack(aa[0]),(Jn===_.length-1||_a!==_[Jn+1].sectionIndex)&&(f.programConfigurations.populatePaintArrays(St.length,z,z.index,{},Te,Ie,Ve,pn&&pn[_a],this.worldview),f.uboBinder&&f.featureIdArray)){const wi=f.uboBinder.populateUBO(z,z.index,Ie,Te,Ve,pn&&pn[_a],void 0);An=wi;const Do=St.length-bn;for(let Ui=0;Ui=0)){const Jn=4*Ln;for(let un=0;un=0?_.rightJustifiedTextSymbolIndex:_.centerJustifiedTextSymbolIndex>=0?_.centerJustifiedTextSymbolIndex:_.leftJustifiedTextSymbolIndex>=0?_.leftJustifiedTextSymbolIndex:_.verticalPlacedTextSymbolIndex>=0?_.verticalPlacedTextSymbolIndex:L),z=eMe(this.textSizeData,f,O)/Bm;return this.tilePixelRatio*z}getSymbolInstanceIconSize(f,_,S){const L=this.icon.placedSymbolArray.get(S),O=eMe(this.iconSizeData,f,L);return this.tilePixelRatio*O}_commitDebugCollisionVertexUpdate(f,_,S,L){f.emplaceBack(_,-S,-S,L),f.emplaceBack(_,S,-S,L),f.emplaceBack(_,S,S,L),f.emplaceBack(_,-S,S,L)}_updateTextDebugCollisionBoxes(f,_,S,L,O,z,G){for(let Y=L;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(f,_){const S=f.placedSymbolArray.get(_),L=S.vertexStartIndex+4*S.numGlyphs;for(let O=S.vertexStartIndex;OL[G]-L[Y]||O[Y]-O[G]),z}getSortedIndexesByZOffset(){if(!this.zOffsetSortDirty)return this.symbolInstanceIndexesSortedZOffset;if(!this.symbolInstanceIndexesSortedZOffset){this.symbolInstanceIndexesSortedZOffset=[];for(let f=0;fthis.symbolInstances.get(_).zOffset-this.symbolInstances.get(f).zOffset)}addToSortKeyRanges(f,_){const S=this.sortKeyRanges[this.sortKeyRanges.length-1];S&&S.sortKey===_?S.symbolInstanceEnd=f+1:this.sortKeyRanges.push({sortKey:_,symbolInstanceStart:f,symbolInstanceEnd:f+1})}sortFeatures(f){if(this.sortFeaturesByY&&this.sortedAngle!==f)if(this.text.segments.get().length>1||this.icon.segments.get().length>1)this.sortFeaturesWithinSegments();else{this.symbolInstanceIndexes=this.getSortedSymbolIndexes(f),this.sortedAngle=f,this.text.indexArray.clear(),this.icon.indexArray.clear(),this.featureSortOrder=[];for(const _ of this.symbolInstanceIndexes){const S=this.symbolInstances.get(_);this.featureSortOrder.push(S.featureIndex);const{rightJustifiedTextSymbolIndex:L,centerJustifiedTextSymbolIndex:O,leftJustifiedTextSymbolIndex:z,verticalPlacedTextSymbolIndex:G,placedIconSymbolIndex:Y,verticalPlacedIconSymbolIndex:re}=S;L>=0&&this.addIndicesForPlacedSymbol(this.text,L),O>=0&&O!==L&&this.addIndicesForPlacedSymbol(this.text,O),z>=0&&z!==O&&z!==L&&this.addIndicesForPlacedSymbol(this.text,z),G>=0&&this.addIndicesForPlacedSymbol(this.text,G),Y>=0&&this.addIndicesForPlacedSymbol(this.icon,Y),re>=0&&this.addIndicesForPlacedSymbol(this.icon,re)}this.text.indexBuffer&&this.text.indexBuffer.updateData(this.text.indexArray),this.icon.indexBuffer&&this.icon.indexBuffer.updateData(this.icon.indexArray)}}getOrCreateSortedSymbolsByBatch(f,_){const S=(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 L of this.symbolsByBatch.values())for(const O of L){const z=this.symbolInstances.get(O.index);O.rotatedY=0|Math.round(f*z.tileAnchorX+_*z.tileAnchorY)}else{this.symbolsByBatch=new Map;for(let L=0;LO.rotatedY-z.rotatedY||z.featureIndex-O.featureIndex);return this.symbolsByBatch}rebuildTextSegmentIndices(f,_){for(const S of f){const L=S.batchIndex;if(L===void 0)continue;const O=_.get(L);if(!O){S.primitiveOffset=this.text.indexArray.length,S.primitiveLength=0;continue}S.primitiveOffset=this.text.indexArray.length;const z=this.text.indexArray.length;for(const{index:G}of O){const Y=this.symbolInstances.get(G),{rightJustifiedTextSymbolIndex:re,centerJustifiedTextSymbolIndex:me,leftJustifiedTextSymbolIndex:ye,verticalPlacedTextSymbolIndex:we}=Y;re>=0&&this.addIndicesForPlacedSymbol(this.text,re),me>=0&&me!==re&&this.addIndicesForPlacedSymbol(this.text,me),ye>=0&&ye!==me&&ye!==re&&this.addIndicesForPlacedSymbol(this.text,ye),we>=0&&this.addIndicesForPlacedSymbol(this.text,we)}S.primitiveLength=this.text.indexArray.length-z}}rebuildIconSegmentIndices(f,_){for(const S of f){const L=S.batchIndex;if(L===void 0)continue;const O=_.get(L);if(!O){S.primitiveOffset=this.icon.indexArray.length,S.primitiveLength=0;continue}S.primitiveOffset=this.icon.indexArray.length;const z=this.icon.indexArray.length;for(const{index:G}of O){const Y=this.symbolInstances.get(G),{placedIconSymbolIndex:re,verticalPlacedIconSymbolIndex:me}=Y;re>=0&&this.addIndicesForPlacedSymbol(this.icon,re),me>=0&&this.addIndicesForPlacedSymbol(this.icon,me)}S.primitiveLength=this.icon.indexArray.length-z}}sortFeaturesWithinSegments(){this.featureSortOrder=[];const f=Math.sin(this.sortedAngle),_=Math.cos(this.sortedAngle),S=this.getOrCreateSortedSymbolsByBatch(f,_),L=Array.from(S.keys()).sort((O,z)=>O-z);for(const O of L){const z=S.get(O);for(const{index:G}of z){const Y=this.symbolInstances.get(G);this.featureSortOrder.push(Y.featureIndex)}}this.text.indexArray.clear(),this.icon.indexArray.clear(),this.rebuildTextSegmentIndices(this.text.segments.get(),S),this.rebuildIconSegmentIndices(this.icon.segments.get(),S),this.text.indexBuffer&&this.text.indexBuffer.updateData(this.text.indexArray),this.icon.indexBuffer&&this.icon.indexBuffer.updateData(this.icon.indexArray)}getElevationFeatureForText(f){const _=this.symbolInstances.get(this.text.symbolInstanceIndices[f]).elevationFeatureIndex;let S;return this.elevationFeatures&&_S in k?String(k[S]):"")}let ftt,xtt,pMe;br(D2,"SymbolBucket",{omit:["layers","collisionBoxArray","compareText","features"]}),D2.addDynamicAttributes=YF;class gtt{constructor(f){this.type=f.property.overrides?f.property.overrides.runtimeType:Ua,this.defaultValue=f}evaluate(f){if(f.formattedSection){const _=this.defaultValue.property.overrides;if(_&&_.hasOverride(f.formattedSection))return _.getOverride(f.formattedSection)}return f.feature&&f.featureState?this.defaultValue.evaluate(f.feature,f.featureState):this.defaultValue.property.specification.default}eachChild(f){this.defaultValue.isConstant()||f(this.defaultValue.value._styleExpression.expression)}outputDefined(){return!1}serialize(){return null}}br(gtt,"FormatSectionOverride",{omit:["defaultValue"]});const fMe=()=>pMe||(pMe={layout:ftt||(ftt=new bc({"symbol-placement":new ir($s.layout_symbol["symbol-placement"]),"symbol-spacing":new ir($s.layout_symbol["symbol-spacing"]),"symbol-avoid-edges":new ir($s.layout_symbol["symbol-avoid-edges"]),"symbol-sort-key":new ar($s.layout_symbol["symbol-sort-key"]),"symbol-z-order":new ir($s.layout_symbol["symbol-z-order"]),"symbol-z-elevate":new ir($s.layout_symbol["symbol-z-elevate"]),"symbol-elevation-reference":new ir($s.layout_symbol["symbol-elevation-reference"]),"icon-allow-overlap":new ir($s.layout_symbol["icon-allow-overlap"]),"icon-ignore-placement":new ir($s.layout_symbol["icon-ignore-placement"]),"icon-optional":new ir($s.layout_symbol["icon-optional"]),"icon-rotation-alignment":new ir($s.layout_symbol["icon-rotation-alignment"]),"icon-size":new ar($s.layout_symbol["icon-size"]),"icon-size-scale-range":new ir($s.layout_symbol["icon-size-scale-range"]),"icon-text-fit":new ar($s.layout_symbol["icon-text-fit"]),"icon-text-fit-padding":new ar($s.layout_symbol["icon-text-fit-padding"]),"icon-image":new ar($s.layout_symbol["icon-image"]),"icon-image-use-theme":new ir({type:"string",default:"default","property-type":"data-constant"}),"icon-rotate":new ar($s.layout_symbol["icon-rotate"]),"icon-padding":new ir($s.layout_symbol["icon-padding"]),"icon-keep-upright":new ir($s.layout_symbol["icon-keep-upright"]),"icon-offset":new ar($s.layout_symbol["icon-offset"]),"icon-anchor":new ar($s.layout_symbol["icon-anchor"]),"icon-pitch-alignment":new ir($s.layout_symbol["icon-pitch-alignment"]),"text-pitch-alignment":new ir($s.layout_symbol["text-pitch-alignment"]),"text-rotation-alignment":new ir($s.layout_symbol["text-rotation-alignment"]),"text-field":new ar($s.layout_symbol["text-field"]),"text-font":new ar($s.layout_symbol["text-font"]),"text-size":new ar($s.layout_symbol["text-size"]),"text-size-scale-range":new ir($s.layout_symbol["text-size-scale-range"]),"text-max-width":new ar($s.layout_symbol["text-max-width"]),"text-line-height":new ar($s.layout_symbol["text-line-height"]),"text-letter-spacing":new ar($s.layout_symbol["text-letter-spacing"]),"text-justify":new ar($s.layout_symbol["text-justify"]),"text-radial-offset":new ar($s.layout_symbol["text-radial-offset"]),"text-variable-anchor":new ir($s.layout_symbol["text-variable-anchor"]),"text-anchor":new ar($s.layout_symbol["text-anchor"]),"text-max-angle":new ir($s.layout_symbol["text-max-angle"]),"text-writing-mode":new ir($s.layout_symbol["text-writing-mode"]),"text-rotate":new ar($s.layout_symbol["text-rotate"]),"text-padding":new ir($s.layout_symbol["text-padding"]),"text-keep-upright":new ir($s.layout_symbol["text-keep-upright"]),"text-transform":new ar($s.layout_symbol["text-transform"]),"text-offset":new ar($s.layout_symbol["text-offset"]),"text-allow-overlap":new ir($s.layout_symbol["text-allow-overlap"]),"text-ignore-placement":new ir($s.layout_symbol["text-ignore-placement"]),"text-optional":new ir($s.layout_symbol["text-optional"]),visibility:new ir($s.layout_symbol.visibility)})),paint:xtt||(xtt=new bc({"icon-opacity":new ar($s.paint_symbol["icon-opacity"]),"icon-occlusion-opacity":new ar($s.paint_symbol["icon-occlusion-opacity"]),"icon-emissive-strength":new ar($s.paint_symbol["icon-emissive-strength"]),"text-emissive-strength":new ar($s.paint_symbol["text-emissive-strength"]),"icon-color":new ar($s.paint_symbol["icon-color"]),"icon-halo-color":new ar($s.paint_symbol["icon-halo-color"]),"icon-halo-width":new ar($s.paint_symbol["icon-halo-width"]),"icon-halo-blur":new ar($s.paint_symbol["icon-halo-blur"]),"icon-translate":new ir($s.paint_symbol["icon-translate"]),"icon-translate-anchor":new ir($s.paint_symbol["icon-translate-anchor"]),"icon-image-cross-fade":new ir($s.paint_symbol["icon-image-cross-fade"]),"text-opacity":new ar($s.paint_symbol["text-opacity"]),"text-occlusion-opacity":new ar($s.paint_symbol["text-occlusion-opacity"]),"text-color":new ar($s.paint_symbol["text-color"],{runtimeType:Ho,getOverride:k=>k.textColor,hasOverride:k=>!!k.textColor}),"text-halo-color":new ar($s.paint_symbol["text-halo-color"]),"text-halo-width":new ar($s.paint_symbol["text-halo-width"]),"text-halo-blur":new ar($s.paint_symbol["text-halo-blur"]),"text-translate":new ir($s.paint_symbol["text-translate"]),"text-translate-anchor":new ir($s.paint_symbol["text-translate-anchor"]),"icon-color-saturation":new ir($s.paint_symbol["icon-color-saturation"]),"icon-color-contrast":new ir($s.paint_symbol["icon-color-contrast"]),"icon-color-brightness-min":new ir($s.paint_symbol["icon-color-brightness-min"]),"icon-color-brightness-max":new ir($s.paint_symbol["icon-color-brightness-max"]),"symbol-z-offset":new ar($s.paint_symbol["symbol-z-offset"]),"icon-color-use-theme":new ar({type:"string",default:"default","property-type":"data-driven"}),"icon-halo-color-use-theme":new ar({type:"string",default:"default","property-type":"data-driven"}),"text-color-use-theme":new ar({type:"string",default:"default","property-type":"data-driven"}),"text-halo-color-use-theme":new ar({type:"string",default:"default","property-type":"data-driven"})}))},pMe);class wse extends Cl{constructor(f,_,S,L){super(f,fMe(),_,S,L,f.layout?f.layout["icon-image-use-theme"]:null),this._colorAdjustmentMatrix=y([]),this.hasOcclusionOpacityProperties=f.paint!==void 0&&("icon-occlusion-opacity"in f.paint||"text-occlusion-opacity"in f.paint)}_handleSpecialPaintPropertyUpdate(f){f!=="icon-occlusion-opacity"&&f!=="text-occlusion-opacity"||(this.hasOcclusionOpacityProperties=!0)}recalculate(f,_){super.recalculate(f,_),this.appearances&&this.appearances.forEach(L=>{L.recalculate(f,_,this.iconImageUseTheme)}),this.layout.get("icon-rotation-alignment")==="auto"&&(this.layout._values["icon-rotation-alignment"]=this.layout.get("symbol-placement")!=="point"?"map":"viewport"),this.layout.get("text-rotation-alignment")==="auto"&&(this.layout._values["text-rotation-alignment"]=this.layout.get("symbol-placement")!=="point"?"map":"viewport"),this.layout.get("text-pitch-alignment")==="auto"&&(this.layout._values["text-pitch-alignment"]=this.layout.get("text-rotation-alignment")),this.layout.get("icon-pitch-alignment")==="auto"&&(this.layout._values["icon-pitch-alignment"]=this.layout.get("icon-rotation-alignment"));const S=this.layout.get("text-writing-mode");if(S){const L=[];for(const O of S)L.indexOf(O)<0&&L.push(O);this.layout._values["text-writing-mode"]=L}else this.layout._values["text-writing-mode"]=this.layout.get("symbol-placement")==="point"?["horizontal"]:["horizontal","vertical"];this._setPaintOverrides()}getColorAdjustmentMatrix(f,_,S,L){return this._saturation===f&&this._contrast===_&&this._brightnessMin===S&&this._brightnessMax===L||(this._colorAdjustmentMatrix=function(O,z,G,Y){O=zr(O),z=is(z);const re=x(),me=O/3,ye=1-2*me,we=[ye,me,me,0,me,ye,me,0,me,me,ye,0,0,0,0,1],Te=.5-.5*z,Ie=Y-G;return v(re,[Ie,0,0,0,0,Ie,0,0,0,0,Ie,0,G,G,G,1],[z,0,0,0,0,z,0,0,0,0,z,0,Te,Te,Te,1]),v(re,re,we),re}(f,_,S,L),this._saturation=f,this._contrast=_,this._brightnessMin=S,this._brightnessMax=L),this._colorAdjustmentMatrix}getValueAndResolveTokens(f,_,S,L){const O=this.layout.get(f).evaluate(_,{},S,L),z=this._unevaluatedLayout._values[f];return z.isDataDriven()||Im(z.value)||!O?O:ptt(_.properties,O)}getAppearanceValueAndResolveTokens(f,_,S,L,O){const z=f.getLayoutProperty(_);if(!z)return;const G=z.evaluate(S,{},L,O),Y=f.getUnevaluatedLayoutProperties()._values[_];return Y.isDataDriven()||Im(Y.value)||!G||typeof G!="string"?G:ptt(S.properties,G)}createBucket(f){return new D2(f)}queryRadius(){return 0}queryIntersectsFeature(){return!1}_setPaintOverrides(){for(const f of fMe().paint.overridableProperties){if(!wse.hasPaintOverride(this.layout,f))continue;const _=this.paint.get(f),S=new gtt(_),L=new Iu(S,_.property.specification,this.scope,this.options,this.layout.get("icon-image-use-theme"));let O=null;O=_.value.kind==="constant"||_.value.kind==="source"?new th("source",L):new Xl("composite",L,_.value.zoomStops,_.value.interpolationType),this.paint._values[f]=new E2(_.property,O,_.parameters)}}_handleOverridablePaintPropertyUpdate(f,_,S){return!(!this.layout||_.isDataDriven()||S.isDataDriven())&&wse.hasPaintOverride(this.layout,f)}static hasPaintOverride(f,_){const S=f.get("text-field"),L=fMe().paint.properties[_];let O=!1;const z=G=>{for(const Y of G)if(L.overrides&&L.overrides.hasOverride(Y))return void(O=!0)};if(S.value.kind==="constant"&&S.value.value instanceof cd)z(S.value.value.sections);else if(S.value.kind==="source"){const G=re=>{O||(re instanceof qr&&kl(re.value)===zg?z(re.value.sections):re instanceof dd?z(re.sections):re.eachChild(G))},Y=S.value;Y._styleExpression&&G(Y._styleExpression.expression)}return O}getProgramIds(){return["symbol"]}getDefaultProgramParams(f,_,S){return{config:new He(this,{zoom:_,lut:S}),overrideFog:!1}}hasElevation(){return this.layout&&this.layout.get("symbol-elevation-reference")==="hd-road-markup"}}let ytt,vtt,btt,_tt;var jse=zn([{name:"a_pos",type:"Int16",components:2},{name:"a_texture_pos",type:"Uint16",components:2}]);function Nse(k,f,_,S,L,O,z,G){const Y=[k,f,1,_,S,1,L,O,1],re=[z,G,1],me=m([],Y),[ye,we,Te]=Se(re,re,me);return p(Y,Y,[ye,0,0,0,we,0,0,0,Te])}function wtt(k,f,_,S,L,O,z,G){const Y=function(re,me,ye,we,Te,Ie,Ve,Je){const rt=Nse(0,0,1,0,1,1,0,1),xt=Nse(re,me,ye,we,Te,Ie,Ve,Je);return p(xt,xt,m([],rt))}(k,f,_,S,L,O,z,G);return[Y[2]/Y[8]/lr,Y[5]/Y[8]/lr]}function kse(k){return[k[0],Math.min(Math.max(k[1],-85.051129),kn)]}class jtt extends om{constructor(f,_,S,L){super(),this.id=f,this.dispatcher=S,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(L),this.options=_,this._dirty=!1}load(f,_){if(this._loaded=_||!1,this.fire(new Oc("dataloading",{dataType:"source"})),this.url=this.options.url,!this.url)return f&&(this.coordinates=f),this._loaded=!0,void this._finishLoading();this._imageRequest=am(this.map._requestManager.transformRequest(this.url,lp.Image),(S,L)=>{this._imageRequest=null,this._loaded=!0,S?this.fire(new cp(S)):L&&(this.image=L,this._dirty=!0,this.width=this.image.width,this.height=this.image.height,f&&(this.coordinates=f),this._finishLoading())})}loaded(){return this._loaded}updateImage(f){return f.url?(this._imageRequest&&f.url!==this.options.url&&(this._imageRequest.cancel(),this._imageRequest=null),this.options.url=f.url,this.load(f.coordinates,this._loaded),this):this}setTexture(f){if(!(f.handle instanceof WebGLTexture))throw new Error("The provided handle is not a WebGLTexture instance");return this.texture=new uH(this.map.painter.context,f.handle),this.width=f.dimensions[0],this.height=f.dimensions[1],this._dirty=!1,this._loaded=!0,this._finishLoading(),this}_finishLoading(){this.map&&(this.setCoordinates(this.coordinates),this.fire(new Oc("data",{dataType:"source",sourceDataType:"metadata"})))}onAdd(f){this.map=f,this.load()}onRemove(f){this._imageRequest&&(this._imageRequest.cancel(),this._imageRequest=null),!this.texture||this.texture instanceof uH||this.texture.destroy(),this.boundsBuffer&&(this.boundsBuffer.destroy(),this.elevatedGlobeVertexBuffer&&this.elevatedGlobeVertexBuffer.destroy(),this.elevatedGlobeIndexBuffer&&this.elevatedGlobeIndexBuffer.destroy())}setCoordinates(f){if(this.coordinates=f,this._boundsArray=void 0,this._unsupportedCoords=!1,!f.length)return this;this.onNorthPole=!1,this.onSouthPole=!1;let _=f[0][1],S=f[0][1];for(const O of f)O[1]>S&&(S=O[1]),O[1]<_&&(_=O[1]);const L=(S+_)/2;if(L>kn?this.onNorthPole=!0:L<-85.051129&&(this.onSouthPole=!0),!this.onNorthPole&&!this.onSouthPole){const O=f.map(ra.fromLngLat);this.tileID=function(z){let G=1/0,Y=1/0,re=-1/0,me=-1/0;for(const Ve of z)G=Math.min(G,Ve.x),Y=Math.min(Y,Ve.y),re=Math.max(re,Ve.x),me=Math.max(me,Ve.y);const ye=Math.max(re-G,me-Y),we=Math.max(0,Math.floor(-Math.log2(ye))),Te=Math.pow(2,we);let Ie=Math.floor((G+re)/2*Te);return Ie>1&&(Ie-=1),new wM(we,Ie,Math.floor((Y+me)/2*Te))}(O),this.minzoom=this.maxzoom=this.tileID.z}return this.fire(new Oc("data",{dataType:"source",sourceDataType:"content"})),this}_clear(){!this.texture||this.texture instanceof uH||(this.texture.destroy(),this._dirty=!0),this.texture=null,this._boundsArray=void 0,this._unsupportedCoords=!1}_prepareData(f){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 _=EM(new wM(0,0,0),this.map.transform.projection),S=[_.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,Pt=Je[3].x-Je[2].x,Rt=Je[3].y-Je[2].y,ws=Je[0].x-Je[3].x,ns=Je[0].y-Je[3].y,xs=rt*St-ut*xt,us=ut*Rt-Pt*St,hs=Pt*ns-ws*Rt,pn=ws*xt-rt*ns;return xs>0&&us>0&&hs>0&&pn>0||xs<0&&us<0&&hs<0&&pn<0}(S))return console.warn("Image source coordinates are defining non-convex area in the Mercator projection"),void(this._unsupportedCoords=!0);const L=EM(this.tileID,this.map.transform.projection),[O,z,G,Y]=this.coordinates.map(Je=>{const rt=L.projection.project(Je[0],Je[1]);return ltt(L,rt)._round()});this.perspectiveTransform=wtt(O.x,O.y,z.x,z.y,G.x,G.y,Y.x,Y.y);const re=this._boundsArray=new so;re.emplaceBack(O.x,O.y,0,0),re.emplaceBack(z.x,z.y,lr,0),re.emplaceBack(Y.x,Y.y,0,lr),re.emplaceBack(G.x,G.y,lr,lr),this.boundsBuffer&&(this.boundsBuffer.destroy(),this.elevatedGlobeVertexBuffer&&this.elevatedGlobeVertexBuffer.destroy(),this.elevatedGlobeIndexBuffer&&this.elevatedGlobeIndexBuffer.destroy()),this.boundsBuffer=f.createVertexBuffer(re,jse.members),this.boundsSegments=sc.simpleSegment(0,0,4,2);const me=[],ye=function(Je){return[kse(Je[0]),kse(Je[1]),kse(Je[2]),kse(Je[3])]}(this.coordinates),[we,Te,Ie,Ve]=function(Je){let rt=Je[0][0],xt=rt,ut=Je[0][1],St=ut;for(let Pt=1;Ptxt&&(xt=Je[Pt][0]),Je[Pt][1]St&&(St=Je[Pt][1]);return[rt,ut,xt-rt,St-ut]}(ye);{const Je=new so,[rt,xt,ut,St]=function(En){let Jn=En[0].x,un=Jn,Mn=En[0].y,Rn=Mn;for(let er=1;erun&&(un=En[er].x),En[er].yRn&&(Rn=En[er].y);return[Jn,Mn,un-Jn,Rn-Mn]}(S),Pt=En=>[(En.x-rt)/ut,(En.y-xt)/St],[Rt,ws,ns,xs]=S.map(Pt),us=function(En,Jn,un,Mn,Rn,er,ur,Zr){const Nr=Nse(0,0,1,0,1,1,0,1);return p(Nr,Nr,m([],Nse(En,Jn,un,Mn,Rn,er,ur,Zr)))}(Rt[0],Rt[1],ws[0],ws[1],ns[0],ns[1],xs[0],xs[1]);this.elevatedGlobePerspectiveTransform=wtt(Rt[0],Rt[1],ws[0],ws[1],ns[0],ns[1],xs[0],xs[1]);const hs=(En,Jn)=>{me.push(En.lng);const un=Math.round((En.lng-we)/Ie*lr),Mn=Math.round((En.lat-Te)/Ve*lr),Rn=Pt(Jn),er=Se([],[Rn[0],Rn[1],1],us),ur=Math.round(er[0]/er[2]*lr),Zr=Math.round(er[1]/er[2]*lr);Je.emplaceBack(un,Mn,ur,Zr)},pn=S[3].x-S[0].x,bn=S[3].y-S[0].y,An=S[2].x-S[1].x,Ln=S[2].y-S[1].y;for(let En=0;En<65;En++){const Jn=En/64,un=[S[0].x+Jn*pn,S[0].y+Jn*bn],Mn=[S[1].x+Jn*An,S[1].y+Jn*Ln],Rn=Mn[0]-un[0],er=Mn[1]-un[1];for(let ur=0;ur<65;ur++){const Zr=ur/64,Nr={x:un[0]+Rn*Zr,y:un[1]+er*Zr};hs(_.projection.unproject(Nr.x,Nr.y),Nr)}}this.elevatedGlobeVertexBuffer=f.createVertexBuffer(Je,jse.members)}{this.maxLongitudeTriangleSize=0;let Je=[],rt=new nu;const xt=(ut,St,Pt)=>{rt.emplaceBack(ut,St,Pt);const Rt=me[ut],ws=me[St],ns=me[Pt],xs=Math.min(Math.min(Rt,ws),ns),us=Math.max(Math.max(Rt,ws),ns)-xs;us>this.maxLongitudeTriangleSize&&(this.maxLongitudeTriangleSize=us),Je.push(xs+us/2)};for(let ut=0;ut<64;ut++)for(let St=0;St<64;St++){const Pt=65*ut+St,Rt=Pt+1,ws=Pt+65,ns=ws+1;xt(Pt,ws,Rt),xt(Rt,ws,ns)}[Je,rt]=function(ut,St){const Pt=Array.from({length:ut.length},(ns,xs)=>xs);Pt.sort((ns,xs)=>ut[ns]-ut[xs]);const Rt=[],ws=new nu;for(let ns=0;ns{z.segments.push({vertexOffset:0,primitiveOffset:ye,vertexLength:_.segments[0].vertexLength,primitiveLength:we,sortKey:void 0,vaos:{}})},Y=.51*this.maxLongitudeTriangleSize;if(Math.abs(S[0]-L)<=Y){const ye=Io(S,0,S.length,L+Y);return ye===S.length||G(ye,wo(S,ye+1,S.length,L+360-Y)-ye),z}L0}}let ktt,Stt,Ctt,Att,Ett,Ttt,Mtt;class Ltt extends Cl{constructor(f,_,S,L){super(f,{layout:ktt||(ktt=new bc({visibility:new ir($s["layout_raster-particle"].visibility)})),paint:Stt||(Stt=new bc({"raster-particle-array-band":new ir($s["paint_raster-particle"]["raster-particle-array-band"]),"raster-particle-count":new ir($s["paint_raster-particle"]["raster-particle-count"]),"raster-particle-color":new G0($s["paint_raster-particle"]["raster-particle-color"]),"raster-particle-max-speed":new ir($s["paint_raster-particle"]["raster-particle-max-speed"]),"raster-particle-speed-factor":new ir($s["paint_raster-particle"]["raster-particle-speed-factor"]),"raster-particle-fade-opacity-factor":new ir($s["paint_raster-particle"]["raster-particle-fade-opacity-factor"]),"raster-particle-reset-rate-factor":new ir($s["paint_raster-particle"]["raster-particle-reset-rate-factor"]),"raster-particle-elevation":new ir($s["paint_raster-particle"]["raster-particle-elevation"]),"raster-particle-color-use-theme":new ar({type:"string",default:"default","property-type":"data-driven"})}))},_,S,L),this._updateColorRamp(),this.lastInvalidatedAt=bd.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(f){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(f){return!1}_handleSpecialPaintPropertyUpdate(f){f!=="raster-particle-color"&&f!=="raster-particle-max-speed"||(this._updateColorRamp(),this._invalidateAnimationState()),f==="raster-particle-count"&&this._invalidateAnimationState()}_updateColorRamp(){if(!this.hasColorMap())return;const f=this._transitionablePaint._values["raster-particle-color"].value.expression,_=this._transitionablePaint._values["raster-particle-max-speed"].value.expression.evaluate({zoom:0});this.colorRamp=ZV({expression:f,evaluationKey:"rasterParticleSpeed",image:this.colorRamp,clips:[{start:0,end:_}],resolution:256}),this.colorRampTexture=null}_invalidateAnimationState(){this.lastInvalidatedAt=bd.now()}tileCoverLift(){return this.paint.get("raster-particle-elevation")}}class xXt extends Cl{constructor(f,_){super(f,{},_,null),this.implementation=f,f.slot&&(this.slot=f.slot)}is3D(f){return this.implementation.renderingMode==="3d"}hasOffscreenPass(){return this.implementation.prerender!==void 0}isDraped(f){return this.implementation.renderToTile!==void 0}shouldRedrape(){return!!this.implementation.shouldRerenderTiles&&this.implementation.shouldRerenderTiles()}recalculate(){}updateTransitions(){}hasTransition(){return!1}serialize(){}onAdd(f){this.implementation.onAdd&&this.implementation.onAdd(f,f.painter.context.gl)}onRemove(f){this.implementation.onRemove&&this.implementation.onRemove(f,f.painter.context.gl)}}function gMe(k,f,_){const S=[0,0,1],L=lt([]);return Ft(L,L,_?-$n(k)+Math.PI:$n(k)),Mt(L,L,-$n(f)),Re(S,S,L),Me(S,S)}class Sse{constructor(f,_,S,L){this.message=(f?`${f}: `:"")+S,L&&(this.identifier=L),_!=null&&_.__line__&&(this.line=_.__line__)}}function yMe(k,f){const _=k.indexOf("://")===-1;try{return new URL(k,_&&f?"http://example.com":void 0),!0}catch{return!1}}class Ptt{constructor(f,_){this.feature=f,this.instancedDataOffset=_,this.instancedDataCount=0,this.rotation=[0,0,0],this.scale=[1,1,1],this.translation=[0,0,0]}}class Itt{constructor(){this.maxScale=1,this.maxXYTranslationDistance=0,this.instancedDataArray=new $V,this.instancesEvaluatedElevation=[],this.features=[],this.idToFeaturesIndex={}}colorForInstance(f){const _=16*f,S=this.instancedDataArray.float32;let L=Math.floor(S[_+2]);const O=1.05*(S[_+2]-L);return L/=100,[S[_]%1*1.05,S[_+1]%1*1.05,O,L]}tileCoordinatesForInstance(f){const _=16*f,S=this.instancedDataArray.float32;let L=S[_+0];return L=L>lr?L-lr:L,new Xt(Math.trunc(L),Math.trunc(S[_+1]))}translationForInstance(f){const _=16*f,S=this.instancedDataArray.float32;return[S[_+4],S[_+5],S[_+6]]}rotationScaleForInstance(f){const _=16*f,S=this.instancedDataArray.float32;return[S[_+7],S[_+8],S[_+9],S[_+10],S[_+11],S[_+12],S[_+13],S[_+14],S[_+15]]}transformForInstance(f){const _=16*f,S=this.instancedDataArray.float32;return[S[_+7],S[_+8],S[_+9],S[_+4],S[_+10],S[_+11],S[_+12],S[_+5],S[_+13],S[_+14],S[_+15],S[_+6],0,0,0,1]}}class vMe{constructor(f){this.zoom=f.zoom,this.canonical=f.canonical,this.overscaledZ=this.canonical.z+Math.log2(f.overscaling),this.layers=f.layers,this.layerIds=this.layers.map(_=>_.fqid),this.projection=f.projection,this.index=f.index,this.worldview=f.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=f.styleDefinedModelURLs,this.hasAppearances=null}updateFootprints(f,_){}updateAppearances(f,_,S,L){return{hasLayoutChanges:!1,hasUboChanges:!1}}populate(f,_,S,L){this.tileToMeter=Bn(S);const O=this.layers[0]._featureFilter.needGeometry;this.lookup=new Uint8Array(this.lookupDim*this.lookupDim);const z=this.layers[0].paint.get("model-elevation-reference")==="hd-road-markup"?_.elevationFeatures:void 0;for(const{feature:G,id:Y,index:re,sourceLayerIndex:me}of f){const ye=Y??(G.properties&&G.properties.hasOwnProperty("id")?G.properties.id:void 0),we=$i(G,O);if(!this.layers[0]._featureFilter.filter(new Si(this.zoom,{worldview:this.worldview,activeFloors:_.activeFloors}),we,S))continue;const Te={id:ye,sourceLayerIndex:me,index:re,geometry:O?we.geometry:Oa(G,S,L),properties:G.properties,type:G.type,patterns:{}},Ie=this.addFeature(Te,Te.geometry,we,z,S);Ie&&_.featureIndex.insert(G,Te.geometry,re,me,this.index,this.instancesPerModel[Ie].instancedDataArray.length,256)}this.lookup=null}evaluateQueryRenderedFeaturePadding(){const f=this.layers[0].modelManager,_=this.layers[0].scope;let S=0;for(const L of this.modelUris){const O=f.getModel(L,_);if(!O)continue;const z=this.instancesPerModel[L];if(z){const G=.5*ge(O.aabb.max,O.aabb.min)*z.maxScale+z.maxXYTranslationDistance,Y=Math.min(lr,Math.max(G/this.tileToMeter,256));S=Math.max(Y,S)}}return S}update(f,_,S,L){for(const O in this.instancesPerModel){const z=this.instancesPerModel[O];for(const G in f)z.idToFeaturesIndex.hasOwnProperty(G)&&(this.evaluate(z.features[z.idToFeaturesIndex[G]],f[G],z,!0),this.uploaded=!1)}this.maxHeight=0}updateZoomBasedPaintProperties(){if(!this.hasZoomDependentProperties)return!1;let f=!1;for(const _ in this.instancesPerModel){const S=this.instancesPerModel[_];for(const L of S.features){const O=this.layers[0],z=L.feature,G=this.canonical,Y=O.paint.get("model-rotation").evaluate(z,{},G),re=O.paint.get("model-scale").evaluate(z,{},G),me=O.paint.get("model-translation").evaluate(z,{},G);Be(L.rotation,Y)&&Be(L.scale,re)&&Be(L.translation,me)||(this.evaluate(L,L.featureStates,S,!0),f=!0)}}return f}updateReplacement(f,_,S,L){if(_.updateTime===this.replacementUpdateTime)return!1;this.replacementUpdateTime=_.updateTime;const O=_.getReplacementRegionsForTile(f.toUnwrapped(),!0);if(Hte(this.activeReplacements,O))return!1;this.activeReplacements=O;let z=!1;for(const G in this.instancesPerModel){const Y=this.instancesPerModel[G],re=Y.instancedDataArray;for(const me of Y.features){const ye=me.instancedDataOffset,we=me.instancedDataCount;for(let Te=0;Telr;Ve=Je?Ve-lr:Ve;const rt=Math.floor(Ve),xt=Math.floor(re.float32[Ie+1]);let ut=!1;for(const St of this.activeReplacements)if(!mJe(St,S,Gte.Model,L)&&!(St.min.x>rt||rt>St.max.x||St.min.y>xt||xt>St.max.y)&&(ut=yJe(gJe(rt,xt,f.canonical,St.footprintTileId.canonical),St.footprint),ut))break;re.float32[Ie]=ut?Ve+lr:Ve,z=z||ut!==Je}}}return z}isEmpty(){for(const f in this.instancesPerModel)if(this.instancesPerModel[f].instancedDataArray.length!==0)return!1;return!0}uploadPending(){return!this.uploaded}upload(f){if(!this.uploaded)for(const _ in this.instancesPerModel){const S=this.instancesPerModel[_];S.instancedDataArray.length<0||S.instancedDataArray.length===0||(S.instancedDataBuffer?S.instancedDataBuffer.updateData(S.instancedDataArray):S.instancedDataBuffer=f.createVertexBuffer(S.instancedDataArray,DYt.members,!0,void 0,this.instanceCount))}this.uploaded=!0}destroy(f){for(const S in this.instancesPerModel){const L=this.instancesPerModel[S];L.instancedDataArray.length!==0&&L.instancedDataBuffer&&L.instancedDataBuffer.destroy()}const _=this.layers[0].modelManager;if(f&&_&&this.modelUris&&this.modelsRequested)for(const S of this.modelUris)_.removeModel(S,"",!0)}addFeature(f,_,S,L,O){const z=this.layers[0],G=z.layout.get("model-id"),Y=z.layout.get("model-allow-density-reduction"),re=G.evaluate(S,{},this.canonical);if(!re)return Or(`modelId is not evaluated for layer ${z.id} and it is not going to get rendered.`),re;(yMe(re,!1)||this.styleDefinedModelURLs[re]!==void 0)&&(this.modelUris.includes(re)||this.modelUris.push(re)),this.instancesPerModel[re]||(this.instancesPerModel[re]=new Itt);const me=this.instancesPerModel[re],ye=me.instancedDataArray,we=new Ptt(S,ye.length);let Te;L&&(Te=cc.getElevationFeature(f,L));for(const Ie of _)for(const Ve of Ie){if(Ve.x<0||Ve.x>=lr||Ve.y<0||Ve.y>=lr)continue;if(this.lookupDim!==0&&Y){const rt=(this.lookupDim-1)/lr,xt=this.lookupDim*(Ve.y*rt|0)+Ve.x*rt|0;if(this.lookup){if(this.lookup[xt]!==0)continue;this.lookup[xt]=1}}this.instanceCount++;const Je=ye.length;if(ye.resize(Je+1),L){me.instancesRoadElevation||(me.instancesRoadElevation=[]);const rt=Te?Te.pointElevation(new Xt(Ve.x,Ve.y)):0;me.instancesRoadElevation.push(rt)}me.instancesEvaluatedElevation.push(0),ye.float32[16*Je]=Ve.x,ye.float32[16*Je+1]=Ve.y}return we.instancedDataCount=me.instancedDataArray.length-we.instancedDataOffset,we.instancedDataCount>0&&(f.id&&(me.idToFeaturesIndex[f.id]=me.features.length),me.features.push(we),this.evaluate(we,{},me,!1)),re}getModelUris(){return this.modelUris}evaluate(f,_,S,L){const O=this.layers[0],z=f.feature,G=this.canonical,Y=f.rotation=O.paint.get("model-rotation").evaluate(z,_,G),re=f.scale=O.paint.get("model-scale").evaluate(z,_,G),me=f.translation=O.paint.get("model-translation").evaluate(z,_,G),ye=Object.assign({},O.paint.get("model-color").evaluate(z,_,G));ye.a=O.paint.get("model-color-mix-intensity").evaluate(z,_,G);const we=[];this.maxVerticalOffset0?Math.sqrt(Te):0;S.maxScale=Math.max(Math.max(S.maxScale,re[0]),Math.max(re[1],re[2])),S.maxXYTranslationDistance=Math.max(S.maxXYTranslationDistance,Ie),this.maxScale=Math.max(Math.max(this.maxScale,re[0]),Math.max(re[1],re[2])),set(we,Y,re);const Ve=Math.round(100*ye.a)+ye.b/1.05;for(let Je=0;Je10?this.tileToMeter:Bn(G,Pt)),ut[xt+4]=me[0],ut[xt+5]=me[1],ut[xt+6]=me[2]+(S.instancesRoadElevation?S.instancesRoadElevation[rt]:0)+St,ut[xt+7]=we[0],ut[xt+8]=we[1],ut[xt+9]=we[2],ut[xt+10]=we[4],ut[xt+11]=we[5],ut[xt+12]=we[6],ut[xt+13]=we[8],ut[xt+14]=we[9],ut[xt+15]=we[10],S.instancesEvaluatedElevation[rt]=me[2]}}}br(vMe,"ModelBucket",{omit:["layers"]}),br(Itt,"PerModelAttributes"),br(Ptt,"ModelFeature");class XF{constructor(f,_,S){this._demTile=f,this._dem=this._demTile.dem,this._scale=_,this._offset=S}static create(f,_,S){const L=S||f.findDEMTileFor(_);if(!L||!L.dem)return;const O=L.dem,z=L.tileID,G=1<<_.canonical.z-z.canonical.z;return new XF(L,O.dim/lr/G,[(_.canonical.x/G-z.canonical.x)*O.dim,(_.canonical.y/G-z.canonical.y)*O.dim])}tileCoordToPixel(f,_){const S=_*this._scale+this._offset[1];return new Xt(Math.floor(f*this._scale+this._offset[0]),Math.floor(S))}getElevationAt(f,_,S,L){const O=f*this._scale+this._offset[0],z=_*this._scale+this._offset[1],G=Math.floor(O),Y=Math.floor(z),re=this._dem;return L=!!L,S?Cs(Cs(re.get(G,Y,L),re.get(G,Y+1,L),z-Y),Cs(re.get(G+1,Y,L),re.get(G+1,Y+1,L),z-Y),O-G):re.get(G,Y,L)}getElevationAtPixel(f,_,S){return this._dem.get(f,_,!!S)}getMeterToDEM(f){return(1<re.fqid),this.stateDependentLayerIds=this.layers.filter(re=>re.isStateDependent()).map(re=>re.id),this.modelTraits|=qF.CoordinateSpaceTile,this.uploaded=!1,this.hasPattern=!1,L&&(this.modelTraits|=qF.HasMapboxMeshFeatures),O&&(this.modelTraits|=qF.HasMeshoptCompression),this.zoom=-1,this.terrainExaggeration=1,this.projection={name:"mercator"},this.replacementUpdateTime=0,this.elevationReadFromZ=255,this.brightness=z,this.worldview=Y,this.dirty=!0,this.needsUpload=!1,this.filter=null,this.nodesInfo=[];for(const re of _)this.nodesInfo.push(new Ftt(re)),Rtt(re,G.featureIndexArray.length,G.grid),G.featureIndexArray.emplaceBack(this.nodesInfo.length-1,0,G.bucketLayerIDs.length-1,0);this.states={},this.hasAppearances=null}updateFootprints(f,_){for(const S of this.getNodesInfo()){const L=S.node;L.footprint&&_.push({footprint:L.footprint,id:f})}}updateAppearances(f,_,S,L){return{hasLayoutChanges:!1,hasUboChanges:!1}}update(f){const _=Object.keys(f).length!==0;if(_&&!this.stateDependentLayers.length)return;const S=_?this.stateDependentLayers:this.layers;if(!rr(f,this.states))for(const L of S)this.evaluate(L,f);this.states=structuredClone(f)}populate(){console.log("populate 3D model bucket")}uploadPending(){return!this.uploaded||this.needsUpload}upload(f){if(!this.needsUpload)return;const _=this.getNodesInfo();for(const S of _){const L=S.node;this.uploaded?this.updatePbrBuffer(L):O6e(L,f,!0)}for(const S of _)ase(S.node);this.uploaded=!0,this.needsUpload=!1}updatePbrBuffer(f){let _=!1;if(!f.meshes)return _;for(const S of f.meshes)S.pbrBuffer&&(S.pbrBuffer.updateData(S.featureArray),_=!0);return _}needsReEvaluation(f,_,S){const L=f.transform.projectionOptions,O=f.style.getBrightness(),z=this.brightness!==O;if(!this.uploaded||this.dirty||L.name!==this.projection.name||CH(S.paint.get("model-color").value,z)||CH(S.paint.get("model-color-mix-intensity").value,z)||CH(S.paint.get("model-roughness").value,z)||CH(S.paint.get("model-emissive-strength").value,z)||CH(S.paint.get("model-height-based-emissive-strength-multiplier").value,z)){this.projection=L,this.brightness=O;const G=this.getNodesInfo();for(const Y of G)Y.state=null;return!0}return!1}evaluateTransform(f,_){if(f.transform.zoom===this.zoom)return;this.zoom=f.transform.zoom;const S=this.getNodesInfo(),L=this.id.canonical;for(const O of S){const z=O.feature;O.evaluatedTranslation=_.paint.get("model-translation").evaluate(z,{},L),O.evaluatedScale=_.paint.get("model-scale").evaluate(z,{},L)}}evaluate(f,_){const S=this.getNodesInfo();for(const L of S){if(!L.node.meshes)continue;const O=L.feature,z=_&&_[O.id];if(rr(z,L.state))continue;L.state=structuredClone(z);const G=L.node.meshes&&L.node.meshes[0].featureData,Y=L.evaluatedColor[2],re=L.evaluatedRMEA[2],me=this.id.canonical;if(L.hasTranslucentParts=!1,G){for(let ye=0;ye=Rt)continue;const Jn=bMe[En],un=Math.abs(Jn);un>hs&&(us=Jn,hs=un,pn=Ln,bn=An)}if(hs>.1){const An=1-(Rt+.5*Math.abs(pn*bn))/Ie;let Ln=_._dem.get(ns,ws)+us*An;const En=_._dem.get(ns+pn,ws+bn),Jn=_._dem.get(ns-pn,ws-bn,!0);(Ln-En)*(Ln-Jn)>0&&(Ln=(En+Jn)/2),bMe[xs]=_._dem.set(ns,ws,Ln),TM[xs]=Rt}}}}}G&&(_._demTile.needsDEMTextureUpload=!0,_._dem._timestamp=bd.now())}setFilter(f){this.filter=f?RC(f):null}getNodesInfo(){return this.filter?this.nodesInfo.filter(f=>this.filter.filter(new Si(this.id.overscaledZ,{worldview:this.worldview}),f.feature,this.id.canonical)):this.nodesInfo}destroy(){const f=this.getNodesInfo();for(const _ of f)ase(_.node),F6e(_.node)}isEmpty(){return!this.nodesInfo.length}updateReplacement(f,_){if(_.updateTime===this.replacementUpdateTime)return;this.replacementUpdateTime=_.updateTime;const S=_.getReplacementRegionsForTile(f.toUnwrapped());for(const L of this.getNodesInfo()){const O=L.node.footprint;L.hiddenByReplacement=!!O&&!S.find(z=>z.footprint===O)}}getHeightAtTileCoord(f,_){const S=[],L=[0,0,0],O=y([]);for(const z of this.getNodesInfo()){const G=z.node.meshes[0],Y=G.transformedAabb;if(fY.max[0]||_>Y.max[1])continue;if(z.node.hidden===!0)return{height:1/0,maxHeight:z.feature.properties.height,hidden:!1,verticalScale:z.evaluatedScale[2]};b(O,z.node.globalMatrix),L[0]=f,L[1]=_,Xe(L,L,O);const re=(L[0]-G.aabb.min[0])/(G.aabb.max[0]-G.aabb.min[0])*kM|0,me=Math.min(63,(L[1]-G.aabb.min[1])/(G.aabb.max[1]-G.aabb.min[1])*kM|0)*kM+Math.min(63,re),ye=G.heightmap[me];if(!(ye<0&&z.node.footprint))return z.hiddenByReplacement?void 0:{height:ye,maxHeight:z.feature.properties.height,hidden:!1,verticalScale:z.evaluatedScale[2]};if(z.node.footprint.grid.query(new Xt(f,_),new Xt(f,_),S),S.length>0)return{height:void 0,maxHeight:z.feature.properties.height,hidden:z.hiddenByReplacement,verticalScale:z.evaluatedScale[2]}}}}function CH(k,f){return k instanceof th&&!k.isLightConstant&&f}function gXt(k,f,_,S,L,O,z,G){let Y=(61440&f|(61440&f)>>4)>>8,re=(3840&f|(3840&f)>>4)>>4,me=240&f|(240&f)>>4;_[3]>0&&(Y=Cs(Y,255*_[0],_[3]),re=Cs(re,255*_[1],_[3]),me=Cs(me,255*_[2],_[3]));const ye=Y<<8|re,we=me<<8|Math.floor(255*S[3]),Te=function(Rt){const ws=pt(Rt,0,2);return Math.min(Math.round(.5*ws*255),255)}(S[2])<<8|15*S[0]<<4|15*S[1],Ie=pt(L[0],0,1),Ve=pt(L[1],0,1),Je=pt(L[2],0,1),rt=pt(L[3],0,1);let xt,ut,St,Pt;if(Ie!==Ve&&z!==O&&Ve!==Ie){const Rt=z-O;ut=1/(Rt*(Ve-Ie)),St=-(O+Rt*Ie)/(Rt*(Ve-Ie));const ws=pt(L[4],-1,1);Pt=Math.pow(10,ws),xt=255*Je<<8|255*rt}else xt=65535,ut=0,St=1,Pt=1;if(k.emplaceBack(ye,we,Te,xt,ut,St,Pt),G){const Rt=G.length;G.clear();for(let ws=0;ws>16&65535,me=O?Y>>16&65535:65535&Y,ye=(15&me)<8?15&me:0,we=k.evaluatedRMEA[ye],Te=k.evaluatedColor[ye],Ie=k.emissionHeightBasedParams[ye];let Ve;if(G&&ye===2&&S.lights&&(Ve=new MF,Ve.resize(10*S.lights.length)),gXt(z.featureArray,re,Te,we,Ie,z.aabb.min[2],z.aabb.max[2],Ve),Ve&&G){G=!1;const Je=S.meshes[S.lightMeshIndex];Je.featureArray=Ve,Je.featureArray._trim()}}z.featureArray._trim(),L++}}br(Cse,"Tiled3dModelBucket",{omit:["layers"]}),br(Ftt,"Tiled3dModelFeature");const vXt=["id","tile","layer","source","sourceLayer","state"];class MM{constructor(f,_,S,L,O){this.type="Feature",this._vectorTileFeature=f,this._z=_,this._x=S,this._y=L,this.properties=f?f.properties:{},this.id=O}clone(){const f=new MM(this._vectorTileFeature,this._z,this._x,this._y,this.id);return this.state&&(f.state=Object.assign({},this.state)),this.layer&&(f.layer=Object.assign({},this.layer)),this.source&&(f.source=this.source),this.sourceLayer&&(f.sourceLayer=this.sourceLayer),f}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(f){this._geometry=f}toJSON(){const f={type:"Feature",state:void 0,geometry:this.geometry,properties:this.properties};for(const _ of vXt)this[_]!==void 0&&(f[_]=this[_]);return f}}class LM extends om{constructor(f,_,S,L){super(),this.id=f,this.type="model",this.models=[],this._options=_,this._modelsInfo=new Map,this._abortController=null}cancelModelRequests(){this._abortController&&(this._abortController.abort(),this._abortController=null)}loadGLTFFromURI(f,_){return QJe(this.map._requestManager.transformRequest(f,lp.Model).url,_)}async loadModel(f,_,S){try{const L=await this.loadGLTFFromURI(_.uri,S);if(S.aborted)return;const O=this._modelsInfo.get(f);if(!O)return;const z=B6e(L),G=O.modelSpec,Y=new net(f,G.uri,G.position,G.orientation,z);LM.applyModelSpecification(Y,G),Y.computeBoundsAndApplyParent(),this.models.push(Y),O.model=Y}catch(L){if(L instanceof Error&&L.name==="AbortError")return;const O=L instanceof Error?L.message:"Unknown error";this.fire(new cp(new Error(`Could not load model ${f} from ${_.uri}: ${O}`)))}}async load(){this._abortController||(this._abortController=new AbortController);const f=this._abortController.signal,_=[];for(const S in this._options.models){const L=this._options.models[S],O=this._modelsInfo.get(S);if(O&&O.model){O.modelSpec=L;const z=O.model;z.position=L.position!=null?new As(L.position[0],L.position[1]):new As(0,0),z.orientation=L.orientation!=null?L.orientation:[0,0,0],LM.applyModelSpecification(z,L),z.computeBoundsAndApplyParent(),this.models.push(z)}else O?O.modelSpec=L:(this._modelsInfo.set(S,{modelSpec:L,model:null}),_.push(this.loadModel(S,L,f)))}_.length!==0?(await Promise.allSettled(_),f.aborted||this.fire(new Oc("data",{dataType:"source",sourceDataType:"metadata"}))):this.loaded()&&this.fire(new Oc("data",{dataType:"source",sourceDataType:"metadata"}))}static applyModelSpecification(f,_){_.nodeOverrides&&LM.convertNodeOverrides(f,_.nodeOverrides),_.materialOverrides&&LM.convertMaterialOverrides(f,_.materialOverrides),_.nodeOverrideNames&&(f.nodeOverrideNames=[..._.nodeOverrideNames]),_.materialOverrideNames&&(f.materialOverrideNames=[..._.materialOverrideNames]),_.featureProperties&&(f.featureProperties=_.featureProperties)}static convertNodeOverrides(f,_){if(Array.isArray(_)&&_.every(S=>typeof S=="string")){f.nodeOverrideNames=[];for(const S of _)f.nodeOverrideNames.push(S)}else Object.entries(_).forEach(([S,L])=>{const O={orientation:[0,0,0]};if(L.hasOwnProperty("orientation")){const z=L.orientation;z&&(O.orientation=z)}f.nodeOverrides.set(S,O)})}static convertMaterialOverrides(f,_){if(Array.isArray(_)&&_.every(S=>typeof S=="string")){f.materialOverrideNames=[];for(const S of _)f.materialOverrideNames.push(S)}else Object.entries(_).forEach(([S,L])=>{const O={color:new Ys(1,1,1),colorMix:0,emissionStrength:0,opacity:1},z=L["model-color"];z!==void 0&&(O.color.r=z[0],O.color.g=z[1],O.color.b=z[2]);const G=L["model-color-mix-intensity"];G!==void 0&&(O.colorMix=G);const Y=L["model-emissive-strength"];Y!==void 0&&(O.emissionStrength=Y);const re=L["model-opacity"];re!==void 0&&(O.opacity=re),f.materialOverrides.set(S,O)})}onAdd(f){this.map=f,this.load()}hasTransition(){return!1}loaded(){if(this._modelsInfo.size===0)return!0;for(const f of this._modelsInfo.values())if(f.model==null)return!1;return!0}getModels(){return this.models}loadTile(f,_){}serialize(){return this._options}setProperty(f,_){return!1}reload(){this.cancelModelRequests();const f=Et(this.id,this.scope);this.map.style.clearSource(f),this.models=[],this._modelsInfo.clear(),this.load()}onRemove(f){this.cancelModelRequests()}setModels(f){this.models=[];const _=new Map;for(const S in f){const L=f[S],O=this._modelsInfo.get(S);O&&O.modelSpec.uri===L.uri&&_.set(S,O)}if(this._modelsInfo.size!==_.size){this.cancelModelRequests();for(const[S,L]of _)L.model||_.delete(S)}this._modelsInfo=_,this._options.models=f,this.load()}}function _Me(k,f,_,S){const L=1<Y>=Pt.vertexArrayOffset&&YSt.polygon).flat());const Je=Te?G:null,[rt,xt]=OJe(O,S,ye,me,re,z,Je,we,Ie,O.center.lat,k.tileID.canonical),ut=k.queryGeometry;return RJe(rt,xt,ut.isPointQuery()?ut.screenBounds:ut.screenGeometry)}},building:class extends Cl{constructor(k,f,_,S){super(k,{layout:uet||(uet=new bc({visibility:new ir($s.layout_building.visibility),"building-facade":new ar($s.layout_building["building-facade"]),"building-facade-floors":new ar($s.layout_building["building-facade-floors"]),"building-facade-unit-width":new ar($s.layout_building["building-facade-unit-width"]),"building-facade-window":new ar($s.layout_building["building-facade-window"]),"building-roof-shape":new ar($s.layout_building["building-roof-shape"]),"building-height":new ar($s.layout_building["building-height"]),"building-base":new ar($s.layout_building["building-base"]),"building-flood-light-wall-radius":new ar($s.layout_building["building-flood-light-wall-radius"]),"building-flood-light-ground-radius":new ar($s.layout_building["building-flood-light-ground-radius"]),"building-flip-roof-orientation":new ar($s.layout_building["building-flip-roof-orientation"])})),paint:het||(het=new bc({"building-opacity":new ir($s.paint_building["building-opacity"]),"building-ambient-occlusion-intensity":new ir($s.paint_building["building-ambient-occlusion-intensity"]),"building-ambient-occlusion-ground-intensity":new ir($s.paint_building["building-ambient-occlusion-ground-intensity"]),"building-ambient-occlusion-ground-radius":new ir($s.paint_building["building-ambient-occlusion-ground-radius"]),"building-ambient-occlusion-ground-attenuation":new ir($s.paint_building["building-ambient-occlusion-ground-attenuation"]),"building-vertical-scale":new ir($s.paint_building["building-vertical-scale"]),"building-cast-shadows":new ir($s.paint_building["building-cast-shadows"]),"building-color":new ar($s.paint_building["building-color"]),"building-emissive-strength":new ar($s.paint_building["building-emissive-strength"]),"building-facade-emissive-chance":new ir($s.paint_building["building-facade-emissive-chance"]),"building-cutoff-fade-range":new ir($s.paint_building["building-cutoff-fade-range"]),"building-front-cutoff":new ir($s.paint_building["building-front-cutoff"]),"building-flood-light-color":new ir($s.paint_building["building-flood-light-color"]),"building-flood-light-intensity":new ir($s.paint_building["building-flood-light-intensity"]),"building-flood-light-ground-attenuation":new ir($s.paint_building["building-flood-light-ground-attenuation"]),"building-color-use-theme":new ar({type:"string",default:"default","property-type":"data-driven"}),"building-flood-light-color-use-theme":new ar({type:"string",default:"default","property-type":"data-driven"})}))},f,_,S),this._stats={numRenderedVerticesInShadowPass:0,numRenderedVerticesInTransparentPass:0}}createBucket(k){return new det(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,f,_,S,L,O,z,G,Y,re){let me=this.layout.get("building-height").evaluate(f,_);const ye=this.layout.get("building-base").evaluate(f,_),we=k.tile.getBucket(this).getFootprint(f);if(we){if(we.hiddenFlags!==0)return!1;me=we.height}const[Te,Ie]=OJe(O,S,ye,me,new Xt(0,0),z,null,[0,0],1,O.center.lat,k.tileID.canonical),Ve=k.queryGeometry;return RJe(Te,Ie,Ve.isPointQuery()?Ve.screenBounds:Ve.screenGeometry)}},line:class extends Cl{constructor(k,f,_,S){const L=wet();super(k,L,f,_,S),L.layout&&(this.layout=new Fm(L.layout)),this.gradientVersion=0,this.hasElevatedBuckets=!1,this.hasNonElevatedBuckets=!1}_handleSpecialPaintPropertyUpdate(k){if(k==="line-gradient"){const f=this._transitionablePaint._values["line-gradient"].value.expression;this.stepInterpolant=f._styleExpression&&f._styleExpression.expression instanceof Dw,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,f){super.recalculate(k,f),this.paint._values["line-floorwidth"]=(()=>{if(mH)return mH;const _=wet();return mH=new mZt(_.paint.properties["line-width"].specification),mH.useIntegerZoom=!0,mH})().possiblyEvaluate(this._transitioningPaint._values["line-width"].value,k)}createBucket(k){return new ose(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,f,_){if(k==="lineBlendComposite")return{};const S=bet(this);return{config:new He(this,{zoom:f,lut:_}),defines:S,overrideFog:!1}}queryRadius(k){const f=k,_=jet(UC("line-width",this,f),UC("line-gap-width",this,f)),S=UC("line-offset",this,f);return _/2+Math.abs(S)+Mte(this.paint.get("line-translate"))}queryIntersectsFeature(k,f,_,S,L,O){if(k.queryGeometry.isAboveHorizon)return!1;const z=bQe(k.tilespaceGeometry,this.paint.get("line-translate"),this.paint.get("line-translate-anchor"),O.angle,k.pixelToTileUnitsFactor),G=k.pixelToTileUnitsFactor/2*jet(this.paint.get("line-width").evaluate(f,_),this.paint.get("line-gap-width").evaluate(f,_)),Y=this.paint.get("line-offset").evaluate(f,_);return Y&&(S=function(re,me){const ye=[],we=new Xt(0,0);for(let Te=0;Te=3){for(let Ie=0;Ie{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 ztt{constructor(f){this._stringToNumber={},this._numberToString=[];for(let _=0;_=0&&we[3]>=0&&re.insert(Y,we[0],we[1],we[2],we[3])}}loadVTLayers(){if(!this.vtLayers){this.vtLayers=new Zo(new lse(this.rawTileData)).layers,this.sourceLayerCoder=new ztt(this.vtLayers?Object.keys(this.vtLayers).sort():["_geojsonTileLayer"]),this.vtFeatures={};for(const f in this.vtLayers)this.vtFeatures[f]=[]}return this.vtLayers}query(f,_){const{tilespaceGeometry:S,transform:L,tileTransform:O,pixelPosMatrix:z,availableImages:G,worldview:Y}=_;this.loadVTLayers(),this.serializedLayersCache.clear();const re=_.queryRadius?_.queryRadius:0,me=S.bufferedTilespaceBounds,ye=this.grid.query(me.min.x,me.min.y,me.max.x,me.max.y,(Ve,Je,rt,xt)=>Ak(S.bufferedTilespaceGeometry,Ve-re,Je-re,rt+re,xt+re));ye.sort(jXt);let we=null;L.elevation&&ye.length>0&&(we=XF.create(L.elevation,this.tileID));const Te={};let Ie;for(let Ve=0;Ve(xt||(xt=Oa(ut,this.tileID.canonical,O)),St.queryIntersectsFeature(S,ut,Pt,xt,this.z,L,z,we,Rt,_.scope)))}return Te}loadMatchingFeature(f,_,S,L,O,z){const{featureIndex:G,bucketIndex:Y,sourceLayerIndex:re,layoutVertexArrayOffset:me}=_,ye=this.bucketLayerIDs[Y],we=S.layers,Te=Object.keys(we);if(Te.length&&!Kr(Te,ye))return;const Ie=S.sourceCache,Ve=this.sourceLayerCoder.decode(re),Je=this.vtLayers[Ve].feature(G),rt=this.getId(Je,Ve);for(let xt=0;xt`${G.key}: ${G.message}`).join(", ");return void Or(`Failed to create expression for promoteId: ${z}`)}this.promoteIdExpression=O.value}S=this.promoteIdExpression.evaluate({zoom:0},f)}else S=f.properties[L];typeof S=="boolean"&&(S=Number(S))}return S}}function $tt(k,f,_,S,L){return Gs(k,(O,z)=>{const G=f instanceof Fm?f.get(z):null;return G&&G.evaluate?G.evaluate(_,S,void 0,L):G})}function jXt(k,f){return f-k}function Utt(k,f){const _={};if(!f)return _;for(const S of k){const L=S.layerIds.map(O=>f.getLayer(O)).filter(Boolean);if(L.length!==0){S.layers=L,S.stateDependentLayerIds&&(S.stateDependentLayers=S.stateDependentLayerIds.map(O=>L.filter(z=>z.id===O)[0]));for(const O of L)_[O.fqid]=S}}return _}br(Btt,"FeatureIndex",{omit:["rawTileData","sourceLayerCoder"]});const Kw=32,Dk=33,YC=new Uint16Array(8184);for(let k=0;k<2046;k++){let f=k+2,_=0,S=0,L=0,O=0,z=0,G=0;for(1&f?L=O=z=Kw:_=S=G=Kw;(f>>=1)>1;){const re=_+L>>1,me=S+O>>1;1&f?(L=_,O=S,_=z,S=G):(_=L,S=O,L=z,O=G),z=re,G=me}const Y=4*k;YC[Y+0]=_,YC[Y+1]=S,YC[Y+2]=L,YC[Y+3]=O}const Rk=new Uint16Array(2178),ZC=new Uint8Array(1089),Ase=new Uint16Array(1089);function qtt(k){return k===0?-.03125:k===32?.03125:0}const Vtt={Other:0,Symbol:1,FillExtrusion:2},Htt={type:2,extent:lr,loadGeometry:()=>[[new Xt(0,0),new Xt(8193,0),new Xt(8193,8193),new Xt(0,8193),new Xt(0,0)]]};class NXt{constructor(){this.tasks={},this.taskQueue=[],qt(["process"],this),this.invoker=new wXt(this.process),this.nextId=0}add(f,_){const S=this.nextId++,L=function({type:O,renderSourceType:z,zoom:G}){G=G||0;const Y=z===Vtt.Symbol;return O==="message"?0:O!=="maybePrepare"||Y?O!=="parseTile"||Y?O==="parseTile"&&Y?300-G:O==="maybePrepare"&&Y?400-G:500:200-G:100-G}(_);if(L===0){try{f()}finally{}return null}return this.tasks[S]={fn:f,metadata:_,priority:L,id:S},this.taskQueue.push(S),this.invoker.trigger(),{cancel:()=>{delete this.tasks[S]}}}process(){try{if(this.taskQueue=this.taskQueue.filter(S=>!!this.tasks[S]),!this.taskQueue.length)return;const f=this.pick();if(f===null)return;const _=this.tasks[f];if(delete this.tasks[f],this.taskQueue.length&&this.invoker.trigger(),!_)return;_.fn()}finally{}}pick(){let f=null,_=1/0;for(let L=0;L>16&255)/255,(k>>8&255)/255,(255&k)/255,1)}function RXt(k,f,_){k===1?(f.rgb_color=Mse(_.readVarint()),f.paint="rgb_color"):k===2?(f.linear_gradient_idx=_.readVarint(),f.paint="linear_gradient_idx"):k===3?(f.radial_gradient_idx=_.readVarint(),f.paint="radial_gradient_idx"):k===5?_.readPackedFloat(f.dasharray):k===6?f.dashoffset=_.readFloat():k===7?f.miterlimit=_.readFloat():k===8?f.opacity=_.readVarint():k===9?f.width=_.readFloat():k===10?f.linecap=_.readVarint():k===11&&(f.linejoin=_.readVarint())}function OXt(k,f,_){k===1?f.transform=Tse(_,_.readVarint()+_.pos):k===2?f.spread_method=_.readVarint():k===3?f.stops.push(Ktt(_,_.readVarint()+_.pos)):k===4?f.x1=_.readFloat():k===5?f.y1=_.readFloat():k===6?f.x2=_.readFloat():k===7&&(f.y2=_.readFloat())}function Ktt(k,f){return k.readFields(FXt,{offset:0,opacity:255,rgb_color:wMe},f)}function FXt(k,f,_){k===1?f.offset=_.readFloat():k===2?f.opacity=_.readVarint():k===3&&(f.rgb_color=Mse(_.readVarint()))}function zXt(k,f,_){k===1?f.transform=Tse(_,_.readVarint()+_.pos):k===2?f.spread_method=_.readVarint():k===3?f.stops.push(Ktt(_,_.readVarint()+_.pos)):k===4?f.cx=_.readFloat():k===5?f.cy=_.readFloat():k===6?f.r=_.readFloat():k===7?f.fx=_.readFloat():k===8?f.fy=_.readFloat():k===9&&(f.fr=_.readFloat())}function BXt(k,f,_){k===1?f.transform=Tse(_,_.readVarint()+_.pos):k===2?f.clip_path_idx=_.readVarint():k===3&&f.children.push(Ese(_,_.readVarint()+_.pos))}function $Xt(k,f,_){k===1?f.left=f.top=_.readFloat():k===2?f.width=f.height=_.readFloat():k===3?f.top=_.readFloat():k===4?f.height=_.readFloat():k===5?f.mask_type=_.readVarint():k===6?f.mask_idx=_.readVarint():k===7&&f.children.push(Ese(_,_.readVarint()+_.pos))}class UXt{static calculate(f={},_=[]){const S=new Map,L=new Map;if(Object.keys(f).length===0)return S;_.forEach(O=>{L.set(O.name,O.rgb_color||new Ys(0,0,0))});for(const[O,z]of Object.entries(f))L.has(O)?S.set(L.get(O).toString(),z):console.warn(`Ignoring unknown image variable "${O}"`);return S}}function QF(k,f=255,_){const S=f/255,L=k.toString(),O=_.has(L)?_.get(L).clone():k.clone();return O.a*=S,O.toString()}function AH(k,f){if(!Ld()){const _=document.createElement("canvas");return _.width=k,_.height=f,_}return new OffscreenCanvas(k,f)}let jMe,EH=null;function NMe(k,f,_,S,L){for(const O of S.children)Ytt(k,f,_,O,L)}function Ytt(k,f,_,S,L){S.group?(k.save(),function(O,z,G,Y,re){const me=Y.mask_idx!=null?G.masks[Y.mask_idx]:null,ye=Y.clip_path_idx!=null?G.clip_paths[Y.clip_path_idx]:null;if(Y.transform&&(z=JF(Y.transform).preMultiplySelf(z)),!function(Ie,Ve,Je){return Ie.opacity!==255||Ve||Je}(Y,ye!=null,me!=null))return void NMe(O,z,G,Y,re);const we=AH(O.canvas.width,O.canvas.height),Te=we.getContext("2d");NMe(Te,z,G,Y,re),ye&&sst(Te,z,G,ye),me&&nst(Te,z,G,me,re),O.globalAlpha=Y.opacity/255,O.drawImage(we,0,0)}(k,f,_,S.group,L),k.restore()):S.path&&(k.save(),function(O,z,G,Y,re){O.setTransform(z),Y.paint_order===1?(Ztt(O,G,Y,re),Qtt(O,G,Y,re)):(Qtt(O,G,Y,re),Ztt(O,G,Y,re))}(k,f,_,S.path,L),k.restore())}function Ztt(k,f,_,S){const L=_.fill;if(!L)return;const O=L.opacity/255;switch(k.save(),k.beginPath(),rst(_,k),L.paint){case"rgb_color":k.fillStyle=QF(L.rgb_color,L.opacity,S);break;case"linear_gradient_idx":{const z=f.linear_gradients[L.linear_gradient_idx];z.transform&&k.setTransform(JF(z.transform).preMultiplySelf(k.getTransform())),k.fillStyle=Jtt(k,z,O,S);break}case"radial_gradient_idx":{const z=f.radial_gradients[L.radial_gradient_idx];z.transform&&k.setTransform(JF(z.transform).preMultiplySelf(k.getTransform())),k.fillStyle=est(k,z,O,S)}}k.fill(Xtt(_)),k.restore()}function Xtt(k){return k.rule===1?"nonzero":k.rule===2?"evenodd":void 0}function Qtt(k,f,_,S){const L=_.stroke;if(!L)return;const O=ast(_);k.lineWidth=L.width,k.miterLimit=L.miterlimit,k.setLineDash(L.dasharray),k.lineDashOffset=L.dashoffset;const z=L.opacity/255;switch(L.paint){case"rgb_color":k.strokeStyle=QF(L.rgb_color,L.opacity,S);break;case"linear_gradient_idx":k.strokeStyle=Jtt(k,f.linear_gradients[L.linear_gradient_idx],z,S,!0);break;case"radial_gradient_idx":k.strokeStyle=est(k,f.radial_gradients[L.radial_gradient_idx],z,S,!0)}switch(L.linejoin){case 2:case 1:k.lineJoin="miter";break;case 3:k.lineJoin="round";break;case 4:k.lineJoin="bevel"}switch(L.linecap){case 1:k.lineCap="butt";break;case 2:k.lineCap="round";break;case 3:k.lineCap="square"}k.stroke(O)}function Jtt(k,f,_,S,L=!1){if(f.stops.length===1){const we=f.stops[0];return QF(we.rgb_color,we.opacity*_,S)}const{x1:O,y1:z,x2:G,y2:Y}=f;let re=new DOMPoint(O,z),me=new DOMPoint(G,Y);if(L){const we=JF(f.transform);re=we.transformPoint(re),me=we.transformPoint(me)}const ye=k.createLinearGradient(re.x,re.y,me.x,me.y);for(const we of f.stops)ye.addColorStop(we.offset,QF(we.rgb_color,we.opacity*_,S));return ye}function est(k,f,_,S,L=!1){if(f.stops.length===1){const rt=f.stops[0];return QF(rt.rgb_color,rt.opacity*_,S)}const O=JF(f.transform),{fx:z,fy:G,fr:Y,cx:re,cy:me,r:ye}=f;let we=new DOMPoint(z,G),Te=new DOMPoint(re,me),Ie=Y,Ve=ye;if(L){we=O.transformPoint(we),Te=O.transformPoint(Te);const rt=(O.a+O.d)/2;Ie=Y*rt,Ve=f.r*rt}const Je=k.createRadialGradient(we.x,we.y,Ie,Te.x,Te.y,Ve);for(const rt of f.stops)Je.addColorStop(rt.offset,QF(rt.rgb_color,rt.opacity*_,S));return Je}function tst(k,f,_,S){const L=S.transform?JF(S.transform).preMultiplySelf(f):f,O=AH(k.canvas.width,k.canvas.height),z=O.getContext("2d");for(const Y of S.children)if(Y.group)tst(z,L,_,Y.group);else if(Y.path){const re=Y.path,me=new Path2D;me.addPath(ast(re),L),z.fill(me,Xtt(re))}const G=S.clip_path_idx!=null?_.clip_paths[S.clip_path_idx]:null;G&&sst(z,L,_,G),k.globalCompositeOperation="source-over",k.drawImage(O,0,0)}function sst(k,f,_,S){const L=AH(k.canvas.width,k.canvas.height);tst(L.getContext("2d"),f,_,S),k.globalCompositeOperation="destination-in",k.drawImage(L,0,0)}function nst(k,f,_,S,L){if(S.children.length===0)return;const O=S.mask_idx!=null?_.masks[S.mask_idx]:null;O&&nst(k,f,_,O,L);const z=k.canvas.width,G=k.canvas.height,Y=AH(z,G),re=Y.getContext("2d"),me=S.width,ye=S.height,we=S.left,Te=S.top,Ie=new Path2D,Ve=new Path2D;Ve.rect(we,Te,me,ye),Ie.addPath(Ve,f),re.clip(Ie);for(const xt of S.children)Ytt(re,f,_,xt,L);const Je=re.getImageData(0,0,z,G),rt=Je.data;if(S.mask_type===1)for(let xt=0;xtf[z])return null}else{const G=1/S[z];let Y=(k[z]-_[z])*G,re=(f[z]-_[z])*G;if(Y>re){const me=Y;Y=re,re=me}if(Y>L&&(L=Y),reO)return null}return L}function lst(k,f,_,S,L,O,z,G,Y,re,me){const ye=S-k,we=L-f,Te=O-_,Ie=z-k,Ve=G-f,Je=Y-_,rt=me[1]*Je-me[2]*Ve,xt=me[2]*Ie-me[0]*Je,ut=me[0]*Ve-me[1]*Ie,St=ye*rt+we*xt+Te*ut;if(Math.abs(St)<1e-15)return null;const Pt=1/St,Rt=re[0]-k,ws=re[1]-f,ns=re[2]-_,xs=(Rt*rt+ws*xt+ns*ut)*Pt;if(xs<0||xs>1)return null;const us=ws*Te-ns*we,hs=ns*ye-Rt*Te,pn=Rt*we-ws*ye,bn=(me[0]*us+me[1]*hs+me[2]*pn)*Pt;return bn<0||xs+bn>1?null:(Ie*us+Ve*hs+Je*pn)*Pt}function cst(k,f,_){return(k-f)/(_-f)}function dst(k,f,_,S,L,O,z,G,Y){const re=1<<_,me=O-S,ye=z-L,we=(k+1)/re*me+S,Te=(f+0)/re*ye+L,Ie=(f+1)/re*ye+L;G[0]=(k+0)/re*me+S,G[1]=Te,Y[0]=we,Y[1]=Ie}class ust{constructor(f){if(this.maximums=[],this.minimums=[],this.leaves=[],this.childOffsets=[],this.nodeCount=0,this.dem=f,this._siblingOffset=[[0,0],[1,0],[0,1],[1,1]],!this.dem)return;const _=function(O){const z=Math.ceil(Math.log2(O.dim/8)),G=[];let Y=Math.ceil(Math.pow(2,z));const re=1/Y,me=(Te,Ie,Ve,Je,rt)=>{const xt=Je?1:0,ut=(Te+1)*Ve-xt,St=Ie*Ve,Pt=(Ie+1)*Ve-xt;rt[0]=Te*Ve,rt[1]=St,rt[2]=ut,rt[3]=Pt};let ye=new ist(Y);const we=[];for(let Te=0;Te=1;Y/=2){const Te=G[G.length-1];ye=new ist(Y);for(let Ie=0;Ie0;){const{idx:Ie,t:Ve,nodex:Je,nodey:rt,depth:xt}=Te.pop();if(this.leaves[Ie]){dst(Je,rt,xt,f,_,S,L,ye,we);const St=1<=En[2])return Ve}continue}let ut=0;for(let St=0;St=re[me[ns]]&&(me.splice(ns,0,St),ws=!0);ws||(me[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+(f+1)}static pack(f,_){const S=[0,0,0,0],L=Pse.getUnpackVector(_);let O=Math.floor((f+L[3])/L[2]);return S[2]=O%256,O=Math.floor(O/256),S[1]=O%256,O=Math.floor(O/256),S[0]=O,S}getPixels(){return new HQe({width:this.stride,height:this.stride},this.pixels)}backfillBorder(f,_,S){if(this.dim!==f.dim)throw new Error("dem dimension mismatch");let L=_*this.dim,O=_*this.dim+this.dim,z=S*this.dim,G=S*this.dim+this.dim;switch(_){case-1:L=O-1;break;case 1:O=L+1}switch(S){case-1:z=G-1;break;case 1:G=z+1}const Y=-_*this.dim,re=-S*this.dim;for(let me=z;me=1;S--){const L=S===1?1:0,O=S===2?1:0;for(let z=0;z>>1^-(1&k[f]);return k}function sQt(k,f){switch(f){case"uint32":return k;case"uint16":for(let _=0;_>4|(61440&S)>>8|(240&L)<<4|61440&L,k[_+1]=15&S|(3840&S)>>4|(15&L)<<8|(3840&L)<<4}return k;case"uint8":for(let _=0;_>6|(192&L)>>4|(192&O)>>2|192&z,k[_+1]=(48&S)>>4|(48&L)>>2|48&O|(48&z)<<2,k[_+2]=(12&S)>>2|12&L|(12&O)<<2|(12&z)<<4,k[_+3]=3&S|(3&L)<<2|(3&O)<<4|(3&z)<<6}return k;default:throw new Error(`Invalid pixel format, "${f}"`)}}br(Pse,"DEMData"),br(ust,"DemMinMaxQuadTree",{omit:["dem"]});var l_=Uint8Array,TH=Uint16Array,nQt=Int32Array,mst=new l_([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]),pst=new l_([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]),rQt=new l_([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),fst=function(k,f){for(var _=new TH(31),S=0;S<31;++S)_[S]=f+=1<>1|(21845&hm)<<1;yst[hm]=((65280&(e7=(61680&(e7=(52428&e7)>>2|(13107&e7)<<2))>>4|(3855&e7)<<4))>>8|(255&e7)<<8)>>1}var MH=function(k,f,_){for(var S=k.length,L=0,O=new TH(f);L>Y]=re;return z},LH=new l_(288);for(hm=0;hm<144;++hm)LH[hm]=8;for(hm=144;hm<256;++hm)LH[hm]=9;for(hm=256;hm<280;++hm)LH[hm]=7;for(hm=280;hm<288;++hm)LH[hm]=8;var vst=new l_(32);for(hm=0;hm<32;++hm)vst[hm]=5;var oQt=MH(LH,9),lQt=MH(vst,5),SMe=function(k){for(var f=k[0],_=1;_f&&(f=k[_]);return f},R2=function(k,f,_){var S=f/8|0;return(k[S]|k[S+1]<<8)>>(7&f)&_},CMe=function(k,f){var _=f/8|0;return(k[_]|k[_+1]<<8|k[_+2]<<16)>>(7&f)},cQt=function(k){return(k+7)/8|0},dQt=["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"],O2=function(k,f,_){var S=new Error(f||dQt[k]);if(S.code=k,Error.captureStackTrace&&Error.captureStackTrace(S,O2),!_)throw S;return S},uQt=new l_(0),hQt=typeof TextDecoder<"u"&&new TextDecoder;try{hQt.decode(uQt,{stream:!0})}catch{}const mQt={gzip_data:"gzip"};class Yw extends Error{constructor(f){super(f),this.name="MRTError"}}const pQt={0:"uint32",1:"uint32",2:"uint16",3:"uint8"},bst={uint32:1,uint16:2,uint8:4},fQt={uint32:Uint32Array,uint16:Uint16Array,uint8:Uint8Array};let AMe;class Ise{constructor(f=5){this.x=NaN,this.y=NaN,this.z=NaN,this.layers={},this._cacheSize=f}getLayer(f){const _=this.layers[f];if(!_)throw new Yw(`Layer '${f}' not found`);return _}getHeaderLength(f){const _=new Uint8Array(f),S=new DataView(f);if(_[0]!==13)throw new Yw("File is not a valid MRT.");return S.getUint32(1,!0)}parseHeader(f){const _=new Uint8Array(f),S=this.getHeaderLength(f);if(_.length= ${S} but got buffer of length ${_.length}`);const L=new AMe(_.subarray(0,S)).readFields(GXt,{headerLength:0,x:0,y:0,z:0,layers:[]},void 0);if(!isNaN(this.x)&&(this.x!==L.x||this.y!==L.y||this.z!==L.z))throw new Yw(`Invalid attempt to parse header ${L.z}/${L.x}/${L.y} for tile ${this.z}/${this.x}/${this.y}`);this.x=L.x,this.y=L.y,this.z=L.z;for(const O of L.layers)this.layers[O.name]=new _st(O,{cacheSize:this._cacheSize});return this}createDecodingTask(f){const _=[],S=this.getLayer(f.layerName);for(let L of f.blockIndices){const O=S.dataIndex[L],z=O.firstByte-f.firstByte,G=O.lastByte-f.firstByte;if(S._blocksInProgress.has(L))continue;const Y={layerName:S.name,firstByte:z,lastByte:G,pixelFormat:S.pixelFormat,blockIndex:L,blockShape:[O.bands.length].concat(S.bandShape),buffer:S.buffer,codec:O.codec.codec,filters:O.filters.map(re=>re.filter)};S._blocksInProgress.add(L),_.push(Y)}return new wst(_,()=>{_.forEach(L=>S._blocksInProgress.delete(L.blockIndex))},(L,O)=>{if(_.forEach(z=>S._blocksInProgress.delete(z.blockIndex)),L)throw L;O.forEach(z=>{this.getLayer(z.layerName).processDecodedData(z)})})}}class _st{constructor({version:f,name:_,units:S,tileSize:L,pixelFormat:O,buffer:z,dataIndex:G},Y){if(this.version=f,this.version!==1)throw new Yw(`Cannot parse raster layer encoded with MRT version ${f}`);this.name=_,this.units=S,this.tileSize=L,this.buffer=z,this.pixelFormat=pQt[O],this.dataIndex=G,this.bandShape=[L+2*z,L+2*z,bst[this.pixelFormat]],this._decodedBlocks=new Lse(Y?Y.cacheSize:5),this._blocksInProgress=new Set}get dimension(){return bst[this.pixelFormat]}get cacheSize(){return this._decodedBlocks.capacity}getBandList(){return this.dataIndex.map(({bands:f})=>f).flat()}processDecodedData(f){const _=f.blockIndex.toString();this._decodedBlocks.get(_)||this._decodedBlocks.put(_,f.data)}getBlockForBand(f){let _=0;switch(typeof f){case"string":for(const[S,L]of this.dataIndex.entries()){for(const[O,z]of L.bands.entries())if(z===f)return{bandIndex:_+O,blockIndex:S,blockBandIndex:O};_+=L.bands.length}break;case"number":for(const[S,L]of this.dataIndex.entries()){if(f>=_&&f<_+L.bands.length)return{bandIndex:f,blockIndex:S,blockBandIndex:f-_};_+=L.bands.length}break;default:throw new Yw(`Invalid band \`${JSON.stringify(f)}\`. Expected string or integer.`)}return{blockIndex:-1,blockBandIndex:-1}}getDataRange(f){let _=1/0,S=-1/0;const L=[],O=new Set;for(const z of f){const{blockIndex:G}=this.getBlockForBand(z);if(G<0)throw new Yw(`Invalid band: ${JSON.stringify(z)}`);const Y=this.dataIndex[G];L.includes(G)||L.push(G),O.add(G),_=Math.min(_,Y.firstByte),S=Math.max(S,Y.lastByte)}if(O.size>this.cacheSize)throw new Yw(`Number of blocks to decode (${O.size}) exceeds cache size (${this.cacheSize}).`);return{layerName:this.name,firstByte:_,lastByte:S,blockIndices:L}}hasBand(f){const{blockIndex:_}=this.getBlockForBand(f);return _>=0}hasDataForBand(f){const{blockIndex:_}=this.getBlockForBand(f);return _>=0&&!!this._decodedBlocks.get(_.toString())}getBandView(f){const{blockIndex:_,blockBandIndex:S}=this.getBlockForBand(f);if(_<0)throw new Yw(`Band not found: ${JSON.stringify(f)}`);const L=this._decodedBlocks.get(_.toString());if(!L)throw new Yw(`Data for band ${JSON.stringify(f)} of layer "${this.name}" not decoded.`);const O=this.dataIndex[_],z=this.bandShape.reduce((re,me)=>re*me,1),G=S*z,Y=L.subarray(G,G+z);return{data:Y,bytes:new Uint8Array(Y.buffer).subarray(Y.byteOffset,Y.byteOffset+Y.byteLength),tileSize:this.tileSize,buffer:this.buffer,pixelFormat:this.pixelFormat,dimension:this.dimension,offset:O.offset,scale:O.scale}}}Ise.setPbf=function(k){AMe=k};class wst{constructor(f,_,S){this.tasks=f,this._onCancel=_,this._onComplete=S,this._finalized=!1}cancel(){this._finalized||(this._onCancel(),this._finalized=!0)}complete(f,_){this._finalized||(this._onComplete(f,_),this._finalized=!0)}}Ise.performDecoding=function(k,f){const _=new Uint8Array(k);return Promise.all(f.tasks.map(S=>{const{layerName:L,firstByte:O,lastByte:z,pixelFormat:G,blockShape:Y,blockIndex:re,filters:me,codec:ye}=S,we=_.subarray(O,z+1),Te=new Uint32Array(Y[0]*Y[1]*Y[2]);let Ie;if(ye!=="gzip_data")throw new Yw(`Unhandled codec: ${ye}`);return Ie=function(Ve,Je){if(!globalThis.DecompressionStream&&Je==="gzip_data")return Promise.resolve((Pt=function(ns){ns[0]==31&&ns[1]==139&&ns[2]==8||O2(6,"invalid gzip data");var xs=ns[3],us=10;4&xs&&(us+=2+(ns[10]|ns[11]<<8));for(var hs=(xs>>3&1)+(xs>>4&1);hs>0;hs-=!ns[us++]);return us+(2&xs)}(rt=Ve),Pt+8>rt.length&&O2(6,"invalid gzip data"),function(ns,xs,us,hs){var pn=ns.length;if(!pn||xs.f&&!xs.l)return us||new l_(0);var bn=!us,An=bn||xs.i!=2,Ln=xs.i;bn&&(us=new l_(3*pn));var En=function(Fd){var Xx=us.length;if(Fd>Xx){var bp=new l_(Math.max(2*Xx,Fd));bp.set(us),us=bp}},Jn=xs.f||0,un=xs.p||0,Mn=xs.b||0,Rn=xs.l,er=xs.d,ur=xs.m,Zr=xs.n,Nr=8*pn;do{if(!Rn){Jn=R2(ns,un,1);var wr=R2(ns,un+1,3);if(un+=3,!wr){var hr=ns[(ll=cQt(un)+4)-4]|ns[ll-3]<<8,Gr=ll+hr;if(Gr>pn){Ln&&O2(0);break}An&&En(Mn+hr),us.set(ns.subarray(ll,Gr),Mn),xs.b=Mn+=hr,xs.p=un=8*Gr,xs.f=Jn;continue}if(wr==1)Rn=oQt,er=lQt,ur=9,Zr=5;else if(wr==2){var aa=R2(ns,un,31)+257,Da=R2(ns,un+10,15)+4,_a=aa+R2(ns,un+5,31)+1;un+=14;for(var _i=new l_(_a),To=new l_(19),wi=0;wi>4)<16)_i[wi++]=ll;else{var ac=0,kd=0;for(ll==16?(kd=3+R2(ns,un,3),un+=2,ac=_i[wi-1]):ll==17?(kd=3+R2(ns,un,7),un+=3):ll==18&&(kd=11+R2(ns,un,127),un+=7);kd--;)_i[wi++]=ac}}var $m=_i.subarray(0,aa),Sd=_i.subarray(aa);ur=SMe($m),Zr=SMe(Sd),Rn=MH($m,ur),er=MH(Sd,Zr)}else O2(1);if(un>Nr){Ln&&O2(0);break}}An&&En(Mn+131072);for(var ru=(1<>4;if((un+=15&ac)>Nr){Ln&&O2(0);break}if(ac||O2(2),qf<256)us[Mn++]=qf;else{if(qf==256){au=un,Rn=null;break}var Um=qf-254;qf>264&&(Um=R2(ns,un,(1<<(Nu=mst[wi=qf-257]))-1)+gst[wi],un+=Nu);var Xi=er[CMe(ns,un)&sh],Kg=Xi>>4;if(Xi||O2(3),un+=15&Xi,Sd=iQt[Kg],Kg>3){var Nu=pst[Kg];Sd+=CMe(ns,un)&(1<Nr){Ln&&O2(0);break}An&&En(Mn+131072);var vp=Mn+Um;if(MnFd.length)&&(bp=Fd.length),new l_(Fd.subarray(0,bp))}(us,0,Mn):us.subarray(0,Mn)}(rt.subarray(Pt,-8),{i:2},new l_(((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,Pt;const Rt=mQt[Je];if(!Rt)throw new Error(`Unhandled codec: ${Je}`);const ws=new globalThis.DecompressionStream(Rt);return new Response(new Blob([Ve]).stream().pipeThrough(ws)).arrayBuffer().then(ns=>new Uint8Array(ns))}(we,ye).then(Ve=>(function(Je,rt){Je.readFields(QXt,rt)}(new AMe(Ve),Te),new fQt[G](Te.buffer))),Ie.then(Ve=>{for(let Je=me.length-1;Je>=0;Je--)switch(me[Je]){case"delta_filter":eQt(Ve,Y);break;case"zigzag_filter":tQt(Ve);break;case"bitshuffle_filter":sQt(Ve,G);break;default:throw new Yw(`Unhandled filter "${me[Je]}"`)}return{layerName:L,blockIndex:re,data:Ve}}).catch(Ve=>{throw Ve})}))},br(wst,"MRTDecodingBatch",{omit:["_onCancel","_onComplete"]}),br(Ise,"MapboxRasterTile"),br(_st,"MapboxRasterLayer",{omit:["_blocksInProgress"]});const jst=[Int8Array,Uint8Array,Uint8ClampedArray,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array];class EMe{static from(f){if(!(f instanceof ArrayBuffer))throw new Error("Data must be an instance of ArrayBuffer.");const[_,S]=new Uint8Array(f,0,2);if(_!==219)throw new Error("Data does not appear to be in a KDBush format.");const L=S>>4;if(L!==1)throw new Error(`Got v${L} data when expected v1.`);const O=jst[15&S];if(!O)throw new Error("Unrecognized array type.");const[z]=new Uint16Array(f,2,1),[G]=new Uint32Array(f,4,1);return new EMe(G,z,O,f)}constructor(f,_=64,S=Float64Array,L){if(isNaN(f)||f<0)throw new Error(`Unpexpected numItems value: ${f}.`);this.numItems=+f,this.nodeSize=Math.min(Math.max(+_,2),65535),this.ArrayType=S,this.IndexArrayType=f<65536?Uint16Array:Uint32Array;const O=jst.indexOf(this.ArrayType),z=2*f*this.ArrayType.BYTES_PER_ELEMENT,G=f*this.IndexArrayType.BYTES_PER_ELEMENT,Y=(8-G%8)%8;if(O<0)throw new Error(`Unexpected typed array class: ${S}.`);L&&L instanceof ArrayBuffer?(this.data=L,this.ids=new this.IndexArrayType(this.data,8,f),this.coords=new this.ArrayType(this.data,8+G+Y,2*f),this._pos=2*f,this._finished=!0):(this.data=new ArrayBuffer(8+z+G+Y),this.ids=new this.IndexArrayType(this.data,8,f),this.coords=new this.ArrayType(this.data,8+G+Y,2*f),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]=f)}add(f,_){const S=this._pos>>1;return this.ids[S]=S,this.coords[this._pos++]=f,this.coords[this._pos++]=_,S}finish(){const f=this._pos>>1;if(f!==this.numItems)throw new Error(`Added ${f} items when expected ${this.numItems}.`);return TMe(this.ids,this.coords,this.nodeSize,0,this.numItems-1,0),this._finished=!0,this}range(f,_,S,L){if(!this._finished)throw new Error("Data not yet indexed - call index.finish().");const{ids:O,coords:z,nodeSize:G}=this,Y=[0,O.length-1,0],re=[];for(;Y.length;){const me=Y.pop()||0,ye=Y.pop()||0,we=Y.pop()||0;if(ye-we<=G){for(let Je=we;Je<=ye;Je++){const rt=z[2*Je],xt=z[2*Je+1];rt>=f&&rt<=S&&xt>=_&&xt<=L&&re.push(O[Je])}continue}const Te=we+ye>>1,Ie=z[2*Te],Ve=z[2*Te+1];Ie>=f&&Ie<=S&&Ve>=_&&Ve<=L&&re.push(O[Te]),(me===0?f<=Ie:_<=Ve)&&(Y.push(we),Y.push(Te-1),Y.push(1-me)),(me===0?S>=Ie:L>=Ve)&&(Y.push(Te+1),Y.push(ye),Y.push(1-me))}return re}within(f,_,S){if(!this._finished)throw new Error("Data not yet indexed - call index.finish().");const{ids:L,coords:O,nodeSize:z}=this,G=[0,L.length-1,0],Y=[],re=S*S;for(;G.length;){const me=G.pop()||0,ye=G.pop()||0,we=G.pop()||0;if(ye-we<=z){for(let Je=we;Je<=ye;Je++)kst(O[2*Je],O[2*Je+1],f,_)<=re&&Y.push(L[Je]);continue}const Te=we+ye>>1,Ie=O[2*Te],Ve=O[2*Te+1];kst(Ie,Ve,f,_)<=re&&Y.push(L[Te]),(me===0?f-S<=Ie:_-S<=Ve)&&(G.push(we),G.push(Te-1),G.push(1-me)),(me===0?f+S>=Ie:_+S>=Ve)&&(G.push(Te+1),G.push(ye),G.push(1-me))}return Y}}function TMe(k,f,_,S,L,O){if(L-S<=_)return;const z=S+L>>1;Nst(k,f,z,S,L,O),TMe(k,f,_,S,z-1,1-O),TMe(k,f,_,z+1,L,1-O)}function Nst(k,f,_,S,L,O){for(;L>S;){if(L-S>600){const re=L-S+1,me=_-S+1,ye=Math.log(re),we=.5*Math.exp(2*ye/3),Te=.5*Math.sqrt(ye*we*(re-we)/re)*(me-re/2<0?-1:1);Nst(k,f,_,Math.max(S,Math.floor(_-me*we/re+Te)),Math.min(L,Math.floor(_+(re-me)*we/re+Te)),O)}const z=f[2*_+O];let G=S,Y=L;for(PH(k,f,S,_),f[2*L+O]>z&&PH(k,f,S,L);Gz;)Y--}f[2*S+O]===z?PH(k,f,S,Y):(Y++,PH(k,f,Y,L)),Y<=_&&(S=Y+1),_<=Y&&(L=Y-1)}}function PH(k,f,_,S){MMe(k,_,S),MMe(f,2*_,2*S),MMe(f,2*_+1,2*S+1)}function MMe(k,f,_){const S=k[f];k[f]=k[_],k[_]=S}function kst(k,f,_,S){const L=k-_,O=f-S;return L*L+O*O}o.$=zf,o.A=class{constructor(k,f,_){this.target=k,this.parent=f,this.mapId=_,this.callbacks={},this.cancelCallbacks={},qt(["receive"],this),this.target.addEventListener("message",this.receive,!1),this.scheduler=new NXt}send(k,f,_,S,L=!1,O){const z=Math.round(1e18*Math.random()).toString(36).substring(0,10);_&&(_.metadata=O,this.callbacks[z]=_);const G=new Set;return this.target.postMessage({id:z,type:k,hasCallback:!!_,targetMapId:S,mustQueue:L,sourceMapId:this.mapId,data:Fc(f,G)},G),{cancel:()=>{_&&delete this.callbacks[z],this.target.postMessage({id:z,type:"",targetMapId:S,sourceMapId:this.mapId})}}}receive(k){const f=k.data;if(!f)return;const _=f.id;if(_&&(!f.targetMapId||this.mapId===f.targetMapId))if(f.type===""){const S=this.cancelCallbacks[_];delete this.cancelCallbacks[_],S&&S.cancel()}else if(f.mustQueue||hi(self)){const S=this.callbacks[_],L=this.scheduler.add(()=>this.processTask(_,f),S&&S.metadata||{type:"message"});L&&(this.cancelCallbacks[_]=L)}else this.processTask(_,f)}processTask(k,f){if(delete this.cancelCallbacks[k],f.type===""){const _=this.callbacks[k];delete this.callbacks[k],_&&(f.error?_(lc(f.error)):_(null,lc(f.data)))}else{const _=new Set,S=f.hasCallback?(O,z)=>{this.target.postMessage({id:k,type:"",sourceMapId:this.mapId,error:O?Fc(O):null,data:Fc(z,_)},_)}:()=>{},L=lc(f.data);if(this.parent[f.type])this.parent[f.type](f.sourceMapId,L,S);else if(this.parent.getWorkerSource){const O=f.type.split("."),{source:z,scope:G}=L;this.parent.getWorkerSource(f.sourceMapId,{type:O[0],source:z,scope:G,uid:0})[O[1]](L,S)}else S(new Error(`Could not find function ${f.type}`))}}remove(){this.scheduler.remove(),this.target.removeEventListener("message",this.receive,!1)}},o.B=cp,o.C=Oc,o.D=wd,o.E=om,o.F=Et,o.G=2,o.H=xH,o.I=Rh,o.J=qet,o.K=$g,o.L=n4,o.M=Gx,o.N=R0,o.O=Nd,o.P=Xt,o.Q=Yo,o.R=lp,o.S=Oh,o.T=Ik,o.U=Im,o.V=Sse,o.W=Sk,o.X=Vc,o.Y=Du,o.Z=eu,o._=B1,o.a=function(k){return Kn.API_CDN_URL_REGEX.test(k)},o.a$=lse,o.a0=Qc,o.a1=Of,o.a2=px,o.a3=Bs,o.a4=r4,o.a5=class extends Sse{},o.a6=tu,o.a7=jd,o.a8=$s,o.a9=function(k){const f=k.value;return f?px(f)?yMe(f,!0)?[]:[new Sse(k.key,f,`invalid url "${f}"`)]:[new Sse(k.key,f,`string expected, "${Gx(f)}" found`)]:[]},o.aA=xet,o.aB=function(k){let f=1/0,_=1/0,S=-1/0,L=-1/0;for(const O of k)f=Math.min(f,O.x),_=Math.min(_,O.y),S=Math.max(S,O.x),L=Math.max(L,O.y);return{min:new Xt(f,_),max:new Xt(S,L)}},o.aC=pt,o.aD=v,o.aE=nt,o.aF=Vt,o.aG=K0,o.aH=Dn,o.aI=Yr,o.aJ=function(k,f){const _={};for(let S=0;S=0?f.slice(_+1):""}catch{return""}},o.aN=class{constructor(k){this.entries={},this.scheduler=k}request(k,f,_,S){const L=this.entries[k]=this.entries[k]||{callbacks:[]};if(L.result){const[O,z]=L.result;return this.scheduler?this.scheduler.add(()=>{S(O,z)},f):S(O,z),()=>{}}return L.callbacks.push(S),L.cancel||(L.cancel=_((O,z)=>{L.result=[O,z];for(const G of L.callbacks)this.scheduler?this.scheduler.add(()=>{G(O,z)},f):G(O,z);setTimeout(()=>delete this.entries[k],3e3)})),()=>{L.result||(L.callbacks=L.callbacks.filter(O=>O!==S),L.callbacks.length||(L.cancel(),delete this.entries[k]))}}},o.aO=function(k,f,_){const S=JSON.stringify(k.request);return k.data&&(this.deduped.entries[S]={result:[null,k.data]}),this.deduped.request(S,{type:"parseTile",renderSourceType:k.renderSourceType,zoom:k.tileZoom},L=>{const O=mh(k.request,(z,G,Y)=>{z?Kd(z)?L(null,null):L(z):G&&L(null,{rawData:G,vectorTile:_?void 0:new Zo(new lse(G)),responseHeaders:new Map(Y.entries())})});return()=>{O.cancel(),L(null,null)}},f)},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){Zi++,Zi>Em&&(k.getActor().send("enforceCacheSizeLimit",Dg),Zi=0)},o.aR=Wg,o.aS=Ntt,o.aT=Ltt,o.aU=As,o.aV=jtt,o.aW=function(k,f){const _=document.createElement("video");_.muted=!0,_.onloadstart=function(){f(null,_)};for(let S=0;S{}}},o.aX=uH,o.aY=LM,o.aZ=qt,o.a_=Ise,o.aa=PC,o.ab=bc,o.ac=ir,o.ad=class{constructor(k){this.specification=k}possiblyEvaluate(k,f){return va(k.expression.evaluate(f))}interpolate(k,f,_){return{x:Cs(k.x,f.x,_),y:Cs(k.y,f.y,_),z:Cs(k.z,f.z,_),azimuthal:Cs(k.azimuthal,f.azimuthal,_),polar:Cs(k.polar,f.polar,_)}}},o.ae=Si,o.af=Xl,o.ag=ra,o.ah=Xe,o.ai=K,o.aj=vt,o.ak=Fm,o.al=u4,o.am=Cs,o.an=lr,o.ao=xn,o.ap=$n,o.aq=Ys,o.ar=class{constructor(k){this.specification=k}possiblyEvaluate(k,f){return function([_,S]){const L=va([1,_,S]);return{x:L.x,y:L.y,z:L.z}}(k.expression.evaluate(f))}interpolate(k,f,_){return{x:Cs(k.x,f.x,_),y:Cs(k.y,f.y,_),z:Cs(k.z,f.z,_)}}},o.as=function(k,f,_=0,S=!0){const L=new Xt(_,_),O=k.sub(L),z=f.add(L),G=[O,new Xt(z.x,O.y),z,new Xt(O.x,z.y)];return S&&G.push(O.clone()),G},o.at=function(k,f){const _=[];for(let S=0;Sthis.buckets[ye].layers.some(we=>z.has(we.fqid))),Y=Object.keys(this.buckets).some(ye=>this.buckets[ye].layers.some(we=>we.hasTransition&&we.hasTransition())),re=this._firstPrepareComplete&&O!==this._lastAvailableImagesCount;this._hasAppearances===null&&(this._hasAppearances=this.hasAppearances(f));const me=this._lastUpdatedBrightness!==S;this._lastAvailableImagesCount=O,this._firstPrepareComplete=!0,(this._lastUpdatedBrightness||S||this._hasAppearances||G||Y||re)&&(!(this._hasAppearances||G||Y||re)&&this._lastUpdatedBrightness&&S&&Math.abs(this._lastUpdatedBrightness-S)<.001||(this.updateBuckets(f,me,void 0,re||G||Y,z,L),this._lastUpdatedBrightness=S))}evaluateQueryRenderedFeaturePadding(){let k=0;for(const f in this.buckets){const _=this.buckets[f];_.evaluateQueryRenderedFeaturePadding&&(k=Math.max(k,_.evaluateQueryRenderedFeaturePadding()))}return k}queryRenderedFeatures(k,f,_,S,L,O,z){if(!this.latestFeatureIndex||!this.latestFeatureIndex.rawTileData&&!this.latestFeatureIndex.is3DTile)return{};const G=this.evaluateQueryRenderedFeaturePadding(),Y=function(re,me){const ye=M([],[.5*re.width,.5*-re.height,1]);return N(ye,ye,[1,-1,0]),v(ye,ye,re.calculateProjMatrix(me.toUnwrapped())),Float32Array.from(ye)}(L,this.tileID);return this.latestFeatureIndex.query(k,{tilespaceGeometry:f,pixelPosMatrix:Y,transform:S,availableImages:_,tileTransform:this.tileTransform,worldview:this.worldview,queryRadius:G,scope:z})}querySourceFeatures(k,f){const _=this.latestFeatureIndex;if(!_||!_.rawTileData)return;const S=_.loadVTLayers(),L=f?f.sourceLayer:"",O=S._geojsonTileLayer||S[L];if(!O)return;const z=RC(f&&f.filter),{z:G,x:Y,y:re}=this.tileID.canonical,me={z:G,x:Y,y:re};for(let ye=0;ye_)S=!1;else if(f)if(this.expirationTime_.appearances&&_.appearances.length>0))return!0;return!1}updateBuckets(k,f,_,S,L,O){if(!this.latestFeatureIndex||!k.style)return;const z=O||k.style.listImages(),G=k.style.getBrightness(),Y=L||new Set;for(const re in this.buckets){if(!k.style.hasLayer(re))continue;const me=this.buckets[re],ye=me.layers[0],we=ye.sourceLayer||"_geojsonTileLayer",Te=k.style.getLayerSourceCache(ye),Ie=me.layers.some(Pt=>Y.has(Pt.fqid)),Ve=(S||Ie)&&me instanceof D2?k.style.getOwnLayer(re):void 0;let Je=_&&_[we]||{};Te&&!_&&(Je=Te._state.getState(we,void 0));const rt=this.imageAtlas?Object.fromEntries(this.imageAtlas.patternPositions):{},xt=Object.keys(Je).length>0&&!f;me.hasAppearances=me.layers.some(Pt=>Pt.appearances&&Pt.appearances.length>0);const ut=xt?me.stateDependentLayers:me.layers;if(xt&&me.stateDependentLayers.length!==0||f||Ie||S){const Pt=this.latestFeatureIndex.loadVTLayers()[we];if(me.update(Je,Pt,z,rt,ut,f,G,this.tileID.canonical),(S||Ie)&&!f&&me instanceof D2&&Ve&&Ve.type==="symbol"){const Rt=me;Rt.text&&Rt.text.uboBinder&&Rt.text.uboBinder.updateDynamicExpressions(Ve,Pt,this.tileID.canonical,z,Je,G),Rt.icon&&Rt.icon.uboBinder&&Rt.icon.uboBinder.updateDynamicExpressions(Ve,Pt,this.tileID.canonical,z,Je,G)}if(me instanceof D2){const Rt=me,ws=k.context;Rt.text&&Rt.text.uboBinder&&Rt.text.uboBinder.upload(ws),Rt.icon&&Rt.icon.uboBinder&&Rt.icon.uboBinder.upload(ws)}}if(xt&&me.stateDependentLayers.length!==0||f||me.hasAppearances){const Pt={zoom:k.transform.zoom,pitch:k.transform.pitch,brightness:k.style.getBrightness()||0,worldview:k.worldview},Rt=me.updateAppearances(this.tileID.canonical,Je,z,Pt,k.imageManager,xt&&me.stateDependentLayers.length!==0);if(Rt&&Rt.hasUboChanges){const ws=k.context;me instanceof D2&&me.text&&me.text.uboBinder&&me.text.uboBinder.upload(ws),me instanceof D2&&me.icon&&me.icon.uboBinder&&me.icon.uboBinder.upload(ws)}}(me instanceof ose||me instanceof Ute)&&k._terrain&&k._terrain.enabled&&Te&&me.uploadPending()&&k._terrain._clearRenderCacheForTile(Te.id,this.tileID);const St=k&&k.style&&k.style.getOwnLayer(re);St&&(this.queryPadding=Math.max(this.queryPadding,St.queryRadius(me)||0))}}holdingForFade(){return this.symbolFadeHoldUntil!==void 0}symbolFadeFinished(){return!this.symbolFadeHoldUntil||this.symbolFadeHoldUntil=0;Ve--){const Je=4*Ve,rt=YC[Je+0],xt=YC[Je+1],ut=YC[Je+2],St=YC[Je+3],Pt=rt+ut>>1,Rt=xt+St>>1,ws=Pt+Rt-xt,ns=Rt+rt-Pt,xs=xt*Dk+rt,us=St*Dk+ut,hs=Rt*Dk+Pt,pn=Math.hypot((Rk[2*xs+0]+Rk[2*us+0])/2-Rk[2*hs+0],(Rk[2*xs+1]+Rk[2*us+1])/2-Rk[2*hs+1])>=16;ZC[hs]=ZC[hs]||(pn?1:0),Ve<1022&&(ZC[hs]=ZC[hs]||ZC[(xt+ns>>1)*Dk+(rt+ws>>1)]||ZC[(St+ns>>1)*Dk+(ut+ws>>1)])}const me=new so,ye=new nu;let we=0;function Te(Ve,Je){const rt=Je*Dk+Ve;return Ase[rt]===0&&(me.emplaceBack(Rk[2*rt+0],Rk[2*rt+1],Ve*lr/Kw,Je*lr/Kw),Ase[rt]=++we),Ase[rt]-1}function Ie(Ve,Je,rt,xt,ut,St){const Pt=Ve+rt>>1,Rt=Je+xt>>1;if(Math.abs(Ve-ut)+Math.abs(Je-St)>1&&ZC[Rt*Dk+Pt])Ie(ut,St,Ve,Je,Pt,Rt),Ie(rt,xt,ut,St,Pt,Rt);else{const ws=Te(Ve,Je),ns=Te(rt,xt),xs=Te(ut,St);ye.emplaceBack(ws,ns,xs)}}return Ie(0,0,Kw,Kw,Kw,0),Ie(Kw,Kw,0,0,0,Kw),{vertices:me,indices:ye}}(this.tileID.canonical,f);S=O.vertices,L=O.indices}else{S=new so,L=new nu;for(const{x:z,y:G}of _)S.emplaceBack(z,G,0,0);const O=FF(S.int16.subarray(0,4*S.length),void 0,4);for(let z=0;z0&&(z=b(new Float64Array(16),f.globeMatrix)),this._makeGlobeTileDebugBorderBuffer(k,S,f,L,z,O),this._makeGlobeTileDebugTextBuffer(k,S,f,L,z,O)}_globePoint(k,f,_,S,L,O,z){let G=KV(k,f,_);if(O){const Y=1<<_.z,re=Dn(S.center.lng),me=Gn(S.center.lat),ye=(_.x+.5)/Y-re;let we=0;ye>.5?we=-1:ye<-.5&&(we=1);let Te=(k/lr+_.x)/Y+we,Ie=(f/lr+_.y)/Y;Te=(Te-re)*S._pixelsPerMercatorPixel+re,Ie=(Ie-me)*S._pixelsPerMercatorPixel+me;const Ve=[Te*S.worldSize,Ie*S.worldSize,0];Xe(Ve,Ve,O),G=d4(G,Ve,z)}return Xe(G,G,L)}_makeGlobeTileDebugBorderBuffer(k,f,_,S,L,O){const z=new zi,G=new o4,Y=new Wo,re=(ye,we,Te,Ie,Ve)=>{const Je=(Te-ye)/(Ve-1),rt=(Ie-we)/(Ve-1),xt=z.length;for(let ut=0;utre*ye+we;for(let ye=0;ye1)return!1;const _=f.getSource().maxzoom,S=1<<_,L=Math.floor(k.x),O=Math.floor((k.x-L)*S),z=Math.floor(k.y*S),G=this.findDEMTileFor(new Wg(_,L,_,O,z));return!(!G||!G.dem)}getAtPointOrZero(k,f=0){return this.getAtPoint(k,f)||0}getAtPoint(k,f,_=!0){if(this.isUsingMockSource())return null;f==null&&(f=null);const S=this._source();if(!S||k.y<0||k.y>1)return f;const L=S.getSource().maxzoom,O=1<{const G=this.getAtTileOffset(k,L,O,z),Y=S.upVector(k.canonical,L.x,L.y);return he(Y,Y,G*S.upVectorScale(k.canonical,f,_).metersToTile),Y}}getForTilePoints(k,f,_,S){if(this.isUsingMockSource())return!1;const L=XF.create(this,k,S);return!!L&&(f.forEach(O=>{O[2]=this.exaggeration()*L.getElevationAt(O[0],O[1],_)}),!0)}getMinMaxForTile(k){if(this.isUsingMockSource())return null;const f=this.findDEMTileFor(k);if(!f||!f.dem)return null;const _=f.dem.tree,S=f.tileID,L=1<0&&(S+=(k[L]-0)*(k[L]-0)),f[L]<0&&(S+=(0-f[L])*(0-f[L]));return S},o.cL=function(k){return k*k*k*k*k},o.cM=an,o.cN=45,o.cO=DF,o.cP=function(k,f,_){const S=Math.sqrt(k*k+f*f+_*_),L=S>0?Math.acos(_/S)*Sn:0;let O=k!==0||f!==0?Math.atan2(-f,-k)*Sn+90:0;return O<0&&(O+=360),[S,O,L]},o.cQ=Q,o.cR=va,o.cS=Bn,o.cT=ce,o.cU=ul,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=QJe,o.cY=B6e,o.cZ=net,o.c_=yMe,o.ca=2,o.cb=7,o.cc=6,o.cd=ke,o.ce=W,o.cf=V,o.cg=0,o.ch=1,o.ci=4,o.cj=5,o.ck=OF,o.cl=Oy,o.cm=eet,o.cn=wM,o.co=EQe,o.cp=function(k,f,_,S,L,O,z,G,Y){if(Y.name==="globe")return EQe(k,f,new wM(_,S,L),!1);const re=EM({z:_,x:S,y:L},Y);return new ul([(O+re.x/re.scale)*f,f*(re.y/re.scale),z],[(O+re.x2/re.scale)*f,f*(re.y2/re.scale),G])},o.cq=function(k,f,_){return k[0]=Math.min(f[0],_[0]),k[1]=Math.min(f[1],_[1]),k[2]=Math.min(f[2],_[2]),k[3]=Math.min(f[3],_[3]),k},o.cr=function(k,f,_){return k[0]=Math.max(f[0],_[0]),k[1]=Math.max(f[1],_[1]),k[2]=Math.max(f[2],_[2]),k[3]=Math.max(f[3],_[3]),k},o.cs=function(k){const f=Math.round((k+45+360)%360/90)%4;return ln[f]},o.ct=kn,o.cu=et,o.cv=6,o.cw=function(k){const f=y(new Float64Array(16));v(f,k.pixelMatrix,k.globeMatrix);const _=[0,ss,0],S=[0,Ns,0];return Xe(_,_,f),Xe(S,S,f),[_[0]>0&&_[0]<=k.width&&_[1]>0&&_[1]<=k.height&&!o6e(k,new As(k.center.lat,90)),S[0]>0&&S[0]<=k.width&&S[1]>0&&S[1]<=k.height&&!o6e(k,new As(k.center.lat,-90))]},o.cx=function(k,f){const{scale:_}=k.tileTransform,S=_*lr/(k.tileSize*Math.pow(2,f.zoom-k.tileID.overscaledZ+k.tileID.canonical.z));return function(L,O,z){var G=O[1],Y=O[2],re=O[3],me=z[0],ye=z[1];return L[0]=O[0]*me,L[1]=G*me,L[2]=Y*ye,L[3]=re*ye,L}(new Float32Array(4),f.inverseAdjustmentMatrix,[S,S])},o.cy=tse,o.cz=q,o.d=function(k){return Kn.API_TILEJSON_REGEX.test(k)},o.d$=NKt,o.d0=Rd,o.d1=class{static calculate(k,f,_){const S=new Set,L=new Map,O=new Set,z=new Set;for(const Y of Object.values(k))for(const[re,me]of Object.entries(Y.floors)){O.add(re),me.isDefault&&z.add(re),me.conflicts&&L.set(re,me.conflicts);const ye=re===f,we=me.connections&&f&&me.connections.has(f);(ye||we)&&S.add(re)}const G=Y=>{const re=L.get(Y)||new Set;for(const me of S)if((L.get(me)||new Set).has(Y)||re.has(me))return!0;return!1};if(_)for(const Y of _)O.has(Y)&&(G(Y)||S.add(Y));for(const Y of z)S.has(Y)||G(Y)||S.add(Y);return S}},o.d2=hse,o.d3=aMe,o.d4=Ti,o.d5=function(){return{API_URL:Kn.API_URL,DRACO_URL:Kn.DRACO_URL,MESHOPT_URL:Kn.MESHOPT_URL,MESHOPT_SIMD_URL:Kn.MESHOPT_SIMD_URL,BUILDING_GEN_URL:Kn.BUILDING_GEN_URL}},o.d6=_k,o.d7=Ay,o.d8=ld,o.d9=Hn,o.dA=Pte,o.dB=zi,o.dC=nu,o.dD=function(k,f){return[Math.pow(k[0],2.2)*f,Math.pow(k[1],2.2)*f,Math.pow(k[2],2.2)*f]},o.dE=h,o.dF=function(k,f){var _=Math.sin(f),S=Math.cos(f);return k[0]=S,k[1]=_,k[2]=0,k[3]=-_,k[4]=S,k[5]=0,k[6]=0,k[7]=0,k[8]=1,k},o.dG=Se,o.dH=MQe,o.dI=is,o.dJ=zr,o.dK=xMe,o.dL=function(k,f){const _=[0,0,0];return Xe(_,_,YV(Mk(f.canonical))),Xe(_,_,k),_},o.dM=k=>({u_matrix:new w(k),u_texsize:new Z1(k),u_pixels_to_tile_units:new H(k),u_device_pixel_ratio:new Fh(k),u_width_scale:new Fh(k),u_floor_width_scale:new Fh(k),u_image:new bM(k),u_units_to_pixels:new Z1(k),u_tile_units_to_pixels:new Fh(k),u_alpha_discard_threshold:new Fh(k),u_trim_offset:new Z1(k),u_trim_fade_range:new Z1(k),u_trim_gradient_mix_range:new Z1(k),u_trim_color:new DF(k),u_zbias_factor:new Fh(k),u_tile_to_meter:new Fh(k),u_ground_shadow_factor:new _M(k),u_pattern_transition:new Fh(k)}),o.dN=k=>({u_matrix:new w(k),u_pixels_to_tile_units:new H(k),u_device_pixel_ratio:new Fh(k),u_width_scale:new Fh(k),u_floor_width_scale:new Fh(k),u_units_to_pixels:new Z1(k),u_dash_image:new bM(k),u_gradient_image:new bM(k),u_image_height:new Fh(k),u_texsize:new Z1(k),u_tile_units_to_pixels:new Fh(k),u_alpha_discard_threshold:new Fh(k),u_trim_offset:new Z1(k),u_trim_fade_range:new Z1(k),u_trim_gradient_mix_range:new Z1(k),u_trim_color:new DF(k),u_zbias_factor:new Fh(k),u_tile_to_meter:new Fh(k),u_ground_shadow_factor:new _M(k)}),o.dO=k=>({u_camera_to_center_distance:new Fh(k),u_extrude_scale:new H(k),u_device_pixel_ratio:new Fh(k),u_matrix:new w(k),u_inv_rot_matrix:new w(k),u_merc_center:new Z1(k),u_tile_id:new _M(k),u_zoom_transition:new Fh(k),u_up_dir:new _M(k),u_emissive_strength:new Fh(k)}),o.dP=RV,o.dQ=jZt,o.dR=class{constructor(k,f,_,S){this.context=k,this.format=S,this.size=_,this.texture=k.gl.createTexture();const[L,O,z]=this.size,{gl:G}=k;G.bindTexture(G.TEXTURE_3D,this.texture),k.pixelStoreUnpackFlipY.set(!1),k.pixelStoreUnpack.set(1),k.pixelStoreUnpackPremultiplyAlpha.set(!1),"data"in f&&f.data&&G.texImage3D(G.TEXTURE_3D,0,this.format,L,O,z,0,P6e(this.format),I6e(this.format),f.data)}bind(k,f){const{context:_}=this,{gl:S}=_;S.bindTexture(S.TEXTURE_3D,this.texture),k!==this.minFilter&&(S.texParameteri(S.TEXTURE_3D,S.TEXTURE_MAG_FILTER,k),S.texParameteri(S.TEXTURE_3D,S.TEXTURE_MIN_FILTER,k),this.minFilter=k),f!==this.wrapS&&(S.texParameteri(S.TEXTURE_3D,S.TEXTURE_WRAP_S,f),S.texParameteri(S.TEXTURE_3D,S.TEXTURE_WRAP_T,f),this.wrapS=f)}destroy(){const{gl:k}=this.context;k.deleteTexture(this.texture),this.texture=null}},o.dS=DQe,o.dT=(k,f,_,S,L,O)=>{const z=k.transform,G=z.projection.name==="globe";let Y;if(O.paint.get("circle-pitch-alignment")==="map")if(G){const me=MQe(z.zoom,f.canonical)*z._pixelsPerMercatorPixel;Y=Float32Array.from([me,0,0,me])}else Y=z.calculatePixelsToTileUnitsMatrix(_);else Y=new Float32Array([z.pixelsToGLUnits[0],0,0,z.pixelsToGLUnits[1]]);const re={u_camera_to_center_distance:k.transform.getCameraToCenterDistance(z.projection),u_matrix:k.translatePosMatrix(f.projMatrix,_,O.paint.get("circle-translate"),O.paint.get("circle-translate-anchor")),u_device_pixel_ratio:bd.devicePixelRatio,u_extrude_scale:Y,u_inv_rot_matrix:TKt,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(G){re.u_inv_rot_matrix=S,re.u_merc_center=L,re.u_tile_id=[f.canonical.x,f.canonical.y,1<{const me=k.transform,ye=me.pitch<15?get(.07,.7,pt((14-me.zoom)/5,0,1)):.07,we=_.paint.get("line-trim-color-use-theme").constantOr("default")==="none";return{u_matrix:vet(k,f,_,S),u_texsize:f.imageAtlasTexture?f.imageAtlasTexture.size:[0,0],u_pixels_to_tile_units:me.calculatePixelsToTileUnitsMatrix(f),u_device_pixel_ratio:L,u_width_scale:O,u_floor_width_scale:z,u_image:0,u_tile_units_to_pixels:yet(f,me),u_units_to_pixels:[1/me.pixelsToGLUnits[0],1/me.pixelsToGLUnits[1]],u_alpha_discard_threshold:0,u_trim_offset:G,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(we?null:_.lut).toArray01(),u_zbias_factor:ye,u_tile_to_meter:Bn(f.tileID.canonical,0),u_ground_shadow_factor:Y,u_pattern_transition:re}},o.dX=(k,f,_,S,L,O,z,G,Y,re)=>{const me=k.transform,ye=me.calculatePixelsToTileUnitsMatrix(f),we=_.paint.get("line-trim-color-use-theme").constantOr("default")==="none",Te=me.pitch<15?get(.07,.7,pt((14-me.zoom)/5,0,1)):.07;return{u_matrix:vet(k,f,_,S),u_pixels_to_tile_units:ye,u_device_pixel_ratio:O,u_width_scale:z,u_floor_width_scale:G,u_units_to_pixels:[1/me.pixelsToGLUnits[0],1/me.pixelsToGLUnits[1]],u_dash_image:0,u_gradient_image:1,u_image_height:L,u_texsize:_et(_)&&f.lineAtlasTexture?f.lineAtlasTexture.size:[0,0],u_tile_units_to_pixels:yet(f,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(we?null:_.lut).toArray01(),u_zbias_factor:Te,u_tile_to_meter:Bn(f.tileID.canonical,0),u_ground_shadow_factor:re}},o.dY=cs,o.dZ=ZV,o.d_=vn,o.da=function(k){const f=k.indexOf(ct);return f>=0?k.slice(0,f):k},o.db=function(k){return k.indexOf(ct)>=0},o.dc=function(k){const f=k.lastIndexOf(ct);return f>=0?k.slice(f+1):""},o.dd=function(k){const f=[],_=k.id;return _===void 0&&f.push({message:`layers.${_}: missing required property "id"`}),k.render===void 0&&f.push({message:`layers.${_}: missing required method "render"`}),k.renderingMode&&k.renderingMode!=="2d"&&k.renderingMode!=="3d"&&f.push({message:`layers.${_}: property "renderingMode" must be either "2d" or "3d"`}),f},o.de=function(k,f,_,S){return k.type==="custom"?new xXt(k,f):new _Xt[k.type](k,f,_,S)},o.df=Vs,o.dg=RC,o.dh=Fs,o.di=class extends MM{constructor(k,f){super(k._vectorTileFeature,k._z,k._x,k._y,k.id),k.state&&(this.state=Object.assign({},k.state)),this.target=f.target,this.namespace=f.namespace,f.properties&&(this.properties=f.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=wk,o.dk=function(k){return k({pluginStatus:Dd,pluginURL:rf}),wk.on("pluginStateChange",k),k},o.dl=s6e,o.dm=class extends Y1{constructor(k){super(k),this.current=E}set(k,f,_){if(this.fetchUniformLocation(k,f)){for(let S=0;S<9;S++)if(_[S]!==this.current[S]){this.current=_,this.gl.uniformMatrix3fv(this.location,!1,_);break}}}},o.dn=Cr,o.dp=function(k,f,_){const S=u4(_.zoom),L=k.style.map._antialias,O=k.terrain&&k.terrain.exaggeration()>0;return S===0&&!L&&!O},o.dq=function(k){const f=k.pixelsPerMeter,_=f/en(1,k.center.lat),S=y(new Float64Array(16));return N(S,S,[k.point.x,k.point.y,0]),C(S,S,[_,_,f]),Float32Array.from(S)},o.dr=Ite,o.ds=function(k){const f=80.051129;k=pt(k,-80.051129,f)/f*90;const _=Math.pow(Math.abs(Math.sin($n(k))),3);return Math.round(_*(ks.length-1))},o.dt=function(k,f,_,S){const L=f.getNorth(),O=f.getSouth(),z=f.getWest(),G=f.getEast(),Y=1<0){const Ie=180/S;p(Te,Te,[Ie/re+1,0,0,0,Ie/me+1,0,-.5*Ie/ye,.5*Ie/we,1])}return Te[2]=Y,Te[5]=k.x,Te[8]=k.y,Te},o.du=YV,o.dv=Mk,o.dw=function(k,f,_){const S=y(new Float64Array(16)),L=(f/(1<0&&++this._updateTime,this._activeRegions=[],this._prevRegions=[]}get updateTime(){return this._updateTime}getReplacementRegionsForTile(k,f=!1){const _=fJe(new Xt(0,0),new Xt(lr,lr),k),S=[];if(f&&!w6e(_,this._globalClipBounds))return S;for(const L of this._activeRegions){if(L.hiddenByOverlap||!w6e(_,L))continue;const O=hYt(L.min,L.max,k);S.push({min:O.min,max:O.max,sourceId:this._sourceIds[L.priority],footprint:L.footprint,footprintTileId:L.tileId,order:L.order,clipMask:L.clipMask,clipScope:L.clipScope})}return S}setSources(k){this._setSources(k.map(f=>({getSourceId:()=>f.cache.id,getFootprints:()=>{const _=[];for(const S of f.cache.getVisibleCoordinates()){const L=f.cache.getTile(S).buckets[f.layer];L&&L.updateFootprints(S.toUnwrapped(),_)}return _},getOrder:()=>f.order,getClipMask:()=>f.clipMask,getClipScope:()=>f.clipScope})))}_addSource(k){const f=k.getFootprints();if(f.length===0)return;const _=k.getOrder(),S=k.getClipMask(),L=k.getClipScope();for(const O of f){if(!O.footprint)continue;const z=fJe(O.footprint.min,O.footprint.max,O.id);this._activeRegions.push({min:z.min,max:z.max,hiddenByOverlap:!1,priority:this._sourceIds.length,tileId:O.id,footprint:O.footprint,order:_,clipMask:S,clipScope:L})}this._sourceIds.push(k.getSourceId())}_computeReplacement(){this._activeRegions.sort((f,_)=>f.priority-_.priority||Vte(f.min,_.min)||Vte(f.max,_.max)||f.order-_.order||f.clipMask-_.clipMask||function(S,L){const O=(z,G)=>z+G;return S.length-L.length||S.reduce(O,"").localeCompare(L.reduce(O,""))}(f.clipScope,_.clipScope));let k=this._activeRegions.length!==this._prevRegions.length;if(!k){let f=0;for(;!k&&f!==this._activeRegions.length;){const _=this._activeRegions[f],S=this._prevRegions[f];k=_.priority!==S.priority||!pJe(_,S)||_.order!==S.order||_.clipMask!==S.clipMask||!rr(_.clipScope,S.clipScope),this._activeRegions[f].hiddenByOverlap=S.hiddenByOverlap,++f}}if(k){++this._updateTime;for(const _ of this._activeRegions)_.order!==rH&&(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 f=_=>{const S=this._activeRegions;if(_>=S.length)return _;const L=S[_].priority;for(;_1){let _=0,S=f(_);for(;_!==S;){let L=_;const O=_;for(;L!==S;){const z=this._activeRegions[L];z.hiddenByOverlap=!1;for(let G=0;G=0;f--)this._addSource(k[f]);this._computeReplacement()}},o.eH=so,o.eI=jse,o.eJ=o4,o.eK=rH,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,f){const _=new zi,S=new nu,L=[],O=k+1+2,z=f[0]+1,G=f[0]+1+(1+f.length),Y=(re,me,ye)=>{let we=re===O-1?re-2:re===0?re:re-1;return we+=ye?24575:0,[we,me]};for(let re=0;re>>=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=CQe,o.ed=a6e,o.ee=W1,o.ef=T,o.eg=function(k,f){return k[0]=f[0],k[1]=f[1],k[2]=f[2],k[3]=f[4],k[4]=f[5],k[5]=f[6],k[6]=f[8],k[7]=f[9],k[8]=f[10],k},o.eh=a4,o.ei=fM,o.ej=function(k,f,_,S,L){return pt((k-f)/(_-f)*(L-S)+S,S,L)},o.ek=Ft,o.el=function(k,f){var _=f[0],S=f[1],L=f[2],O=f[3],z=f[4],G=f[5],Y=f[6],re=f[7],me=f[8],ye=me*z-G*re,we=-me*O+G*Y,Te=re*O-z*Y,Ie=_*ye+S*we+L*Te;return Ie?(k[0]=ye*(Ie=1/Ie),k[1]=(-me*S+L*re)*Ie,k[2]=(G*S-L*z)*Ie,k[3]=we*Ie,k[4]=(me*_-L*Y)*Ie,k[5]=(-G*_+L*O)*Ie,k[6]=Te*Ie,k[7]=(-re*_+S*Y)*Ie,k[8]=(z*_-S*O)*Ie,k):null},o.em=fa,o.en=2,o.eo=Ee,o.ep=ft,o.eq=D,o.er=function(k,f){var _=new d(3);D(_,f);var S=1/_[0],L=1/_[1],O=1/_[2],z=f[0]*S,G=f[1]*L,Y=f[2]*O,re=f[4]*S,me=f[5]*L,ye=f[6]*O,we=f[8]*S,Te=f[9]*L,Ie=f[10]*O,Ve=z+me+Ie,Je=0;return Ve>0?(Je=2*Math.sqrt(Ve+1),k[3]=.25*Je,k[0]=(ye-Te)/Je,k[1]=(we-Y)/Je,k[2]=(G-re)/Je):z>me&&z>Ie?(Je=2*Math.sqrt(1+z-me-Ie),k[3]=(ye-Te)/Je,k[0]=.25*Je,k[1]=(G+re)/Je,k[2]=(we+Y)/Je):me>Ie?(Je=2*Math.sqrt(1+me-z-Ie),k[3]=(we-Y)/Je,k[0]=(G+re)/Je,k[1]=.25*Je,k[2]=(ye+Te)/Je):(Je=2*Math.sqrt(1+Ie-z-me),k[3]=(G-re)/Je,k[0]=(we+Y)/Je,k[1]=(ye+Te)/Je,k[2]=.25*Je),k},o.es=function(k,f){var _=2*Math.acos(f[3]),S=Math.sin(_/2);return S>c?(k[0]=f[0]/S,k[1]=f[1]/S,k[2]=f[2]/S):(k[0]=1,k[1]=0,k[2]=0),_},o.et=_Me,o.eu=rse,o.ev=nse,o.ew=[1,1,1],o.ex=XF,o.ey=function(k,f,_,S){var L=f[0],O=f[1],z=f[2],G=f[3];return k[0]=L+S*(_[0]-L),k[1]=O+S*(_[1]-O),k[2]=z+S*(_[2]-z),k[3]=G+S*(_[3]-G),k},o.ez=qF,o.f=yo,o.f0=PQe,o.f1=function(k){const f=[0,0,0],_=y(new Float64Array(16));return v(_,k.pixelMatrix,k.globeMatrix),Xe(f,f,_),new Xt(f[0],f[1])},o.f2=H0,o.f3=function(k,f,_=!1){if(Dd===Ru.deferred||Dd===Ru.loading||Dd===Ru.loaded)throw new Error("setRTLTextPlugin cannot be called multiple times.");rf=bd.resolveURL(k),Dd=Ru.deferred,um=f,A2(),_||jk()},o.f4=ca,o.f5=Ur,o.f6=wn,o.f7=function(k){const f=L0();if(!f)return;const _=f.delete(Kp);k&&_.then(()=>k()).catch(k)},o.f8=br,o.f9=qC,o.fA=li,o.fB=function(k){let f=0;if(new Uint32Array(k,0,1)[0]!==WJe){const _=new Uint32Array(k,0,7),[,,S,L,O,z]=_;f=_.byteLength+L+O+z+O,(S!==k.byteLength||f>=k.byteLength)&&Or("Invalid b3dm header information.")}return XJe(k,f)},o.fC=function(k,f){const _=B6e(k);for(const S of _){for(const L of S.meshes)qYt(L);S.lights&&(S.lightMeshIndex=S.meshes.length,S.meshes.push(VYt(S.lights,f)))}return _},o.fD=Cse,o.fE=hi,o.fF=Zx,o.fG=Ru,o.fH=function(k){jo(),eh!=null&&eh.then(f=>{f.keys().then(_=>{for(let S=0;S<_.length-k;S++)f.delete(_[S]).catch(L=>Or(L.message))}).catch(_=>Or(_.message))}).catch(f=>Or(f.message))},o.fa=2,o.fb=Ug,o.fc=EM,o.fd=UV,o.fe=ztt,o.ff=Btt,o.fg=met,o.fh=Ii,o.fi="hd_road_elevation",o.fj=cc,o.fk=Gs,o.fl=Ute,o.fm=h4,o.fn=nMe,o.fo=1,o.fp=D2,o.fq=function(k,f,_,S,L,O,z,G=1,Y,re,me,ye){k.createArrays(),k.tilePixelRatio=lr/(512*k.overscaling),k.compareText={},k.iconsNeedLinear=!1;const we=k.layers[0].layout,Te=k.layers[0]._unevaluatedLayout._values,Ie={};Ie.scaleFactor=G,Ie.textSizeScaleRange=we.get("text-size-scale-range"),Ie.iconSizeScaleRange=we.get("icon-size-scale-range");const[Ve,Je]=Ie.textSizeScaleRange,[rt,xt]=Ie.iconSizeScaleRange;Ie.textScaleFactor=pt(Ie.scaleFactor,Ve,Je),Ie.iconScaleFactor=pt(Ie.scaleFactor,rt,xt);const ut=Te["text-size"],St=Te["icon-size"];if(k.textSizeData.kind==="composite"){const{minZoom:us,maxZoom:hs}=k.textSizeData;Ie.compositeTextSizes=[ut.possiblyEvaluate(new Si(us,{worldview:me}),O),ut.possiblyEvaluate(new Si(hs,{worldview:me}),O)]}if(k.iconSizeData.kind==="composite"){const{minZoom:us,maxZoom:hs}=k.iconSizeData;Ie.compositeIconSizes=[St.possiblyEvaluate(new Si(us,{worldview:me}),O,ye),St.possiblyEvaluate(new Si(hs,{worldview:me}),O,ye)]}Ie.layoutTextSize=ut.possiblyEvaluate(new Si(z+1,{worldview:me}),O),Ie.layoutIconSize=St.possiblyEvaluate(new Si(z+1,{worldview:me}),O,ye),Ie.textMaxSize=ut.possiblyEvaluate(new Si(18,{worldview:me}),O);const Pt=we.get("symbol-placement"),Rt=we.get("text-rotation-alignment")==="map"&&Pt!=="point",ws=we.get("text-size");let ns=!1;const xs=[];for(const us of k.features){const hs=we.get("text-font").evaluate(us,{},O).join(","),pn=ws.evaluate(us,{},O)*Ie.textScaleFactor,bn=Ie.layoutTextSize.evaluate(us,{},O)*Ie.textScaleFactor,An=Ie.layoutIconSize.evaluate(us,{},O,ye)*Ie.iconScaleFactor,Ln={horizontal:{},vertical:void 0},En=us.text;let Jn,un=[0,0];if(En){const Ui=En.toString(),Od=we.get("text-letter-spacing").evaluate(us,{},O)*Bm,ll=we.get("text-line-height").evaluate(us,{},O)*Bm,$o=J5(Ui)?Od:0,ac=we.get("text-anchor").evaluate(us,{},O),kd=we.get("text-variable-anchor");if(!kd){const au=we.get("text-radial-offset").evaluate(us,{},O);if(au)un=Jet(ac,[au*Bm,oMe]);else{const qf=we.get("text-offset").evaluate(us,{},O);un=[qf[0]*Bm,qf[1]*Bm]}}let $m=Rt?"center":we.get("text-justify").evaluate(us,{},O);const Sd=Pt==="point",ru=Sd?we.get("text-max-width").evaluate(us,{},O)*Bm:1/0,sh=au=>{k.allowVerticalPlacement&&nf(Ui)&&(Ln.vertical=Z6e(En,f,_,L,hs,ru,ll,ac,au,$o,un,Fv.vertical,!0,bn,pn,Y,Ie.textScaleFactor))};if(!Rt&&kd){const au=$m==="auto"?kd.map(Um=>lMe(Um)):[$m];let qf=!1;for(let Um=0;Um=0||!nf(Ui)){const au=Z6e(En,f,_,L,hs,ru,ll,ac,$m,$o,un,Fv.horizontal,!1,bn,pn,Y,Ie.textScaleFactor);au&&(Ln.horizontal[$m]=au)}sh(Sd?"left":$m)}}let Mn,Rn,er,ur,Zr,Nr,wr=!1;const hr=we.get("icon-text-fit").evaluate(us,{},O);if(us.icon&&us.icon.hasPrimary()){const Ui=vH(us.icon,k.iconSizeData,Te["icon-size"],O,k.zoom,us,Y,Ie.iconScaleFactor,me,ye);Mn=Ui.iconPrimary,er=Ui.iconSecondary;const Od=Mn.toString();if(Rn=S.get(Od),Rn&&(Zr=we.get("icon-offset").evaluate(us,{},O),Nr=we.get("icon-anchor").evaluate(us,{},O),Jn=dse(L.get(Od),er?L.get(er.toString()):void 0,Zr,Nr),wr=Rn.sdf,k.sdfIcons===void 0?k.sdfIcons=Rn.sdf:k.sdfIcons!==Rn.sdf&&Or("Style sheet warning: Cannot mix SDF and non-SDF icons in one buffer"),(Rn.pixelRatio!==k.pixelRatio||we.get("icon-rotate").constantOr(1)!==0)&&(k.iconsNeedLinear=!0)),er){const ll=er.toString();ur=S.get(ll)}}ns=ns||!(!us.icon||!us.icon.hasSecondary());const Gr=gse(Ln.horizontal)||Ln.vertical;k.iconsInText||(k.iconsInText=!!Gr&&Gr.iconsInText);const aa=bn*Ie.textScaleFactor/Bm,{defaultShapedIcon:Da,verticallyShapedIcon:_a}=eXt(k,Jn,we,us,O,Ln,aa,Zr,hr);hr!=="none"&&Jn&&(Det(Jn)||Ret(Jn))&&(xse(0,Rn,Mn,Jn,Da,hr,re,S,L),xse(0,ur,er,Jn,Da,hr,re,S,L),_a&&(xse(0,Rn,Mn,Jn,_a,hr,re,S,L),xse(0,ur,er,Jn,_a,hr,re,S,L))),Jn=Da;const{iconBBox:_i,iconVerticalBBox:To,textBBox:wi,textVerticalBBox:Do}=YZt(k,Jn,_a,we,us,O,An,Zr,Ie,L,Nr,Ln,bn,un,ye);xs.push({feature:us,shapedTextOrientations:Ln,shapedText:Gr,shapedIcon:Jn,iconPrimary:Mn,iconSecondary:er,iconOffset:Zr,iconAnchor:Nr,verticallyShapedIcon:_a,layoutTextSize:bn,layoutIconSize:An,textOffset:un,isSDFIcon:wr,iconTextFit:hr,iconCollisionBounds:_i,iconVerticalCollisionBounds:To,textCollisionBounds:wi,textVerticalCollisionBounds:Do})}return{featureData:xs,sizes:Ie,hasAnySecondaryIcon:ns,textAlongLine:Rt,symbolPlacement:Pt}},o.fr=rMe,o.fs=sMe,o.ft=Het,o.fu=Get,o.fv=function(k,f,_,S,L,O,z,G,Y,re){k.iconAtlasPositions=re.iconPositions;const{featureData:me,hasAnySecondaryIcon:ye,sizes:we,textAlongLine:Te,symbolPlacement:Ie}=f;for(const Ve of me){const{shapedIcon:Je,verticallyShapedIcon:rt,feature:xt,shapedTextOrientations:ut,shapedText:St,layoutTextSize:Pt,textOffset:Rt,isSDFIcon:ws,iconPrimary:ns,iconSecondary:xs,iconTextFit:us,iconOffset:hs,iconCollisionBounds:pn,iconVerticalCollisionBounds:bn,textCollisionBounds:An}=Ve;ntt(Je,re.iconPositions,ns,xs),ntt(rt,re.iconPositions,ns,xs),JZt(ut,re.iconPositions),QZt(ns,xs,re.iconPositions),(St||Je)&&tXt(k,xt,ut,Je,rt,Y,we,Pt,0,Rt,ws,S,L,z,G,ye,us,hs,Te,Ie,pn,bn,An)}_&&k.generateCollisionDebugBuffers(O,k.collisionBoxArray,we.textScaleFactor)},o.fw=ose,o.fx=Zo,o.fy=function(k){return k<=1?1:Math.pow(2,Math.floor(Math.log2(k)))},o.fz=Pse,o.g=Kn,o.h=function(k,f){return rm(Object.assign(k,{method:"GET"}),f)},o.i=function(k){return Kn.API_STYLE_REGEX.test(k)&&!vo(k)},o.j=function(k){return btoa(encodeURIComponent(k).replace(/%([0-9A-F]{2})/g,(f,_)=>String.fromCharCode(+("0x"+_))))},o.k=Ey,o.l=function(k){return decodeURIComponent(atob(k).split("").map(f=>"%"+("00"+f.charCodeAt(0).toString(16)).slice(-2)).join(""))},o.m=function(k,f){return rm(Object.assign(k,{type:"json"}),f)},o.n=am,o.o=bd,o.p=function(k,f){return rm(Object.assign(k,{method:"POST"}),f)},o.q=vx,o.r=Ls,o.s=function(k){try{const f=self[k];return f.setItem("_mapbox_test_",1),f.removeItem("_mapbox_test_"),!0}catch{return!1}},o.t=Zt,o.u=function(){return function k(f){return f?(f^Math.random()*(16>>f/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=Or,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(f=>{this.cache.delete(f),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 f=this.textures.get(k);if(f){const _=this.calculateTextureMemory(k);f.destroy(),this.textures.delete(k),this.textureAccessTimes.delete(k),this.textureMemoryUsed-=_}}evictTexturesIfNeeded(k){for(;this.textureMemoryUsed+k>this.maxTextureMemory&&this.textures.size>0;){let f=null,_=1/0;for(const[S]of this.textures.entries()){const L=this.textureAccessTimes.get(S)||0;L<_&&(_=L,f=S)}if(!f)break;this.evictTexture(f)}}findCachedAtlas(k){const f=this.cache.get(k.hash);if(f){const _=f.deref();if(_&&_.contentDescriptor&&this.isMipmapCompatible(k,_.contentDescriptor))return _}for(const[,_]of this.cache.entries()){const S=_.deref();if(S&&S.contentDescriptor){const L=k.subsetOf(S.contentDescriptor),O=this.isMipmapCompatible(k,S.contentDescriptor);if(L&&O)return S}}}getTextureForAtlas(k,f,_){this.textureAccessTimes.set(k,performance.now());let S=this.textures.get(k);if(S)return S;if(k.image){const L=this.calculateTextureMemory(k);return this.evictTexturesIfNeeded(L),S=new Ik(f,k.image,_,{useMipmap:!!k.patternPositions.size}),this.textures.set(k,S),this.textureMemoryUsed+=L,S}return null}clearExpiredTextures(){for(const[k]of this.textures.entries())if(!this.isAtlasCached(k)){const f=this.textures.get(k);if(f){const _=this.calculateTextureMemory(k);f.destroy(),this.textureMemoryUsed-=_}this.textures.delete(k),this.textureAccessTimes.delete(k)}}isAtlasCached(k){if(!k.contentDescriptor)return!1;const f=this.cache.get(k.contentDescriptor.hash);return!!f&&f.deref()===k}getOrCache(k){if(!("image"in k)){const L=this.cache.get(k.sourceAtlasHash);if(L){const O=L.deref();if(O)return O}return Or("ImageAtlasReference points to GC'd atlas - atlas may have been evicted"),null}if(!k.contentDescriptor)return k;const f=k.contentDescriptor,_=f.hash,S=this.cache.get(_);if(S){const L=S.deref();if(L&&L.contentDescriptor&&this.isMipmapCompatible(f,L.contentDescriptor))return L}return this.cache.set(_,new WeakRef(k)),this.finalizationRegistry.register(k,_,k),k}isMipmapCompatible(k,f){return!k.requiresMipMaps||f.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=Ld,o.z=kMe}),i(["require","./shared"],function(o,c){function d(ms){const ot=ms?ms.url.toString():void 0;return ot?performance.getEntriesByName(ot):[]}function u(ms){if(typeof ms=="number"||typeof ms=="boolean"||typeof ms=="string"||ms==null)return JSON.stringify(ms);if(Array.isArray(ms)){let pt="[";for(const vt of ms)pt+=`${u(vt)},`;return`${pt}]`}let ot="{";for(const pt of Object.keys(ms).sort())ot+=`${pt}:${u(ms[pt])},`;return`${ot}}`}function h(ms){let ot="";for(const pt of c.b5)ot+=`/${u(ms[pt])}`;return ot}function m(ms,ot){return function pt(vt){return typeof vt=="string"&&vt===ot||(Array.isArray(vt)?vt.some(pt):!(!vt||typeof vt!="object")&&Object.values(vt).some(pt))}(ms)}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,pt){this._layerConfigs=Object.create(null),this._layers=Object.create(null),this.update(ot,[],pt)}update(ot,pt,vt){this._options=vt;for(const Zt of ot)this._layerConfigs[Zt.id]=Zt,(this._layers[Zt.id]=c.de(Zt,this.scope,null,this._options)).compileFilter(vt),this.keyCache[Zt.id]&&delete this.keyCache[Zt.id];for(const Zt of pt)delete this.keyCache[Zt],delete this._layerConfigs[Zt],delete this._layers[Zt];this.familiesBySource=Object.create(null);const At=function(Zt,as){const Ls=Object.create(null);for(let qt=0;qtthis._layers[Hn.id]),Ls=as[0];if(Ls.visibility==="none")continue;const cs=Ls.source||"";let qt=this.familiesBySource[cs];qt||(qt=this.familiesBySource[cs]=Object.create(null));const Gs=Ls.sourceLayer||"_geojsonTileLayer";let Vs=qt[Gs];Vs||(Vs=qt[Gs]=[]),Vs.push(as)}}}const x=1*c.fa;class g{constructor(ot){const pt={},vt=[];for(const Ls in ot){const cs=ot[Ls],qt=pt[Ls]={};for(const Gs in cs.glyphs){const Vs=cs.glyphs[+Gs];if(!Vs||Vs.bitmap.width===0||Vs.bitmap.height===0)continue;const Hn=Vs.metrics.localGlyph?x:1,Kr={x:0,y:0,w:Vs.bitmap.width+2*Hn,h:Vs.bitmap.height+2*Hn};vt.push(Kr),qt[Gs]=Kr}}const{w:At,h:Zt}=c.J(vt),as=new c.f9({width:At||1,height:Zt||1});for(const Ls in ot){const cs=ot[Ls];for(const qt in cs.glyphs){const Gs=cs.glyphs[+qt];if(!Gs||Gs.bitmap.width===0||Gs.bitmap.height===0)continue;const Vs=pt[Ls][qt],Hn=Gs.metrics.localGlyph?x:1;c.f9.copy(Gs.bitmap,as,{x:0,y:0},{x:Vs.x+Hn,y:Vs.y+Hn},Gs.bitmap)}}this.image=as,this.positions=pt}}function y(ms,ot,pt){ms[ot]?pt&&(ms[ot].center=pt):ms[ot]={floorIds:new Set,center:pt||[0,0],floors:{}}}function b(ms,ot,pt,vt){for(const At of ot)y(ms,At),ms[At].floors[pt]=vt,ms[At].floorIds.add(pt)}function v(ms){return{id:ms.properties.id.toString(),center:[ms.properties.center_lon||0,ms.properties.center_lat||0]}}function N(ms,ot){const pt=ms.properties.id.toString(),vt=!!ms.properties.is_default&&ms.properties.is_default,At=ms.properties.connected_floor_ids?new Set(ms.properties.connected_floor_ids.toString().split(";")):new Set,Zt=ms.properties.conflicted_floor_ids?new Set(ms.properties.conflicted_floor_ids.toString().split(";")):new Set,as=ms.properties.structure_ids?new Set(ms.properties.structure_ids.toString().split(";")):new Set,Ls=ms.properties.name.toString(),cs=ms.properties.z_index,qt=function(Gs,Vs){const Hn=Gs.loadGeometry();if(!Hn||Hn.length===0)return;const Kr=Hn.map(ma=>ma.map(Or=>c.fb(Or,Vs,Gs.extent)));return Kr.length===0?void 0:{type:"Polygon",coordinates:[Kr[0]]}}(ms,ot);return{id:pt,isDefault:vt,connections:At,conflicts:Zt,buildings:as,name:Ls,zIndex:cs,geometry:qt}}function C(ms,ot){return ot.every(pt=>ms.properties&&ms.properties[pt]!=null)}function A(ms){return C(ms,["type","id","name"])&&ms.properties.type==="structure"}function T(ms){return C(ms,["type","id","name","z_index"])&&ms.properties.type==="floor"}c.f8(g,"GlyphAtlas");class P{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,pt,vt,At,Zt,as){this.status="parsing",this.data=ot,this.collisionBoxArray=new c.fd;const Ls=new c.fe(Object.keys(ot.layers).sort()),cs=new c.ff(this.tileID,this.promoteId);cs.bucketLayerIDs=[];const qt={},Gs=new c.fg(256,256),Vs={featureIndex:cs,iconDependencies:new Map,patternDependencies:new Map,glyphDependencies:{},lineAtlas:Gs,availableImages:vt,brightness:this.brightness,scaleFactor:this.scaleFactor,elevationFeatures:void 0,activeFloors:void 0};this.indoor&&(Vs.activeFloors=function(Or,ta,da,va){const hi=ta.indoorState.activeFloorsVisible;if(!ta.sourceLayers)return hi?ta.indoorState.activeFloors:void 0;const el=function(Wa,wo){if(!Wa)return c.w("No source layers defined in indoor specification"),wo;if(Wa.size===0)return wo;const Io=Wa.difference(wo);for(const is of Io)c.w(`Missing source layer required in indoor specification: ${is}`);return wo.intersection(wo)}(ta.sourceLayers,new Set(Object.keys(Or.layers))),Oo=ta.indoorState,Ei=function(Wa,wo,Io,is,zr){const Sa={};for(const Kn of wo){const wn=Wa.layers[Kn];if(wn)for(let Ur=0;Ur=is.maxzoom||is.visibility==="none")continue;M(Io,this.zoom,Vs.brightness,vt,this.worldview,Vs.activeFloors);const zr=qt[is.id]=is.createBucket({index:cs.bucketLayerIDs.length,layers:Io,zoom:this.zoom,lut:this.lut,canonical:this.canonical,pixelRatio:this.pixelRatio,overscaling:this.overscaling,collisionBoxArray:this.collisionBoxArray,sourceLayerIndex:Oo,sourceID:this.source,projection:this.projection.spec,tessellationStep:this.tessellationStep,styleDefinedModelURLs:At,worldview:this.worldview,localizable:Wa,availableImages:vt,maxUniformBufferBindings:this.maxUniformBufferBindings,maxUniformBlockSizeDwords:this.maxUniformBlockSizeDwords,disableSymbolUBO:this.disableSymbolUBO});cs.bucketLayerIDs.push(Io.map(Kn=>c.F(Kn.id,Kn.scope)));let Sa=zr.prepare?zr.prepare():null;Sa!=null?(Sa=Sa.then(()=>zr.populate(Ei,Vs,this.tileID.canonical,this.tileTransform)),Hn.push(Sa)):zr.populate(Ei,Vs,this.tileID.canonical,this.tileTransform)}}const ma=()=>{Gs.trim();const Or=!(!Vs.elevationFeatures||!Vs.elevationFeatures.some(is=>is.heightRange.min<0));let ta,da,va,hi,el,Oo,Ei;const Wa={type:"maybePrepare",renderSourceType:this.renderSourceType,zoom:this.zoom},wo=()=>{if(ta)return this.status="done",as(ta);if(this.extraShadowCaster)this.status="done",as(null,{buckets:Object.values(qt).filter(is=>!is.isEmpty()),featureIndex:cs,collisionBoxArray:null,hasTunnelGeometry:Or,glyphAtlasImage:null,lineAtlas:null,imageAtlas:null,brightness:Vs.brightness,glyphMap:null,iconMap:null,glyphPositions:null});else if(da&&va&&hi&&Ei){const zr=new g(da),Sa=new Map;for(const[Ur,ca]of va.entries()){const{imagePosition:yo}=c.fn(Ur,ca,c.fo);Sa.set(Ur,yo)}const Kn={};for(const Ur in qt){const ca=qt[Ur];ca instanceof c.fp&&(M(ca.layers,this.zoom,Vs.brightness,vt,this.worldview,Vs.activeFloors),Kn[Ur]=c.fq(ca,da,zr.positions,va,Sa,this.tileID.canonical,this.tileZoom,this.scaleFactor,this.pixelRatio,el,this.worldview,vt))}const wn={iconsPending:!0,patternsPending:!0};this.rasterizeIfNeeded(Zt,va,el,()=>{wn.iconsPending=!1,Io(Kn,zr,wn,void 0,Ei)}),this.rasterizeIfNeeded(Zt,hi,Oo,()=>{wn.patternsPending=!1,Io(Kn,zr,wn,void 0,Ei)})}},Io=(is,zr,Sa,Kn,wn)=>{if(Sa.iconsPending||Sa.patternsPending)return;const Ur=va.size>0||hi.size>0,ca=Object.keys(is).length>0;if(!Ur&&!ca)return this.status="done",void as(null,{buckets:Object.values(qt).filter(vo=>!vo.isEmpty()),featureIndex:cs,collisionBoxArray:this.collisionBoxArray,hasTunnelGeometry:Or,glyphAtlasImage:zr.image,lineAtlas:Gs,imageAtlas:null,brightness:Vs.brightness});const yo=(vo,Vo)=>{for(const Xc in qt){const uo=qt[Xc];if(Xc in is)c.fv(uo,is[Xc],this.showCollisionBoxes,vt,this.tileID.canonical,this.tileZoom,this.projection,this.brightness,va,Vo);else if(uo.hasPattern&&(uo instanceof c.fw||uo instanceof c.fl||uo instanceof c.e0)){M(uo.layers,this.zoom,Vs.brightness,vt,this.worldview,Vs.activeFloors);const bo=Object.fromEntries(Vo.patternPositions);uo.addFeatures(Vs,this.tileID.canonical,bo,vt,this.tileTransform,this.brightness)}}this.status="done",as(null,{buckets:Object.values(qt).filter(Xc=>!Xc.isEmpty()),featureIndex:cs,collisionBoxArray:this.collisionBoxArray,hasTunnelGeometry:Or,glyphAtlasImage:zr.image,lineAtlas:Gs,imageAtlas:vo,brightness:Vs.brightness})};if(Ur){const vo=new Map,Vo=c.fr(va,vo),Xc=c.fr(hi,vo),uo=new c.fs(Vo,Xc,wn,this.lut,vo);Zt.send("checkAtlasCache",{descriptor:uo,scope:this.scope},(bo,od)=>{let Ju,Ld;if(bo&&c.w(`[Worker] Error checking atlas cache: ${bo.message}`),od)Ju=new c.ft(od.sourceHash),Ld=od;else{const bd=new c.fu(va,hi,this.lut,wn);Ju=bd,Ld=bd}yo(Ju,Ld)})}else yo(null,{iconPositions:new Map,patternPositions:new Map})};if(!this.extraShadowCaster){const is=c.fk(Vs.glyphDependencies,Kn=>Object.keys(Kn).map(Number));Object.keys(is).length?Zt.send("getGlyphs",{uid:this.uid,stacks:is},(Kn,wn)=>{ta||(ta=Kn,da=wn,wo())},void 0,!1,Wa):da={},Ei=new Map;const zr=Array.from(Vs.iconDependencies.keys()).map(Kn=>c.I.parse(Kn));zr.length?Zt.send("getImages",{images:zr,source:this.source,scope:this.scope,tileID:this.tileID,type:"icons"},(Kn,wn)=>{if(!ta){ta=Kn,va=new Map,el=this.updateImageMapAndGetImageTaskQueue(va,wn.images,Vs.iconDependencies);for(const[Ur,ca]of wn.versions.entries())Ei.set(Ur,ca);wo()}},void 0,!1,Wa):(va=new Map,el=new Map);const Sa=Array.from(Vs.patternDependencies.keys()).map(Kn=>c.I.parse(Kn));Sa.length?Zt.send("getImages",{images:Sa,source:this.source,scope:this.scope,tileID:this.tileID,type:"patterns"},(Kn,wn)=>{if(!ta){ta=Kn,hi=new Map,Oo=this.updateImageMapAndGetImageTaskQueue(hi,wn.images,Vs.patternDependencies);for(const[Ur,ca]of wn.versions.entries())Ei.set(Ur,ca);wo()}},void 0,!1,Wa):(hi=new Map,Oo=new Map)}if(Vs.elevationFeatures&&Vs.elevationFeatures.length>0){const is=[];for(const Sa of Object.values(qt))if(Sa instanceof c.fl){const Kn=Sa.getUnevaluatedPortalGraph();Kn&&is.push(Kn)}const zr=c.fm.evaluate(is);for(const Sa of Object.values(qt))if(Sa instanceof c.fl){const Kn=ot.layers[Ls.decode(Sa.sourceLayerIndex)];Sa.setEvaluatedPortalGraph(zr,Kn,this.tileID.canonical,Vs.availableImages,Vs.brightness)}}wo()};Hn.length>0?Promise.allSettled(Hn).then(ma).catch(as):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,pt,vt,At){Array.from(pt.values()).some(Zt=>Zt.usvg)?this.rasterize(ot,pt,vt,At):At()}updateImageMapAndGetImageTaskQueue(ot,pt,vt){const At=new Map;for(const Zt of pt.keys()){const as=vt.get(Zt)||[];for(const Ls of as){const cs=Ls.toString(),qt=pt.get(Ls.id.toString());qt.usvg?At.has(cs)||(At.set(cs,Ls),ot.set(cs,Object.assign({},qt))):ot.set(cs,qt)}}return At}rasterize(ot,pt,vt,At){this.rasterizeTask=ot.send("rasterizeImages",{scope:this.scope,tasks:vt},(Zt,as)=>{if(!Zt)for(const[Ls,cs]of as.entries()){const qt=Object.assign(pt.get(Ls),{data:cs});pt.set(Ls,qt)}At()})}cancelRasterize(){this.rasterizeTask&&this.rasterizeTask.cancel()}}function M(ms,ot,pt,vt,At,Zt){const as=new c.ae(ot,{brightness:pt,worldview:At,activeFloors:Zt});for(const Ls of ms)Ls.recalculate(as,vt)}class I extends c.E{constructor({actor:ot,layerIndex:pt,availableImages:vt,availableModels:At,isSpriteLoaded:Zt,tileProvider:as,brightness:Ls,maxUniformBufferBindings:cs,maxUniformBlockSizeDwords:qt,disableSymbolUBO:Gs}){super(),this.actor=ot,this.layerIndex=pt,this.availableImages=vt,this.availableModels=At,this.loadVectorData=c.aO,this.tileProvider=as,this.loading={},this.loaded={},this.deduped=new c.aN(ot.scheduler),this.isSpriteLoaded=Zt,this.scheduler=ot.scheduler,this.brightness=Ls,this.maxUniformBufferBindings=cs,this.maxUniformBlockSizeDwords=qt,this.disableSymbolUBO=Gs}loadTileData(ot,pt){if(!this.tileProvider)return this.loadVectorData(ot,pt);const vt=new AbortController,{z:At,x:Zt,y:as}=ot.tileID.canonical;return this.tileProvider.loadTile({z:At,x:Zt,y:as},{request:ot.request,signal:vt.signal}).then(Ls=>{if(vt.signal.aborted)return;if(Ls==null){const qt=new Error("Tile not found");return qt.status=404,pt(qt)}if(Ls.data===null)return pt(null,null);const cs=new Map;Ls.expires&&cs.set("expires",Ls.expires),Ls.cacheControl&&cs.set("cache-control",Ls.cacheControl),pt(null,{rawData:Ls.data,responseHeaders:cs})}).catch(Ls=>{vt.signal.aborted||pt(Ls instanceof Error?Ls:new Error(String(Ls)))}),()=>vt.abort()}loadTile(ot,pt){const vt=ot.uid,At=ot&&ot.request,Zt=At&&At.collectResourceTiming,as=this.loading[vt]=new P(ot);as.maxUniformBufferBindings=this.maxUniformBufferBindings,as.maxUniformBlockSizeDwords=this.maxUniformBlockSizeDwords,as.disableSymbolUBO=this.disableSymbolUBO,as.abort=this.loadTileData(ot,(Ls,cs)=>{const qt=!this.loading[vt];if(delete this.loading[vt],as.cancelRasterize(),qt||Ls||!cs)return as.status="done",qt||(this.loaded[vt]=as),pt(Ls);const Gs=cs.rawData,Vs={},Hn=c.aP(cs.responseHeaders);Hn&&Hn.expires&&(Vs.expires=Hn.expires),Hn&&Hn.cacheControl&&(Vs.cacheControl=Hn.cacheControl),as.vectorTile=cs.vectorTile||new c.fx(new c.a$(Gs));const Kr=()=>{as.parse(as.vectorTile,this.layerIndex,this.availableImages,this.availableModels,this.actor,(ma,Or)=>{if(ma||!Or)return pt(ma);const ta={};if(Zt){const da=d(At);da.length>0&&(ta.resourceTiming=JSON.parse(JSON.stringify(da)))}pt(null,Object.assign({rawTileData:Gs.slice(0),responseHeaders:cs.responseHeaders},Or,Vs,ta))})};this.isSpriteLoaded?Kr():this.once("isSpriteLoaded",()=>{this.scheduler?this.scheduler.add(Kr,{type:"parseTile",renderSourceType:ot.renderSourceType,zoom:ot.tileZoom}):Kr()}),this.loaded=this.loaded||{},this.loaded[vt]=as})}reloadTile(ot,pt){const vt=this.loaded,At=ot.uid;if(vt&&vt[At]){const Zt=vt[At];Zt.updateParameters(ot);const as=(Ls,cs)=>{const qt=Zt.reloadCallback;qt&&(delete Zt.reloadCallback,Zt.parse(Zt.vectorTile,this.layerIndex,this.availableImages,this.availableModels,this.actor,qt)),pt(Ls,cs)};Zt.status==="parsing"?Zt.reloadCallback=as:Zt.status==="done"&&(Zt.vectorTile?Zt.parse(Zt.vectorTile,this.layerIndex,this.availableImages,this.availableModels,this.actor,as):as())}else pt(null,void 0)}abortTile(ot,pt){const vt=ot.uid,At=this.loading[vt];At&&(At.abort&&At.abort(),delete this.loading[vt]),pt()}removeTile(ot,pt){const vt=this.loaded,At=ot.uid;vt&&vt[At]&&delete vt[At],pt()}}class D{constructor(ot){this.loading={}}loadTile(ot,pt){const vt=ot.uid,{cancel:At}=c.b1(ot.request,(Zt,as,Ls)=>{const cs=!this.loading[vt];if(delete this.loading[vt],cs||Zt||!as)return pt(Zt);this.decodeTile(vt,as,ot.encoding).then(qt=>{const{expires:Gs,cacheControl:Vs}=c.aP(Ls);pt(null,Object.assign(qt,{expires:Gs,cacheControl:Vs}))}).catch(qt=>pt(qt))});this.loading[vt]={cancel:At}}async decodeTile(ot,pt,vt){const At=await createImageBitmap(new Blob([new Uint8Array(pt)],{type:"image/png"})),Zt=1-(At.width-c.fy(At.width))/2,as=Zt<1,Ls=this.getImageData(At,Zt);return At.close(),{dem:new c.fz(ot,Ls,vt,as),borderReady:as}}reloadTile(ot,pt){pt(null,null)}abortTile(ot,pt){const vt=ot.uid,At=this.loading[vt];At&&(At.cancel(),delete this.loading[vt]),pt()}removeTile(ot,pt){pt()}getImageData(ot,pt){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 vt=this.offscreenCanvasContext.getImageData(-pt,-pt,ot.width+2*pt,ot.height+2*pt);return this.offscreenCanvasContext.clearRect(0,0,this.offscreenCanvas.width,this.offscreenCanvas.height),vt}}c.a_.setPbf(c.a$);class B{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,pt){const vt=this._mrt;this.status="parsing",this._entireBuffer=ot;try{vt.parseHeader(ot),this._isHeaderLoaded=!0;const At=[];for(const Zt in vt.layers){const as=vt.getLayer(Zt),Ls=as.getDataRange(as.getBandList()),cs=vt.createDecodingTask(Ls),qt=ot.slice(Ls.firstByte,Ls.lastByte+1),Gs=c.a_.performDecoding(qt,cs).then(Vs=>cs.complete(null,Vs)).catch(Vs=>cs.complete(Vs,null));At.push(Gs)}Promise.allSettled(At).then(()=>pt(null,vt)).catch(Zt=>pt(Zt))}catch(At){pt(At)}}}class q{constructor({actor:ot}){this.actor=ot,this.loading={},this.loaded={}}loadTile(ot,pt){const vt=ot.uid,At=ot.request,Zt=this.loading[vt]=new B(ot),{cancel:as}=c.b1(At,(Ls,cs,qt)=>{const Gs=!this.loading[vt];if(delete this.loading[vt],Gs||Ls||!cs)return Zt.status="done",Gs||(this.loaded[vt]=Zt),pt(Ls);Zt.parse(cs,(Vs,Hn)=>{if(Vs||!Hn)return pt(Vs);pt(null,Hn,qt)}),this.loaded[vt]=Zt});Zt.abort=as}reloadTile(ot,pt){pt(null,void 0)}abortTile(ot,pt){const vt=ot.uid,At=this.loading[vt];At&&(At.abort&&At.abort(),delete this.loading[vt]),pt()}removeTile(ot,pt){const vt=ot.uid;this.loaded[vt]&&delete this.loaded[vt],pt()}decodeRasterArray(ot,pt){c.a_.performDecoding(ot.buffer,ot.task).then(vt=>pt(null,vt)).catch(vt=>pt(vt))}}const W=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 pt of this._feature.geometry)ot.push([new c.P(pt[0],pt[1])]);return ot}{const ot=[];for(const pt of this._feature.geometry){const vt=[];for(const At of pt)vt.push(new c.P(At[0],At[1]));ot.push(vt)}return ot}}toGeoJSON(ot,pt,vt){return W.call(this,ot,pt,vt)}}class K{constructor(ot,pt){this.name=ot,this.extent=c.an,this.length=pt.length,this._jsonFeatures=pt}feature(ot){return new V(this._jsonFeatures[ot])}}class Q{constructor(ot){this.layers={},this.extent=c.an;for(const pt of Object.keys(ot))this.layers[pt]=new K(pt,ot[pt])}}const J=64/4096;class ce{constructor(){this.features=new Map}clear(){this.features.clear()}load(ot=[],pt){for(const vt of ot){const At=vt.id;if(At==null)continue;let Zt=this.features.get(At);Zt&&this.updateCache(Zt,pt),vt.geometry?(Zt=ne(vt),this.updateCache(Zt,pt),this.features.set(At,Zt)):this.features.delete(At),this.updateCache(Zt,pt)}}updateCache(ot,pt){for(const{canonical:vt,uid:At}of Object.values(pt)){const{z:Zt,x:as,y:Ls}=vt;ue(ot,Math.pow(2,Zt),as,Ls)&&delete pt[At]}}getTile(ot,pt,vt){const At=Math.pow(2,ot),Zt=[];for(const as of this.features.values())ue(as,At,pt,vt)&&Zt.push(ve(as,At,pt,vt));return{features:Zt}}getFeatures(){return[...this.features.values()]}}function ue({minX:ms,minY:ot,maxX:pt,maxY:vt},At,Zt,as){return ms<(Zt+1+J)/At&&ot<(as+1+J)/At&&pt>(Zt-J)/At&&vt>(as-J)/At}function ne(ms){const{id:ot,geometry:pt,properties:vt}=ms;if(!pt)return;if(pt.type==="GeometryCollection")throw new Error("GeometryCollection not supported in dynamic mode.");const{type:At,coordinates:Zt}=pt,as={id:ot,type:1,geometry:[],tags:vt,minX:1/0,minY:1/0,maxX:-1/0,maxY:-1/0},Ls=as.geometry;if(At==="Point")ee(Zt,Ls,as);else if(At==="MultiPoint")for(const cs of Zt)ee(cs,Ls,as);else if(At==="LineString")as.type=2,le(Zt,Ls,as);else if(At==="MultiLineString")as.type=2,he(Zt,Ls,as);else if(At==="Polygon")as.type=3,he(Zt,Ls,as,!0);else{if(At!=="MultiPolygon")throw new Error("Input data is not a valid GeoJSON object.");as.type=3;for(const cs of Zt)he(cs,Ls,as,!0)}return as}function ee([ms,ot],pt,vt){const At=c.aH(ms);let Zt=c.aL(ot);Zt=Zt<0?0:Zt>1?1:Zt,pt.push(At,Zt),vt.minX=Math.min(vt.minX,At),vt.minY=Math.min(vt.minY,Zt),vt.maxX=Math.max(vt.maxX,At),vt.maxY=Math.max(vt.maxY,Zt)}function le(ms,ot,pt,vt=!1,At=!1){const Zt=[];for(const as of ms)ee(as,Zt,pt);ot.push(Zt),vt&&function(as,Ls){let cs=0;for(let qt=0,Gs=as.length,Vs=Gs-2;qt0===Ls)for(let qt=0,Gs=as.length;qt=as&&Vs>=as||(qt>=as?(Gs+=Math.round(ma*((as-qt)/Kr)),qt=as):Vs>=as&&(Hn=Gs+Math.round(ma*((as-qt)/Kr)),Vs=as),Gs>=as&&Hn>=as||(Gs>=as?(qt+=Math.round(Kr*((as-Gs)/ma)),Gs=as):Hn>=as&&(Vs=qt+Math.round(Kr*((as-Gs)/ma)),Hn=as),Ls&&qt===Ls[Ls.length-1][0]&&Gs===Ls[Ls.length-1][1]||(Ls=[[qt,Gs]],At.push(Ls)),Ls.push([Vs,Hn])))))}}function fe(ms,ot,pt,vt,At){const Zt=(pt-J)/ot,as=(vt-J)/ot,Ls=(pt+1+J)/ot,cs=(vt+1+J)/ot;function qt(Hn,Kr){let ma=0;return HnLs&&(ma|=2),Krcs&&(ma|=8),ma}let Gs=[];for(let Hn=1;Hn<=8;Hn*=2){let Kr=ms[ms.length-2],ma=ms[ms.length-1],Or=!(qt(Kr,ma)&Hn);for(let ta=0;ta>31}function ke(ms,ot){const{geometry:pt,type:vt}=ms;let At=0,Zt=0;if(vt===1){ot.writeVarint(De(1,pt.length));for(const as of pt){const Ls=as[0]-At,cs=as[1]-Zt;ot.writeVarint(ze(Ls)),ot.writeVarint(ze(cs)),At+=Ls,Zt+=cs}}else for(const as of pt){if(as.length===0)continue;ot.writeVarint(De(1,1));const Ls=as.length-(vt===3?1:0);for(let cs=0;csms},Re=Math.fround||(Ae=new Float32Array(1),ms=>(Ae[0]=+ms,Ae[0]));var Ae;class Be{constructor(ot){this.options=Object.assign(Object.create(Se),ot),this.trees=new Array(this.options.maxZoom+1),this.stride=this.options.reduce?7:6,this.clusterProps=[]}load(ot){const{log:pt,minZoom:vt,maxZoom:At}=this.options;pt&&console.time("total time");const Zt=`prepare ${ot.length} points`;pt&&console.time(Zt),this.points=ot;const as=[];for(let cs=0;cs=vt;cs--){const qt=+Date.now();Ls=this.trees[cs]=this._createTree(this._cluster(Ls,cs)),pt&&console.log("z%d: %d clusters in %dms",cs,Ls.numItems,+Date.now()-qt)}return pt&&console.timeEnd("total time"),this}getClusters(ot,pt){let vt=((ot[0]+180)%360+360)%360-180;const At=Math.max(-90,Math.min(90,ot[1]));let Zt=ot[2]===180?180:((ot[2]+180)%360+360)%360-180;const as=Math.max(-90,Math.min(90,ot[3]));if(ot[2]-ot[0]>=360)vt=-180,Zt=180;else if(vt>Zt){const Vs=this.getClusters([vt,At,180,as],pt),Hn=this.getClusters([-180,At,Zt,as],pt);return Vs.concat(Hn)}const Ls=this.trees[this._limitZoom(pt)],cs=Ls.range(Ze(vt),Ue(as),Ze(Zt),Ue(At)),qt=Ls.data,Gs=[];for(const Vs of cs){const Hn=this.stride*Vs;Gs.push(qt[Hn+5]>1?qe(qt,Hn,this.clusterProps):this.points[qt[Hn+3]])}return Gs}getChildren(ot){const pt=this._getOriginId(ot),vt=this._getOriginZoom(ot),At="No cluster with the specified id.",Zt=this.trees[vt];if(!Zt)throw new Error(At);const as=Zt.data;if(pt*this.stride>=as.length)throw new Error(At);const Ls=this.options.radius/(this.options.extent*Math.pow(2,vt-1)),cs=Zt.within(as[pt*this.stride],as[pt*this.stride+1],Ls),qt=[];for(const Gs of cs){const Vs=Gs*this.stride;as[Vs+4]===ot&&qt.push(as[Vs+5]>1?qe(as,Vs,this.clusterProps):this.points[as[Vs+3]])}if(qt.length===0)throw new Error(At);return qt}getLeaves(ot,pt,vt){const At=[];return this._appendLeaves(At,ot,pt=pt||10,vt=vt||0,0),At}getTile(ot,pt,vt){const At=this.trees[this._limitZoom(ot)],Zt=Math.pow(2,ot),{extent:as,radius:Ls}=this.options,cs=Ls/as,qt=(vt-cs)/Zt,Gs=(vt+1+cs)/Zt,Vs={features:[]};return this._addTileFeatures(At.range((pt-cs)/Zt,qt,(pt+1+cs)/Zt,Gs),At.data,pt,vt,Zt,Vs),pt===0&&this._addTileFeatures(At.range(1-cs/Zt,qt,1,Gs),At.data,Zt,vt,Zt,Vs),pt===Zt-1&&this._addTileFeatures(At.range(0,qt,cs/Zt,Gs),At.data,-1,vt,Zt,Vs),Vs.features.length?Vs:null}getClusterExpansionZoom(ot){let pt=this._getOriginZoom(ot)-1;for(;pt<=this.options.maxZoom;){const vt=this.getChildren(ot);if(pt++,vt.length!==1)break;ot=vt[0].properties.cluster_id}return pt}_appendLeaves(ot,pt,vt,At,Zt){const as=this.getChildren(pt);for(const Ls of as){const cs=Ls.properties;if(cs&&cs.cluster?Zt+cs.point_count<=At?Zt+=cs.point_count:Zt=this._appendLeaves(ot,cs.cluster_id,vt,At,Zt):Zt1;let Gs,Vs,Hn;if(qt)Gs=Ke(pt,cs,this.clusterProps),Vs=pt[cs],Hn=pt[cs+1];else{const Or=this.points[pt[cs+3]];Gs=Or.properties;const[ta,da]=Or.geometry.coordinates;Vs=Ze(ta),Hn=Ue(da)}const Kr={type:1,geometry:[[Math.round(this.options.extent*(Vs*Zt-vt)),Math.round(this.options.extent*(Hn*Zt-At))]],tags:Gs};let ma;ma=qt||this.options.generateId?pt[cs+3]:this.points[pt[cs+3]].id,ma!==void 0&&(Kr.id=ma),as.features.push(Kr)}}_limitZoom(ot){return Math.max(this.options.minZoom,Math.min(Math.floor(+ot),this.options.maxZoom+1))}_cluster(ot,pt){const{radius:vt,extent:At,reduce:Zt,minPoints:as}=this.options,Ls=vt/(At*Math.pow(2,pt)),cs=ot.data,qt=[],Gs=this.stride;for(let Vs=0;Vspt&&(ta+=cs[va+5])}if(ta>Or&&ta>=as){let da,va=Hn*Or,hi=Kr*Or,el=-1;const Oo=(Vs/Gs<<5)+(pt+1)+this.points.length;for(const Ei of ma){const Wa=Ei*Gs;if(cs[Wa+2]<=pt)continue;cs[Wa+2]=pt;const wo=cs[Wa+5];va+=cs[Wa]*wo,hi+=cs[Wa+1]*wo,cs[Wa+4]=Oo,Zt&&(da||(da=this._map(cs,Vs,!0),el=this.clusterProps.length,this.clusterProps.push(da)),Zt(da,this._map(cs,Wa)))}cs[Vs+4]=Oo,qt.push(va/ta,hi/ta,1/0,Oo,-1,ta),Zt&&qt.push(el)}else{for(let da=0;da1)for(const da of ma){const va=da*Gs;if(!(cs[va+2]<=pt)){cs[va+2]=pt;for(let hi=0;hi>5}_getOriginZoom(ot){return(ot-this.points.length)%32}_map(ot,pt,vt){if(ot[pt+5]>1){const as=this.clusterProps[ot[pt+6]];return vt?Object.assign({},as):as}const At=this.points[ot[pt+3]].properties,Zt=this.options.map(At);return vt&&Zt===At?Object.assign({},Zt):Zt}}function qe(ms,ot,pt){return{type:"Feature",id:ms[ot+3],properties:Ke(ms,ot,pt),geometry:{type:"Point",coordinates:[(vt=ms[ot],360*(vt-.5)),et(ms[ot+1])]}};var vt}function Ke(ms,ot,pt){const vt=ms[ot+5],At=vt>=1e4?`${Math.round(vt/1e3)}k`:vt>=1e3?Math.round(vt/100)/10+"k":vt,Zt=ms[ot+6],as=Zt===-1?{}:Object.assign({},pt[Zt]);return Object.assign(as,{cluster:!0,cluster_id:ms[ot+3],point_count:vt,point_count_abbreviated:At})}function Ze(ms){return ms/360+.5}function Ue(ms){const ot=Math.sin(ms*Math.PI/180),pt=.5-.25*Math.log((1+ot)/(1-ot))/Math.PI;return pt<0?0:pt>1?1:pt}function et(ms){const ot=(180-360*ms)*Math.PI/180;return 360*Math.atan(Math.exp(ot))/Math.PI-90}function Qe(ms,ot,pt,vt){let At=vt;const Zt=ot+(pt-ot>>1);let as,Ls=pt-ot;const cs=ms[ot],qt=ms[ot+1],Gs=ms[pt],Vs=ms[pt+1];for(let Hn=ot+3;HnAt)as=Hn,At=Kr;else if(Kr===At){const ma=Math.abs(Hn-Zt);mavt&&(as-ot>3&&Qe(ms,ot,as,vt),ms[as+2]=At,pt-as>3&&Qe(ms,as,pt,vt))}function Ge(ms,ot,pt,vt,At,Zt){let as=At-pt,Ls=Zt-vt;if(as!==0||Ls!==0){const cs=((ms-pt)*as+(ot-vt)*Ls)/(as*as+Ls*Ls);cs>1?(pt=At,vt=Zt):cs>0&&(pt+=as*cs,vt+=Ls*cs)}return as=ms-pt,Ls=ot-vt,as*as+Ls*Ls}function nt(ms,ot,pt,vt){const At={id:ms??null,type:ot,geometry:pt,tags:vt,minX:1/0,minY:1/0,maxX:-1/0,maxY:-1/0};if(ot==="Point"||ot==="MultiPoint"||ot==="LineString")ft(At,pt);else if(ot==="Polygon")ft(At,pt[0]);else if(ot==="MultiLineString")for(const Zt of pt)ft(At,Zt);else if(ot==="MultiPolygon")for(const Zt of pt)ft(At,Zt[0]);return At}function ft(ms,ot){for(let pt=0;pt0&&(as+=vt?(At*Gs-qt*Zt)/2:Math.sqrt(Math.pow(qt-At,2)+Math.pow(Gs-Zt,2))),At=qt,Zt=Gs}const Ls=ot.length-3;ot[2]=1,Qe(ot,0,Ls,pt),ot[Ls+2]=1,ot.size=Math.abs(as),ot.start=0,ot.end=ot.size}function Ts(ms,ot,pt,vt){for(let At=0;At1?1:pt}function Nt(ms,ot,pt,vt,At,Zt,as,Ls){if(vt/=ot,Zt>=(pt/=ot)&&as=vt)return null;const cs=[];for(const qt of ms){const Gs=qt.geometry;let Vs=qt.type;const Hn=At===0?qt.minX:qt.minY,Kr=At===0?qt.maxX:qt.maxY;if(Hn>=pt&&Kr=vt)continue;let ma=[];if(Vs==="Point"||Vs==="MultiPoint")Ds(Gs,ma,pt,vt,At);else if(Vs==="LineString")_t(Gs,ma,pt,vt,At,!1,Ls.lineMetrics);else if(Vs==="MultiLineString")rn(Gs,ma,pt,vt,At,!1);else if(Vs==="Polygon")rn(Gs,ma,pt,vt,At,!0);else if(Vs==="MultiPolygon")for(const Or of Gs){const ta=[];rn(Or,ta,pt,vt,At,!0),ta.length&&ma.push(ta)}if(ma.length){if(Ls.lineMetrics&&Vs==="LineString"){for(const Or of ma)cs.push(nt(qt.id,Vs,Or,qt.tags));continue}Vs!=="LineString"&&Vs!=="MultiLineString"||(ma.length===1?(Vs="LineString",ma=ma[0]):Vs="MultiLineString"),Vs!=="Point"&&Vs!=="MultiPoint"||(Vs=ma.length===3?"Point":"MultiPoint"),cs.push(nt(qt.id,Vs,ma,qt.tags))}}return cs.length?cs:null}function Ds(ms,ot,pt,vt,At){for(let Zt=0;Zt=pt&&as<=vt&&Ps(ot,ms[Zt],ms[Zt+1],ms[Zt+2])}}function _t(ms,ot,pt,vt,At,Zt,as){let Ls=Xs(ms);const cs=At===0?_n:Zs;let qt,Gs,Vs=ms.start;for(let ta=0;tapt&&(Gs=cs(Ls,da,va,el,Oo,pt),as&&(Ls.start=Vs+qt*Gs)):Ei>vt?Wa=pt&&(Gs=cs(Ls,da,va,el,Oo,pt),wo=!0),Wa>vt&&Ei<=vt&&(Gs=cs(Ls,da,va,el,Oo,vt),wo=!0),!Zt&&wo&&(as&&(Ls.end=Vs+qt*Gs),ot.push(Ls),Ls=Xs(ms)),as&&(Vs+=qt)}let Hn=ms.length-3;const Kr=ms[Hn],ma=ms[Hn+1],Or=At===0?Kr:ma;Or>=pt&&Or<=vt&&Ps(Ls,Kr,ma,ms[Hn+2]),Hn=Ls.length-3,Zt&&Hn>=3&&(Ls[Hn]!==Ls[0]||Ls[Hn+1]!==Ls[1])&&Ps(Ls,Ls[0],Ls[1],Ls[2]),Ls.length&&ot.push(Ls)}function Xs(ms){const ot=[];return ot.size=ms.size,ot.start=ms.start,ot.end=ms.end,ot}function rn(ms,ot,pt,vt,At,Zt){for(const as of ms)_t(as,ot,pt,vt,At,Zt,!1)}function Ps(ms,ot,pt,vt){ms.push(ot,pt,vt)}function _n(ms,ot,pt,vt,At,Zt){const as=(Zt-ot)/(vt-ot);return Ps(ms,Zt,pt+(At-pt)*as,1),as}function Zs(ms,ot,pt,vt,At,Zt){const as=(Zt-pt)/(At-pt);return Ps(ms,ot+(vt-ot)*as,Zt,1),as}function gr(ms,ot){const pt=[];for(let vt=0;vt0&&ot.size<(At?as:vt))return void(pt.numPoints+=ot.length/3);const Ls=[];for(let cs=0;csas)&&(pt.numSimplified++,Ls.push(ot[cs],ot[cs+1])),pt.numPoints++;At&&function(cs,qt){let Gs=0;for(let Vs=0,Hn=cs.length,Kr=Hn-2;Vs0===qt)for(let Vs=0,Hn=cs.length;Vs24)throw new Error("maxZoom should be in the 0-24 range");if(pt.promoteId&&pt.generateId)throw new Error("promoteId and generateId cannot be used together.");let At=function(Zt,as){const Ls=[];if(Zt.type==="FeatureCollection")for(let cs=0;cs1&&console.time("creation"),Kr=this.tiles[Hn]=or(ot,pt,vt,At,qt),this.tileCoords.push({z:pt,x:vt,y:At}),Gs)){Gs>1&&(console.log("tile z%d-%d-%d (features: %d, points: %d, simplified: %d)",pt,vt,At,Kr.numFeatures,Kr.numPoints,Kr.numSimplified),console.timeEnd("creation"));const wo=`z${pt}`;this.stats[wo]=(this.stats[wo]||0)+1,this.total++}if(Kr.source=ot,Zt==null){if(pt===qt.indexMaxZoom||Kr.numPoints<=qt.indexMaxPoints)continue}else{if(pt===qt.maxZoom||pt===Zt)continue;if(Zt!=null){const wo=Zt-pt;if(vt!==as>>wo||At!==Ls>>wo)continue}}if(Kr.source=null,ot.length===0)continue;Gs>1&&console.time("clipping");const ma=.5*qt.buffer/qt.extent,Or=.5-ma,ta=.5+ma,da=1+ma;let va=null,hi=null,el=null,Oo=null,Ei=Nt(ot,Vs,vt-ma,vt+ta,0,Kr.minX,Kr.maxX,qt),Wa=Nt(ot,Vs,vt+Or,vt+da,0,Kr.minX,Kr.maxX,qt);ot=null,Ei&&(va=Nt(Ei,Vs,At-ma,At+ta,1,Kr.minY,Kr.maxY,qt),hi=Nt(Ei,Vs,At+Or,At+da,1,Kr.minY,Kr.maxY,qt),Ei=null),Wa&&(el=Nt(Wa,Vs,At-ma,At+ta,1,Kr.minY,Kr.maxY,qt),Oo=Nt(Wa,Vs,At+Or,At+da,1,Kr.minY,Kr.maxY,qt),Wa=null),Gs>1&&console.timeEnd("clipping"),cs.push(va||[],pt+1,2*vt,2*At),cs.push(hi||[],pt+1,2*vt,2*At+1),cs.push(el||[],pt+1,2*vt+1,2*At),cs.push(Oo||[],pt+1,2*vt+1,2*At+1)}}getTile(ot,pt,vt){ot=+ot,pt=+pt,vt=+vt;const At=this.options,{extent:Zt,debug:as}=At;if(ot<0||ot>24)return null;const Ls=1<1&&console.log("drilling down to z%d-%d-%d",ot,pt,vt);let qt,Gs=ot,Vs=pt,Hn=vt;for(;!qt&&Gs>0;)Gs--,Vs>>=1,Hn>>=1,qt=this.tiles[Xt(Gs,Vs,Hn)];return qt&&qt.source?(as>1&&(console.log("found parent tile z%d-%d-%d",Gs,Vs,Hn),console.time("drilling down")),this.splitTile(qt.source,Gs,Vs,Hn,ot,pt,vt),as>1&&console.timeEnd("drilling down"),this.tiles[cs]?In(this.tiles[cs],Zt):null):null}}function Xt(ms,ot,pt){return 32*((1<qt.tags&&"3d_elevation_id"in qt.tags&&"source"in qt.tags&&qt.tags.source==="elevation",Zt=vt.features.filter(qt=>At(qt));let as={_geojsonTileLayer:vt.features};Zt.length>0&&(as={_geojsonTileLayer:vt.features.filter(qt=>!At(qt)),hd_road_elevation:Zt});const Ls=new Q(as),cs=function(qt){const Gs=new c.a$;for(const Vs of Object.keys(qt))Gs.writeMessage(3,je,{name:Vs,features:qt[Vs]});return Gs.finish()}(as).buffer;ot(null,{vectorTile:Ls,rawData:cs})}class Qn extends I{constructor(ot){super(ot),this.loadVectorData=rr,this._dynamicIndex=new ce}loadData(ot,pt){const vt=ot&&ot.request,At=vt&&vt.collectResourceTiming;this._geoJSONIndex=null,this.loadGeoJSON(ot,(Zt,as)=>{if(Zt||!as)return pt(Zt);if(typeof as!="object")return pt(new Error(`Input data given to '${ot.source}' is not a valid GeoJSON object.`));{try{if(ot.filter){const cs=c.X(ot.filter,{type:"boolean","property-type":"data-driven",overridable:!1,transition:!1});if(cs.result==="error")throw new Error(cs.value.map(qt=>`${qt.key}: ${qt.message}`).join(", "));as.features=as.features.filter(qt=>cs.value.evaluate({zoom:0},qt))}ot.dynamic?(as.type==="Feature"&&(as={type:"FeatureCollection",features:[as]}),ot.append||(this._dynamicIndex.clear(),this.loaded={}),this._dynamicIndex.load(as.features,this.loaded),ot.cluster&&(as.features=this._dynamicIndex.getFeatures())):this.loaded={},this._geoJSONIndex=ot.cluster?new Be(function({superclusterOptions:cs,clusterProperties:qt}){if(!qt||!cs)return cs;const Gs={},Vs={},Hn={accumulated:null,zoom:0},Kr={properties:null},ma=Object.keys(qt);for(const Or of ma){const[ta,da]=qt[Or],va=c.X(da),hi=c.X(typeof ta=="string"?[ta,["accumulated"],["get",Or]]:ta);Gs[Or]=va.value,Vs[Or]=hi.value}return cs.map=Or=>{Kr.properties=Or;const ta={};for(const da of ma)ta[da]=Gs[da].evaluate(Hn,Kr);return ta},cs.reduce=(Or,ta)=>{Kr.properties=ta;for(const da of ma)Hn.accumulated=Or[da],Or[da]=Vs[da].evaluate(Hn,Kr)},cs}(ot)).load(as.features):ot.dynamic?this._dynamicIndex:function(cs,qt){return new Zn(cs,qt)}(as,ot.geojsonVtOptions)}catch(cs){return pt(cs)}const Ls={};if(At){const cs=d(vt);cs&&(Ls.resourceTiming={},Ls.resourceTiming[ot.source]=JSON.parse(JSON.stringify(cs)))}pt(null,Ls)}})}reloadTile(ot,pt){const vt=this.loaded;return vt&&vt[ot.uid]?ot.partial?pt(null,void 0):super.reloadTile(ot,pt):this.loadTile(ot,pt)}loadGeoJSON(ot,pt){if(ot.request)c.m(ot.request,pt);else{if(typeof ot.data!="string")return pt(new Error(`Input data given to '${ot.source}' is not a valid GeoJSON object.`));setTimeout(()=>{try{return pt(null,JSON.parse(ot.data))}catch{return pt(new Error(`Input data given to '${ot.source}' is not a valid GeoJSON object.`))}},0)}}getClusterExpansionZoom(ot,pt){try{pt(null,this._geoJSONIndex.getClusterExpansionZoom(ot.clusterId))}catch(vt){pt(vt)}}getClusterChildren(ot,pt){try{pt(null,this._geoJSONIndex.getChildren(ot.clusterId))}catch(vt){pt(vt)}}getClusterLeaves(ot,pt){try{pt(null,this._geoJSONIndex.getLeaves(ot.clusterId,ot.limit,ot.offset))}catch(vt){pt(vt)}}}class Sn{constructor(ot,pt,vt){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=pt,this.worldview=vt}parse(ot,pt,vt,At){this.status="parsing";const Zt=new c.aR(vt.tileID.overscaledZ,vt.tileID.wrap,vt.tileID.canonical.z,vt.tileID.canonical.x,vt.tileID.canonical.y),as=[],Ls=pt.familiesBySource[vt.source],cs=new c.ff(Zt,vt.promoteId);cs.bucketLayerIDs=[],cs.is3DTile=!0,c.fB(ot).then(qt=>{const Gs=qt.json.extensionsUsed&&qt.json.extensionsUsed.includes("MAPBOX_mesh_features")||qt.json.asset.extras&&qt.json.asset.extras.MAPBOX_mesh_features,Vs=qt.json.extensionsUsed&&qt.json.extensionsUsed.includes("EXT_meshopt_compression"),Hn=new c.ae(this.zoom,{brightness:this.brightness,worldview:this.worldview});for(const Kr in Ls)for(const ma of Ls[Kr]){const Or=ma[0];cs.bucketLayerIDs.push(ma.map(va=>c.F(va.id,va.scope))),Or.recalculate(Hn,[]);const ta=c.fC(qt,1/c.cS(vt.tileID.canonical)),da=new c.fD(ma,ta,Zt,Gs,Vs,this.brightness,cs,this.worldview);Gs||(da.needsUpload=!0),as.push(da),da.evaluate(Or)}this.status="done",At(null,{buckets:as,featureIndex:cs,collisionBoxArray:null,glyphAtlasImage:null,lineAtlas:null,imageAtlas:null,brightness:null})}).catch(qt=>At(new Error(qt.message)))}}class $n{constructor({actor:ot,layerIndex:pt,availableImages:vt,availableModels:At,brightness:Zt,worldview:as}){this.actor=ot,this.layerIndex=pt,this.availableImages=vt,this.availableModels=At,this.brightness=Zt,this.loading={},this.loaded={},this.worldview=as}loadTile(ot,pt){const vt=ot.uid,At=this.loading[vt]=new Sn(ot,this.brightness,this.worldview);c.b1(ot.request,(Zt,as)=>{const Ls=!this.loading[vt];return delete this.loading[vt],Ls||Zt?(At.status="done",Ls||(this.loaded[vt]=At),pt(Zt)):as&&as.byteLength!==0?void At.parse(as,this.layerIndex,ot,(cs,qt)=>{At.status="done",this.loaded=this.loaded||{},this.loaded[vt]=At,cs||!qt?pt(cs):pt(null,qt)}):(At.status="done",this.loaded[vt]=At,pt())})}reloadTile(ot,pt){const vt=this.loaded,At=ot.uid;if(vt&&vt[At]){const Zt=vt[At];Zt.projection=ot.projection,Zt.brightness=ot.brightness;const as=(Ls,cs)=>{Zt.reloadCallback&&(delete Zt.reloadCallback,this.loadTile(ot,pt)),pt(Ls,cs)};Zt.status==="parsing"?Zt.reloadCallback=as:Zt.status==="done"&&this.loadTile(ot,pt)}}abortTile(ot,pt){const vt=ot.uid;this.loading[vt]&&delete this.loading[vt],pt()}removeTile(ot,pt){const vt=this.loaded,At=ot.uid;vt&&vt[At]&&delete vt[At],pt()}}const tn=new Map,ln=new Map;class Cr{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:Qn,"raster-dem":D,"raster-array":q,"batched-model":$n},this.workerSources={},this.self.registerWorkerSource=(pt,vt)=>{if(this.workerSourceTypes[pt])throw new Error(`Worker source with name "${pt}" already registered.`);this.workerSourceTypes[pt]=vt},this.self.registerRTLTextPlugin=pt=>{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=pt.applyArabicShaping,c.fF.processBidirectionalText=pt.processBidirectionalText,c.fF.processStyledBidirectionalText=pt.processStyledBidirectionalText;for(const vt of this.rtlPluginParsingListeners)vt(null,!0);this.rtlPluginParsingListeners=[]}}clearCaches(ot,pt,vt){delete this.layerIndexes[ot],delete this.availableImages[ot],delete this.availableModels[ot],delete this.workerSources[ot],vt()}checkIfReady(ot,pt,vt){vt()}setReferrer(ot,pt){this.referrer=pt}spriteLoaded(ot,pt){this.isSpriteLoaded[ot]||(this.isSpriteLoaded[ot]={});const{scope:vt,isLoaded:At}=pt;if(this.isSpriteLoaded[ot][vt]=At,this.workerSources[ot]&&this.workerSources[ot][vt])for(const Zt in this.workerSources[ot][vt]){const as=this.workerSources[ot][vt][Zt];for(const Ls in as){const cs=as[Ls];cs instanceof I&&(cs.isSpriteLoaded=At,cs.fire(new c.C("isSpriteLoaded")))}}}setImages(ot,pt,vt){this.availableImages[ot]||(this.availableImages[ot]={});const{scope:At,images:Zt}=pt;if(this.availableImages[ot][At]=Zt,this.workerSources[ot]&&this.workerSources[ot][At]){for(const as in this.workerSources[ot][At]){const Ls=this.workerSources[ot][At][as];for(const cs in Ls)Ls[cs].availableImages=Zt}vt()}else vt()}setModels(ot,{scope:pt,models:vt},At){if(this.availableModels[ot]||(this.availableModels[ot]={}),this.availableModels[ot][pt]=vt,this.workerSources[ot]&&this.workerSources[ot][pt]){for(const Zt in this.workerSources[ot][pt]){const as=this.workerSources[ot][pt][Zt];for(const Ls in as)as[Ls].availableModels=vt}At()}else At()}setProjection(ot,pt){this.projections[ot]=c.c0(pt)}setBrightness(ot,pt,vt){this.brightness=pt,vt()}setContextParams(ot,pt,vt){this.maxUniformBufferBindings=pt.maxBindingPoints,this.maxUniformBlockSizeDwords=pt.maxUniformBlockSizeDwords,this.disableSymbolUBO=pt.disableSymbolUBO,vt()}setWorldview(ot,pt,vt){this.worldview=pt,vt()}setLayers(ot,pt,vt){this.getLayerIndex(ot,pt.scope).replace(pt.layers,pt.options),vt()}updateLayers(ot,pt,vt){this.getLayerIndex(ot,pt.scope).update(pt.layers,pt.removedIds,pt.options),vt()}loadTile(ot,pt,vt){pt.projection=this.projections[ot]||this.defaultProjection,this.getWorkerSource(ot,pt).loadTile(pt,vt)}decodeRasterArray(ot,pt,vt){this.getWorkerSource(ot,pt).decodeRasterArray(pt,vt)}reloadTile(ot,pt,vt){pt.projection=this.projections[ot]||this.defaultProjection,this.getWorkerSource(ot,pt).reloadTile(pt,vt)}abortTile(ot,pt,vt){this.getWorkerSource(ot,pt).abortTile(pt,vt)}removeTile(ot,pt,vt){this.getWorkerSource(ot,pt).removeTile(pt,vt)}removeSource(ot,pt,vt){if(!(this.workerSources[ot]&&this.workerSources[ot][pt.scope]&&this.workerSources[ot][pt.scope][pt.type]&&this.workerSources[ot][pt.scope][pt.type][pt.source]))return;const At=this.workerSources[ot][pt.scope][pt.type][pt.source];delete this.workerSources[ot][pt.scope][pt.type][pt.source],At.removeSource!==void 0?At.removeSource(pt,vt):vt()}loadTileProvider(ot,pt,vt){(async function(At,Zt){const as=ln.get(At);if(as)return as;const Ls=tn.get(At);if(Ls!==void 0)return Ls;const cs=import(Zt).then(qt=>{const Gs=qt.default;if(typeof Gs!="function")throw new Error(`TileProvider "${At}" module must default-export a class`);if(typeof Gs.prototype.loadTile!="function")throw new Error(`TileProvider "${At}" class must have a loadTile method`);return ln.set(At,Gs),Gs}).finally(()=>{tn.delete(At)});return tn.set(At,cs),cs})(pt.name,pt.url).then(At=>{const Zt=new At(pt.options);return this.getWorkerSource(ot,{type:pt.type,source:pt.source,scope:pt.scope},Zt),Zt.load&&pt.request?Zt.load({request:pt.request}):null}).then(At=>vt(null,At)).catch(At=>vt(At instanceof Error?At:new Error(typeof At=="string"?At:"Unknown error")))}loadWorkerSource(ot,pt,vt){try{this.self.importScripts(pt.url),vt()}catch(At){vt(At)}}syncRTLPluginState(ot,pt,vt){if(c.fF.isParsed())vt(null,!0);else if(c.fF.isParsing())this.rtlPluginParsingListeners.push(vt);else try{c.fF.setState(pt);const At=c.fF.getPluginURL();!c.fF.isLoaded()||c.fF.isParsed()||c.fF.isParsing()||At==null||(c.fF.setState({pluginStatus:c.fG.parsing,pluginURL:c.fF.getPluginURL()}),this.self.importScripts(At),c.fF.isParsed()?vt(null,!0):this.rtlPluginParsingListeners.push(vt))}catch(At){vt(At)}}setConfig(ot,pt){Object.assign(c.g,pt)}getAvailableImages(ot,pt){this.availableImages[ot]||(this.availableImages[ot]={});let vt=this.availableImages[ot][pt];return vt||(vt=[]),vt}getAvailableModels(ot,pt){this.availableModels[ot]||(this.availableModels[ot]={});let vt=this.availableModels[ot][pt];return vt||(vt={}),vt}getLayerIndex(ot,pt){this.layerIndexes[ot]||(this.layerIndexes[ot]={});let vt=this.layerIndexes[ot][pt];return vt||(vt=this.layerIndexes[ot][pt]=new p,vt.scope=pt),vt}getWorkerSource(ot,pt,vt){const{type:At,source:Zt,scope:as}=pt,Ls=this.workerSources;if(Ls[ot]||(Ls[ot]={}),Ls[ot][as]||(Ls[ot][as]={}),Ls[ot][as][At]||(Ls[ot][as][At]={}),this.isSpriteLoaded[ot]||(this.isSpriteLoaded[ot]={}),!Ls[ot][as][At][Zt]){const cs={send:(Gs,Vs,Hn,Kr,ma,Or)=>this.actor.send(Gs,Vs,Hn,ot,ma,Or),scheduler:this.actor.scheduler},qt=this.workerSourceTypes[At];if(!qt)throw new Error(`Unknown worker source type "${At}".`);Ls[ot][as][At][Zt]=new qt({actor:cs,layerIndex:this.getLayerIndex(ot,as),availableImages:this.getAvailableImages(ot,as),availableModels:this.getAvailableModels(ot,as),isSpriteLoaded:this.isSpriteLoaded[ot][as],tileProvider:vt,brightness:this.brightness,worldview:this.worldview,maxUniformBufferBindings:this.maxUniformBufferBindings,maxUniformBlockSizeDwords:this.maxUniformBlockSizeDwords,disableSymbolUBO:this.disableSymbolUBO})}return Ls[ot][as][At][Zt]}rasterizeImagesWorker(ot,pt,vt){const At=new Map;for(const[Zt,{image:as,imageVariant:Ls}]of pt.tasks.entries()){const cs=this.imageRasterizer.rasterize(Ls,as,pt.scope,ot);At.set(Zt,cs)}vt(void 0,At)}removeRasterizedImages(ot,pt,vt){this.imageRasterizer.removeImagesFromCacheByIds(pt.imageIds,pt.scope,ot),vt()}enforceCacheSizeLimit(ot,pt){c.fH(pt)}getWorkerPerformanceMetrics(ot,pt,vt){vt(void 0,void 0)}}return c.fE(self)&&(self.worker=new Cr(self)),Cr}),i(["./shared"],function(o){var c="3.22.0";const d={create:"create",load:"load",fullLoad:"fullLoad"},u={mark(R){performance.mark(R)},measure(R,w,E){performance.measure(R,w,E)}};function h(R){const w=R.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={},x=function(){if(m)return p;function R(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 Z,X,oe=new Blob([""],{type:"text/javascript"}),xe=URL.createObjectURL(oe);try{X=new Worker(xe),Z=!0}catch{Z=!1}return X&&X.terminate(),URL.revokeObjectURL(xe),Z}()?function(){var Z=document.createElement("canvas");Z.width=Z.height=1;var X=Z.getContext("2d");if(!X)return!1;var oe=X.getImageData(0,0,1,1);return oe&&oe.width===Z.width}()?(E[H=F&&F.failIfMajorPerformanceCaveat]===void 0&&(E[H]=function(Z){var X,oe=function(xe){var Ne=document.createElement("canvas"),Le=Object.create(R.webGLContextAttributes);return Le.failIfMajorPerformanceCaveat=xe,Ne.getContext("webgl2",Le)}(Z);if(!oe)return!1;try{X=oe.createShader(oe.VERTEX_SHADER)}catch{return!1}return!(!X||oe.isContextLost())&&(oe.shaderSource(X,"void main() {}"),oe.compileShader(X),oe.getShaderParameter(X,oe.COMPILE_STATUS)===!0)}(H)),E[H]?document.documentMode?"insufficient ECMAScript 6 support":void 0:"insufficient WebGL2 support"):"insufficient Canvas/getImageData support":"insufficient worker support";var H}m=1,p.supported=R,p.notSupportedReason=w;var E={};return R.webGLContextAttributes={antialias:!1,alpha:!0,stencil:!0,depth:!0},p}();function g(R,w,E){const F=document.createElement(R);return w!=null&&(F.className=w),E&&E.appendChild(F),F}function y(R,w,E){const F=document.createElementNS("http://www.w3.org/2000/svg",R);for(const H of Object.keys(w))F.setAttributeNS(null,H,String(w[H]));return E&&E.appendChild(F),F}const b=typeof document<"u"?document.documentElement&&document.documentElement.style:null,v=b&&b.userSelect!==void 0?"userSelect":"WebkitUserSelect";let N;function C(){b&&v&&(N=b[v],b[v]="none")}function A(){b&&v&&(b[v]=N)}function T(R){R.preventDefault(),R.stopPropagation(),window.removeEventListener("click",T,!0)}function P(){window.addEventListener("click",T,!0),window.setTimeout(()=>{window.removeEventListener("click",T,!0)},0)}function M(R,w){const E=R.getBoundingClientRect();return B(R,E,w)}function I(R,w){const E=R.getBoundingClientRect(),F=[];for(let H=0;Hthis._skuTokenExpiresAt}transformRequest(w,E){return this._transformRequestFn&&this._transformRequestFn(w,E)||{url:w}}normalizeStyleURL(w,E){if(!o.e(w))return w;const F=Q(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=Q(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=Q(w);return F.path=`/models/v1${F.path}`,this._makeAPIURL(F,this._customAccessToken||E)}normalizeSourceURL(w,E,F,H){if(!o.e(w))return w;const Z=Q(w);return Z.path=`/v4/${Z.authority}.json`,Z.params.push("secure"),F&&Z.params.push(`language=${F}`),H&&Z.params.push(`worldview=${H}`),this._makeAPIURL(Z,this._customAccessToken||E)}normalizeIconsetURL(w,E){const F=Q(w);return o.e(w)?(F.path=`/styles/v1${F.path}/iconset.pbf`,this._makeAPIURL(F,this._customAccessToken||E)):J(F)}normalizeSpriteURL(w,E,F,H){const Z=Q(w);return o.e(w)?(Z.path=`/styles/v1${Z.path}/sprite${E}${F}`,this._makeAPIURL(Z,this._customAccessToken||H)):(Z.path+=`${E}${F}`,J(Z))}normalizeTileURL(w,E,F){if(this._isSkuTokenExpired()&&this._createSkuToken(),w&&!o.e(w))return w;const H=Q(w);H.path=H.path.replace(/(\.(png|jpg)\d*)(?=$)/,`${E||F&&H.authority!=="raster"&&F===512?"@2x":""}${o.k.supported?".webp":"$1"}`),H.authority==="raster"?H.path=`/${o.g.RASTER_URL_PREFIX}${H.path}`:H.authority==="rasterarrays"?H.path=`/${o.g.RASTERARRAYS_URL_PREFIX}${H.path}`:H.authority==="3dtiles"?H.path=`/${o.g.TILES3D_URL_PREFIX}${H.path}`:(H.path=H.path.replace(/^.+\/v4\//,"/"),H.path=`/${o.g.TILE_URL_VERSION}${H.path}`);const Z=this._customAccessToken||function(X){for(const oe of X){const xe=oe.match(/^access_token=(.*)$/);if(xe)return xe[1]}return null}(H.params)||o.g.ACCESS_TOKEN;return o.g.REQUIRE_ACCESS_TOKEN&&Z&&this._skuToken&&H.params.push(`sku=${this._skuToken}`),this._makeAPIURL(H,Z)}canonicalizeTileURL(w,E){const F=Q(w);if(!F.path.match(/^(\/v4\/|\/(raster|rasterarrays)\/v1\/)/)||!F.path.match(/\.[\w]+$/))return w;let H="mapbox://";F.path.match(/^\/raster\/v1\//)?H+=`raster/${F.path.replace(`/${o.g.RASTER_URL_PREFIX}/`,"")}`:F.path.match(/^\/rasterarrays\/v1\//)?H+=`rasterarrays/${F.path.replace(`/${o.g.RASTERARRAYS_URL_PREFIX}/`,"")}`:H+=`tiles/${F.path.replace(`/${o.g.TILE_URL_VERSION}/`,"")}`;let Z=F.params;return E&&(Z=Z.filter(X=>!X.match(/^access_token=/))),Z.length&&(H+=`?${Z.join("&")}`),H}canonicalizeTileset(w,E){const F=!!E&&o.e(E),H=[];for(const Z of w.tiles||[])o.f(Z)?H.push(this.canonicalizeTileURL(Z,F)):H.push(Z);return H}_makeAPIURL(w,E){const F="See https://docs.mapbox.com/api/overview/#access-tokens-and-token-scopes",H=Q(o.g.API_URL);if(w.protocol=H.protocol,w.authority=H.authority,w.protocol==="http"){const Z=w.params.indexOf("secure");Z>=0&&w.params.splice(Z,1)}if(H.path!=="/"&&(w.path=`${H.path}${w.path}`),!o.g.REQUIRE_ACCESS_TOKEN)return J(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(Z=>Z.indexOf("access_token")===-1),w.params.push(`access_token=${E||""}`),J(w)}}const K=/^(\w+):\/\/([^/?]*)(\/[^?]+)?\??(.+)?/;function Q(R){const w=R.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 J(R){const w=R.params.length?`?${R.params.join("&")}`:"";return`${R.protocol}://${R.authority}${R.path}${w}`}const ce="mapbox.eventData";function ue(R){if(!R)return null;const w=R.split(".");if(!w||w.length!==3)return null;try{return JSON.parse(o.l(w[1]))}catch{return null}}function ne(R){return!(!o.g.EVENTS_URL||!R&&!o.g.ACCESS_TOKEN)}class ee{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?`${ce}.${w}:${F}`:`${ce}:${F}`}fetchEventData(){const w=o.s("localStorage"),E=this.getStorageKey(),F=this.getStorageKey("uuid"),H=this.getStorageKey("uuidTimestamp");if(w)try{const Z=localStorage.getItem(E);Z&&(this.eventData=JSON.parse(Z));const X=localStorage.getItem(F);X&&(this.anonId=X);const oe=localStorage.getItem(H);oe&&(this.anonIdTimestamp=Number(oe));const xe=Date.now()-864e5;(!this.anonIdTimestamp||this.anonIdTimestamp=1&&localStorage.setItem(E,JSON.stringify(this.eventData)),X&&localStorage.setItem(H,X.toString())}catch{o.w("Unable to write to LocalStorage")}}processRequests(w){}postEvent(w,E,F,H){if(!o.g.EVENTS_URL)return;const Z=Q(o.g.EVENTS_URL);Z.params.push(`access_token=${H||o.g.ACCESS_TOKEN||""}`);const X={event:this.type,created:new Date(w).toISOString()},oe=E?Object.assign(X,E):X,xe={url:J(Z),headers:{"Content-Type":"text/plain"},body:JSON.stringify([oe])};this.pendingRequest=o.p(xe,Ne=>{this.pendingRequest=null,F(Ne),this.saveEventData(),this.processRequests(H)})}queueRequest(w,E){this.queue.push(w),this.processRequests(E)}}class le extends ee{constructor(w){super("metrics"),w&&(this.data=w)}postMetricsEvent(w){if(!ne(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 he=new class extends ee{constructor(R){super("appUserTurnstile"),this._customAccessToken=R}postTurnstileEvent(R,w){ne(w)&&Array.isArray(R)&&R.some(E=>o.e(E)||o.f(E))&&this.queueRequest(Date.now(),w)}processRequests(R){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 H=this.queue.shift();if(this.eventData.lastSuccess){const Z=new Date(this.eventData.lastSuccess),X=new Date(H),oe=(H-this.eventData.lastSuccess)/864e5;F=F||oe>=1||oe<-1||Z.getDate()!==X.getDate()}else F=!0;F?this.postEvent(H,{sdkIdentifier:"mapbox-gl-js",sdkVersion:c,skuId:q,"enabled.telemetry":!1,userId:this.anonId},Z=>{Z||(this.eventData.lastSuccess=H,this.eventData.tokenU=E)},R):this.processRequests()}},ve=he.postTurnstileEvent.bind(he),ge=new class extends ee{constructor(){super("map.load"),this.success={},this.skuToken=""}postMapLoadEvent(R,w,E,F){this.skuToken=w,this.errorCb=F,o.g.EVENTS_URL&&(E||o.g.ACCESS_TOKEN?this.queueRequest({id:R,timestamp:Date.now()},E):this.errorCb(new Error(W)))}processRequests(R){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:q,skuToken:this.skuToken,userId:this.anonId},F=>{F?this.errorCb(F):w&&(this.success[w]=!0)},R))}remove(){this.errorCb=null}},fe=ge.postMapLoadEvent.bind(ge),je=new class extends ee{constructor(){super("style.load"),this.eventIdPerMapInstanceMap=new Map,this.mapInstanceIdMap=new WeakMap}getMapInstanceId(R){let w=this.mapInstanceIdMap.get(R);return w||(w=o.u(),this.mapInstanceIdMap.set(R,w)),w}getEventId(R){const w=this.eventIdPerMapInstanceMap.get(R)||0;return this.eventIdPerMapInstanceMap.set(R,w+1),w}postStyleLoadEvent(R,w){const{map:E,style:F,importedStyles:H}=w;if(!ne(R))return;const Z=this.getMapInstanceId(E),X={mapInstanceId:Z,eventId:this.getEventId(Z),style:F};H.length&&(X.importedStyles=H),this.queueRequest({timestamp:Date.now(),payload:X},R)}processRequests(R){if(this.pendingRequest||this.queue.length===0)return;const{timestamp:w,payload:E}=this.queue.shift();this.postEvent(w,E,()=>{},R)}},Ee=je.postStyleLoadEvent.bind(je),Me=new le({attributes:[{name:"maps/js/layer-animations/style-with-appearances"}]}),De=Me.postMetricsEvent.bind(Me),ze=new le({attributes:[{name:"maps/js/layer-animations/runtime-appearances"}]}),ke=ze.postMetricsEvent.bind(ze),Xe=new class extends ee{constructor(){super("gljs.performance")}postPerformanceEvent(R,w){ne(R)&&this.queueRequest({timestamp:Date.now(),performanceData:w},R)}processRequests(R){if(this.pendingRequest||this.queue.length===0)return;const{timestamp:w,performanceData:E}=this.queue.shift(),F=function(H){const Z=performance.getEntriesByType("resource"),X=performance.getEntriesByType("mark"),oe=function(tt){const dt={};if(tt){for(const it in tt)if(it!=="other")for(const jt of tt[it]){const wt=`${it}ResolveRangeMin`,Ot=`${it}ResolveRangeMax`,Vt=`${it}RequestCount`,Ct=`${it}RequestCachedCount`;dt[wt]=Math.min(dt[wt]||1/0,jt.startTime),dt[Ot]=Math.max(dt[Ot]||-1/0,jt.responseEnd);const ks=ss=>{dt[ss]===void 0&&(dt[ss]=0),++dt[ss]};jt.transferSize!==void 0&&jt.transferSize===0&&ks(Ct),ks(Vt)}}return dt}(function(tt,dt){const it={};if(tt)for(const jt of tt){const wt=dt(jt);it[wt]===void 0&&(it[wt]=[]),it[wt].push(jt)}return it}(Z,h)),xe=window.devicePixelRatio,Ne=navigator.connection||navigator.mozConnection||navigator.webkitConnection,Le=Ne?Ne.effectiveType:void 0,We={counters:[],metadata:[],attributes:[]},He=(tt,dt,it)=>{it!=null&&tt.push({name:dt,value:it.toString()})};for(const tt in oe)He(We.counters,tt,oe[tt]);if(H.interactionRange[0]!==1/0&&H.interactionRange[1]!==-1/0&&(He(We.counters,"interactionRangeMin",H.interactionRange[0]),He(We.counters,"interactionRangeMax",H.interactionRange[1])),X)for(const tt of Object.values(d)){const dt=X.find(it=>it.name===tt);dt&&He(We.counters,tt,dt.startTime)}return He(We.counters,"visibilityHidden",H.visibilityHidden),He(We.attributes,"style",function(tt){if(tt)for(const dt of tt){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]}`}}}(Z)),He(We.attributes,"terrainEnabled",H.terrainEnabled?"true":"false"),He(We.attributes,"fogEnabled",H.fogEnabled?"true":"false"),He(We.attributes,"projection",H.projection),He(We.attributes,"zoom",H.zoom),He(We.metadata,"devicePixelRatio",xe),He(We.metadata,"connectionEffectiveType",Le),He(We.metadata,"navigatorUserAgent",navigator.userAgent),He(We.metadata,"screenWidth",window.screen.width),He(We.metadata,"screenHeight",window.screen.height),He(We.metadata,"windowWidth",window.innerWidth),He(We.metadata,"windowHeight",window.innerHeight),He(We.metadata,"mapWidth",H.width/xe),He(We.metadata,"mapHeight",H.height/xe),He(We.metadata,"webglRenderer",H.renderer),He(We.metadata,"webglVendor",H.vendor),He(We.metadata,"sdkVersion",c),He(We.metadata,"sdkIdentifier","mapbox-gl-js"),We}(E);for(const H of F.metadata);for(const H of F.counters);for(const H of F.attributes);this.postEvent(w,F,()=>{},R)}},Se=Xe.postPerformanceEvent.bind(Xe),Re=new class extends ee{constructor(){super("map.auth"),this.success={},this.skuToken=""}getSession(R,w,E,F){if(!o.g.API_URL||!o.g.SESSION_PATH)return;const H=Q(o.g.API_URL+o.g.SESSION_PATH);H.params.push(`sku=${w||""}`),H.params.push(`access_token=${F||o.g.ACCESS_TOKEN||""}`);const Z={url:J(H),headers:{"Content-Type":"text/plain"}};this.pendingRequest=o.h(Z,X=>{this.pendingRequest=null,E(X),this.saveEventData(),this.processRequests(F)})}getSessionAPI(R,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:R,timestamp:Date.now()},E):this.errorCb(new Error(W)))}processRequests(R){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)},R)}remove(){this.errorCb=null}},Ae=Re.getSessionAPI.bind(Re),Be=new Set;function qe(R,w){w?Be.add(R):Be.delete(R)}class Ke{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(R){const{userImage:w}=R;return!!(w&&w.render&&w.render())&&(R.data.replace(new Uint8Array(w.data.buffer)),!0)}const Ue={workerUrl:"",workerClass:null,workerParams:void 0};function et(R){return Ue.workerClass!=null?new Ue.workerClass:new self.Worker(Ue.workerUrl,Object.assign({name:R},Ue.workerParams))}const Qe="mapboxgl_preloaded_worker_pool";class Ge{constructor(w){this.active={},this.name=w}acquire(w,E=Ge.workerCount){if(!this.workers)for(this.workers=[];this.workers.length{E.terminate()}),this.workers=null)}isPreloaded(){return!!this.active[Qe]}numActive(){return Object.keys(this.active).length}}Ge.workerCount=2;class nt{constructor(w,E,F="Worker",H=Ge.workerCount){this.workerPool=w,this.actors=[],this.currentActor=0,this.id=o.r();const Z=this.workerPool.acquire(this.id,H);for(let X=0;X{this.ready=!0})}broadcast(w,E,F){o.t(this.actors,(H,Z)=>{H.send(w,E,Z)},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 ft,lt;function Mt(){return ft||(ft=new Ge),ft}nt.Actor=o.A;class Ft 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 nt((lt||(lt=new Ge("ImageRasterizer")),lt),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:H}of this.requestors)this._notify(F,E,H);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 H=this.imageVersions.get(E),Z=H.get(w.toString())||0;H.set(w.toString(),Z+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 H of w){if(H[0]o.I.from(E))}getImageVersions(w){const E=this.imageVersions.get(w);if(E)return E}getImages(w,E,F){const H=[],Z=[],X=this.imageProviders.get(E);for(const Le of w){if(!Le.iconsetId){H.push(Le);continue}const We=X.get(Le.iconsetId);We&&(this.getImage(Le,E)?Z.push(Le):We.addPendingRequest(Le))}if(H.length===0)return void this._notify(Z,E,F);let oe=!0;const xe=!!this.loaded.get(E),Ne=this.images.get(E);if(!xe)for(const Le of H)Ne.has(Le.toString())||(oe=!1);xe||oe?this._notify(H,E,F):this.requestors.push({ids:H,scope:E,callback:F})}rasterizeImages(w,E){const F=new Map,{tasks:H,scope:Z}=w;for(const[X,oe]of H.entries()){const xe=this.getImage(oe.id,Z);xe&&F.set(X,{image:xe,imageVariant:oe})}this._rasterizeImages(Z,F,E)}_rasterizeImages(w,E,F){if(o.y())this.imageRasterizerDispatcher.getActor().send("rasterizeImagesWorker",{tasks:E,scope:w},F);else{const H=new Map;for(const[Z,{image:X,imageVariant:oe}]of E.entries())H.set(Z,this.imageRasterizer.rasterize(oe,X,w,0));F(void 0,H)}}getUpdatedImages(w){return this.updatedImages.get(w)||new Set}_notify(w,E,F){const H=this.images.get(E),Z=new Map;for(const X of w){if(!H.get(X.toString())){if(X.iconsetId)continue;this.fire(new o.C("styleimagemissing",{id:X.name}))}const oe=H.get(X.toString());if(!oe){o.w(`Image "${X.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 xe={data:oe.usvg?null:oe.data.clone(),pixelRatio:oe.pixelRatio,sdf:oe.sdf,usvg:oe.usvg,stretchX:oe.stretchX,stretchY:oe.stretchY,content:oe.content,hasRenderCallback:!!(oe.userImage&&oe.userImage.render)};oe.usvg&&Object.assign(xe,{width:oe.icon.usvg_tree.width,height:oe.icon.usvg_tree.height}),Z.set(o.I.toString(X),xe)}F(null,{images:Z,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 H=w.toString(),Z=this.patterns.get(E),X=Z.get(H),oe=this.getImage(w,E);if(!oe)return null;if(X){if(X.position.version===oe.version)return X.position;X.position.version=oe.version}else{if(oe.usvg&&!oe.data){const xe=this.getPatternInFlightId(H,E);if(this.patternsInFlight.has(xe))return null;this.patternsInFlight.add(xe);const Ne=new o.D(w).scaleSelf(o.o.devicePixelRatio),Le=new Map([[Ne.toString(),{image:oe,imageVariant:Ne}]]);return this._rasterizeImages(E,Le,(We,He)=>this.storePatternImage(Ne,E,oe,F,He)),null}this.storePattern(w,E,oe)}return this._updatePatternAtlas(E,F),Z.get(H).position}getPatternInFlightId(w,E){return o.F(w,E)}hasPatternsInFlight(){return this.patternsInFlight.size!==0}storePatternImage(w,E,F,H,Z){const X=w.toString(),oe=Z?Z.get(X):void 0;oe&&(F.data=oe,this.storePattern(w.id,E,F),this._updatePatternAtlas(E,H),this.patternsInFlight.delete(this.getPatternInFlightId(w.id.toString(),E)))}storePattern(w,E,F){const H={w:F.data.width+2*o.G,h:F.data.height+2*o.G,x:0,y:0},Z=new o.H(H,F,o.G);this.patterns.get(E).set(w.toString(),{bin:H,position:Z})}destroyAtlasTextures(){for(const w of this.atlasTexture.values())w&&w.destroy();this.atlasTexture.clear()}bind(w,E){const F=w.gl;let H=this.atlasTexture.get(E);H?this.dirty&&(H.update(this.atlasImage.get(E)),this.dirty=!1):(H=new o.T(w,this.atlasImage.get(E),F.RGBA8),this.atlasTexture.set(E,H)),H.bind(F.LINEAR,F.CLAMP_TO_EDGE)}_updatePatternAtlas(w,E){const F=this.patterns.get(w),H=Array.from(F.values()).map(({bin:Ne})=>Ne),{w:Z,h:X}=o.J(H),oe=this.atlasImage.get(w);oe.resize({width:Z||1,height:X||1});const xe=this.images.get(w);for(const[Ne,{bin:Le,position:We}]of F.entries()){let He=We.padding;const tt=Le.x+He,dt=Le.y+He,it=xe.get(Ne).data,jt=it.width,wt=it.height;He=He>1?He-1:He,o.q.copy(it,oe,{x:0,y:0},{x:tt,y:dt},{width:jt,height:wt},E),o.q.copy(it,oe,{x:0,y:wt-He},{x:tt,y:dt-He},{width:jt,height:He},E),o.q.copy(it,oe,{x:0,y:0},{x:tt,y:dt+wt},{width:jt,height:He},E),o.q.copy(it,oe,{x:jt-He,y:0},{x:tt-He,y:dt},{width:He,height:wt},E),o.q.copy(it,oe,{x:0,y:0},{x:tt+jt,y:dt},{width:He,height:wt},E),o.q.copy(it,oe,{x:jt-He,y:wt-He},{x:tt-He,y:dt-He},{width:He,height:He},E),o.q.copy(it,oe,{x:0,y:wt-He},{x:tt+jt,y:dt-He},{width:He,height:He},E),o.q.copy(it,oe,{x:0,y:0},{x:tt+jt,y:dt+wt},{width:He,height:He},E),o.q.copy(it,oe,{x:jt-He,y:0},{x:tt-He,y:dt+wt},{width:He,height:He},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 H of w){if(this.callbackDispatchedThisFrame.get(E).has(H.toString()))continue;this.callbackDispatchedThisFrame.get(E).add(H.toString());const Z=F.get(H.toString());Ze(Z)&&this.updateImage(H,E,Z)}}destroy(){this.imageRasterizerDispatcher&&this.imageRasterizerDispatcher.remove()}}function Ts(R){const w=R.value,E=R.valueSpec,F=R.style,H=R.styleSpec,Z=R.key,X=R.arrayElementValidator||Qn;if(!Array.isArray(w))return[new o.V(Z,w,`array expected, ${o.M(w)} found`)];if(E.length&&w.length!==E.length)return[new o.V(Z,w,`array length ${E.length} expected, length ${w.length} found`)];if(E["min-length"]&&w.lengthH)return[new o.V(w,E,`${E} is greater than the maximum value ${H}`)]}return[]}function zt(R){const w=R.key,E=R.value;if(!o.K(E))return[new o.V(w,E,`object expected, ${o.M(E)} found`)];const F=R.valueSpec,H=o.L(E.type);let Z,X,oe,xe={};const Ne=H!=="categorical"&&E.property===void 0,Le=!Ne,We=function(it){const jt=it.stops;return Array.isArray(jt)&&Array.isArray(jt[0])&&o.K(jt[0][0])}(E),He=Sn({key:R.key,value:R.value,valueSpec:R.styleSpec.function,style:R.style,styleSpec:R.styleSpec,objectElementValidators:{stops:function(it){if(H==="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(Ts({key:it.key,value:wt,valueSpec:it.valueSpec,style:it.style,styleSpec:it.styleSpec,arrayElementValidator:tt})),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 Qn({key:it.key,value:it.value,valueSpec:F,style:it.style,styleSpec:it.styleSpec})}}});return H==="identity"&&Ne&&He.push(new o.V(R.key,R.value,'missing required property "property"')),H==="identity"||E.stops||He.push(new o.V(R.key,R.value,'missing required property "stops"')),H==="exponential"&&F.expression&&!o.O(F)&&He.push(new o.V(R.key,R.value,"exponential functions not supported")),R.styleSpec.$version>=8&&(Le&&!o.Q(F)?He.push(new o.V(R.key,R.value,"property functions not supported")):Ne&&!o.S(F)&&He.push(new o.V(R.key,R.value,"zoom functions not supported"))),H!=="categorical"&&!We||E.property!==void 0||He.push(new o.V(R.key,R.value,'"property" property is required')),He;function tt(it){let jt=[];const wt=it.value,Ot=it.key;if(!Array.isArray(wt))return[new o.V(Ot,wt,`array expected, ${o.M(wt)} found`)];if(wt.length!==2)return[new o.V(Ot,wt,`array length 2 expected, length ${wt.length} found`)];if(We){if(!o.K(wt[0]))return[new o.V(Ot,wt,`object expected, ${o.M(wt[0])} found`)];const Vt=wt[0];if(Vt.zoom===void 0)return[new o.V(Ot,wt,"object stop key must have zoom")];if(Vt.value===void 0)return[new o.V(Ot,wt,"object stop key must have value")];const Ct=o.L(Vt.zoom);if(typeof Ct!="number")return[new o.V(Ot,Vt.zoom,"stop zoom values must be numbers")];if(oe&&oe>Ct)return[new o.V(Ot,Vt.zoom,"stop zoom values must appear in ascending order")];Ct!==oe&&(oe=Ct,X=void 0,xe={}),jt=jt.concat(Sn({key:`${Ot}[0]`,value:wt[0],valueSpec:{zoom:{}},style:it.style,styleSpec:it.styleSpec,objectElementValidators:{zoom:js,value:dt}}))}else jt=jt.concat(dt({key:`${Ot}[0]`,value:wt[0],style:it.style,styleSpec:it.styleSpec},wt));return o.U(o.W(wt[1]))?jt.concat([new o.V(`${Ot}[1]`,wt[1],"expressions are not allowed in function stops.")]):jt.concat(Qn({key:`${Ot}[1]`,value:wt[1],valueSpec:F,style:it.style,styleSpec:it.styleSpec}))}function dt(it,jt){const wt=o.M(it.value),Ot=o.L(it.value),Vt=it.value!==null?it.value:jt;if(Z){if(wt!==Z)return[new o.V(it.key,Vt,`${wt} stop domain type must match previous stop domain type ${Z}`)]}else Z=wt;if(wt!=="number"&&wt!=="string"&&wt!=="boolean"&&typeof Ot!="number"&&typeof Ot!="string"&&typeof Ot!="boolean")return[new o.V(it.key,Vt,"stop domain value must be a number, string, or boolean")];if(wt!=="number"&&H!=="categorical"){let Ct=`number expected, ${wt} found`;return o.Q(F)&&H===void 0&&(Ct+='\nIf you intended to use a categorical function, specify `"type": "categorical"`.'),[new o.V(it.key,Vt,Ct)]}return H!=="categorical"||wt!=="number"||typeof Ot=="number"&&isFinite(Ot)&&Math.floor(Ot)===Ot?H!=="categorical"&&wt==="number"&&typeof Ot=="number"&&typeof X=="number"&&X!==void 0&&Otnew o.V(`${R.key}${F.key}`,R.value,F.message));const E=w.value.expression||w.value._styleExpression.expression;if(R.expressionContext==="property"&&R.propertyKey==="text-font"&&!E.outputDefined())return[new o.V(R.key,R.value,`Invalid data expression for "${R.propertyKey}". Output values must be contained as literals within the expression.`)];if(R.expressionContext==="property"&&R.propertyType==="layout"&&!o.$(E))return[new o.V(R.key,R.value,'"feature-state" data expressions are not supported with layout properties.')];if(R.expressionContext==="filter")return Ds(E,R);if(R.expressionContext==="appearance")return _t(E,R);if(R.expressionContext&&R.expressionContext.indexOf("cluster")===0){if(!o.Z(E,["zoom","feature-state"]))return[new o.V(R.key,R.value,'"zoom" and "feature-state" expressions are not supported with cluster properties.')];if(R.expressionContext==="cluster-initial"&&!o._(E))return[new o.V(R.key,R.value,"Feature data expressions are not supported with initial expression part of cluster properties.")]}return[]}function Ds(R,w){const E=new Set(["zoom","feature-state","pitch","distance-from-center"]);if(w.valueSpec&&w.valueSpec.expression)for(const H of w.valueSpec.expression.parameters)E.delete(H);if(E.size===0)return[];const F=[];return R instanceof o.a0&&E.has(R.name)?[new o.V(w.key,w.value,`["${R.name}"] expression is not supported in a filter for a ${w.object.type} layer with id: ${w.object.id}`)]:(R.eachChild(H=>{F.push(...Ds(H,w))}),F)}function _t(R,w){const E=new Set;if(w.valueSpec&&w.valueSpec.expression)for(const H of w.valueSpec.expression.parameters)E.add(H);if(E.size===0)return[];const F=[];return R instanceof o.a0&&!E.has(R.name)?[new o.V(w.key,w.value,`["${R.name}"] is not an allowed parameter`)]:(R.eachChild(H=>{F.push(..._t(H,w))}),F)}function Xs(R){const w=R.key,E=R.value,F=R.valueSpec,H=[];return Array.isArray(F.values)?F.values.indexOf(o.L(E))===-1&&H.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&&H.push(new o.V(w,E,`expected one of [${Object.keys(F.values).join(", ")}], ${JSON.stringify(E)} found`)),H}function rn(R){return o.a4(o.W(R.value))?Nt(Object.assign({},R,{expressionContext:"filter",valueSpec:R.styleSpec[`filter_${R.layerType||"fill"}`]})):Ps(R)}function Ps(R){const w=R.value,E=R.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=R.styleSpec;let H=Xs({key:`${E}[0]`,value:w[0],valueSpec:F.filter_operator});const Z=()=>{w.length>=2&&(o.a2(w[1])||H.push(new o.V(`${E}[1]`,w[1],`string expected, ${o.M(w[1])} found`)));for(let X=2;X":case">=":w.length>=2&&o.L(w[1])==="$type"&&H.push(new o.V(E,w,`"$type" cannot be use with operator "${w[0]}"`)),w.length!==3&&H.push(new o.V(E,w,`filter array for operator "${w[0]}" must have 3 elements`)),Z();break;case"==":case"!=":w.length!==3&&H.push(new o.V(E,w,`filter array for operator "${w[0]}" must have 3 elements`)),Z();break;case"in":case"!in":Z();break;case"any":case"all":case"none":for(let X=1;X{Ne in E&&w.push(new o.V(F,E[Ne],`"${Ne}" is prohibited for ref layers`))}),H.layers.forEach(Ne=>{o.L(Ne.id)===oe&&(xe=Ne)}),xe?xe.ref?w.push(new o.V(F,E.ref,"ref cannot reference another ref layer")):X=o.L(xe.type):typeof oe=="string"&&w.push(new o.V(F,E.ref,`ref layer "${oe}" not found`))}else if(X!=="background"&&X!=="sky"&&X!=="slot")if(E.source)if(o.a2(E.source)){const xe=H.sources&&H.sources[E.source],Ne=xe&&o.L(xe.type);xe?Ne==="vector"&&X==="raster"?w.push(new o.V(F,E.source,`layer "${E.id}" requires a raster source`)):Ne==="raster"&&X!=="raster"?w.push(new o.V(F,E.source,`layer "${E.id}" requires a vector source`)):Ne!=="vector"||E["source-layer"]?Ne==="raster-dem"&&X!=="hillshade"?w.push(new o.V(F,E.source,"raster-dem source can only be used with layer type 'hillshade'.")):Ne!=="raster-array"||["raster","raster-particle"].includes(X)?X==="line"&&E.paint&&(E.paint["line-gradient"]||E.paint["line-trim-offset"])&&Ne==="geojson"&&!xe.lineMetrics?w.push(new o.V(F,E,`layer "${E.id}" specifies a line-gradient, which requires the GeoJSON source to have \`lineMetrics\` enabled.`)):X==="raster-particle"&&Ne!=="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(Sn({key:F,value:E,valueSpec:Z.layer,style:R.style,styleSpec:R.styleSpec,objectElementValidators:{"*":()=>[],type:()=>Qn({key:`${F}.type`,value:E.type,valueSpec:Z.layer.type,style:R.style,styleSpec:R.styleSpec,object:E,objectKey:"type"}),filter:xe=>rn(Object.assign({layerType:X},xe)),layout:xe=>Sn({layer:E,key:xe.key,value:xe.value,valueSpec:{},style:xe.style,styleSpec:xe.styleSpec,objectElementValidators:{"*":Ne=>gr(Object.assign({layerType:X},Ne))}}),paint:xe=>Sn({layer:E,key:xe.key,value:xe.value,valueSpec:{},style:xe.style,styleSpec:xe.styleSpec,objectElementValidators:{"*":Ne=>Zs(Object.assign({layerType:X,layer:E},Ne))}}),appearances(xe){const Ne=Ts({key:xe.key,value:xe.value,valueSpec:xe.valueSpec,style:xe.style,styleSpec:xe.styleSpec,arrayElementValidator:He=>function(tt){const{key:dt,layer:it,layerType:jt}=tt,wt=o.L(tt.value),Ot=o.L(wt.name),Vt=o.L(wt.condition),Ct=Sn({key:dt,value:wt,valueSpec:tt.styleSpec.appearance,style:tt.style,styleSpec:tt.styleSpec,objectElementValidators:{condition:ks=>function(ss){const Ns=[];return Ns.push(...Nt({key:ss.key,value:ss.object.condition,valueSpec:o.a8.appearance.condition,expressionContext:"appearance"})),Ns}(Object.assign({layer:it,layerType:jt},ks)),properties:ks=>function(ss){const Ns=[],{styleSpec:Gt,layer:es,layerType:fs}=ss,Ws=Gt[`paint_${fs}`],As=Gt[`layout_${fs}`],gn=ss.object[ss.objectKey];for(const an in gn){const Dn=an in Ws?"paint":an in As?"layout":void 0;if(!Dn){Ns.push(new o.V(ss.key,an,`unknown property "${an}" for layer type "${fs}"`));continue}const Gn=Object.assign({},ss,{key:`${ss.key}.${an}`,object:gn,objectKey:an,layer:es,layerType:fs,value:gn[an],valueSpec:Dn==="paint"?Ws[an]:As[an]});Ns.push(..._n(Gn,Dn))}return Ns}(Object.assign({layer:it,layerType:jt},ks))}});return Ot!=="hidden"&&Vt===void 0&&Ct.push(new o.V(tt.key,"name",'Appearance with name different than "hidden" must have a condition')),Ct}(Object.assign({layerType:X,layer:E},He))}),Le=Array.isArray(xe.value)?xe.value:[],We=new Set;return Le.forEach((He,tt)=>{const dt=o.L(He.name);if(dt)if(We.has(dt)){const it=o.L(E.id);Ne.push(new o.V(xe.key,dt,`Duplicated appearance name "${dt}" for layer "${it}"`))}else We.add(dt)}),Ne}}})),w}function In({key:R,value:w}){return o.a2(w)?[]:[new o.V(R,w,`string expected, ${o.M(w)} found`)]}const Ar={promoteId:function R({key:w,value:E}){if(o.a2(E))return In({key:w,value:E});if(Array.isArray(E)){const H=[],Z=o.W(E),X=o.X(Z);return X.result==="error"?(X.value.forEach(oe=>{H.push(new o.V(`${w}${oe.key}`,null,`${oe.message}`))}),H):(o.Z(X.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"])||H.push(new o.V(`${w}`,null,"promoteId expression should be only feature dependent")),H)}if(!o.K(E))return[new o.V(w,E,`string, expression or object expected, "${o.M(E)}" found`)];const F=[];for(const H in E)F.push(...R({key:`${w}.${H}`,value:E[H]}));return F}};function or(R){const w=R.value,E=R.key,F=R.styleSpec,H=R.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 Z=o.L(w.type);let X=[];switch(["vector","raster","raster-dem","raster-array"].includes(Z)&&("url"in w||"tiles"in w||X.push(new o.a5(E,w,'Either "url" or "tiles" is required.'))),Z){case"vector":case"raster":case"raster-dem":case"raster-array":return X=X.concat(Sn({key:E,value:w,valueSpec:F[`source_${Z.replace("-","_")}`],style:R.style,styleSpec:F,objectElementValidators:Ar})),X;case"geojson":if(X=Sn({key:E,value:w,valueSpec:F.source_geojson,style:H,styleSpec:F,objectElementValidators:Ar}),"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 oe in w.clusterProperties){const xe=w.clusterProperties[oe];if(!Array.isArray(xe))return[new o.V(`${E}.clusterProperties.${oe}`,xe,"array expected")];const[Ne,Le]=xe,We=typeof Ne=="string"?[Ne,["accumulated"],["get",oe]]:Ne;X.push(...Nt({key:`${E}.${oe}.map`,value:Le,expressionContext:"cluster-map"})),X.push(...Nt({key:`${E}.${oe}.reduce`,value:We,expressionContext:"cluster-reduce"}))}}return X;case"video":return Sn({key:E,value:w,valueSpec:F.source_video,style:H,styleSpec:F});case"image":return Sn({key:E,value:w,valueSpec:F.source_image,style:H,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 Xs({key:`${E}.type`,value:w.type,valueSpec:{values:qs(F)}})}}function qs(R){return R.source.reduce((w,E)=>{const F=R[E];return F.type.type==="enum"&&(w=w.concat(Object.keys(F.type.values||{}))),w},[])}function yr(R){const w=R.value,E=R.styleSpec,F=E.light,H=R.style;if(w===void 0)return[];if(!o.K(w))return[new o.V("light",w,`object expected, ${o.M(w)} found`)];let Z=[];for(const X in w){const oe=X.match(/^(.*)-transition$/),xe=X.match(/^(.*)-use-theme$/);Z=Z.concat(xe&&F[xe[1]]?Qn({key:X,value:w[X],valueSpec:{type:"string"},style:H,styleSpec:E}):oe&&F[oe[1]]&&F[oe[1]].transition?Qn({key:X,value:w[X],valueSpec:E.transition,style:H,styleSpec:E}):F[X]?Qn({key:X,value:w[X],valueSpec:F[X],style:H,styleSpec:E}):[new o.V(X,w[X],`unknown property "${X}"`)])}return Z}function fn(R){const w=R.value;if(!w)return[];const E=R.key;if(!o.K(w))return[new o.V(E,w,`object expected, ${o.M(w)} found`)];let F=[];const H=R.styleSpec,Z=H["light-3d"],X=R.style,oe=R.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(oe)for(let Le=0;Le[],array:Ts,boolean:function(R){const w=R.value,E=R.key;return o.a1(w)?[]:[new o.V(E,w,`boolean expected, ${o.M(w)} found`)]},number:js,color:function({key:R,value:w}){return o.a2(w)?o.a3.parseCSSColor(w)===null?[new o.V(R,w,`color expected, "${w}" found`)]:[]:[new o.V(R,w,`color expected, ${o.M(w)} found`)]},enum:Xs,filter:rn,function:zt,layer:Un,object:Sn,source:or,model:o.a9,light:yr,"light-3d":fn,terrain:Zn,fog:Xt,string:In,formatted:function(R){return In(R).length===0?[]:Nt(R)},resolvedImage:function(R){return In(R).length===0?[]:Nt(R)},projection:function(R){const w=R.value,E=R.styleSpec,F=E.projection,H=R.style;if(o.K(w)){let Z=[];for(const X in w)Z=Z.concat(Qn({key:X,value:w[X],valueSpec:F[X],style:H,styleSpec:E}));return Z}return o.a2(w)?[]:[new o.V("projection",w,`object or string expected, ${o.M(w)} found`)]},import:function(R){const w=R.key,{value:E,styleSpec:F}=R;if(!o.K(E))return[new o.V(w,E,"import must be an object")];const{data:H,...Z}=E;Object.defineProperty(Z,"__line__",{value:E.__line__,enumerable:!1});let X=Sn(Object.assign({},R,{value:Z,valueSpec:F.import}));return o.L(Z.id)===""&&X.push(new o.V(`${R.key}.id`,Z,"import id can't be an empty string")),H&&(X=X.concat(tn(H,F,{key:`${R.key}.data`}))),X},iconset:function(R){const w=R.value,E=R.key,F=R.styleSpec,H=R.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 Z=o.L(w.type);let X=[];if(X=X.concat(Sn({key:E,value:w,valueSpec:F[`iconset_${Z}`],style:H,styleSpec:F})),function(oe,xe){return!(oe!=="source"||!xe.source)}(Z,w)){const oe=H.sources&&H.sources[w.source],xe=oe&&o.L(oe.type);oe?xe!=="raster-array"&&X.push(new o.V(E,w.source,`iconset cannot be used with a source of type ${String(xe)}, it only be used with a "raster-array" source type`)):X.push(new o.V(E,w.source,`source "${w.source}" not found`))}return X}};function Qn(R,w=!1){const E=R.value,F=R.valueSpec,H=R.styleSpec;if(F.expression){if(o.a6(o.L(E)))return zt(R);if(o.U(o.W(E)))return Nt(R)}if(F.type&&rr[F.type]){const Z=rr[F.type](R);return w===!0&&Z.length>0&&Array.isArray(R.value)?Nt(R):Z}return Sn(Object.assign({},R,{valueSpec:F.type?H[F.type]:F}))}function Sn(R){const w=R.key,E=R.value,F=R.valueSpec||{},H=R.objectElementValidators||{},Z=R.style,X=R.styleSpec;if(!o.K(E))return[new o.V(w,E,`object expected, ${o.M(E)} found`)];let oe=[];for(const xe in E){const Ne=xe.split(".")[0];let Le;H[Ne]?Le=H[Ne]:F[Ne]?Le=Qn:H["*"]?Le=H["*"]:F["*"]&&(Le=Qn),Le?oe=oe.concat(Le({key:(w&&`${w}.`)+xe,value:E[xe],valueSpec:F[Ne]||F["*"],style:Z,styleSpec:X,object:E,objectKey:xe},E)):oe.push(new o.a5(w,E[xe],`unknown property "${xe}"`))}for(const xe in F){if(H[xe])continue;const Ne=F[xe];Ne.required&&Ne.default===void 0&&E[xe]===void 0&&oe.push(new o.V(w,E,`missing required property "${xe}"`))}return oe}function $n({key:R,value:w}){const E=In({key:R,value:w});if(E.length)return E;const F=w;return F.indexOf("{fontstack}")===-1&&E.push(new o.V(R,w,'"glyphs" url must include a "{fontstack}" token')),F.indexOf("{range}")===-1&&E.push(new o.V(R,w,'"glyphs" url must include a "{range}" token')),E}function tn(R,w=o.a8,E={}){return Sn({key:E.key||"",value:R,valueSpec:Object.assign(w.$root,{"*":{type:"*"}}),styleSpec:w,style:R,objectElementValidators:{glyphs:$n}})}function ln(R,w=o.a8){return Vs(tn(R,w))}const Cr=R=>Vs(or(R)),ms=R=>Vs(yr(R)),ot=R=>Vs(fn(R)),pt=R=>Vs(Zn(R)),vt=R=>Vs(Xt(R)),At=R=>Vs(function(w){const E=w.value,F=w.style,H=w.styleSpec,Z=H.snow;if(E===void 0)return[];if(!o.K(E))return[new o.V("snow",E,`object expected, ${o.M(E)} found`)];let X=[];for(const oe in E){const xe=oe.match(/^(.*)-transition$/);X=X.concat(xe&&Z[xe[1]]&&Z[xe[1]].transition?Qn({key:oe,value:E[oe],valueSpec:H.transition,style:F,styleSpec:H}):Z[oe]?Qn({key:oe,value:E[oe],valueSpec:Z[oe],style:F,styleSpec:H}):[new o.a5(oe,E[oe],`unknown property "${oe}"`)])}return X}(R)),Zt=R=>Vs(function(w){const E=w.value,F=w.style,H=w.styleSpec,Z=H.rain;if(E===void 0)return[];if(!o.K(E))return[new o.V("rain",E,`object expected, ${o.M(E)} found`)];let X=[];for(const oe in E){const xe=oe.match(/^(.*)-transition$/);X=X.concat(xe&&Z[xe[1]]&&Z[xe[1]].transition?Qn({key:oe,value:E[oe],valueSpec:H.transition,style:F,styleSpec:H}):Z[oe]?Qn({key:oe,value:E[oe],valueSpec:Z[oe],style:F,styleSpec:H}):[new o.a5(oe,E[oe],`unknown property "${oe}"`)])}return X}(R)),as=R=>Vs(Un(R)),Ls=R=>Vs(rn(R)),cs=R=>Vs(Zs(R)),qt=R=>Vs(gr(R)),Gs=R=>Vs(o.a9(R));function Vs(R){return R.slice().sort((w,E)=>w.line&&E.line?w.line-E.line:0)}function Hn(R,w){let E=!1;if(w&&w.length)for(const F of w)F instanceof o.a5?o.w(F.message):(R.fire(new o.B(new Error(F.message))),E=!0);return E}const Kr=o.a8.light;let ma;class Or extends o.E{constructor(w,E="flat"){super(),this._transitionable=new o.aa(ma||(ma=new o.ab({anchor:new o.ac(Kr.anchor),position:new o.ad(Kr.position),color:new o.ac(Kr.color),intensity:new o.ac(Kr.intensity)}))),this.setLight(w,E),this._transitioning=this._transitionable.untransitioned()}getLight(){return this._transitionable.serialize()}setLight(w,E,F={}){this._validate(ms,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)&&Hn(this,w.call(ln,Object.assign({value:E,style:{glyphs:!0,sprite:!0},styleSpec:o.a8})))}}const ta=o.a8.terrain;let da=class extends o.E{constructor(R,w,E,F,H){super(),this.scope=E,this._transitionable=new o.aa(new o.ab({source:new o.ac(ta.source),exaggeration:new o.ac(ta.exaggeration)}),E,F),this._transitionable.setTransitionOrValue(R,F),this._transitioning=this._transitionable.untransitioned(),this.drapeRenderMode=w,this.worldview=H}get(){return this._transitionable.serialize()}set(R,w){this._transitionable.setTransitionOrValue(R,w)}updateTransitions(R){this._transitioning=this._transitionable.transitioned(R,this._transitioning)}hasTransition(){return this._transitioning.hasTransition()}recalculate(R){this.properties=this._transitioning.possiblyEvaluate(R)}getExaggeration(R){return this._transitioning.possiblyEvaluate(new o.ae(R,{worldview:this.worldview})).get("exaggeration")}getAttenuationRange(){if(!this.isZoomDependent())return null;const R=this._transitionable._values.exaggeration;if(!R)return null;const w=R.value.expression;if(!w)return null;let E=-1,F=-1,H=1;for(const Z of w.zoomStops)H=w.evaluate(new o.ae(Z,{worldview:this.worldview})),H>.01?(E=Z,F=-1):F=Z;return H<.01&&E>0&&F>E?[E,F]:null}isZoomDependent(){const R=this._transitionable._values.exaggeration;return R!=null&&R.value!=null&&R.value.expression!=null&&R.value.expression instanceof o.af}};const va=.05;function hi(R,w,E,F){const H=o.aj(45,65,E),[Z,X]=el(R,F);let oe=1-Math.min(1,Math.exp((w-Z)/(X-Z)*-6));return oe*=oe*oe,oe=Math.min(1,1.00747*oe),oe*H*R.alpha}function el(R,w){const E=.5/Math.tan(.5*w);return[R.range[0]+E,R.range[1]+E]}function Oo(R,w,E,F,H){const Z=o.ah([],[w,E,F],H.mercatorFogMatrix);return hi(R,o.ai(Z),H.pitch,H._fov)}function Ei(R,w,E,F,H,Z,X){const oe=[[E,F,0],[H,F,0],[H,Z,0],[E,Z,0]];let xe=Number.MAX_VALUE,Ne=-Number.MAX_VALUE;for(const Le of oe){const We=o.ah([],Le,w),He=o.ai(We);xe=Math.min(xe,He),Ne=Math.max(Ne,He)}return[hi(R,xe,X.pitch,X._fov),hi(R,Ne,X.pitch,X._fov)]}const Wa=o.a8.fog;class wo extends o.E{constructor(w,E,F,H){super();const Z=new o.ab({range:new o.ac(Wa.range),color:new o.ac(Wa.color),"color-use-theme":new o.ac({type:"string","property-type":"data-constant",default:"default"}),"high-color":new o.ac(Wa["high-color"]),"high-color-use-theme":new o.ac({type:"string","property-type":"data-constant",default:"default"}),"space-color":new o.ac(Wa["space-color"]),"space-color-use-theme":new o.ac({type:"string","property-type":"data-constant",default:"default"}),"horizon-blend":new o.ac(Wa["horizon-blend"]),"star-intensity":new o.ac(Wa["star-intensity"]),"vertical-range":new o.ac(Wa["vertical-range"])});this._transitionable=new o.aa(Z,F,new Map(H)),this.set(w,H),this._transitioning=this._transitionable.untransitioned(),this._transform=E,this.properties=new o.ak(Z),this.scope=F}get state(){const w=this._transform,E=w.projection.name==="globe",F=o.al(w.zoom),H=this.properties.get("range"),Z=[.5,3];return{range:E?[o.am(Z[0],H[0],F),o.am(Z[1],H[1],F)]:H,horizonBlend:this.properties.get("horizon-blend"),alpha:this.properties.get("color").a}}get(){return this._transitionable.serialize()}set(w,E,F={}){if(this._validate(vt,w,F))return;const H=Object.assign({},w);for(const Z of Object.keys(Wa))H[Z]===void 0&&(H[Z]=Wa[Z].default);this._options=H,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,H,Z){const X=o.ag.fromLngLat(H),oe=Z.elevation?Z.elevation.getAtPointOrZero(X):0;return Oo(F,X.x,X.y,oe,Z)}(this.state,w,E):0}getOpacityForTile(w){if(!this._transform.projection.supportsFog)return[1,1];const E=this._transform.calculateFogTileMatrix(w.toUnwrapped());return Ei(this.state,E,0,0,o.an,o.an,this._transform)}getOpacityForBounds(w,E,F,H,Z){return this._transform.projection.supportsFog?Ei(this.state,w,E,F,H,Z,this._transform):[1,1]}getFovAdjustedRange(w){return this._transform.projection.supportsFog?el(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 H=w.points[F];let Z;if(H[2]>=0)Z=H;else{const X=w.points[F-4];Z=o.ao(X,H,X[2]/(X[2]-H[2]))}if(Oo(this.state,Z[0],Z[1],0,this._transform)>=va)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)&&Hn(this,w.call(ln,Object.assign({value:E,style:{glyphs:!0,sprite:!0},styleSpec:o.a8})))}}let Io,is,zr,Sa=class extends o.E{constructor(R,w,E,F){super();const H=Io||(Io=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(H,E,new Map(F)),this.set(R,F),this._transitioning=this._transitionable.untransitioned(),this.properties=new o.ak(H),this.scope=E}get state(){const R=this.properties.get("opacity"),w=this.properties.get("color"),E=this.properties.get("direction"),F=o.ap(E[0]),H=-Math.max(o.ap(E[1]),.01),Z=[Math.cos(F)*Math.cos(H),Math.sin(F)*Math.cos(H),Math.sin(H)],X=this.properties.get("vignette"),oe=this.properties.get("vignette-color");return oe.a=X,{density:this.properties.get("density"),intensity:this.properties.get("intensity"),color:new o.aq(w.r,w.g,w.b,w.a*R),direction:Z,centerThinning:this.properties.get("center-thinning"),flakeSize:this.properties.get("flake-size"),vignetteColor:oe}}get(){return this._transitionable.serialize()}set(R,w,E={}){if(this._validate(At,R,E))return;const F=Object.assign({},R),H=o.a8.snow;for(const Z of Object.keys(H))F[Z]===void 0&&(F[Z]=H[Z].default);this._options=F,this._transitionable.setTransitionOrValue(this._options,w)}updateConfig(R){this._transitionable.setTransitionOrValue(this._options,new Map(R))}updateTransitions(R){this._transitioning=this._transitionable.transitioned(R,this._transitioning)}hasTransition(){return this._transitioning.hasTransition()}recalculate(R){this.properties=this._transitioning.possiblyEvaluate(R)}_validate(R,w,E){return(!E||E.validate!==!1)&&Hn(this,R.call(ln,Object.assign({value:w,style:{glyphs:!0,sprite:!0},styleSpec:o.a8})))}},Kn=class extends o.E{constructor(R,w,E,F){super();const H=is||(is=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(H,E,new Map(F)),this.set(R,F),this._transitioning=this._transitionable.untransitioned(),this.properties=new o.ak(H),this.scope=E}get state(){const R=this.properties.get("opacity"),w=this.properties.get("color"),E=this.properties.get("direction"),F=o.ap(E[0]),H=-Math.max(o.ap(E[1]),.01),Z=[Math.cos(F)*Math.cos(H),Math.sin(F)*Math.cos(H),Math.sin(H)],X=this.properties.get("vignette-color");return X.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*R),direction:Z,centerThinning:this.properties.get("center-thinning"),dropletSize:this.properties.get("droplet-size"),distortionStrength:this.properties.get("distortion-strength"),vignetteColor:X}}get(){return this._transitionable.serialize()}set(R,w,E={}){if(this._validate(Zt,R,E))return;const F=Object.assign({},R),H=o.a8.rain;for(const Z of Object.keys(H))F[Z]===void 0&&(F[Z]=H[Z].default);this._options=F,this._transitionable.setTransitionOrValue(this._options,w)}updateConfig(R){this._transitionable.setTransitionOrValue(this._options,new Map(R))}updateTransitions(R){this._transitioning=this._transitionable.transitioned(R,this._transitioning)}hasTransition(){return this._transitioning.hasTransition()}recalculate(R){this.properties=this._transitioning.possiblyEvaluate(R)}_validate(R,w,E){return(!E||E.validate!==!1)&&Hn(this,R.call(ln,Object.assign({value:w,style:{glyphs:!0,sprite:!0},styleSpec:o.a8})))}};class wn extends o.E{constructor(w,E,F,H){super(),this.scope=F,this._options=w,this.properties=new o.ak(E),this._transitionable=new o.aa(E,F,new Map(H)),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 Ur=()=>zr||(zr=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 ca;const yo=()=>ca||(ca=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 vo{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,H;if(w instanceof o.P||typeof w[0]=="number"){const Z=o.P.convert(w);F=[Z],H=E.isPointAboveHorizon(Z)}else{const Z=o.P.convert(w[0]),X=o.P.convert(w[1]),oe=Z.add(X)._div(2);F=[Z,X],H=o.as(Z,X).every(xe=>E.isPointAboveHorizon(xe))&&E.isPointAboveHorizon(oe)}return new vo(F,H,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],H=o.as(E,F,0,!1);return this.cameraPoint.y>F.y&&(this.cameraPoint.x>E.x&&this.cameraPoint.x=F.x?H[2]=this.cameraPoint:this.cameraPoint.x<=E.x&&(H[3]=this.cameraPoint)),o.at(H,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],H=o.as(E,F,w),Z=this.cameraPoint.clone(),X=+(Z.x>E.x)+ +(Z.x>F.x);switch(3*(+(Z.y>E.y)+ +(Z.y>F.y))+X){case 0:H[0]=Z,H[4]=Z.clone();break;case 1:H.splice(1,0,Z);break;case 2:H[1]=Z;break;case 3:H.splice(4,0,Z);break;case 5:H.splice(2,0,Z);break;case 6:H[3]=Z;break;case 7:H.splice(3,0,Z);break;case 8:H[2]=Z}return H}containsTile(w,E,F,H=0){const Z=Math.max(w.queryPadding,w.evaluateQueryRenderedFeaturePadding())/E._pixelsPerMercatorPixel+1,X=F?this._bufferedCameraMercator(Z,E):this._bufferedScreenMercator(Z,E);let oe=w.tileID.wrap+(X.unwrapped?H:0);const xe=X.polygon.map(jt=>o.au(w.tileTransform,jt,oe));if(!o.av(xe,0,0,o.an,o.an))return;oe=w.tileID.wrap+(this.screenGeometryMercator.unwrapped?H:0);const Ne=this.screenGeometryMercator.polygon.map(jt=>o.aw(w.tileTransform,jt,oe)),Le=Ne.map(jt=>new o.P(jt[0],jt[1])),We=E.getFreeCameraOptions().position||new o.ag(0,0,0),He=o.aw(w.tileTransform,We,oe),tt=Ne.map(jt=>{const wt=o.ax(jt,jt,He);return o.ay(wt,wt),new o.az(He,wt)}),dt=o.aA(w,1,E.zoom)*E._pixelsPerMercatorPixel;return{queryGeometry:this,tilespaceGeometry:Le,tilespaceRays:tt,bufferedTilespaceGeometry:xe,bufferedTilespaceBounds:(it=o.aB(xe),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=uo(w);if(this._screenRaycastCache[F])return this._screenRaycastCache[F];{let H;return H=E.projection.name==="globe"?this._projectAndResample(this.bufferedScreenGeometry(w),E):{polygon:this.bufferedScreenGeometry(w).map(Z=>E.pointCoordinate3D(Z)),unwrapped:!0},this._screenRaycastCache[F]=H,H}}_bufferedCameraMercator(w,E){const F=uo(w);if(this._cameraRaycastCache[F])return this._cameraRaycastCache[F];{let H;return H=E.projection.name==="globe"?this._projectAndResample(this.bufferedCameraGeometryGlobe(w),E):{polygon:this.bufferedCameraGeometry(w).map(Z=>E.pointCoordinate3D(Z)),unwrapped:!0},this._cameraRaycastCache[F]=H,H}}_projectAndResample(w,E){const F=function(Z,X){const oe=o.aD([],X.pixelMatrix,X.globeMatrix),xe=[0,-o.aF,0,1],Ne=[0,o.aF,0,1],Le=[0,0,0,1];o.aE(xe,xe,oe),o.aE(Ne,Ne,oe),o.aE(Le,Le,oe);const We=new o.P(xe[0]/xe[3],xe[1]/xe[3]),He=new o.P(Ne[0]/Ne[3],Ne[1]/Ne[3]),tt=o.aG(Z,We)&&xe[3]1?Vo(Z.slice(0,jt),X):[],Vt=jtnew o.P(Xc(Ns.x),Ns.y)),Vt=Vt.map(Ns=>new o.P(Xc(Ns.x),Ns.y));const Ct=[...Ot];Ct.length===0&&Ct.push(Vt[Vt.length-1]);const ks=o.am(Ct[Ct.length-1].y,(Vt.length===0?Ot[0]:Vt[0]).y,wt);let ss;return ss=tt?[new o.P(0,ks),new o.P(0,0),new o.P(1,0),new o.P(1,ks)]:[new o.P(1,ks),new o.P(1,1),new o.P(0,1),new o.P(0,ks)],Ct.push(...ss),Vt.length===0?Ct.push(Ot[0]):Ct.push(...Vt),{polygon:Ct.map(Ns=>new o.ag(Ns.x,Ns.y)),unwrapped:!1}}(w,E);if(F)return F;const H=function(Z,X){let oe=!1,xe=-1/0,Ne=0;for(let We=0;Wexe&&(xe=Z[We].x,Ne=We);for(let We=0;We.5&&(tt.x{We.x-=1}),{polygon:Z,unwrapped:oe}}(Vo(w,E).map(Z=>new o.P(Xc(Z.x),Z.y)),E);return{polygon:H.polygon.map(Z=>new o.ag(Z.x,Z.y)),unwrapped:H.unwrapped}}}function Vo(R,w){return o.aI(R,E=>{const F=w.pointCoordinate3D(E);E.x=F.x,E.y=F.y},1/256)}function Xc(R){return R<0?1+R%1:R%1}function uo(R){return 100*R|0}function bo(R,w,E){try{w=function(H){if(!H.variants)return H;if(!Array.isArray(H.variants))throw new Error("variants must be an array");for(const Z of H.variants){if(Z==null||typeof Z!="object"||Z.constructor!==Object)throw new Error("variant must be an object");if(!Array.isArray(Z.capabilities))throw new Error("capabilities must be an array");if(Z.capabilities.length===1&&Z.capabilities[0]==="meshopt")return Object.assign(H,Z)}return H}(w)}catch(H){return new Error("Failed to process TileJSON variants",{cause:H})}const F=o.aJ(Object.assign({},w,R),["tilejson","tiles","minzoom","maxzoom","attribution","mapbox_logo","bounds","extra_bounds","scheme","tileSize","encoding","vector_layers","raster_layers","worldview_options","worldview_default","worldview"]);return R.url&&w.tiles&&R.tiles&&(F.tiles=w.tiles),F.tiles=E.canonicalizeTileset(F,R.url),F}function od(R,w,E,F,H){const Z=function(oe,xe){if(oe)return H(oe);if(xe){R.url&&xe.tiles&&R.tiles&&delete R.tiles;const Ne=bo(R,xe,w);if(Ne instanceof Error)return H(Ne);H(null,Ne)}},X=function(oe,xe,Ne){if(!oe)return null;if(!xe&&!Ne)return oe;Ne=Ne||oe.worldview_default;const Le=Object.values(oe.language||{});if(Le.length===0)return null;const We=Object.values(oe.worldview||{});if(We.length===0)return null;const He=Le.every(dt=>dt===xe),tt=We.every(dt=>dt===Ne);return He&&tt?oe:xe in(oe.language_options||{})||Ne in(oe.worldview_options||{})?null:oe.language_options&&oe.worldview_options?oe:null}(R.data,E,F);return X?o.o.frame(()=>Z(null,X)):R.url?o.m(w.transformRequest(w.normalizeSourceURL(R.url,null,E,F),o.R.Source),Z):o.o.frame(()=>{const{data:oe,...xe}=R;Z(null,xe)})}function Ju(R,w){const E=Math.pow(2,w.z),F=Math.floor(o.aH(R.getWest())*E),H=Math.floor(o.aL(R.getNorth())*E),Z=Math.ceil(o.aH(R.getEast())*E),X=Math.ceil(o.aL(R.getSouth())*E);return w.x>=F&&w.x=H&&w.ythis.maxzoom||w.z{this._tileJSONRequest=null,this._loaded=!0,X?(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(X))):oe&&(this._setTileJSON(oe),ve(oe.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(X)};this.provider=this._options.provider;const Z=function(X){if("provider"in X&&!X.provider)return null;let oe=X.provider;if(!oe&&"url"in X&&X.url&&(oe=o.aM(X.url)),!oe)return null;const xe=o.g.TILE_PROVIDER_URLS[oe];if(!xe)return null;let Ne;try{Ne=new URL(xe,o.g.API_URL).href}catch{return o.w(`TileProvider "${oe}" has an invalid URL: "${xe}"`),null}return{name:oe,url:Ne}}(this._options);if(this.provider&&!Z)return this._loaded=!0,this.fire(new o.B(new Error(`TileProvider "${this.provider}" is not registered`))),void(w&&w());this._tileJSONRequest=Z?this._loadWithProvider(Z,H):od(this._options,this.map._requestManager,E,F,H)}_loadWithProvider(w,E){this.provider=w.name;const F=new AbortController,H=this._options.url&&!this._options.tiles?this.map._requestManager.transformRequest(this._options.url,o.R.Source):void 0,Z=H?Object.assign({},this._options,{url:H.url}):this._options;return this.dispatcher.broadcast("loadTileProvider",{name:w.name,url:w.url,source:this.id,scope:this.scope,type:this.type,options:Z,request:H},(X,oe)=>{if(F.signal.aborted)return;if(X)return void E(X);const xe=oe?oe.find(Ne=>Ne!=null):null;if(xe){const Ne=bo(this._options,xe,this.map._requestManager);Ne instanceof Error?E(Ne):E(null,Ne)}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=Ld.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),H=this.map._requestManager.normalizeTileURL(F),Z=this.map._requestManager.transformRequest(H,o.R.Tile),X=this.map.style?this.map.style.getLut(this.scope):null,oe=X?{image:X.image.clone()}:null,xe={request:Z,data:void 0,uid:w.uid,tileID:w.tileID,tileZoom:w.tileZoom,zoom:w.tileID.overscaledZ,maxZoom:this.maxzoom,lut:oe,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)&&(xe.localizableLayerIds=this.localizableLayerIds),xe.request.collectResourceTiming=this._collectResourceTiming,w.actor&&w.state!=="expired")w.state==="loading"?w.reloadCallback=E:w.request=w.actor.send("reloadTile",xe,Ne.bind(this));else if(w.actor=this._tileWorkers[H]=this._tileWorkers[H]||this.dispatcher.getActor(),this.dispatcher.ready||this.provider)w.request=w.actor.send("loadTile",xe,Ne.bind(this),void 0,!0);else{const Le=o.aO.call({deduped:this._deduped},xe,(We,He)=>{if(We||!He)Ne.call(this,We);else{const tt=o.aP(He.responseHeaders);xe.data={rawData:He.rawData.slice(0),expires:tt.expires,cacheControl:tt.cacheControl},w.actor&&w.actor.send("loadTile",xe,Ne.bind(this),void 0,!0)}},!0);w.request={cancel:Le}}function Ne(Le,We){return delete w.request,w.aborted?E(null):Le?E(Le):(We&&We.resourceTiming&&(w.resourceTiming=We.resourceTiming),this.map._refreshExpiredTiles&&We&&w.setExpiryData(We),w.loadVectorData(We,this.map.painter),o.aQ(this.dispatcher),E(null,We),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 hx extends o.E{constructor(w,E,F,H){super(),this.id=w,this.dispatcher=F,this.setEventedParent(H),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=od(this._options,this.map._requestManager,null,E,(F,H)=>{this._tileJSONRequest=null,this._loaded=!0,F?this.fire(new o.B(F)):H&&(Object.assign(this,H),H.raster_layers&&(this.rasterLayers=H.raster_layers,this.rasterLayerIds=this.rasterLayers.map(Z=>Z.id)),this.tileBounds=Ld.fromTileJSON(H),ve(H.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,H=this.map._requestManager.normalizeTileURL(w.tileID.canonical.url(this.tiles,this.scheme),F,this.tileSize);w.request=o.n(this.map._requestManager.transformRequest(H,o.R.Tile),(Z,X,oe)=>{if(delete w.request,w.aborted)return w.state="unloaded",E(null);if(Z)return w.state="errored",E(Z);if(!X)return E(null);const xe=o.aP(oe);this.map._refreshExpiredTiles&&w.setExpiryData(xe),w.setTexture(X,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 Ay([R,w],E,F,{scaled:H=!0}={}){const{tileSize:Z,buffer:X}=F,{x:oe,y:xe,z:Ne}=E;if(!isFinite(oe)||!isFinite(xe)||!isFinite(Ne))throw new Error("Invalid MRT header");const Le=2**Ne,We=Le*o.aH(R),He=Le*o.aL(w);return function([tt,dt],it,{scaled:jt=!0}={}){if(!it)throw new Error("bandView is undefined");const{data:wt,tileSize:Ot,buffer:Vt,offset:Ct,scale:ks,dimension:ss}=it;if(tt<-Vt||tt>Ot+Vt||dt<-Vt||dt>Ot+Vt)throw new Error(`Point (${tt}, ${dt}) out of bounds for tileSize=${Ot}, buffer=${Vt}`);const Ns=(dt+Vt)*(Ot+2*Vt)+(tt+Vt);if(new Uint32Array(wt.buffer)[Ns]===4294967295)return null;let Gt=[];Gt=jt?[]:new it.data.constructor(ss);for(let es=0;es{if(delete w.request,w.aborted)return w.state="unloaded",E(null);if(oe)return oe.name==="AbortError"?void 0:(w.state="errored",E(oe));if(this.map._refreshExpiredTiles&&xe){const Le=o.aP(Ne);w.setExpiryData(Le)}if(this.partial&&w.state!=="expired")w.state="empty";else if(!this.partial){if(!xe)return E(null);w.state="loaded",w._isHeaderLoaded=!0,w._mrt=xe}E(null)};w.request=this.partial?w.fetchHeader(void 0,X.bind(this)):w.actor.send("loadTile",Z,X.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 H of F.values())this.map.painter.saveTileTexture(H)}else w.destroy()}prepareTile(w,E,F,H){w._isHeaderLoaded&&(w.state!=="empty"&&(w.state="reloading"),w.fetchBandForRender(E,F,H,(Z,X)=>{Z?(w.state="errored",this.fire(new o.B(Z))):X&&(w._isHeaderLoaded=!0,w.setTexturePerLayer(F,X,this.map.painter),w.state="loaded"),this.triggerRepaint(w)}))}getInitialBand(w){if(!this.rasterLayers)return 0;const E=this.rasterLayers.find(({id:Z})=>Z===w),F=E&&E.fields,H=F&&F.bands&&F.bands;return H?H[0]:0}getTextureDescriptor(w,E,F){if(!w)return;const H=E.sourceLayer||this.rasterLayerIds&&this.rasterLayerIds[0];if(!H)return;let Z=null;E instanceof o.aS?Z=E.paint.get("raster-array-band"):E instanceof o.aT&&(Z=E.paint.get("raster-particle-array-band"));const X=Z||this.getInitialBand(H);if(X==null)return;if(!w.textureDescriptorPerLayer.get(E.id))return void this.prepareTile(w,H,E.id,X);if(w.updateNeeded(E.id,X)&&!F)return;const oe=w.textureDescriptorPerLayer.get(E.id);return Object.assign({},oe,{texture:w.texturePerLayer.get(E.id)})}getImages(w,E){const F=new Map;for(const H of w)for(const Z of E){const[X,oe]=Z.split("/"),xe=H.getLayer(X);if(!xe||!xe.hasBand(oe)||!xe.hasDataForBand(oe))continue;const{bytes:Ne,tileSize:Le,buffer:We}=xe.getBandView(oe),He=Le+2*We,tt={data:new o.q({width:He,height:He},Ne),pixelRatio:2,sdf:!1,usvg:!1,version:0};F.set(Z,tt)}return F}queryRasterArrayValueByBandId(w,E,F){const H=E._mrt;return new Promise(Z=>{const X={},oe=new Set;for(const[xe,Ne]of Object.entries(H.layers)){if(F.layerName&&xe!==F.layerName)continue;const Le={};X[xe]=Le;for(const{bands:We}of Ne.dataIndex)for(const He of We)F.bands&&!F.bands.includes(He)||(oe.add(o.F(xe,He)),E.fetchBand(xe,null,He,tt=>{o.o.frame(()=>{Le[He]=tt?null:Ay([w.lng,w.lat],H,Ne.getBandView(He)),oe.delete(o.F(xe,He)),oe.size===0&&Z(X)})},!1))}oe.size===0&&Z(X)})}_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),H=this.map._requestManager.transformRequest(F,o.R.Tile);w.actor.send("loadTile",{request:H,uid:w.uid,tileID:w.tileID,type:this.type,source:this.id,scope:this.scope,partial:!1},(Z,X,oe)=>{if(Z)return this._loadTilePending[w.uid].forEach(xe=>xe(Z,null)),void delete this._loadTilePending[w.uid];if(!X)return this._loadTilePending[w.uid].forEach(xe=>xe(null,null)),void delete this._loadTilePending[w.uid];if(this.map._refreshExpiredTiles&&X){const xe=o.aP(oe);w.setExpiryData(xe)}w._mrt=X,w._isHeaderLoaded=!0,w.state="loaded",this._loadTilePending[w.uid].forEach(xe=>xe(null,X)),this._loadTileLoaded[w.uid]=!0,delete this._loadTilePending[w.uid]},void 0,!0)}queryRasterArrayValueByAllBands(w,E,F){return new Promise((H,Z)=>{this._loadTileForQuery(E,(X,oe)=>{X?Z(X):H(oe?this.queryRasterArrayValueByBandId(w,E,F):null)})})}queryRasterArrayValue(w,E){const F=o.aU.convert(w),H=this.findLoadedParent(F);return H&&H._mrt?E.bands||!this.partial?this.queryRasterArrayValueByBandId(F,H,E):this.queryRasterArrayValueByAllBands(F,H,E):Promise.resolve(null)}findLoadedParent(w){const E=o.ag.fromLngLat(w,this.map.transform.tileSize),F=this.maxzoom+1,H=1<0&&(oe[new o.aR(R.overscaledZ,H,w.z,F,w.y-1).key]={backfilled:!1},oe[new o.aR(R.overscaledZ,R.wrap,w.z,w.x,w.y-1).key]={backfilled:!1},oe[new o.aR(R.overscaledZ,X,w.z,Z,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 Z={dataType:"source",sourceDataType:this._metadataFired?"content":"metadata"};this._collectResourceTiming&&H&&H.resourceTiming&&H.resourceTiming[this.id]&&(Z.resourceTiming=H.resourceTiming[this.id]),R&&(this._partialReload=!0),this.fire(new o.C("data",Z)),this._partialReload=!1,this._metadataFired=!0}this._coalesce&&(this._updateWorkerData(R),this._coalesce=!1)})}loaded(){return this._loaded}reload(){const R=o.F(this.id,this.scope);this.map.style.clearSource(R),this._updateWorkerData()}loadTile(R,w){const E=R.actor?"reloadTile":"loadTile";R.actor=this.actor;const F=this.map.style?this.map.style.getLut(this.scope):null,H=F?{image:F.image.clone()}:null,Z=this._partialReload,X={type:this.type,uid:R.uid,tileID:R.tileID,tileZoom:R.tileZoom,zoom:R.tileID.overscaledZ,maxZoom:this.maxzoom,tileSize:this.tileSize,source:this.id,lut:H,scope:this.scope,pixelRatio:o.o.devicePixelRatio,showCollisionBoxes:this.map.showCollisionBoxes,promoteId:this.promoteId,brightness:this.map.style&&this.map.style.getBrightness()||0,extraShadowCaster:R.isExtraShadowCaster,scaleFactor:this.map.getScaleFactor(),partial:Z,worldview:this.map.getWorldview(),indoor:this.map.getIndoorTileOptions(this.id,this.scope)};R.request=this.actor.send(E,X,(oe,xe)=>Z&&!xe?(R.state="loaded",w(null)):(delete R.request,R.destroy(!1),R.aborted?w(null):oe?w(oe):(R.loadVectorData(xe,this.map.painter,E==="reloadTile"),w(null))),void 0,E==="loadTile")}abortTile(R){R.request&&(R.request.cancel(),delete R.request),R.aborted=!0}unloadTile(R,w){this.actor.send("removeTile",{uid:R.uid,type:this.type,source:this.id,scope:this.scope}),R.destroy()}onRemove(R){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(R,w,E,F){super(R,w,E,F),this.roundZoom=!0,this.type="video",this.options=w}load(){this._loaded=!1;const R=this.options;this.urls=[];for(const w of R.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(R){if(this.video){const w=this.video.seekable;Rw.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=R}}getVideo(){return this.video}onAdd(R){this.map||(this.map=R,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 R=this.map.painter.context,w=R.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(R,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(R)}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(R,w,E,F){super(),this.type="batched-model",this.id=R,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(R){this.map=R,this.load()}reload(){this.cancelTileJSONRequest();const R=o.F(this.id,this.scope);this.load(()=>this.map.style.clearSource(R))}cancelTileJSONRequest(){this._tileJSONRequest&&(this._tileJSONRequest.cancel(),this._tileJSONRequest=null)}load(R){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=od(this._options,this.map._requestManager,w,E,(F,H)=>{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))):H&&(Object.assign(this,H),H.bounds&&(this.tileBounds=new Ld(H.bounds,this.minzoom,this.maxzoom)),ve(H.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"}))),R&&R(F)})}hasTransition(){return!1}hasTile(R){return!this.tileBounds||this.tileBounds.contains(R.canonical)}loaded(){return this._loaded}loadTile(R,w){const E=this.map._requestManager.normalizeTileURL(R.tileID.canonical.url(this.tiles,this.scheme)),F={request:this.map._requestManager.transformRequest(E,o.R.Tile),data:void 0,uid:R.uid,tileID:R.tileID,tileZoom:R.tileZoom,zoom:R.tileID.overscaledZ,tileSize:this.tileSize*R.tileID.overscaleFactor(),type:this.type,source:this.id,scope:this.scope,showCollisionBoxes:this.map.showCollisionBoxes,renderSourceType:R.renderSourceType,brightness:this.map.style&&this.map.style.getBrightness()||0,pixelRatio:o.o.devicePixelRatio,promoteId:this.promoteId};if(R.actor&&R.state!=="expired")if(R.state==="loading")R.reloadCallback=w;else{if(R.buckets){const Z=Object.values(R.buckets);for(const X of Z)X.dirty=!0;return void(R.state="loaded")}R.request=R.actor.send("reloadTile",F,H.bind(this))}else R.actor=this.dispatcher.getActor(),R.request=R.actor.send("loadTile",F,H.bind(this),void 0,!0);function H(Z,X){return R.aborted?w(null):Z&&Z.status!==404?w(Z):(this.map._refreshExpiredTiles&&X&&R.setExpiryData(X),R.loadModelData(X,this.map.painter),R.state="loaded",void w(null))}}serialize(){return Object.assign({},this._options)}},canvas:class extends o.aV{constructor(R,w,E,F){super(R,w,E,F),w.coordinates?Array.isArray(w.coordinates)&&w.coordinates.length===4&&!w.coordinates.some(H=>!Array.isArray(H)||H.length!==2||H.some(Z=>typeof Z!="number"))||this.fire(new o.B(new o.V(`sources.${R}`,null,'"coordinates" property must be an array of 4 longitude/latitude array pairs'))):this.fire(new o.B(new o.V(`sources.${R}`,null,'missing required property "coordinates"'))),w.animate&&typeof w.animate!="boolean"&&this.fire(new o.B(new o.V(`sources.${R}`,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.${R}`,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.${R}`,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(R){this.map=R,this.load(),this.canvas&&this.animate&&this.play()}onRemove(R){this.pause()}prepare(){let R=!1;if(this.canvas.width!==this.width&&(this.width=this.canvas.width,R=!0),this.canvas.height!==this.height&&(this.height=this.canvas.height,R=!0),this._hasInvalidDimensions()||Object.keys(this.tiles).length===0)return;const w=this.map.painter.context;this.texture?!R&&!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 R of[this.canvas.width,this.canvas.height])if(isNaN(R)||R<=0)return!0;return!1}},custom:class extends o.E{constructor(R,w,E,F){super(),this.id=R,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 Ld(this._implementation.bounds,this.minzoom,this.maxzoom));const H=w;H.update=this._update.bind(this),H.clearTiles=this._clearTiles.bind(this),H.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(R){this.map=R,this._loaded=!1,this.fire(new o.C("dataloading",{dataType:"source"})),this._implementation.onAdd&&this._implementation.onAdd(R),this.load()}onRemove(R){this._implementation.onRemove&&this._implementation.onRemove(R)}hasTile(R){if(this._implementation.hasTile){const{x:w,y:E,z:F}=R.canonical;return this._implementation.hasTile({x:w,y:E,z:F})}return!this.tileBounds||this.tileBounds.contains(R.canonical)}loadTile(R,w){const{x:E,y:F,z:H}=R.tileID.canonical,Z=new AbortController,X=Promise.resolve(this._implementation.loadTile({x:E,y:F,z:H},{signal:Z.signal})).then((function(oe){return delete R.request,R.aborted?(R.state="unloaded",w(null)):oe===void 0?(R.state="errored",w(null)):oe===null?(this.loadTileData(R,{width:this.tileSize,height:this.tileSize,data:null}),R.state="loaded",w(null)):function(xe){return xe instanceof ImageData||xe instanceof HTMLCanvasElement||xe instanceof ImageBitmap||xe instanceof HTMLImageElement}(oe)?(this.loadTileData(R,oe),R.state="loaded",void w(null)):(R.state="errored",w(new Error(`Can't infer data type for ${this.id}, only raster data supported at the moment`)))}).bind(this)).catch(oe=>{oe.name!=="AbortError"&&(R.state="errored",w(oe))});X.cancel=()=>Z.abort(),R.request=X}loadTileData(R,w){R.setTexture(w,this.map.painter)}unloadTile(R,w){if(R.texture&&R.texture instanceof o.T?(R.destroy(!1),R.texture&&R.texture instanceof o.T&&this.map.painter.saveTileTexture(R.texture)):R.destroy(),this._implementation.unloadTile){const{x:E,y:F,z:H}=R.tileID.canonical;this._implementation.unloadTile({x:E,y:F,z:H})}w&&w()}abortTile(R,w){R.request&&R.request.cancel&&(R.request.cancel(),delete R.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(R=>({x:R.canonical.x,y:R.canonical.y,z:R.canonical.z}))}_clearTiles(){const R=o.F(this.id,this.scope);this.map.style.clearSource(R)}_update(){this.fire(new o.C("data",{dataType:"source",sourceDataType:"content"}))}}},Em=function(R,w,E,F){const H=new Dg[w.type](R,w,E,F);if(H.id!==R)throw new Error(`Expected Source id to be ${R} instead of ${H.id}`);return o.aZ(["load","abort","unload","serialize","prepare"],H),H};function Lf(R,w,E=""){return`${E}:${w.id||""}:${w.layer.id}:${function(F){if("layerId"in F)return`layer:${F.layerId}`;{const{featuresetId:H,importId:Z}=F;return`featureset:${H}${Z?`:import:${Z}`:""}`}}(R.target)}`}function eh(R,w,E,F=""){if(R.uniqueFeatureID){const H=Lf(R,w,F);if(E.has(H))return!0;E.add(H)}return!1}function L0(R,w,E,F,H=!1,Z=void 0){const X=w.sourceCache.transform,oe=w.sourceCache.tilesIn(R,w.has3DLayers,H);oe.sort(Ey);const xe=[];for(const Ne of oe){const Le=Ne.tile.queryRenderedFeatures(w,Ne,E,F,X,H,Z);Object.keys(Le).length&&xe.push({wrappedTileID:Ne.tile.tileID.wrapped().key,queryResults:Le})}for(const Ne in w.layers){const Le=w.layers[Ne];if(Le.styleLayer){const We=Le.styleLayer.queryRenderedFeatures(R,w.sourceCache,F);Object.keys(We).length&&xe.push({wrappedTileID:0,queryResults:We})}}return xe.length===0?{}:function(Ne){const Le={},We={};for(const He of Ne){const tt=He.queryResults,dt=He.wrappedTileID,it=We[dt]=We[dt]||{};for(const jt in tt){const wt=tt[jt],Ot=it[jt]=it[jt]||{},Vt=Le[jt]=Le[jt]||[];for(const Ct of wt)Ot[Ct.featureIndex]||(Ot[Ct.featureIndex]=!0,Vt.push(Ct))}}return Le}(xe)}function jo(R,w,E,F,H,Z){const X={},oe=F.queryRenderedSymbols(R),xe=[];for(const Ne of Object.keys(oe).map(Number))xe.push(H[Ne]);xe.sort(Ey);for(const Ne of xe){const Le=Ne.featureIndex.lookupSymbolFeatures(oe[Ne.bucketInstanceId],Ne.bucketIndex,Ne.sourceLayerIndex,w,E,Z);for(const We in Le){const He=X[We]=X[We]||[],tt=Le[We];tt.sort((dt,it)=>{const jt=Ne.featureSortOrder;if(jt){const wt=jt.indexOf(dt.featureIndex);return jt.indexOf(it.featureIndex)-wt}return it.featureIndex-dt.featureIndex});for(const dt of tt)He.push(dt)}}return X}function Zi(R,w){const E=R.getRenderableIds().map(Z=>R.getTileByID(Z)),F=[],H={};for(let Z=0;Z{if(Z)E(Z);else try{const xe=F.getHeaderLength(X);if(xe>w)return void(this.request=this.fetchHeader(xe,E));F.parseHeader(X),this._isHeaderLoaded=!0;let Ne=0;for(const Le of Object.values(F.layers))Ne=Math.max(Ne,Le.dataIndex[Le.dataIndex.length-1].lastByte);X.byteLength>=Ne&&(this.entireBuffer=X),E(null,this.entireBuffer||X,oe)}catch(xe){E(xe)}}),this.request}fetchBandForRender(w,E,F,H){this.fetchBand(w,E,F,Z=>{if(Z)return void H(Z);this.updateTextureDescriptor(w,E,F);const X=this.textureDescriptorPerLayer.get(E);H(null,X?X.img:null)})}fetchBand(w,E,F,H,Z=!0){const X=this._mrt;if(!this._isHeaderLoaded||!X)return void H(new Error("Tile header is not ready"));const oe=this.actor;if(!oe)return void H(new Error("Can't fetch tile band without an actor"));let xe;const Ne=o.F(String(F),o.F(this.tileID.key,w));let Le=this._taskQueue.get(Ne);Le?Le.add(H):(Le=new Set,Le.add(H),this._taskQueue.set(Ne,Le));const We=(it,jt)=>{xe.complete(it,jt),it?H(it):(Le.forEach(wt=>wt(null,jt)),this._taskQueue.delete(Ne))},He=(it,jt)=>{if(it)return H(it);const wt=oe.send("decodeRasterArray",{type:"raster-array",source:this.source,scope:this.scope,tileID:this.tileID,uid:this.uid,buffer:jt,task:xe},We,void 0,!0);if(E!==null){const Ot=this._workQueuePerLayer.get(E)||[];Ot.push(()=>{wt&&wt.cancel(),xe.cancel()}),this._workQueuePerLayer.has(E)||this._workQueuePerLayer.set(E,Ot)}};let tt;try{tt=X.getLayer(w)}catch(it){if(this.state==="reloading")return;throw it}if(!tt)return void H(new Error(`Unknown sourceLayer "${w}"`));if(tt.hasDataForBand(F))return Le.forEach(it=>it(null,null)),void this._taskQueue.delete(Ne);const dt=tt.getDataRange([F]);if(xe=X.createDecodingTask(dt),!xe||xe.tasks.length)if(E!==null&&this.flushQueues(E),this.entireBuffer)He(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,He);if(E!==null){const wt=this._fetchQueuePerLayer.get(E)||[];wt.push(()=>{jt.cancel(),xe.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 H=this._mrt.getLayer(w);if(!H||!H.hasBand(F)||!H.hasDataForBand(F))return;const{bytes:Z,tileSize:X,buffer:oe,offset:xe,scale:Ne}=H.getBandView(F),Le=X+2*oe,We=new o.q({width:Le,height:Le},Z),He=this.texturePerLayer.get(E);He&&He instanceof o.T&&He.update(We,{premultiply:!1}),this.textureDescriptorPerLayer.set(E,{layer:w,band:F,img:We,buffer:oe,offset:xe,tileSize:X,format:H.pixelFormat,mix:[Ne,256*Ne,65536*Ne,16777216*Ne]})}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 If{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 H=w.wrapped().key;this.data[H]===void 0&&(this.data[H]=[]);const Z={value:E,timeout:void 0};if(F!==void 0&&(Z.timeout=setTimeout(()=>{this.remove(w,Z)},F)),this.data[H].push(Z),this.order.push(H),this.order.length>this.max){const X=this._getAndRemoveByKey(this.order[0]);X&&this.onRemove(X)}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,H=E===void 0?0:this.data[F].indexOf(E),Z=this.data[F][H];return this.data[F].splice(H,1),Z.timeout&&clearTimeout(Z.timeout),this.data[F].length===0&&delete this.data[F],this.onRemove(Z.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 H of this.data[F])w(H.value)||E.push(H);for(const F of E)this.remove(F.value.tileID,F)}}class Rg{constructor(){this.state={},this.stateChanges={},this.deletedStates={}}updateState(w,E,F){const H=String(E);if(this.stateChanges[w]=this.stateChanges[w]||{},this.stateChanges[w][H]=this.stateChanges[w][H]||{},Object.assign(this.stateChanges[w][H],F),this.deletedStates[w]===null){this.deletedStates[w]={};for(const Z in this.state[w])Z!==H&&(this.deletedStates[w][Z]=null)}else if(this.deletedStates[w]&&this.deletedStates[w][H]===null){this.deletedStates[w][H]={};for(const Z in this.state[w][H])F[Z]||(this.deletedStates[w][H][Z]=null)}else for(const Z in F)this.deletedStates[w]&&this.deletedStates[w][H]&&this.deletedStates[w][H][Z]===null&&delete this.deletedStates[w][H][Z]}removeFeatureState(w,E,F){if(this.deletedStates[w]===null)return;const H=String(E);if(this.deletedStates[w]=this.deletedStates[w]||{},F&&E!==void 0)this.deletedStates[w][H]!==null&&(this.deletedStates[w][H]=this.deletedStates[w][H]||{},this.deletedStates[w][H][F]=null);else if(E!==void 0)if(this.stateChanges[w]&&this.stateChanges[w][H])for(F in this.deletedStates[w][H]={},this.stateChanges[w][H])this.deletedStates[w][H][F]=null;else this.deletedStates[w][H]=null;else this.deletedStates[w]=null}getState(w,E){const F=this.state[w]||{},H=this.stateChanges[w]||{},Z=this.deletedStates[w];if(Z===null)return{};if(E!==void 0){const oe=String(E),xe=Object.assign({},F[oe],H[oe]);if(Z){const Ne=Z[E];if(Ne===null)return{};for(const Le in Ne)delete xe[Le]}return xe}const X=Object.assign({},F,H);if(Z)for(const oe in Z)delete X[oe];return X}initializeTileState(w,E){w.refreshFeatureState(E)}coalesceChanges(w,E){const F={};for(const H in this.stateChanges){this.state[H]=this.state[H]||{};const Z={};for(const X in this.stateChanges[H])this.state[H][X]||(this.state[H][X]={}),Object.assign(this.state[H][X],this.stateChanges[H][X]),Z[X]=this.state[H][X];F[H]=Z}for(const H in this.deletedStates){this.state[H]=this.state[H]||{};const Z={};if(this.deletedStates[H]===null)for(const X in this.state[H])Z[X]={},this.state[H][X]={};else for(const X in this.deletedStates[H]){if(this.deletedStates[H][X]===null)this.state[H][X]={};else if(this.state[H][X])for(const oe of Object.keys(this.deletedStates[H][X]))delete this.state[H][X][oe];Z[X]=this.state[H][X]}F[H]=F[H]||{},Object.assign(F[H],Z)}if(this.stateChanges={},this.deletedStates={},Object.keys(F).length!==0)for(const H in w)w[H].refreshFeatureState(E,F)}}class ql extends o.E{constructor(w,E,F){super(),this.id=w,this._renderSourceType=F,this._maxzoomOverride=null,E.on("data",H=>{H.dataType==="source"&&H.sourceDataType==="metadata"&&(this._sourceLoaded=!0),this._sourceLoaded&&!this._paused&&H.dataType==="source"&&H.sourceDataType==="content"&&(this.reload(),this.transform&&this.update(this.transform))}),E.on("error",()=>{this._sourceErrored=!0}),this._source=E,this._tiles={},this._cache=new If(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 Rg,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(Df).map(w=>w.key)}getRenderableIds(w,E){const F=[];for(const H in this._tiles)this._isIdRenderable(+H,w,E)&&F.push(this._tiles[H]);return w?F.sort((H,Z)=>{const X=H.tileID,oe=Z.tileID,xe=new o.P(X.canonical.x,X.canonical.y)._rotate(this.transform.angle),Ne=new o.P(oe.canonical.x,oe.canonical.y)._rotate(this.transform.angle);return X.overscaledZ-oe.overscaledZ||Ne.y-xe.y||Ne.x-xe.x}).map(H=>H.tileID.key):F.map(H=>H.tileID).sort(Df).map(H=>H.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,H,Z){if(H){if(w.state="errored",o.b2(H)){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 oe=this.map.painter.terrain;this.update(this.transform,oe.getScaledDemTileSize(),!0),oe.resetTileLookupCache(this.id)}else this.update(this.transform)}else this._source.fire(new o.B(H,{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 X=new Map;Z&&Z.responseHeaders&&(X=Z.responseHeaders),this._source.fire(new o.C("data",{dataType:"source",tile:w,coord:w.tileID,sourceCacheId:this.id,responseHeaders:X}))}_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 H=0;H1||(Math.abs(X)>1&&(Math.abs(X+xe)===1?X+=xe:Math.abs(X-xe)===1&&(X-=xe)),Z.dem&&H.dem&&(H.dem.backfillBorder(Z.dem,X,oe),H.neighboringTiles&&H.neighboringTiles[Ne]&&(H.neighboringTiles[Ne].backfilled=!0)))}}getTile(w){return this.getTileByID(w.key)}getTileByID(w){return this._tiles[w]}_retainLoadedChildren(w,E,F,H){for(const Z in this._tiles){let X=this._tiles[Z];if(H[Z]||!X.hasData()||X.tileID.overscaledZ<=E||X.tileID.overscaledZ>F)continue;let oe=X.tileID;for(;X&&X.tileID.overscaledZ>E+1;){const Ne=X.tileID.scaledTo(X.tileID.overscaledZ-1);X=this._tiles[Ne.key],X&&X.hasData()&&(oe=Ne)}let xe=oe;for(;xe.overscaledZ>E;)if(xe=xe.scaledTo(xe.overscaledZ-1),w[xe.key]){H[oe.key]=oe;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 H=w.scaledTo(F),Z=this._getLoadedTile(H);if(Z)return Z}}_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,H=Math.ceil(w.height/E)+1,Z=Math.floor(F*H*5),X=typeof this._minTileCacheSize=="number"?Math.max(this._minTileCacheSize,Z):Z,oe=typeof this._maxTileCacheSize=="number"?Math.min(this._maxTileCacheSize,X):X;this._cache.setMaxSize(oe)}handleWrapJump(w){const E=Math.round((w-(this._prevLng===void 0?w:this._prevLng))/360);if(this._prevLng=w,E){const F={};for(const H in this._tiles){const Z=this._tiles[H];Z.tileID=Z.tileID.unwrapTo(Z.tileID.wrap+E),F[Z.tileID.key]=Z}this._tiles=F;for(const H in this._timers)clearTimeout(this._timers[H]),delete this._timers[H];for(const H in this._tiles)this._setTileReloadTimer(+H,this._tiles[H])}}update(w,E,F,H,Z){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 X=this._source.type==="batched-model";let oe,xe=this._source.maxzoom;this._maxzoomOverride!==null&&(xe=Math.min(xe,this._maxzoomOverride));const Ne=this.map&&this.map.painter?this.map.painter._terrain:null;if(Ne&&Ne.sourceCache===this&&Ne.attenuationRange()){const tt=Ne.attenuationRange()[0],dt=Math.floor(tt)-Math.log2(Ne.getDemUpscale());xe>dt&&(xe=dt)}const Le=this._maxzoomOverride===null&&this._source.reparseOverscaled;if(this.used||this.usedForTerrain){if(this._source.tileID)oe=w.getVisibleUnwrappedCoordinates(this._source.tileID).map(tt=>new o.aR(tt.canonical.z,tt.wrap,tt.canonical.z,tt.canonical.x,tt.canonical.y));else if(this.tileCoverLift!==0){const tt=w.clone();tt.tileCoverLift=this.tileCoverLift,oe=tt.coveringTiles({tileSize:E||this._source.tileSize,minzoom:this._source.minzoom,maxzoom:xe,roundZoom:this._source.roundZoom&&!F,reparseOverscaled:Le,isTerrainDEM:this.usedForTerrain,calculateQuadrantVisibility:X}),this._source.minzoom<=1&&w.projection.name==="globe"&&(oe.push(new o.aR(1,0,1,0,0)),oe.push(new o.aR(1,0,1,1,0)),oe.push(new o.aR(1,0,1,0,1)),oe.push(new o.aR(1,0,1,1,1)))}else if(oe=w.coveringTiles({tileSize:E||this._source.tileSize,minzoom:this._source.minzoom,maxzoom:xe,roundZoom:this._source.roundZoom&&!F,reparseOverscaled:Le,isTerrainDEM:this.usedForTerrain,calculateQuadrantVisibility:X}),this._source.hasTile){const tt=this._source.hasTile.bind(this._source);oe=oe.filter(dt=>tt(dt))}}else oe=[];if(oe.length>0&&this.transform.projection.name!=="globe"&&!this.usedForTerrain&&!this._supportsFading){const tt=w.coveringZoomLevel({tileSize:E||this._source.tileSize,roundZoom:this._source.roundZoom&&!F}),dt=Math.min(tt,xe);if(X){const it=w.extendTileCover(oe,dt);for(const jt of it)oe.push(jt)}else if(Z){const it=this.transform.getFrustum(dt),jt=w.extendTileCoverToNearPlane(oe,it,dt);for(const wt of jt)oe.push(wt);if(dt>=18&&this._hasTunnelGeometry()){const wt=w.extendTileCoverForTunnels(oe,it,dt,20);for(const Ot of wt)oe.push(Ot)}}else if(this.castsShadows&&H){const it=w.extendTileCover(oe,dt,H,16);for(const jt of it)this._shadowCasterTiles[jt.key]=!0,oe.push(jt)}}const We=this._updateRetainedTiles(oe);if(this._supportsFading&&oe.length!==0){const tt={},dt={},it=o.o.now(),jt=Object.keys(We);for(const Ot of jt){const Vt=We[Ot],Ct=this._tiles[Ot];if(!Ct||Ct.fadeEndTime!==void 0&&Ct.fadeEndTime<=it)continue;const ks=this.findLoadedParent(Vt,Math.max(Vt.overscaledZ-ql.maxOverzooming,this._source.minzoom));ks&&(this._addTile(ks.tileID),tt[ks.tileID.key]=ks.tileID),dt[Ot]=Vt}const wt=oe[oe.length-1].overscaledZ;for(const Ot in this._tiles){const Vt=this._tiles[Ot];if(We[Ot]||!Vt.hasData())continue;let Ct=Vt.tileID;for(;Ct.overscaledZ>wt;){Ct=Ct.scaledTo(Ct.overscaledZ-1);const ks=this._tiles[Ct.key];if(ks&&ks.hasData()&&dt[Ct.key]){We[Ot]=Vt.tileID;break}}}for(const Ot in tt)We[Ot]||(this._coveredTiles[Ot]=!0,We[Ot]=tt[Ot])}for(const tt in We)this._tiles[tt].clearFadeHold();const He=o.b3(this._tiles,We);for(const tt of He){const dt=this._tiles[tt];dt.hasSymbolBuckets&&!dt.holdingForFade()?dt.setHoldDuration(this.map._fadeDuration):dt.hasSymbolBuckets&&!dt.symbolFadeFinished()||this._removeTile(+tt)}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={},H=w.reduce((Ne,Le)=>Math.min(Ne,Le.overscaledZ),1/0),Z=w[0].overscaledZ,X=Math.max(Z-ql.maxOverzooming,this._source.minzoom),oe=Math.max(Z+ql.maxUnderzooming,this._source.minzoom),xe={};for(const Ne of w){const Le=this._addTile(Ne);E[Ne.key]=Ne,Le.hasData()||H=this._source.maxzoom){const He=Ne.children(this._source.maxzoom)[0],tt=this.getTile(He);if(tt&&tt.hasData()){E[He.key]=He;continue}}else{const He=Ne.children(this._source.maxzoom);if(E[He[0].key]&&E[He[1].key]&&E[He[2].key]&&E[He[3].key])continue}let We=Le.wasRequested();for(let He=Ne.overscaledZ-1;He>=X;--He){const tt=Ne.scaledTo(He);if(F[tt.key]||(F[tt.key]=!0,Le=this.getTile(tt),!Le&&We&&(Le=this._addTile(tt)),Le&&(E[tt.key]=tt,We=Le.wasRequested(),Le.hasData())))break}}return E}_updateLoadedParentTileCache(){this._loadedParentTiles={};for(const w in this._tiles){const E=[];let F,H=this._tiles[w].tileID;for(;H.overscaledZ>0;){if(H.key in this._loadedParentTiles){F=this._loadedParentTiles[H.key];break}E.push(H.key);const Z=H.scaledTo(H.overscaledZ-1);if(F=this._getLoadedTile(Z),F)break;H=Z}for(const Z of E)this._loadedParentTiles[Z]=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 H=this.map?this.map.painter:null,Z=this._source.tileSize*w.overscaleFactor();E=this._source.type==="raster-array"?new Pf(w,Z,this.transform.tileZoom,H,this._isRaster):new o.b0(w,Z,this.transform.tileZoom,H,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 H=[],Z=this.transform;if(!Z)return H;const X=Z.projection.name==="globe",oe=o.aH(Z.center.lng);for(const xe in this._tiles){const Ne=this._tiles[xe];if(F&&Ne.clearQueryDebugViz(),Ne.holdingForFade())continue;let Le;if(X){const We=Ne.tileID.canonical;if(We.z===0){const He=[Math.abs(o.aC(oe,...Lu(We,-1))-oe),Math.abs(o.aC(oe,...Lu(We,1))-oe)];Le=[0,2*He.indexOf(Math.min(...He))-1]}else{const He=[Math.abs(o.aC(oe,...Lu(We,-1))-oe),Math.abs(o.aC(oe,...Lu(We,0))-oe),Math.abs(o.aC(oe,...Lu(We,1))-oe)];Le=[He.indexOf(Math.min(...He))-1]}}else Le=[0];for(const We of Le){const He=w.containsTile(Ne,Z,E,We);He&&H.push(He)}}return H}getShadowCasterCoordinates(){return this._getRenderableCoordinates(!1,!0)}getVisibleCoordinates(w){return this._getRenderableCoordinates(w)}_getRenderableCoordinates(w,E){const F=this.getRenderableIds(w,E).map(Z=>this._tiles[Z].tileID),H=this.transform.projection.name==="globe";for(const Z of F)Z.projMatrix=this.transform.calculateProjMatrix(Z.toUnwrapped()),Z.expandedProjMatrix=H?this.transform.calculateProjMatrix(Z.toUnwrapped(),!1,!0):Z.projMatrix;return F}sortCoordinatesByDistance(w){const E=w.slice(),F=this.transform._camera.position,H=this.transform._camera.forward(),Z={};for(const X of E){const oe=1/(1<Z[X.key]-Z[oe.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 H=this._tiles[w];H&&H.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 xe=()=>{this._sourceLoaded&&(this._source.off("data",xe),this._preloadTiles(w,E))};return void this._source.on("data",xe)}const F=new Map,H=Array.isArray(w)?w:[w],Z=this.map.painter.terrain,X=this.usedForTerrain&&Z?Z.getScaledDemTileSize():this._source.tileSize;for(const xe of H){const Ne=xe.coveringTiles({tileSize:X,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 Ne)F.set(Le.key,Le);this.usedForTerrain&&xe.updateElevation(!1)}const oe=Array.from(F.values());o.t(oe,(xe,Ne)=>{const Le=new o.b0(xe,this._source.tileSize*xe.overscaleFactor(),this.transform.tileZoom,this.map.painter,this._isRaster,this._source.worldview);this._loadTile(Le,We=>{this._source.type==="raster-dem"&&Le.dem&&this._backfillDEM(Le),Ne(We,Le)})},E)}}function Df(R,w){const E=Math.abs(2*R.wrap)-+(R.wrap<0),F=Math.abs(2*w.wrap)-+(w.wrap<0);return R.overscaledZ-w.overscaledZ||F-E||w.canonical.y-R.canonical.y||w.canonical.x-R.canonical.x}function Lu(R,w){const E=1<0:F.type==="building"?H=!F.isHidden(w)&&F.paint.get("building-opacity")>0:F.type==="model"&&(H=!F.isHidden(w)&&F.paint.get("model-opacity").constantOr(1)>0),this.layersGotHidden=this.layersGotHidden||!H&&E.visible,E.visible=H}}updateZOffset(w,E){this.currentBuildingBuckets=[];for(const H of this.layers){const Z=H.layer,X=this.style.getLayerSourceCache(Z);let oe=1;Z.type==="fill-extrusion"?oe=H.visible?Z.paint.get("fill-extrusion-vertical-scale"):0:Z.type==="building"&&(oe=H.visible?Z.paint.get("building-vertical-scale"):0);let xe=X?X.getTile(E):null;if(!xe&&X)for(const Ne in X._tiles){const Le=X._tiles[Ne];if(E.canonical.isChildOf(Le.tileID.canonical)){xe=Le;break}}this.currentBuildingBuckets.push({bucket:xe?xe.getBucket(Z):null,tileID:xe?xe.tileID:E,verticalScale:oe})}w.hasAnyZOffset=!1;let F=!1;for(let H=0;H{F in w&&(E[F]=w[F])}),E}function Kd(R){R=R.slice();const w=Object.create(null);for(const E of R)w[E.id]=E;for(let E=0;E0?(H-X)/oe:0;return this.points[Z].mult(1-xe).add(this.points[E].mult(xe))}}class mx{constructor(w,E,F){const H=this.boxCells=[],Z=this.circleCells=[];this.xCellCount=Math.ceil(w/F),this.yCellCount=Math.ceil(E/F);for(let X=0;Xthis.width||H<0||E>this.height)return!Z&&[];const oe=[];if(w<=0&&E<=0&&this.width<=F&&this.height<=H){if(Z)return!0;for(let xe=0;xe0:oe}_queryCircle(w,E,F,H,Z){const X=w-F,oe=w+F,xe=E-F,Ne=E+F;if(oe<0||X>this.width||Ne<0||xe>this.height)return!H&&[];const Le=[];return this._forEachCell(X,xe,oe,Ne,this._queryCellCircle,Le,{hitTest:H,circle:{x:w,y:E,radius:F},seenUids:{box:{},circle:{}}},Z),H?Le.length>0:Le}query(w,E,F,H,Z){return this._query(w,E,F,H,!1,Z)}hitTest(w,E,F,H,Z){return this._query(w,E,F,H,!0,Z)}hitTestCircle(w,E,F,H){return this._queryCircle(w,E,F,!0,H)}_queryCell(w,E,F,H,Z,X,oe,xe){const Ne=oe.seenUids,Le=this.boxCells[Z];if(Le!==null){const He=this.bboxes;for(const tt of Le)if(!Ne.box[tt]){Ne.box[tt]=!0;const dt=4*tt;if(w<=He[dt+2]&&E<=He[dt+3]&&F>=He[dt+0]&&H>=He[dt+1]&&(!xe||xe(this.boxKeys[tt]))){if(oe.hitTest)return X.push(!0),!0;X.push({key:this.boxKeys[tt],x1:He[dt],y1:He[dt+1],x2:He[dt+2],y2:He[dt+3]})}}}const We=this.circleCells[Z];if(We!==null){const He=this.circles;for(const tt of We)if(!Ne.circle[tt]){Ne.circle[tt]=!0;const dt=3*tt;if(this._circleAndRectCollide(He[dt],He[dt+1],He[dt+2],w,E,F,H)&&(!xe||xe(this.circleKeys[tt]))){if(oe.hitTest)return X.push(!0),!0;{const it=He[dt],jt=He[dt+1],wt=He[dt+2];X.push({key:this.circleKeys[tt],x1:it-wt,y1:jt-wt,x2:it+wt,y2:jt+wt})}}}}}_queryCellCircle(w,E,F,H,Z,X,oe,xe){const Ne=oe.circle,Le=oe.seenUids,We=this.boxCells[Z];if(We!==null){const tt=this.bboxes;for(const dt of We)if(!Le.box[dt]){Le.box[dt]=!0;const it=4*dt;if(this._circleAndRectCollide(Ne.x,Ne.y,Ne.radius,tt[it+0],tt[it+1],tt[it+2],tt[it+3])&&(!xe||xe(this.boxKeys[dt])))return X.push(!0),!0}}const He=this.circleCells[Z];if(He!==null){const tt=this.circles;for(const dt of He)if(!Le.circle[dt]){Le.circle[dt]=!0;const it=3*dt;if(this._circlesCollide(tt[it],tt[it+1],tt[it+2],Ne.x,Ne.y,Ne.radius)&&(!xe||xe(this.circleKeys[dt])))return X.push(!0),!0}}}_forEachCell(w,E,F,H,Z,X,oe,xe){const Ne=this._convertToXCellCoord(w),Le=this._convertToYCellCoord(E),We=this._convertToXCellCoord(F),He=this._convertToYCellCoord(H);for(let tt=Ne;tt<=We;tt++)for(let dt=Le;dt<=He;dt++)if(Z.call(this,w,E,F,H,this.xCellCount*dt+tt,X,oe,xe))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,H,Z,X){const oe=H-w,xe=Z-E,Ne=F+X;return Ne*Ne>oe*oe+xe*xe}_circleAndRectCollide(w,E,F,H,Z,X,oe){const xe=(X-H)/2,Ne=Math.abs(w-(H+xe));if(Ne>xe+F)return!1;const Le=(oe-Z)/2,We=Math.abs(E-(Z+Le));if(We>Le+F)return!1;if(Ne<=xe||We<=Le)return!0;const He=Ne-xe,tt=We-Le;return He*He+tt*tt<=F*F}}const P0=Math.tan(85*Math.PI/180);function ld(R,w,E,F,H,Z,X){const oe=o.bb();if(E)if(Z.name==="globe"){const xe=o.bc(H,w);o.aD(oe,oe,xe)}else{const xe=o.bd([],X);oe[0]=xe[0],oe[1]=xe[1],oe[4]=xe[2],oe[5]=xe[3],F||o.ba(oe,oe,H.angle)}else o.aD(oe,H.labelPlaneMatrix,R);return oe}function Oc(R,w,E,F,H,Z,X){const oe=ld(R,w,E,F,H,Z,X);return Z.name==="globe"&&E||(oe[2]=oe[6]=oe[10]=oe[14]=0),oe}function cp(R,w,E,F,H,Z,X){if(E){if(Z.name==="globe"){const oe=ld(R,w,E,F,H,Z,X);return o.b7(oe,oe),o.aD(oe,R,oe),oe}{const oe=o.b8(R),xe=o.b9([]);return xe[0]=X[0],xe[1]=X[1],xe[4]=X[2],xe[5]=X[3],o.aD(oe,oe,xe),F||o.ba(oe,oe,-H.angle),oe}}return H.glCoordMatrix}function _d(R,w,E,F){const H=[R,w,E,1];E?o.aE(H,H,F):Cs(H,H,F);const Z=H[3];return H[0]/=Z,H[1]/=Z,H[2]/=Z,H}function dp(R,w){return Math.min(.5+R/w*.5,1.5)}function om(R,w){const E=R[0]/R[3],F=R[1]/R[3];return E>=-w[0]&&E<=w[0]&&F>=-w[1]&&F<=w[1]}function Rh(R,w,E,F,H,Z,X,oe,xe,Ne,Le=1){const We=E.transform,He=F?R.textSizeData:R.iconSizeData,tt=o.bj(He,E.transform.zoom,Le),dt=We.projection.name==="globe",it=[256/E.width*2+1,256/E.height*2+1],jt=F?R.text.dynamicLayoutVertexArray:R.icon.dynamicLayoutVertexArray;jt.clear();let wt=null;dt&&(wt=F?R.text.globeExtVertexArray:R.icon.globeExtVertexArray);const Ot=R.lineVertexArray,Vt=F?R.text.placedSymbolArray:R.icon.placedSymbolArray,Ct=E.transform.width/E.transform.height;let ks,ss=!1;for(let Ns=0;NsMath.abs(E)?{useVertical:!0}:R===o.bk.vertical?F>0?{needsFlipping:!0}:null:w!==0&&function(H,Z){return H===0||Math.abs(Z/H)>P0}(E,F)?w===1?{needsFlipping:!0}:null:E<0?{needsFlipping:!0}:null}function Bs(R,w,E,F,H,Z,X,oe,xe,Ne,Le,We,He,tt,dt,it,jt,wt,Ot,Vt){const Ct=w/24,ks=R.lineOffsetX*Ct,ss=R.lineOffsetY*Ct,{lineStartIndex:Ns,glyphStartIndex:Gt,numGlyphs:es,segment:fs,writingMode:Ws,flipState:As}=R,gn=Ns+R.lineLength,an=Dn=>{if(Le){const[mn,vn,kn]=Dn.up,_r=Ne.length;o.bm(Le,_r+0,mn,vn,kn),o.bm(Le,_r+1,mn,vn,kn),o.bm(Le,_r+2,mn,vn,kn),o.bm(Le,_r+3,mn,vn,kn)}const[Gn,en,Ms]=Dn.point;o.bn(Ne,Gn,en,Ms,Dn.angle)};if(es>1){const Dn=at(Ct,oe,ks,ss,E,We,He,R,xe,Z,tt,it,!1,jt,wt,Ot,Vt);if(!Dn)return{notEnoughRoom:!0};if(F&&!E){let[Gn,en,Ms]=Dn.first.point,[mn,vn,kn]=Dn.last.point;[Gn,en]=_d(Gn,en,Ms,X),[mn,vn]=_d(mn,vn,kn,X);const _r=Wt(Ws,As,(mn-Gn)*dt,vn-en);if(R.flipState=_r&&_r.needsFlipping?1:2,_r)return _r}an(Dn.first);for(let Gn=Gt+1;Gn0?mn:jn(He,Ms,Gn,1,H,void 0,jt,wt.canonical),kn=Wt(Ws,As,(vn[0]-Gn[0])*dt,vn[1]-Gn[1]);if(R.flipState=kn&&kn.needsFlipping?1:2,kn)return kn}const Dn=Ir(Ct*oe.getoffsetX(Gt),ks,ss,E,We,He,fs,Ns,gn,xe,Z,tt,it,!1,!1,jt,wt,Ot,Vt);if(!Dn)return{notEnoughRoom:!0};an(Dn)}return{}}function Ys(R,w,E,F,H){const{x:Z,y:X,z:oe}=F.projectTilePoint(R.x,R.y,w);if(!H)return _d(Z,X,oe,E);const[xe,Ne,Le]=H.getElevation(R,H.elevation,H.elevationFeature);return _d(Z+xe,X+Ne,oe+Le,E)}function jn(R,w,E,F,H,Z,X,oe){const xe=Ys(R.sub(w)._unit()._add(R),oe,H,X,Z);return o.ax(xe,E,xe),o.ay(xe,xe),o.bg(xe,E,xe,F)}function Ir(R,w,E,F,H,Z,X,oe,xe,Ne,Le,We,He,tt,dt,it,jt,wt,Ot){const Vt=F?R-w:R+w;let Ct=Vt>0?1:-1,ks=0;F&&(Ct*=-1,ks=Math.PI),Ct<0&&(ks+=Math.PI);let ss=oe+X+(Ct>0?0:1)|0,Ns=H,Gt=H,es=0,fs=0;const Ws=Math.abs(Vt),As=[],gn=[];let an=Z,Dn=an,Gn=o.be([]);const en=()=>jn(Dn,an,Gt,Ws-es+1,Le,He,it,jt.canonical);for(;es+fs<=Ws;){if(ss+=Ct,ss=xe)return null;if(Gt=Ns,Dn=an,As.push(Gt),tt&&gn.push(Dn),an=new o.P(Ne.getx(ss),Ne.gety(ss)),Ns=We[ss],!Ns){const wa=Ys(an,jt.canonical,Le,it,He);Ns=wa[3]>0?We[ss]=wa:en()}es+=fs;const Bn=o.ax([],Ns,Gt),ra=o.bf(Gt,Ns);if(E&&ra>0&&fs>0&&o.bi(Gn,Bn)/(fs*ra)0,Vt),Ns=Ne*ss.perspectiveRatio,Gt=(F.x1*E+oe.x-F.padding)*Ns+ss.point.x,es=(F.y1*E+oe.y-F.padding)*Ns+ss.point.y,fs=(F.x2*E+oe.x+F.padding)*Ns+ss.point.x,Ws=(F.y2*E+oe.y+F.padding)*Ns+ss.point.y,As=ss.perspectiveRatio<=.55||ss.occluded;return!this.isInsideGrid(Gt,es,fs,Ws)||!xe&&this.grid.hitTest(Gt,es,fs,Ws,We)||As?{box:[],offscreen:!1,occluded:ss.occluded}:{box:[Gt,es,fs,Ws],offscreen:this.isOffscreen(Gt,es,fs,Ws),occluded:!1}}placeCollisionCircles(w,E,F,H,Z,X,oe,xe,Ne,Le,We,He,tt,dt,it,jt){const wt=[],Ot=this.transform.elevation,Vt=w.getProjection(),Ct=w.elevationType==="road",ks=!!Ot||Ct,ss=o.bu.getAtTileOffsetFunc(jt,this.transform.center.lat,this.transform.worldSize,Vt),Ns=new o.P(F.tileAnchorX,F.tileAnchorY),Gt=new o.P(F.tileAnchorX,F.tileAnchorY);let{x:es,y:fs,z:Ws}=Vt.projectTilePoint(Gt.x,Gt.y,jt.canonical),As=null;if(ks){const ra=Ct?w.getElevationFeatureForText(H):null;As={getElevation:ss,elevation:Ot,elevationFeature:ra};const[wa,Yr,na]=ss(Ns,Ot,ra);es+=wa,fs+=Yr,Ws+=na}const gn=Vt.name==="globe",an=this.projectAndGetPerspectiveRatio(xe,es,fs,Ws,jt,gn||!!Ot||this.transform.pitch>0,Vt),{perspectiveRatio:Dn}=an,Gn=(He?oe/Dn:oe*Dn)/o.by,en=_d(es,fs,Ws,Ne),Ms=F.lineOffsetX*Gn,mn=F.lineOffsetY*Gn,vn=o.ap(w.layers[0].layout.get("text-max-angle")),kn=Math.cos(vn),_r=an.signedDistanceFromCamera>0?at(Gn,X,Ms,mn,Ct&&F.flipState===1,en,Gt,F,Z,Ne,{},ks&&!He?As:null,He&&ks,Vt,jt,He,kn):null;let cr=!1,dr=!1,Bn=!0;if(_r&&!an.occluded){const ra=.5*dt*Dn+it,wa=new o.P(-100,-100),Yr=new o.P(this.screenRightBoundary,this.screenBottomBoundary),na=new Vx,{first:Xa,last:pi}=_r,oi=Xa.path.length;let Bi=[];for(let li=oi-1;li>=1;li--)Bi.push(Xa.path[li]);for(let li=1;li(ks&&!gn&&(Rl=ss(tdli[3]<=0)&&(Bi=[]));let $i=[];if(Bi.length>0){let li=1/0,Fo=-1/0,Rl=1/0,td=-1/0;for(const nc of Bi)li=Math.min(li,nc[0]),Rl=Math.min(Rl,nc[1]),Fo=Math.max(Fo,nc[0]),td=Math.max(td,nc[1]);Fo>=wa.x&&li<=Yr.x&&td>=wa.y&&Rl<=Yr.y&&($i=[Bi.map(nc=>new o.P(nc[0],nc[1]))],(liYr.x||RlYr.y)&&($i=o.bv($i,wa.x,wa.y,Yr.x,Yr.y)))}for(const li of $i){na.reset(li,.25*ra);let Fo=0;Fo=na.length<=.5*ra?1:Math.ceil(na.paddedLength/Oa)+1;for(let Rl=0;Rl0?(o.aE(xe,xe,w),this.fogState&&Z&&oe.name!=="globe"&&(Ne=function(He,tt,dt,it,jt,wt){const Ot=wt.calculateFogTileMatrix(jt),Vt=[tt,dt,it];return o.ah(Vt,Vt,Ot),hi(He,o.ai(Vt),wt.pitch,wt._fov)}(this.fogState,E,F,H,Z.toUnwrapped(),this.transform)>.9)):Cs(xe,xe,w);const Le=xe[3];return{point:new o.P((xe[0]/Le+1)/2*this.transform.width+xn,(-xe[1]/Le+1)/2*this.transform.height+xn),perspectiveRatio:Math.min(.5+this.transform.getCameraToCenterDistance(oe)/Le*.5,1.5),signedDistanceFromCamera:Le,occluded:X&&xe[2]>Le||Ne}}isOffscreen(w,E,F,H){return F=this.screenRightBoundary||Hthis.screenBottomBoundary}isInsideGrid(w,E,F,H){return F>=0&&w=0&&EF.collisionGroupID===E}}return this.collisionGroups[w]}}function Ho(R,w,E,F,H){const{horizontalAlign:Z,verticalAlign:X}=o.bF(R),oe=-(Z-.5)*w,xe=-(X-.5)*E,Ne=o.bG(R,F);return new o.P(oe+Ne[0]*H,xe+Ne[1]*H)}function Kl(R,w,E,F,H){const Z=new o.P(R,w);return E&&Z._rotate(F?H:-H),Z}class Hi{constructor(w,E,F,H,Z,X){this.transform=w.clone(),this.projection=w.projection.name,this.collisionIndex=new Rr(this.transform,Z),this.buildingIndex=X,this.frontCutoffStart=0,this.placements={},this.opacities={},this.variableOffsets={},this.stale=!1,this.commitTime=0,this.fadeDuration=E,this.retainedQueryData={},this.collisionGroups=new ri(F),this.collisionCircleArrays={},this.prevPlacement=H,H&&(H.prevPlacement=void 0),this.placedOrientations={},this.lastReplacementSourceUpdateTime=0}getBucketParts(w,E,F,H,Z=1){const X=F.getBucket(E),oe=F.latestFeatureIndex;if(!X||!oe||E.fqid!==X.layerIds[0])return;const xe=X.layers[0].layout,Ne=X.layers[0].paint,Le=F.collisionBoxArray,We=Math.pow(2,this.transform.zoom-F.tileID.overscaledZ),He=F.tileSize/o.an,tt=F.tileID.toUnwrapped();this.transform.setProjection(X.projection);const dt=(it=F.tileID,jt=X.getProjection(),wt=this.transform,jt.name===this.projection?wt.calculateProjMatrix(it.toUnwrapped()):Fg(wt,jt,it));var it,jt,wt;const Ot=xe.get("text-pitch-alignment")==="map",Vt=xe.get("text-rotation-alignment")==="map";E.compileFilter(E.options);const Ct=E.dynamicFilter(),ks=E.dynamicFilterNeedsFeature(),ss=E.dynamicFilterNeedsGeometry(),Ns=this.transform.calculatePixelsToTileUnitsMatrix(F),Gt=Oc(dt,F.tileID.canonical,Ot,Vt,this.transform,X.getProjection(),Ns);let es=null;const fs=X.getProjection().createInversionMatrix(this.transform,F.tileID.canonical);if(Ot){const mn=cp(dt,F.tileID.canonical,Ot,Vt,this.transform,X.getProjection(),Ns);es=o.aD([],this.transform.labelPlaneMatrix,mn)}let Ws=null;Ct&&F.latestFeatureIndex&&(Ws={unwrappedTileID:tt,dynamicFilter:Ct,dynamicFilterNeedsFeature:ks,needGeometry:ss}),this.retainedQueryData[X.bucketInstanceId]=new Ra(X.bucketInstanceId,oe,X.sourceLayerIndex,X.index,F.tileID);const[As,gn]=X.layers[0].layout.get("text-size-scale-range"),an=o.aC(Z,As,gn),[Dn,Gn]=xe.get("icon-size-scale-range"),en=o.aC(Z,Dn,Gn),Ms={bucket:X,layout:xe,paint:Ne,posMatrix:dt,invMatrix:fs,mercatorCenter:[o.aH(this.transform.center.lng),o.aL(this.transform.center.lat)],textLabelPlaneMatrix:Gt,labelToScreenMatrix:es,clippingData:Ws,scale:We,textPixelRatio:He,holdingForFade:F.holdingForFade(),collisionBoxArray:Le,partiallyEvaluatedTextSize:o.bj(X.textSizeData,this.transform.zoom,an),partiallyEvaluatedIconSize:o.bj(X.iconSizeData,this.transform.zoom,en),collisionGroup:this.collisionGroups.get(X.sourceID),latestFeatureIndex:F.latestFeatureIndex};if(H)for(const mn of X.sortKeyRanges){const{sortKey:vn,symbolInstanceStart:kn,symbolInstanceEnd:_r}=mn;w.push({sortKey:vn,symbolInstanceStart:kn,symbolInstanceEnd:_r,parameters:Ms})}else w.push({symbolInstanceStart:0,symbolInstanceEnd:X.symbolInstances.length,parameters:Ms})}attemptAnchorPlacement(w,E,F,H,Z,X,oe,xe,Ne,Le,We,He,tt,dt,it,jt,wt,Ot,Vt,Ct,ks){const{textOffset0:ss,textOffset1:Ns,crossTileID:Gt}=it,es=[ss,Ns],fs=Ho(w,X,oe,es,xe),Ws=this.collisionIndex.placeCollisionBox(wt,xe,E,F,H,Z,Kl(fs.x,fs.y,Ne,Le,this.transform.angle),dt,We,He,tt.predicate);if(Vt){const As=wt.getSymbolInstanceIconSize(ks,this.transform.zoom,it.placedIconSymbolIndex);if(this.collisionIndex.placeCollisionBox(wt,As,Vt,F,H,Z,Kl(fs.x,fs.y,Ne,Le,this.transform.angle),dt,We,He,tt.predicate).box.length===0)return}if(Ws.box.length>0){let As;return this.prevPlacement&&this.prevPlacement.variableOffsets[Gt]&&this.prevPlacement.placements[Gt]&&this.prevPlacement.placements[Gt].text&&(As=this.prevPlacement.variableOffsets[Gt].anchor),this.variableOffsets[Gt]={textOffset:es,width:X,height:oe,anchor:w,textScale:xe,prevAnchor:As},this.markUsedJustification(wt,w,it,Ot),wt.allowVerticalPlacement&&(this.markUsedOrientation(wt,Ot,it),this.placedOrientations[Gt]=Ot),{shift:fs,placedGlyphBoxes:Ws}}}placeLayerBucketPart(w,E,F,H,Z=1){const{bucket:X,layout:oe,paint:xe,posMatrix:Ne,textLabelPlaneMatrix:Le,labelToScreenMatrix:We,clippingData:He,textPixelRatio:tt,mercatorCenter:dt,invMatrix:it,holdingForFade:jt,collisionBoxArray:wt,partiallyEvaluatedTextSize:Ot,partiallyEvaluatedIconSize:Vt,collisionGroup:Ct,latestFeatureIndex:ks}=w.parameters,ss=oe.get("text-optional"),Ns=oe.get("icon-optional"),Gt=oe.get("text-allow-overlap"),es=oe.get("icon-allow-overlap"),fs=oe.get("text-rotation-alignment")==="map",Ws=oe.get("icon-rotation-alignment")==="map",As=oe.get("text-pitch-alignment")==="map",gn=xe.get("symbol-z-offset"),an=oe.get("symbol-elevation-reference")==="sea",Dn=oe.get("symbol-placement"),[Gn,en]=oe.get("text-size-scale-range"),[Ms,mn]=oe.get("icon-size-scale-range"),vn=o.aC(Z,Gn,en),kn=o.aC(Z,Ms,mn),_r=oe.get("text-variable-anchor"),cr=fs&&Dn!=="point",dr=Ws&&Dn!=="point",Bn=_r&&X.hasTextData(),ra=X.hasIconTextFit()&&Bn&&X.hasIconData();this.transform.setProjection(X.projection);const wa=Bn||cr,Yr=dr||ra;let na=Gt&&(es||!X.hasIconData()||Ns),Xa=es&&(Gt||!X.hasTextData()||ss);const pi=!gn.isConstant();!X.collisionArrays&&wt&&X.deserializeCollisionBoxes(wt),F&&H&&X.updateCollisionDebugBuffers(this.transform.zoom,wt,vn,kn);const oi=(Oa,$i,li)=>{const{crossTileID:Fo,numVerticalGlyphVertices:Rl}=Oa;let td=null;if(He&&He.dynamicFilterNeedsFeature||pi){const cc=this.retainedQueryData[X.bucketInstanceId],_c=ks.loadFeature({featureIndex:Oa.featureIndex,bucketIndex:cc.bucketIndex,sourceLayerIndex:cc.sourceLayerIndex,layoutVertexArrayOffset:0}),Al=_c.properties?_c.properties.worldview:null;if(X.localizable&&X.worldview&&typeof Al=="string")if(Al==="all")_c.properties.$localized=!0;else{if(!Al.split(",").includes(X.worldview))return;_c.properties.$localized=!0,_c.properties.worldview=X.worldview}td=He&&He.needGeometry?o.bD(_c,!0):_c}if(He&&!(0,He.dynamicFilter)({zoom:this.transform.zoom,pitch:this.transform.pitch,worldview:X.worldview},td,this.retainedQueryData[X.bucketInstanceId].tileID.canonical,new o.P(Oa.tileAnchorX,Oa.tileAnchorY),this.transform.calculateDistanceTileData(He.unwrappedTileID)))return this.placements[Fo]=new Ua(!1,!1,!1,!0),void E.add(Fo);const nc=gn.evaluate(td,{});if((Oa.zOffset||0)+(nc||0)>0&&this.frontCutoffStart>0){const cc=2*this.frontCutoffStart-1,_c=[Oa.tileAnchorX,Oa.tileAnchorY,0,1],Al=o.aE(o.bE(),_c,Ne);if(Al[1]/Al[3]{cc.tileID=this.retainedQueryData[X.bucketInstanceId].tileID;const _c=this.transform.elevation;cc.elevation=an?nc:nc+o.bu.getAtTileOffset(cc.tileID,new o.P(cc.tileAnchorX,cc.tileAnchorY),_c,zh),cc.elevation+=Oa.zOffset},Oy=li.textBox;if(Oy){gp(Oy);const cc=Al=>{let ju=o.bk.horizontal;if(X.allowVerticalPlacement&&!Al&&this.prevPlacement){const yx=this.prevPlacement.placedOrientations[Fo];yx&&(this.placedOrientations[Fo]=yx,ju=yx,this.markUsedOrientation(X,ju,Oa))}return ju},_c=(Al,ju)=>{if(X.allowVerticalPlacement&&Rl>0&&li.verticalTextBox){for(const yx of X.writingModes)if(yx===o.bk.vertical?(vi=ju(),Hc=vi):vi=Al(),vi&&vi.box&&vi.box.length)break}else vi=Al()};if(_r){let Al=_r;if(this.prevPlacement&&this.prevPlacement.variableOffsets[Fo]){const Rd=this.prevPlacement.variableOffsets[Fo];Al.indexOf(Rd.anchor)>0&&(Al=Al.filter(Fy=>Fy!==Rd.anchor),Al.unshift(Rd.anchor))}const ju=(Rd,Fy,Ck)=>{const l4=X.getSymbolInstanceTextSize(Ot,Oa,this.transform.zoom,$i),c4=(Rd.x2-Rd.x1)*l4+2*Rd.padding,BC=(Rd.y2-Rd.y1)*l4+2*Rd.padding,L2=Oa.hasIconTextFit&&!es?Fy:null;L2&&gp(L2);let Ww={box:[],offscreen:!1,occluded:!1};const $C=Gt?2*Al.length:Al.length;for(let K0=0;K0<$C;++K0){const Ak=this.attemptAnchorPlacement(Al[K0%Al.length],Rd,dt,it,wa,c4,BC,l4,fs,As,tt,Ne,Ct,K0>=Al.length,Oa,$i,X,Ck,L2,Ot,Vt);if(Ak&&(Ww=Ak.placedGlyphBoxes,Ww&&Ww.box&&Ww.box.length)){Zo=!0,Xo=Ak.shift;break}}return Ww};_c(()=>ju(Oy,li.iconBox,o.bk.horizontal),()=>{const Rd=li.verticalTextBox;return Rd&&gp(Rd),X.allowVerticalPlacement&&!(vi&&vi.box&&vi.box.length)&&Rl>0&&Rd?ju(Rd,li.verticalIconBox,o.bk.vertical):{box:null,offscreen:null,occluded:null}}),vi&&(Zo=vi.box,Ii=vi.offscreen,rc=vi.occluded);const yx=cc(!(!vi||!vi.box));if(!Zo&&this.prevPlacement){const Rd=this.prevPlacement.variableOffsets[Fo];Rd&&(this.variableOffsets[Fo]=Rd,this.markUsedJustification(X,Rd.anchor,Oa,yx))}}else{const Al=(ju,yx)=>{const Rd=X.getSymbolInstanceTextSize(Ot,Oa,this.transform.zoom,$i),Fy=this.collisionIndex.placeCollisionBox(X,Rd,ju,dt,it,wa,new o.P(0,0),Gt,tt,Ne,Ct.predicate);return Fy&&Fy.box&&Fy.box.length&&(this.markUsedOrientation(X,yx,Oa),this.placedOrientations[Fo]=yx),Fy};_c(()=>Al(Oy,o.bk.horizontal),()=>{const ju=li.verticalTextBox;return X.allowVerticalPlacement&&Rl>0&&ju?(gp(ju),Al(ju,o.bk.vertical)):{box:null,offscreen:null,occluded:null}}),cc(!!(vi&&vi.box&&vi.box.length))}}if(Ol=vi,Zo=Ol&&Ol.box&&Ol.box.length>0,Ii=Ol&&Ol.offscreen,rc=Ol&&Ol.occluded,Oa.useRuntimeCollisionCircles){const cc=Oa.centerJustifiedTextSymbolIndex>=0?Oa.centerJustifiedTextSymbolIndex:Oa.verticalPlacedTextSymbolIndex,_c=X.text.placedSymbolArray.get(cc),Al=o.bl(X.textSizeData,Ot,_c),ju=oe.get("text-padding");Fu=this.collisionIndex.placeCollisionCircles(X,Gt,_c,cc,X.lineVertexArray,X.glyphOffsetArray,Al,Ne,Le,We,F,As,Ct.predicate,Oa.collisionCircleDiameter*Al/o.by,ju,this.retainedQueryData[X.bucketInstanceId].tileID),Zo=Gt||Fu.circles.length>0&&!Fu.collisionDetected,Ii=Ii&&Fu.offscreen,rc=Fu.occluded}if(li.iconFeatureIndex&&(Uf=li.iconFeatureIndex),li.iconBox){const cc=_c=>{gp(_c);const Al=Oa.hasIconTextFit&&Xo?Kl(Xo.x,Xo.y,fs,As,this.transform.angle):new o.P(0,0),ju=X.getSymbolInstanceIconSize(Vt,this.transform.zoom,Oa.placedIconSymbolIndex);return this.collisionIndex.placeCollisionBox(X,ju,_c,dt,it,Yr,Al,es,tt,Ne,Ct.predicate)};Hc&&Hc.box&&Hc.box.length&&li.verticalIconBox?(ro=cc(li.verticalIconBox),Pi=ro.box.length>0):(ro=cc(li.iconBox),Pi=ro.box.length>0),Ii=Ii&&ro.offscreen,hd=ro.occluded}const ul=ss||Oa.numHorizontalGlyphVertices===0&&Rl===0,Iv=Ns||Oa.numIconVertices===0;if(ul||Iv?Iv?ul||(Pi=Pi&&Zo):Zo=Pi&&Zo:Pi=Zo=Pi&&Zo,Zo&&Ol&&Ol.box&&this.collisionIndex.insertCollisionBox(Ol.box,oe.get("text-ignore-placement"),X.bucketInstanceId,Hc&&Hc.box&&bh?bh:Ql,Ct.ID),Pi&&ro&&this.collisionIndex.insertCollisionBox(ro.box,oe.get("icon-ignore-placement"),X.bucketInstanceId,Uf,Ct.ID),Fu&&(Zo&&this.collisionIndex.insertCollisionCircles(Fu.circles,oe.get("text-ignore-placement"),X.bucketInstanceId,Ql,Ct.ID),F)){const cc=X.bucketInstanceId;let _c=this.collisionCircleArrays[cc];_c===void 0&&(_c=this.collisionCircleArrays[cc]=new sr);for(let Al=0;Al=0;--$i){const li=Oa[$i];oi(X.symbolInstances.get(li),li,X.collisionArrays[li])}X.hasAnyZOffset&&o.w(`${X.layerIds[0]} layer symbol-z-elevate: symbols are not sorted by elevation if symbol-z-order is evaluated to viewport-y`)}else if(X.hasAnyZOffset){const Oa=X.getSortedIndexesByZOffset();for(let $i=0;$i=0&&(w.text.placedSymbolArray.get(Z).crossTileID=We>=0&&Z!==We?0:Ne),X>=0&&(w.text.placedSymbolArray.get(X).crossTileID=We>=0&&X!==We?0:Ne),oe>=0&&(w.text.placedSymbolArray.get(oe).crossTileID=We>=0&&oe!==We?0:Ne),xe>=0&&(w.text.placedSymbolArray.get(xe).crossTileID=We>=0&&xe!==We?0:Ne)}markUsedOrientation(w,E,F){const H=E===o.bk.horizontal||E===o.bk.horizontalOnly?E:0,Z=E===o.bk.vertical?E:0,{leftJustifiedTextSymbolIndex:X,centerJustifiedTextSymbolIndex:oe,rightJustifiedTextSymbolIndex:xe,verticalPlacedTextSymbolIndex:Ne}=F,Le=w.text.placedSymbolArray;X>=0&&(Le.get(X).placedOrientation=H),oe>=0&&(Le.get(oe).placedOrientation=H),xe>=0&&(Le.get(xe).placedOrientation=H),Ne>=0&&(Le.get(Ne).placedOrientation=Z)}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 H=E?E.symbolFadeChange(w):1,Z=E?E.opacities:{},X=E?E.variableOffsets:{},oe=E?E.placedOrientations:{};for(const xe in this.placements){const Ne=this.placements[xe],Le=Z[xe];Le?(this.opacities[xe]=new Aa(Le,H,Ne.text,Ne.icon,null,Ne.clipped),F=F||Ne.text!==Le.text.placed||Ne.icon!==Le.icon.placed):(this.opacities[xe]=new Aa(null,H,Ne.text,Ne.icon,Ne.skipFade,Ne.clipped),F=F||Ne.text||Ne.icon)}for(const xe in Z){const Ne=Z[xe];if(!this.opacities[xe]){const Le=new Aa(Ne,H,!1,!1);Le.isHidden()||(this.opacities[xe]=Le,F=F||Ne.text.placed||Ne.icon.placed)}}for(const xe in X)this.variableOffsets[xe]||!this.opacities[xe]||this.opacities[xe].isHidden()||(this.variableOffsets[xe]=X[xe]);for(const xe in oe)this.placedOrientations[xe]||!this.opacities[xe]||this.opacities[xe].isHidden()||(this.placedOrientations[xe]=oe[xe]);F?this.lastPlacementChangeTime=w:typeof this.lastPlacementChangeTime!="number"&&(this.lastPlacementChangeTime=E?E.lastPlacementChangeTime:w)}updateLayerOpacities(w,E,F,H){H&&(this.lastReplacementSourceUpdateTime=H.updateTime);const Z=new Set;for(const X of E){const oe=X.getBucket(w);oe&&X.latestFeatureIndex&&w.fqid===oe.layerIds[0]&&(this.updateBucketOpacities(oe,Z,X,X.collisionBoxArray,F,H,X.tileID,w.scope),oe.elevationType==="offset"&&this.buildingIndex&&this.buildingIndex.updateZOffset(oe,X.tileID),oe.elevationType==="road"&&oe.updateRoadElevation(X.tileID.canonical),oe.updateZOffset())}}updateBucketOpacities(w,E,F,H,Z,X,oe,xe){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 Ne=w.layers[0].layout,Le=w.layers[0].paint,We=!!w.layers[0].dynamicFilter(),He=new Aa(null,0,!1,!1,!0),tt=Ne.get("text-allow-overlap"),dt=Ne.get("icon-allow-overlap"),it=Ne.get("text-variable-anchor"),jt=Ne.get("text-rotation-alignment")==="map",wt=Ne.get("text-pitch-alignment")==="map",Ot=Le.get("symbol-z-offset"),Vt=Ne.get("symbol-elevation-reference")==="sea",Ct=!Ot.isConstant(),ks=new Aa(null,0,tt&&(dt||!w.hasIconData()||Ne.get("icon-optional")),dt&&(tt||!w.hasTextData()||Ne.get("text-optional")),!0);!w.collisionArrays&&H&&(w.hasIconCollisionBoxData()||w.hasTextCollisionBoxData())&&w.deserializeCollisionBoxes(H);const ss=(Gt,es,fs)=>{for(let Ws=0;Ws0||Ws>0,_r=gn>0,cr=this.placedOrientations[As],dr=cr===o.bk.vertical,Bn=cr===o.bk.horizontal||cr===o.bk.horizontalOnly;!kn&&!_r||vn.isHidden()||Ns++;let ra=!1;if((kn||_r)&&X)for(const wa of w.activeReplacements){if(o.bz(wa,Z,o.bA.Symbol,xe)||wa.min.x>an||an>wa.max.x||wa.min.y>Dn||Dn>wa.max.y)continue;const Yr=o.bB(an,Dn,oe.canonical,wa.footprintTileId.canonical);if(ra=o.bC(Yr,wa.footprint),ra)break}if(ra&&this.collisionIndex.markSymbolAsClipped(w.bucketInstanceId,es.featureIndex),kn){const wa=ra?up:Yd(vn.text);ss(w.text,fs,dr?up:wa),ss(w.text,Ws,Bn?up:wa);const Yr=vn.text.isHidden(),{leftJustifiedTextSymbolIndex:na,centerJustifiedTextSymbolIndex:Xa,rightJustifiedTextSymbolIndex:pi,verticalPlacedTextSymbolIndex:oi}=es,Bi=w.text.placedSymbolArray,Oa=Yr||dr?1:0;na>=0&&(Bi.get(na).hidden=Oa),Xa>=0&&(Bi.get(Xa).hidden=Oa),pi>=0&&(Bi.get(pi).hidden=Oa),oi>=0&&(Bi.get(oi).hidden=Yr||Bn?1:0);const $i=this.variableOffsets[As];$i&&this.markUsedJustification(w,$i.anchor,es,cr);const li=this.placedOrientations[As];li&&(this.markUsedJustification(w,"left",es,li),this.markUsedOrientation(w,li,es))}if(_r){const wa=ra?up:Yd(vn.icon),{placedIconSymbolIndex:Yr,verticalPlacedIconSymbolIndex:na}=es,Xa=w.icon.placedSymbolArray,pi=vn.icon.isHidden()?1:0;Yr>=0&&(ss(w.icon,gn,dr?up:wa),Xa.get(Yr).hidden=pi),na>=0&&(ss(w.icon,es.numVerticalIconVertices,Bn?up:wa),Xa.get(na).hidden=pi)}if(w.hasIconCollisionBoxData()||w.hasTextCollisionBoxData()){const wa=w.collisionArrays[Gt];if(wa){let Yr=new o.P(0,0),na=!0;if(wa.textBox||wa.verticalTextBox){if(it){const pi=this.variableOffsets[As];pi?(Yr=Ho(pi.anchor,pi.width,pi.height,pi.textOffset,pi.textScale),jt&&Yr._rotate(wt?this.transform.angle:-this.transform.angle)):na=!1}We&&(na=!vn.clipped),wa.textBox&&lm(w.textCollisionBox.collisionVertexArray,vn.text.placed,!na||dr,Ms,Vt,Yr.x,Yr.y),wa.verticalTextBox&&lm(w.textCollisionBox.collisionVertexArray,vn.text.placed,!na||Bn,Ms,Vt,Yr.x,Yr.y)}const Xa=na&&!!(!Bn&&wa.verticalIconBox);wa.iconBox&&lm(w.iconCollisionBox.collisionVertexArray,vn.icon.placed,Xa,Ms,Vt,es.hasIconTextFit?Yr.x:0,es.hasIconTextFit?Yr.y:0),wa.verticalIconBox&&lm(w.iconCollisionBox.collisionVertexArray,vn.icon.placed,!Xa,Ms,Vt,es.hasIconTextFit?Yr.x:0,es.hasIconTextFit?Yr.y:0)}}}if(w.fullyClipped=Ns===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 lm(R,w,E,F,H,Z,X){R.emplaceBack(w?1:0,E?1:0,Z||0,X||0,F,H?1:0),R.emplaceBack(w?1:0,E?1:0,Z||0,X||0,F,H?1:0),R.emplaceBack(w?1:0,E?1:0,Z||0,X||0,F,H?1:0),R.emplaceBack(w?1:0,E?1:0,Z||0,X||0,F,H?1:0)}const zg=Math.pow(2,25),Bg=Math.pow(2,24),gu=Math.pow(2,17),tc=Math.pow(2,16),L1=Math.pow(2,9),Hx=Math.pow(2,8),I0=Math.pow(2,1);function Yd(R){if(R.opacity===0&&!R.placed)return 0;if(R.opacity===1&&R.placed)return 4294967295;const w=R.placed?1:0,E=Math.floor(127*R.opacity);return E*zg+w*Bg+E*gu+w*tc+E*L1+w*Hx+E*I0+w}const up=0;class D0{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,H,Z,X){const oe=this._bucketParts;for(;this._currentTileIndexxe.sortKey-Ne.sortKey));this._currentPartIndex{const xe=o.o.now()-X;return!this.isFullPlacementRequested()&&this._fadeDuration!==0&&xe>2};for(;this._currentPlacementIndex>=0;){const xe=E[w[this._currentPlacementIndex]],Ne=this.placement.collisionIndex.transform.zoom;if(xe.type==="symbol"&&xe.visibility!=="none"&&(!xe.minzoom||xe.minzoom<=Ne)&&(!xe.maxzoom||xe.maxzoom>Ne)){const Le=xe,We=Le.layout.get("symbol-z-elevate"),He=Le.layout.get("symbol-sort-key").constantOr(1)!==void 0,tt=Le.layout.get("symbol-z-order"),dt=tt==="viewport-y"||tt==="auto"&&!(tt!=="viewport-y"&&He),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 D0(Le),Ot=o.F(xe.source,xe.scope);if(wt.continuePlacement(We||jt?H[Ot]:F[Ot],this.placement,this._showCollisionBoxes,xe,oe,Z))return;delete this._inProgressLayer}this._currentPlacementIndex--}this._forceFullPlacement=!1,this._done=!0}commit(w){return this.placement.commit(w),this.placement}}const cd=512/o.an/2;class wd{constructor(w,E,F){this.tileID=w,this.bucketInstanceId=F,this.index=new o.bI(E.length,16,Int32Array),this.keys=[],this.crossTileIDs=[];const H=w.canonical.x*o.an,Z=w.canonical.y*o.an;for(let X=0;Xjt-wt);for(const jt of it){const wt=this.crossTileIDs[jt];if(this.keys[jt]===Le&&!F.has(wt)){F.add(wt),Ne.crossTileID=wt;break}}}}}class Pu{constructor(){this.maxCrossTileID=0}generate(){return++this.maxCrossTileID}}class Lm{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 H=this.indexes[F],Z={};for(const X in H){const oe=H[X];oe.tileID=oe.tileID.unwrapTo(oe.tileID.wrap+E),Z[oe.tileID.key]=oe}this.indexes[F]=Z}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 Z=0;Zw.overscaledZ)for(const oe in X){const xe=X[oe];xe.tileID.isChildOf(w)&&xe.findMatches(E.symbolInstances,w,H)}else{const oe=X[w.scaledTo(Number(Z)).key];oe&&oe.findMatches(E.symbolInstances,w,H)}}for(let Z=0;Z{E[F]=!0});for(const F in this.layerIndexes)E[F]||delete this.layerIndexes[F]}}const kl=771;class Ma{constructor(w,E,F,H){this.blendFunction=w,this.blendColor=E.toNonPremultipliedRenderColor(null),this.mask=F,this.blendEquation=H}}Ma.Replace=[1,0,1,0],Ma.disabled=new Ma(Ma.Replace,o.aq.transparent,[!1,!1,!1,!1]),Ma.unblended=new Ma(Ma.Replace,o.aq.transparent,[!0,!0,!0,!0]),Ma.alphaBlended=new Ma([1,kl,1,kl],o.aq.transparent,[!0,!0,!0,!0]),Ma.alphaBlendedNonPremultiplied=new Ma([770,kl,770,kl],o.aq.transparent,[!0,!0,!0,!0]),Ma.multiply=new Ma([774,0,774,0],o.aq.transparent,[!0,!0,!0,!0]),Ma.multiplyAccumulateAlpha=new Ma([774,0,1,kl],o.aq.transparent,[!0,!0,!0,!0]),Ma.additive=new Ma([1,1,1,1],o.aq.transparent,[!0,!0,!0,!0]);class qr{constructor(w,E,F){this.func=w,this.mask=E,this.range=F}}qr.ReadOnly=!1,qr.ReadWrite=!0,qr.disabled=new qr(519,qr.ReadOnly,[0,1]);const Yl=7680;class La{constructor(w,E,F,H,Z,X){this.test=w,this.ref=E,this.mask=F,this.fail=H,this.depthFail=Z,this.pass=X}}La.disabled=new La({func:519,mask:0},0,0,Yl,Yl,Yl);const Pm=1029,dd=2305;class pa{constructor(w,E,F){this.enable=w,this.mode=E,this.frontFace=F}}function Gx(R,w){const E=o.bO(R,3);o.bR(R,w),o.bW(R,3,E)}function $g(R,w){const E=o.bL([]);return o.bM(E,E,-w),o.bN(E,E,-R),E}function px(R,w){const E=[R[0],R[1],0],F=[w[0],w[1],0];if(o.ai(E)>=1e-15){const X=o.ay([],E);o.bJ(F,X,o.bi(F,X)),w[0]=F[0],w[1]=F[1]}const H=o.bh([],w,R);if(o.bK(H)<1e-15)return null;const Z=Math.atan2(-H[1],H[0]);return $g(Math.atan2(Math.sqrt(R[0]*R[0]+R[1]*R[1]),-R[2]),Z)}pa.disabled=new pa(!1,Pm,dd),pa.backCCW=new pa(!0,Pm,dd),pa.backCW=new pa(!0,Pm,2304),pa.frontCW=new pa(!0,1028,2304),pa.frontCCW=new pa(!0,1028,dd);class R0{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 H=this.position,Z=F||(this._elevation?this._elevation.getAtPointOrZero(o.ag.fromLngLat(w)):0),X=o.ag.fromLngLat(w,Z),oe=[X.x-H.x,X.y-H.y,X.z-H.z];E||(E=[0,0,1]),E[2]=Math.abs(E[2]),this.orientation=px(oe,E)}setPitchBearing(w,E){this.orientation=$g(o.ap(w),o.ap(-E))}}class Of{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&&Gx(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=$g(w,E),Gx(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 H=this.position;o.bJ(H,H,-w);const Z=new Float64Array(16);return o.bP(Z,[F,F,F]),o.bx(Z,Z,H),Z[10]*=E,Z}getWorldToCamera(w,E){const F=new Float64Array(16),H=new Float64Array(4),Z=this.position;return o.bQ(H,this._orientation),o.bJ(Z,Z,-w),o.bR(F,H),o.bx(F,F,Z),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,H){const Z=new Float64Array(16);return o.bS(Z,w,E,F,H),Z}getCameraToClipOrthographic(w,E,F,H,Z,X){const oe=new Float64Array(16);return o.bT(oe,w,E,F,H,Z,X),oe}getDistanceToElevation(w,E=!1){const F=w===0?0:o.bU(w,E?o.bV(this.position[1]):this.position[1]),H=this.forward();return(F-this.position[2])/H[2]}clone(){return new Of([...this.position],[...this.orientation])}}const qc=(R,w)=>({u_matrix:R,u_ground_shadow_factor:w});class hp{constructor(w=0,E=0,F=0,H=0){if(isNaN(w)||w<0||isNaN(E)||E<0||isNaN(F)||F<0||isNaN(H)||H<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=H}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),H=o.aC((this.top+E-this.bottom)/2,0,E);return new o.P(F,H)}equals(w){return this.top===w.top&&this.bottom===w.bottom&&this.left===w.left&&this.right===w.right}clone(){return new hp(this.top,this.bottom,this.left,this.right)}toJSON(){return{top:this.top,bottom:this.bottom,left:this.left,right:this.right}}}const fh=15;class yu{constructor(w,E,F,H,Z,X,oe){this.tileSize=512,this._renderWorldCopies=Z===void 0||Z,this._minZoom=w||0,this._maxZoom=E||22,this._minPitch=F??0,this._maxPitch=H??60,this.setProjection(X),this.setMaxBounds(oe),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 hp,this._projMatrixCache={},this._alignedProjMatrixCache={},this._fogTileMatrixCache={},this._expandedProjMatrixCache={},this._distanceTileDataCache={},this._camera=new Of,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 yu(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 H=0,Z=0;for(let X=0;X{const jt=o.ck(He,We,tt,dt,it);xe.has(jt)||(Z.push(new o.aR(We,He,tt,dt,it)),xe.add(jt))};for(let We=0;WeHe.canonical.z)continue;const tt=He.canonical,dt=He.overscaledZ,it=He.wrap,jt=1<0,Vt=tt.y+10,ks=He.wrap-(Ot?0:1),ss=He.wrap+(wt?0:1),Ns=Ot?tt.x-1:jt-1,Gt=wt?tt.x+1:0;if(X)F[0]<0?(Ne(dt,ss,tt.z,Gt,tt.y),F[1]<0&&Vt&&(Ne(dt,it,tt.z,tt.x,tt.y+1),Ne(dt,ss,tt.z,Gt,tt.y+1)),F[1]>0&&Ct&&(Ne(dt,it,tt.z,tt.x,tt.y-1),Ne(dt,ss,tt.z,Gt,tt.y-1))):F[0]>0?(Ne(dt,ks,tt.z,Ns,tt.y),F[1]<0&&Vt&&(Ne(dt,it,tt.z,tt.x,tt.y+1),Ne(dt,ks,tt.z,Ns,tt.y+1)),F[1]>0&&Ct&&(Ne(dt,it,tt.z,tt.x,tt.y-1),Ne(dt,ks,tt.z,Ns,tt.y-1))):F[1]<0&&Vt?Ne(dt,it,tt.z,tt.x,tt.y+1):Ct&&Ne(dt,it,tt.z,tt.x,tt.y-1);else{const es=He.visibleQuadrants;1&es&&(Ne(dt,ks,tt.z,Ns,tt.y),Ct&&(Ne(dt,it,tt.z,tt.x,tt.y-1),Ne(dt,ks,tt.z,Ns,tt.y-1))),2&es&&(Ne(dt,ss,tt.z,Gt,tt.y),Ct&&(Ne(dt,it,tt.z,tt.x,tt.y-1),Ne(dt,ss,tt.z,Gt,tt.y-1))),4&es&&(Ne(dt,ks,tt.z,Ns,tt.y),Vt&&(Ne(dt,it,tt.z,tt.x,tt.y+1),Ne(dt,ks,tt.z,Ns,tt.y+1))),8&es&&(Ne(dt,ss,tt.z,Gt,tt.y),Vt&&(Ne(dt,it,tt.z,tt.x,tt.y+1),Ne(dt,ss,tt.z,Gt,tt.y+1)))}}const Le=[];for(const We of Z)Z.some(He=>We.isChildOf(He))||Le.push(We);if(Z=Le.filter(We=>!w.some(He=>!!(We.overscaledZ{const wt=jt.canonical.x+.5-tt[0],Ot=jt.canonical.y+.5-tt[1];return wt*wt+Ot*Ot{const Ns=o.ck(Vt,Ot,Ct,ks,ss);Z.has(Ns)||(H.push(new o.aR(Ot,Vt,Ct,ks,ss)),Z.add(Ns))},oe=w.reduce((Ot,Vt)=>Math.max(Ot,Vt.overscaledZ),F),xe=1<{const Ct=Math.floor(Ot[0]),ks=Math.floor(Ot[1]),ss=(Ot[0]-Ct)*o.an,Ns=(Ot[1]-ks)*o.an,Gt=Math.floor(Vt[0]),es=Math.floor(Vt[1]),fs=(Vt[0]-Gt)*o.an,Ws=(Vt[1]-es)*o.an;for(let As=-1;As<=1;As++){const gn=Ct+As;if(!(gn<0||gn>=xe)){Le.x=ss-As*o.an,We.x=fs-(gn-Gt)*o.an;for(let an=-1;an<=1;an++){const Dn=ks+an;Le.y=Ns-an*o.an,We.y=Ws-(Dn-es)*o.an,o.cI(Le,We,Ne)&&X(oe,0,F,gn,Dn)}}}},tt=E.points,dt=tt[o.c9],it=tt[o.ca],jt=this._projectToGround(dt,tt[o.cb]),wt=this._projectToGround(it,tt[o.cc]);return He(dt,jt),He(it,wt),H}_projectToGround(w,E){return o.cd(o.ce(),w,E,w[2]/(w[2]-E[2]))}_projectToZ(w,E,F){const H=w[2]-E[2];return Math.abs(H)<1e-6?o.cf(w):o.cd(o.ce(),w,E,(w[2]-F)/H)}extendTileCoverForTunnels(w,E,F,H){if(F<18)return[];const Z=E.points,X=Z[o.cg],oe=Z[o.ch],xe=Z[o.ci],Ne=Z[o.cj];if(xe[2]>=0&&Ne[2]>=0||X[2]<=0||oe[2]<=0)return[];const Le=xe[2]<0?this._projectToZ(X,xe,0):xe,We=Ne[2]<0?this._projectToZ(oe,Ne,0):Ne,He=-H,tt=xe[2]3&&(it.length=3),it}_findExtensionTilesInQuad(w,E,F,H){const Z=[],X=new Set;for(const Gt of w)X.add(Gt.key);const oe=w.reduce((Gt,es)=>Math.max(Gt,es.overscaledZ),E),xe=1<{const fs=Gt.canonical.x+.5-ss,Ws=Gt.canonical.y+.5-Ns,As=es.canonical.x+.5-ss,gn=es.canonical.y+.5-Ns;return fs*fs+Ws*Ws-(As*As+gn*gn)||Gt.canonical.x-es.canonical.x||Gt.canonical.y-es.canonical.y}),Z}coveringTiles(w){let E=this.coveringZoomLevel(w);const F=E,H=this.elevation&&this.elevation.exaggeration(),Z=H&&!w.isTerrainDEM,X=this.projection.name==="mercator";if(w.minzoom!==void 0&&Ew.maxzoom&&(E=w.maxzoom);const oe=this.locationCoordinate(this.center),xe=this.center.lat,Ne=1<{const vn=new o.ag(Ms.x+25e-6,Ms.y,Ms.z),kn=new o.ag(Ms.x,Ms.y+25e-6,Ms.z),_r=Ms.toLngLat(),cr=vn.toLngLat(),dr=kn.toLngLat(),Bn=this.locationCoordinate(_r),ra=this.locationCoordinate(cr),wa=this.locationCoordinate(dr),Yr=Math.hypot(ra.x-Bn.x,ra.y-Bn.y),na=Math.hypot(wa.x-Bn.x,wa.y-Bn.y);return Math.sqrt(Yr*na)*Ns/25e-6},es=Ms=>{const mn=ks,vn=ss;return{aabb:o.cp(this,Ne,0,0,0,Ms,vn,mn,this.projection),zoom:0,x:0,y:0,minZ:vn,maxZ:mn,wrap:Ms,fullyVisible:!1}},fs=[];let Ws=[];const As=E,gn=w.reparseOverscaled?F:E,an=(jt-this._centerAltitude)*it,Dn=Ms=>{if(!this._elevation||!Ms.tileID||!X)return;const mn=this._elevation.getMinMaxForTile(Ms.tileID),vn=Ms.aabb;mn?(vn.min[2]=mn.min,vn.max[2]=mn.max,vn.center[2]=(vn.min[2]+vn.max[2])/2):(Ms.shouldSplit=en(Ms),Ms.shouldSplit||(vn.min[2]=vn.max[2]=vn.center[2]=this._centerAltitude))},Gn=(Ms,mn)=>{if(.707*mn{if(Ms.zoom=.9)return!0}else if(Z&&(kn=Ms.aabb.distanceZ(wt)*it),this.projection.isReprojectedInTileSpace&&F<=5){const na=Math.pow(2,Ms.zoom),Xa=Gt(new o.ag((Ms.x+.5)/na,(Ms.y+.5)/na));_r=Xa>.85?1:Xa}if(!X&&!We){const na=Math.sqrt(mn*mn+vn*vn+kn*kn);let Xa=(1<0;){const Ms=fs.pop(),mn=Ms.x,vn=Ms.y;let kn=Ms.fullyVisible;const _r=()=>this.projection.name==="globe"&&(Ms.y===0||Ms.y===(1<cr)continue;let dr=0;if(!kn){let Yr=Ot?Ms.aabb.intersectsPrecise(tt):Ms.aabb.intersectsPreciseFlat(tt);if(Yr===0&&_r()){const na=new o.cn(Ms.zoom,mn,vn);Yr=o.co(this,Ne,na,!0).intersectsPrecise(tt)}if(Yr===0)continue;if(w.calculateQuadrantVisibility)if(tt.containsPoint(Ms.aabb.center))dr=15;else for(let na=0;na<4;na++)Ms.aabb.quadrant(na).intersects(tt)!==0&&(dr|=1<>1),ra={aabb:X?Ms.aabb.quadrant(cr):o.cp(this,Ne,Ms.zoom+1,dr,Bn,Ms.wrap,Ms.minZ,Ms.maxZ,this.projection),zoom:Ms.zoom+1,x:dr,y:Bn,wrap:Ms.wrap,fullyVisible:kn,tileID:void 0,shouldSplit:void 0,minZ:Ms.minZ,maxZ:Ms.maxZ};Z&&!We&&(ra.tileID=new o.aR(Ms.zoom+1===As?gn:Ms.zoom+1,Ms.wrap,Ms.zoom+1,dr,Bn),Dn(ra)),fs.push(ra)}}if(this.fogCullDistSq){const Ms=this.fogCullDistSq,mn=this.horizonLineFromTop();Ws=Ws.filter(vn=>{const kn=[0,0,0,1],_r=[o.an,o.an,0,1],cr=this.calculateFogTileMatrix(vn.tileID.toUnwrapped());o.aE(kn,kn,cr),o.aE(_r,_r,cr);const dr=o.cq([],kn,_r),Bn=o.cr([],kn,_r),ra=o.cK(dr,Bn);if(ra===0)return!0;let wa=!1;const Yr=this._elevation;if(Yr&&ra>Ms&&mn!==0){const na=this.calculateProjMatrix(vn.tileID.toUnwrapped());let Xa;w.isTerrainDEM||(Xa=Yr.getMinMaxForTile(vn.tileID)),Xa||(Xa={min:ss,max:ks});const pi=o.cs(this.rotation),oi=[pi[0]*o.an,pi[1]*o.an,Xa.max];o.ah(oi,oi,na),wa=(1-oi[1])*this.height*.5Ms.distanceSq-mn.distanceSq).map(Ms=>Ms.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,H;const Z=this.centerPoint;if(this.projection.name==="globe"){const oe=this.worldSize;F=(E.x-Z.x)/oe,H=(E.y-Z.y)/oe}else{const oe=this.pointCoordinate(E),xe=this.pointCoordinate(Z);F=oe.x-xe.x,H=oe.y-xe.y}const X=this.locationCoordinate(w);this.setLocation(new o.ag(X.x-F,X.y-H))}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,H=this.projection.project(w.lng,w.lat);return new o.ag(H.x,H.y,F)}coordinateLocation(w){return this.projection.unproject(w.x,w.y)}pointRayIntersection(w,E){const F=E??this._centerAltitude,H=[w.x,w.y,0,1],Z=[w.x,w.y,1,1];o.aE(H,H,this.pixelMatrixInverse),o.aE(Z,Z,this.pixelMatrixInverse);const X=Z[3];o.cu(H,H,1/H[3]),o.cu(Z,Z,1/X);const oe=H[2],xe=Z[2];return{p0:H,p1:Z,t:oe===xe?0:(F-oe)/(xe-oe)}}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:H}=w,Z=o.bU(E[2],this._center.lat),X=o.bU(F[2],this._center.lat);return new o.ag(o.am(E[0],F[0],H)/this.worldSize,o.am(E[1],F[1],H)/this.worldSize,o.am(Z,X,H))}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 H=0,Z=this.horizonLineFromTop();if(w.y>Z)return this.pointCoordinate(w,E);const X=.02*Z,oe=w.clone();for(let xe=0;xe<10&&Z-H>X;xe++){oe.y=o.am(H,Z,.66);const Ne=this.projection.pointCoordinate3D(this,oe.x,oe.y);Ne?(Z=oe.y,F=Ne):H=oe.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,H=[w.x*this.worldSize,w.y*this.worldSize,F+w.toAltitude(),1];return o.aE(H,H,this.pixelMatrix),H[3]>0?new o.P(H[0]/H[3],H[1]/H[3]):new o.P(Number.MAX_VALUE,Number.MAX_VALUE)}_getBoundsNonRectangular(){const{top:w,left:E}=this._edgeInsets,F=this.height-this._edgeInsets.bottom,H=this.width-this._edgeInsets.right,Z=this.pointLocation3D(new o.P(E,w)),X=this.pointLocation3D(new o.P(H,w)),oe=this.pointLocation3D(new o.P(H,F)),xe=this.pointLocation3D(new o.P(E,F));let Ne=Math.min(Z.lng,X.lng,oe.lng,xe.lng),Le=Math.max(Z.lng,X.lng,oe.lng,xe.lng),We=Math.min(Z.lat,X.lat,oe.lat,xe.lat),He=Math.max(Z.lat,X.lat,oe.lat,xe.lat);const tt=Math.pow(2,-this.zoom)/16*270,dt=this.projection.name==="globe"?1:4,it=(jt,wt,Ot,Vt,Ct)=>{const ks=(jt+Ot)/2,ss=(wt+Vt)/2,Ns=new o.P(ks,ss),{lng:Gt,lat:es}=this.pointLocation3D(Ns),fs=Math.max(0,Ne-Gt,We-es,Gt-Le,es-He);Ne=Math.min(Ne,Gt),Le=Math.max(Le,Gt),We=Math.min(We,es),He=Math.max(He,es),(Cttt)&&(it(jt,wt,ks,ss,Ct+1),it(ks,ss,Ot,Vt,Ct+1))};if(it(E,w,H,w,1),it(H,w,H,F,1),it(H,F,E,F,1),it(E,F,E,w,1),this.projection.name==="globe"){const[jt,wt]=o.cw(this);jt?(He=90,Le=180,Ne=-180):wt&&(We=-90,Le=180,Ne=-180)}return new o.aK(new o.aU(Ne,We),new o.aU(Le,He))}_getBoundsRectangular(w,E){const{top:F,left:H}=this._edgeInsets,Z=this.height-this._edgeInsets.bottom,X=this.width-this._edgeInsets.right,oe=new o.P(H,F),xe=new o.P(X,F),Ne=new o.P(X,Z),Le=new o.P(H,Z);let We=this.pointCoordinate(oe,w),He=this.pointCoordinate(xe,w);const tt=this.pointCoordinate(Ne,E),dt=this.pointCoordinate(Le,E),it=(jt,wt)=>(wt.y-jt.y)/(wt.x-jt.x);return We.y>1&&He.y>=0?We=new o.ag((1-dt.y)/it(dt,We)+dt.x,1):We.y<0&&He.y<=1&&(We=new o.ag(-dt.y/it(dt,We)+dt.x,0)),He.y>1&&We.y>=0?He=new o.ag((1-tt.y)/it(tt,He)+tt.x,1):He.y<0&&We.y<=1&&(He=new o.ag(-tt.y/it(tt,He)+tt.x,0)),new o.aK().extend(this.coordinateLocation(We)).extend(this.coordinateLocation(He)).extend(this.coordinateLocation(dt)).extend(this.coordinateLocation(tt))}_getBoundsRectangularTerrain(){const w=this.elevation;if(!w.visibleDemTiles.length||w.isUsingMockSource())return this._getBoundsRectangular(0,0);const E=w.visibleDemTiles.reduce((F,H)=>{if(H.dem){const Z=H.dem.tree;F.min=Math.min(F.min,Z.minimums[0]),F.max=Math.max(F.max,Z.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.maxLngWe&&(oe=We-Ne),We-Lett&&(X=tt-xe),tt-He{for(let en=0;en<16;en++)gn[en]=o.am(an[en],Dn[en],Gn)})(oe,oe,xe,o.cL(this.pitch>=fh?1:this.pitch/fh))}else oe=xe;const Ne=o.cz([],xe,X);let Le=o.cz([],oe,X);if(this.projection.isReprojectedInTileSpace){const es=this.locationCoordinate(this.center),fs=o.b9([]);o.bx(fs,fs,[es.x*this.worldSize,es.y*this.worldSize,0]),o.aD(fs,fs,o.cA(this)),o.bx(fs,fs,[-es.x*this.worldSize,-es.y*this.worldSize,0]),o.aD(Le,Le,fs),o.aD(Ne,Ne,fs),this.inverseAdjustmentMatrix=o.cB(this)}else this.inverseAdjustmentMatrix=[1,0,0,1];if(this.mercatorMatrix=o.cC([],Le,[this.worldSize,this.worldSize,this.worldSize/Z,1]),this.projMatrix=Le,this.invProjMatrix=o.b7(new Float64Array(16),this.projMatrix),E){const es=this._camera.getCameraToClipPerspective(this._fov,this.width/this.height,this._nearZ,1/0);es[8]=2*-w.x/this.width,es[9]=2*w.y/this.height,this.expandedFarZProjMatrix=o.cz([],es,X)}else this.expandedFarZProjMatrix=this.projMatrix;const We=o.b7([],oe);this.frustumCorners=o.cD.fromInvProjectionMatrix(We,this.horizonLineFromTop(),this.height),this.cameraFrustum=o.cl.fromInvProjectionMatrix(this.invProjMatrix,this.worldSize,0,!E);const He=new Float32Array(16);o.b9(He),o.cC(He,He,[1,-1,1]),o.cE(He,He,this._pitch),o.ba(He,He,this.angle);const tt=o.bS(new Float32Array(16),this._fov,this.width/this.height,this._nearZ,this._farZ);this.starsProjMatrix=o.b8(tt);const dt=(Math.PI/2-this._pitch)*(this.height/this._fov)*this._horizonShift;tt[8]=2*-w.x/this.width,tt[9]=2*(w.y+dt)/this.height,this.skyboxMatrix=o.aD(He,tt,He);const it=this.point,jt=it.x,wt=it.y,Ot=this.width%2/2,Vt=this.height%2/2,Ct=Math.cos(this.angle),ks=Math.sin(this.angle),ss=jt-Math.round(jt)+Ct*Ot+ks*Vt,Ns=wt-Math.round(wt)+Ct*Vt+ks*Ot,Gt=new Float64Array(Le);if(o.bx(Gt,Gt,[ss>.5?ss-1:ss,Ns>.5?Ns-1:Ns,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,Ne),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 es=[this.globeMatrix[12],this.globeMatrix[13],this.globeMatrix[14]];this.globeCenterInViewSpace=o.ah(es,es,X),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,H=1/this.height/this._pixelsPerMercatorPixel,Z=[w,w,E];o.bJ(Z,Z,H),o.bJ(F,F,-1),o.cG(F,F,Z);const X=o.bb();o.bx(X,X,F),o.cC(X,X,Z),this.mercatorFogMatrix=X,this.worldToFogMatrix=this._camera.getWorldToCameraPosition(w,E,H)}_computeCameraPosition(w){const E=(w=w||this.pixelsPerMeter)/this.pixelsPerMeter,F=this._camera.forward(),H=this.point,Z=this._mercatorZfromZoom(this._seaLevelZoom?this._seaLevelZoom:this._zoom)*E-w/this.worldSize*this._centerAltitude;return[H.x/this.worldSize-F[0]*Z,H.y/this.worldSize-F[1]*Z,w/this.worldSize*this._centerAltitude-F[2]*Z]}_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],H=w[2];let Z=1;this.projection.wrap&&(this.center=this.center.wrap()),H>0&&(Z=Math.min((E-F)/H,1)),this._camera.position=o.bg([],this._camera.position,w,Z),this._updateStateFromCamera()}_updateStateFromCamera(){const w=this._camera.position,E=this._camera.forward(),{pitch:F,bearing:H}=this._camera.getPitchBearing(),Z=o.bU(this._centerAltitude,this.center.lat)*this._pixelsPerMercatorPixel,X=this._mercatorZfromZoom(this._maxZoom)*Math.cos(o.ap(this._maxPitch)),oe=Math.max((w[2]-Z)/Math.cos(F),X),xe=this._zoomFromMercatorZ(oe);o.bg(w,w,E,oe),this._pitch=o.aC(F,o.ap(this.minPitch),o.ap(this.maxPitch)),this.angle=o.bs(H,-Math.PI,Math.PI),this._setZoom(o.aC(xe,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,H=0,Z=1/0;for(;F-E>1e-6&&F>E;){const X=E+.5*(F-E),oe=this.tileSize*Math.pow(2,X),xe=this.getCameraToCenterDistance(this.projection,X,oe),Ne=this.scaleZoom(xe/(Math.max(0,w)*this.tileSize)),Le=Math.abs(X-Ne);LeNe||He.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)),H=this._zoomFromMercatorZ(F)+E;return F-this._mercatorZfromZoom(H)}getCameraPoint(){if(this.projection.name==="globe"){const w=function([E,F,H],Z){const X=[E,F,H,1];o.aE(X,X,Z);const oe=X[3]=Math.max(X[3],1e-6);return X[0]/=oe,X[1]/=oe,X[2]/=oe,X}([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 H=o.cy(w,E,this.width,this.height,1024),Z=w.pixelSpaceConversion(this.center.lat,F,H);let X=.5/Math.tan(.5*this._fov)*this.height*Z;return this.isOrthographic&&(X=o.am(1,X,o.cL(this.pitch>=fh?1:this.pitch/fh))),X}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 Qc=(R,w)=>{if(w>0&&R.terrain&&o.w("Cutoff is currently disabled on terrain"),w<=0||R.terrain)return{shouldRenderCutoff:!1,uniformValues:{u_cutoff_params:[0,0,0,1]}};const E=R.transform,F=E.pitch,H=E.isLODDisabled(!1)?60:30;if(F0,uniformValues:{u_cutoff_params:[E._nearZ,E._farZ,(Le-E._nearZ)/Z,(Le-He-E._nearZ)/Z]}}},mp=2048;class Nv{constructor(w,E){this.aabb=w,this.lastCascade=E}}class kv{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 Nv(E,null)}clear(){this.receivers={}}get(w){return this.receivers[w.key]}computeRequiredCascades(w,E,F){const H=o.cU.fromPoints(w.points);let Z=0;for(const X in this.receivers){const oe=this.receivers[X];if(!oe||!H.intersectsAabb(oe.aabb))continue;oe.aabb.min=H.closestPoint(oe.aabb.min),oe.aabb.max=H.closestPoint(oe.aabb.max);const xe=oe.aabb.getCorners();for(let Ne=0;Ne1||He[1]<-1||He[1]>1){Le=!1;break}}if(oe.lastCascade=Ne,Z=Math.max(Z,Ne),Le)break}}return Z+1}}class Ac{constructor(w){this.painter=w,this._enabled=!1,this._drawShadowAfterLayer=-1,this._numCascadesToRender=0,this._cascades=[],this._groundShadowTiles=[],this._receivers=new kv,this._depthMode=new qr(w.context.gl.LEQUAL,qr.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 H=E.properties.get("shadow-intensity"),Z=E.properties.get("shadow-draw-before-layer");if(!E.shadowsEnabled()||H<=0)return;let X=-1,oe=0;for(const wt of F.style.order){const Ot=F.style._mergedLayers[wt];Ot.hasShadowPass()&&!Ot.isHidden(w.zoom)&&(X=oe),!Z||Z!==wt&&Z!==Ot.slot||(this._drawShadowAfterLayer=oe>0?oe-1:0),oe+=1}if(this._enabled=X>=0,!this.enabled)return;this._drawShadowAfterLayer<0&&(this._drawShadowAfterLayer=X);const xe=F.context,Ne=mp,Le=mp;if(this._cascades.length===0||mp!==this._cascades[0].texture.size[0]){this._cascades=[];for(let wt=0;wt<2;++wt){const Ot=xe.gl,Vt=xe.createFramebuffer(Ne,Le,0,"texture"),Ct=new o.T(xe,{width:Ne,height:Le,data:null},Ot.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=O0(E);let We=0;if(w.elevation){const wt=w.elevation,Ot=[1e4,-1e4];wt.visibleDemTiles.filter(Vt=>Vt.dem).forEach(Vt=>{const Ct=Vt.dem.tree;Ot[0]=Math.min(Ot[0],Ct.minimums[0]),Ot[1]=Math.max(Ot[1],Ct.maximums[0])}),Ot[0]!==1e4&&(We=(Ot[1]-Ot[0])*wt.exaggeration())}const He=1.5*w.cameraToCenterDistance,tt=3*He,dt=new Float64Array(16);for(let wt=0;wt=0)return{};const Z=function(xe,Ne,Le){const We=Le/(1<0&&(o.cT(Z[1],Z[1],[H[0]*X,0,0]),o.cT(Z[2],Z[2],[H[0]*X,0,0])),H[1]<0?(o.cT(Z[0],Z[0],[0,H[1]*X,0]),o.cT(Z[1],Z[1],[0,H[1]*X,0])):H[1]>0&&(o.cT(Z[2],Z[2],[0,H[1]*X,0]),o.cT(Z[3],Z[3],[0,H[1]*X,0]));const oe={};return oe.vertices=Z,oe.planes=[Wx(Z[1],Z[0],Z[4]),Wx(Z[2],Z[1],Z[5]),Wx(Z[3],Z[2],Z[6]),Wx(Z[0],Z[3],Z[7])],oe}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 Wx(R,w,E){const F=o.ax([],E,w),H=o.ax([],R,w),Z=o.bh([],F,H),X=o.ai(Z);return X===0?[0,0,1,0]:(o.bJ(Z,Z,1/X),[Z[0],Z[1],Z[2],-o.bi(Z,w)])}function O0(R){const w=R.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 xh(R,w,E){const F=w.properties.get("color-use-theme")==="none",H=w.properties.get("color"),Z=w.properties.get("intensity"),X=w.properties.get("direction"),oe=[X.x,X.y,X.z],xe=E.properties.get("color-use-theme")==="none",Ne=E.properties.get("color"),Le=E.properties.get("intensity"),We=Math.max(o.bi([0,0,1],oe),0),He=[0,0,0];o.bJ(He,Ne.toPremultipliedRenderColor(xe?null:R.getLut(w.scope)).toArray01Linear().slice(0,3),Le);const tt=[0,0,0];return o.bJ(tt,H.toPremultipliedRenderColor(F?null:R.getLut(E.scope)).toArray01Linear().slice(0,3),We*Z),o.cW([He[0]>0?He[0]/(He[0]+tt[0]):0,He[1]>0?He[1]/(He[1]+tt[1]):0,He[2]>0?He[2]/(He[2]+tt[2]):0])}function Ff(R,w,E,F,H,Z){const X=R.zoom,oe=R.scale,xe=R.worldSize,Ne=1/xe,Le=R.aspect,We=Math.sqrt(1+Le*Le)*Math.tan(.5*R.fovX),He=We*We,tt=F-E,dt=F+E;let it,jt;He>tt/dt?(it=F,jt=F*We):(it=.5*dt*(1+He),jt=.5*Math.sqrt(tt*tt+2*(F*F+E*E)*He+dt*dt*He*He));const wt=R.projection.pixelsPerMeter(R.center.lat,xe),Ot=R._camera.getCameraToWorldMercator(),Vt=[0,0,-it*Ne];o.ah(Vt,Vt,Ot);let Ct=jt*Ne;const ks=function(kn){return kn[0]/=oe,kn[1]/=oe,kn[2]=o.bU(kn[2],R._center.lat),kn},ss=R._edgeInsets;if(!(ss.left===0&&ss.top===0&&ss.right===0&&ss.bottom===0||ss.left===ss.right&&ss.top===ss.bottom)){const kn=R._camera.getWorldToCamera(R.worldSize,R.projection.zAxisUnit==="meters"?wt:1),_r=R._camera.getCameraToClipPerspective(R._fov,R.width/R.height,E,F);_r[8]=2*-R.centerOffset.x/R.width,_r[9]=2*R.centerOffset.y/R.height;const cr=new Float64Array(16);o.cz(cr,_r,kn);const dr=new Float64Array(16);o.b7(dr,cr);const Bn=o.cl.fromInvProjectionMatrix(dr,xe,X,!0);for(const ra of Bn.points){const wa=ks(ra);Ct=Math.max(Ct,o.bK(o.cV([],Vt,wa)))}}Ct*=H/(H-1);const Ns=Math.acos(w[2]),Gt=Math.atan2(-w[0],-w[1]),es=new Of;es.position=Vt,es.setPitchBearing(Ns,Gt);const fs=es.getWorldToCamera(xe,wt),Ws=Ct*xe,As=Math.min(R._mercatorZfromZoom(17)*xe*-2,-2*Ws),gn=es.getCameraToClipOrthographic(-Ws,Ws,-Ws,Ws,As,(Ws+Z*wt)/w[2]),an=new Float64Array(16);o.aD(an,gn,fs);const Dn=o.cQ(Math.floor(1e6*Vt[0])/1e6*xe,Math.floor(1e6*Vt[1])/1e6*xe,0),Gn=.5*H,en=[0,0,0];o.ah(en,Dn,an),o.bJ(en,en,Gn);const Ms=[Math.floor(en[0]),Math.floor(en[1]),Math.floor(en[2])],mn=[0,0,0];o.ax(mn,en,Ms),o.bJ(mn,mn,-1/Gn);const vn=new Float64Array(16);return o.b9(vn),o.bx(vn,vn,mn),o.aD(an,vn,an),[an,Ws]}class P1 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 H=o.cY(F),Z=new o.cZ(w,E,void 0,void 0,H);return Z.computeBoundsAndApplyParent(),Z}).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 H=Object.keys(w),Z=[],X=[];for(const oe of H){const xe=w[oe];this.hasURLBeenRequested(xe)&&!F.forceReload||(this.modelByURL[xe]={modelId:oe,scope:E},Z.push(this.loadModel(oe,xe)),X.push(oe)),this.models[E][oe]||(this.models[E][oe]={model:null,numReferences:1})}this.numModelsLoading[E]=(this.numModelsLoading[E]||0)+X.length,Promise.allSettled(Z).then(oe=>{for(let xe=0;xe{this.fire(new o.B(new Error(`Could not load models: ${oe.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 H=this.requestManager.normalizeModelURL(E);if((this.hasModel(w,F,{exactIdMatch:!0})||this.hasModelBeenAdded(w,F))&&this.modelUris[F][w]===H)this.models[F][w].numReferences++;else if(this.hasURLBeenRequested(H)){const{scope:Z,modelId:X}=this.modelByURL[H];this.models[Z][X].numReferences++}else this.modelUris[F][w]=H,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 H in w)F[H]=this.requestManager.normalizeModelURL(w[H])}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 H of w)this.hasModel(H,E,{exactIdMatch:!0})||this.hasURLBeenRequested(H)?this.models[E][H].numReferences++:this.modelUris[E][H]&&!this.hasURLBeenRequested(H)?F[H]=this.modelUris[E][H]:!this.hasURLBeenRequested(H)&&o.c_(H,!1)&&(this.modelUris[E][H]=this.requestManager.normalizeModelURL(H),F[H]=this.modelUris[E][H]);this.load(F,E)}hasURLBeenRequested(w){return this.modelByURL[w]!==void 0}removeModel(w,E,F=!1,H=!1){if(this.models[E]&&this.models[E][w]&&(this.models[E][w].numReferences--,this.models[E][w].numReferences===0||H)){const Z=this.modelUris[E][w];F||delete this.modelUris[E][w],delete this.modelByURL[Z];const X=this.models[E][w].model;if(!X)return;delete this.models[E][w],X.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 vu=o.a8.colorTheme,Zl=new o.ab({data:new o.ac(vu.data)});function tl(R){if(!R.metadata||!R.metadata.content_area)return;const w=o.o.devicePixelRatio,{left:E,top:F,width:H,height:Z}=R.metadata.content_area,X=E*w,oe=F*w;return[X,oe,X+H*w,oe+Z*w]}function Go(R){if(R)return R.map(([w,E])=>[w*o.o.devicePixelRatio,E*o.o.devicePixelRatio])}class Zd{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 Kp))return w;const H=E.map(X=>this.sourceCache.getTile(X)),Z=F.getImages(H,Array.from(this.pendingRequests));for(const[X,oe]of Z)w.set(o.I.from({name:X,iconsetId:this.id}),oe),this.pendingRequests.delete(X);for(const X of this.pendingRequests)this.missingRequests.add(X);return this.pendingRequests.clear(),w}}class Jc{constructor(){this._previousClosestBuildingId=null,this._hysteresisRatio=.8,this._indoorMinimumZoom=16}findClosestBuilding(w,E,F,H,Z){if(Fxe*this._hysteresisRatio&&(X=this._previousClosestBuildingId):Ne&&!X&&(X=this._previousClosestBuildingId),this._previousClosestBuildingId=X,X}_calculateDistance(w,E){if(!E.center)return Number.MAX_VALUE;const F=w.lat-E.center[1],H=w.lng-E.center[0];return F*F+H*H}_isBuildingVisible(w,E,F){if(!F)return!1;for(const H of w.floorIds){const Z=w.floors[H];if(!Z.geometry)continue;const X=Z.geometry;if(X.type==="Polygon"){const oe=this._convertRingToPoints(X.coordinates[0]);if(o.bw(oe,F))return!0}else if(X.type==="MultiPolygon"){const oe=this._convertMultiPolygonToPoints(X.coordinates);if(o.d0(F,oe))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 Kx 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 Jc,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,H]of Object.entries(w.buildings))if(this._buildings[F])for(const Z of H.floorIds)this._buildings[F].floorIds.add(Z),this._buildings[F].floors[Z]?this._mergeFloors(this._buildings[F].floors[Z],H.floors[Z]):(this._buildings[F].floors[Z]=H.floors[Z],E=!0);else this._buildings[F]=H,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 H=null;for(const X of F.floorIds)if(this._activeFloors&&this._activeFloors.has(X)){H=X;break}const Z=Array.from(F.floorIds).map(X=>({id:X,name:F.floors[X].name,zIndex:F.floors[X].zIndex})).sort((X,oe)=>oe.zIndex-X.zIndex).filter((X,oe,xe)=>oe===0||X.zIndex!==xe[oe-1].zIndex);return{selectedFloorId:H,activeFloorsVisible:!!this._indoorState&&this._indoorState.activeFloorsVisible,floors:Z}}_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 H of E)if(!F.has(H))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(H=>new o.P(H.lng,H.lat))}}const F0=(R,w)=>Hn(R,w&&w.filter(E=>E.identifier!=="source.canvas")),gh=o.aJ(Ti,["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"]),Xb=o.aJ(Ti,["setCenter","setZoom","setBearing","setPitch"]),Tw=new Set(["background","sky","slot","custom"]),Qb={version:8,layers:[],sources:{}},Yx={duration:300,delay:0};class bu 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({},Yx),this._buildingIndex=new lp(this),this.crossTileSymbolIndex=new Rf,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 Ke,this._hasDataDrivenEmissive=!1,this.indoorManager=new Kx(this),this.dispatcher=E.dispatcher?E.dispatcher:new nt(Mt(),this),this.map.painter&&this.map.painter.context){const H=this.map.painter.context.maxUniformBufferBindings,Z=Math.floor(this.map.painter.context.maxUniformBlockSize/4);this.dispatcher.broadcast("setContextParams",{maxBindingPoints:H,maxUniformBlockSizeDwords:Z,disableSymbolUBO:this.map.painter.context.disableSymbolUBO})}E.imageManager?this.imageManager=E.imageManager:(this.imageManager=new Ft(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 P1(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=bu.registerForPluginStateChange(H=>{F.dispatcher.broadcast("syncRTLPluginState",{pluginStatus:H.pluginStatus,pluginURL:H.pluginURL},(Z,X)=>{if(o.d6(Z),X&&X.every(oe=>oe))for(const oe in F._sourceCaches){const xe=F._sourceCaches[oe],Ne=xe.getSource().type;Ne!=="vector"&&Ne!=="geojson"||xe.reload()}})}),this.on("data",H=>{if(H.dataType!=="source"||H.sourceDataType!=="metadata")return;const Z=this.getOwnSource(H.sourceId);if(Z&&Z.vectorLayerIds)for(const X in this._layers){const oe=this._layers[X];oe.source===Z.id&&this._validateLayer(oe)}})}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 H=(Z,X)=>{try{X(null,this.setState(Z,F))}catch(oe){X(oe,!1)}};if(typeof w=="string"){const Z=this.map._requestManager.normalizeStyleURL(w),X=this.map._requestManager.transformRequest(Z,o.R.Style);o.m(X,(oe,xe)=>{oe?this.fire(new o.B(oe)):xe&&H(xe,E)})}else typeof w=="object"&&H(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 H=this.importsCache.get(w);if(H)return this._load(H,F);const Z=this.map._requestManager.transformRequest(w,o.R.Style);this._request=o.m(Z,(X,oe)=>{if(this._request=null,X)this.fire(new o.B(X));else if(oe)return this.importsCache.set(w,oe),this._load(oe,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(Qb,!1)}_loadImports(w,E,F){if(this.importDepth>=4)return o.w("Style doesn't support nesting deeper than 5"),Promise.resolve();const H=[];for(const Z of w){const X=this._createFragmentStyle(Z),oe=new Promise(Le=>{X.once("style.import.load",Le),X.once("error",Le)}).then(()=>{this.mergeAll(),this.fire(new o.C("data",{dataType:"style"}))});if(H.push(oe),this.resolvedImports.has(Z.url)){X.loadEmpty();continue}const xe=Z.data||this.importsCache.get(Z.url);xe?(Z.data?(X.fire(new o.C("dataloading",{dataType:"style"})),X.globalId=X._getGlobalId(xe),queueMicrotask(()=>X._load(xe,E))):X.loadJSON(xe,{validate:E}),this._isInternalStyle(xe)&&(X.globalId=null)):Z.url?X.loadURL(Z.url,{validate:E}):X.loadEmpty();const Ne={style:X,id:Z.id,config:Z.config};if(F){const Le=this.fragments.findIndex(({id:We})=>We===F);this.fragments=this.fragments.slice(0,Le).concat(Ne).concat(this.fragments.slice(Le))}else this.fragments.push(Ne)}return Promise.allSettled(H)}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 H=this._initialConfig&&this._initialConfig[E];(w.config||H)&&(F=Object.assign({},w.config,H));const Z=new bu(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 Z.setEventedParent(this.map,{style:Z}),Z}_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 Z=Object.assign({},Qb,{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(Z,E)}if(this.updateConfig(this._config,w.schema),E&&F0(this,ln(w)))return;this._loaded=!0;for(const Z in w.sources)this.addSource(Z,w.sources[Z],{validate:!1,isInitialLoad:!0});this.stylesheet=o.d9(w);const F=()=>{if(w.iconsets)for(const xe in w.iconsets)this.addIconset(xe,w.iconsets[xe]);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 Z=Kd(this.stylesheet.layers);if(this._order=Z.map(xe=>xe.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 xe=this.stylesheet.lights[0];this.light=new Or(xe.properties,xe.id)}else this.setLights(this.stylesheet.lights);this.light||(this.light=new Or(this.stylesheet.light)),this._layers={};for(const xe of Z){const Ne=o.de(xe,this.scope,this._styleColorTheme.lut,this.options);Ne.expressionDependencies.configDependencies.size!==0&&this._configDependentLayers.add(Ne.fqid),Ne.expressionDependencies.isIndoorDependent&&this._indoorDependentLayers.add(Ne.fqid),this._hasAppearances=this._hasAppearances||Ne.getAppearances().length!==0,Ne.setEventedParent(this,{layer:{id:Ne.id}}),this._layers[Ne.id]=Ne;const Le=this.getOwnLayerSourceCache(Ne),We=!!this.directionalLight&&this.directionalLight.shadowsEnabled();Le&&Ne.canCastShadows()&&We&&(Le.castsShadows=!0)}if(this.glyphManager.url){const xe=new Set;for(const Ne in this._layers){const Le=this._layers[Ne];if(Le.type==="symbol"&&Le.layout){const We=Le.layout.get("text-font");We&&We.value&&We.value.kind==="constant"&&xe.add(We.value.value.join(","))}}for(const Ne of xe)this.glyphManager.prefetchRange(Ne,0)}this.stylesheet.featuresets&&this.setFeaturesetSelectors(this.stylesheet.featuresets),this.stylesheet.models&&this.addModelURLs(this.stylesheet.models);const X=this.stylesheet.terrain;X&&(this.checkCanvasFingerprintNoise(),this.disableElevatedTerrain||this.terrainSetForDrapingOnly()||this._createTerrain(X,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 oe=this.isRootStyle();w.imports?this._loadImports(w.imports,E).then(()=>{this._reloadImports(),this.fire(new o.C(oe?"style.load":"style.import.load"))}).catch(xe=>{this.fire(new o.B(new Error("Failed to load imports",xe))),this.fire(new o.C(oe?"style.load":"style.import.load"))}):(this._reloadImports(),this.fire(new o.C(oe?"style.load":"style.import.load")))};this._styleColorTheme.colorTheme=this.stylesheet["color-theme"];const H=this._styleColorTheme.colorThemeOverride?this._styleColorTheme.colorThemeOverride:this._styleColorTheme.colorTheme;if(H){const Z=this._evaluateColorThemeData(H);this._loadColorTheme(Z).then(()=>{F()}).catch(X=>{o.w(`Couldn't load color theme from the stylesheet: ${X}`),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,H,Z,X,oe,xe,Ne,Le;const We={};this.terrain&&this.terrain.scope!==this.scope&&delete this.terrain,this.forEachFragmentStyle(He=>{if(He.stylesheet){if(He.light!=null&&(w=He.light),He.stylesheet.lights)for(const tt of He.stylesheet.lights)tt.type==="ambient"&&He.ambientLight!=null&&(E=He.ambientLight),tt.type==="directional"&&He.directionalLight!=null&&(F=He.directionalLight);H=this._prioritizeTerrain(H,He.terrain,He.stylesheet.terrain),He.stylesheet.fog&&He.fog!=null&&(Z=He.fog),He.stylesheet.snow&&He.snow!=null&&(X=He.snow),He.stylesheet.rain&&He.rain!=null&&(oe=He.rain),He.stylesheet.camera!=null&&(Le=He.stylesheet.camera),He.stylesheet.projection!=null&&(xe=He.stylesheet.projection),He.stylesheet.transition!=null&&(Ne=He.stylesheet.transition),We[He.scope]=He._styleColorTheme}}),this.light=w,this.ambientLight=E,this.directionalLight=F,this.fog=Z,this.snow=X,this.rain=oe,this._styleColorThemeForScope=We,H===null?delete this.terrain:this.terrain=H,this.camera=Le||{"camera-projection":"perspective"},this.projection=xe||{name:"mercator"},this.transition=Object.assign({},Yx,Ne),this.mergeSources(),this.mergeLayers(),this.mergeIndoor()}forEachFragmentStyle(w){const E=F=>{for(const H of F.fragments)E(H.style);w(F)};E(this)}_prioritizeTerrain(w,E,F){const H=w&&w.drapeRenderMode===0;return F===null?E&&E.drapeRenderMode===0?E:H?w:null:E!=null&&(!w||H||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={},H={};this.forEachFragmentStyle(Z=>{for(const X in Z._sourceCaches){const oe=o.F(X,Z.scope);w[oe]=Z._sourceCaches[X]}for(const X in Z._otherSourceCaches){const oe=o.F(X,Z.scope);E[oe]=Z._otherSourceCaches[X]}for(const X in Z._symbolSourceCaches){const oe=o.F(X,Z.scope);F[oe]=Z._symbolSourceCaches[X]}for(const X in Z._fillExtrusionSourceCaches){const oe=o.F(X,Z.scope);H[oe]=Z._fillExtrusionSourceCaches[X]}}),this._mergedSourceCaches=w,this._mergedOtherSourceCaches=E,this._mergedSymbolSourceCaches=F,this._mergedFillExtrusionSourceCaches=H}mergeIndoor(){this.forEachFragmentStyle(w=>{if(w.stylesheet&&w.stylesheet.indoor)for(const E of Object.values(w.stylesheet.indoor)){const F=E,H=o.F(F.sourceId,w.scope);this._mergedIndoor[H]=new Set(F.sourceLayers||[])}})}mergeLayers(){const w={},E=[],F={};this._mergedSlots=[],this._has3DLayers=!1,this._hasCircleLayers=!1,this._hasSymbolLayers=!1,this.forEachFragmentStyle(X=>{for(const oe of X._order){const xe=X._layers[oe];if(xe.type==="slot"){const Ne=o.da(oe);if(w[Ne])continue;w[Ne]=[]}xe.slot&&w[xe.slot]?w[xe.slot].push(xe):E.push(xe)}}),this._mergedOrder=[];let H=-1;const Z=(X=[])=>{for(const oe of X)if(oe.type==="slot"){const xe=o.da(oe.id);w[xe]&&Z(w[xe]),this._mergedSlots.push(xe)}else{const xe=o.F(oe.id,oe.scope);this._mergedOrder.push(xe),F[xe]=oe,oe.is3D(!!this.terrain)&&(this._has3DLayers=!0,H=this._mergedOrder.length-1),oe.type==="circle"&&(this._hasCircleLayers=!0),oe.type==="symbol"&&(this._hasSymbolLayers=!0),oe.type==="clip"&&(this._clipLayerPresent=!0)}};if(Z(E),this._has3DLayers){const X={};for(let oe=0;oeX[oe]-X[xe])}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,H){const Z=Object.assign({},F);for(const oe of Object.keys(vu))Z[oe]===void 0&&(Z[oe]=vu[oe].default);const X=new o.aa(Zl,E,new Map(H));return X.setTransitionOrValue(Z,H),X.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,H)=>{const Z="data:image/png;base64,";if(!w||w.length===0)return this._styleColorTheme.lut=null,this._styleColorTheme.lutLoading=!1,void F();let X=w;X.startsWith(Z)||(X=Z+X);const oe=o.I.from("mapbox-reserved-lut"),xe=new Image;xe.src=X,xe.onerror=()=>{this._styleColorTheme.lutLoading=!1,H(new Error("Failed to load image data"))},xe.onload=()=>{if(this._styleColorTheme.lutLoadingCorrelationID!==E)return void F();this._styleColorTheme.lutLoading=!1;const{width:Ne,height:Le,data:We}=o.o.getImageData(xe);if(Le>32)return void H(new Error("The height of the image must be less than or equal to 32 pixels."));if(Ne!==Le*Le)return void H(new Error("The width of the image must be equal to the height squared."));this.getImage(oe)&&this.removeImage(oe),this.addImage(oe,{data:new o.q({width:Ne,height:Le},We),pixelRatio:1,sdf:!1,usvg:!1,version:0});const He=this.imageManager.getImage(oe,this.scope);He?(this._styleColorTheme.lut={image:He.data,data:w},F()):H(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,H){let Z,X,oe;const xe=o.o.devicePixelRatio>1?"@2x":"";let Ne=o.m(F.transformRequest(F.normalizeSpriteURL(E,xe,".json"),o.R.SpriteJSON),(He,tt)=>{Ne=null,oe||(oe=He,Z=tt,We())}),Le=o.n(F.transformRequest(F.normalizeSpriteURL(E,xe,".png"),o.R.SpriteImage),(He,tt)=>{Le=null,oe||(oe=He,X=tt,We())});function We(){if(oe)H(oe);else if(Z&&X){const He=o.o.getImageData(X),tt={};for(const dt in Z){const{width:it,height:jt,x:wt,y:Ot,sdf:Vt,pixelRatio:Ct,stretchX:ks,stretchY:ss,content:Ns}=Z[dt],Gt=new o.q({width:it,height:jt});o.q.copy(He,Gt,{x:wt,y:Ot},{x:0,y:0},{width:it,height:jt},null),tt[dt]={data:Gt,pixelRatio:Ct!==void 0?Ct:1,sdf:Vt!==void 0&&Vt,stretchX:ks,stretchY:ss,content:Ns,usvg:!1,version:0}}H(null,tt)}}return{cancel(){Ne&&(Ne.cancel(),Ne=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 H=new Map;for(const Z in F)H.set(o.I.from(Z),F[Z]);this.addImages(H)}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 H=F.getSource();if(H.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`)));H.partial=!1;const Z=new Zd(w,this.scope,F);this.imageManager.addImageProvider(Z,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,H;this._spriteRequest=(H=(Z,X)=>{if(this._spriteRequest=null,Z)E?this._loadSprite(w):this.fire(new o.B(Z));else if(X){const oe=new Map;for(const xe in X)oe.set(o.I.from(xe),X[xe]);this.addImages(oe)}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),(Z,X)=>{if(Z)return void H(Z);const oe={},xe=o.c$(new o.a$(X));for(const Ne of xe.icons){const Le={version:1,pixelRatio:o.o.devicePixelRatio,content:tl(Ne),stretchX:Ne.metadata?Go(Ne.metadata.stretch_x_areas):void 0,stretchY:Ne.metadata?Go(Ne.metadata.stretch_y_areas):void 0,sdf:!1,usvg:!0,icon:Ne};oe[Ne.name]=Le}H(null,oe)}))}_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 H=this._layers[F];H&&H.type!=="custom"&&E.push(H.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 H=w.minzoom||0;H<(w.maxzoom||25.5);H++){const Z=w.getProgramIds();if(Z)for(const X of Z){const oe=w.getDefaultProgramParams(X,E.zoom,this._styleColorTheme.lut);oe&&(F.style=this,this.fog&&(F._fogVisible=!0,oe.overrideFog=!0,F.getOrCreateProgram(X,oe)),F._fogVisible=!1,oe.overrideFog=!1,F.getOrCreateProgram(X,oe),(this.stylesheet.terrain||this.stylesheet.projection&&this.stylesheet.projection.name==="globe")&&(oe.overrideRtt=!0,F.getOrCreateProgram(X,oe)))}}}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 H=!1;if(this._changes.isDirty()){const xe=this._changes.getLayerUpdatesByScope();for(const Ne in xe){const{updatedIds:Le,removedIds:We}=xe[Ne];(Le||We)&&(this._updateWorkerLayers(Ne,Le,We),H=!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 Z={};for(const xe in this._mergedSourceCaches){const Ne=this._mergedSourceCaches[xe];Z[xe]=Ne.used,Ne.used=!1,Ne.tileCoverLift=0}const X={};for(const xe of this._mergedOrder){const Ne=this._mergedLayers[xe];if((Ne.visibility!=="none"||Ne.hasTransition())&&Ne.recalculate(w,this._availableImages),!Ne.isHidden(w.zoom)){const Le=this.getLayerSourceCache(Ne);Le&&(Le.used=!0,Le.tileCoverLift=Math.max(Le.tileCoverLift,Ne.tileCoverLift()))}if(Ne.type==="fill-extrusion"){const Le=o.F(Ne.source,Ne.scope);if(Le in this._mergedFillExtrusionSourceCaches){const We=Ne.layout&&Ne.layout.get("source-max-zoom");if(We!=null){const He=X[Le];X[Le]=He==null?We:Math.min(He,We)}}}!this._precompileDone&&this._shouldPrecompile&&("requestIdleCallback"in window?requestIdleCallback(()=>{this.precompilePrograms(Ne,w)}):this.precompilePrograms(Ne,w))}this._shouldPrecompile&&(this._precompileDone=!0);for(const xe in this._mergedFillExtrusionSourceCaches)this._mergedFillExtrusionSourceCaches[xe].setMaxzoomOverride(X[xe]!=null?X[xe]:null);this.terrain&&H&&this.mergeLayers();const oe=this.imageManager.getPendingImageProviders();for(const xe of oe)xe.sourceCache.used=!0;for(const xe in Z){const Ne=this._mergedSourceCaches[xe];Z[xe]!==Ne.used&&Ne.getSource().fire(new o.C("data",{sourceDataType:"visibility",dataType:"source",sourceId:Ne.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(),H=this.getFragmentStyle(E.scope);H&&H.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 H=this.getFragmentStyle(w);H&&this.dispatcher.broadcast("updateLayers",{layers:E?H._serializeLayers(E):[],scope:w,removedIds:F||[],options:H.options})}setState(w,E){if(this._checkLoaded(),F0(this,ln(w)))return!1;(w=o.d9(w)).layers=Kd(w.layers);const F=function(X,oe){if(!X)return[{command:Ti.setStyle,args:[oe]}];let xe=[];try{if(!o.b6(X.version,oe.version))return[{command:Ti.setStyle,args:[oe]}];if(o.b6(X.center,oe.center)||xe.push({command:Ti.setCenter,args:[oe.center]}),o.b6(X.zoom,oe.zoom)||xe.push({command:Ti.setZoom,args:[oe.zoom]}),o.b6(X.bearing,oe.bearing)||xe.push({command:Ti.setBearing,args:[oe.bearing]}),o.b6(X.pitch,oe.pitch)||xe.push({command:Ti.setPitch,args:[oe.pitch]}),o.b6(X.sprite,oe.sprite)||xe.push({command:Ti.setSprite,args:[oe.sprite]}),o.b6(X.glyphs,oe.glyphs)||xe.push({command:Ti.setGlyphs,args:[oe.glyphs]}),o.b6(X.imports,oe.imports)||function(tt=[],dt=[],it){dt=dt||[];const jt=(tt=tt||[]).map(am),wt=dt.map(am),Ot=tt.reduce(Og,{}),Vt=dt.reduce(Og,{}),Ct=jt.slice();let ks,ss,Ns,Gt;for(ks=0,ss=0;ks{tt.source&&Ne[tt.source]?xe.push({command:Ti.removeLayer,args:[tt.id]}):We.push(tt)});let He=X.terrain;He&&Ne[He.source]&&(xe.push({command:Ti.setTerrain,args:[void 0]}),He=void 0),xe=xe.concat(Le),o.b6(He,oe.terrain)||xe.push({command:Ti.setTerrain,args:[oe.terrain]}),function(tt,dt,it){dt=dt||[];const jt=(tt=tt||[]).map(am),wt=dt.map(am),Ot=tt.reduce(Og,{}),Vt=dt.reduce(Og,{}),Ct=jt.slice(),ks=Object.create(null);let ss,Ns,Gt,es,fs,Ws,As;for(ss=0,Ns=0;ss!(X.command in Xb));if(F.length===0)return!1;const H=F.filter(X=>!(X.command in gh));if(H.length>0)throw new Error(`Unimplemented: ${H.map(X=>X.command).join(", ")}.`);const Z=[];return F.forEach(X=>{Z.push(this[X.command](...X.args))}),E&&Promise.all(Z).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(Gs,`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(Cr,`sources.${w}`,E,null,F))return;this.map&&this.map._collectResourceTiming&&(E.collectResourceTiming=!0);const H=Em(w,E,this.dispatcher,this);H.scope=this.scope,H.setEventedParent(this,()=>({isSourceLoaded:this._isSourceCacheLoaded(H.id),source:H.serialize(),sourceId:H.id}));const Z=X=>{const oe=(X===o.b4.Symbol?"symbol:":X===o.b4.FillExtrusion?"fill-extrusion:":"other:")+H.id,xe=o.F(oe,this.scope),Ne=this._sourceCaches[oe]=new ql(xe,H,X);X===o.b4.Symbol?this._symbolSourceCaches[H.id]=Ne:X===o.b4.FillExtrusion?this._fillExtrusionSourceCaches[H.id]=Ne:this._otherSourceCaches[H.id]=Ne,Ne.onAdd(this.map)};Z(o.b4.Other),E.type!=="vector"&&E.type!=="geojson"||(Z(o.b4.Symbol),E.type==="vector"&&Z(o.b4.FillExtrusion)),H.onAdd&&H.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 H in this._layers)if(this._layers[H].source===w)return this.fire(new o.B(new Error(`Source "${w}" cannot be removed while layer "${H}" 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 H=Object.entries(this.stylesheet.iconsets).find(([Z,X])=>X.type==="source"&&X.source===w);if(H)return this.fire(new o.B(new Error(`Source "${w}" cannot be removed while iconset "${H[0]}" is using it.`)))}const F=this.getOwnSourceCaches(w);for(const H of F){const Z=o.da(H.id);delete this._sourceCaches[Z],this._changes.discardSourceCacheUpdate(H.id),H.fire(new o.C("data",{sourceDataType:"metadata",dataType:"source",sourceId:H.getSource().id})),H.setEventedParent(null),H.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 H in F){const Z=F[H];if(Z.state!=="loaded"&&Z.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 Z of w){if(this._validate(ot,"lights",Z))return;switch(Z.type){case"ambient":if(this.ambientLight){const X=this.ambientLight;X.set(Z),X.updateTransitions(E)}else this.ambientLight=new wn(Z,Ur(),this.scope,this.options);break;case"directional":if(this.directionalLight){const X=this.directionalLight;X.set(Z),X.updateTransitions(E)}else this.directionalLight=new wn(Z,yo(),this.scope,this.options)}}const F=Object.assign(E,{worldview:this.map.getWorldview()}),H=new o.ae(this.z||0,F);this.ambientLight&&this.ambientLight.recalculate(H),this.directionalLight&&this.directionalLight.recalculate(H),this._brightness=this.calculateLightsBrightness(),this.dispatcher.broadcast("setBrightness",this._brightness)}calculateLightsBrightness(){const w=this.directionalLight,E=this.ambientLight;if(!w||!E)return;const F=He=>.2126*(He[0]<=.03928?He[0]/12.92:Math.pow((He[0]+.055)/1.055,2.4))+.7152*(He[1]<=.03928?He[1]/12.92:Math.pow((He[1]+.055)/1.055,2.4))+.0722*(He[2]<=.03928?He[2]/12.92:Math.pow((He[2]+.055)/1.055,2.4)),H=w.properties.get("color").toNonPremultipliedRenderColor(null).toArray01(),Z=w.properties.get("intensity"),X=w.properties.get("direction"),oe=1-o.cP(X.x,X.y,X.z)[2]/90,xe=F(H)*Z*oe,Ne=E.properties.get("color").toNonPremultipliedRenderColor(null).toArray01(),Le=E.properties.get("intensity"),We=F(Ne)*Le;return Number(((xe+We)/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:Z})=>Z===E);if(!F)return;const H=o.da(w);return F.style.getFragmentStyle(H)}{const E=this.fragments.find(({id:F})=>F===w);return E?E.style:void 0}}setFeaturesetSelectors(w){if(!w)return;const E=(F,H="")=>`${F}::${H}`;this._featuresetSelectors={};for(const F in w){const H={},Z=this._featuresetSelectors[F]=[];for(const X of w[F].selectors){if(X.featureNamespace){const xe=this.getOwnLayer(X.layer);if(!xe){o.w(`Layer is undefined for selector: ${X.layer}`);continue}const Ne=E(xe.source,xe.sourceLayer);if(Ne in H&&H[Ne]!==X.featureNamespace){o.w(`"featureNamespace ${X.featureNamespace} of featureset ${F}'s selector is not associated to the same source, skip this selector`);continue}H[Ne]=X.featureNamespace}let oe;if(X.properties)for(const xe in X.properties){const Ne=o.X(X.properties[xe]);Ne.result==="success"&&(oe=oe||{},oe[xe]=Ne.value)}Z.push({layerId:X.layer,namespace:X.featureNamespace,properties:oe,uniqueFeatureID:X._uniqueFeatureID})}}}getFeaturesetDescriptors(w){const E=this.getFragmentStyle(w);if(!E||!E.stylesheet.featuresets)return[];const F=[];for(const H in E.stylesheet.featuresets)F.push({featuresetId:H,importId:E.scope?E.scope:void 0});return F}getFeaturesetLayers(w,E){const F=this.getFragmentStyle(E),H=F.stylesheet.featuresets;if(!H||!H[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 Z=[];for(const X of H[w].selectors){const oe=F.getOwnLayer(X.layer);oe&&Z.push(oe)}return Z}getConfigProperty(w,E){const F=this.getFragmentStyle(w);if(!F)return null;const H=o.F(E,F.scope),Z=F.options.get(H),X=Z?Z.value||Z.default:null;return X?X.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 H=this.getFragmentStyle(w);if(!H)return;const Z=H.stylesheet.schema;if(!Z||!Z[E])return;const X=o.X(F);if(X.result!=="success")return void F0(this,X.value);const oe=X.value.expression,xe=o.F(E,H.scope),Ne=H.options.get(xe);if(!Ne)return;let Le;const{minValue:We,maxValue:He,stepValue:tt,type:dt,values:it}=Z[E],jt=o.X(Z[E].default);jt.result==="success"&&(Le=jt.value.expression),Le?(this.options.set(xe,Object.assign({},Ne,{value:oe,default:Le,minValue:We,maxValue:He,stepValue:tt,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 H={};for(const Z in F){const X=o.F(Z,E.scope),oe=E.options.get(X),xe=oe?oe.value||oe.default:null;H[Z]=xe?xe.serialize():null}return H}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 H,Z;const X=o.X(E[F].default);if(X.result==="success"&&(H=X.value.expression),w&&w[F]!==void 0){const He=o.X(w[F]);He.result==="success"&&(Z=He.value.expression)}const{minValue:oe,maxValue:xe,stepValue:Ne,type:Le,values:We}=E[F];if(H){const He=o.F(F,this.scope);this.options.set(He,{default:H,value:Z,minValue:oe,maxValue:xe,stepValue:Ne,type:Le,values:We})}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 H=this.getLayer(F);H&&E(H)&&(H.possiblyEvaluateVisibility(),this._updateLayer(H),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 H=E._evaluateColorThemeData(F);(!E._styleColorTheme.lut&&H!==""||E._styleColorTheme.lut&&H!==E._styleColorTheme.lut.data)&&E.setColorTheme(F)}}),this._changes.setDirty()}addLayer(w,E,F={}){this._checkLoaded();const H=w.id;if(this._layers[H])return void this.fire(new o.B(new Error(`Layer with id "${H}" already exists on this map`)));let Z;if(w.type==="custom"){if(F0(this,o.dd(w)))return;Z=o.de(w,this.scope,this._styleColorTheme.lut,this.options)}else{if(typeof w.source=="object"&&(this.addSource(H,w.source),w=o.d9(w),w=Object.assign(w,{source:H})),this._validate(as,`layers.${H}`,w,{arrayIndex:-1},F))return;Z=o.de(w,this.scope,this._styleColorTheme.lut,this.options),this._validateLayer(Z),Z.setEventedParent(this,{layer:{id:H}})}const X=o.F(Z.source,Z.scope);Z.expressionDependencies.configDependencies.size!==0&&this._configDependentLayers.add(X),Z.expressionDependencies.isIndoorDependent&&this._indoorDependentLayers.add(X);let oe=this._order.length;if(E){const We=this._order.indexOf(E);if(We===-1)return void this.fire(new o.B(new Error(`Layer with id "${E}" does not exist on this map.`)));Z.slot&&Z.slot!==this._layers[E].slot?o.w(`Layer with id "${E}" has a different slot. Layers can only be rearranged within the same slot.`):oe=We}this._order.splice(oe,0,H),this._handleLayerOrderChange(),this._layers[H]=Z;const xe=this.getOwnLayerSourceCache(Z),Ne=!!this.directionalLight&&this.directionalLight.shadowsEnabled();xe&&Z.canCastShadows()&&Ne&&(xe.castsShadows=!0);const Le=this._changes.getRemovedLayer(Z);if(Le&&Z.source&&xe&&Z.type!=="custom"){this._changes.discardLayerRemoval(Z);const We=o.F(Z.source,Z.scope);Le.type!==Z.type?this._changes.updateSourceCache(We,"clear"):(this._changes.updateSourceCache(We,"reload"),xe.pause())}this._updateLayer(Z),Z.onAdd&&Z.onAdd(this.map),Z.scope=this.scope,this.mergeLayers()}moveLayer(w,E){this._checkLoaded();const F=this._checkLayer(w);if(!F||w===E)return;const H=this._order.indexOf(w);this._order.splice(H,1);let Z=this._order.length;if(E){const X=this._order.indexOf(E);if(X===-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.`):Z=X}this._order.splice(Z,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 H=this.getOwnLayerSourceCache(E);if(H&&H.castsShadows){let Z=!1;for(const X in this._layers)if(this._layers[X].source===E.source&&this._layers[X].canCastShadows()){Z=!0;break}H.castsShadows=Z}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 H=this._checkLayer(w);H&&(H.minzoom===E&&H.maxzoom===F||(E!=null&&(H.minzoom=E),F!=null&&(H.maxzoom=F),this._updateLayer(H)))}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 H=this._checkLayer(w);if(H&&!o.b6(H.filter,E))return E==null?(H.filter=void 0,void this._updateLayer(H)):void(this._validate(Ls,`layers.${H.id}.filter`,E,{layerType:H.type},F)||(H.filter=o.d9(E),this._updateLayer(H)))}getFilter(w){const E=this._checkLayer(w);if(E)return o.d9(E.filter)}setLayoutProperty(w,E,F,H={}){this._checkLoaded();const Z=this._checkLayer(w);if(Z&&!o.b6(Z.getLayoutProperty(E),F)){if(F!=null&&(!H||H.validate!==!1)&&F0(Z,qt.call(ln,{key:`layers.${w}.layout.${E}`,layerType:Z.type,objectKey:E,value:F,styleSpec:o.a8,style:{glyphs:!0,sprite:!0}})))return;Z.setLayoutProperty(E,F),Z.expressionDependencies.configDependencies.size!==0&&this._configDependentLayers.add(Z.fqid),Z.expressionDependencies.isIndoorDependent&&this._indoorDependentLayers.add(Z.fqid),this._updateLayer(Z)}}setLayerProperty(w,E,F,H={}){this._checkLoaded();const Z=this._checkLayer(w);Z&&(E==="appearances"?(Z.setAppearances(F),this._updateLayer(Z)):Z.isPaintProperty(E)?this.setPaintProperty(w,E,F,H):this.setLayoutProperty(w,E,F,H))}getLayoutProperty(w,E){const F=this._checkLayer(w);if(F)return F.getLayoutProperty(E)}setPaintProperty(w,E,F,H={}){this._checkLoaded();const Z=this._checkLayer(w);if(!Z||o.b6(Z.getPaintProperty(E),F)||F!=null&&(!H||H.validate!==!1)&&F0(Z,cs.call(ln,{key:`layers.${w}.paint.${E}`,layerType:Z.type,objectKey:E,value:F,styleSpec:o.a8})))return;const X=Z.setPaintProperty(E,F);Z.expressionDependencies.configDependencies.size!==0&&this._configDependentLayers.add(Z.fqid),Z.expressionDependencies.isIndoorDependent&&this._indoorDependentLayers.add(Z.fqid),X&&this._updateLayer(Z),this._changes.updatePaintProperties(Z)}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:xe,importId:Ne}=w.target,Le=this.getFragmentStyle(Ne),We=Le.getFeaturesetLayers(xe);for(const{source:He,sourceLayer:tt}of We)Le.setFeatureState({id:w.id,source:He,sourceLayer:tt},E)}else if("layerId"in w.target){const{layerId:xe}=w.target,Ne=this.getLayer(xe);this.setFeatureState({id:w.id,source:Ne.source,sourceLayer:Ne.sourceLayer},E)}return}const F=w.source,H=w.sourceLayer,Z=this._checkSource(F);if(!Z)return;const X=Z.type;if(X==="geojson"&&H)return void this.fire(new o.B(new Error("GeoJSON sources cannot have a sourceLayer parameter.")));if(X==="vector"&&!H)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 oe=this.getOwnSourceCaches(F);for(const xe of oe)xe.setFeatureState(H,w.id,E)}removeFeatureState(w,E){if(this._checkLoaded(),"target"in w){if("featuresetId"in w.target){const{featuresetId:xe,importId:Ne}=w.target,Le=this.getFragmentStyle(Ne),We=Le.getFeaturesetLayers(xe);for(const{source:He,sourceLayer:tt}of We)Le.removeFeatureState({id:w.id,source:He,sourceLayer:tt},E)}else if("layerId"in w.target){const{layerId:xe}=w.target,Ne=this.getLayer(xe);this.removeFeatureState({id:w.id,source:Ne.source,sourceLayer:Ne.sourceLayer},E)}return}const F=w.source,H=this._checkSource(F);if(!H)return;const Z=H.type,X=Z==="vector"?w.sourceLayer:void 0;if(Z==="vector"&&!X)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 oe=this.getOwnSourceCaches(F);for(const xe of oe)xe.removeFeatureState(X,w.id,E)}getFeatureState(w){if(this._checkLoaded(),"target"in w){let Z;if("featuresetId"in w.target){const{featuresetId:X,importId:oe}=w.target,xe=this.getFragmentStyle(oe),Ne=xe.getFeaturesetLayers(X);for(const{source:Le,sourceLayer:We}of Ne){const He=xe.getFeatureState({id:w.id,source:Le,sourceLayer:We});if(He&&!Z)Z=He;else if(!o.b6(Z,He))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:X}=w.target,oe=this.getLayer(X);Z=this.getFeatureState({id:w.id,source:oe.source,sourceLayer:oe.sourceLayer})}return Z}const E=w.source,F=w.sourceLayer,H=this._checkSource(E);if(H){if(H.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),H=this._changes.getUpdatedSourceCaches();w.source&&!H[F]&&E&&E.getSource().type!=="raster"&&(this._changes.updateSourceCache(F,"reload"),E.pause()),w.invalidateCompiledFilter()}_flattenAndSortRenderedFeatures(w){const E=oe=>this._mergedLayers[oe].is3D(!!this.terrain),F=this.order,H={},Z=[];for(let oe=F.length-1;oe>=0;oe--){const xe=F[oe];if(E(xe)){H[xe]=oe;for(const Ne of w){const Le=Ne[xe];if(Le)for(const We of Le)Z.push(We)}}}Z.sort((oe,xe)=>xe.intersectionZ-oe.intersectionZ);const X=[];for(let oe=F.length-1;oe>=0;oe--){const xe=F[oe];if(E(xe))for(let Ne=Z.length-1;Ne>=0;Ne--){const Le=Z[Ne].feature;if(Le.layer&&H[Le.layer.id]{if(Tw.has(Le.type))return;const We=this.getOwnLayerSourceCache(Le),He=Z[We.id]=Z[We.id]||{sourceCache:We,layers:{},has3DLayers:!1};Le.is3D(!!this.terrain)&&(He.has3DLayers=!0),He.layers[Le.fqid]=He.layers[Le.fqid]||{styleLayer:Le,targets:[]},He.layers[Le.fqid].targets.push({filter:H})};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 We=this._layers[Le];if(!We)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.`))),[];X(We)}}else for(const Le in this._layers)X(this._layers[Le]);const oe=this._queryRenderedFeatures(w,Z,F),xe=this._flattenAndSortRenderedFeatures(oe),Ne=[];for(const Le of xe)o.dh(Le.layer.id)===this.scope&&Ne.push(Le);return Ne}queryRenderedFeatureset(w,E,F){let H;E&&!Array.isArray(E)&&E.filter&&(this._validate(Ls,"queryRenderedFeatures.filter",E.filter,null,E),H=o.dg(E.filter));const Z="mock",X=[];if(E&&E.target)X.push(Object.assign({},E,{targetId:Z,filter:H}));else{const Le=this.getFeaturesetDescriptors();for(const We of Le)X.push({targetId:Z,filter:H,target:We});for(const{style:We}of this.fragments){const He=We.getFeaturesetDescriptors();for(const tt of He)X.push({targetId:Z,filter:H,target:tt})}}const oe=this.queryRenderedTargets(w,X,F),xe=[],Ne=new Set;for(const Le of oe)for(const We of Le.variants[Z])eh(We,Le,Ne)||xe.push(new o.di(Le,We));return xe}queryRenderedTargets(w,E,F){const H={},Z=(oe,xe,Ne,Le)=>{const We=H[xe.id]=H[xe.id]||{sourceCache:xe,layers:{},has3DLayers:!1};if(We.layers[oe.fqid]=We.layers[oe.fqid]||{styleLayer:oe,targets:[]},oe.is3D(!!this.terrain)&&(We.has3DLayers=!0),!Le)return Ne.uniqueFeatureID=!1,void We.layers[oe.fqid].targets.push(Ne);We.layers[oe.fqid].targets.push(Object.assign({},Ne,{namespace:Le.namespace,properties:Le.properties,uniqueFeatureID:Le.uniqueFeatureID}))};for(const oe of E)if("featuresetId"in oe.target){const{featuresetId:xe,importId:Ne}=oe.target,Le=this.getFragmentStyle(Ne);if(!Le||!Le._featuresetSelectors)continue;const We=Le._featuresetSelectors[xe];if(!We){this.fire(new o.B(new Error(`The featureset '${xe}' does not exist in the map's style and cannot be queried for features.`)));continue}for(const He of We){const tt=Le.getOwnLayer(He.layerId);tt&&!Tw.has(tt.type)&&Z(tt,Le.getOwnLayerSourceCache(tt),oe,He)}}else if("layerId"in oe.target){const{layerId:xe}=oe.target,Ne=this.getLayer(xe);if(!Ne||Tw.has(Ne.type))continue;Z(Ne,this.getLayerSourceCache(Ne),oe)}const X=this._queryRenderedFeatures(w,H,F);return this._flattenAndSortRenderedFeatures(X)}_queryRenderedFeatures(w,E,F){const H=[],Z=!!this.map._showQueryGeometry,X=vo.createFromScreenPoints(w,F);for(const oe in E){const xe=L0(X,E[oe],this._availableImages,F,Z,this.getActualScope());Object.keys(xe).length&&H.push(xe)}if(this.placement)for(const oe in E){if(E[oe].sourceCache._renderSourceType!==o.b4.Symbol)continue;const xe=jo(X.screenGeometry,E[oe],this._availableImages,this.placement.collisionIndex,this.placement.retainedQueryData,this.map.getWorldview());Object.keys(xe).length&&H.push(xe)}return H}querySourceFeatures(w,E){const F=E&&E.filter;F&&this._validate(Ls,"querySourceFeatures.filter",F,null,E);let H=[];const Z=this.getOwnSourceCaches(w);for(const X of Z)H=H.concat(Zi(X,E));return H}addSourceType(w,E,F){return bu.getSourceType(w)?F(new Error(`A source type called "${w}" already exists.`)):(bu.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 H=this.light.getLight();let Z=!1;for(const oe in w)if(!o.b6(w[oe],H[oe])){Z=!0;break}if(!Z)return;const X=this._getTransitionParameters();this.light.setLight(w,E,F),this.light.updateTransitions(X)}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 H=!("source"in w)||w.source==null;if(E===1){if(this.disableElevatedTerrain)return;if("source"in F&&typeof F.source=="object"){const oe="terrain-dem-src";this.addSource(oe,F.source),F=o.d9(F),F=Object.assign(F,{source:oe})}const Z=Object.assign({},F),X={};if(this.terrain&&H){Z.source=this.terrain.get().source;const oe=this.terrain?this.getFragmentStyle(this.terrain.scope):null;oe&&(X.style=oe.serialize())}if(this._validate(pt,"terrain",Z,X))return}if(!this.terrain||this.terrain.scope!==this.scope&&!H||this.terrain&&E!==this.terrain.drapeRenderMode){if(!F)return;this._createTerrain(F,E),this.fire(new o.C("data",{dataType:"style"}))}else{const Z=this.terrain,X=Z.get();for(const oe of Object.keys(o.a8.terrain))!F.hasOwnProperty(oe)&&o.a8.terrain[oe].default&&(F[oe]=o.a8.terrain[oe].default);for(const oe in w)if(!o.b6(w[oe],X[oe])){Z.set(w,this.options),this.stylesheet.terrain=w;const xe=this._getTransitionParameters({duration:0});Z.updateTransitions(xe),this.fire(new o.C("data",{dataType:"style"}));break}}this.mergeTerrain(),this.updateDrapeFirstLayers(),this._markersNeedUpdate=!0}_createFog(w){const E=this.fog=new wo(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 Sa(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 Kn(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 H in this._layers)this._layers[H].lut=this._styleColorTheme.lut;for(const H in this._sourceCaches)this._sourceCaches[H].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(H=>{o.w(`Couldn't set color theme: ${H}`)})}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 da(w,E,this.scope,this.options,this.map.getWorldview());E===1&&(this.stylesheet.terrain=w),this.mergeTerrain(),this.updateDrapeFirstLayers(),this._force3DLayerUpdate();const H=this._getTransitionParameters({duration:0});F.updateTransitions(H)}_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,H,Z={}){if(Z&&Z.validate===!1)return!1;const X=Object.assign({},this.serialize());return F0(this,w.call(ln,Object.assign({key:E,style:X,value:F,styleSpec:o.a8},H)))}_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=O0(this.directionalLight));const F=new Set,H=new Set,Z=new Set;for(const X in this._mergedLayers){const oe=this._mergedLayers[X];oe.type==="building"?F.add(oe.source):oe.type==="raster"&&oe.paint&&oe.paint.get("raster-elevation-reference")==="ground"&&Z.add(oe.source),oe.hasElevation()&&!H.has(oe.source)&&H.add(oe.source)}for(const X in this._mergedSourceCaches){const oe=this._mergedSourceCaches[X],xe=H.has(oe._source.id);oe._isRasterElevatedOverTerrain=Z.has(oe._source.id),F.has(oe._source.id)&&(oe._source.reparseOverscaled=!1),oe.update(w,void 0,void 0,E,xe)}}_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 My),this.pauseablePlacement.requestFullPlacement()}_setLabelPlacementStale(){this.placement&&this.placement.setStale()}_updatePlacement(w,E,F,H,Z){this.pauseablePlacement||(this.pauseablePlacement=new My);let X=!1,oe=!1;const xe={},Ne={};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 Ot=xe[wt];if(!Ot){const Ct=this.getLayerSourceCache(jt);if(!Ct)continue;const ks=Ct.getRenderableIds(!0).map(ss=>Ct.getTileByID(ss));Ne[wt]=ks.slice(),Ot=xe[wt]=ks.sort((ss,Ns)=>Ns.tileID.overscaledZ-ss.tileID.overscaledZ||(ss.tileID.isLessThan(Ns.tileID)?-1:1))}const Vt=this.crossTileSymbolIndex.addLayer(jt,Ot,w.center.lng,w.projection);X=X||Vt}this.crossTileSymbolIndex.pruneUnusedLayers(this._mergedOrder);const Le=!!(this.placement&&!w.equals(this.placement.transform)),We=!!(this.placement&&(this.placement.lastReplacementSourceUpdateTime!==0&&!Z||this.placement.lastReplacementSourceUpdateTime!==Z.updateTime)),He=Le||We||X,tt=(He||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||tt||dt)&&(this.pauseablePlacement=this.pauseablePlacement.startNewPlacement(w,this._mergedOrder,E,F,H,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)),Ot=wt*wt*(3-2*wt);this.pauseablePlacement.placement.frontCutoffStart=-.5*(1-Ot)+it*Ot}}}if(this.pauseablePlacement.isDone()?He&&F!==0&&this.pauseablePlacement.setStale():(this.pauseablePlacement.continuePlacement(this._mergedOrder,this._mergedLayers,xe,Ne,this.map.painter.scaleFactor),this.pauseablePlacement.isDone()&&(this.placement=this.pauseablePlacement.commit(o.o.now()),oe=!0),X&&this.pauseablePlacement.setStale()),oe||X){this._buildingIndex.onNewFrame(w.zoom);for(let it=0;itZ===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 H=F.findIndex(({id:Z})=>Z===E);return H===-1&&this.fire(new o.B(new Error(`Import with id "${E}" does not exist on this map.`))),this.stylesheet.imports=F.slice(0,H).concat(w).concat(F.slice(H)),this._loadImports([w],!0,E)}updateImport(w,E){this._checkLoaded();const F=this.stylesheet.imports||[],H=this.getImportIndex(w);return H===-1?this:typeof E=="string"?(this.setImportUrl(w,E),this):(E.url&&E.url!==F[H].url&&this.setImportUrl(w,E.url),o.b6(E.config,F[H].config)||this.setImportConfig(w,E.config,E.data.schema),o.b6(E.data,F[H].data)||this.setImportData(w,E.data),this)}moveImport(w,E){this._checkLoaded();let F=this.stylesheet.imports||[];const H=this.getImportIndex(w);if(H===-1)return this;const Z=this.getImportIndex(E);if(Z===-1)return this;const X=F[H],oe=this.fragments[H];return F=F.filter(({id:xe})=>xe!==w),this.fragments=this.fragments.filter(({id:xe})=>xe!==w),this.stylesheet.imports=F.slice(0,Z).concat(X).concat(F.slice(Z)),this.fragments=this.fragments.slice(0,Z).concat(oe).concat(this.fragments.slice(Z)),this.mergeLayers(),this}setImportUrl(w,E){this._checkLoaded();const F=this.stylesheet.imports||[],H=this.getImportIndex(w);if(H===-1)return this;F[H].url=E;const Z=this.fragments[H];return Z.style=this._createFragmentStyle(F[H]),Z.style.on("style.import.load",()=>this.mergeAll()),Z.style.loadURL(E),this}setImportData(w,E){this._checkLoaded();const F=this.getImportIndex(w),H=this.stylesheet.imports||[];return F===-1?this:E?(this.fragments[F].style.setState(E),this._reloadImports(),this):(delete H[F].data,this.setImportUrl(w,H[F].url))}setImportConfig(w,E,F){this._checkLoaded();const H=this.getImportIndex(w),Z=this.stylesheet.imports||[];if(H===-1)return this;E?Z[H].config=E:delete Z[H].config;const X=this.fragments[H];F&&X.style.stylesheet&&(X.style.stylesheet.schema=F);const oe=X.style.stylesheet&&X.style.stylesheet.schema;return X.config=E,X.style.updateConfig(E,oe),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 H=this.getLayer(F);H&&H.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 H=X=>{if(X){const oe=E.images.map(xe=>o.I.toString(xe));X.setDependencies(E.tileID.key,E.type,oe)}},Z=o.F(E.source,E.scope);H(this._mergedOtherSourceCaches[Z]),H(this._mergedSymbolSourceCaches[Z]),E.images.some(X=>X.iconsetId)&&this.fire(new o.C("data",{dataType:"style"}))}rasterizeImages(w,E,F){this.imageManager.rasterizeImages(E,F)}checkAtlasCache(w,E,F){const H=this.imageManager.imageAtlasCache.findCachedAtlas(E.descriptor);F(null,H&&H.contentDescriptor?{iconPositions:H.iconPositions,patternPositions:H.patternPositions,sourceHash:H.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"),H=w.type==="building";if(w.is3D(!!this.terrain)){if(F||H||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)}}bu.getSourceType=function(R){return Dg[R]},bu.setSourceType=function(R,w){Dg[R]=w},bu.registerForPluginStateChange=o.dk;var z0=` #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`,Mw=` #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;}`,B0=` #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`,Jb="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;}",b2=` #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`,_2=`#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`,I1=`#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`,D1=`#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`,w2=`#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;}`,e_=`#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`,pp=`#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 yh=/#include\s+"([^"]+)"/g,lr=/#pragma mapbox: ([\w\-]+) ([\w]+) ([\w]+) ([\w]+)/g,R1=/\b[A-Za-z_][A-Za-z0-9_]*\b/g,O1=new Set(["ifdef","ifndef","elif","if","defined"]),Sv=new Set;Ug(z0,Sv),Ug(B0,Sv),Ug(Mw,Sv);const Zp={"_prelude_fog.vertex.glsl":_2,"_prelude_terrain.vertex.glsl":b2,"_prelude_shadow.vertex.glsl":e_,"_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":I1,"_prelude_shadow.fragment.glsl":pp,"_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":D1,"_prelude_raster_particle.glsl":w2},Ly={};ho("",b2),ho(I1,_2),ho(pp,e_),ho(D1,""),ho(w2,"");const $0=ho(Mw,B0),t_=z0,Cv=[` #if defined(GL_EXT_blend_func_extended) && defined(DUAL_SOURCE_BLENDING) #extension GL_EXT_blend_func_extended : require #endif`,"precision mediump float;",t_,$0.fragmentSource].join(` `),j2=["precision highp float;",t_,$0.vertexSource].join(` `);var Lw={background:ho(`#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:ho(`#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:ho(`#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:ho(`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:ho("void main() {}","in vec3 a_pos_3f;uniform mat4 u_matrix;void main() {gl_Position=u_matrix*vec4(a_pos_3f,1.0);}"),circle:ho(`#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:ho("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:ho(`#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:ho(`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:ho("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:ho("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:ho("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:ho("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:ho(`#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:ho(`#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:ho(`#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:ho(`#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:ho(`#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:ho(`#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:ho(`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:ho(`#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:ho("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:ho(`#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:ho(`#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:ho(`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:ho(`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:ho(`#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:ho(`#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:ho(`#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:ho(`#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:ho(`#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:ho("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:ho("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:ho(`#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:ho(`#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:ho(`#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:ho("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:ho(`#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 }`,Jb),skyboxGradient:ho(`#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 }`,Jb),skyboxCapture:ho(` 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:ho(`#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:ho(`#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:ho(`#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:ho("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:ho(`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:ho("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:ho("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:ho("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:ho("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 Ug(R,w){const E=R.split(` `);for(let F of E){if(F=F.trimStart(),F[0]!=="#"||!F.includes("if")||F.startsWith("#endif"))continue;const H=F.match(R1);if(H)for(const Z of H)O1.has(Z)||w.add(Z)}}function W5(R){return new Set(["uint","int","uvec2","ivec2","uvec3","ivec3","uvec4","ivec4"]).has(R)}function ho(R,w){const E=new Set,F=[],H=[];R=R.replace(yh,(X,oe)=>(H.push(oe),"")),w=w.replace(yh,(X,oe)=>(F.push(oe),""));let Z=new Set(Sv);Ug(R,Z),Ug(w,Z);for(const X of[...F,...H])Ly[X]||(Ly[X]=new Set,Ug(Zp[X],Ly[X])),Z=new Set([...Z,...Ly[X]]);return{fragmentSource:R=R.replace(lr,(X,oe,xe,Ne,Le)=>(E.add(Le),oe==="define"?` #ifndef HAS_UNIFORM_u_${Le} ${W5(Ne)?"flat ":""}in ${xe} ${Ne} ${Le}; #else uniform ${xe} ${Ne} u_${Le}; #endif `:oe==="initialize"?` #ifdef HAS_UNIFORM_u_${Le} ${xe} ${Ne} ${Le} = u_${Le}; #endif `:oe==="define-attribute"?` #ifdef HAS_ATTRIBUTE_a_${Le} in ${xe} ${Ne} ${Le}; #endif `:oe==="initialize-attribute"?"":void 0)),vertexSource:w=w.replace(lr,(X,oe,xe,Ne,Le)=>{const We=`MATERIAL_ATTRIBUTE_OFFSET_${Le}`,He=Ne==="float"?"vec2":Ne,tt=`GET_ATTRIBUTE_${He}(a_${Le}, materialInfo, ${We})`,dt=Le.match(/color/)?"color":He;return oe==="define-attribute-vertex-shader-only"?` #ifdef HAS_ATTRIBUTE_a_${Le} in ${xe} ${Ne} a_${Le}; #endif `:E.has(Le)?oe==="define"?` #ifndef HAS_UNIFORM_u_${Le} uniform lowp float u_${Le}_t; #if !defined(${We}) in ${xe} ${He} a_${Le}; #endif ${W5(Ne)?"flat ":""}out ${xe} ${Ne} ${Le}; #else uniform ${xe} ${Ne} u_${Le}; #endif `:oe==="initialize"?dt==="vec4"||dt==="uvec4"?` #ifndef HAS_UNIFORM_u_${Le} ${Le} = a_${Le}; #else ${xe} ${Ne} ${Le} = u_${Le}; #endif `:` #if !defined(HAS_UNIFORM_u_${Le}) #ifdef ${We} ${Le} = unpack_mix_${dt}(${tt}, u_${Le}_t); #else ${Le} = unpack_mix_${dt}(a_${Le}, u_${Le}_t); #endif #else ${xe} ${Ne} ${Le} = u_${Le}; #endif `:oe==="define-attribute"?` #ifdef HAS_ATTRIBUTE_a_${Le} in ${xe} ${Ne} a_${Le}; out ${xe} ${Ne} ${Le}; #endif `:oe==="initialize-attribute"?` #ifdef HAS_ATTRIBUTE_a_${Le} ${Le} = a_${Le}; #endif `:void 0:oe==="define"?` #ifndef HAS_UNIFORM_u_${Le} uniform lowp float u_${Le}_t; #if !defined(${We}) in ${xe} ${He} a_${Le}; #endif #else uniform ${xe} ${Ne} u_${Le}; #endif `:oe==="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 ${xe} ${Ne} u_${Le}; #endif `:` #ifdef INSTANCED_ARRAYS in ${xe} ${He} a_${Le}; #else uniform ${xe} ${Ne} u_${Le}; #endif `:oe==="initialize-attribute-custom"?` #ifdef HAS_ATTRIBUTE_a_${Le} ${xe} ${Ne} ${Le} = a_${Le}; #endif `:dt==="vec4"||dt==="uvec4"?` #ifndef HAS_UNIFORM_u_${Le} #ifdef ${We} ${xe} ${Ne} ${Le} = ${tt}; #else ${xe} ${Ne} ${Le} = a_${Le}; #endif #else ${xe} ${Ne} ${Le} = u_${Le}; #endif `:` #ifndef HAS_UNIFORM_u_${Le} #ifdef ${We} ${xe} ${Ne} ${Le} = unpack_mix_${dt}(${tt}, u_${Le}_t); #else ${xe} ${Ne} ${Le} = unpack_mix_${dt}(a_${Le}, u_${Le}_t); #endif #else ${xe} ${Ne} ${Le} = u_${Le}; #endif `}),usedDefines:Z,vertexIncludes:F,fragmentIncludes:H}}class mk{constructor(){this.boundProgram=null,this.boundLayoutVertexBuffer=null,this.boundPaintVertexBuffers=[],this.boundIndexBuffer=null,this.boundVertexOffset=null,this.boundDynamicVertexBuffers=[],this.vao=null}bind(w,E,F,H,Z,X,oe,xe){this.context=w;let Ne=this.boundPaintVertexBuffers.length!==H.length;for(let We=0;!Ne&&We{const ks=Vt.paint.get("hillshade-shadow-color"),ss=Vt.paint.get("hillshade-shadow-color-use-theme").constantOr("default")==="none",Ns=Vt.paint.get("hillshade-highlight-color"),Gt=Vt.paint.get("hillshade-highlight-color-use-theme").constantOr("default")==="none",es=Vt.paint.get("hillshade-accent-color"),fs=Vt.paint.get("hillshade-accent-color-use-theme").constantOr("default")==="none",Ws=Vt.paint.get("hillshade-emissive-strength");let As=o.ap(Vt.paint.get("hillshade-illumination-direction"));if(Vt.paint.get("hillshade-illumination-anchor")==="viewport")As-=wt.transform.angle;else if(wt.style&&wt.style.enable3dLights()&&wt.style.directionalLight){const an=wt.style.directionalLight.properties.get("direction"),Dn=o.cP(an.x,an.y,an.z);As=o.ap(Dn[1])}const gn=!wt.options.moving;return{u_matrix:Ct||wt.transform.calculateProjMatrix(Ot.tileID.toUnwrapped(),gn),u_image:0,u_latrange:K5(0,Ot.tileID),u_light:[Vt.paint.get("hillshade-exaggeration"),As],u_shadow:ks.toPremultipliedRenderColor(ss?null:Vt.lut),u_highlight:Ns.toPremultipliedRenderColor(Gt?null:Vt.lut),u_emissive_strength:Ws,u_accent:es.toPremultipliedRenderColor(fs?null:Vt.lut)}})(R,E,F,R.terrain?w.projMatrix:null);R.uploadCommonUniforms(oe,He,w.toUnwrapped());const{tileBoundsBuffer:dt,tileBoundsIndexBuffer:it,tileBoundsSegments:jt}=R.getTileBoundsBuffers(E);He.draw(R,xe.TRIANGLES,H,Z,X,pa.disabled,tt,F.id,dt,it,jt)}function Y5(R,w,E){if(!w.needsDEMTextureUpload)return;const F=R.context,H=F.gl;F.pixelStoreUnpackPremultiplyAlpha.set(!1),w.demTexture=w.demTexture||R.getTileTexture(E.stride);const Z=E.getPixels();w.demTexture?w.demTexture.update(Z,{premultiply:!1}):w.demTexture=new o.T(F,Z,H.R32F,{premultiply:!1}),w.needsDEMTextureUpload=!1}function MC(R,w,E){const F=R.context,H=F.gl;if(!w.dem)return;const Z=w.dem;if(F.activeTexture.set(H.TEXTURE1),Y5(R,w,Z),!w.demTexture)return;w.demTexture.bind(H.NEAREST,H.CLAMP_TO_EDGE);const X=Z.dim;F.activeTexture.set(H.TEXTURE0);let oe=w.hillshadeFBO;if(!oe){const He=new o.T(F,{width:X,height:X,data:null},H.RGBA8);He.bind(H.LINEAR,H.CLAMP_TO_EDGE),oe=w.hillshadeFBO=F.createFramebuffer(X,X,1,"renderbuffer"),oe.colorAttachment0.set(He.texture)}F.bindFramebuffer.set(oe.framebuffer),F.viewport.set([0,0,X,X]);const{tileBoundsBuffer:xe,tileBoundsIndexBuffer:Ne,tileBoundsSegments:Le}=R.getMercatorTileBoundsBuffers(),We=[];R.linearFloatFilteringSupported()&&We.push("TERRAIN_DEM_FLOAT_FORMAT"),R.terrain&&R.terrain.renderingToTexture&&R.emissiveMode==="mrt-fallback"&&We.push("USE_MRT1"),R.getOrCreateProgram("hillshadePrepare",{defines:We}).draw(R,H.TRIANGLES,qr.disabled,La.disabled,Ma.unblended,pa.disabled,((He,tt)=>{const dt=tt.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:He.overscaledZ}})(w.tileID,Z),E.id,xe,Ne,Le),w.needsHillshadePrepare=!1}class Ec{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 s_ extends Ec{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 Z5 extends Ec{getDefault(){return 1}set(w){(w!==this.current||this.dirty)&&(this.gl.clearDepth(w),this.current=w,this.dirty=!1)}}class F1 extends Ec{getDefault(){return 0}set(w){(w!==this.current||this.dirty)&&(this.gl.clearStencil(w),this.current=w,this.dirty=!1)}}class aM extends Ec{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 qg extends Ec{getDefault(){return!0}set(w){(w!==this.current||this.dirty)&&(this.gl.depthMask(w),this.current=w,this.dirty=!1)}}class Pw extends Ec{getDefault(){return 255}set(w){(w!==this.current||this.dirty)&&(this.gl.stencilMask(w),this.current=w,this.dirty=!1)}}class n_ extends Ec{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 pk extends Ec{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 z1 extends Ec{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 B1 extends Ec{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 zf extends Ec{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 eu extends Ec{getDefault(){return this.gl.LESS}set(w){(w!==this.current||this.dirty)&&(this.gl.depthFunc(w),this.current=w,this.dirty=!1)}}class Vg extends Ec{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 N2 extends Ec{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 X5 extends Ec{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 fx extends Ec{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 Xp extends Ec{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 k2 extends Ec{getDefault(){return this.gl.BACK}set(w){(w!==this.current||this.dirty)&&(this.gl.cullFace(w),this.current=w,this.dirty=!1)}}class fk extends Ec{getDefault(){return this.gl.CCW}set(w){(w!==this.current||this.dirty)&&(this.gl.frontFace(w),this.current=w,this.dirty=!1)}}let Iw=class extends Ec{getDefault(){return null}set(R){(R!==this.current||this.dirty)&&(this.gl.useProgram(R),this.current=R,this.dirty=!1)}};class Dw extends Ec{getDefault(){return this.gl.TEXTURE0}set(w){(w!==this.current||this.dirty)&&(this.gl.activeTexture(w),this.current=w,this.dirty=!1)}}class Qp extends Ec{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 fp extends Ec{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 Q5 extends Ec{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 Py extends Ec{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 Rw extends Ec{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 Ow extends Ec{getDefault(){return null}set(w){const E=this.gl;E.bindBuffer(E.ELEMENT_ARRAY_BUFFER,w),this.current=w,this.dirty=!1}}class xk extends Ec{getDefault(){return null}set(w){this.gl&&(w!==this.current||this.dirty)&&(this.gl.bindVertexArray(w),this.current=w,this.dirty=!1)}}class gk extends Ec{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 yk extends Ec{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 Fw extends Ec{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 zw extends Ec{constructor(w,E){super(w),this.context=w,this.parent=E}getDefault(){return null}}class r_ extends zw{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 S2 extends zw{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 vk extends zw{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 LC extends S2{attachment(){return this.gl.DEPTH_STENCIL_ATTACHMENT}}const a_=(R,w,E,F)=>({u_matrix:R,u_image0:0,u_image1:1,u_skirt_height:w,u_ground_shadow_factor:E,u_emissive_texture_available:F}),Iy=(R,w,E,F,H,Z,X,oe,xe,Ne,Le,We,He,tt,dt,it,jt)=>({u_proj_matrix:Float32Array.from(R),u_globe_matrix:w,u_normalize_matrix:Float32Array.from(F),u_merc_matrix:E,u_zoom_transition:H,u_merc_center:Z,u_image0:0,u_image1:1,u_frustum_tl:X,u_frustum_tr:oe,u_frustum_br:xe,u_frustum_bl:Ne,u_globe_pos:Le,u_globe_radius:We,u_viewport:He,u_grid_matrix:jt?Float32Array.from(jt):new Float32Array(9),u_skirt_height:tt,u_far_z_cutoff:dt,u_emissive_texture_available:it});function Bw(R,w){return R!=null&&w!=null&&!(!R.hasData()||!w.hasData())&&R.demTexture!=null&&w.demTexture!=null&&R.tileID.key!==w.tileID.key}const cm=new class{constructor(){this.operations={}}newMorphing(R,w,E,F,H){if(R in this.operations){const Z=this.operations[R];Z.to.tileID.key!==E.tileID.key&&(Z.queued=E)}else this.operations[R]={startTime:F,phase:0,duration:H,from:w,to:E,queued:null}}getMorphValuesForProxy(R){if(!(R in this.operations))return null;const w=this.operations[R];return{from:w.from,to:w.to,phase:w.phase}}update(R){for(const w in this.operations){const E=this.operations[w];for(E.phase=(R-E.startTime)/E.duration;E.phase>=1||!this._validOp(E);)if(!this._nextOp(E,R)){delete this.operations[w];break}}}_nextOp(R,w){return!!R.queued&&(R.from=R.to,R.to=R.queued,R.queued=null,R.phase=0,R.startTime=w,!0)}_validOp(R){return R.from.hasData()&&R.to.hasData()}},$w={0:null,1:"TERRAIN_VERTEX_MORPHING"};function i_(R,w,E){if(w===0)return 0;const F=w<1&&E===514?.25/w:1;return 6*Math.pow(1.5,22-R)*Math.max(w,1)*F}function Ce(R,w){const E=1<({u_matrix:R});function bt(R,w,E,F,H){if(H>0){const Z=o.o.now(),X=(Z-R.timeAdded)/H,oe=w?(Z-w.timeAdded)/H:-1,xe=E.getSource(),Ne=F.coveringZoomLevel({tileSize:xe.tileSize,roundZoom:xe.roundZoom}),Le=!w||Math.abs(w.tileID.overscaledZ-Ne)>Math.abs(R.tileID.overscaledZ-Ne),We=Le&&R.refreshedUponExpiration?1:o.aC(Le?X:1-oe,0,1);return w?{opacity:1,mix:1-We,isFading:X<1}:{opacity:We,mix:0,isFading:X<1}}return{opacity:1,mix:0,isFading:!1}}class Yt extends ql{constructor(w){const E={type:"raster-dem",maxzoom:Math.ceil(w.transform.maxZoom)},F=Em("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 ls extends ql{constructor(w){const E=Em("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 H=w.coveringTiles({tileSize:this._source.tileSize,minzoom:this._source.minzoom,maxzoom:this._source.maxzoom,roundZoom:this._source.roundZoom,reparseOverscaled:this._source.reparseOverscaled}).reduce((Z,X)=>{if(Z[X.key]="",!this._tiles[X.key]){const oe=new o.b0(X,this._source.tileSize*X.overscaleFactor(),w.tileZoom,void 0,void 0,this._source.worldview);oe.state="loaded",this._tiles[X.key]=oe}return Z},{});for(const Z in this._tiles)Z in H||(this.freeFBO(Z),this._tiles[Z].unloadVectorData(),delete this._tiles[Z])}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 ps 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 Ss extends o.bu{constructor(w,E){super(),this._debugParams={sortTilesHiZFirst:!0,disableRenderCache:!1},this.painter=w,this.terrainTileForTile={},this.prevTerrainTileForTile={};const[F,H,Z]=function(){const xe=new o.dB,Ne=new o.dC,Le=131;xe.reserve(17161),Ne.reserve(33800);const We=o.an/128,He=o.an+We/2,tt=He+We;for(let it=-We;itHe||it<0||it>He?24575:0,Ot=o.aC(Math.round(jt),0,o.an),Vt=o.aC(Math.round(it),0,o.an);xe.emplaceBack(Ot+wt,Vt)}const dt=(it,jt)=>{const wt=jt*Le+it;Ne.emplaceBack(wt+1,wt,wt+Le),Ne.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)}),[xe,Ne,32768]}(),X=w.context;this.gridBuffer=X.createVertexBuffer(F,o.dx.members),this.gridIndexBuffer=X.createIndexBuffer(H),this.gridSegments=o.dy.simpleSegment(0,0,F.length,H.length),this.gridNoSkirtSegments=o.dy.simpleSegment(0,0,F.length,Z),this.proxyCoords=[],this.proxiedCoords={},this._visibleDemTiles=[],this._drapedRenderBatches=[],this._sourceTilesOverlap={},this.proxySourceCache=new ls(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 oe=X.gl;this._overlapStencilMode=new La({func:oe.GEQUAL,mask:255},0,255,oe.KEEP,oe.KEEP,oe.REPLACE),this._previousZoom=w.transform.zoom,this.pool=[],this._findCoveringTileCache={},this._tilesDirty={},this.style=E,this._useVertexMorphing=!0,this._exaggeration=1,this._mockSourceCache=new Yt(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 H=w.terrain.properties,Z=w.terrain.drapeRenderMode===0,X=w.terrain.isZoomDependent();this._previousUpdateTimestamp=this.enabled?this._updateTimestamp:void 0,this._updateTimestamp=o.o.now();const oe=w.terrain&&w.terrain.scope,xe=H.get("source"),Ne=Z?this._mockSourceCache:w.getSourceCache(xe,oe);if(!Ne)return void o.w(`Couldn't find terrain source "${xe}".`);if(this.sourceCache=Ne,this._attenuationRange=w.terrain.getAttenuationRange(),this._exaggeration=X?this.calculateExaggeration(E):H.get("exaggeration"),!E.projection.requiresDraping&&X&&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 We=this.getScaledDemTileSize();this.sourceCache.update(E,We,!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 H=E!=null?F-E:Number.MAX_VALUE;if(Math.abs(H)<2)return this._exaggeration;const Z=w.zoom,X=this._style.terrain;if(!this._previousUpdateTimestamp)return X.getExaggeration(Z);let oe=Z-this._previousZoom;const xe=this._previousUpdateTimestamp;let Ne=Z;this._evaluationZoom!=null&&(Ne=this._evaluationZoom,Math.abs(Z-Ne)>.5&&(oe=.5*(Z-Ne+oe)),oe*H<0&&(Ne+=oe)),this._evaluationZoom=Ne;const Le=X.getExaggeration(Ne),We=Le===X.getExaggeration(Math.max(0,Ne-.1));if(We&&Math.abs(Le-this._exaggeration)<.01)return Le;let He=Math.min(.1,.00375*(this._updateTimestamp-xe));return(We||Le<.1||Math.abs(oe)<1e-4)&&(He=Math.min(.2,4*He)),o.am(this._exaggeration,Le,He)}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 H=this.proxyCoords=E.getIds().map(xe=>{const Ne=E.getTileByID(xe).tileID;return Ne.projMatrix=F.calculateProjMatrix(Ne.toUnwrapped()),Ne});(function(xe,Ne){const Le=Ne.transform.pointCoordinate(Ne.transform.getCameraPoint()),We=new o.P(Le.x,Le.y);xe.sort((He,tt)=>{if(tt.overscaledZ-He.overscaledZ)return tt.overscaledZ-He.overscaledZ;const dt=new o.P(He.canonical.x+(1<{this.proxyToSource[xe.key]={}}),this.terrainTileForTile={};const X=this._style._mergedSourceCaches;for(const xe in X){const Ne=X[xe];if(!Ne.used||(Ne!==this.sourceCache&&this.resetTileLookupCache(Ne.id),this._setupProxiedCoordsForOrtho(Ne,w[xe],Z),Ne.usedForTerrain))continue;const Le=w[xe];(Ne.getSource().reparseOverscaled||Ne._isRasterElevatedOverTerrain)&&this._assignTerrainTiles(Le)}this.proxiedCoords[E.id]=H.map(xe=>new ps(xe,xe.key,this.orthoMatrix)),this._assignTerrainTiles(H),this._prepareDEMTextures(),this._setupDrapedRenderBatches(),this._initFBOPool(),this._setupRenderCache(Z),this.renderingToTexture=!1;const oe={};this._visibleDemTiles=[];for(const xe of this.proxyCoords){const Ne=this.terrainTileForTile[xe.key];if(!Ne)continue;const Le=Ne.tileID.key;Le in oe||(this._visibleDemTiles.push(Ne),oe[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 H=this.terrainTileForTile[F],Z=H.dem;!Z||H.demTexture&&!H.needsDEMTextureUpload||(w.activeTexture.set(E.TEXTURE1),Y5(this.painter,H,Z))}}_prepareDemTileUniforms(w,E,F,H){if(!E||E.demTexture==null)return!1;const Z=w.tileID.canonical,X=Math.pow(2,E.tileID.canonical.z-Z.z),oe=H||"";return F[`u_dem_tl${oe}`]=[Z.x*X%1,Z.y*X%1],F[`u_dem_scale${oe}`]=X,!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,H)=>{if(!H.dem)return F;const Z=H.dem.tree.minimums[0];return Z>0&&w++,F+Z},0);return w?E/w:0}_updateEmptyDEMTexture(){const w=this.painter.context,E=w.gl;w.activeTexture.set(E.TEXTURE2);const F=this._getLoadedAreaMinimum(),H=new o.dz({width:1,height:1},new Float32Array([F]));this._emptyDEMTextureDirty=!1;let Z=this._emptyDEMTexture;return Z?Z.update(H,{premultiply:!1}):Z=this._emptyDEMTexture=new o.T(w,H,E.R32F,{premultiply:!1}),Z}setupElevationDraw(w,E,F){const H=this.painter.context,Z=H.gl,X={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};X.u_exaggeration=this.exaggeration();let oe=null,xe=null,Ne=1;if(F&&F.morphing&&this._useVertexMorphing){const tt=F.morphing.srcDemTile,dt=F.morphing.dstDemTile;Ne=F.morphing.phase,tt&&dt&&(this._prepareDemTileUniforms(w,tt,X,"_prev")&&(xe=tt),this._prepareDemTileUniforms(w,dt,X)&&(oe=dt))}const Le=tt=>tt&&tt.demTexture&&this.painter.linearFloatFilteringSupported()?Z.LINEAR:Z.NEAREST;let We=null;var He;if(this.enabled?xe&&oe?(We=oe.demTexture,H.activeTexture.set(Z.TEXTURE4),xe.demTexture.bind(Le(xe),Z.CLAMP_TO_EDGE),X.u_dem_lerp=Ne):(oe=this.terrainTileForTile[w.tileID.key],We=this._prepareDemTileUniforms(w,oe,X)?oe.demTexture:this.emptyDEMTexture):We=this.emptyDEMTexture,H.activeTexture.set(Z.TEXTURE2),We&&(X.u_dem_size=(He=We).size[0]===1?1:He.size[0]-2,We.bind(Le(oe),Z.CLAMP_TO_EDGE)),this.painter.setupDepthForOcclusion(F&&F.useDepthForOcclusion,E,X),F&&F.useMeterToDem&&oe){const tt=(1<{if(wt===an)return;const Dn=[$w[an],"PROJECTION_GLOBE_VIEW"];Vt&&Dn.push("CUSTOM_ANTIALIASING");const Gn=Ne.isTileAffectedByFog(gn);jt=Ne.getOrCreateProgram("globeRaster",{defines:Dn,overrideFog:Gn}),wt=an},ks=Ne.colorModeForRenderPass(),ss=new qr(it.LEQUAL,qr.ReadWrite,Ne.depthRangeFor3D);cm.update(tt);const Ns=o.dq(Ot),Gt=[o.aH(Ot.center.lng),o.aL(Ot.center.lat)],es=Ne.globeSharedBuffers,fs=[Ot.width*o.o.devicePixelRatio,Ot.height*o.o.devicePixelRatio],Ws=Float32Array.from(Ot.globeMatrix),As={useDenormalizedUpVectorScale:!0};{const gn=Ne.transform,an=i_(gn.zoom,Le.exaggeration(),Le.sourceCache._source.tileSize);wt=-1;const Dn=it.TRIANGLES;for(const Gn of He){const en=We.getTile(Gn),Ms=La.disabled,mn=Le.prevTerrainTileForTile[Gn.key],vn=Le.terrainTileForTile[Gn.key];Bw(mn,vn)&&cm.newMorphing(Gn.key,mn,vn,tt,250),Fe(Ne,en.emissiveTexture),dt.activeTexture.set(it.TEXTURE0),en.texture&&en.texture.bind(it.LINEAR,it.CLAMP_TO_EDGE);const kn=cm.getMorphValuesForProxy(Gn.key),_r=kn?1:0;kn&&Object.assign(As,{morphing:{srcDemTile:kn.from,dstDemTile:kn.to,phase:o.dn(kn.phase)}});const cr=o.dr(Gn.canonical),dr=o.ds(cr.getCenter().lat),Bn=o.dt(Gn.canonical,cr,dr,gn.worldSize/gn._pixelsPerMercatorPixel),ra=o.du(o.dv(Gn.canonical)),wa=Ne.emissiveMode==="mrt-fallback"?1:0,Yr=Iy(gn.expandedFarZProjMatrix,Ws,Ns,ra,o.al(gn.zoom),Gt,gn.frustumCorners.TL,gn.frustumCorners.TR,gn.frustumCorners.BR,gn.frustumCorners.BL,gn.globeCenterInViewSpace,gn.globeRadius,fs,an,gn._farZ,wa,Bn);if(Ct(Gn,_r),jt&&(Le.setupElevationDraw(en,jt,As),Ne.uploadCommonUniforms(dt,jt,Gn.toUnwrapped()),es)){const[na,Xa,pi]=es.getGridBuffers(dr,an!==0);jt.draw(Ne,Dn,ss,Ms,ks,pa.backCCW,Yr,"globe_raster",na,Xa,pi)}}}if(es&&(Ne.renderDefaultNorthPole||Ne.renderDefaultSouthPole)){const gn=["GLOBE_POLES","PROJECTION_GLOBE_VIEW"];Vt&&gn.push("CUSTOM_ANTIALIASING"),jt=Ne.getOrCreateProgram("globeRaster",{defines:gn});for(const an of He){const{x:Dn,y:Gn,z:en}=an.canonical,Ms=Gn===0,mn=Gn===(1<na.draw(Ne,it.TRIANGLES,ss,La.disabled,ks,pa.disabled,Iy(Ot.expandedFarZProjMatrix,Bn,Bn,ra,0,Gt,Ot.frustumCorners.TL,Ot.frustumCorners.TR,Ot.frustumCorners.BR,Ot.frustumCorners.BL,Ot.globeCenterInViewSpace,Ot.globeRadius,fs,0,Ot._farZ,wa),"globe_pole_raster",Xa,_r,cr);Le.setupElevationDraw(dr,jt,As),Ne.uploadCommonUniforms(dt,jt,an.toUnwrapped()),Ms&&Ne.renderDefaultNorthPole&&Yr(jt,vn),mn&&Ne.renderDefaultSouthPole&&(Bn=o.cC(o.bb(),Bn,[1,-1,1]),Yr(jt,kn))}}}})(H,Z,X,oe,xe);else{const Ne=H.context,Le=Ne.gl;let We,He;const tt=H.shadowRenderer,dt=Qc(H,H.longestCutoffRange),it=ks=>{if(He===ks)return;const ss=[];ss.push($w[ks]),dt.shouldRenderCutoff&&ss.push("RENDER_CUTOFF"),tt&&(ss.push("RENDER_SHADOWS"),tt.useNormalOffset&&ss.push("NORMAL_OFFSET")),We=H.getOrCreateProgram("terrainRaster",{defines:ss}),He=ks},jt=H.colorModeForRenderPass(),wt=new qr(Le.LEQUAL,qr.ReadWrite,H.depthRangeFor3D);cm.update(xe);const Ot=H.transform,Vt=i_(Ot.zoom,Z.exaggeration(),Z.sourceCache._source.tileSize);let Ct=[0,0,0];if(tt){const ks=H.style.directionalLight,ss=H.style.ambientLight;ks&&ss&&(Ct=xh(H.style,ks,ss))}{He=-1;const ks=Le.TRIANGLES,[ss,Ns]=[Z.gridIndexBuffer,Z.gridSegments];for(const Gt of oe){const es=X.getTile(Gt),fs=La.disabled,Ws=Z.prevTerrainTileForTile[Gt.key],As=Z.terrainTileForTile[Gt.key];Bw(Ws,As)&&cm.newMorphing(Gt.key,Ws,As,xe,250),Fe(H,es.emissiveTexture),Ne.activeTexture.set(Le.TEXTURE0),es.texture&&es.texture.bind(Le.LINEAR,Le.CLAMP_TO_EDGE);const gn=cm.getMorphValuesForProxy(Gt.key),an=gn?1:0;let Dn;gn&&(Dn={morphing:{srcDemTile:gn.from,dstDemTile:gn.to,phase:o.dn(gn.phase)}});const Gn=H.emissiveMode==="mrt-fallback"?1:0,en=a_(Gt.projMatrix,Ce(Gt.canonical,Ot.renderWorldCopies)?Vt/10:Vt,Ct,Gn);if(it(an),!We)continue;Z.setupElevationDraw(es,We,Dn);const Ms=Gt.toUnwrapped();tt&&tt.setupShadows(Ms,We),H.uploadCommonUniforms(Ne,We,Ms,null,dt),We.draw(H,ks,wt,fs,jt,pa.backCCW,en,"terrain_raster",Z.gridBuffer,ss,Ns)}}}}(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,H=this.proxySourceCache,Z=this.proxiedCoords[H.id],X=this._drapedRenderBatches.shift(),oe=E.style.order,xe=[];this._updateFBOs(E.emissiveMode==="mrt-fallback");let Ne=0;for(const Le of Z){const We=H.getTileByID(Le.proxyTileKey),He=H.proxyCachedFBO[Le.key]?H.proxyCachedFBO[Le.key][w]:void 0,tt=He!==void 0?H.renderCache[He]:this.pool[Ne++],dt=He!==void 0;if(We.texture=tt.tex,We.emissiveTexture=tt.emissiveTex,dt&&!tt.dirty){xe.push(We.tileID);continue}F.bindFramebuffer.set(tt.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,tt.dirty&&(F.clear({color:o.aq.transparent,stencil:0}),tt.dirty=!1);for(let wt=X.start;wt<=X.end;++wt){const Ot=E.style._mergedLayers[oe[wt]];if(Ot.isHidden(E.transform.zoom))continue;const Vt=E.style.getLayerSourceCache(Ot),Ct=Vt?this.proxyToSource[Le.key][Vt.id]:[Le];if(!Ct)continue;const ks=Ct;F.viewport.set([0,0,tt.fb.width,tt.fb.height]),jt!==(Vt?Vt.id:null)&&(this._setupStencil(tt,Ct,Ot,Vt),jt=Vt?Vt.id:null),E.renderLayer(E,Vt,Ot,ks)}if(it.drawBuffers([it.COLOR_ATTACHMENT0]),this._drapedRenderBatches.length===0)for(const wt of this._pendingGroundEffectLayers){const Ot=E.style._mergedLayers[oe[wt]];if(Ot.isHidden(E.transform.zoom))continue;const Vt=E.style.getLayerSourceCache(Ot),Ct=Vt?this.proxyToSource[Le.key][Vt.id]:[Le];if(!Ct)continue;const ks=Ct;F.viewport.set([0,0,tt.fb.width,tt.fb.height]),jt!==(Vt?Vt.id:null)&&(this._setupStencil(tt,Ct,Ot,Vt),jt=Vt?Vt.id:null),E.renderLayer(E,Vt,Ot,ks)}this.renderedToTile?(tt.dirty=!0,xe.push(We.tileID)):dt||--Ne,Ne===5&&(Ne=0,this.renderToBackBuffer(xe))}return this.renderToBackBuffer(xe),this.renderingToTexture=!1,F.bindFramebuffer.set(null),F.viewport.set([0,0,E.width,E.height]),X.end+1}postRender(){}isLayerOrderingCorrect(w){const E=w.order.length;let F=-1,H=E;for(let Z=0;ZF}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 H=this._visibleDemTiles.filter(Z=>Z.dem).map(Z=>{const X=Z.tileID,oe=1<(Z.t!==null?Z.t:Number.MAX_VALUE)-(X.t!==null?X.t:Number.MAX_VALUE));for(const Z of H){if(Z.t==null)return null;const X=Z.tile.dem.tree.raycast(Z.minx,Z.miny,Z.maxx,Z.maxy,w,E,F);if(X!=null)return X}return null}_createFBO(){const w=this.painter.context,E=w.gl,F=this.drapeBufferSize;w.activeTexture.set(E.TEXTURE0);const H=new o.T(w,{width:F[0],height:F[1],data:null},E.RGBA8);H.bind(E.LINEAR,E.CLAMP_TO_EDGE);const Z=w.createFramebuffer(F[0],F[1],1,null);let X;return Z.colorAttachment0.set(H.texture),this._emissiveTexture&&(X=new o.T(w,{width:F[0],height:F[1],data:null},E.R8),X.bind(E.LINEAR,E.CLAMP_TO_EDGE),Z.createColorAttachment(w,1),Z.colorAttachment1.set(X.texture)),Z.depthAttachment=new LC(w,Z.framebuffer),this._sharedDepthStencil===void 0?(this._sharedDepthStencil=w.createRenderbuffer(w.gl.DEPTH_STENCIL,F[0],F[1]),this._stencilRef=0,Z.depthAttachment.set(this._sharedDepthStencil),w.clear({stencil:0})):Z.depthAttachment.set(this._sharedDepthStencil),w.extTextureFilterAnisotropic&&E.texParameterf(E.TEXTURE_2D,w.extTextureFilterAnisotropic.TEXTURE_MAX_ANISOTROPY_EXT,w.extTextureFilterAnisotropicMax),{fb:Z,tex:H,emissiveTex:X,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,H=this.painter.context,Z=H.gl,X=this.drapeBufferSize;if(E){const oe=new o.T(H,{width:X[0],height:X[1],data:null},Z.R8);oe.bind(Z.LINEAR,Z.CLAMP_TO_EDGE),w.emissiveTex=oe,F.createColorAttachment(H,1),F.colorAttachment1.set(oe.texture)}else w.emissiveTex=void 0,F.removeColorAttachment(H,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 bd){w=!0;break}if(!w)return;const E={};for(let F=0;Fxe>oe.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 X=Object.values(E.proxyCachedFBO);E.proxyCachedFBO={};for(let oe=0;oe=0;X--){const oe=F[X];if(E.getTileByID(oe.key),E.proxyCachedFBO[oe.key]!==void 0){const xe=w[oe.key],Ne=this.proxyToSource[oe.key];let Le=0;for(const We in Ne){const He=Ne[We],tt=xe[We];if(!tt||tt.length!==He.length||He.some((dt,it)=>dt!==tt[it]||H[We]&&H[We].hasOwnProperty(dt.key))){Le=-1;break}++Le}for(const We in E.proxyCachedFBO[oe.key])E.renderCache[E.proxyCachedFBO[oe.key][We]].dirty=Le<0||Le!==Object.values(xe).length}}const Z=[...this._drapedRenderBatches];Z.sort((X,oe)=>oe.end-oe.start-(X.end-X.start));for(const X of Z)for(const oe of F){if(E.proxyCachedFBO[oe.key])continue;let xe=E.renderCachePool.pop();xe===void 0&&E.renderCache.length<50&&(xe=E.renderCache.length,E.renderCache.push(this._createFBO())),xe!==void 0&&(E.proxyCachedFBO[oe.key]={},E.proxyCachedFBO[oe.key][X.start]=xe,E.renderCache[xe].dirty=!0)}this._tilesDirty={}}_setupStencil(w,E,F,H){if(!H||!this._sourceTilesOverlap[H.id])return void(this._overlapStencilType&&(this._overlapStencilType=!1));const Z=this.painter.context,X=Z.gl;if(E.length<=1)return void(this._overlapStencilType=!1);let oe;if(F.isTileClipped())oe=E.length,this._overlapStencilMode.test={func:X.EQUAL,mask:255},this._overlapStencilType="Clip";else{if(!(E[0].overscaledZ>E[E.length-1].overscaledZ))return void(this._overlapStencilType=!1);oe=1,this._overlapStencilMode.test={func:X.GREATER,mask:255},this._overlapStencilType="Mask"}this._stencilRef+oe>255&&(Z.clear({stencil:0}),this._stencilRef=0),this._stencilRef+=oe,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):La.disabled}_renderTileClippingMasks(w,E){const F=this.painter,H=this.painter.context,Z=H.gl;F._tileClippingMaskIDs={},H.setColorMode(Ma.disabled),H.setDepthMode(qr.disabled);const X=F.getOrCreateProgram("clippingMask");for(const oe of w){const xe=F._tileClippingMaskIDs[oe.key]=--E;X.draw(F,Z.TRIANGLES,qr.disabled,new La({func:Z.ALWAYS,mask:0},xe,255,Z.KEEP,Z.KEEP,Z.REPLACE),Ma.disabled,pa.disabled,mt(oe.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 H=E._camera.position,Z=o.bU(1,E.center.lat),X=[H[0],H[1],H[2]/Z,0],oe=o.cV([],F.slice(0,3),X);o.ay(oe,oe);const xe=this.raycast(X,oe,this._exaggeration);return xe!==null&&xe?(o.bg(X,X,oe,xe),X[3]=X[2],X[2]*=Z,X):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 H=this.proxiedCoords[w.id]=[],Z=this.proxyCoords;for(let xe=0;xeLe.overscaledZ-Ne.overscaledZ)}_setupProxiedCoordsForImageSource(w,E,F){if(!w.getSource().loaded())return;const H=this.proxiedCoords[w.id]=[],Z=this.proxyCoords,X=w.getSource(),oe=X.tileID;if(!oe)return;const xe=new o.P(oe.x,oe.y)._div(1<(We.min.x=Math.min(We.min.x,He.x-xe.x),We.min.y=Math.min(We.min.y,He.y-xe.y),We.max.x=Math.max(We.max.x,He.x-xe.x),We.max.y=Math.max(We.max.y,He.y-xe.y),We),{min:new o.P(Number.MAX_VALUE,Number.MAX_VALUE),max:new o.P(-Number.MAX_VALUE,-Number.MAX_VALUE)}),Le=(We,He)=>{const tt=We.wrap+We.canonical.x/(1<jt+Ne.max.x||dt+itwt+Ne.max.y};for(let We=0;WeX.key===E.tileID.key);if(Z)return Z}if(E.tileID.key!==w.key){const Z=w.canonical.z-E.tileID.canonical.z;let X,oe,xe;H=o.bb();const Ne=E.tileID.wrap-w.wrap<0?(X=o.an>>Z,oe=X*((E.tileID.canonical.x<=We){const He=w.canonical.z-We;E.getSource().reparseOverscaled?(oe=Math.max(w.canonical.z+2,E.transform.tileZoom),X=new o.aR(oe,w.wrap,We,w.canonical.x>>He,w.canonical.y>>He)):He!==0&&(oe=We,X=new o.aR(oe,w.wrap,We,w.canonical.x>>He,w.canonical.y>>He))}X.key!==w.key&&(Ne.push(X.key),F=E.getTile(X))}const Le=We=>{Ne.forEach(He=>{H[He]=We}),Ne.length=0};for(oe-=1;oe>=xe&&(!F||!F.hasData());oe--){F&&Le(F.tileID.key);const We=X.calculateScaledKey(oe);if(F=E.getTileByID(We),F&&F.hasData())break;const He=H[We];if(He===null)break;He===void 0?Ne.push(We):F=E.getTileByID(He)}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 Es(R,w,E){const F=function(oe,xe,Ne){const Le=o.bi(xe,oe),We=o.bi(Ne,[.2126,.7152,.0722]),He=(dt,it,jt)=>(1-jt)*dt+jt*it,tt=He(1-.3*Math.min(We,1),1,Math.min(Le+1,1));return He(.92,1,Math.asin(o.aC(xe[2],-1,1))/Math.PI+.5)*tt}(R,[0,0,1],w),H=[0,0,0];o.bJ(H,E.slice(0,3),F);const Z=[0,0,0];o.bJ(Z,w.slice(0,3),R[2]);const X=[0,0,0];return o.cT(X,H,Z),o.cW(X)}const Qs=["fill","fillOutline","fillPattern","line","linePattern","background","backgroundPattern","hillshade","raster"],Cn=["stars","rainParticle","snowParticle","fillExtrusion","fillExtrusionGroundEffect","building","buildingBloom","elevatedStructures","model","symbol"];class Xn{static cacheKey(w,E,F,H){const Z=[E];H&&Z.push(H.cacheKey);for(const X of F)(typeof X=="string"&&X.includes(" ")||w.usedDefines.has(X))&&Z.push(X);return Z.join("/")}constructor(w,E,F,H,Z,X){const oe=w.gl;this.program=oe.createProgram(),this.configuration=H,this.name=E,this.fixedDefines=[...X];const xe=`#version 300 es ${(H?H.defines():[]).concat(X.map(it=>`#define ${it}`)).join(` `)}`,Ne=[xe,Cv];for(const it of F.fragmentIncludes)Ne.push(Zp[it]);Ne.push(F.fragmentSource);const Le=Ne.join(` `),We=[xe,j2];for(const it of F.vertexIncludes)We.push(Zp[it]);this.forceManualRenderingForInstanceIDShaders=w.forceManualRenderingForInstanceIDShaders&&F.vertexSource.includes("gl_InstanceID"),this.forceManualRenderingForInstanceIDShaders&&We.push("uniform int u_instanceID;"),We.push(F.vertexSource);let He=We.join(` `);this.forceManualRenderingForInstanceIDShaders&&(He=He.replaceAll("gl_InstanceID","u_instanceID"));const tt=oe.createShader(oe.FRAGMENT_SHADER);if(oe.isContextLost())return void(this.failedToCreate=!0);oe.shaderSource(tt,Le),oe.compileShader(tt),oe.attachShader(this.program,tt);const dt=oe.createShader(oe.VERTEX_SHADER);oe.isContextLost()?this.failedToCreate=!0:(oe.shaderSource(dt,He),oe.compileShader(dt),oe.attachShader(this.program,dt),this.attributes={},oe.linkProgram(this.program),oe.deleteShader(dt),oe.deleteShader(tt),this.fixedUniforms=Z(w),this.fixedUniformsEntries=Object.entries(this.fixedUniforms),this.binderUniforms=H?H.getUniforms(w):[],this.forceManualRenderingForInstanceIDShaders&&(this.instancingUniforms=(it=>({u_instanceID:new o.bX(it)}))(w)),(X.includes("TERRAIN")||X.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)),X.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)),X.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)),X.includes("RENDER_CUTOFF")&&(this.cutoffUniforms=(it=>({u_cutoff_params:new o.cO(it)}))(w)),X.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)),X.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 H in E)F[H]&&F[H].set(this.program,H,E[H])}}setGlobeUniformValues(w,E){if(!this.globeUniforms)return;const F=this.globeUniforms;if(!this.failedToCreate){w.program.set(this.program);for(const H in E)F[H]&&F[H].set(this.program,H,E[H])}}setFogUniformValues(w,E){if(!this.fogUniforms)return;const F=this.fogUniforms;if(!this.failedToCreate){w.program.set(this.program);for(const H in E)F[H].set(this.program,H,E[H])}}setCutoffUniformValues(w,E){if(!this.cutoffUniforms)return;const F=this.cutoffUniforms;if(!this.failedToCreate){w.program.set(this.program);for(const H in E)F[H].set(this.program,H,E[H])}}setLightsUniformValues(w,E){if(!this.lightsUniforms)return;const F=this.lightsUniforms;if(!this.failedToCreate){w.program.set(this.program);for(const H in E)F[H].set(this.program,H,E[H])}}setShadowUniformValues(w,E){if(this.failedToCreate||!this.shadowUniforms)return;const F=this.shadowUniforms;w.program.set(this.program);for(const H in E)F[H].set(this.program,H,E[H])}_drawDebugWireframe(w,E,F,H,Z,X,oe,xe,Ne,Le){const We=w.options.wireframe;if(We.terrain===!1&&We.layers2D===!1&&We.layers3D===!1)return;const He=w.context;if(!(!(!We.terrain||this.name!=="terrainRaster"&&this.name!=="globeRaster")||!(!We.layers2D||w._terrain&&w._terrain.renderingToTexture||!Qs.includes(this.name))||!(!We.layers3D||!Cn.includes(this.name))))return;const tt=He.gl,dt=w.wireframeDebugCache.getLinesFromTrianglesBuffer(w.frameCounter,Z,He);if(!dt)return;const it=[...this.fixedDefines,"DEBUG_WIREFRAME"],jt=w.getOrCreateProgram(this.name,{config:this.configuration,defines:it});He.program.set(jt.program);const wt=(Ct,ks,ss)=>{if(ks[Ct]&&ss[Ct])for(const Ns in ks[Ct])ss[Ct][Ns]&&ss[Ct][Ns].set(ss.program,Ns,ks[Ct][Ns].current)};Ne&&Ne.setUniforms(jt.program,He,jt.binderUniforms,oe,{zoom:xe}),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(),He.setColorMode(new Ma([tt.ONE,tt.ONE_MINUS_SRC_ALPHA,tt.ZERO,tt.ONE],o.aq.transparent,[!0,!0,!0,!1])),He.setDepthMode(new qr(E.func===tt.LESS?tt.LEQUAL:E.func,qr.ReadOnly,E.range)),He.setStencilMode(La.disabled);const Ot=3*X.primitiveLength*2,Vt=3*X.primitiveOffset*2*2;if(this.forceManualRenderingForInstanceIDShaders){const Ct=Le||1;for(let ks=0;ks1?tt.drawElementsInstanced(tt.LINES,Ot,tt.UNSIGNED_SHORT,Vt,Le):tt.drawElements(tt.LINES,Ot,tt.UNSIGNED_SHORT,Vt);Z.bind(),He.program.set(this.program),He.setDepthMode(E),He.setStencilMode(F),He.setColorMode(H)}checkUniforms(w,E,F){if(this.fixedDefines.includes(E)){for(const H of Object.keys(F))if(!F[H].initialized)throw new Error(`Program '${this.name}', from draw '${w}': uniform ${H} not set but required by ${E} being defined`)}}draw(w,E,F,H,Z,X,oe,xe,Ne,Le,We,He,tt,dt,it,jt){const wt=w.context,Ot=wt.gl;if(this.failedToCreate)return;wt.program.set(this.program),wt.setDepthMode(F),wt.setStencilMode(H),wt.setColorMode(Z),wt.setCullFace(X);for(const[Gt,es]of this.fixedUniformsEntries)es.set(this.program,Gt,oe[Gt]);dt&&dt.setUniforms(this.program,wt,this.binderUniforms,He,{zoom:tt});const Vt={[Ot.POINTS]:1,[Ot.LINES]:2,[Ot.TRIANGLES]:3,[Ot.LINE_STRIP]:1}[E];this.checkUniforms(xe,"RENDER_SHADOWS",this.shadowUniforms);const Ct=it||[],ks=dt?dt.getPaintVertexBuffers():[],ss=E===Ot.TRIANGLES&&Le,Ns=jt&&jt>0?1:void 0;for(const Gt of We.get()){const es=Gt.vaos||(Gt.vaos={});if((es[xe]||(es[xe]=new mk)).bind(wt,this,Ne,ks,Le,Gt.vertexOffset,Ct,Ns),this.forceManualRenderingForInstanceIDShaders){const fs=jt||1;for(let Ws=0;Ws1?Ot.drawElementsInstanced(E,Gt.primitiveLength*Vt,Ot.UNSIGNED_SHORT,Gt.primitiveOffset*Vt*2,jt):Le?Ot.drawElements(E,Gt.primitiveLength*Vt,Ot.UNSIGNED_SHORT,Gt.primitiveOffset*Vt*2):Ot.drawArrays(E,Gt.vertexOffset,Gt.vertexLength);ss&&this._drawDebugWireframe(w,F,H,Z,Le,Gt,He,tt,dt,jt)}}}function Js(R,w,E=0){const F=Math.pow(2,w.tileID.overscaledZ),H=w.tileSize*Math.pow(2,R.transform.tileZoom)/F,Z=H*(w.tileID.canonical.x+w.tileID.wrap*F),X=H*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,R.transform.tileZoom),u_pixel_coord_upper:[Z>>16,X>>16],u_pixel_coord_lower:[65535&Z,65535&X],u_pattern_transition:E}}const On={terrain:0,flat:1},nr=o.bb(),Mr=(R,w,E,F,H,Z,X,oe,xe,Ne,Le,We,He,tt,dt,it,jt,wt,Ot=[0,0,1])=>{const Vt=w.style.light,Ct=Vt.properties.get("position"),ks=[Ct.x,Ct.y,Ct.z],ss=o.dE();Vt.properties.get("anchor")==="viewport"&&(o.dF(ss,-w.transform.angle),o.dG(ks,ks,ss));const Ns=Vt.properties.get("color").toPremultipliedRenderColor(null),Gt=w.transform,es={u_matrix:R,u_lightpos:ks,u_lightintensity:Vt.properties.get("intensity"),u_lightcolor:[Ns.r,Ns.g,Ns.b],u_vertical_gradient:+E,u_opacity:F,u_tile_id:[0,0,0],u_zoom_transition:0,u_inv_rot_matrix:nr,u_merc_center:[0,0],u_up_dir:[0,0,0],u_height_lift:0,u_height_type:On[Ne],u_base_type:On[Le],u_ao:H,u_edge_radius:Z,u_width_scale:X,u_flood_light_color:dt,u_vertical_scale:it,u_flood_light_intensity:jt,u_ground_shadow_factor:wt,u_front_cutoff_params:Ot};return Gt.projection.name==="globe"&&(es.u_tile_id=[oe.canonical.x,oe.canonical.y,1<({u_matrix:R,u_edge_radius:w,u_width_scale:E,u_vertical_scale:F,u_height_type:On[H],u_base_type:On[Z]}),Fn=(R,w,E,F,H,Z,X,oe,xe,Ne,Le,We,He,tt,dt,it,jt,wt)=>{const Ot=Mr(R,w,E,F,H,Z,X,oe,Ne,Le,We,He,tt,dt,it,jt,1,[0,0,0]),Vt={u_height_factor:-Math.pow(2,oe.overscaledZ)/xe.tileSize/8};return Object.assign(Ot,Js(w,xe,wt),Vt)},$r=(R,w,E)=>({u_matrix:R,u_emissive_strength:w,u_ground_shadow_factor:E}),ba=(R,w,E,F,H,Z=0)=>Object.assign($r(R,w,H),Js(E,F,Z)),fa=(R,w,E,F)=>({u_matrix:R,u_world:E,u_emissive_strength:w,u_ground_shadow_factor:F}),Fi=(R,w,E,F,H,Z,X=0)=>Object.assign(ba(R,w,E,F,Z,X),{u_world:H}),bi=(R,w)=>({u_matrix:R,u_depth_bias:w}),sl=(R,w)=>({u_matrix:R,u_ground_shadow_factor:w}),Li=(R,w,E,F,H)=>({u_matrix:R,u_camera_pos:[w[0],w[1],w[2]],u_depth_bias:E,u_height_scale:F,u_reset_depth:H}),Dl=(R,w,E)=>({u_image:R,u_opacity:w,u_blend_mode:E}),Pd=(R,w,E,F,H,Z,X,oe,xe,Ne=[0,0,1])=>({u_matrix:R,u_normal_matrix:w,u_opacity:E,u_faux_facade_ao_intensity:F,u_camera_pos:H,u_tile_to_meter:Z,u_facade_emissive_chance:X,u_flood_light_color:oe,u_flood_light_intensity:xe,u_front_cutoff_params:Ne}),nl=R=>({u_matrix:R}),Di=R=>({u_matrix:R}),ti=(R,w,E,F,H,Z,X,oe)=>{const xe=o.an/Z.tileSize;return{u_matrix:R,u_inv_rot_matrix:w,u_camera_to_center_distance:E.getCameraToCenterDistance(oe),u_extrude_scale:[E.pixelsToGLUnits[0]/xe,E.pixelsToGLUnits[1]/xe],u_zoom_transition:F,u_tile_id:X,u_merc_center:H}},ol=(R,w,E,F)=>({u_matrix:R,u_inv_matrix:w,u_camera_to_center_distance:E.getCameraToCenterDistance(F),u_viewport_size:[E.width,E.height]}),co=(R,w,E=1)=>({u_matrix:R,u_color:w,u_overlay:0,u_overlay_scale:E}),Yo=o.bb(),jd=(R,w,E,F,H,Z,X)=>{const oe=R.transform,xe=oe.projection.name==="globe",Ne=xe?o.dH(oe.zoom,w.canonical)*oe._pixelsPerMercatorPixel:o.aA(E,1,Z),Le={u_matrix:w.projMatrix,u_extrude_scale:Ne,u_intensity:X,u_inv_rot_matrix:Yo,u_merc_center:[0,0],u_tile_id:[0,0,0],u_zoom_transition:0,u_up_dir:[0,0,0]};if(xe){Le.u_inv_rot_matrix=F,Le.u_merc_center=H,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:H,u_grid_matrix:Z,u_tl_parent:X,u_scale_parent:Le,u_fade_t:We.mix,u_opacity:We.opacity*He.paint.get("raster-opacity"),u_image0:0,u_image1:1,u_brightness_low:He.paint.get("raster-brightness-min"),u_brightness_high:He.paint.get("raster-brightness-max"),u_saturation_factor:o.dJ(He.paint.get("raster-saturation")),u_contrast_factor:o.dI(He.paint.get("raster-contrast")),u_spin_weights:Jp(He.paint.get("raster-hue-rotate")),u_perspective_transform:tt,u_raster_elevation:dt,u_zoom_transition:oe,u_merc_center:xe,u_cutoff_params:Ne,u_colorization_mix:Oh(o.dK,jt,Ot),u_colorization_offset:Nd(o.dK,wt,Ot),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:ks,u_zbias_factor:tu(R)});function Jp(R){R*=Math.PI/180;const w=Math.sin(R),E=Math.cos(R);return[(2*E+1)/3,(-Math.sqrt(3)*w-E+1)/3,(Math.sqrt(3)*w-E+1)/3]}const ud=.05,gc=(R,w,E,F,H,Z,X,oe,xe,Ne,Le,We)=>({u_matrix:R,u_normalize_matrix:w,u_globe_matrix:E,u_merc_matrix:F,u_grid_matrix:H,u_tl_parent:Z,u_scale_parent:Ne,u_fade_t:Le.mix,u_opacity:Le.opacity,u_image0:0,u_image1:1,u_raster_elevation:We,u_zoom_transition:X,u_merc_center:oe,u_cutoff_params:xe}),ed=(R,w,E,F,H,Z,X,oe,xe,Ne)=>({u_particle_texture:R,u_particle_texture_side_len:w,u_tile_offset:E,u_velocity:F,u_color_ramp:Z,u_velocity_res:H,u_max_speed:X,u_uv_offset:oe,u_data_scale:[255*xe[0],255*xe[1]],u_data_offset:Ne,u_particle_pos_scale:1.1,u_particle_pos_offset:[ud,ud]}),_u=(R,w,E,F,H,Z,X,oe,xe,Ne)=>({u_particle_texture:R,u_particle_texture_side_len:w,u_velocity:E,u_velocity_res:F,u_max_speed:H,u_speed_factor:Z,u_reset_rate:X,u_rand_seed:Math.random(),u_uv_offset:oe,u_data_scale:[255*xe[0],255*xe[1]],u_data_offset:Ne,u_particle_pos_scale:1.1,u_particle_pos_offset:[ud,ud]}),Tc=o.bb(),Iu=(R,w,E,F,H,Z,X,oe,xe,Ne,Le,We,He,tt,dt,it,jt,wt,Ot,Vt,Ct,ks,ss,Ns)=>{const Gt=H.transform,es={u_is_size_zoom_constant:+(R==="constant"||R==="source"),u_is_size_feature_constant:+(R==="constant"||R==="camera"),u_size_t:w?w.uSizeT:0,u_size:w?w.uSize:0,u_camera_to_center_distance:Gt.getCameraToCenterDistance(Ot),u_rotate_symbol:+E,u_aspect_ratio:Gt.width/Gt.height,u_fade_change:H.options.fadeDuration?H.symbolFadeChange:1,u_matrix:Z,u_label_plane_matrix:X,u_coord_matrix:oe,u_is_text:+Ne,u_elevation_from_sea:xe?1:0,u_pitch_with_map:+F,u_texsize:Le,u_texsize_icon:We,u_texture:0,u_texture_icon:1,u_tile_id:[0,0,0],u_zoom_transition:0,u_inv_rot_matrix:Tc,u_merc_center:[0,0],u_camera_forward:[0,0,0],u_ecef_origin:[0,0,0],u_tile_matrix:Tc,u_up_vector:[0,-1,0],u_color_adj_mat:ks,u_icon_transition:ss||0,u_gamma_scale:F?H.transform.getCameraToCenterDistance(Ot)*Math.cos(H.terrain?0:H.transform._pitch):1,u_device_pixel_ratio:o.o.devicePixelRatio,u_is_halo:1,u_scale_factor:Ns||1,u_ground_shadow_factor:Vt,u_inv_matrix:o.b7(o.bb(),X),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 Ot.name==="globe"&&(es.u_tile_id=[tt.canonical.x,tt.canonical.y,1<({u_matrix:R,u_emissive_strength:w,u_opacity:E,u_color:F}),Vc=(R,w,E,F,H,Z,X,oe,xe)=>Object.assign(function(Ne,Le,We,He,tt,dt){const{width:it,height:jt}=He.imageManager.getPixelSize(Le),wt=Math.pow(2,dt.tileID.overscaledZ),Ot=dt.tileSize*Math.pow(2,He.transform.tileZoom)/wt,Vt=Ot*(dt.tileID.canonical.x+dt.tileID.wrap*wt),Ct=Ot*dt.tileID.canonical.y;return{u_image:0,u_pattern_tl:We.tl,u_pattern_br:We.br,u_texsize:[it,jt],u_pattern_size:We.displaySize,u_pattern_units_to_pixels:tt?[He.transform.width,-1*He.transform.height]:[1/o.aA(dt,1,He.transform.tileZoom),1/o.aA(dt,1,He.transform.tileZoom)],u_pixel_coord_upper:[Vt>>16,Ct>>16],u_pixel_coord_lower:[65535&Vt,65535&Ct]}}(0,Z,X,F,oe,xe),{u_matrix:R,u_emissive_strength:w,u_opacity:E}),th=new Float32Array(o.b9([])),Xl=(R,w,E,F,H,Z,X,oe,xe,Ne,Le,We,He,tt=[0,0,0],dt,it,jt)=>{const wt=H.style.light,Ot=wt.properties.get("position"),Vt=[-Ot.x,-Ot.y,Ot.z],Ct=o.dE();wt.properties.get("anchor")==="viewport"&&(o.dF(Ct,-H.transform.angle),o.dG(Vt,Vt,Ct));const ks=Le.alphaMode==="MASK",ss=wt.properties.get("color").toNonPremultipliedRenderColor(null),Ns=He.paint.get("model-ambient-occlusion-intensity"),Gt=He.paint.get("model-color").constantOr(o.aq.white).toNonPremultipliedRenderColor(null);return Gt.a=He.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,We=it.emissionStrength,Z*=it.opacity),{u_matrix:R,u_lighting_matrix:w,u_normal_matrix:E,u_node_matrix:F||th,u_lightpos:Vt,u_lightintensity:wt.properties.get("intensity"),u_lightcolor:[ss.r,ss.g,ss.b],u_camera_pos:tt,u_opacity:Z,u_baseTextureIsAlpha:0,u_alphaMask:+ks,u_alphaCutoff:Le.alphaCutoff,u_baseColorFactor:X.toNonPremultipliedRenderColor(null).toArray01(),u_emissiveFactor:oe.toNonPremultipliedRenderColor(null).toArray01(),u_metallicFactor:xe,u_roughnessFactor:Ne,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:Ns,u_emissive_strength:We,u_occlusionTextureTransform:dt||[0,0,0,0]}},Du=(R,w=th,E=th)=>({u_matrix:R,u_instance:w,u_node_matrix:E}),Dm={fillExtrusion:R=>({u_matrix:new o.b$(R),u_lightpos:new o.bY(R),u_lightintensity:new o.bZ(R),u_lightcolor:new o.bY(R),u_vertical_gradient:new o.bZ(R),u_opacity:new o.bZ(R),u_edge_radius:new o.bZ(R),u_width_scale:new o.bZ(R),u_ao:new o.b_(R),u_height_type:new o.bX(R),u_base_type:new o.bX(R),u_tile_id:new o.bY(R),u_zoom_transition:new o.bZ(R),u_inv_rot_matrix:new o.b$(R),u_merc_center:new o.b_(R),u_up_dir:new o.bY(R),u_height_lift:new o.bZ(R),u_flood_light_color:new o.bY(R),u_vertical_scale:new o.bZ(R),u_flood_light_intensity:new o.bZ(R),u_ground_shadow_factor:new o.bY(R),u_front_cutoff_params:new o.bY(R)}),fillExtrusionDepth:R=>({u_matrix:new o.b$(R),u_edge_radius:new o.bZ(R),u_width_scale:new o.bZ(R),u_vertical_scale:new o.bZ(R),u_height_type:new o.bX(R),u_base_type:new o.bX(R)}),fillExtrusionPattern:R=>({u_matrix:new o.b$(R),u_lightpos:new o.bY(R),u_lightintensity:new o.bZ(R),u_lightcolor:new o.bY(R),u_vertical_gradient:new o.bZ(R),u_height_factor:new o.bZ(R),u_edge_radius:new o.bZ(R),u_width_scale:new o.bZ(R),u_ao:new o.b_(R),u_height_type:new o.bX(R),u_base_type:new o.bX(R),u_tile_id:new o.bY(R),u_zoom_transition:new o.bZ(R),u_inv_rot_matrix:new o.b$(R),u_merc_center:new o.b_(R),u_up_dir:new o.bY(R),u_height_lift:new o.bZ(R),u_image:new o.bX(R),u_texsize:new o.b_(R),u_pixel_coord_upper:new o.b_(R),u_pixel_coord_lower:new o.b_(R),u_tile_units_to_pixels:new o.bZ(R),u_opacity:new o.bZ(R),u_pattern_transition:new o.bZ(R)}),fillExtrusionGroundEffect:R=>({u_matrix:new o.b$(R),u_opacity:new o.bZ(R),u_ao_pass:new o.bZ(R),u_meter_to_tile:new o.bZ(R),u_ao:new o.b_(R),u_flood_light_intensity:new o.bZ(R),u_flood_light_color:new o.bY(R),u_attenuation:new o.bZ(R),u_edge_radius:new o.bZ(R),u_fb:new o.bX(R),u_fb_size:new o.bZ(R),u_dynamic_offset:new o.bZ(R)}),fill:R=>({u_matrix:new o.b$(R),u_emissive_strength:new o.bZ(R),u_ground_shadow_factor:new o.bY(R)}),fillPattern:R=>({u_matrix:new o.b$(R),u_emissive_strength:new o.bZ(R),u_image:new o.bX(R),u_texsize:new o.b_(R),u_pixel_coord_upper:new o.b_(R),u_pixel_coord_lower:new o.b_(R),u_tile_units_to_pixels:new o.bZ(R),u_ground_shadow_factor:new o.bY(R),u_pattern_transition:new o.bZ(R)}),fillOutline:R=>({u_matrix:new o.b$(R),u_emissive_strength:new o.bZ(R),u_world:new o.b_(R),u_ground_shadow_factor:new o.bY(R)}),fillOutlinePattern:R=>({u_matrix:new o.b$(R),u_emissive_strength:new o.bZ(R),u_world:new o.b_(R),u_image:new o.bX(R),u_texsize:new o.b_(R),u_pixel_coord_upper:new o.b_(R),u_pixel_coord_lower:new o.b_(R),u_tile_units_to_pixels:new o.bZ(R),u_ground_shadow_factor:new o.bY(R),u_pattern_transition:new o.bZ(R)}),lineBlendComposite:R=>({u_image:new o.bX(R),u_opacity:new o.bZ(R),u_blend_mode:new o.bX(R)}),building:R=>({u_matrix:new o.b$(R),u_normal_matrix:new o.b$(R),u_opacity:new o.bZ(R),u_faux_facade_ao_intensity:new o.bZ(R),u_camera_pos:new o.bY(R),u_tile_to_meter:new o.bZ(R),u_facade_emissive_chance:new o.bZ(R),u_flood_light_color:new o.bY(R),u_flood_light_intensity:new o.bZ(R),u_front_cutoff_params:new o.bY(R)}),buildingBloom:R=>({u_matrix:new o.b$(R)}),buildingDepth:R=>({u_matrix:new o.b$(R)}),elevatedStructuresDepth:R=>({u_matrix:new o.b$(R),u_depth_bias:new o.bZ(R)}),elevatedStructures:R=>({u_matrix:new o.b$(R),u_ground_shadow_factor:new o.bY(R)}),elevatedStructuresDepthReconstruct:R=>({u_matrix:new o.b$(R),u_camera_pos:new o.bY(R),u_depth_bias:new o.bZ(R),u_height_scale:new o.bZ(R),u_reset_depth:new o.bZ(R)}),circle:o.dO,collisionBox:R=>({u_matrix:new o.b$(R),u_inv_rot_matrix:new o.b$(R),u_camera_to_center_distance:new o.bZ(R),u_extrude_scale:new o.b_(R),u_zoom_transition:new o.bZ(R),u_merc_center:new o.b_(R),u_tile_id:new o.bY(R)}),collisionCircle:R=>({u_matrix:new o.b$(R),u_inv_matrix:new o.b$(R),u_camera_to_center_distance:new o.bZ(R),u_viewport_size:new o.b_(R)}),debug:R=>({u_color:new o.dl(R),u_matrix:new o.b$(R),u_overlay:new o.bX(R),u_overlay_scale:new o.bZ(R)}),clippingMask:R=>({u_matrix:new o.b$(R)}),heatmap:R=>({u_extrude_scale:new o.bZ(R),u_intensity:new o.bZ(R),u_matrix:new o.b$(R),u_inv_rot_matrix:new o.b$(R),u_merc_center:new o.b_(R),u_tile_id:new o.bY(R),u_zoom_transition:new o.bZ(R),u_up_dir:new o.bY(R)}),heatmapTexture:R=>({u_image:new o.bX(R),u_color_ramp:new o.bX(R),u_opacity:new o.bZ(R)}),hillshade:R=>({u_matrix:new o.b$(R),u_image:new o.bX(R),u_latrange:new o.b_(R),u_light:new o.b_(R),u_shadow:new o.dl(R),u_highlight:new o.dl(R),u_emissive_strength:new o.bZ(R),u_accent:new o.dl(R)}),hillshadePrepare:R=>({u_matrix:new o.b$(R),u_image:new o.bX(R),u_dimension:new o.b_(R),u_zoom:new o.bZ(R)}),line:o.dN,linePattern:o.dM,raster:R=>({u_matrix:new o.b$(R),u_normalize_matrix:new o.b$(R),u_globe_matrix:new o.b$(R),u_merc_matrix:new o.b$(R),u_grid_matrix:new o.dm(R),u_tl_parent:new o.b_(R),u_scale_parent:new o.bZ(R),u_fade_t:new o.bZ(R),u_opacity:new o.bZ(R),u_image0:new o.bX(R),u_image1:new o.bX(R),u_brightness_low:new o.bZ(R),u_brightness_high:new o.bZ(R),u_saturation_factor:new o.bZ(R),u_contrast_factor:new o.bZ(R),u_spin_weights:new o.bY(R),u_perspective_transform:new o.b_(R),u_raster_elevation:new o.bZ(R),u_zoom_transition:new o.bZ(R),u_merc_center:new o.b_(R),u_cutoff_params:new o.cO(R),u_colorization_mix:new o.cO(R),u_colorization_offset:new o.bZ(R),u_color_ramp:new o.bX(R),u_texture_offset:new o.b_(R),u_texture_res:new o.b_(R),u_emissive_strength:new o.bZ(R),u_zbias_factor:new o.bZ(R)}),rasterParticle:R=>({u_matrix:new o.b$(R),u_normalize_matrix:new o.b$(R),u_globe_matrix:new o.b$(R),u_merc_matrix:new o.b$(R),u_grid_matrix:new o.dm(R),u_tl_parent:new o.b_(R),u_scale_parent:new o.bZ(R),u_fade_t:new o.bZ(R),u_opacity:new o.bZ(R),u_image0:new o.bX(R),u_image1:new o.bX(R),u_raster_elevation:new o.bZ(R),u_zoom_transition:new o.bZ(R),u_merc_center:new o.b_(R),u_cutoff_params:new o.cO(R)}),rasterParticleTexture:R=>({u_texture:new o.bX(R),u_opacity:new o.bZ(R)}),rasterParticleDraw:R=>({u_particle_texture:new o.bX(R),u_particle_texture_side_len:new o.bZ(R),u_tile_offset:new o.b_(R),u_velocity:new o.bX(R),u_color_ramp:new o.bX(R),u_velocity_res:new o.b_(R),u_max_speed:new o.bZ(R),u_uv_offset:new o.b_(R),u_data_scale:new o.b_(R),u_data_offset:new o.bZ(R),u_particle_pos_scale:new o.bZ(R),u_particle_pos_offset:new o.b_(R)}),rasterParticleUpdate:R=>({u_particle_texture:new o.bX(R),u_particle_texture_side_len:new o.bZ(R),u_velocity:new o.bX(R),u_velocity_res:new o.b_(R),u_max_speed:new o.bZ(R),u_speed_factor:new o.bZ(R),u_reset_rate:new o.bZ(R),u_rand_seed:new o.bZ(R),u_uv_offset:new o.b_(R),u_data_scale:new o.b_(R),u_data_offset:new o.bZ(R),u_particle_pos_scale:new o.bZ(R),u_particle_pos_offset:new o.b_(R)}),symbol:R=>({u_is_size_zoom_constant:new o.bX(R),u_is_size_feature_constant:new o.bX(R),u_size_t:new o.bZ(R),u_size:new o.bZ(R),u_camera_to_center_distance:new o.bZ(R),u_rotate_symbol:new o.bX(R),u_aspect_ratio:new o.bZ(R),u_fade_change:new o.bZ(R),u_matrix:new o.b$(R),u_label_plane_matrix:new o.b$(R),u_coord_matrix:new o.b$(R),u_is_text:new o.bX(R),u_elevation_from_sea:new o.bX(R),u_pitch_with_map:new o.bX(R),u_texsize:new o.b_(R),u_texsize_icon:new o.b_(R),u_texture:new o.bX(R),u_texture_icon:new o.bX(R),u_gamma_scale:new o.bZ(R),u_device_pixel_ratio:new o.bZ(R),u_tile_id:new o.bY(R),u_zoom_transition:new o.bZ(R),u_inv_rot_matrix:new o.b$(R),u_merc_center:new o.b_(R),u_camera_forward:new o.bY(R),u_tile_matrix:new o.b$(R),u_up_vector:new o.bY(R),u_ecef_origin:new o.bY(R),u_is_halo:new o.bX(R),u_icon_transition:new o.bZ(R),u_color_adj_mat:new o.b$(R),u_scale_factor:new o.bZ(R),u_ground_shadow_factor:new o.bY(R),u_inv_matrix:new o.b$(R),u_normal_scale:new o.bZ(R),u_lutTexture:new o.bX(R),u_zoom:new o.bZ(R),u_spp_fill_np_color:new o.cO(R),u_spp_halo_np_color:new o.cO(R),u_spp_opacity:new o.bZ(R),u_spp_halo_width:new o.bZ(R),u_spp_halo_blur:new o.bZ(R),u_spp_emissive_strength:new o.bZ(R),u_spp_occlusion_opacity:new o.bZ(R),u_spp_z_offset:new o.bZ(R),u_spp_translate_rotation:new o.b_(R)}),background:R=>({u_matrix:new o.b$(R),u_emissive_strength:new o.bZ(R),u_opacity:new o.bZ(R),u_color:new o.dl(R)}),backgroundPattern:R=>({u_matrix:new o.b$(R),u_emissive_strength:new o.bZ(R),u_opacity:new o.bZ(R),u_image:new o.bX(R),u_pattern_tl:new o.b_(R),u_pattern_br:new o.b_(R),u_texsize:new o.b_(R),u_pattern_size:new o.b_(R),u_pixel_coord_upper:new o.b_(R),u_pixel_coord_lower:new o.b_(R),u_pattern_units_to_pixels:new o.b_(R)}),terrainRaster:R=>({u_matrix:new o.b$(R),u_image0:new o.bX(R),u_image1:new o.bX(R),u_skirt_height:new o.bZ(R),u_ground_shadow_factor:new o.bY(R),u_emissive_texture_available:new o.bZ(R)}),skybox:R=>({u_matrix:new o.b$(R),u_sun_direction:new o.bY(R),u_cubemap:new o.bX(R),u_opacity:new o.bZ(R),u_temporal_offset:new o.bZ(R)}),skyboxGradient:R=>({u_matrix:new o.b$(R),u_color_ramp:new o.bX(R),u_center_direction:new o.bY(R),u_radius:new o.bZ(R),u_opacity:new o.bZ(R),u_temporal_offset:new o.bZ(R)}),skyboxCapture:R=>({u_matrix_3f:new o.dm(R),u_sun_direction:new o.bY(R),u_sun_intensity:new o.bZ(R),u_color_tint_r:new o.cO(R),u_color_tint_m:new o.cO(R),u_luminance:new o.bZ(R)}),globeRaster:R=>({u_proj_matrix:new o.b$(R),u_globe_matrix:new o.b$(R),u_normalize_matrix:new o.b$(R),u_merc_matrix:new o.b$(R),u_zoom_transition:new o.bZ(R),u_merc_center:new o.b_(R),u_image0:new o.bX(R),u_image1:new o.bX(R),u_grid_matrix:new o.dm(R),u_skirt_height:new o.bZ(R),u_far_z_cutoff:new o.bZ(R),u_frustum_tl:new o.bY(R),u_frustum_tr:new o.bY(R),u_frustum_br:new o.bY(R),u_frustum_bl:new o.bY(R),u_globe_pos:new o.bY(R),u_globe_radius:new o.bZ(R),u_viewport:new o.b_(R),u_emissive_texture_available:new o.bZ(R)}),globeAtmosphere:R=>({u_frustum_tl:new o.bY(R),u_frustum_tr:new o.bY(R),u_frustum_br:new o.bY(R),u_frustum_bl:new o.bY(R),u_horizon:new o.bZ(R),u_transition:new o.bZ(R),u_fadeout_range:new o.bZ(R),u_atmosphere_fog_color:new o.cO(R),u_high_color:new o.cO(R),u_space_color:new o.cO(R),u_temporal_offset:new o.bZ(R),u_horizon_angle:new o.bZ(R)}),model:R=>({u_matrix:new o.b$(R),u_lighting_matrix:new o.b$(R),u_normal_matrix:new o.b$(R),u_node_matrix:new o.b$(R),u_lightpos:new o.bY(R),u_lightintensity:new o.bZ(R),u_lightcolor:new o.bY(R),u_camera_pos:new o.bY(R),u_opacity:new o.bZ(R),u_baseColorFactor:new o.cO(R),u_emissiveFactor:new o.cO(R),u_metallicFactor:new o.bZ(R),u_roughnessFactor:new o.bZ(R),u_baseTextureIsAlpha:new o.bX(R),u_alphaMask:new o.bX(R),u_alphaCutoff:new o.bZ(R),u_baseColorTexture:new o.bX(R),u_metallicRoughnessTexture:new o.bX(R),u_normalTexture:new o.bX(R),u_occlusionTexture:new o.bX(R),u_emissionTexture:new o.bX(R),u_lutTexture:new o.bX(R),u_color_mix:new o.cO(R),u_aoIntensity:new o.bZ(R),u_emissive_strength:new o.bZ(R),u_occlusionTextureTransform:new o.cO(R)}),modelDepth:R=>({u_matrix:new o.b$(R),u_instance:new o.b$(R),u_node_matrix:new o.b$(R)}),groundShadow:R=>({u_matrix:new o.b$(R),u_ground_shadow_factor:new o.bY(R)}),stars:R=>({u_matrix:new o.b$(R),u_up:new o.bY(R),u_right:new o.bY(R),u_intensity_multiplier:new o.bZ(R)}),snowParticle:R=>({u_modelview:new o.b$(R),u_projection:new o.b$(R),u_time:new o.bZ(R),u_cam_pos:new o.bY(R),u_velocityConeAperture:new o.bZ(R),u_velocity:new o.bZ(R),u_horizontalOscillationRadius:new o.bZ(R),u_horizontalOscillationRate:new o.bZ(R),u_boxSize:new o.bZ(R),u_billboardSize:new o.bZ(R),u_simpleShapeParameters:new o.b_(R),u_screenSize:new o.b_(R),u_thinningCenterPos:new o.b_(R),u_thinningShape:new o.bY(R),u_thinningAffectedRatio:new o.bZ(R),u_thinningParticleOffset:new o.bZ(R),u_particleColor:new o.cO(R),u_direction:new o.bY(R)}),rainParticle:R=>({u_modelview:new o.b$(R),u_projection:new o.b$(R),u_time:new o.bZ(R),u_cam_pos:new o.bY(R),u_texScreen:new o.bX(R),u_velocityConeAperture:new o.bZ(R),u_velocity:new o.bZ(R),u_boxSize:new o.bZ(R),u_rainDropletSize:new o.b_(R),u_distortionStrength:new o.bZ(R),u_rainDirection:new o.bY(R),u_color:new o.cO(R),u_screenSize:new o.b_(R),u_thinningCenterPos:new o.b_(R),u_thinningShape:new o.bY(R),u_thinningAffectedRatio:new o.bZ(R),u_thinningParticleOffset:new o.bZ(R),u_shapeDirectionalPower:new o.bZ(R),u_shapeNormalPower:new o.bZ(R),u_mode:new o.bZ(R)}),vignette:R=>({u_vignetteShape:new o.bY(R),u_vignetteColor:new o.cO(R)}),occlusion:R=>({u_matrix:new o.b$(R),u_anchorPos:new o.bY(R),u_screenSizePx:new o.b_(R),u_occluderSizePx:new o.b_(R),u_color:new o.cO(R)})};class Id{constructor(w,E,F,H){this.id=Id.uniqueIdxCounter,Id.uniqueIdxCounter++,this.context=w;const Z=w.gl;this.buffer=Z.createBuffer(),this.dynamicDraw=!!F,this.context.unbindVAO(),w.bindElementBuffer.set(this.buffer),Z.bufferData(Z.ELEMENT_ARRAY_BUFFER,E.arrayBuffer,this.dynamicDraw?Z.DYNAMIC_DRAW:Z.STATIC_DRAW),this.dynamicDraw||H||E.destroy()}bind(){this.context.bindElementBuffer.set(this.buffer)}updateData(w){this.id=Id.uniqueIdxCounter,Id.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)}}Id.uniqueIdxCounter=0;const ef={Int8:"BYTE",Uint8:"UNSIGNED_BYTE",Int16:"SHORT",Uint16:"UNSIGNED_SHORT",Int32:"INT",Uint32:"UNSIGNED_INT",Float32:"FLOAT"};class tf{constructor(w,E,F,H,Z,X){this.length=E.length,this.attributes=F,this.itemSize=E.bytesPerElement,this.dynamicDraw=H,this.instanceCount=X,this.context=w;const oe=w.gl;this.buffer=oe.createBuffer(),w.bindVertexBuffer.set(this.buffer),oe.bufferData(oe.ARRAY_BUFFER,E.arrayBuffer,this.dynamicDraw?oe.DYNAMIC_DRAW:oe.STATIC_DRAW),this.dynamicDraw||Z||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 H=E.getAttributeLocation(w,F.name);H!==-1&&w.enableVertexAttribArray(H)}}setVertexAttribPointers(w,E,F){for(const H of this.attributes){const Z=E.getAttributeLocation(w,H.name);if(Z!==-1){const X=H.offset+this.itemSize*(F||0);H.type==="Float32"?w.vertexAttribPointer(Z,H.components,w.FLOAT,!1,this.itemSize,X):w.vertexAttribIPointer(Z,H.components,w[ef[H.type]],this.itemSize,X)}}}setVertexAttribDivisor(w,E,F){for(let H=0;H0&&w.vertexAttribDivisor(Z,F)}}destroy(){this.buffer&&(this.context.gl.deleteBuffer(this.buffer),delete this.buffer)}}class Rm{constructor(w,E,F,H,Z){this.context=w,this.width=E,this.height=F;const X=this.framebuffer=w.gl.createFramebuffer();H>0&&(this.colorAttachment0=new r_(w,X,0)),H>1&&(this.colorAttachment1=new r_(w,X,1)),Z&&(this.depthAttachmentType=Z,this.depthAttachment=Z==="renderbuffer"?new S2(w,X):new vk(w,X))}static createWithTexture(w,E,F,H,Z){const X=w.gl;if(w.activeTexture.set(X.TEXTURE1),w.viewport.set([0,0,F,H]),E&&E.width===F&&E.height===H)return X.bindTexture(X.TEXTURE_2D,E.colorAttachment0.get()),w.bindFramebuffer.set(E.framebuffer),E;E&&E.destroy();const oe=new o.T(w,{width:F,height:H,data:null},w.extRenderToTextureHalfFloat?w.gl.RGBA16F:w.gl.RGBA8);oe.bind(X.LINEAR,X.CLAMP_TO_EDGE);const xe=w.createFramebuffer(F,H,1,null);if(xe.colorAttachment0.set(oe.texture),Z){const Ne=w.createRenderbuffer(X.DEPTH24_STENCIL8,F,H);w.bindFramebuffer.set(xe.framebuffer),X.framebufferRenderbuffer(X.FRAMEBUFFER,X.DEPTH_STENCIL_ATTACHMENT,X.RENDERBUFFER,Ne),xe._stencilRbo=Ne}return xe}createColorAttachment(w,E){E===0?this.colorAttachment0=new r_(w,this.framebuffer,0):E===1&&(this.colorAttachment1=new r_(w,this.framebuffer,1))}removeColorAttachment(w,E){const F=this.context.gl;let H;E===0?(H=this.colorAttachment0.get(),this.colorAttachment0=void 0):E===1&&(H=this.colorAttachment1.get(),this.colorAttachment1=void 0),H&&F.deleteTexture(H)}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 vh{constructor(w,E){this.gl=w,this.clearColor=new s_(this),this.clearDepth=new Z5(this),this.clearStencil=new F1(this),this.colorMask=new aM(this),this.depthMask=new qg(this),this.stencilMask=new Pw(this),this.stencilFunc=new n_(this),this.stencilOp=new pk(this),this.stencilTest=new z1(this),this.depthRange=new B1(this),this.depthTest=new zf(this),this.depthFunc=new eu(this),this.blend=new Vg(this),this.blendFunc=new N2(this),this.blendColor=new X5(this),this.blendEquation=new fx(this),this.cullFace=new Xp(this),this.cullFaceSide=new k2(this),this.frontFace=new fk(this),this.program=new Iw(this),this.activeTexture=new Dw(this),this.viewport=new Qp(this),this.bindFramebuffer=new fp(this),this.bindRenderbuffer=new Q5(this),this.bindTexture=new Py(this),this.bindVertexBuffer=new Rw(this),this.bindElementBuffer=new Ow(this),this.bindVertexArrayOES=new xk(this),this.pixelStoreUnpack=new gk(this),this.pixelStoreUnpackPremultiplyAlpha=new yk(this),this.pixelStoreUnpackFlipY=new Fw(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 Id(this,w,E,F)}createVertexBuffer(w,E,F,H,Z){return new tf(this,w,E,F,H,Z)}createRenderbuffer(w,E,F){const H=this.gl,Z=H.createRenderbuffer();return this.bindRenderbuffer.set(Z),H.renderbufferStorage(H.RENDERBUFFER,w,E,F),this.bindRenderbuffer.set(null),Z}createFramebuffer(w,E,F,H){return new Rm(this,w,E,F,H)}clear({color:w,depth:E,stencil:F,colorMask:H}){const Z=this.gl;let X=0;w&&(X|=Z.COLOR_BUFFER_BIT,this.clearColor.set(w.toNonPremultipliedRenderColor(null)),this.colorMask.set(H||[!0,!0,!0,!0])),E!==void 0&&(X|=Z.DEPTH_BUFFER_BIT,this.depthRange.set([0,1]),this.clearDepth.set(E),this.depthMask.set(!0)),F!==void 0&&(X|=Z.STENCIL_BUFFER_BIT,this.clearStencil.set(F),this.stencilMask.set(255)),Z.clear(X)}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,Ma.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 yc;function br(R,w,E,F,H,Z,X){const oe=R.context,xe=oe.gl,Ne=R.transform,Le=[o.aH(Ne.center.lng),o.aL(Ne.center.lat)],We=E.layout.get("symbol-placement"),He=E.layout.get("text-variable-anchor"),tt=E.layout.get("icon-rotation-alignment")==="map",dt=E.layout.get("text-rotation-alignment")==="map",it=We!=="point",jt=[];let wt=0,Ot=0;for(let Gt=0;Gt0){const wa=o.bb(),Yr=cr;o.cz(wa,Ws.placementInvProjMatrix,Ne.glCoordMatrix),o.cz(wa,wa,Ws.placementViewportMatrix),jt.push({circleArray:Bn,circleOffset:Ot,transform:Yr,invTransform:wa,projection:Ws.getProjection()}),wt+=Bn.length/4,Ot=wt}if(!dr)continue;R.terrain&&R.terrain.setupElevationDraw(fs,_r);const ra=vn?[es.canonical.x,es.canonical.y,1<=0&&(tt[Vt.associatedIconIndex]={x:As,y:gn,z:an,angle:mn})}else kt(ss,We)}if(Ne){He.clear();const Ot=R.icon.placedSymbolArray;for(let Vt=0;Vt{let vi=[0,0,0];if(Xo){const Hc=R.style.directionalLight,Ol=R.style.ambientLight;Hc&&Ol&&(vi=xh(R.style,Hc,Ol))}return vi},$i=Xo=>{if(R.context.disableSymbolUBO)return;Xo.push("USE_PAINT_PROPERTIES_UBO");const vi=Math.floor(R.context.maxUniformBlockSize/4),Hc=Math.floor(vi/4);Xo.push(`MAX_UBO_SIZE_VEC4 ${Hc}u`)},li=Xo=>{es.depthOcclusionForSymbolsAndCircles&&(E.hasOcclusionOpacityProperties||R.terrain)&&(Xo.push("DEPTH_D24"),Xo.push("DEPTH_OCCLUSION"))},Fo=Xo=>{E.lut&&!ss&&(E.lut.texture||(E.lut.texture=new o.dR(R.context,E.lut.image,[E.lut.image.height,E.lut.image.height,E.lut.image.height],Ns.gl.RGBA8)),Ns.activeTexture.set(Ns.gl.TEXTURE0+10),E.lut.texture&&E.lut.texture.bind(Ns.gl.LINEAR,Ns.gl.CLAMP_TO_EDGE),Xo.push("APPLY_LUT_ON_GPU"))},Rl=()=>{const Xo=fs&&E.layout.get("symbol-placement")!=="point",vi=[];li(vi),Fo(vi);const Hc=Xo||pi,Ol=Bn.elevationType==="road",Fu=R.shadowRenderer,ro=Ol&&As&&!!Fu&&Fu.enabled,Ql=Oa(ro),bh=Ol&&As&&!R.terrain?en:Gn,Uf=E.paint.get("icon-image-cross-fade");R.terrainRenderModeElevated()&&As&&vi.push("PITCH_WITH_MAP_TERRAIN"),ra&&(vi.push("PROJECTION_GLOBE_VIEW"),Hc&&vi.push("PROJECTED_POS_ON_VIEWPORT")),Uf>0&&Bn.hasAnySecondaryIcon&&vi.push("ICON_TRANSITION"),!Bn.icon.zOffsetVertexBuffer||Ol&&R.terrain||vi.push("Z_OFFSET"),wt===0&&Ot===0&&Vt===0&&Ct===1||vi.push("COLOR_ADJUSTMENT"),Bn.sdfIcons&&vi.push("RENDER_SDF"),ro&&vi.push("RENDER_SHADOWS","NORMAL_OFFSET"),Ol&&As&&!R.terrain&&Bn.icon.orientationVertexBuffer&&vi.push("ELEVATED_ROADS"),$i(vi);const zh=Ns.disableSymbolUBO?Bn.icon.programConfigurations.get(E.id):null,gp=R.getOrCreateProgram("symbol",{config:zh,defines:vi}),Oy=dr.imageAtlasTexture?dr.imageAtlasTexture.size:[0,0],ul=Bn.iconSizeData,Iv=o.bj(ul,es.zoom),Dv=As||!es.isOrthographic,cc=ld(Yr,dr.tileID.canonical,As,fs,es,Bn.getProjection(),na),_c=cp(Yr,dr.tileID.canonical,As,fs,es,Bn.getProjection(),na),Al=Bn.icon.uboBinder&&Bn.icon.uboBinder.cachedHeader&&256&Bn.icon.uboBinder.cachedHeader.dataDrivenMask?[0,0]:oe,ju=R.translatePosMatrix(_c,dr,Al,Ne,!0),yx=R.translatePosMatrix(Yr,dr,Al,Ne),Rd=Hc?No:cc,Fy=fs&&!As&&!Xo;let Ck=_r;!vn&&!es.mercatorFromTransition||fs||(Ck=Fc(es));const l4=ra?Ck:_r,c4=E.getColorAdjustmentMatrix(wt,Ot,Vt,Ct),BC=Iu(ul.kind,Iv,Fy,As,R,yx,Rd,ju,ks,!1,Oy,[0,0],0,cr,wa,Ms,oi,l4,Bn.getProjection(),Ql,Bi,c4,Uf,null),L2=dr.imageAtlasTexture?dr.imageAtlasTexture:null,Ww=E.layout.get("icon-size").constantOr(0)!==1||Bn.iconsNeedLinear,$C=Bn.sdfIcons||R.options.rotating||R.options.zooming||Ww||Dv?Gt.LINEAR:Gt.NEAREST,K0=Bn.sdfIcons&&E.paint.get("icon-halo-width").constantOr(1)!==0,Ak=R.terrain&&As&&Xo?o.b7(o.bb(),cc):No;if(Xo&&Bn.icon){const Ek=o.bu.getAtTileOffsetFunc(cr,es.center.lat,es.worldSize,Bn.getProjection()),Tk=Oc(Yr,dr.tileID.canonical,As,fs,es,Bn.getProjection(),na),RF=E.layout.get("icon-size-scale-range"),UC=o.aC(R.scaleFactor,RF[0],RF[1]);Rh(Bn,Yr,R,!1,Tk,_c,As,it,Ek,cr,UC)}return{program:gp,buffers:Bn.icon,uniformValues:BC,atlasTexture:L2,atlasTextureIcon:null,atlasInterpolation:$C,atlasInterpolationIcon:null,isSDF:Bn.sdfIcons,hasHalo:K0,depthMode:bh,tile:dr,renderWithShadows:ro,labelPlaneMatrixInv:Ak}},td=()=>{const Xo=Ws&&E.layout.get("symbol-placement")!=="point",vi=[],Hc=Xo||mn||pi,Ol=Bn.elevationType==="road",Fu=R.shadowRenderer,ro=Ol&&gn&&!!Fu&&Fu.enabled,Ql=Oa(ro),bh=Ol&&gn&&!R.terrain?en:Gn;R.terrainRenderModeElevated()&&gn&&vi.push("PITCH_WITH_MAP_TERRAIN"),ra&&(vi.push("PROJECTION_GLOBE_VIEW"),Hc&&vi.push("PROJECTED_POS_ON_VIEWPORT")),!Bn.text.zOffsetVertexBuffer||Ol&&R.terrain||vi.push("Z_OFFSET"),Bn.iconsInText&&vi.push("RENDER_TEXT_AND_SYMBOL"),vi.push("RENDER_SDF"),ro&&vi.push("RENDER_SHADOWS","NORMAL_OFFSET"),Ol&&gn&&!R.terrain&&Bn.text.orientationVertexBuffer&&vi.push("ELEVATED_ROADS"),li(vi),$i(vi);const Uf=Ns.disableSymbolUBO?Bn.text.programConfigurations.get(E.id):null,zh=R.getOrCreateProgram("symbol",{config:Uf,defines:vi});let gp,Oy=[0,0],ul=null;const Iv=Bn.textSizeData;Bn.iconsInText&&(Oy=dr.imageAtlasTexture?dr.imageAtlasTexture.size:[0,0],ul=dr.imageAtlasTexture?dr.imageAtlasTexture:null,gp=gn||!es.isOrthographic||R.options.rotating||R.options.zooming||Iv.kind==="composite"||Iv.kind==="camera"?Gt.LINEAR:Gt.NEAREST);const Dv=dr.glyphAtlasTexture?dr.glyphAtlasTexture.size:[0,0],cc=E.layout.get("text-size-scale-range"),_c=o.aC(R.scaleFactor,cc[0],cc[1]),Al=o.bj(Iv,es.zoom,_c),ju=ld(Yr,dr.tileID.canonical,gn,Ws,es,Bn.getProjection(),na),yx=cp(Yr,dr.tileID.canonical,gn,Ws,es,Bn.getProjection(),na),Rd=Bn.text.uboBinder&&Bn.text.uboBinder.cachedHeader&&256&Bn.text.uboBinder.cachedHeader.dataDrivenMask?[0,0]:xe,Fy=R.translatePosMatrix(yx,dr,Rd,Le,!0),Ck=R.translatePosMatrix(Yr,dr,Rd,Le),l4=Hc?No:ju,c4=Ws&&!gn&&!Xo;let BC=_r;!vn&&!es.mercatorFromTransition||Ws||(BC=Fc(es));const L2=Iu(Iv.kind,Al,c4,gn,R,Ck,l4,Fy,ks,!0,Dv,Oy,0,cr,wa,Ms,oi,ra?BC:_r,Bn.getProjection(),Ql,Bi,null,null,_c),Ww=dr.glyphAtlasTexture?dr.glyphAtlasTexture:null,$C=Gt.LINEAR,K0=E.paint.get("text-halo-width").constantOr(1)!==0,Ak=R.terrain&&gn&&Xo?o.b7(o.bb(),ju):No;if(Xo&&Bn.text){const Ek=o.bu.getAtTileOffsetFunc(cr,es.center.lat,es.worldSize,Bn.getProjection()),Tk=Oc(Yr,dr.tileID.canonical,gn,Ws,es,Bn.getProjection(),na);Rh(Bn,Yr,R,!0,Tk,yx,gn,jt,Ek,cr,_c)}return{program:zh,buffers:Bn.text,uniformValues:L2,atlasTexture:Ww,atlasTextureIcon:ul,atlasInterpolation:$C,atlasInterpolationIcon:gp,isSDF:!0,hasHalo:K0,depthMode:bh,tile:dr,renderWithShadows:ro,labelPlaneMatrixInv:Ak}},nc=Bn.icon.segments.get().length,Zo=Bn.text.segments.get().length,Pi=nc&&!X.onlyText?Rl():null,Ii=Zo&&!X.onlyIcons?td():null,rc=E.paint.get("icon-opacity").constantOr(1),hd=E.paint.get("text-opacity").constantOr(1);if(an&&Bn.canOverlap){Dn=!0;const Xo=rc&&!X.onlyText?Bn.icon.segments.get():[],vi=hd&&!X.onlyIcons?Bn.text.segments.get():[];for(const Hc of Xo)kn.push({segments:new o.dy([Hc]),sortKey:Hc.sortKey,state:Pi});for(const Hc of vi)kn.push({segments:new o.dy([Hc]),sortKey:Hc.sortKey,state:Ii})}else X.onlyText||kn.push({segments:rc?Bn.icon.segments:new o.dy([]),sortKey:0,state:Pi}),X.onlyIcons||kn.push({segments:hd?Bn.text.segments:new o.dy([]),sortKey:0,state:Ii})}Dn&&kn.sort((cr,dr)=>cr.sortKey-dr.sortKey);for(const cr of kn){const dr=cr.state;if(dr)if(R.terrain?R.terrain.setupElevationDraw(dr.tile,dr.program,{useDepthForOcclusion:es.depthOcclusionForSymbolsAndCircles,labelPlaneMatrixInv:dr.labelPlaneMatrixInv}):R.setupDepthForOcclusion(es.depthOcclusionForSymbolsAndCircles,dr.program),Ns.activeTexture.set(Gt.TEXTURE0),dr.atlasTexture&&dr.atlasTexture.bind(dr.atlasInterpolation,Gt.CLAMP_TO_EDGE,!0),dr.atlasTextureIcon&&(Ns.activeTexture.set(Gt.TEXTURE1),dr.atlasTextureIcon&&dr.atlasTextureIcon.bind(dr.atlasInterpolationIcon,Gt.CLAMP_TO_EDGE,!0)),dr.renderWithShadows&&R.shadowRenderer.setupShadows(dr.tile.tileID.toUnwrapped(),dr.program,"vector-tile"),R.uploadCommonLightUniforms(R.context,dr.program),dr.hasHalo){const Bn=dr.uniformValues;Bn.u_is_halo=1,U0(dr.buffers,cr.segments,E,R,dr.program,dr.depthMode,H,Z,Bn,2),Bn.u_is_halo=0}else{if(dr.isSDF){const Bn=dr.uniformValues;dr.hasHalo&&(Bn.u_is_halo=1,U0(dr.buffers,cr.segments,E,R,dr.program,dr.depthMode,H,Z,Bn,1)),Bn.u_is_halo=0}U0(dr.buffers,cr.segments,E,R,dr.program,dr.depthMode,H,Z,dr.uniformValues,1)}}}function U0(R,w,E,F,H,Z,X,oe,xe,Ne){const Le=F.context,We=Le.gl,He=[R.dynamicLayoutVertexBuffer,R.opacityVertexBuffer,R.iconTransitioningVertexBuffer,R.globeExtVertexBuffer,R.zOffsetVertexBuffer,R.orientationVertexBuffer];R.featureIdBuffer&&He.push(R.featureIdBuffer);const tt=R.uboBinder?null:R.programConfigurations.get(E.id);if(R.uboBinder){R.uboBinder.layer=E;const jt=F.transform.zoom,wt=F.style.getBrightness?F.style.getBrightness():null,Ot=R.uboBinder.getConstantUniformValues(jt,wt);xe.u_spp_fill_np_color=Ot.fill_np_color,xe.u_spp_halo_np_color=Ot.halo_np_color,xe.u_spp_opacity=Ot.opacity,xe.u_spp_halo_width=Ot.halo_width,xe.u_spp_halo_blur=Ot.halo_blur,xe.u_spp_emissive_strength=Ot.emissive_strength,xe.u_spp_occlusion_opacity=Ot.occlusion_opacity,xe.u_spp_z_offset=Ot.z_offset;const Vt=E.paint.get(R.uboBinder.isText?"text-translate-anchor":"icon-translate-anchor"),Ct=R.uboBinder.cachedHeader&&256&R.uboBinder.cachedHeader.dataDrivenMask&&Vt==="map"?F.transform.angle:0;xe.u_spp_translate_rotation=[Math.cos(Ct),Math.sin(Ct)]}const{batchIndices:dt,batchSegments:it}=R.getBatchGrouping(w);for(const jt of dt){const wt=it.get(jt);R.uboBinder&&R.uboBinder.bind(Le,H.program,jt),H.draw(F,We.TRIANGLES,Z,X,oe,pa.disabled,xe,E.id,R.layoutVertexBuffer,R.indexBuffer,wt,E.paint,F.transform.zoom,tt,He,Ne)}}function su(R,w,E,F,H,Z){const X=E.paint.get("line-width"),oe=E.paint.get("line-emissive-strength").isConstant(),xe=E.paint.get("line-emissive-strength").constantOr(0),Ne=E.paint.get("line-occlusion-opacity"),Le=E.layout.get("line-elevation-reference"),We=E.layout.get("line-width-unit")==="meters",He=Le==="sea",tt=!(!R.terrain||!R.terrain.enabled),dt=R.context,it=dt.gl;if(E.hasElevatedBuckets&&R.transform.projection.name==="globe")return;const jt=E.layout.get("line-cross-slope"),wt=jt!==void 0,Ot=jt<1,Vt=H||R.colorModeForDrapableLayerRenderPass(oe?xe:null),Ct=R.terrain&&R.terrain.renderingToTexture||Z,ks=Ct?1:o.o.devicePixelRatio,ss=E.paint.get("line-dasharray"),Ns=ss.constantOr(1),Gt=E.layout.get("line-cap"),es=ss.constantOr(null),fs=Gt.constantOr(null),Ws=E.paint.get("line-pattern"),As=Ws.constantOr(1),gn=E.paint.get("line-pattern-cross-fade"),an=Ws.constantOr(null),Dn=E.paint.get("line-opacity").constantOr(1);let Gn=!As&&Dn!==1||R.depthOcclusion&&Ne>0&&Ne<1;const en=E.paint.get("line-gradient"),Ms=As?"linePattern":"line",mn=o.dU(E);let vn;if(Ct&&R.terrain&&R.terrain.clipOrMaskOverlapStencilType()&&(Gn=!1),Ne!==0&&R.depthOcclusion){const Bn=E.paint._values["line-opacity"];Bn&&Bn.value&&Bn.value.kind==="constant"?vn=Bn.value:o.w(`Occlusion opacity for layer ${E.id} is supported only when line-opacity isn't data-driven.`)}X.value.kind!=="constant"&&X.value.isLineProgressConstant===!1&&mn.push("VARIABLE_LINE_WIDTH"),Ct&&(R.emissiveMode!=="dual-source-blending"||oe?R.emissiveMode==="mrt-fallback"&&mn.push("USE_MRT1"):mn.push("DUAL_SOURCE_BLENDING"));const kn={},_r=(Bn,ra,wa,Yr,na,Xa)=>{for(const pi of Bn){const oi=w.getTile(pi);if(As&&!oi.patternsLoaded())continue;const Bi=oi.getBucket(E);if(!Bi||Bi.elevationType!=="none"&&!na||Bi.elevationType==="none"&&na)continue;R.prepareDrawTile();const Oa=[...ra],$i=R.shadowRenderer,li=Bi.elevationType==="road"&&!!$i&&$i.enabled;let Fo=[0,0,0];if(li){const ro=R.style.directionalLight,Ql=R.style.ambientLight;ro&&Ql&&(Fo=xh(R.style,ro,Ql)),Oa.push("RENDER_SHADOWS","NORMAL_OFFSET")}const Rl=Bi.programConfigurations.get(E.id);let td=!1;if(an&&oi.imageAtlas){const ro=o.dV.from(an),Ql=ro.getPrimary().scaleSelf(ks).toString(),bh=oi.imageAtlas.patternPositions.get(Ql),Uf=ro.getSecondary(),zh=Uf?oi.imageAtlas.patternPositions.get(Uf.scaleSelf(ks).toString()):null;td=!!bh&&!!zh,bh&&Rl.setConstantPatternPositions(bh,zh)}gn>0&&(td||Rl.getPatternTransitionVertexBuffer("line-pattern"))&&Oa.push("LINE_PATTERN_TRANSITION"),Bi.elevationGroundScaleVertexBuffer&&Oa.push("ELEVATION_GROUND_SCALE");const nc=R.isTileAffectedByFog(pi),Zo=R.getOrCreateProgram(Ms,{config:Rl,defines:Oa,overrideFog:nc});if(!As&&es&&fs&&oi.lineAtlas){const ro=oi.lineAtlas.getDash(es,fs);ro&&Rl.setConstantPatternPositions(ro)}li&&$i.setupShadows(oi.tileID.toUnwrapped(),Zo,"vector-tile");let[Pi,Ii]=E.paint.get("line-trim-offset");(fs==="round"||fs==="square")&&Pi!==Ii&&(Pi===0&&(Pi-=1),Ii===1&&(Ii+=1));const rc=Ct?pi.projMatrix:null,hd=We?1/Bi.tileToMeter/o.aA(oi,1,R.transform.zoom):1,Xo=We?1/Bi.tileToMeter/o.aA(oi,1,Math.floor(R.transform.zoom)):1,vi=Ns?E.paint._values["line-floorwidth"]:null;let Hc;if(vi&&vi.value.kind==="constant"){const ro=Bi.zoom;ro in kn||(kn[ro]=Math.max(.01,E.widthExpression().evaluate({zoom:ro}))),Hc=vi.value.value;const Ql=Math.floor(R.transform.zoom);vi.value.value=kn[ro]*Math.pow(2,Ql-oi.tileID.overscaledZ)}const Ol=As?o.dW(R,oi,E,rc,ks,hd,Xo,[Pi,Ii],Fo,gn):o.dX(R,oi,E,rc,Bi.lineClipsArray.length,ks,hd,Xo,[Pi,Ii],Fo);if(en){const ro=Bi.gradients[E.id];let Ql=ro.texture;if(E.gradientVersion!==ro.version){let bh=256;if(E.stepInterpolant){const Uf=w.getSource().maxzoom,zh=pi.canonical.z===Uf?Math.ceil(1<{vn!=null&&(vn.value=Dn*Ne),Zo.draw(R,it.TRIANGLES,wa,ro,Vt,pa.disabled,Ol,E.id,Bi.layoutVertexBuffer,Bi.indexBuffer,Bi.segments,E.paint,R.transform.zoom,Rl,[Bi.layoutVertexBuffer2,Bi.patternVertexBuffer,Bi.zOffsetVertexBuffer,Bi.elevationGroundScaleVertexBuffer]),vn!=null&&(vn.value=Dn)};if(Gn&&!na){const ro=R.stencilModeForClipping(pi).ref;ro===0&&Ct&&dt.clear({stencil:0});const Ql={func:it.EQUAL,mask:255};Ol.u_alpha_discard_threshold=.8,Fu(new La(Ql,ro,255,it.KEEP,it.KEEP,it.INVERT)),Ol.u_alpha_discard_threshold=0,Fu(new La(Ql,ro,255,it.KEEP,it.KEEP,it.KEEP))}else Ol.u_alpha_discard_threshold=Gn&&na&&Xa?.8:0,Fu(na?Yr:R.stencilModeForClipping(pi));Hc!==void 0&&(vi.value.value=Hc)}};let cr=R.depthModeForSublayer(0,qr.ReadOnly);const dr=new qr(R.depthOcclusion?it.GREATER:it.LEQUAL,qr.ReadOnly,R.depthRangeFor3D);if(E.hasNonElevatedBuckets){const Bn=!Ct&&R.terrain;Ne!==0&&Bn?o.w(`Occlusion opacity for layer ${E.id} is supported on terrain only if the layer has line-z-offset enabled.`):Bn?o.w(`Cannot render non-elevated lines in immediate mode when terrain is enabled. Layer: ${E.id}.`):_r(F,mn,cr,La.disabled,!1,!0)}if(E.hasElevatedBuckets){Le==="hd-road-markup"?tt||(cr=dr,mn.push("ELEVATED_ROADS")):(mn.push("ELEVATED"),cr=dr,wt&&mn.push(Ot?"CROSS_SLOPE_HORIZONTAL":"CROSS_SLOPE_VERTICAL"),He&&mn.push("ELEVATION_REFERENCE_SEA"));const Bn=Gn?R.stencilModeFor3D():La.disabled;R.forceTerrainMode=!0,_r(F,mn,cr,Bn,!0,!0),Gn&&_r(F,mn,cr,Bn,!0,!1),R.forceTerrainMode=!1}Gn&&(R.resetStencilClippingMasks(),Ct&&dt.clear({stencil:0})),Ne===0||R.depthOcclusion||Ct||R.layersWithOcclusionOpacity.push(R.currentLayer)}const xp={additive:{clearColor:new o.aq(0,0,0,0),colorMode:Ma.additive,compositeUniformValue:1},multiply:{clearColor:new o.aq(1,1,1,1),colorMode:Ma.multiply,compositeUniformValue:0}};function Av(R,w){const E=1<=fh?1:tt.pitch/fh))),2*dt}(R.transform),Ne=R.transform.getFreeCameraOptions().position,Le="elevatedStructuresDepthReconstruct",We=R.getOrCreateProgram(Le,{defines:["DEPTH_RECONSTRUCTION"]}),He=R.getOrCreateProgram(Le);for(const tt of F){const dt=w.getTile(tt),it=dt.getBucket(E);if(!it)continue;const jt=it.elevatedStructures;if(!jt)continue;const wt=it.elevationBufferData.heightRange,Ot=Av(tt.toUnwrapped(),Ne),Vt=R.translatePosMatrix(tt.projMatrix,dt,E.paint.get("fill-translate"),E.paint.get("fill-translate-anchor"));let Ct,ks,ss,Ns;if(H==="initialize"){if(!wt||wt.min>=1||jt.depthSegments.segments[0].primitiveLength===0)continue;Ct=Li(Vt,Ot,xe,1,0),ks=X,ss=jt.depthSegments,Ns=We}else if(H==="reset"){if(!wt||wt.min>=0||jt.maskSegments.segments[0].primitiveLength===0)continue;Ct=Li(Vt,Ot,0,0,1),ks=oe,ss=jt.maskSegments,Ns=We}else if(H==="geometry"){if(jt.depthSegments.segments[0].primitiveLength===0)continue;Ct=Li(Vt,Ot,xe,1,0),ks=X,ss=jt.depthSegments,Ns=He}Ns.draw(R,Z.TRIANGLES,ks,La.disabled,Ma.disabled,pa.disabled,Ct,E.id,jt.vertexBuffer,jt.indexBuffer,ss,E.paint,R.transform.zoom)}}function Ev(R,w,E,F){const{painter:H,sourceCache:Z,layer:X,coords:oe,colorMode:xe,elevationType:Ne,terrainEnabled:Le,pass:We}=R,He=H.context.gl,tt=X.paint.get("fill-pattern"),dt=X.paint.get("fill-pattern-cross-fade"),it=tt.constantOr(null);let jt=Ne;Ne!=="road"||w&&!Le||(jt="none");const wt=jt==="road",Ot=R.painter.shadowRenderer,Vt=wt&&!!Ot&&Ot.enabled,Ct=new qr(H.context.gl.LEQUAL,qr.ReadOnly,H.depthRangeFor3D);let ks=[0,0,0];if(Vt){const es=H.style.directionalLight,fs=H.style.ambientLight;es&&fs&&(ks=xh(H.style,es,fs))}const ss=tt&&tt.constantOr(1),Ns=H.terrain&&H.terrain.renderingToTexture,Gt=(es,fs)=>{let Ws,As,gn,an,Dn;fs?(Ws=ss&&!X.getPaintProperty("fill-outline-color")?"fillOutlinePattern":"fillOutline",gn=He.LINES):(Ws=ss?"fillPattern":"fill",gn=He.TRIANGLES);for(const Gn of oe){const en=Z.getTile(Gn);if(ss&&!en.patternsLoaded())continue;const Ms=en.getBucket(X);if(!Ms)continue;const mn=w?Ms.elevationBufferData:Ms.bufferData;if(mn.isEmpty())continue;H.prepareDrawTile();const vn=mn.programConfigurations.get(X.id),kn=H.isTileAffectedByFog(Gn),_r=[],cr=[];wt&&(_r.push("ELEVATED_ROADS"),cr.push(mn.elevatedLayoutVertexBuffer)),Vt&&_r.push("RENDER_SHADOWS","NORMAL_OFFSET"),Ns&&E&&_r.push("USE_MRT1"),ss&&(H.context.activeTexture.set(He.TEXTURE0),en.imageAtlasTexture&&en.imageAtlasTexture.bind(He.LINEAR,He.CLAMP_TO_EDGE),vn.updatePaintBuffers());let dr=!1;if(it&&en.imageAtlas){const na=en.imageAtlas,Xa=o.dV.from(it),pi=Xa.getPrimary().scaleSelf(o.o.devicePixelRatio).toString(),oi=Xa.getSecondary(),Bi=na.patternPositions.get(pi),Oa=oi?na.patternPositions.get(oi.scaleSelf(o.o.devicePixelRatio).toString()):null;dr=!!Bi&&!!Oa,Bi&&vn.setConstantPatternPositions(Bi,Oa)}dt>0&&(dr||vn.getPatternTransitionVertexBuffer("fill-pattern"))&&_r.push("FILL_PATTERN_TRANSITION");const Bn=H.getOrCreateProgram(Ws,{config:vn,overrideFog:kn,defines:_r}),ra=H.translatePosMatrix(Gn.projMatrix,en,X.paint.get("fill-translate"),X.paint.get("fill-translate-anchor"));Vt&&Ot.setupShadows(en.tileID.toUnwrapped(),Bn,"vector-tile");const wa=X.paint.get("fill-emissive-strength");if(fs){an=mn.lineIndexBuffer,Dn=mn.lineSegments;const na=H.terrain&&H.terrain.renderingToTexture?H.terrain.drapeBufferSize:[He.drawingBufferWidth,He.drawingBufferHeight];As=Ws==="fillOutlinePattern"&&ss?Fi(ra,wa,H,en,na,ks,dt):fa(ra,wa,na,ks)}else an=mn.indexBuffer,Dn=mn.triangleSegments,As=ss?ba(ra,wa,H,en,ks,dt):$r(ra,wa,ks);H.uploadCommonUniforms(H.context,Bn,Gn.toUnwrapped());let Yr=es;(Ne==="road"&&!Le||Ne==="offset")&&(Yr=Ct),Bn.draw(H,gn,Yr,F||H.stencilModeForClipping(Gn),xe,pa.disabled,As,X.id,mn.layoutVertexBuffer,an,Dn,X.paint,H.transform.zoom,vn,cr)}};H.renderPass===We&&Gt(H.depthModeForSublayer(1,H.renderPass==="opaque"?qr.ReadWrite:qr.ReadOnly),!1),jt==="none"&&H.renderPass==="translucent"&&X.paint.get("fill-antialias")&&Gt(H.depthModeForSublayer(X.getPaintProperty("fill-outline-color")?2:0,qr.ReadOnly),!0)}function Om(R,w,E,F,H,Z,X,oe){E.resetLayerRenderingStats(R);const xe=R.context,Ne=xe.gl,Le=R.transform,We=E.paint.get("fill-extrusion-pattern"),He=E.paint.get("fill-extrusion-pattern-cross-fade"),tt=We.constantOr(null),dt=We.constantOr(1),it=E.paint.get("fill-extrusion-opacity"),jt=R.style.enable3dLights(),wt=E.paint.get(jt&&!dt?"fill-extrusion-ambient-occlusion-wall-radius":"fill-extrusion-ambient-occlusion-radius"),Ot=[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"),ks=Ct?0:Vt,ss=Le.projection.name==="globe"?o.e1():0,Ns=Le.projection.name==="globe",Gt=Ns?o.al(Le.zoom):0,es=[o.aH(Le.center.lng),o.aL(Le.center.lat)],fs=E.paint.get("fill-extrusion-flood-light-color-use-theme").constantOr("default")==="none",Ws=E.paint.get("fill-extrusion-flood-light-color").toNonPremultipliedRenderColor(fs?null:E.lut).toArray01().slice(0,3),As=E.paint.get("fill-extrusion-flood-light-intensity"),gn=E.paint.get("fill-extrusion-vertical-scale"),an=E.paint.get("fill-extrusion-line-width").constantOr(1)!==0,Dn=E.paint.get("fill-extrusion-height-alignment"),Gn=E.paint.get("fill-extrusion-base-alignment"),en=Qc(R,E.paint.get("fill-extrusion-cutoff-fade-range")),Ms=E.paint.get("fill-extrusion-front-cutoff"),mn=Uw(Le.pitch,Ms,!!R.terrain),vn=mn[2]<1;vn&&(R.maxFrontCutoffRawStart=Math.max(R.maxFrontCutoffRawStart,Ms[0]));const kn=[];let _r;Ns&&kn.push("PROJECTION_GLOBE_VIEW"),Ot[0]>0&&kn.push("FAUX_AO"),Ct&&kn.push("ZERO_ROOF_RADIUS"),oe&&kn.push("HAS_CENTROID"),As>0&&kn.push("FLOOD_LIGHT"),en.shouldRenderCutoff&&kn.push("RENDER_CUTOFF"),vn&&kn.push("RENDER_FRONT_CUTOFF"),an&&kn.push("RENDER_WALL_MODE");const cr=R.renderPass==="shadow",dr=R.shadowRenderer,Bn=cr&&!!dr,ra=cr?pa.disabled:pa.backCCW;R.shadowRenderer&&(R.shadowRenderer.useNormalOffset=!0);let wa=[0,0,0];if(dr){const Xa=R.style.directionalLight,pi=R.style.ambientLight;Xa&&pi&&(wa=xh(R.style,Xa,pi)),cr||(kn.push("RENDER_SHADOWS"),dr.useNormalOffset&&kn.push("NORMAL_OFFSET")),_r=kn.concat(["SHADOWS_SINGLE_CASCADE"])}const Yr=Bn?"fillExtrusionDepth":dt?"fillExtrusionPattern":"fillExtrusion",na=E.getLayerRenderingStats();for(const Xa of F){const pi=w.getTile(Xa),oi=pi.getBucket(E);if(!oi||oi.projection.name!==Le.projection.name)continue;let Bi=!1;dr&&(Bi=dr.getMaxCascadeForTile(Xa.toUnwrapped())===0);const Oa=R.isTileAffectedByFog(Xa),$i=oi.programConfigurations.get(E.id);let li=!1;if(tt&&pi.imageAtlas){const Ii=pi.imageAtlas,rc=o.dV.from(tt),hd=rc.getPrimary().scaleSelf(o.o.devicePixelRatio).toString(),Xo=rc.getSecondary(),vi=Ii.patternPositions.get(hd),Hc=Xo?Ii.patternPositions.get(Xo.scaleSelf(o.o.devicePixelRatio).toString()):null;li=!!vi&&!!Hc,vi&&$i.setConstantPatternPositions(vi,Hc)}He>0&&(li||$i.getPatternTransitionVertexBuffer("fill-extrusion-pattern"))&&kn.push("FILL_EXTRUSION_PATTERN_TRANSITION");const Fo=R.getOrCreateProgram(Yr,{config:$i,defines:Bi?_r:kn,overrideFog:Oa});if(R.terrain&&R.terrain.setupElevationDraw(pi,Fo,{useMeterToDem:!0}),!oi.centroidVertexBuffer){const Ii=Fo.getAttributeLocation(Ne,"a_centroid_pos");Ii!==-1&&Ne.vertexAttribI4ui(Ii,0,0,0,0)}!cr&&dr&&dr.setupShadows(pi.tileID.toUnwrapped(),Fo,"vector-tile"),dt&&(R.context.activeTexture.set(Ne.TEXTURE0),pi.imageAtlasTexture&&pi.imageAtlasTexture.bind(Ne.LINEAR,Ne.CLAMP_TO_EDGE),$i.updatePaintBuffers());const Rl=E.paint.get("fill-extrusion-vertical-gradient"),td=1/oi.tileToMeter;let nc;if(cr&&dr){if(xx(pi.tileID,oi.maxHeight,R))continue;const Ii=dr.calculateShadowPassMatrixFromTile(pi.tileID.toUnwrapped());nc=xr(Ii,ks,td,gn,Dn,Gn)}else{const Ii=R.translatePosMatrix(Xa.expandedProjMatrix,pi,E.paint.get("fill-extrusion-translate"),E.paint.get("fill-extrusion-translate-anchor")),rc=Le.projection.createInversionMatrix(Le,Xa.canonical);nc=dt?Fn(Ii,R,Rl,it,Ot,ks,td,Xa,pi,ss,Dn,Gn,Gt,es,rc,Ws,gn,He):Mr(Ii,R,Rl,it,Ot,ks,td,Xa,ss,Dn,Gn,Gt,es,rc,Ws,gn,As,wa,mn)}R.uploadCommonUniforms(xe,Fo,Xa.toUnwrapped(),null,en);let Zo=oi.segments;if(Le.projection.name==="mercator"&&!cr&&(Zo=oi.getVisibleSegments(pi.tileID,R.terrain,R.transform.getFrustum(0)),!Zo.get().length))continue;if(na)if(cr)for(const Ii of Zo.get())na.numRenderedVerticesInShadowPass+=Ii.primitiveLength;else for(const Ii of Zo.get())na.numRenderedVerticesInTransparentPass+=Ii.primitiveLength;const Pi=[];(R.terrain||oe)&&Pi.push(oi.centroidVertexBuffer),Ns&&Pi.push(oi.layoutVertexExtBuffer),an&&Pi.push(oi.wallVertexBuffer),Fo.draw(R,xe.gl.TRIANGLES,H,Z,X,ra,nc,E.id,oi.layoutVertexBuffer,oi.indexBuffer,Zo,E.paint,R.transform.zoom,$i,Pi)}R.shadowRenderer&&(R.shadowRenderer.useNormalOffset=!1)}class sf{constructor(){this.translate=[0,0],this.translateAnchor="map",this.edgeRadius=0,this.cutoffFadeRange=0}}function Uw(R,w,E){if(!(w[2]<1)||E)return[0,0,1];const F=180*R/Math.PI;if(F<15)return[-.5,w[1],w[2]];const H=Math.min(1,Math.max(0,(F-15)/5)),Z=H*H*(3-2*H);return[-.5*(1-Z)+w[0]*Z,w[1],w[2]]}function Hg(R,w,E,F,H,Z,X,oe,xe,Ne,Le,We,He,tt,dt,it,jt,wt,Ot,Vt,Ct){const ks=w.context,ss=ks.gl,Ns=w.transform,Gt=w.transform.zoom,es=[],fs=R.translate,Ws=R.translateAnchor,As=R.edgeRadius,gn=Qc(w,R.cutoffFadeRange);Le==="clear"?(es.push("CLEAR_SUBPASS"),Vt&&(es.push("CLEAR_FROM_TEXTURE"),ks.activeTexture.set(ss.TEXTURE0),Vt.bind(ss.LINEAR,ss.CLAMP_TO_EDGE))):Le==="sdf"?es.push("SDF_SUBPASS"):Le==="emissive"&&(es.push("USE_MRT1"),ks.activeTexture.set(ss.TEXTURE0),Vt.bind(ss.LINEAR,ss.CLAMP_TO_EDGE)),wt&&es.push("HAS_CENTROID"),gn.shouldRenderCutoff&&es.push("RENDER_CUTOFF");const an=(Dn,Gn,en,Ms,mn)=>{let vn=es;Gn.groundRadiusBuffer!=null&&(vn=es.concat("HAS_ATTRIBUTE_a_flood_light_ground_radius"));const kn=Gn.programConfigurations.get(F.id),_r=w.isTileAffectedByFog(Dn),cr=w.getOrCreateProgram("fillExtrusionGroundEffect",{config:kn,defines:vn,overrideFog:_r}),dr=((ra,wa,Yr,na,Xa,pi,oi,Bi,Oa,$i,li)=>({u_matrix:wa,u_opacity:Yr,u_ao_pass:na?1:0,u_meter_to_tile:Xa,u_ao:pi,u_flood_light_intensity:oi,u_flood_light_color:Bi,u_attenuation:Oa,u_edge_radius:$i,u_fb:0,u_fb_size:li,u_dynamic_offset:1}))(0,Ms,We,Ne,mn,[He,tt*mn],dt,it,jt,Gt>=17?0:As*mn,Vt?Vt.size[0]:0),Bn=[];wt&&Bn.push(Gn.hiddenByLandmarkVertexBuffer),Gn.groundRadiusBuffer!=null&&Bn.push(Gn.groundRadiusBuffer),w.uploadCommonUniforms(ks,cr,Dn.toUnwrapped(),null,gn),cr.draw(w,ks.gl.TRIANGLES,Z,X,oe,xe,dr,F.id,Gn.vertexBuffer,Gn.indexBuffer,en,F.paint,Gt,kn,Bn)};for(const Dn of H){const Gn=E.getTile(Dn),en=Gn.getBucket(F);if(!en||en.projection.name!==Ns.projection.name||!en.groundEffect||en.groundEffect&&!en.groundEffect.hasData())continue;const Ms=en.groundEffect,mn=1/en.tileToMeter;{const vn=w.translatePosMatrix(Dn.projMatrix,Gn,fs,Ws),kn=Ms.getDefaultSegment();an(Dn,Ms,kn,vn,mn)}if(Ot)for(let vn=0;vn<4;vn++){const kn=o.d$[vn](Dn),_r=E.getTile(kn);if(!_r)continue;const cr=_r.getBucket(F);if(!cr||cr.projection.name!==Ns.projection.name||!cr.groundEffect||cr.groundEffect&&!cr.groundEffect.hasData())continue;const dr=cr.groundEffect;let Bn,ra;vn===0?(Bn=[-o.an,0,0],ra=1):vn===1?(Bn=[o.an,0,0],ra=0):vn===2?(Bn=[0,-o.an,0],ra=3):(Bn=[0,o.an,0],ra=2);const wa=dr.regionSegments[ra];if(!wa)continue;const Yr=new Float32Array(16);o.bx(Yr,Dn.projMatrix,Bn),an(Dn,dr,wa,w.translatePosMatrix(Yr,Gn,fs,Ws),mn)}}}function q0(R,w,E,F,H,Z,X){F.centroidVertexArray.length===0&&F.createCentroidsBuffer();const oe=Z?Z.findDEMTileFor(E):null;if(!(oe&&oe.dem||X))return;Z&&oe&&oe.dem&&F.selfDEMTileTimestamp!==oe.dem._timestamp&&(F.borderDoneWithNeighborZ=[-1,-1,-1,-1],F.selfDEMTileTimestamp=oe.dem._timestamp);const xe=(wt,Ot)=>{(wt.flags|Ot.flags)&o.e3?(wt.flags|=o.e3,Ot.flags|=o.e3):(wt.flags&=~o.e3,Ot.flags&=~o.e3)},Ne=wt=>new o.P(Math.ceil((wt+o.e4)*o.e5),0),Le=(wt,Ot,Vt)=>{const Ct=Math.ceil((wt+o.e4)*o.e5),ks=Math.floor(Math.max(0,Math.min(o.an-1,Vt))/4);return new o.P(Ct,ks<<5|(3&Ot)<<3|7)},We=wt=>{const Ot=w.getSource().minzoom,Vt=ks=>{const ss=w.getTileByID(ks);if(ss&&ss.hasData())return ss.getBucket(H)},Ct=[0,-1,1];for(const ks of Ct){if(wt.overscaledZ+ks(He[0]=Math.min(wt.min.y,Ot.min.y),He[1]=Math.max(wt.max.y,Ot.max.y),He[2]=o.an-Ot.min.x>wt.max.x?Ot.min.x-o.an:wt.max.x,He),dt=(wt,Ot)=>(He[0]=Math.min(wt.min.x,Ot.min.x),He[1]=Math.max(wt.max.x,Ot.max.x),He[2]=o.an-Ot.min.y>wt.max.y?Ot.min.y-o.an:wt.max.y,He),it=[(wt,Ot)=>tt(wt,Ot),(wt,Ot)=>tt(Ot,wt),(wt,Ot)=>dt(wt,Ot),(wt,Ot)=>dt(Ot,wt)],jt=(wt,Ot,Vt,Ct,ks,ss,Ns)=>{if(!Z)return 0;const Gt=[[ss?Vt:wt,ss?wt:Vt,0],[ss?Vt:Ot,ss?Ot:Vt,0]],es=Ns<0?o.an+Ns:Ns,fs=[ss?es:(wt+Ot)/2,ss?(wt+Ot)/2:es,0];return Vt===0&&Ns<0||Vt!==0&&Ns>0?Z.getForTilePoints(ks,[fs],!0,Ct):Gt.push(fs),Z.getForTilePoints(E,Gt,!0,oe),Math.max(Gt[0][2],Gt[1][2],fs[2])/Z.exaggeration()};for(let wt=0;wt<4;wt++){const Ot=F.borderFeatureIndices[wt];if(Ot.length===0)continue;const Vt=o.d$[wt](E),Ct=We(Vt);if(!(Ct&&Ct instanceof o.e0))continue;const ks=Z?Z.findDEMTileFor(Vt):null;if(!(ks&&ks.dem||X)||(Z&&ks&&ks.dem&&F.borderDEMTileTimestamp[wt]!==ks.dem._timestamp&&(F.borderDoneWithNeighborZ[wt]=-1,F.borderDEMTileTimestamp[wt]=ks.dem._timestamp),F.borderDoneWithNeighborZ[wt]===Ct.canonical.z))continue;Ct.centroidVertexArray.length===0&&Ct.createCentroidsBuffer();const ss=(wt<2?1:5)-wt,Ns=Ct.borderDoneWithNeighborZ[ss]!==F.canonical.z,Gt=Ct.borderFeatureIndices[ss];let es=0;if(F.canonical.z!==Ct.canonical.z){for(const gn of Ot)F.showCentroid(F.featuresOnBorder[gn]);if(Ns)for(const gn of Gt)Ct.showCentroid(Ct.featuresOnBorder[gn]);F.borderDoneWithNeighborZ[wt]=Ct.canonical.z,Ct.borderDoneWithNeighborZ[ss]=F.canonical.z;continue}const fs=new Map,Ws=new Set,As=new Set;for(let gn=0;gn1||en.intersectsCount()>1;{let cr=0;if(ks&&ks.dem&&!_r){const dr=it[wt](Dn,Ms),Bn=wt%2?o.an-1:0;cr=jt(dr[0],Math.min(o.an-1,dr[1]),Bn,ks,Vt,wt<2,dr[2])}Dn.centroidXY=Le(cr,wt,kn),Ms.centroidXY=Le(cr,ss,kn)}if(F.writeCentroidToBuffer(Dn),Ct.writeCentroidToBuffer(Ms),an.buildingId!==void 0){for(const cr of F.centroidData)cr.buildingId===an.buildingId&&cr!==Dn&&(cr.centroidXY=Dn.centroidXY,F.writeCentroidToBuffer(cr));for(const cr of Ct.centroidData)cr.buildingId===an.buildingId&&cr!==Ms&&(cr.centroidXY=Ms.centroidXY,Ct.writeCentroidToBuffer(cr))}}for(const gn of Ot){if(Ws.has(gn))continue;const an=F.featuresOnBorder[gn],Dn=F.centroidData[an.centroidDataIndex],Gn=an.borders[wt];let en;for(;esGn[0]+3||Ms[0]>Gn[0]-3)break;Ct.showCentroid(en),es++}if(en&&esGn[1]-3||(mn++,++es===Gt.length))break;en=Ct.featuresOnBorder[Gt[es]]}for(;Ms=Gt.length){F.showCentroid(an);continue}en=Ct.featuresOnBorder[Gt[Ms]];let vn=!1;if(mn>=1){const cr=en.borders[ss];Math.abs(Gn[0]-cr[0])<3&&Math.abs(Gn[1]-cr[1])<3&&(mn=1,vn=!0,es=Ms+1)}else if(mn===0){F.showCentroid(an);continue}const kn=Ct.centroidData[en.centroidDataIndex];X&&vn&&xe(Dn,kn);const _r=an.intersectsCount()>1||en.intersectsCount()>1;if(mn>1)es=Ms,Dn.centroidXY=kn.centroidXY=new o.P(0,0);else if(ks&&ks.dem&&!_r){const cr=it[wt](Dn,kn),dr=wt%2?o.an-1:0,Bn=jt(cr[0],Math.min(o.an-1,cr[1]),dr,ks,Vt,wt<2,cr[2]);Dn.centroidXY=kn.centroidXY=Ne(Bn)}else _r?Dn.centroidXY=kn.centroidXY=new o.P(0,0):(Dn.centroidXY=F.encodeBorderCentroid(an),kn.centroidXY=Ct.encodeBorderCentroid(en));F.writeCentroidToBuffer(Dn),Ct.writeCentroidToBuffer(kn)}else F.showCentroid(an)}F.borderDoneWithNeighborZ[wt]=Ct.canonical.z,Ct.borderDoneWithNeighborZ[ss]=F.canonical.z}(F.needsCentroidUpdate||!F.centroidVertexBuffer&&F.centroidVertexArray.length!==0)&&F.uploadCentroid(R)}const Dy=[1,0,0],qw=[0,1,0],Vw=[0,0,1];function xx(R,w,E){const F=E.transform,H=E.shadowRenderer;if(!H)return!0;const Z=R.toUnwrapped(),X=F.tileSize*H._cascades[E.currentShadowCascade].scale;let oe=w;if(F.elevation){const dt=F.elevation.getMinMaxForTile(R);dt&&(oe+=dt.max)}const xe=F.scaleZoom(X);oe/=o.e2(F.center.lat,xe);const Ne=[...H.shadowDirection];Ne[2]=-Ne[2];const Le=H.computeSimplifiedTileShadowVolume(Z,oe,X,Ne);if(!Le)return!1;const We=[Dy,qw,Vw,Ne,[Ne[0],0,Ne[2]],[0,Ne[1],Ne[2]]],He=o.cl.fromInvProjectionMatrix(F.invProjMatrix,F.worldSize,xe,F.projection.name!=="globe"),tt=H.getCurrentCascadeFrustum();return He.intersectsPrecise(Le.vertices,Le.planes,We)===0||tt.intersectsPrecise(Le.vertices,Le.planes,We)===0}function Ry(R){const{painter:w,source:E,layer:F,coords:H}=R;let Z=R.defines;const X=w.context,oe=w.renderPass==="shadow",xe=w.renderPass==="light-beam",Ne=w.shadowRenderer,Le=o.e2(w.transform.center.lat,w.transform.zoom),We=Qc(w,F.paint.get("building-cutoff-fade-range"));We.shouldRenderCutoff&&(Z=Z.concat("RENDER_CUTOFF"));const He=F.paint.get("building-front-cutoff"),tt=He[2]<1&&!w.terrain,dt=Uw(w.transform.pitch,He,!!w.terrain);tt&&(Z=Z.concat("RENDER_FRONT_CUTOFF"),w.maxFrontCutoffRawStart=Math.max(w.maxFrontCutoffRawStart,He[0])),R.floodLightIntensity>0&&(Z=Z.concat("FLOOD_LIGHT"));for(const it of H){const jt=E.getTile(it),wt=jt.getBucket(F);if(!wt)continue;Ne&&Ne.getMaxCascadeForTile(it.toUnwrapped())===0&&(Z=Z.concat("SHADOWS_SINGLE_CASCADE"));const Ot=wt.programConfigurations.get(F.id);let Vt,Ct,ks,ss=w.translatePosMatrix(it.expandedProjMatrix,jt,[0,0],"map");if(ss=o.cC(o.bb(),ss,[1,1,R.verticalScale]),oe&&Ne){if(xx(jt.tileID,wt.maxHeight*Le,w))continue;let Gt=Ne.calculateShadowPassMatrixFromTile(jt.tileID.toUnwrapped());Gt=o.cC(o.bb(),Gt,[1,1,R.verticalScale]),ks=Di(Gt),Vt=Ct=w.getOrCreateProgram("buildingDepth",{config:Ot,defines:Z,overrideFog:!1})}else if(xe)Vt=Ct=w.getOrCreateProgram("buildingBloom",{config:Ot,defines:Z,overrideFog:!1}),ks=nl(ss);else{const Gt=w.transform.calculatePosMatrix(it.toUnwrapped(),w.transform.worldSize);o.cC(Gt,Gt,[1,1,R.verticalScale]);const es=o.bb();o.cC(es,Gt,[1,-1,1/Le]),o.b7(es,es),o.e6(es,es);const fs=w.transform.getFreeCameraOptions().position,Ws=1<{if(xe){const fs=Gt.entranceBloom;es.draw(w,X.gl.TRIANGLES,R.depthMode,La.disabled,R.blendMode,pa.disabled,ks,F.id,fs.layoutVertexBuffer,fs.indexBuffer,fs.segmentsBucket,F.paint,w.transform.zoom,Ot,[fs.layoutAttenuationBuffer,fs.layoutColorBuffer])}else{const fs=Gt.segmentsBucket;let Ws=[Gt.layoutNormalBuffer,Gt.layoutCentroidBuffer,Gt.layoutColorBuffer,Gt.layoutFloodLightDataBuffer];Gt.layoutFacadePaintBuffer&&(Ws=Ws.concat([Gt.layoutFacadeDataBuffer,Gt.layoutFacadeVerticalRangeBuffer,Gt.layoutFacadePaintBuffer])),es.draw(w,X.gl.TRIANGLES,R.depthMode,La.disabled,R.blendMode,oe?pa.disabled:pa.backCW,ks,F.id,Gt.layoutVertexBuffer,Gt.indexBuffer,fs,F.paint,w.transform.zoom,Ot,Ws)}};w.uploadCommonUniforms(X,Ct,it.toUnwrapped(),null,We),wt.buildingWithoutFacade&&Ns(wt.buildingWithoutFacade,Ct),wt.buildingWithFacade&&(Vt!==Ct&&w.uploadCommonUniforms(X,Vt,it.toUnwrapped(),null,We),Ns(wt.buildingWithFacade,Vt))}}function gx(R,w,E,F,H,Z,X,oe,xe,Ne,Le,We,He,tt){const dt=R.context.gl,it=R.depthModeForSublayer(1,qr.ReadOnly,dt.LEQUAL,!0),jt=.1*(1-(wt=Le))+3*wt;var wt;const Ot=R._showOverdrawInspector,Vt=We,Ct=new sf;Ot||Hg(Ct,R,w,E,F,it,new La({func:dt.ALWAYS,mask:255},255,255,dt.KEEP,dt.KEEP,dt.REPLACE),new Ma([dt.ONE,dt.ONE,dt.ONE,dt.ONE],o.aq.transparent,[!1,!1,!1,!0],dt.MIN),pa.disabled,H,"sdf",Z,X,oe,xe,Ne,jt,Vt,!1,void 0);{const ks=Ot?La.disabled:new La({func:dt.EQUAL,mask:255},255,255,dt.KEEP,dt.DECR,dt.DECR),ss=Ot?R.colorModeForRenderPass():new Ma([dt.ONE_MINUS_DST_ALPHA,dt.DST_ALPHA,dt.ONE,dt.ONE],o.aq.transparent,[!0,!0,!0,!0]);Hg(Ct,R,w,E,F,it,ks,ss,pa.disabled,H,"color",Z,X,oe,xe,Ne,jt,Vt,!1,void 0)}}function o_(R){return[R[0]*o.e7,R[1]*o.e7,R[2]*o.e7,0]}function U1(R,w,E,F,H,Z,X,oe,xe){const Ne=F.getSource(),Le=E.globeSharedBuffers;if(!Le)return;let We,He,tt;if(w&&(We=F.getTile(w)),Ne instanceof o.aV?(He=Ne.texture,tt=o.dw(0,0,E.transform)):We&&w&&(He=We.texture,tt=o.dw(w.canonical.z,w.canonical.x,E.transform)),!He||!tt)return;R||(tt=o.cC(o.bb(),tt,[1,-1,1]));const dt=E.context,it=dt.gl,jt=H.paint.get("raster-resampling")==="nearest"?it.NEAREST:it.LINEAR,wt=E.colorModeForDrapableLayerRenderPass(Z),Ot=X.defines;Ot.push("GLOBE_POLES");const Vt=new qr(it.LEQUAL,qr.ReadWrite,E.depthRangeFor3D),Ct=Float32Array.from(E.transform.expandedFarZProjMatrix),ks=Float32Array.from(o.du(o.dv(new o.cn(0,0,0))));E.terrain&&E.terrain.prepareDrawTile(),dt.activeTexture.set(it.TEXTURE0),He.bind(jt,it.CLAMP_TO_EDGE),dt.activeTexture.set(it.TEXTURE1),He.bind(jt,it.CLAMP_TO_EDGE),"useMipmap"in He&&dt.extTextureFilterAnisotropic&&E.transform.pitch>20&&it.texParameterf(it.TEXTURE_2D,dt.extTextureFilterAnisotropic.TEXTURE_MAX_ANISOTROPY_EXT,dt.extTextureFilterAnisotropicMax);const[ss,Ns,Gt,es]=w?Le.getPoleBuffers(w.canonical.z,!1):Le.getPoleBuffers(0,!0),fs=H.paint.get("raster-elevation");let Ws;R?(Ws=ss,E.renderDefaultNorthPole=fs!==0):(Ws=Ns,E.renderDefaultSouthPole=fs!==0);const As=o_(X.mix),gn=((Dn,Gn,en,Ms,mn,vn,kn,_r,cr,dr,Bn,ra,wa,Yr)=>Xd(Dn,Gn,en,Ms,new Float32Array(16),new Float32Array(9),[0,0],mn,[0,0],[0,0,0,0],1,{opacity:1,mix:0},kn,[0,0],cr,2,Bn,ra,wa,1,0,Yr))(E,Ct,ks,tt,o.al(E.transform.zoom),0,H,0,fs,0,As,X.offset,X.range,Z),an=E.getOrCreateProgram("raster",{defines:Ot});E.uploadCommonUniforms(dt,an,null),an.draw(E,it.TRIANGLES,Vt,xe,wt,oe,gn,H.id,Ws,Gt,es)}function q1(R){if(R.isOrthographic)return[0,0,0,0];const w=R._nearZ,E=R.projection.farthestPixelDistance(R),F=E-w,H=.2*R.height,Z=w+H;return[w,E,(Z-H-w)/F,(Z-w)/F]}function Hw(R,w,E,F){if(R)return w instanceof Kp&&R instanceof Pf?w.getTextureDescriptor(R,E,!0):{texture:R.texture,mix:o_(F.mix),offset:F.offset,buffer:0,tileSize:1}}var V1=o.e8([{name:"a_index",type:"Int16",components:1}]);class wu{constructor(w,E,F,H){const Z={width:F[0],height:F[1],data:null},X=w.gl;this.targetColorTexture=new o.T(w,Z,X.RGBA8,{useMipmap:!1}),this.backgroundColorTexture=new o.T(w,Z,X.RGBA8,{useMipmap:!1}),this.context=w,this.updateParticleTexture(E,H),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,H=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 Z=new o.e9;Z.reserve(H);for(let X=0;X0){const As=o.ec(E.canonical,xe),gn=o.ed(As);He=o.aD(new Float32Array(16),xe.globeMatrix,gn),o.aD(He,xe.projMatrix,He)}const tt=o.bb();tt[12]+=2*H/(o.o.devicePixelRatio*xe.width),tt[13]+=2*Z/(o.o.devicePixelRatio*xe.height),o.aD(He,tt,He);const dt=R.getOrCreateProgram("debug",{defines:We}),it=w.getTileByID(E.key);R.terrain&&R.terrain.setupElevationDraw(it,dt);const jt=qr.disabled,wt=La.disabled,Ot=R.colorModeForRenderPass(),Vt="$debug";oe.activeTexture.set(Ne.TEXTURE0),R.emptyTexture.bind(Ne.LINEAR,Ne.CLAMP_TO_EDGE),Le?it._makeGlobeTileDebugBuffers(R.context,xe):it._makeDebugTileBoundsBuffers(R.context,xe.projection);const Ct=it._tileDebugBuffer||R.debugBuffer,ks=it._tileDebugIndexBuffer||R.debugIndexBuffer,ss=it._tileDebugSegments||R.debugSegments;if(dt.draw(R,Ne.LINE_STRIP,jt,wt,Ot,pa.disabled,co(He,F.toPremultipliedRenderColor(null)),Vt,Ct,ks,ss,null,null,null,[it._globeTileDebugBorderBuffer]),X){const As=it.latestRawTileData,gn=Math.floor((As&&As.byteLength||0)/1024);let an=E.canonical.toString();E.overscaledZ!==E.canonical.z&&(an+=` => ${E.overscaledZ}`),an+=` ${it.state}`,an+=` ${gn}kb`,function(Dn,Gn){Dn.initDebugOverlayCanvas();const en=Dn.debugOverlayCanvas,Ms=Dn.context.gl,mn=Dn.debugOverlayCanvas.getContext("2d");mn.clearRect(0,0,en.width,en.height),mn.shadowColor="white",mn.shadowBlur=2,mn.lineWidth=1.5,mn.strokeStyle="white",mn.textBaseline="top",mn.font="bold 36px Open Sans, sans-serif",mn.fillText(Gn,5,5),mn.strokeText(Gn,5,5),Dn.debugOverlayTexture.update(en),Dn.debugOverlayTexture.bind(Ms.LINEAR,Ms.CLAMP_TO_EDGE)}(R,an)}const Ns=w.getTile(E).tileSize,Gt=512/Math.min(Ns,512)*(E.overscaledZ/xe.zoom)*.5,es=it._tileDebugTextBuffer||R.debugBuffer,fs=it._tileDebugTextIndexBuffer||R.quadTriangleIndexBuffer,Ws=it._tileDebugTextSegments||R.debugSegments;dt.draw(R,Ne.TRIANGLES,jt,wt,Ma.alphaBlended,pa.disabled,co(He,o.aq.transparent.toPremultipliedRenderColor(null),Gt),Vt,es,fs,Ws,null,null,null,[it._globeTileDebugTextBuffer])}function t4(R,w,E,F){Gg(R,0,w+E/2,R.transform.width,E,F)}function Lv(R,w,E,F){Gg(R,w-E/2,0,E,R.transform.height,F)}function Gg(R,w,E,F,H,Z){const X=R.context,oe=X.gl;oe.enable(oe.SCISSOR_TEST),oe.scissor(w*o.o.devicePixelRatio,E*o.o.devicePixelRatio,F*o.o.devicePixelRatio,H*o.o.devicePixelRatio),X.clear({color:Z}),oe.disable(oe.SCISSOR_TEST)}const C2=o.e8([{name:"a_pos_3f",components:3,type:"Float32"}]),{members:Ru}=C2;function um(R,w,E,F){R.emplaceBack(w,E,F)}class Dd{constructor(w){this.vertexArray=new o.ee,this.indices=new o.dC,um(this.vertexArray,-1,-1,1),um(this.vertexArray,1,-1,1),um(this.vertexArray,-1,1,1),um(this.vertexArray,1,1,1),um(this.vertexArray,-1,-1,-1),um(this.vertexArray,1,-1,-1),um(this.vertexArray,-1,1,-1),um(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,Ru),this.indexBuffer=w.createIndexBuffer(this.indices),this.segment=o.dy.simpleSegment(0,0,36,12)}}function rf(R,w,E,F,H,Z){const X=R.context.gl,oe=w.paint.get("sky-atmosphere-color"),xe=w.paint.get("sky-atmosphere-halo-color"),Ne=w.paint.get("sky-atmosphere-sun-intensity"),Le=((We,He,tt,dt,it)=>({u_matrix_3f:We,u_sun_direction:He,u_sun_intensity:tt,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),H,Ne,oe.toPremultipliedRenderColor(null),xe.toPremultipliedRenderColor(null));X.framebufferTexture2D(X.FRAMEBUFFER,X.COLOR_ATTACHMENT0,X.TEXTURE_CUBE_MAP_POSITIVE_X+Z,w.skyboxTexture,0),E.draw(R,X.TRIANGLES,qr.disabled,La.disabled,Ma.unblended,pa.frontCW,Le,"skyboxCapture",w.skyboxGeometry.vertexBuffer,w.skyboxGeometry.indexBuffer,w.skyboxGeometry.segment)}const _k=o.e8([{type:"Float32",name:"a_pos",components:3},{type:"Float32",name:"a_uv",components:2}]);class A2{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,_k.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 wk=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 H0{constructor(){this.starsCount=16e3,this.sizeMultiplier=.15,this.sizeRange=100,this.intensityRange=200}}class jk{constructor(w){this.colorModeAlphaBlendedWriteRGB=new Ma([1,kl,1,kl],o.aq.transparent,[!0,!0,!0,!1]),this.colorModeWriteAlpha=new Ma([1,0,1,0],o.aq.transparent,[!1,!1,!1,!0]),this.params=new H0,this.updateNeeded=!0}update(w){const E=w.context;if(!this.atmosphereBuffer||this.updateNeeded){this.updateNeeded=!1,this.atmosphereBuffer=new A2(E);const F=this.params.sizeRange,H=this.params.intensityRange,Z=function(Le){const We=o.em(30),He=[];for(let tt=0;tt{const Gt=Z.projection.name==="globe"?["PROJECTION_GLOBE_VIEW","FOG"]:["FOG"];Ns&&Gt.push("ALPHA_PASS");const es=w.getOrCreateProgram("globeAtmosphere",{defines:Gt}),fs=((As,gn,an,Dn,Gn,en,Ms,mn,vn,kn,_r,cr)=>({u_frustum_tl:As,u_frustum_tr:gn,u_frustum_br:an,u_frustum_bl:Dn,u_horizon:Gn,u_transition:en,u_fadeout_range:Ms,u_atmosphere_fog_color:mn.toArray01(),u_high_color:vn.toArray01(),u_space_color:kn.toArray01(),u_temporal_offset:_r,u_horizon_angle:cr}))(Z.frustumCorners.TL,Z.frustumCorners.TR,Z.frustumCorners.BR,Z.frustumCorners.BL,Z.frustumCorners.horizon,oe,jt,Le,He,dt,Ot,ks);w.uploadCommonUniforms(F,es);const Ws=this.atmosphereBuffer;Ws&&es.draw(w,H.TRIANGLES,X,La.disabled,Ns?this.colorModeWriteAlpha:this.colorModeAlphaBlendedWriteRGB,pa.backCW,fs,Ns?"atmosphere_glow_alpha":"atmosphere_glow",Ws.vertexBuffer,Ws.indexBuffer,Ws.segments)};ss(!1),ss(!0)}drawStars(w,E){const F=o.aC(E.properties.get("star-intensity"),0,1);if(F===0)return;const H=w.context,Z=H.gl,X=w.transform,oe=w.getOrCreateProgram("stars"),xe=o.bL([]);o.bN(xe,xe,-X._pitch),o.bM(xe,xe,-X.angle),o.bN(xe,xe,o.ap(X._center.lat)),o.ek(xe,xe,-o.ap(X._center.lng));const Ne=o.bR(new Float32Array(16),xe),Le=o.aD([],X.starsProjMatrix,Ne),We=o.eg([],Ne),He=o.el([],We),tt=[0,1,0];o.dG(tt,tt,He),o.bJ(tt,tt,this.params.sizeMultiplier);const dt=[1,0,0];o.dG(dt,dt,He),o.bJ(dt,dt,this.params.sizeMultiplier);const it=(jt=tt,wt=dt,Ot=F,{u_matrix:Float32Array.from(Le),u_up:jt,u_right:wt,u_intensity_multiplier:Ot});var jt,wt,Ot;w.uploadCommonUniforms(H,oe),this.starsVx&&this.starsIdx&&oe.draw(w,Z.TRIANGLES,qr.disabled,La.disabled,this.colorModeAlphaBlendedWriteRGB,pa.disabled,it,"atmosphere_stars",this.starsVx,this.starsIdx,this.starsSegments)}}class Zx{constructor(){this.visibleTiles=[]}updateBorders(w,E){const F=[],H=[],Z=w._getRenderableCoordinates(!1,!0);for(const xe of Z){const Ne=w.getTile(xe);if(!Ne.hasData())continue;const Le=Ne.getBucket(E);Le&&(Le.isEmpty()||(F.push(xe.key),H.push({bucket:Le,tileID:xe.canonical})))}let X=F.length!==this.visibleTiles.length;if(!X){F.sort();for(let xe=0;xexe.tileID.z-Ne.tileID.z||xe.tileID.x-Ne.tileID.x||xe.tileID.y-Ne.tileID.y);for(const xe of H){const Ne=new Array,Le=new Array,We=xe.bucket;for(const He of We.featuresOnBorder)oe.has(He.featureId)?Le.push(He.footprintIndex):(oe.add(He.featureId),Ne.push(He.footprintIndex));We.updateFootprintHiddenFlags(Ne,o.en,!1),We.updateFootprintHiddenFlags(Le,o.en,!0)}}}function iM(R,w){const E=[...R],F=w.cameraWorldSizeForFog/w.worldSize,H=o.b9([]);return o.cC(H,H,[F,F,1]),o.aD(E,H,E),o.aD(E,w.worldToFogMatrix,E),E}function Si(R,w,E,F,H){const Z=E.material,X=F.context,{baseColorTexture:oe,metallicRoughnessTexture:xe}=Z.pbrMetallicRoughness,{normalTexture:Ne,occlusionTexture:Le,emissionTexture:We}=Z;function He(dt,it,jt){if(dt&&(R.push(it),X.activeTexture.set(X.gl.TEXTURE0+jt),dt.gfxTexture)){const{minFilter:wt,magFilter:Ot,wrapS:Vt,wrapT:Ct}=dt.sampler;dt.gfxTexture.bindExtraParam(wt,Ot,Vt,Ct)}}He(oe,"HAS_TEXTURE_u_baseColorTexture",5),He(xe,"HAS_TEXTURE_u_metallicRoughnessTexture",6),He(Ne,"HAS_TEXTURE_u_normalTexture",7),He(Le,"HAS_TEXTURE_u_occlusionTexture",8),He(We,"HAS_TEXTURE_u_emissionTexture",9),H&&(H.texture||(H.texture=new o.dR(F.context,H.image,[H.image.height,H.image.height,H.image.height],X.gl.RGBA8)),X.activeTexture.set(X.gl.TEXTURE0+10),H.texture&&H.texture.bind(X.gl.LINEAR,X.gl.CLAMP_TO_EDGE),R.push("APPLY_LUT_ON_GPU")),E.texcoordBuffer&&(R.push("HAS_ATTRIBUTE_a_uv_2f"),w.push(E.texcoordBuffer)),E.colorBuffer&&(R.push(E.colorBuffer.itemSize===12?"HAS_ATTRIBUTE_a_color_3f":"HAS_ATTRIBUTE_a_color_4f"),w.push(E.colorBuffer)),E.normalBuffer&&(R.push("HAS_ATTRIBUTE_a_normal_3f"),w.push(E.normalBuffer)),E.pbrBuffer&&(R.push("HAS_ATTRIBUTE_a_pbr"),R.push("HAS_ATTRIBUTE_a_heightBasedEmissiveStrength"),w.push(E.pbrBuffer)),Z.alphaMode!=="OPAQUE"&&Z.alphaMode!=="MASK"||R.push("UNPREMULT_TEXTURE_IN_SHADER"),Z.defined||R.push("DIFFUSE_SHADED");const tt=F.shadowRenderer;tt&&(R.push("RENDER_SHADOWS"),tt.useNormalOffset&&R.push("NORMAL_OFFSET"))}function Nk(R,w,E,F,H,Z){const X=R.modelOpacity,oe=w.context,xe=new qr(w.context.gl.LEQUAL,R.isLightMesh?qr.ReadOnly:qr.ReadWrite,w.depthRangeFor3D),Ne=w.transform,Le=R.mesh,We=Le.material,He=We.pbrMetallicRoughness,tt=w.style.fog;let dt;dt=w.transform.projection.zAxisUnit==="pixels"?[...R.nodeModelMatrix]:o.aD([],F.zScaleMatrix,R.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),Ot=Xl(new Float32Array(R.worldViewProjection),new Float32Array(dt),new Float32Array(it),null,w,X,He.baseColorFactor,We.emissiveFactor,He.metallicFactor,He.roughnessFactor,We,wt,E,void 0,void 0,R.materialOverride,R.modelColor),Vt={defines:[]},Ct=[],ks=w.shadowRenderer;ks&&(ks.useNormalOffset=!1),Si(Vt.defines,Ct,Le,w,jt?null:E.lut);let ss=null;if(tt){const es=iM(R.nodeModelMatrix,w.transform);if(ss=new Float32Array(es),Ne.projection.name!=="globe"){const fs=Le.aabb.min,Ws=Le.aabb.max,[As,gn]=tt.getOpacityForBounds(es,fs[0],fs[1],Ws[0],Ws[1]);Vt.overrideFog=As>=va||gn>=va}}const Ns=Qc(w,E.paint.get("model-cutoff-fade-range"));Ns.shouldRenderCutoff&&Vt.defines.push("RENDER_CUTOFF");const Gt=w.getOrCreateProgram("model",Vt);w.uploadCommonUniforms(oe,Gt,null,ss,Ns),w.renderPass!=="shadow"&&ks&&ks.setupShadowsFromMatrix(R.nodeModelMatrix,Gt),Gt.draw(w,oe.gl.TRIANGLES,xe,H,Z,Le.material.doubleSided?pa.disabled:pa.backCCW,Ot,E.id,Le.vertexBuffer,Le.indexBuffer,Le.segments,E.paint,w.transform.zoom,void 0,Ct)}function s4(R,w){return R.style._importedAsBasemap?"basemap":w.scope}function PC(R,w,E,F,H,Z,X,oe,xe,Ne){const Le=R.transform,We=!!w.isGeometryBloom&&w.isGeometryBloom;if(We&&R.renderPass==="shadow")return;const He=Le.projection.name==="globe"?o.ev(E,Le):[...E];o.aD(He,He,w.globalMatrix);const tt=o.aD([],F,He);if(w.meshes)for(const dt of w.meshes){const it=oe.get(dt.material.name);if(it&&it.opacity<=0)continue;if(dt.material.alphaMode!=="BLEND"){X.push({mesh:dt,depth:0,modelIndex:H,worldViewProjection:tt,nodeModelMatrix:He,isLightMesh:We,materialOverride:it,modelOpacity:xe,modelColor:Ne,node:w,modelMatrix:E});continue}const jt=o.ah([],dt.centroid,tt);!Le.isOrthographic&&jt[2]<=0||Z.push({mesh:dt,depth:jt[2],modelIndex:H,worldViewProjection:tt,nodeModelMatrix:He,isLightMesh:We,materialOverride:it,modelOpacity:xe,modelColor:Ne,node:w,modelMatrix:E})}if(w.children)for(const dt of w.children)PC(R,dt,E,F,H,Z,X,oe,xe,Ne)}function kk(R,w,E,F){const H=E.shadowRenderer;if(!H)return;const Z=H.getShadowPassDepthMode(),X=H.calculateShadowPassMatrixFromMatrix(w),oe=Du(X);E.getOrCreateProgram("modelDepth").draw(E,E.context.gl.TRIANGLES,Z,La.disabled,Ma.disabled,pa.disabled,oe,F.id,R.vertexBuffer,R.indexBuffer,R.segments,F.paint,E.transform.zoom,void 0,void 0)}function IC(R,w,E,F){const H=function(Le,We){if(We.footprintDebugMesh)return We.footprintDebugMesh;if(!We.footprint)return null;const He=Le.context,tt=We.footprint.vertices,dt=We.footprint.indices,it=new o.dB;it.reserve(tt.length);for(const fs of tt)it.emplaceBack(fs.x,fs.y);const jt=new o.dC;jt.reserve(dt.length);for(let fs=0;fs0){const He=Z.terrain,tt=He.findDEMTileFor(oe);tt&&tt.dem?xe=o.ex.create(He,oe,tt):We=0}if(We===0&&(X.terrainElevationMin=0,X.terrainElevationMax=0),We===X.validForExaggeration&&(We===0||xe&&xe._demTile&&xe._demTile.tileID===X.validForDEMTile.id&&xe._dem._timestamp===X.validForDEMTile.timestamp))return!1;for(const He in X.instancesPerModel){const tt=X.instancesPerModel[He];for(let dt=0;dtNe&&(Ne=tt.max)}const Le=o.aC(F.x,Z,X)-F.x,We=o.aC(F.y,oe,xe)-F.y,He=o.bU(Ne,w.center.lat)-F.z;return w._zoomFromMercatorZ(Math.sqrt(Le*Le+We*We+He*He))}function bc(R,w,E,F,H,Z,X){const oe=R.context,xe=R.renderPass==="shadow",Ne=R.shadowRenderer,Le=xe&&Ne?Ne.getShadowPassDepthMode():new qr(oe.gl.LEQUAL,qr.ReadWrite,R.depthRangeFor3D),We=R.isTileAffectedByFog(Z),He=R.transform.projection.name==="globe";if(E.meshes)for(const tt of E.meshes){const dt=He?[]:["MODEL_POSITION_ON_GPU"],it=[];let jt,wt,Ot;const Vt=!He&&F.instancedDataArray.length>20;Vt&&dt.push("INSTANCED_ARRAYS");const Ct=Qc(R,w.paint.get("model-cutoff-fade-range"));if(Ct.shouldRenderCutoff&&dt.push("RENDER_CUTOFF"),xe&&Ne)jt=R.getOrCreateProgram("modelDepth",{defines:dt}),wt=Du(X.shadowTileMatrix,X.shadowTileMatrix,Float32Array.from(E.globalMatrix)),Ot=Ma.disabled;else{Si(dt,it,tt,R,w.paint.get("model-color-use-theme").constantOr("default")==="none"?null:w.lut),jt=R.getOrCreateProgram("model",{defines:dt,overrideFog:We});const ss=tt.material,Ns=ss.pbrMetallicRoughness,Gt=w.paint.get("model-opacity").constantOr(1),es=w.paint.get("model-emissive-strength").constantOr(0);wt=Xl(Z.expandedProjMatrix,Float32Array.from(E.globalMatrix),new Float32Array(16),null,R,Gt,Ns.baseColorFactor,ss.emissiveFactor,Ns.metallicFactor,Ns.roughnessFactor,ss,es,w,H),Ne&&(X.shadowUniformsInitialized?jt.setShadowUniformValues(oe,Ne.getShadowUniformValues()):(Ne.setupShadows(Z.toUnwrapped(),jt,"model-tile"),X.shadowUniformsInitialized=!0)),Ot=Ct.shouldRenderCutoff||Gt<1||ss.alphaMode!=="OPAQUE"?Ma.alphaBlended:Ma.unblended}R.uploadCommonUniforms(oe,jt,Z.toUnwrapped(),null,Ct);const ks=tt.material.doubleSided?pa.disabled:pa.backCCW;if(Vt)it.push(F.instancedDataBuffer),jt.draw(R,oe.gl.TRIANGLES,Le,La.disabled,Ot,ks,wt,w.id,tt.vertexBuffer,tt.indexBuffer,tt.segments,w.paint,R.transform.zoom,void 0,it,F.instancedDataArray.length);else{const ss=xe?"u_instance":"u_normal_matrix";for(let Ns=0;Nsxe[1]?X:xe,Z[0]=E.max[0],X=o.aE(o.bE(),Z,H),oe=X[1]xe[1]?X:xe,Z[1]=E.min[1],X=o.aE(o.bE(),Z,H),oe=X[1]xe[1]?X:xe;const Ne=o.aC(F[0],0,1),Le=100*w.pixelsPerMeter*o.aC(F[1],0,1),We=o.aC(F[2],0,1),He=o.ey(o.bE(),oe,xe,Ne),tt=Math.tan(.5*w.fovX),dt=-He[2]*tt;if(Le===0)return He[1]<-Math.abs(dt)?We:1;const it=(-Math.abs(dt)-He[1])/Le,jt=(Ot,Vt,Ct)=>(1-Ct)*Ot+Ct*Vt,wt=o.aC(jt(1,We,it),We,1);return jt(1,wt,o.aC((w.pitch-20)/20,0,1))}class RC{}class oM{constructor(){this._storage=new Map}getLinesFromTrianglesBuffer(w,E,F){{const We=this._storage.get(E.id);if(We)return We.lastUsedFrameIdx=w,We.buf}const H=F.gl,Z=H.getBufferParameter(H.ELEMENT_ARRAY_BUFFER,H.BUFFER_SIZE),X=new ArrayBuffer(Z),oe=new Int16Array(X);H.getBufferSubData(H.ELEMENT_ARRAY_BUFFER,0,new Int16Array(X));const xe=new o.eA;for(let We=0;We30&&(F.buf.destroy(),this._storage.delete(E))}destroy(){for(const[w,E]of this._storage)E.buf.destroy(),this._storage.delete(w)}}class lM{constructor(){this.occluderSize=30,this.depthOffset=-1e-4}}const T2=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 cM{constructor(w){this.revealStart=11,this.revealRange=2}}const OC=o.e8([{type:"Float32",name:"a_pos_2f",components:2}]);class SF{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 X=new o.eB,oe=new o.dC;X.emplaceBack(-1,-1),X.emplaceBack(1,-1),X.emplaceBack(1,1),X.emplaceBack(-1,1),oe.emplaceBack(0,1,2),oe.emplaceBack(0,2,3),this.vignetteVx=w.context.createVertexBuffer(X,OC.members),this.vignetteIdx=w.context.createIndexBuffer(oe)}const H=o.dy.simpleSegment(0,0,4,6);if(this.vignetteVx&&this.vignetteIdx){w.uploadCommonUniforms(w.context,F);const X={u_vignetteShape:(Z={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:Z.vignetteColor};F.draw(w,w.context.gl.TRIANGLES,qr.disabled,La.disabled,Ma.alphaBlended,pa.disabled,X,"vignette",this.vignetteVx,this.vignetteIdx,H)}var Z}}class FC{constructor(){this._accumulatedOffsetX=0,this._accumulatedOffsetY=0,this._accumulatedElevation=0}update(w,E){const F=w.getFreeCameraOptions().position,H=F.toAltitude(),Z=F.toLngLat(),X=o.ap(Z.lng),oe=o.ap(Z.lat),xe=w.pixelsPerMeter/E,Ne=X*o.eD,Le=o.eD*Math.log(Math.tan(Math.PI/4+oe/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 We=-this._offsetYPrev+Le,He=-this._elevationPrev+H;this._accumulatedOffsetX+=(-this._offsetXPrev+Ne)*xe,this._accumulatedOffsetY+=We*xe,this._accumulatedElevation+=He*xe,this._offsetXPrev=Ne,this._offsetYPrev=Le,this._elevationPrev=H}}getPosition(){return[this._accumulatedOffsetX,this._accumulatedOffsetY,this._accumulatedElevation]}}function te(R,w){return[-(R[0]-Math.floor(R[0]/w)*w),-(R[1]-Math.floor(R[1]/w)*w),-(R[2]-Math.floor(R[2]/w)*w)]}function ie(R){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=ie(this.particlesCount),H=new o.eE,Z=new o.dC;let X=0;const oe=o.em(1323123451230);for(let xe=0;xeF)return;const H=Pe(0,1,E.revealStart,E.revealStart+E.revealRange,F);if(!this.particlesVx||!this.particlesIdx)return;const Z=structuredClone(this._params);let X=[-Z.direction.x,Z.direction.y,-100];o.ay(X,X);const oe=structuredClone(this._vignetteParams);oe.strength*=H,Z.overrideStyleParameters||(Z.intensity=w.style.rain.state.density,Z.timeFactor=w.style.rain.state.intensity,Z.color=structuredClone(w.style.rain.state.color),X=structuredClone(w.style.rain.state.direction),Z.screenThinning.intensity=w.style.rain.state.centerThinning,Z.dropletSizeX=w.style.rain.state.dropletSize[0],Z.dropletSizeYScale=w.style.rain.state.dropletSize[1]/w.style.rain.state.dropletSize[0],Z.distortionStrength=100*w.style.rain.state.distortionStrength,oe.strength=1,oe.color=structuredClone(w.style.rain.state.vignetteColor));const xe=this.updateOnRender(w,Z.timeFactor),Ne=w.context,Le=Ne.gl,We=w.transform;this.screenTexture&&this.screenTexture.size[0]===w.width&&this.screenTexture.size[1]===w.height||(this.screenTexture=new o.T(Ne,{width:w.width,height:w.height,data:null},Le.RGBA8)),Z.distortionStrength>0&&(Ne.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 He=w.getOrCreateProgram("rainParticle");w.uploadCommonUniforms(Ne,He),Ne.activeTexture.set(Le.TEXTURE0),this.screenTexture.bind(Le.LINEAR,Le.CLAMP_TO_EDGE);const tt=[Z.color.r,Z.color.g,Z.color.b,Z.color.a],dt=(it,jt)=>{const wt=te(this._movement.getPosition(),it),Ot=Z.dropletSizeX,Vt=Z.dropletSizeX*Z.dropletSizeYScale,Ct=w.width/2,ks=w.height/2,ss=Pe(0,Z.screenThinning.start,0,1,Z.screenThinning.intensity),Ns=Pe(.001,Z.screenThinning.range,0,1,Z.screenThinning.intensity),Gt=Pe(0,Z.screenThinning.particleOffset,0,1,Z.screenThinning.intensity),es=(fs={modelview:xe.modelviewMatrix,projection:xe.projectionMatrix,time:this._accumulatedTimeFromStart,camPos:wt,velocityConeAperture:Z.velocityConeAperture,velocity:Z.velocity,boxSize:it,rainDropletSize:[Ot,Vt],distortionStrength:Z.distortionStrength,rainDirection:X,color:tt,screenSize:[We.width,We.height],thinningCenterPos:[Ct,ks],thinningShape:[ss,Ns,Math.pow(10,Z.screenThinning.fadePower)],thinningAffectedRatio:Z.screenThinning.affectedRatio,thinningParticleOffset:Gt,shapeDirectionalPower:Z.shapeDirPower,shapeNormalPower:Z.shapeNormalPower,mode:jt?0:1},{u_modelview:Float32Array.from(fs.modelview),u_projection:Float32Array.from(fs.projection),u_time:fs.time,u_cam_pos:fs.camPos,u_texScreen:0,u_velocityConeAperture:fs.velocityConeAperture,u_velocity:fs.velocity,u_boxSize:fs.boxSize,u_rainDropletSize:fs.rainDropletSize,u_distortionStrength:fs.distortionStrength,u_rainDirection:fs.rainDirection,u_color:fs.color,u_screenSize:fs.screenSize,u_thinningCenterPos:fs.thinningCenterPos,u_thinningShape:fs.thinningShape,u_thinningAffectedRatio:fs.thinningAffectedRatio,u_thinningParticleOffset:fs.thinningParticleOffset,u_shapeDirectionalPower:fs.shapeDirectionalPower,u_shapeNormalPower:fs.shapeNormalPower,u_mode:fs.mode});var fs;const Ws=Math.round(Z.intensity*this.particlesCount),As=o.dy.simpleSegment(0,0,4*Ws,2*Ws);He.draw(w,Le.TRIANGLES,qr.disabled,La.disabled,Ma.alphaBlended,pa.disabled,es,"rain_particles",this.particlesVx,this.particlesIdx,As)};Z.distortionStrength>0&&dt(Z.boxSize,!0),dt(Z.boxSize,!1),this._vignette.draw(w,oe)}}const Et=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 Fs extends st{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 cM("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=ie(this.particlesCount),H=new o.eF,Z=new o.dC;let X=0;const oe=o.em(1323123451230);for(let xe=0;xeX)return;const oe=Pe(0,1,Z.revealStart,Z.revealStart+Z.revealRange,X);H.strength*=oe,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,H.strength=1,H.color=structuredClone(w.style.snow.state.vignetteColor));const xe=this.updateOnRender(w,E.timeFactor);if(!this.particlesVx||!this.particlesIdx)return;const Ne=w.context,Le=Ne.gl,We=w.transform,He=w.getOrCreateProgram("snowParticle");w.uploadCommonUniforms(Ne,He),((tt,dt,it)=>{const jt=te(this._movement.getPosition(),tt),wt=We.width/2,Ot=We.height/2,Vt=Pe(0,it.screenThinning.start,0,1,it.screenThinning.intensity),Ct=Pe(.001,it.screenThinning.range,0,1,it.screenThinning.intensity),ks=Pe(0,it.screenThinning.particleOffset,0,1,it.screenThinning.intensity),ss=(Ns={modelview:xe.modelviewMatrix,projection:xe.projectionMatrix,time:this._accumulatedTimeFromStart,camPos:jt,velocityConeAperture:it.velocityConeAperture,velocity:it.velocity,horizontalOscillationRadius:it.horizontalOscillationRadius,horizontalOscillationRate:it.horizontalOscillationRate,boxSize:tt,billboardSize:1*it.billboardSize,simpleShapeParameters:[it.shapeFadeStart,it.shapeFadePower],screenSize:[We.width,We.height],thinningCenterPos:[wt,Ot],thinningShape:[Vt,Ct,Math.pow(10,it.screenThinning.fadePower)],thinningAffectedRatio:it.screenThinning.affectedRatio,thinningParticleOffset:ks,color:[it.color.r,it.color.g,it.color.b,it.color.a],direction:F},{u_modelview:Float32Array.from(Ns.modelview),u_projection:Float32Array.from(Ns.projection),u_time:Ns.time,u_cam_pos:Ns.camPos,u_velocityConeAperture:Ns.velocityConeAperture,u_velocity:Ns.velocity,u_horizontalOscillationRadius:Ns.horizontalOscillationRadius,u_horizontalOscillationRate:Ns.horizontalOscillationRate,u_boxSize:Ns.boxSize,u_billboardSize:Ns.billboardSize,u_simpleShapeParameters:Ns.simpleShapeParameters,u_screenSize:Ns.screenSize,u_thinningCenterPos:Ns.thinningCenterPos,u_thinningShape:Ns.thinningShape,u_thinningAffectedRatio:Ns.thinningAffectedRatio,u_thinningParticleOffset:Ns.thinningParticleOffset,u_particleColor:Ns.color,u_direction:Ns.direction});var Ns;const Gt=Math.round(it.intensity*this.particlesCount),es=o.dy.simpleSegment(0,0,4*Gt,2*Gt);this.particlesVx&&this.particlesIdx&&He.draw(w,Le.TRIANGLES,qr.disabled,La.disabled,Ma.alphaBlended,pa.disabled,ss,"snow_particles",this.particlesVx,this.particlesIdx,es)})(E.boxSize,0,E),this._vignette.draw(w,H)}}const Yn={symbol:function(R,w,E,F,H){if(R.renderPass!=="translucent")return;const Z=La.disabled,X=R.colorModeForRenderPass(),oe=E.layout.get("text-variable-anchor"),xe=E.layout.get("text-size-scale-range"),Ne=o.aC(R.scaleFactor,xe[0],xe[1]);oe&&function(He,tt,dt,it,jt,wt,Ot,Vt){const Ct=tt.transform,ks=jt==="map",ss=wt==="map";for(const Ns of He){const Gt=it.getTile(Ns),es=Gt.getBucket(dt);if(!es||!es.text||!es.text.segments.get().length)continue;const fs=o.bj(es.textSizeData,Ct.zoom,Vt),Ws=im(Ns,es.getProjection(),Ct),As=Ct.calculatePixelsToTileUnitsMatrix(Gt),gn=ld(Ws,Gt.tileID.canonical,ss,ks,Ct,es.getProjection(),As),an=es.hasIconTextFit()&&es.hasIconData();fs&&vc(es,ks,ss,Ot,Ct,gn,Ns,Math.pow(2,Ct.zoom-Gt.tileID.overscaledZ),fs,an)}}(F,R,E,w,E.layout.get("text-rotation-alignment"),E.layout.get("text-pitch-alignment"),H,Ne);const Le=E.paint.get("icon-opacity").constantOr(1)!==0,We=E.paint.get("text-opacity").constantOr(1)!==0;E.layout.get("symbol-sort-key").constantOr(1)!==void 0&&(Le||We)?dm(R,w,E,F,Z,X):(Le&&dm(R,w,E,F,Z,X,{onlyIcons:!0}),We&&dm(R,w,E,F,Z,X,{onlyText:!0})),w.map.showCollisionBoxes&&(br(R,w,E,F,E.paint.get("text-translate"),E.paint.get("text-translate-anchor"),!0),br(R,w,E,F,E.paint.get("icon-translate"),E.paint.get("icon-translate-anchor"),!1))},circle:function(R,w,E,F){if(R.renderPass!=="translucent")return;const H=E.paint.get("circle-opacity"),Z=E.paint.get("circle-stroke-width"),X=E.paint.get("circle-stroke-opacity"),oe=E.layout.get("circle-sort-key").constantOr(1)!==void 0,xe=E.paint.get("circle-emissive-strength");if(H.constantOr(1)===0&&(Z.constantOr(1)===0||X.constantOr(1)===0))return;const Ne=R.context,Le=Ne.gl,We=R.transform,He=!(!R.terrain||!R.terrain.enabled),tt=E.layout.get("circle-elevation-reference"),dt=R.depthModeForSublayer(0,qr.ReadOnly),it=new qr(R.context.gl.LEQUAL,qr.ReadOnly,R.depthRangeFor3D),jt=tt==="none"||He?dt:it,wt=La.disabled,Ot=R.colorModeForDrapableLayerRenderPass(xe),Vt=We.projection.name==="globe",Ct=[o.aH(We.center.lng),o.aL(We.center.lat)],ks=[];for(let Ns=0;NsNs.sortKey-Gt.sortKey);const ss={useDepthForOcclusion:We.depthOcclusionForSymbolsAndCircles};for(const Ns of ks){const{programConfiguration:Gt,program:es,layoutVertexBuffer:fs,dynamicBuffers:Ws,indexBuffer:As,uniformValues:gn,tile:an}=Ns.state,Dn=Ns.segments;R.terrain&&R.terrain.setupElevationDraw(an,es,ss),R.uploadCommonUniforms(Ne,es,an.tileID.toUnwrapped()),es.draw(R,Le.TRIANGLES,jt,wt,Ot,pa.disabled,gn,E.id,fs,As,Dn,E.paint,We.zoom,Gt,Ws)}},heatmap:function(R,w,E,F){if(E.paint.get("heatmap-opacity")!==0)if(R.renderPass==="offscreen"){const H=R.context,Z=H.gl,X=La.disabled,oe=new Ma([Z.ONE,Z.ONE,Z.ONE,Z.ONE],o.aq.transparent,[!0,!0,!0,!0]),xe=R.transform.projection.name==="globe"?.5:.25;E.heatmapFbo=Rm.createWithTexture(H,E.heatmapFbo,R.width*xe,R.height*xe),H.clear({color:o.aq.transparent});const Ne=R.transform,Le=Ne.projection.name==="globe",We=Le?["PROJECTION_GLOBE_VIEW"]:[],He=Le?pa.frontCCW:pa.disabled,tt=[o.aH(Ne.center.lng),o.aL(Ne.center.lat)];for(let dt=0;dt({u_image:0,u_color_ramp:1,u_opacity:We.paint.get("heatmap-opacity")}))(0,Z),Z.id,H.viewportBuffer,H.quadTriangleIndexBuffer,H.viewportSegments,Z.paint,H.transform.zoom)}(R,E))},line:function(R,w,E,F){const H=E.paint.get("line-opacity"),Z=E.paint.get("line-width");if(H.constantOr(1)===0||Z.constantOr(1)===0)return;const X=E.paint.get("line-blend-mode");if(X!=="default"&&R.transform.projection.name!=="globe")return R.terrain&&R.terrain.renderingToTexture?void function(oe,xe,Ne,Le,We){if(oe.renderPass!=="translucent")return;const He=oe.context,tt=He.gl,dt=oe.terrain;if(!dt)return;const it=He.bindFramebuffer.current,jt=oe.emissiveMode==="mrt-fallback";Ne.lineBlendDrapeFbo=Rm.createWithTexture(He,Ne.lineBlendDrapeFbo,dt.drapeBufferSize[0],dt.drapeBufferSize[1],!0),Ne.lineBlendDrapeStencil=Ne.lineBlendDrapeFbo._stencilRbo,jt&&tt.drawBuffers([tt.COLOR_ATTACHMENT0]),He.clear({color:xp[We].clearColor,depth:1,stencil:0});const wt=oe.currentStencilSource,Ot=oe._tileClippingMaskIDs,Vt=oe.nextStencilID;oe.currentStencilSource=void 0,oe._tileClippingMaskIDs={},oe.nextStencilID=1;const Ct=oe._terrain;oe._terrain=null,oe._renderTileClippingMasks(Ne,xe,Le),su(oe,xe,Ne,Le,xp[We].colorMode,!0),oe._terrain=Ct,oe.currentStencilSource=wt,oe._tileClippingMaskIDs=Ot,oe.nextStencilID=Vt,He.bindFramebuffer.set(it),jt&&tt.drawBuffers([tt.COLOR_ATTACHMENT0,tt.COLOR_ATTACHMENT1]);const ks=dt.drapeBufferSize;He.viewport.set([0,0,ks[0],ks[1]]);const ss=Ne.lineBlendDrapeFbo;if(!ss)return;He.activeTexture.set(tt.TEXTURE0),tt.bindTexture(tt.TEXTURE_2D,ss.colorAttachment0.get());const Ns=We==="additive"?1:Ne.paint.get("line-opacity").constantOr(1),Gt=Ne.paint.get("line-emissive-strength").constantOr(0),es=We==="additive"?oe.colorModeForDrapableLayerRenderPass(Gt):xp[We].colorMode;oe.getOrCreateProgram("lineBlendComposite").draw(oe,tt.TRIANGLES,qr.disabled,La.disabled,es,pa.disabled,Dl(0,Ns,xp[We].compositeUniformValue),Ne.id,oe.viewportBuffer,oe.quadTriangleIndexBuffer,oe.viewportSegments,Ne.paint,oe.transform.zoom)}(R,w,E,F,X):R.renderPass==="offscreen"?void function(oe,xe,Ne,Le,We){const He=oe.context,tt=Math.ceil(oe.width),dt=Math.ceil(oe.height);Ne.lineBlendFbo=Rm.createWithTexture(He,Ne.lineBlendFbo,tt,dt,!0),Ne.lineBlendStencil=Ne.lineBlendFbo._stencilRbo,He.clear({color:xp[We].clearColor,depth:1,stencil:0});const it=oe.currentStencilSource,jt=oe._tileClippingMaskIDs,wt=oe.nextStencilID;oe.currentStencilSource=void 0,oe._tileClippingMaskIDs={},oe.nextStencilID=1,oe._renderTileClippingMasks(Ne,xe,Le);const Ot=oe.renderPass;oe.renderPass="translucent",su(oe,xe,Ne,Le,xp[We].colorMode),oe.renderPass=Ot,oe.currentStencilSource=it,oe._tileClippingMaskIDs=jt,oe.nextStencilID=wt,He.viewport.set([0,0,oe.width,oe.height])}(R,w,E,F,X):R.renderPass==="translucent"?void function(oe,xe,Ne){const Le=oe.context,We=Le.gl,He=xe.lineBlendFbo;if(!He)return;Le.activeTexture.set(We.TEXTURE0),We.bindTexture(We.TEXTURE_2D,He.colorAttachment0.get());const tt=Ne==="additive"?1:xe.paint.get("line-opacity").constantOr(1),dt=Ne==="additive"?oe.colorModeForDrapableLayerRenderPass(xe.paint.get("line-emissive-strength").constantOr(0)):xp[Ne].colorMode;oe.getOrCreateProgram("lineBlendComposite").draw(oe,We.TRIANGLES,qr.disabled,La.disabled,dt,pa.disabled,Dl(0,tt,xp[Ne].compositeUniformValue),xe.id,oe.viewportBuffer,oe.quadTriangleIndexBuffer,oe.viewportSegments,xe.paint,oe.transform.zoom)}(R,E,X):void 0;R.renderPass==="translucent"&&su(R,w,E,F)},fill:function(R,w,E,F){const H=E.paint.get("fill-color"),Z=E.paint.get("fill-opacity");if(Z.constantOr(1)===0)return;const X=E.paint.get("fill-emissive-strength"),oe=R.colorModeForDrapableLayerRenderPass(X),xe=E.paint.get("fill-pattern"),Ne=R.opaquePassEnabledForLayer()&&!xe.constantOr(1)&&H.constantOr(o.aq.transparent).a===1&&Z.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 We=!(!R.terrain||!R.terrain.enabled),He={painter:R,sourceCache:w,layer:E,coords:F,colorMode:oe,elevationType:Le,terrainEnabled:We,pass:Ne};if(R.renderPass==="shadow")return void(R.shadowRenderer&&Le==="road"&&!We&&function(dt){const{painter:it,sourceCache:jt,layer:wt,coords:Ot}=dt,Vt=it.context.gl,Ct=dt.painter.shadowRenderer;for(const ks of Ot){const ss=jt.getTile(ks),Ns=ss.getBucket(wt);if(!Ns)continue;const Gt=Ns.elevatedStructures;if(!Gt||!Gt.shadowCasterSegments||Gt.shadowCasterSegments.segments[0].primitiveLength===0)continue;it.prepareDrawTile();const es=Ns.bufferData.programConfigurations.get(wt.id),fs=it.isTileAffectedByFog(ks),Ws=it.getOrCreateProgram("elevatedStructuresDepth",{config:es,overrideFog:fs}),As=Ct.calculateShadowPassMatrixFromTile(ss.tileID.toUnwrapped());it.uploadCommonUniforms(it.context,Ws,ks.toUnwrapped());const gn=bi(As,0);Ws.draw(it,Vt.TRIANGLES,Ct.getShadowPassDepthMode(),La.disabled,Ma.disabled,pa.disabled,gn,wt.id,Gt.vertexBuffer,Gt.indexBuffer,Gt.shadowCasterSegments,wt.paint,it.transform.zoom,es)}}(He));const tt=R.emissiveMode==="mrt-fallback";if(Le!=="offset"){if(Ev(He,!1,tt),Le==="road"){const dt=!We&&R.renderPass==="translucent";dt&&$1(R,w,E,F,"geometry"),Ev(He,!0,tt,La.disabled),dt&&function(it){const{painter:jt,sourceCache:wt,layer:Ot,coords:Vt,colorMode:Ct}=it,ks=jt.context.gl,ss=it.painter.shadowRenderer,Ns=!!ss&&ss.enabled,Gt=new qr(jt.context.gl.LEQUAL,qr.ReadOnly,jt.depthRangeFor3D);let es=[0,0,0];if(Ns){const Ws=jt.style.directionalLight,As=jt.style.ambientLight;Ws&&As&&(es=xh(jt.style,Ws,As))}const fs=Ws=>{for(const As of Vt){const gn=wt.getTile(As),an=gn.getBucket(Ot);if(!an)continue;const Dn=an.elevatedStructures;if(!Dn)continue;let Gn,en;if(Ws?(Gn=Dn.renderableBridgeSegments,en=Dn.bridgeProgramConfigurations.get(Ot.id)):(Gn=Dn.renderableTunnelSegments,en=Dn.tunnelProgramConfigurations.get(Ot.id)),!Gn||Gn.segments[0].primitiveLength===0)continue;en.updatePaintBuffers(),jt.prepareDrawTile();const Ms=jt.isTileAffectedByFog(As),mn=[];Ns&&mn.push("RENDER_SHADOWS","NORMAL_OFFSET");const vn=jt.getOrCreateProgram("elevatedStructures",{config:en,overrideFog:Ms,defines:mn}),kn=jt.translatePosMatrix(As.projMatrix,gn,Ot.paint.get("fill-translate"),Ot.paint.get("fill-translate-anchor"));Ns&&ss.setupShadows(gn.tileID.toUnwrapped(),vn,"vector-tile");const _r=sl(kn,es);jt.uploadCommonUniforms(jt.context,vn,As.toUnwrapped()),vn.draw(jt,ks.TRIANGLES,Gt,La.disabled,Ct,pa.backCCW,_r,Ot.id,Dn.vertexBuffer,Dn.indexBuffer,Gn,Ot.paint,jt.transform.zoom,en,[Dn.vertexBufferNormal])}};fs(!0),fs(!1)}(He)}}else Ev(He,!1,tt,R.stencilModeFor3D())},"fill-extrusion":function(R,w,E,F){const H=E.paint.get("fill-extrusion-opacity"),Z=R.context,X=Z.gl,oe=R.terrain,xe=oe&&oe.renderingToTexture;if(H===0)return;const Ne=R.emissiveMode==="mrt-fallback",Le=R.conflationActive&&R.style.isLayerClipped(E,w.getSource()),We=R.style.order.indexOf(E.fqid);if(Le&&function(He,tt,dt,it,jt){for(const wt of it){const Ot=tt.getTile(wt).getBucket(dt);Ot&&(Ot.updateReplacement(wt,He.replacementSource,jt),Ot.uploadCentroid(He.context))}}(R,w,E,F,We),oe||Le)for(const He of F){const tt=w.getTile(He).getBucket(E);tt&&q0(R.context,w,He,tt,E,oe,Le)}if(R.renderPass==="shadow"&&R.shadowRenderer){if(oe&&H<.65&&E._transitionablePaint._values["fill-extrusion-opacity"].value.expression instanceof o.af)return;const He=R.shadowRenderer.getShadowPassDepthMode();Om(R,w,E,F,He,La.disabled,Ma.disabled,Le)}else if(R.renderPass==="translucent"){const He=!E.paint.get("fill-extrusion-pattern").constantOr(1),tt=E.paint.get("fill-extrusion-color").constantOr(o.aq.white);if(!xe&&tt.a!==0){const dt=new qr(R.context.gl.LEQUAL,qr.ReadWrite,R.depthRangeFor3D);H===1&&He?Om(R,w,E,F,dt,La.disabled,Ma.unblended,Le):(Om(R,w,E,F,dt,La.disabled,Ma.disabled,Le),Om(R,w,E,F,dt,R.stencilModeFor3D(),R.colorModeForRenderPass(),Le),R.resetStencilClippingMasks())}if(R.style.enable3dLights()&&He&&(!oe&&R.transform.projection.name!=="globe"||xe)){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"),Ot=E.paint.get("fill-extrusion-flood-light-color-use-theme").constantOr("default")==="none",Vt=E.paint.get("fill-extrusion-flood-light-color").toNonPremultipliedRenderColor(Ot?null:E.lut).toArray01().slice(0,3),Ct=it>0&&jt>0,ks=wt>0,ss=(es,fs,Ws)=>(1-Ws)*es+Ws*fs,Ns=new sf;Ns.translate=E.paint.get("fill-extrusion-translate"),Ns.translateAnchor=E.paint.get("fill-extrusion-translate-anchor"),Ns.edgeRadius=E.layout.get("fill-extrusion-edge-radius"),Ns.cutoffFadeRange=E.paint.get("fill-extrusion-cutoff-fade-range");const Gt=es=>{const fs=R.depthModeForSublayer(1,qr.ReadOnly,X.LEQUAL,!0),Ws=E.paint.get(es?"fill-extrusion-ambient-occlusion-ground-attenuation":"fill-extrusion-flood-light-ground-attenuation"),As=ss(.1,3,Ws),gn=R._showOverdrawInspector;if(!gn){const an=new La({func:X.ALWAYS,mask:255},255,255,X.KEEP,X.KEEP,X.REPLACE),Dn=new Ma([X.ONE,X.ONE,X.ONE,X.ONE],o.aq.transparent,[!1,!1,!1,!0],X.MIN);Hg(Ns,R,w,E,F,fs,an,Dn,pa.disabled,es,"sdf",dt,it,jt,wt,Vt,As,Le,!1)}{const an=gn?La.disabled:new La({func:X.EQUAL,mask:255},255,255,X.KEEP,X.DECR,X.DECR),Dn=gn?R.colorModeForRenderPass():new Ma([X.ONE_MINUS_DST_ALPHA,X.DST_ALPHA,X.ONE,X.ONE],o.aq.transparent,[!0,!0,!0,!0]);Hg(Ns,R,w,E,F,fs,an,Dn,pa.disabled,es,"color",dt,it,jt,wt,Vt,As,Le,!1)}};if(xe){const es=()=>{const Ws=oe.drapeBufferSize[0],As=oe.drapeBufferSize[1];let gn=oe.framebufferCopyTexture;return gn&&(!gn||gn.size[0]===Ws&&gn.size[1]===As)||(gn&&gn.destroy(),gn=oe.framebufferCopyTexture=new o.T(Z,new o.q({width:Ws,height:As}),X.RGBA8)),gn.bind(X.LINEAR,X.CLAMP_TO_EDGE),X.copyTexSubImage2D(X.TEXTURE_2D,0,0,0,0,0,Ws,As),gn},fs=(Ws,As,gn)=>{const an=R.depthModeForSublayer(1,qr.ReadOnly,X.LEQUAL,!1),Dn=E.paint.get(Ws?"fill-extrusion-ambient-occlusion-ground-attenuation":"fill-extrusion-flood-light-ground-attenuation"),Gn=ss(.1,3,Dn);{const en=new Ma([X.ONE,X.ONE,X.ONE,X.ONE],o.aq.transparent,[!1,!1,!1,!0]);Hg(Ns,R,w,E,F,an,La.disabled,en,pa.disabled,Ws,"clear",dt,it,jt,wt,Vt,Gn,Le,As)}{const en=new La({func:X.ALWAYS,mask:255},255,255,X.KEEP,X.KEEP,X.REPLACE),Ms=new Ma([X.ONE,X.ONE,X.ONE,X.ONE],o.aq.transparent,[!1,!1,!1,!0],X.MIN);Hg(Ns,R,w,E,F,an,en,Ms,pa.disabled,Ws,"sdf",dt,it,jt,wt,Vt,Gn,Le,As)}Ne&&!Ws&&(gn=es());{const en=Ws?X.ZERO:X.ONE_MINUS_DST_ALPHA,Ms=new La({func:X.EQUAL,mask:255},255,255,X.KEEP,X.DECR,X.DECR),mn=new Ma([en,X.DST_ALPHA,X.ONE_MINUS_DST_ALPHA,X.ZERO],o.aq.transparent,[!0,!0,!0,!0]);Hg(Ns,R,w,E,F,an,Ms,mn,pa.disabled,Ws,"color",dt,it,jt,wt,Vt,Gn,Le,As)}if(!Ne||Ws){const en=new Ma([X.ONE,X.ONE,X.ONE,Ws?X.ZERO:X.ONE],o.aq.transparent,[!1,!1,!1,!0],Ws?X.FUNC_ADD:X.MAX);Hg(Ns,R,w,E,F,an,La.disabled,en,pa.disabled,Ws,"clear",dt,it,jt,wt,Vt,Gn,Le,As,gn)}else{X.drawBuffers([X.NONE,X.COLOR_ATTACHMENT1]);const en=new La({func:X.EQUAL,mask:255},254,255,X.KEEP,X.DECR,X.DECR),Ms=new Ma([X.ONE,X.ONE,X.ONE,X.ONE],o.aq.transparent,[!0,!1,!1,!1],X.MAX);Hg(Ns,R,w,E,F,an,en,Ms,pa.disabled,Ws,"emissive",dt,it,jt,wt,Vt,Gn,Le,As,gn),X.drawBuffers([X.COLOR_ATTACHMENT0])}};if(Ct||ks){let Ws;R.prepareDrawTile(),Ne&&!Ct||(Ws=es()),Ct&&fs(!0,!1,Ws),ks&&fs(!1,!0,Ws)}}else Ct&&Gt(!0),ks&&Gt(!1),(Ct||ks)&&R.resetStencilClippingMasks()}}},building:function(R,w,E,F){R.currentLayer0&&Z>0,Ne=!0;const Le=E.paint.get("building-vertical-scale");if(Le<=0)return;R.shadowRenderer||(Ne=!1);const We=R.conflationActive&&R.style.isLayerClipped(E,w.getSource()),He=R.style.order.indexOf(E.fqid);if(function(tt,dt,it,jt,wt,Ot){for(const Vt of Ot){const Ct=dt.getTile(Vt).getBucket(it);Ct&&(wt&&Ct.updateReplacement(Vt,tt.replacementSource,jt),Ct.uploadUpdatedIndexBuffer(tt.context))}}(R,w,E,He,We,F),function(tt,dt,it,jt){for(const wt of jt){const Ot=dt.getTile(wt).getBucket(it);Ot&&Ot.needsEvaluation()&&Ot.uploadUpdatedColorBuffer(tt.context)}}(R,w,E,F),E.resetLayerRenderingStats(R),R.shadowRenderer&&(R.shadowRenderer.useNormalOffset=!0),R.renderPass==="shadow"&&R.shadowRenderer){const tt=[],dt=R.shadowRenderer.getShadowPassDepthMode();Ry({painter:R,source:w,layer:E,coords:F,defines:tt,blendMode:Ma.disabled,depthMode:dt,opacity:oe,verticalScale:Le,facadeEmissiveChance:0,facadeAOIntensity:0,floodLightIntensity:0,floodLightColor:[0,0,0]})}else if(R.renderPass==="translucent"){let tt=["HAS_ATTRIBUTE_a_part_color_emissive","LIGHTING_3D_MODE"];Ne&&(tt=tt.concat("RENDER_SHADOWS")),R.shadowRenderer&&R.shadowRenderer.useNormalOffset&&(tt=tt.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",Ot=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,ks=new qr(R.context.gl.LEQUAL,qr.ReadWrite,R.depthRangeFor3D);oe<1&&Ry({painter:R,source:w,layer:E,coords:F,defines:tt,blendMode:Ma.disabled,depthMode:ks,opacity:oe,verticalScale:Le,facadeEmissiveChance:dt,facadeAOIntensity:it,floodLightIntensity:jt,floodLightColor:Ot,depthOnly:!0});const ss=R.colorModeForRenderPass();Ry({painter:R,source:w,layer:E,coords:F,defines:tt,blendMode:ss,depthMode:ks,opacity:oe,verticalScale:Le,facadeEmissiveChance:dt,facadeAOIntensity:it,floodLightIntensity:jt,floodLightColor:Ot});const Ns=E.paint.get("building-front-cutoff");Uw(R.transform.pitch,Ns,!!R.terrain),xe&&gx(R,w,E,F,!0,oe,H,Z,jt,Ot,X,We),Ct&&gx(R,w,E,F,!1,oe,H,Z,jt,Ot,Vt,We)}else if(R.renderPass==="light-beam"){const tt=["HAS_ATTRIBUTE_a_part_color_emissive","HAS_ATTRIBUTE_a_bloom_attenuation"],dt=new qr(R.context.gl.LEQUAL,qr.ReadOnly,R.depthRangeFor3D);Ry({painter:R,source:w,layer:E,coords:F,defines:tt,blendMode:Ma.alphaBlended,depthMode:dt,opacity:oe,verticalScale:Le,facadeEmissiveChance:0,facadeAOIntensity:0,floodLightIntensity:0,floodLightColor:[0,0,0]})}R.shadowRenderer&&(R.shadowRenderer.useNormalOffset=!1),R.resetStencilClippingMasks()},hillshade:function(R,w,E,F){if(R.renderPass!=="offscreen"&&R.renderPass!=="translucent"||R.style.disableElevatedTerrain)return;const H=R.context,Z=R.terrain&&R.terrain.renderingToTexture,[X,oe]=R.renderPass!=="translucent"||Z?[{},F]:R.stencilConfigForOverlap(F);for(const xe of oe){const Ne=w.getTile(xe);if(Ne.needsHillshadePrepare&&R.renderPass==="offscreen")MC(R,Ne,E);else if(R.renderPass==="translucent"){const Le=R.depthModeForSublayer(0,qr.ReadOnly),We=E.paint.get("hillshade-emissive-strength"),He=R.colorModeForDrapableLayerRenderPass(We),tt=Z&&R.terrain?R.terrain.stencilModeForRTTOverlap(xe):X[xe.overscaledZ];rM(R,xe,Ne,E,Le,tt,He)}}H.viewport.set([0,0,R.width,R.height]),R.resetStencilClippingMasks()},raster:function(R,w,E,F,H,Z){if(R.renderPass!=="translucent")return;const X=E.paint.get("raster-opacity");if(X===0)return;const oe=R.transform.projection.name==="globe",xe=E.paint.get("raster-elevation")!==0,Ne=xe&&oe,Le=R.terrain&&R.terrain.exaggeration()>0&&xe&&E.paint.get("raster-elevation-reference")==="ground",We=!oe&&Le;if(R.renderElevatedRasterBackface&&!Ne)return;const He=R.context,tt=He.gl,dt=w.getSource(),it=function(es,fs,Ws,As,gn){const an=fs.paint.get("raster-color"),Dn=es.type==="raster-array",Gn=[],en=fs.paint.get("raster-resampling"),Ms=fs.paint.get("raster-color-mix");let mn=fs.paint.get("raster-color-range");const vn=[Ms[0],Ms[1],Ms[2],0],kn=Ms[3];let _r=en==="nearest"?As.NEAREST:As.LINEAR;if(Dn&&(Gn.push("RASTER_ARRAY"),an||Gn.push("RASTER_COLOR"),en==="linear"&&Gn.push("RASTER_ARRAY_LINEAR"),_r=As.NEAREST,!mn&&es.rasterLayers)){const cr=es.rasterLayers.find(({id:dr})=>dr===fs.sourceLayer);cr&&cr.fields&&cr.fields.range&&(mn=cr.fields.range)}if(mn=mn||[0,1],an){Gn.push("RASTER_COLOR"),Ws.activeTexture.set(As.TEXTURE2),fs.updateColorRamp(mn);let cr=fs.colorRampTexture;cr||(cr=fs.colorRampTexture=new o.T(Ws,fs.colorRamp,As.RGBA8)),cr.bind(_r,As.CLAMP_TO_EDGE)}return gn&&Gn.push("USE_MRT1"),{mix:vn,range:mn,offset:kn,defines:Gn,resampling:_r}}(dt,E,He,tt,R.terrain&&R.terrain.renderingToTexture&&R.emissiveMode==="mrt-fallback");if(dt instanceof o.aV&&!F.length&&!oe)return;const jt=E.paint.get("raster-emissive-strength"),wt=R.colorModeForDrapableLayerRenderPass(jt),Ot=R.terrain&&R.terrain.renderingToTexture,Vt=!R.options.moving,Ct=E.paint.get("raster-resampling")==="nearest"?tt.NEAREST:tt.LINEAR;if(dt instanceof o.aV&&!F.length&&(dt.onNorthPole||dt.onSouthPole)){const es=xe?R.stencilModeFor3D():La.disabled;return void U1(!!dt.onNorthPole,null,R,w,E,jt,it,pa.disabled,es)}if(!F.length)return;const[ks,ss]=dt instanceof o.aV||Ot?[{},F]:R.stencilConfigForOverlap(F),Ns=ss[ss.length-1].overscaledZ;Ne&&it.defines.push("PROJECTION_GLOBE_VIEW"),xe&&it.defines.push("RENDER_CUTOFF","ELEVATED"),Le&&it.defines.push("ELEVATION_REFERENCE_GROUND");const Gt=(es,fs,Ws)=>{for(const As of es){const gn=As.toUnwrapped(),an=w.getTile(As);if(Ot&&(!an||!an.hasData()))continue;He.activeTexture.set(tt.TEXTURE0);const Dn=Hw(an,dt,E,it);if(!Dn||!Dn.texture)continue;const{texture:Gn,mix:en,offset:Ms,tileSize:mn,buffer:vn}=Dn;let kn,_r;Ot?(kn=qr.disabled,_r=As.projMatrix):xe?(kn=new qr(tt.LEQUAL,qr.ReadWrite,R.depthRangeFor3D),_r=oe?Float32Array.from(R.transform.expandedFarZProjMatrix):R.transform.calculateProjMatrix(gn,Vt)):(kn=R.depthModeForSublayer(As.overscaledZ-Ns,X===1?qr.ReadWrite:qr.ReadOnly,tt.LESS),_r=R.transform.calculateProjMatrix(gn,Vt));const cr=R.terrain&&Ot?R.terrain.stencilModeForRTTOverlap(As):ks[As.overscaledZ],dr=Z?0:E.paint.get("raster-fade-duration");an.registerFadeDuration(dr);const Bn=w.findLoadedParent(As,0),ra=bt(an,Bn,w,R.transform,dr);let wa,Yr;!ra.isFading&&an.refreshedUponExpiration&&(an.refreshedUponExpiration=!1),R.terrain&&R.terrain.prepareDrawTile(),He.activeTexture.set(tt.TEXTURE0),Gn.bind(Ct,tt.CLAMP_TO_EDGE),He.activeTexture.set(tt.TEXTURE1),Bn?(Bn.texture&&Bn.texture.bind(Ct,tt.CLAMP_TO_EDGE),wa=Math.pow(2,Bn.tileID.overscaledZ-an.tileID.overscaledZ),Yr=[an.tileID.canonical.x*wa%1,an.tileID.canonical.y*wa%1]):Gn.bind(Ct,tt.CLAMP_TO_EDGE),"useMipmap"in Gn&&He.extTextureFilterAnisotropic&&R.transform.pitch>20&&tt.texParameterf(tt.TEXTURE_2D,He.extTextureFilterAnisotropic.TEXTURE_MAX_ANISOTROPY_EXT,He.extTextureFilterAnisotropicMax);const na=R.transform;let Xa;const pi=xe?q1(na):[0,0,0,0];let oi,Bi,Oa,$i,li,Fo=0;if(Ne&&dt instanceof o.aV&&dt.coordinates.length>3)oi=Float32Array.from(o.du(o.dv(new o.cn(0,0,0)))),Bi=Float32Array.from(na.globeMatrix),Oa=Float32Array.from(o.dq(na)),$i=[o.aH(na.center.lng),o.aL(na.center.lat)],Xa=dt.elevatedGlobePerspectiveTransform,li=dt.elevatedGlobeGridMatrix||new Float32Array(9);else if(Ne){const Zo=o.dr(As.canonical);Fo=o.ds(Zo.getCenter().lat),oi=Float32Array.from(o.du(o.dv(As.canonical))),Bi=Float32Array.from(na.globeMatrix),Oa=Float32Array.from(o.dq(na)),$i=[o.aH(na.center.lng),o.aL(na.center.lat)],Xa=[0,0],li=Float32Array.from(o.dt(As.canonical,Zo,Fo,na.worldSize/na._pixelsPerMercatorPixel))}else Xa=dt instanceof o.aV?dt.perspectiveTransform:[0,0],oi=new Float32Array(16),Bi=new Float32Array(9),Oa=new Float32Array(16),$i=[0,0],li=new Float32Array(9);const Rl=Xd(R,_r,oi,Bi,Oa,li,Yr||[0,0],o.al(R.transform.zoom),$i,pi,wa||1,ra,E,Xa,xe?E.paint.get("raster-elevation"):0,2,en,Ms,it.range,mn,vn,jt),td=R.isTileAffectedByFog(As),nc=R.getOrCreateProgram("raster",{defines:it.defines,overrideFog:td});if(R.uploadCommonUniforms(He,nc,gn),dt instanceof o.aV){const Zo=dt.elevatedGlobeVertexBuffer,Pi=dt.elevatedGlobeIndexBuffer;if(Ot||!oe)dt.boundsBuffer&&dt.boundsSegments&&nc.draw(R,tt.TRIANGLES,kn,La.disabled,wt,pa.disabled,Rl,E.id,dt.boundsBuffer,R.quadTriangleIndexBuffer,dt.boundsSegments);else if(Zo&&Pi){const Ii=na.zoom<=o.cJ?dt.elevatedGlobeSegments:dt.getSegmentsForLongitude(na.center.lng);Ii&&nc.draw(R,tt.TRIANGLES,kn,La.disabled,wt,fs,Rl,E.id,Zo,Pi,Ii)}}else if(Ne){kn=new qr(tt.LEQUAL,qr.ReadOnly,R.depthRangeFor3D);const Zo=R.globeSharedBuffers;if(Zo){Le&&(R.terrain.setupElevationDraw(an,nc),R.uploadCommonUniforms(He,nc,an.tileID.toUnwrapped()));const[Pi,Ii,rc]=Zo.getGridBuffers(Fo,!1),hd=nc.getAttributeLocation(tt,"a_texture_pos");hd!==-1&&tt.vertexAttribI4ui(hd,0,0,0,0),nc.draw(R,tt.TRIANGLES,kn,Ws||cr,R.colorModeForRenderPass(),fs,Rl,E.id,Pi,Ii,rc)}}else if(We)kn=new qr(tt.LEQUAL,qr.ReadWrite,R.depthRangeFor3D),R.terrain.setupElevationDraw(an,nc),R.uploadCommonUniforms(He,nc,an.tileID.toUnwrapped()),na.pitch>20&&nc.draw(R,tt.TRIANGLES,kn,La.disabled,Ma.disabled,pa.frontCCW,Rl,E.id,R.terrain.gridBuffer,R.terrain.gridIndexBuffer,R.terrain.gridSegments),nc.draw(R,tt.TRIANGLES,kn,cr,wt,pa.backCCW,Rl,E.id,R.terrain.gridBuffer,R.terrain.gridIndexBuffer,R.terrain.gridSegments);else{const{tileBoundsBuffer:Zo,tileBoundsIndexBuffer:Pi,tileBoundsSegments:Ii}=R.getTileBoundsBuffers(an);nc.draw(R,tt.TRIANGLES,kn,cr,wt,pa.disabled,Rl,E.id,Zo,Pi,Ii)}}if(!(dt instanceof o.aV)&&Ne)for(const As of es){const gn=As.canonical.y===(1<o.d$[vn](gn));en.push(gn);const Ms=gn.canonical.x,mn=gn.canonical.y;for(const vn of en){const kn=Ct.getTile(fs?vn.wrapped():vn);if(!kn)continue;const _r=kn.rasterParticleState;if(!_r)continue;const cr=vn.canonical.x+(1<Ns.tileID)),tt&&(Ne.activeTexture.set(Le.TEXTURE0),R.imageManager.bind(R.context,E.scope));const ss=[];if(R.terrain&&R.terrain.renderingToTexture&&R.emissiveMode==="mrt-fallback"&&ss.push("USE_MRT1"),xe){const Ns=R.getOrCreateProgram(Vt,{overrideFog:!1,overrideRtt:!0,defines:ss}),Gt=new Float32Array(o.b9([])),es=new o.aR(0,0,0,0,0),fs=tt?Vc(Gt,oe,X,R,0,E.scope,dt,xe,{tileID:es,tileSize:He}):Im(Gt,oe,X,H.toPremultipliedRenderColor(Z?null:E.lut));return void Ns.draw(R,Le.TRIANGLES,wt,jt,Ot,pa.disabled,fs,E.id,R.viewportBuffer,R.quadTriangleIndexBuffer,R.viewportSegments)}for(const Ns of ks){const Gt=R.isTileAffectedByFog(Ns),es=R.getOrCreateProgram(Vt,{overrideFog:Gt,defines:ss}),fs=Ns.toUnwrapped(),Ws=F?Ns.projMatrix:R.transform.calculateProjMatrix(fs);R.prepareDrawTile();const As=w?w.getTile(Ns):Ct?Ct[Ns.key]:new o.b0(Ns,He,We.zoom,R),gn=tt?Vc(Ws,oe,X,R,0,E.scope,dt,xe,{tileID:Ns,tileSize:He}):Im(Ws,oe,X,H.toPremultipliedRenderColor(Z?null:E.lut));R.uploadCommonUniforms(Ne,es,fs);const{tileBoundsBuffer:an,tileBoundsIndexBuffer:Dn,tileBoundsSegments:Gn}=R.getTileBoundsBuffers(As);es.draw(R,Le.TRIANGLES,wt,jt,Ot,pa.disabled,gn,E.id,an,Dn,Gn)}},sky:function(R,w,E){const F=R._atmosphere?o.al(R.transform.zoom):1,H=E.paint.get("sky-opacity")*F;if(H===0)return;const Z=R.context,X=E.paint.get("sky-type"),oe=new qr(Z.gl.LEQUAL,qr.ReadOnly,[0,1]),xe=R.frameCounter/1e3%1;X==="atmosphere"?R.renderPass==="offscreen"?E.needsSkyboxCapture(R)&&(function(Ne,Le){const We=Ne.context,He=We.gl;let tt=Le.skyboxFbo;if(!tt){tt=Le.skyboxFbo=We.createFramebuffer(32,32,1,null),Le.skyboxGeometry=new Dd(We),Le.skyboxTexture=We.gl.createTexture(),He.bindTexture(He.TEXTURE_CUBE_MAP,Le.skyboxTexture),He.texParameteri(He.TEXTURE_CUBE_MAP,He.TEXTURE_WRAP_S,He.CLAMP_TO_EDGE),He.texParameteri(He.TEXTURE_CUBE_MAP,He.TEXTURE_WRAP_T,He.CLAMP_TO_EDGE),He.texParameteri(He.TEXTURE_CUBE_MAP,He.TEXTURE_MIN_FILTER,He.LINEAR),He.texParameteri(He.TEXTURE_CUBE_MAP,He.TEXTURE_MAG_FILTER,He.LINEAR);for(let wt=0;wt<6;++wt)He.texImage2D(He.TEXTURE_CUBE_MAP_POSITIVE_X+wt,0,He.RGBA,32,32,0,He.RGBA,He.UNSIGNED_BYTE,null)}We.bindFramebuffer.set(tt.framebuffer),We.viewport.set([0,0,32,32]);const dt=Le.getCenter(Ne,!0),it=Ne.getOrCreateProgram("skyboxCapture"),jt=new Float64Array(16);o.b9(jt),o.ef(jt,jt,.5*-Math.PI),rf(Ne,Le,it,jt,dt,0),o.b9(jt),o.ef(jt,jt,.5*Math.PI),rf(Ne,Le,it,jt,dt,1),o.b9(jt),o.cE(jt,jt,.5*-Math.PI),rf(Ne,Le,it,jt,dt,2),o.b9(jt),o.cE(jt,jt,.5*Math.PI),rf(Ne,Le,it,jt,dt,3),o.b9(jt),rf(Ne,Le,it,jt,dt,4),o.b9(jt),o.ef(jt,jt,Math.PI),rf(Ne,Le,it,jt,dt,5),We.viewport.set([0,0,Ne.width,Ne.height])}(R,E),E.markSkyboxValid(R)):R.renderPass==="sky"&&function(Ne,Le,We,He,tt){const dt=Ne.context,it=dt.gl,jt=Ne.transform,wt=Ne.getOrCreateProgram("skybox");dt.activeTexture.set(it.TEXTURE0),it.bindTexture(it.TEXTURE_CUBE_MAP,Le.skyboxTexture);const Ot=((Vt,Ct,ks,ss,Ns)=>({u_matrix:Vt,u_sun_direction:Ct,u_cubemap:0,u_opacity:ss,u_temporal_offset:Ns}))(jt.skyboxMatrix,Le.getCenter(Ne,!1),0,He,tt);Ne.uploadCommonUniforms(dt,wt),wt.draw(Ne,it.TRIANGLES,We,La.disabled,Ne.colorModeForRenderPass(),pa.backCW,Ot,"skybox",Le.skyboxGeometry.vertexBuffer,Le.skyboxGeometry.indexBuffer,Le.skyboxGeometry.segment)}(R,E,oe,H,xe):X==="gradient"&&R.renderPass==="sky"&&function(Ne,Le,We,He,tt){const dt=Ne.context,it=dt.gl,jt=Ne.transform,wt=Ne.getOrCreateProgram("skyboxGradient");Le.skyboxGeometry||(Le.skyboxGeometry=new Dd(dt)),dt.activeTexture.set(it.TEXTURE0);let Ot=Le.colorRampTexture;Ot||(Ot=Le.colorRampTexture=new o.T(dt,Le.colorRamp,it.RGBA8)),Ot.bind(it.LINEAR,it.CLAMP_TO_EDGE);const Vt=((Ct,ks,ss,Ns,Gt)=>({u_matrix:Ct,u_color_ramp:0,u_center_direction:ks,u_radius:o.ap(ss),u_opacity:Ns,u_temporal_offset:Gt}))(jt.skyboxMatrix,Le.getCenter(Ne,!1),Le.paint.get("sky-gradient-radius"),He,tt);Ne.uploadCommonUniforms(dt,wt),wt.draw(Ne,it.TRIANGLES,We,La.disabled,Ne.colorModeForRenderPass(),pa.backCW,Vt,"skyboxGradient",Le.skyboxGeometry.vertexBuffer,Le.skyboxGeometry.indexBuffer,Le.skyboxGeometry.segment)}(R,E,oe,H,xe)},custom:function(R,w,E,F){const H=R.context,Z=E.implementation;if(!R.transform.projection.unsupportedLayers||!R.transform.projection.unsupportedLayers.includes("custom")||R.terrain&&(R.terrain.renderingToTexture||R.renderPass==="offscreen")&&E.isDraped(w)){if(R.renderPass==="offscreen"){const X=Z.prerender;if(X){if(R.setCustomLayerDefaults(),H.setColorMode(R.colorModeForRenderPass()),R.transform.projection.name==="globe"){const oe=R.transform.pointMerc;X.call(Z,H.gl,R.transform.customLayerMatrix(),R.transform.getProjection(),R.transform.globeToMercatorMatrix(),o.al(R.transform.zoom),[oe.x,oe.y],R.transform.pixelsPerMeterRatio)}else X.call(Z,H.gl,R.transform.customLayerMatrix());H.setDirty(),R.setBaseState()}}else if(R.renderPass==="translucent"){if(R.terrain&&R.terrain.renderingToTexture){const oe=Z.renderToTile;if(oe){const xe=F[0].canonical,Ne={x:xe.x+F[0].wrap*(Z.wrapTileId?0:1<{Ne&&(Ne.useNormalOffset=!0,Le||(Ne.enabled=!0))},He=w.getSource();if(R.renderPass==="light-beam"&&He.type!=="batched-model")return;if(He.type==="vector"||He.type==="geojson")return function(Ct,ks,ss,Ns,Gt){const es=Ct.transform,fs=es.projection.name==="globe",Ws=es.getFreeCameraOptions().position;if(!Ct.modelManager)return;const As=Ct.modelManager;ss.modelManager=As;const gn=Ct.shadowRenderer;if(!ss._unevaluatedLayout._values.hasOwnProperty("model-id"))return;const an=ss._unevaluatedLayout._values["model-id"],Dn=Object.assign({},ss.layout.get("model-id").parameters),Gn=Ct.style.order.indexOf(ss.fqid),en=ss.paint.get("model-opacity").constantOr(1);for(const Ms of Ns){const mn=ks.getTile(Ms).getBucket(ss);if(!mn||mn.projection.name!==es.projection.name)continue;const vn=mn.getModelUris();if(vn&&!mn.modelsRequested&&(As.addModelsFromBucket(vn,Gt),mn.modelsRequested=!0),fs)Dn.zoom=Ms.overscaledZ;else{const Yr=G0(Ms,es);Dn.zoom=Yr}const kn=an.possiblyEvaluate(Dn);if(ir(Ct,mn,Ms),ar.shadowUniformsInitialized=!1,ar.useSingleShadowCascade=!!gn&&gn.getMaxCascadeForTile(Ms.toUnwrapped())===0,Ct.renderPass==="shadow"&&gn){if(Ct.currentShadowCascade===1&&mn.isInsideFirstShadowMapFrustum)continue;const Yr=es.calculatePosMatrix(Ms.toUnwrapped(),es.worldSize);if(ar.tileMatrix.set(Yr),ar.shadowTileMatrix=Float32Array.from(gn.calculateShadowPassMatrixFromMatrix(Yr)),ar.aabb.min=[0,0,0],ar.aabb.max[0]=ar.aabb.max[1]=o.an,ar.aabb.max[2]=0,n4(mn,ar,Ct,ss.scope))continue}const _r=1<0&&Ct.style.isLayerClipped(ss,ks.getSource())&&mn.updateReplacement(Ms,Ct.replacementSource,Gn,ss.scope)&&(mn.uploaded=!1,mn.upload(Ct.context));let dr=0;const Bn=new Array,ra=new Array,wa=new Array;for(let Yr in mn.instancesPerModel){const na=mn.instancesPerModel[Yr];na.features.length>0&&!fs&&(Yr=kn.evaluate(na.features[0].feature,{}));const Xa=As.getModel(Yr,Gt);if(Xa||As.hasURLBeenRequested(Yr)||mn.modelUris.includes(Yr)||(mn.modelUris.push(Yr),mn.modelsRequested=!1),Xa&&Xa.uploaded)if(fs){const pi=o.bJ([],[Ws.x,Ws.y,Ws.z],Ct.transform.worldSize);o.eo(pi,pi);for(let oi=0;oi0&&$i.elevationUpdate(Yr.terrain,oi,Oa,Xa.source),$i.needsReEvaluation(Yr,Bi,Xa)&&$i.evaluate(Xa))}})(Ct,ks,ss,Ns),function(){const Yr=new Map;let na,Xa,pi;Bn?(na=Ns.length-1,Xa=-1,pi=-1):(na=0,Xa=Ns.length,pi=1);const oi=new Float64Array(16),Bi=o.ce(),Oa=new o.P(0,0);for(let $i=na;$i!==Xa;$i+=pi){const li=Ns[$i],Fo=ks.getTile(li).getBucket(ss);if(!Fo||!Fo.uploaded)continue;let Rl=!1;Ws&&(Rl=Ws.getMaxCascadeForTile(li.toUnwrapped())===0);const td=es.calculatePosMatrix(li.toUnwrapped(),es.worldSize),nc=Fo.modelTraits;!_r&&Bn&&(o.b7(oi,td),o.ah(Bi,gn,oi),Oa.x=Bi[0],Oa.y=Bi[1]);const Zo=[];Fo.setFilter(ss.filter);for(const Pi of Fo.getNodesInfo()){if(Pi.hiddenByReplacement||!Pi.node.meshes)continue;const Ii=Pi.node;let rc=0;Ct.terrain&&Ii.elevation&&(rc=Ii.elevation*Ct.terrain.exaggeration());const hd=(()=>{const gp=Pi.aabb;return kn.min=[...gp.min],kn.max=[...gp.max],kn.min[2]+=rc,kn.max[2]+=rc,o.ah(kn.min,kn.min,td),o.ah(kn.max,kn.max,td),kn})(),Xo=Pi.evaluatedScale;if(Xo[0]<=1&&Xo[1]<=1&&Xo[2]<=1&&hd.intersects(cr)===0)continue;if(!_r&&Bn){const gp=.16666666666666666;Pi.cameraCollisionOpacity=gn[0]>hd.min[0]&&gn[0]hd.min[1]&&gn[1]!Bn||Pi.opacity===1&&Ii.opacity===1?Pi.depthIi.depth?-1:1);for(const Pi of Zo){const Ii=Pi.nodeInfo,rc=Ii.node;if(Ct._debugParams.show3DModelFootprints&&rc.footprint){const ro=rc.id||rc.name||"footprint";Yr.has(ro)||Yr.set(ro,{node:rc,mvp:Pi.wvpForTile})}let hd=o.aD([],en,Pi.tileModelMatrix);o.aD(hd,Dn,hd);const Xo=o.b7([],hd);o.e6(Xo,Xo),o.cC(Xo,Xo,$s),hd=o.aD(hd,hd,rc.globalMatrix);const vi=Ct.renderPass==="light-beam",Hc=ss.paint.get("model-color-use-theme").constantOr("default")==="none",Ol=nc&o.ez.HasMapboxMeshFeatures,Fu=Ol?0:Ii.evaluatedRMEA[0][2];for(let ro=0;ro=va||Fy>=va}}const ul=Ql.material;let Iv;ul.occlusionTexture&&ul.occlusionTexture.offsetScale&&(Iv=ul.occlusionTexture.offsetScale,zh.defines.push("OCCLUSION_TEXTURE_TRANSFORM"));const Dv=Ct.getOrCreateProgram("model",zh);!_r&&Ws&&Ws.setupShadowsFromMatrix(Pi.tileModelMatrix,Dv,Ws.useNormalOffset),Ct.uploadCommonUniforms(Gt,Dv,null,Oy);const cc=ul.pbrMetallicRoughness;cc.metallicFactor=.9,cc.roughnessFactor=.5;const _c=Xl(new Float32Array(Uf),new Float32Array(hd),new Float32Array(Xo),new Float32Array(rc.globalMatrix),Ct,Pi.opacity,cc.baseColorFactor,ul.emissiveFactor,cc.metallicFactor,cc.roughnessFactor,ul,Fu,ss,[0,0,0],Iv);!bh&&(Ii.hasTranslucentParts||Pi.opacity<1)&&Dv.draw(Ct,Gt.gl.TRIANGLES,mn,La.disabled,Ma.disabled,pa.backCCW,_c,ss.id,Ql.vertexBuffer,Ql.indexBuffer,Ql.segments,ss.paint,Ct.transform.zoom,void 0,gp),Dv.draw(Ct,Gt.gl.TRIANGLES,bh?vn:mn,La.disabled,bh||Pi.opacity<1||Ii.hasTranslucentParts?Ma.alphaBlended:Ma.unblended,pa.backCCW,_c,ss.id,Ql.vertexBuffer,Ql.indexBuffer,Ql.segments,ss.paint,Ct.transform.zoom,void 0,gp)}}}if(Ct._debugParams.show3DModelFootprints&&Yr.size>0){const $i=Array.from(Yr.keys()).sort();for(const li of $i){const{node:Fo,mvp:Rl}=Yr.get(li);IC(Ct,0,Fo,Rl)}}}()}(R,w,E,F),void We();if(He.type!=="model")return;const tt=He.getModels(),dt=[],it=R.transform.getFreeCameraOptions().position,jt=o.bJ([],[it.x,it.y,it.z],R.transform.worldSize);o.eo(jt,jt);const wt=[],Ot=[];let Vt=0;for(const Ct of tt){const ks=w.getFeatureState("",Ct.id),ss={type:"Unknown",id:Ct.id,properties:Ct.featureProperties},Ns=E.paint.get("model-rotation").evaluate(ss,ks),Gt=E.paint.get("model-scale").evaluate(ss,ks),es=E.paint.get("model-translation").evaluate(ss,ks),fs=E.paint.get("model-opacity").evaluate(ss,ks);DC(E,Ct.id,ks,Ct.featureProperties,Ct.nodeOverrideNames,Ct.nodeOverrides),E2(E,Ct.id,ks,Ct.featureProperties,Ct.materialOverrideNames,Ct.materialOverrides),Ct.nodeOverrides.size>0&&Ct.computeBoundsAndApplyParent(),Ct.computeModelMatrix(R,Ns,Gt,es,oe,X,!1);const Ws=o.b9([]),As=o.e2(Ct.position.lat,R.transform.zoom),gn=o.bP([],[1,1,1/As]);o.bx(Ws,Ws,jt),dt.push({zScaleMatrix:gn,negCameraPosMatrix:Ws});for(const an of Ct.nodes)PC(R,an,Ct.matrix,R.transform.expandedFarZProjMatrix,Vt,wt,Ot,Ct.materialOverrides,fs);Vt++}if(wt.sort((Ct,ks)=>ks.depth-Ct.depth),R.renderPass!=="shadow"){if(R._debugParams.show3DModelFootprints){const Ct=R.transform.projMatrix,ks=new Map,ss=(Gt,es)=>{if(Gt.footprint){const fs=Gt.id||Gt.name||"footprint";if(!ks.has(fs)){const Ws=o.aD([],Ct,es);ks.set(fs,{node:Gt,mvp:Ws})}}};for(const Gt of Ot)ss(Gt.node,Gt.modelMatrix);for(const Gt of wt)ss(Gt.node,Gt.modelMatrix);const Ns=Array.from(ks.keys()).sort();for(const Gt of Ns){const{node:es,mvp:fs}=ks.get(Gt);IC(R,0,es,fs)}}Fm(R,E,wt,Ot,dt),We()}else{for(const Ct of Ot)kk(Ct.mesh,Ct.nodeModelMatrix,R,E);for(const Ct of wt)kk(Ct.mesh,Ct.nodeModelMatrix,R,E);We()}}},Pr={line:function(R,w,E){if(R.hasElevatedBuckets=!1,R.hasNonElevatedBuckets=!1,R._unevaluatedLayout.getValue("line-elevation-reference")!==void 0||R._unevaluatedLayout.getValue("line-z-offset")!==void 0){if(w){const F=w.getVisibleCoordinates();for(const H of F){const Z=w.getTile(H).getBucket(R);if(Z&&(Z.elevationType!=="none"?R.hasElevatedBuckets=!0:R.hasNonElevatedBuckets=!0,R.hasElevatedBuckets&&R.hasNonElevatedBuckets))break}}}else R.hasNonElevatedBuckets=!0},model:function(R,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,s4(E,R)));if(F.type==="batched-model"||F.type!=="model")return;const H=F.getModels();for(const Z of H)Z.upload(E.context)},raster:function(R,w,E){const F=w.getSource();if(!(F instanceof Kp&&F.loaded()))return;const H=R.sourceLayer||F.rasterLayerIds&&F.rasterLayerIds[0];if(!H)return;const Z=R.paint.get("raster-array-band")||F.getInitialBand(H);if(Z==null)return;const X=w.getIds().map(oe=>w.getTileByID(oe));for(const oe of X)oe.updateNeeded(R.id,Z)&&F.prepareTile(oe,H,R.id,Z)},"raster-particle":function(R,w,E){const F=w.getSource();if(!(F instanceof Kp&&F.loaded()))return;const H=R.sourceLayer||F.rasterLayerIds&&F.rasterLayerIds[0];if(!H)return;const Z=R.paint.get("raster-particle-array-band")||F.getInitialBand(H);if(Z==null)return;const X=w.getIds().map(oe=>w.getTileByID(oe));for(const oe of X)oe.updateNeeded(R.id,Z)&&F.prepareTile(oe,H,R.id,Z)}},Pa={fill:$1},Ri={fill:function(R,w,E,F){if(!E.layout||E.layout.get("fill-elevation-reference")==="none"||E.paint.get("fill-opacity").constantOr(1)===0)return;const H=R.context.gl,Z=new qr(H.LEQUAL,qr.ReadOnly,R.depthRangeFor3D),X=new La({func:H.ALWAYS,mask:255},255,255,H.KEEP,H.KEEP,H.REPLACE),oe=R.transform.getFreeCameraOptions().position,xe=R.getOrCreateProgram("elevatedStructuresDepthReconstruct");for(const Ne of F){const Le=w.getTile(Ne),We=Le.getBucket(E);if(!We)continue;const He=We.elevatedStructures;if(!He||He.depthSegments.segments[0].primitiveLength===0)continue;const tt=Av(Ne.toUnwrapped(),oe),dt=R.translatePosMatrix(Ne.projMatrix,Le,E.paint.get("fill-translate"),E.paint.get("fill-translate-anchor")),it=Li(dt,tt,0,1,0);xe.draw(R,H.TRIANGLES,Z,X,Ma.disabled,pa.disabled,it,E.id,He.vertexBuffer,He.indexBuffer,He.depthSegments,E.paint,R.transform.zoom)}}};class Sl{constructor(w,E,F,H,Z){this.context=new vh(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 X=["fill","line","symbol","circle","heatmap","fill-extrusion","building","raster","raster-particle","hillshade","model","background","sky"];for(const xe of X)this._debugParams.enabledLayers[xe]=!0;for(const xe of X);this.occlusionParams=new lM,this.setup(),this.numSublayers=ql.maxUnderzooming+ql.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 Ac(this),this._wireframeDebugCache=new oM,this.renderDefaultNorthPole=!0,this.renderDefaultSouthPole=!0,this.layersWithOcclusionOpacity=[];const oe=new o.q({width:1,height:1},Uint8Array.of(0,0,0,0));this.emptyDepthTexture=new o.T(this.context,oe,w.RGBA8),this._clippingActiveLastFrame=!1,this.scaleFactor=H,this.maxFrontCutoffRawStart=0,this.worldview=Z,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 Ss(this,w));const H=this._terrain;this.transform.elevation=F?H:null,H.update(w,this.transform,E),this.transform.elevation&&!H.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,H]=E.getFovAdjustedRange(this.transform._fov);if(F>H)return void(this.transform.fogCullDistSq=null);const Z=F+.78*(H-F);this.transform.fogCullDistSq=Z*Z}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 Ss(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 H=new o.dB;H.emplaceBack(-1,-1),H.emplaceBack(1,-1),H.emplaceBack(-1,1),H.emplaceBack(1,1),this.viewportBuffer=w.createVertexBuffer(H,o.dx.members),this.viewportSegments=o.dy.simpleSegment(0,0,4,2);const Z=new o.eH;Z.emplaceBack(0,0,0,0),Z.emplaceBack(o.an,0,o.an,0),Z.emplaceBack(0,o.an,0,o.an),Z.emplaceBack(o.an,o.an,o.an,o.an),this.mercatorBoundsBuffer=w.createVertexBuffer(Z,o.eI.members),this.mercatorBoundsSegments=o.dy.simpleSegment(0,0,4,2);const X=new o.dC;X.emplaceBack(0,1,2),X.emplaceBack(2,1,3),this.quadTriangleIndexBuffer=w.createIndexBuffer(X);const oe=new o.eJ;for(const Ne of[0,1,3,2,0])oe.emplaceBack(Ne);this.debugIndexBuffer=w.createIndexBuffer(oe),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 xe=this.context.gl;this.stencilClearMode=new La({func:xe.ALWAYS,mask:0},0,255,xe.ZERO,xe.ZERO,xe.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,qr.disabled,this.stencilClearMode,Ma.disabled,pa.disabled,mt(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 oe=!1;for(const xe of F)if(this._tileClippingMaskIDs[xe.key]===void 0){oe=!0;break}if(!oe)return}this.currentStencilSource=E.id;const H=this.context,Z=H.gl;this.nextStencilID+F.length>256&&this.clearStencil(),H.setColorMode(Ma.disabled),H.setDepthMode(qr.disabled);const X=this.getOrCreateProgram("clippingMask");this._tileClippingMaskIDs={};for(const oe of F){const xe=E.getTile(oe),Ne=this._tileClippingMaskIDs[oe.key]=this.nextStencilID++,{tileBoundsBuffer:Le,tileBoundsIndexBuffer:We,tileBoundsSegments:He}=this.getTileBoundsBuffers(xe);X.draw(this,Z.TRIANGLES,qr.disabled,new La({func:Z.ALWAYS,mask:0},Ne,255,Z.KEEP,Z.KEEP,Z.REPLACE),Ma.disabled,pa.disabled,mt(oe.projMatrix),"$clipping",Le,We,He)}}stencilModeFor3D(){this.currentStencilSource=void 0,this.nextStencilID+1>256&&this.clearStencil();const w=this.nextStencilID++,E=this.context.gl;return new La({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 La({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((X,oe)=>oe.overscaledZ-X.overscaledZ),H=F[F.length-1].overscaledZ,Z=F[0].overscaledZ-H+1;if(Z>1){this.currentStencilSource=void 0,this.nextStencilID+Z>256&&this.clearStencil();const X={};for(let oe=0;oethis._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 H=this.style._mergedLayers,Z=!(!this.terrain||!this.terrain.enabled),X=()=>this.style._getOrder(Z).filter(en=>{const Ms=H[en];return!(Ms.type in this._debugParams.enabledLayers)||this._debugParams.enabledLayers[Ms.type]});let oe=X(),xe=!1,Ne=!1,Le=null,We=0,He=!1;for(const en of oe){const Ms=H[en];Ms.visibility!=="none"&&(Ms.type==="circle"?xe=!0:Ms.type==="building"?(Le=Ms,++We):Ms.type==="symbol"&&(Ms.hasOcclusionOpacityProperties?Ne=!0:xe=!0))}this.updateEmissiveMode();let tt=oe.map(en=>H[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 Ms=dt[en];Ms.used&&(Ms.prepare(this.context),Ms.getSource().usedInConflation&&++We)}let it=!1;for(const en of tt)en.isHidden(this.transform.zoom)||(en.type==="clip"&&(it=!0),this.prepareLayer(en));const jt={},wt={},Ot={},Vt={},Ct={};for(const en in dt){const Ms=dt[en];jt[en]=Ms.getVisibleCoordinates(),wt[en]=jt[en].slice().reverse(),Ot[en]=Ms.getVisibleCoordinates(!0).reverse(),Vt[en]=Ms.getShadowCasterCoordinates(),Ct[en]=Ms.sortCoordinatesByDistance(jt[en])}const ks=en=>{const Ms=this.style.getLayerSourceCache(en);return Ms&&Ms.used?Ms.getSource():null};if(We||it||this._clippingActiveLastFrame){const en=[],Ms=[];let mn=0;for(const vn of tt)this.isSourceForClippingOrConflation(vn,ks(vn))&&(en.push(vn),Ms.push(mn)),mn++;if(en&&(it||en.length>1)||this._clippingActiveLastFrame){it=!1;const vn=[];for(let kn=0;kn0){const vn=ks(Ms);vn&&(this.minCutoffZoom=Math.max(vn.minzoom,this.minCutoffZoom)),Ms.minzoom&&(this.minCutoffZoom=Math.max(Ms.minzoom,this.minCutoffZoom))}Ms.is3D(Z)&&(this.opaquePassCutoff===1/0&&(this.opaquePassCutoff=en),this._lastOcclusionLayer=en)}const ss=this.style&&this.style.fog;ss?(this._fogVisible=ss.getOpacity(this.transform.pitch)!==0,this._fogVisible&&this.transform.projection.name!=="globe"&&(this._fogVisible=ss.isVisibleOnFrustum(this.transform.cameraFrustum))):this._fogVisible=!1,this._cachedTileFogOpacities={},this.terrain&&(this.terrain.updateTileBinding(Ot),this.opaquePassCutoff=0,oe=X(),tt=oe.map(en=>H[en]));const Ns=this._shadowRenderer;if(Ns){Ns.updateShadowParameters(this.transform,this.style.directionalLight);for(const en in dt)for(const Ms of jt[en]){let mn={min:0,max:0};this.terrain&&(mn=this.terrain.getMinMaxForTile(Ms)||mn),Ns.addShadowReceiver(Ms.toUnwrapped(),mn.min,mn.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 jk(this)),this._atmosphere.update(this)):this._atmosphere&&(this._atmosphere.destroy(),this._atmosphere=void 0);const Gt=this._debugParams.forceEnablePrecipitation||!(!this.style||!this.style.snow),es=this._debugParams.forceEnablePrecipitation||!(!this.style||!this.style.rain);if(Gt&&!this._snow&&(this._snow=new Fs(this)),!Gt&&this._snow&&(this._snow.destroy(),delete this._snow),es&&!this._rain&&(this._rain=new ct(this)),!es&&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 Zx);const en=this.style.getLayerSourceCache(Le);this.buildingTileBorderManager.updateBorders(en,Le)}if(!Be.has(this.context.gl))return;this.renderPass="offscreen";for(const en of tt){const Ms=w.getLayerSourceCache(en);if(!en.hasOffscreenPass()||en.isHidden(this.transform.zoom))continue;const mn=Ms?wt[Ms.id]:void 0;(en.type==="custom"||en.type==="raster"||en.type==="raster-particle"||en.isSky()||mn&&mn.length)&&this.renderLayer(this,Ms,en,mn)}this.depthRangeFor3D=[0,1-(tt.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 fs=this.transform.projection.name==="globe"||this.transform.isHorizonVisible(),Ws=(()=>{if(E.showOverdrawInspector)return o.aq.black;const en=this.style.fog;if(en&&this.transform.projection.supportsFog){const Ms=this.style.getLut(en.scope);if(!fs){const mn=en.properties.get("color-use-theme")==="none",vn=en.properties.get("color").toNonPremultipliedRenderColor(mn?null:Ms).toArray01();return new o.aq(...vn)}if(fs){const mn=en.properties.get("space-color-use-theme")==="none",vn=en.properties.get("space-color").toNonPremultipliedRenderColor(mn?null:Ms).toArray01();return new o.aq(...vn)}}return o.aq.transparent})();if(this.context.clear({color:Ws,depth:1}),this.clearStencil(),this._showOverdrawInspector=E.showOverdrawInspector,this.renderPass="opaque",this.style.fog&&this.transform.projection.supportsFog&&this._atmosphere&&!this._showOverdrawInspector&&fs&&this._atmosphere.drawStars(this,this.style.fog),!this.terrain)for(this.currentLayer=oe.length-1;this.currentLayer>=0;this.currentLayer--){const en=tt[this.currentLayer],Ms=w.getLayerSourceCache(en);if(en.isSky())continue;const mn=Ms?(en.is3D(Z)?Ct:wt)[Ms.id]:void 0;this._renderTileClippingMasks(en,Ms,mn),this.renderLayer(this,Ms,en,mn)}if(this.style.fog&&this.transform.projection.supportsFog&&this._atmosphere&&!this._showOverdrawInspector&&fs&&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 mn=this.currentLayer;this.depthOcclusion=!0;for(const vn of this.layersWithOcclusionOpacity){this.currentLayer=vn;const kn=tt[this.currentLayer],_r=w.getLayerSourceCache(kn),cr=_r?wt[_r.id]:void 0;this.terrain||this._renderTileClippingMasks(kn,_r,_r?jt[_r.id]:void 0),this.renderLayer(this,_r,kn,cr)}this.depthOcclusion=!1,this.currentLayer=mn,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;tt.forEach(Ms=>{const mn=w.getLayerSourceCache(Ms);mn&&!Ms.isHidden(this.transform.zoom)&&mn.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 H=F===void 0?this.terrain&&this.terrain.renderingToTexture:F,Z=[];return this.style&&this.style.enable3dLights()&&(w==="globeRaster"||w==="terrainRaster"?(Z.push("LIGHTING_3D_MODE"),Z.push("LIGHTING_3D_ALPHA_EMISSIVENESS")):H||Z.push("LIGHTING_3D_MODE")),this.terrainRenderModeElevated()&&(Z.push("TERRAIN"),this.linearFloatFilteringSupported()&&Z.push("TERRAIN_DEM_FLOAT_FORMAT")),this.transform.projection.name==="globe"&&Z.push("GLOBE"),!this._fogVisible||H||E!==void 0&&!E||Z.push("FOG"),H&&Z.push("RENDER_TO_TEXTURE"),this._showOverdrawInspector&&Z.push("OVERDRAW_INSPECTOR"),Z}getOrCreateProgram(w,E){this.cache=this.cache||{};const F=E&&E.defines||[],H=E&&E.config,Z=this.currentGlobalDefines(w,E&&E.overrideFog,E&&E.overrideRtt).concat(F),X=Xn.cacheKey(Lw[w],w,Z,H);return this.cache[X]||(this.cache[X]=new Xn(this.context,w,Lw[w],H,Dm[w],Z)),this.cache[X]}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,H=this.style.ambientLight;if(F&&H){const Z=((X,oe,xe)=>{const Ne=X.properties.get("direction"),Le=X.properties.get("color-use-theme")==="none",We=X.properties.get("color").toNonPremultipliedRenderColor(Le?null:xe.getLut(X.scope)).toArray01(),He=X.properties.get("intensity"),tt=oe.properties.get("color-use-theme")==="none",dt=oe.properties.get("color").toNonPremultipliedRenderColor(tt?null:xe.getLut(oe.scope)).toArray01(),it=oe.properties.get("intensity"),jt=[Ne.x,Ne.y,Ne.z],wt=o.dD(dt,it),Ot=o.dD(We,He);return{u_lighting_ambient_color:wt,u_lighting_directional_dir:jt,u_lighting_directional_color:Ot,u_ground_radiance:Es(jt,Ot,wt)}})(F,H,this.style);E.setLightsUniformValues(w,Z)}}}uploadCommonUniforms(w,E,F,H,Z){if(this.uploadCommonLightUniforms(w,E),this.terrain&&this.terrain.renderingToTexture)return;const X=this.style.fog;if(X){const oe=X.getOpacity(this.transform.pitch),xe=((Ne,Le,We,He,tt,dt,it,jt,wt,Ot,Vt,Ct)=>{const ks=Ne.transform,ss=Le.properties.get("color-use-theme")==="none",Ns=Le.properties.get("color").toNonPremultipliedRenderColor(ss?null:Ne.style.getLut(Le.scope)).toArray01();Ns[3]=He;const Gt=Ne.frameCounter/1e3%1,[es,fs]=Le.properties.get("vertical-range");return{u_fog_matrix:We?ks.calculateFogTileMatrix(We):Ct||Ne.identityMat,u_fog_range:Le.getFovAdjustedRange(ks._fov),u_fog_color:Ns,u_fog_horizon_blend:Le.properties.get("horizon-blend"),u_fog_vertical_limit:[Math.min(es,fs),fs],u_fog_temporal_offset:Gt,u_frustum_tl:tt,u_frustum_tr:dt,u_frustum_br:it,u_frustum_bl:jt,u_globe_pos:wt,u_globe_radius:Ot,u_viewport:Vt,u_globe_transition:o.al(ks.zoom),u_is_globe:+(ks.projection.name==="globe")}})(this,X,F,oe,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],H);E.setFogUniformValues(w,xe)}Z&&E.setCutoffUniformValues(w,Z.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 H of F)E[H.key]=w[H.key]||new o.b0(H,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]>=va||E[1]>=va}setupDepthForOcclusion(w,E,F){const H=this.context,Z=H.gl,X=!!F;var oe;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}),H.activeTexture.set(Z.TEXTURE3),w&&this.depthFBO&&this.depthTexture?(this.depthTexture.bind(Z.NEAREST,Z.CLAMP_TO_EDGE),F.u_depth_size_inv=[1/this.depthFBO.width,1/this.depthFBO.height],F.u_depth_range_unpack=[2/((oe=this.depthRangeFor3D)[1]-oe[0]),-1-2*oe[0]/(oe[1]-oe[0])],F.u_occluder_half_size=.5*this.occlusionParams.occluderSize,F.u_occlusion_depth_offset=this.occlusionParams.depthOffset):this.emptyDepthTexture.bind(Z.NEAREST,Z.CLAMP_TO_EDGE),H.activeTexture.set(Z.TEXTURE0),X||E.setTerrainUniformValues(H,F)}updateEmissiveMode(){if(this._forceEmissiveMode)return;const w=this.style.hasDataDrivenEmissiveStrength();this.emissiveMode=w?this.context.extBlendFuncExtended?"dual-source-blending":"mrt-fallback":"constant"}}function yi(R,w){let E=!1,F=null;const H=()=>{F=null,E&&(R(),F=setTimeout(H,w),E=!1)};return()=>(E=!0,F||H(),F)}class Ou{constructor(w){this._hashName=w&&encodeURIComponent(w),o.aZ(["_getCurrentHash","_onHashChange","_updateHash"],this),this._updateHash=yi(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=Cl(w);if(this._hashName){const F=this._hashName;let H=!1;const Z=location.hash.slice(1).split("&").map(X=>{const oe=X.split("=")[0];return oe===F?(H=!0,`${oe}=${E}`):X}).filter(X=>X);return H||Z.push(`${F}=${E}`),`#${Z.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 Cl(R,w){const E=R.getCenter(),F=Math.round(100*R.getZoom())/100,H=Math.ceil((F*Math.LN2+Math.log(512/360/.5))/Math.LN10),Z=Math.pow(10,H),X=Math.round(E.lng*Z)/Z,oe=Math.round(E.lat*Z)/Z,xe=R.getBearing(),Ne=R.getPitch();let Le=w?`/${X}/${oe}/${F}`:`${F}/${oe}/${X}`;return(xe||Ne)&&(Le+="/"+Math.round(10*xe)/10),Ne&&(Le+=`/${Math.round(Ne)}`),Le}const $f={linearity:.3,easing:o.eN(0,0,.3,1)},W0=Object.assign({deceleration:2500,maxSpeed:1400},$f),Er=Object.assign({deceleration:20,maxSpeed:1400},$f),Nn=Object.assign({deceleration:1e3,maxSpeed:360},$f),zn=Object.assign({deceleration:1e3,maxSpeed:90},$f);class Ci{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:Z}of this._inertiaBuffer)E.zoom+=Z.zoomDelta||0,E.bearing+=Z.bearingDelta||0,E.pitch+=Z.pitchDelta||0,Z.panDelta&&E.pan._add(Z.panDelta),Z.around&&(E.around=Z.around),Z.pinchAround&&(E.pinchAround=Z.pinchAround);const F=this._inertiaBuffer[this._inertiaBuffer.length-1].time-this._inertiaBuffer[0].time,H={};if(E.pan.mag()){const Z=Wo(E.pan.mag(),F,Object.assign({},W0,w||{}));H.offset=E.pan.mult(Z.amount/E.pan.mag()),H.center=this._map.transform.center,zi(H,Z)}if(E.zoom){const Z=Wo(E.zoom,F,Er);H.zoom=this._map.transform.zoom+Z.amount,zi(H,Z)}if(E.bearing){const Z=Wo(E.bearing,F,Nn);H.bearing=this._map.transform.bearing+o.aC(Z.amount,-179,179),zi(H,Z)}if(E.pitch){const Z=Wo(E.pitch,F,zn);H.pitch=this._map.transform.pitch+Z.amount,zi(H,Z)}if(H.zoom||H.bearing){const Z=E.pinchAround===void 0?E.around:E.pinchAround;H.around=Z?this._map.unproject(Z):this._map.getCenter()}return this.clear(),H.noMoveStart=!0,H}}function zi(R,w){(!R.duration||R.durationE.unproject(xe)),oe=Z.reduce((xe,Ne,Le,We)=>xe.add(Ne.div(We.length)),new o.P(0,0));super(w,{points:Z,point:oe,lngLats:X,lngLat:E.unproject(oe),originalEvent:F}),this._defaultPrevented=!1}}class zm extends o.C{preventDefault(){this._defaultPrevented=!0}get defaultPrevented(){return this._defaultPrevented}constructor(w,E){super("wheel",{originalEvent:E}),this._defaultPrevented=!1}}class zc{constructor(w,E){this._map=w,this._clickTolerance=E.clickTolerance}reset(){this._mousedownPos=void 0}wheel(w){return this._firePreventable(new zm(this._map,w))}mousedown(w,E){return this._mousedownPos=E,this._firePreventable(new so(w.type,this._map,w))}mouseup(w){this._map.fire(new so(w.type,this._map,w))}preclick(w){const E=new MouseEvent("preclick",w);this._map.fire(new so(E.type,this._map,E))}click(w,E){this._mousedownPos&&this._mousedownPos.dist(E)>=this._clickTolerance||(this.preclick(w),this._map.fire(new so(w.type,this._map,w)))}dblclick(w){return this._firePreventable(new so(w.type,this._map,w))}mouseover(w){this._map.fire(new so(w.type,this._map,w))}mouseout(w){this._map.fire(new so(w.type,this._map,w))}touchstart(w){return this._firePreventable(new xl(w.type,this._map,w))}touchmove(w){this._map.fire(new xl(w.type,this._map,w))}touchend(w){this._map.fire(new xl(w.type,this._map,w))}touchcancel(w){this._map.fire(new xl(w.type,this._map,w))}_firePreventable(w){if(this._map.fire(w),w.defaultPrevented)return{}}isEnabled(){return!0}isActive(){return!1}enable(){}disable(){}}class G1{constructor(w){this._map=w}reset(){this._delayContextMenu=!1,this._contextMenuEvent=void 0}mousemove(w){this._map.fire(new so(w.type,this._map,w))}mousedown(){this._delayContextMenu=!0}mouseup(){this._delayContextMenu=!1,this._contextMenuEvent&&(this._map.fire(new so("contextmenu",this._map,this._contextMenuEvent)),delete this._contextMenuEvent)}contextmenu(w){this._delayContextMenu?this._contextMenuEvent=w:this._map.fire(new so(w.type,this._map,w)),this._map.listens("contextmenu")&&w.preventDefault()}isEnabled(){return!0}isActive(){return!1}enable(){}disable(){}}class dM{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&&(C(),this._startPos=this._lastPos=E,this._active=!0)}mousemoveWindow(w,E){if(!this._active)return;const F=E,H=this._startPos,Z=this._lastPos;if(!H||!Z||Z.equals(F)||!this._box&&F.dist(H){this._box&&(this._box.style.transform=`translate(${X}px,${xe}px)`,this._box.style.width=oe-X+"px",this._box.style.height=Ne-xe+"px")})}mouseupWindow(w,E){if(!this._active)return;const F=this._startPos,H=E;if(F&&w.button===0){if(this.reset(),P(),F.x!==H.x||F.y!==H.y)return this._map.fire(new o.C("boxzoomend",{originalEvent:w})),{cameraAnimation:Z=>Z.fitScreenCoordinates(F,H,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 uM(R,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(H){const Z=new o.P(0,0);for(const X of H)Z._add(X);return Z.div(H.length)}(E),this.touches=uM(F,E)))}touchmove(w,E,F){if(this.aborted||!this.centroid)return;const H=uM(F,E);for(const Z in this.touches){const X=H[Z];(!X||X.dist(this.touches[Z])>30)&&(this.aborted=!0)}}touchend(w,E,F){if((!this.centroid||w.timeStamp-this.startTime>500)&&(this.aborted=!0),F.length===0){const H=!this.aborted&&this.centroid;if(this.reset(),H)return H}}}class Gw{constructor(w){this.singleTap=new W1(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 H=this.singleTap.touchend(w,E,F);if(H){const Z=w.timeStamp-this.lastTime<500,X=!this.lastTap||this.lastTap.dist(H)<30;if(Z&&X||this.reset(),this.count++,this.lastTime=w.timeStamp,this.lastTap=H,this.count===this.numTaps)return this.reset(),H}}}class zC{constructor(){this._zoomIn=new Gw({numTouches:1,numTaps:2}),this._zoomOut=new Gw({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 H=this._zoomIn.touchend(w,E,F),Z=this._zoomOut.touchend(w,E,F);return H?(this._active=!0,w.preventDefault(),setTimeout(()=>this.reset(),0),{cameraAnimation:X=>X.easeTo({duration:300,zoom:X.getZoom()+1,around:X.unproject(H)},{originalEvent:w})}):Z?(this._active=!0,w.preventDefault(),setTimeout(()=>this.reset(),0),{cameraAnimation:X=>X.easeTo({duration:300,zoom:X.getZoom()-1,around:X.unproject(Z)},{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 CF=0,IV=2,DV={[CF]:1,[IV]:2},M2={Control:"ctrlKey",Alt:"altKey",Shift:"shiftKey",Meta:"metaKey"};class hM{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=D(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(H,Z){const X=DV[Z];return H.buttons===void 0||(H.buttons&X)!==X}(w,this._eventButton))this.reset();else if(this._moved||!(E.dist(F)0&&(this._active=!0);const H=uM(F,E),Z=new o.P(0,0),X=new o.P(0,0);let oe=0;for(const Ne in H){const Le=H[Ne],We=this._touches[Ne];We&&(Z._add(Le),X._add(Le.sub(We)),oe++,H[Ne]=Le)}if(this._touches=H,oe{this._alertContainer.classList.remove("mapboxgl-touch-pan-blocker-show"),this._alertContainer.removeAttribute("role")},500)}}class pM{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 H=this._firstTwoTouches;if(!H)return;w.preventDefault();const[Z,X]=H,oe=nu(F,E,Z),xe=nu(F,E,X);if(!oe||!xe)return;const Ne=this._aroundCenter?null:oe.add(xe).div(2);return this._move([oe,xe],Ne,w)}touchend(w,E,F){if(!this._firstTwoTouches)return;const[H,Z]=this._firstTwoTouches,X=nu(F,E,H),oe=nu(F,E,Z);X&&oe||(this._active&&P(),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 nu(R,w,E){for(let F=0;FMath.abs(R.x)}class FV extends pM{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,fM(w[0].sub(w[1]))&&(this._valid=!1)}_move(w,E,F){const H=this._lastPoints;if(!H)return;const Z=w[0].sub(H[0]),X=w[1].sub(H[1]);return this._map._cooperativeGestures&&!o.eO()&&F.touches.length<3||(this._valid=this.gestureBeginsVertically(Z,X,F.timeStamp),!this._valid)?void 0:(this._lastPoints=w,this._active=!0,{pitchDelta:(Z.y+X.y)/2*-.5})}gestureBeginsVertically(w,E,F){if(this._valid!==void 0)return this._valid;const H=w.mag()>=2,Z=E.mag()>=2;if(!H&&!Z)return;if(!H||!Z)return this._firstMove==null&&(this._firstMove=F),F-this._firstMove<100&&void 0;const X=w.y>0==E.y>0;return fM(w)&&fM(E)&&X}}const zV={panStep:100,bearingStep:15,pitchStep:10};class i4{constructor(){const w=zV;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,H=0,Z=0,X=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(),Z=-1);break;case 39:w.shiftKey?F=1:(w.preventDefault(),Z=1);break;case 38:w.shiftKey?H=1:(w.preventDefault(),X=-1);break;case 40:w.shiftKey?H=-1:(w.preventDefault(),X=1);break;default:return}return this._rotationDisabled&&(F=0,H=0),{cameraAnimation:oe=>{const xe=oe.getZoom();oe.easeTo({duration:300,easeId:"keyboardHandler",easing:BV,zoom:E?Math.round(xe)+E*(w.shiftKey?2:1):xe,bearing:oe.getBearing()+F*this._bearingStep,pitch:oe.getPitch()+H*this._pitchStep,offset:[-Z*this._panStep,-X*this._panStep],center:oe.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 BV(R){return R*(2-R)}const o4=4.000244140625,$V=1/450;class MF{constructor(w,E){this._map=w,this._el=w.getCanvasContainer(),this._handler=E,this._delta=0,this._lastDelta=0,this._defaultZoomRate=.01,this._wheelZoomRate=$V,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(),H=F-(this._lastWheelEventTime||0);this._lastWheelEventTime=F,E!==0&&E%o4===0?this._type="wheel":E!==0&&Math.abs(E)<4?this._type="trackpad":H>400?(this._type=null,this._lastValue=E,this._timeout=window.setTimeout(this._onTimeout,40,w)):this._type||(this._type=Math.abs(H*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 Ne=this._type==="wheel"&&Math.abs(this._delta)>o4?this._wheelZoomRate:this._defaultZoomRate;let Le=2/(1+Math.exp(-Math.abs(this._delta*Ne)));this._delta<0&&Le!==0&&(Le=1/Le);const We=E(),He=Math.pow(2,We),tt=typeof this._targetZoom=="number"?w.zoomScale(this._targetZoom):He;this._targetZoom=Math.min(w.maxZoom,Math.max(w.minZoom,w.scaleZoom(tt*Le))),this._type==="wheel"&&(this._startZoom=We,this._easing=this._smoothOutEasing(200)),this._lastDelta=this._delta,this._delta=0}const F=typeof this._targetZoom=="number"?this._targetZoom:E(),H=this._startZoom,Z=this._easing;let X,oe=!1;if(this._type==="wheel"&&H&&Z){const Ne=Math.min((o.o.now()-this._lastWheelEventTime)/200,1),Le=Z(Ne);X=o.am(H,F,Le),Ne<1?this._frameId||(this._frameId=!0):oe=!0}else X=F,oe=!0;this._active=!0,oe&&(this._active=!1,this._finishTimeout=window.setTimeout(()=>{this._zooming=!1,this._handler._triggerRenderFrame(),delete this._targetZoom,delete this._finishTimeout},200));let xe=X-E();return xe*this._lastDelta<0&&(xe=0),{noInertia:!0,needsRenderFrame:!oe,zoomDelta:xe,around:this._aroundPoint,aroundCoord:this._aroundCoord,originalEvent:this._lastWheelEvent}}_smoothOutEasing(w){let E=o.eP;if(this._prevEase){const F=this._prevEase,H=(o.o.now()-F.start)/F.duration,Z=F.easing(H+.01)-F.easing(H),X=.27/Math.sqrt(Z*Z+1e-4)*.01,oe=Math.sqrt(.0729-X*X);E=o.eN(X,oe,.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=g("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 LF{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 PF{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 jte{constructor(){this._tap=new Gw({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 H=E[0],Z=H.y-this._swipePoint.y;return this._swipePoint=H,w.preventDefault(),this._active=!0,{zoomDelta:Z/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 UV{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 Nte{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 kte{constructor(w,E,F,H){this._el=w,this._touchZoom=E,this._touchRotate=F,this._tapDragZoom=H,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 xM=R=>R.zoom||R.drag||R.pitch||R.rotate;class Ste extends o.C{}class Cte{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])),H=o.bJ([],o.ay([],[E[0],E[1],0]),this.radius),Z=o.cT([],E,o.bJ([],o.ax([],o.cT([],H,F),E),2));E[0]=Z[0],E[1]=Z[1]}return E}}function gM(R){return R.panDelta&&R.panDelta.mag()||R.zoomDelta||R.bearingDelta||R.pitchDelta}class Ate{constructor(w,E){this._map=w,this._el=this._map.getCanvasContainer(),this._handlers=[],this._handlersById={},this._changes=[],this._inertia=new Ci(w),this._bearingSnap=E.bearingSnap,this._previousActiveHandlers={},this._trackingEllipsoid=new Cte,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[H,Z,X]of this._listeners){const oe=H===document?this.handleWindowEvent:this.handleEvent;H.addEventListener(Z,oe,X)}}destroy(){for(const[w,E,F]of this._listeners){const H=w===document?this.handleWindowEvent:this.handleEvent;w.removeEventListener(E,H,F)}}_addDefaultHandlers(w){const E=this._map,F=E.getCanvasContainer();this._add("mapEvent",new zc(E,w));const H=E.boxZoom=new dM(E,w);this._add("boxZoom",H);const Z=new zC,X=new PF;E.doubleClickZoom=new LF(X,Z),this._add("tapZoom",Z),this._add("clickZoom",X);const oe=new jte;this._add("tapDragZoom",oe);const xe=E.touchPitch=new FV(E);this._add("touchPitch",xe);const Ne=new AF(w),Le=new mM(w);E.dragRotate=new Nte(w,Ne,Le),this._add("mouseRotate",Ne,["mousePitch"]),this._add("mousePitch",Le,["mouseRotate"]);const We=new K1(w),He=new RV(E,w);E.dragPan=new UV(F,We,He),this._add("mousePan",We),this._add("touchPan",He,["touchZoom","touchRotate"]);const tt=new a4,dt=new OV;E.touchZoomRotate=new kte(F,dt,tt,oe),this._add("touchRotate",tt,["touchPan","touchZoom"]),this._add("touchZoom",dt,["touchPan","touchRotate"]),this._add("blockableMapEvent",new G1(E));const it=E.scrollZoom=new MF(E,this);this._add("scrollZoom",it,["mousePan"]);const jt=E.keyboard=new i4;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!!xM(this._eventsInProgress)||this.isZooming()}_isDragging(){return!!this._eventsInProgress.drag}_blockedByActive(w,E,F){for(const H in w)if(H!==F&&(!E||E.indexOf(H)<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",H=F?void 0:w,Z={needsRenderFrame:!1},X={},oe={},xe=w.touches?this._getMapTouches(w.touches):void 0,Ne=xe?I(this._el,xe):F?void 0:M(this._el,w);for(const{handlerName:He,handler:tt,allowed:dt}of this._handlers){if(!tt.isEnabled())continue;let it;this._blockedByActive(oe,dt,He)?tt.reset():tt[E||w.type]&&(it=tt[E||w.type](w,Ne,xe),this.mergeHandlerResult(Z,X,it,He,H),it&&it.needsRenderFrame&&this._triggerRenderFrame()),(it||tt.isActive())&&(oe[He]=tt)}const Le={};for(const He in this._previousActiveHandlers)oe[He]||(Le[He]=H);this._previousActiveHandlers=oe,(Object.keys(Le).length||gM(Z))&&(this._changes.push([Z,X,Le]),this._triggerRenderFrame()),(Object.keys(oe).length||gM(Z))&&this._map._stop(!0),this._updatingCamera=!1;const{cameraAnimation:We}=Z;We&&(this._inertia.clear(),this._fireEvents({},{},!0),this._changes=[],We(this._map))}mergeHandlerResult(w,E,F,H,Z){if(!F)return;Object.assign(w,F);const X={handlerName:H,originalEvent:F.originalEvent||Z};F.zoomDelta!==void 0&&(E.zoom=X),F.panDelta!==void 0&&(E.drag=X),F.pitchDelta!==void 0&&(E.pitch=X),F.bearingDelta!==void 0&&(E.rotate=X)}_applyChanges(){const w={},E={},F={};for(const[H,Z,X]of this._changes)H.panDelta&&(w.panDelta=(w.panDelta||new o.P(0,0))._add(H.panDelta)),H.zoomDelta&&(w.zoomDelta=(w.zoomDelta||0)+H.zoomDelta),H.bearingDelta&&(w.bearingDelta=(w.bearingDelta||0)+H.bearingDelta),H.pitchDelta&&(w.pitchDelta=(w.pitchDelta||0)+H.pitchDelta),H.around!==void 0&&(w.around=H.around),H.aroundCoord!==void 0&&(w.aroundCoord=H.aroundCoord),H.pinchAround!==void 0&&(w.pinchAround=H.pinchAround),H.noInertia&&(w.noInertia=H.noInertia),Object.assign(E,Z),Object.assign(F,X);this._updateMapTransform(w,E,F),this._changes=[]}_updateMapTransform(w,E,F){const H=this._map,Z=H.transform,X=Ot=>[Ot.x,Ot.y,Ot.z];if((()=>{const Ot=this._eventsInProgress.drag;return Ot&&!this._handlersById[Ot.handlerName].isActive()})()&&!gM(w)){const Ot=Z.zoom;Z.cameraElevationReference="sea",this._originalZoom!=null&&Z._orthographicProjectionAtLowPitch&&Z.projection.name!=="globe"&&Z.pitch===0?(Z.cameraElevationReference="ground",Z.zoom=this._originalZoom):(Z.recenterOnTerrain(),Z.cameraElevationReference="ground"),Ot!==Z.zoom&&this._map._update(!0)}if(Z._isCameraConstrained&&H._stop(!0),!gM(w))return void this._fireEvents(E,F,!0);let{panDelta:oe,zoomDelta:xe,bearingDelta:Ne,pitchDelta:Le,around:We,aroundCoord:He,pinchAround:tt}=w;Z._isCameraConstrained&&(xe>0&&(xe=0),Z._isCameraConstrained=!1),tt!==void 0&&(We=tt),(xe||(Ot=>E[Ot]&&!this._eventsInProgress[Ot])("drag"))&&We&&(this._dragOrigin=X(Z.pointCoordinate3D(We)),this._originalZoom=Z.zoom,this._trackingEllipsoid.setup(Z._camera.position,this._dragOrigin)),Z.cameraElevationReference="sea",H._stop(!0),We=We||H.transform.centerPoint,Ne&&(Z.bearing+=Ne),Le&&(Z.pitch+=Le),Z._updateCameraState();const dt=[0,0,0];if(oe)if(Z.projection.name==="mercator"){const Ot=this._trackingEllipsoid.projectRay(Z.screenPointToMercatorRay(We).dir),Vt=this._trackingEllipsoid.projectRay(Z.screenPointToMercatorRay(We.sub(oe)).dir);dt[0]=Vt[0]-Ot[0],dt[1]=Vt[1]-Ot[1]}else{const Ot=Z.pointCoordinate(We);if(Z.projection.name==="globe"){oe=oe.rotate(-Z.angle);const Vt=Z._pixelsPerMercatorPixel/Z.worldSize;dt[0]=-oe.x*o.eQ(o.bV(Ot.y))*Vt,dt[1]=-oe.y*o.eQ(Z.center.lat)*Vt}else{const Vt=Z.pointCoordinate(We.sub(oe));Ot&&Vt&&(dt[0]=Vt.x-Ot.x,dt[1]=Vt.y-Ot.y)}}const it=Z.zoom,jt=[0,0,0];if(xe){const Ot=X(He||Z.pointCoordinate3D(We)),Vt={dir:o.ay([],o.ax([],Ot,Z._camera.position))};if(Vt.dir[2]<0){const Ct=Z.zoomDeltaToMovement(Ot,xe);o.bJ(jt,Vt.dir,Ct)}}const wt=o.cT(dt,dt,jt);Z._translateCameraConstrained(wt),xe&&Math.abs(Z.zoom-it)>1e-4&&Z.recenterOnTerrain(),Z.cameraElevationReference="ground",this._map._update(),w.noInertia||this._inertia.record(w),this._fireEvents(E,F,!0)}_fireEvents(w,E,F){const H=xM(this._eventsInProgress),Z=xM(w),X={};for(const Le in w){const{originalEvent:We}=w[Le];this._eventsInProgress[Le]||(X[`${Le}start`]=We),this._eventsInProgress[Le]=w[Le]}!H&&Z&&this._fireEvent("movestart",Z.originalEvent);for(const Le in X)this._fireEvent(Le,X[Le]);Z&&this._fireEvent("move",Z.originalEvent);for(const Le in w){const{originalEvent:We}=w[Le];this._fireEvent(Le,We)}const oe={};let xe;for(const Le in this._eventsInProgress){const{handlerName:We,originalEvent:He}=this._eventsInProgress[Le];this._handlersById[We].isActive()||(delete this._eventsInProgress[Le],xe=E[We]||He,oe[`${Le}end`]=xe)}for(const Le in oe)this._fireEvent(Le,oe[Le]);const Ne=xM(this._eventsInProgress);if(F&&(H||Z)&&!Ne){this._updatingCamera=!0;const Le=this._inertia._onMoveEnd(this._map.dragPan._inertiaOptions),We=He=>He!==0&&-this._bearingSnap{this._frameId=void 0,this.handleEvent(new Ste("renderFrame",{timeStamp:w})),this._applyChanges()})}_triggerRenderFrame(){this._frameId===void 0&&(this._frameId=this._requestFrame())}}const qV="map.setFreeCameraOptions(...) and map.getFreeCameraOptions() are not yet supported for non-mercator projections.";class Ete 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):H/(2*Math.tan(.5*w.fovY)*w.aspect)}_cameraForBoundsOnGlobe(w,E,F,H,Z,X){const oe=w.clone(),xe=this._extendCameraOptions(X);oe.bearing=H,oe.pitch=Z;const Ne=o.aU.convert(E),Le=o.aU.convert(F),We=.5*(Ne.lat+Le.lat),He=.5*(Ne.lng+Le.lng),tt=o.eT(We,He),dt=o.ay([],tt),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],Ot=[tt,o.eT(Ne.lat,Ne.lng),o.eT(Le.lat,Ne.lng),o.eT(Le.lat,Le.lng),o.eT(Ne.lat,Le.lng),o.eT(We,Ne.lng),o.eT(We,Le.lng),o.eT(Ne.lat,He),o.eT(Le.lat,He)];let Vt=o.cU.fromPoints(Ot.map(vn=>[o.bi(it,vn),o.bi(jt,vn),o.bi(dt,vn)]));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),oe.center=o.eW(Ct);const ks=oe.getWorldToCameraMatrix(),ss=o.b7(new Float64Array(16),ks);Vt=o.cU.applyTransform(Vt,o.aD([],ks,wt));const Ns=this._extendAABB(Vt,oe,xe,H);if(!Ns)return void o.w("Map cannot fit within canvas with the given bounds, padding, and/or offset.");Vt=Ns,o.ah(Ct,Ct,ks);const Gt=.5*(Vt.max[2]-Vt.min[2]),es=this._minimumAABBFrustumDistance(oe,Vt),fs=o.bJ([],[0,0,1],Gt),Ws=o.cT(fs,Ct,fs),As=es+(oe.pitch===0?0:o.bf(Ct,Ws)),gn=oe.globeCenterInViewSpace,an=o.ax([],Ct,[gn[0],gn[1],gn[2]]);o.ay(an,an),o.bJ(an,an,As);const Dn=o.cT([],Ct,an);o.ah(Dn,Dn,ss);const Gn=o.eD/o.aF,en=o.ai(Dn),Ms=o.bU(Math.max(en*Gn-o.eD,Number.EPSILON),0),mn=Math.min(oe.zoomFromMercatorZAdjusted(Ms),xe.maxZoom);return mn>.5*(o.cJ+o.cv)?(oe.setProjection({name:"mercator"}),oe.zoom=mn,this._cameraForBounds(oe,E,F,H,Z,X)):{center:oe.center,zoom:mn,bearing:H,pitch:Z}}_extendAABB(w,E,F,H){const Z=.5*((F.padding.left||0)+(F.padding.right||0)),X=.5*((F.padding.top||0)+(F.padding.bottom||0)),oe=X,xe=Z,Ne=Z,Le=X,We=E.width-(xe+Ne),He=E.height-(oe+Le),tt=o.ax([],w.max,w.min),dt=Math.min(We/tt[0],He/tt[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]-xe*jt,w.min[1]-Le*jt,w.min[2]],[w.max[0]+Ne*jt,w.max[1]+oe*jt,w.max[2]]),Ot=(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(H));return wt.center[0]-=Ot.x*jt,wt.center[1]+=Ot.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,H,Z,X){if(w.projection.name==="globe")return this._cameraForBoundsOnGlobe(w,E,F,H,Z,X);const oe=w.clone(),xe=this._extendCameraOptions(X);oe.bearing=H,oe.pitch=Z;const Ne=o.aU.convert(E),Le=o.aU.convert(F),We=new o.aU(Ne.lng,Le.lat),He=new o.aU(Le.lng,Ne.lat),tt=oe.project(Ne),dt=oe.project(Le),it=this.queryTerrainElevation(Ne),jt=this.queryTerrainElevation(Le),wt=this.queryTerrainElevation(We),Ot=this.queryTerrainElevation(He),Vt=[[tt.x,tt.y,Math.min(it||0,jt||0,wt||0,Ot||0)],[dt.x,dt.y,Math.max(it||0,jt||0,wt||0,Ot||0)]];let Ct=o.cU.fromPoints(Vt);const ks=oe.getWorldToCameraMatrix(),ss=o.b7(new Float64Array(16),ks);Ct=o.cU.applyTransform(Ct,ks);const Ns=this._extendAABB(Ct,oe,xe,H);if(!Ns)return void o.w("Map cannot fit within canvas with the given bounds, padding, and/or offset.");Ct=Ns;const Gt=.5*o.ax([],Ct.max,Ct.min)[2],es=this._minimumAABBFrustumDistance(oe,Ct),fs=[0,0,1,0];o.aE(fs,fs,ks),o.eX(fs,fs);const Ws=o.bJ([],fs,es+Gt),As=o.cT([],Ct.center,Ws);o.ah(Ct.center,Ct.center,ss),o.ah(As,As,ss);const gn=oe.unproject(new o.P(Ct.center[0],Ct.center[1])),an=o.eY(oe.projection,gn),Dn=Math.pow(2,an),Gn=Math.min(oe._zoomFromMercatorZ(As[2]*oe.pixelsPerMeter*Dn/oe.worldSize),xe.maxZoom);return oe.mercatorFromTransition&&Gn<.5*(o.cJ+o.cv)?(oe.setProjection({name:"globe"}),oe.zoom=Gn,this._cameraForBounds(oe,E,F,H,Z,X)):{center:gn,zoom:Gn,bearing:H,pitch:Z}}fitBounds(w,E,F){const H=this.cameraForBounds(w,E);return this._fitInternal(H,E,F)}fitScreenCoordinates(w,E,F,H,Z){const X=o.P.convert(w),oe=o.P.convert(E),xe=new o.P(Math.min(X.x,oe.x),Math.min(X.y,oe.y)),Ne=new o.P(Math.max(X.x,oe.x),Math.max(X.y,oe.y));if(this.transform.projection.name==="mercator"&&this.transform.anyCornerOffEdge(X,oe))return this;const Le=this.transform.pointLocation3D(xe),We=this.transform.pointLocation3D(Ne),He=this.transform.pointLocation3D(new o.P(xe.x,Ne.y)),tt=this.transform.pointLocation3D(new o.P(Ne.x,xe.y)),dt=[Math.min(Le.lng,We.lng,He.lng,tt.lng),Math.min(Le.lat,We.lat,He.lat,tt.lat)],it=[Math.max(Le.lng,We.lng,He.lng,tt.lng),Math.max(Le.lat,We.lat,He.lat,tt.lat)],jt=H&&H.pitch?H.pitch:this.getPitch(),wt=this._cameraForBounds(this.transform,dt,it,F,jt,H);return this._fitInternal(wt,H,Z)}_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 H=!1,Z=!1,X=!1;"zoom"in w&&F.zoom!==+w.zoom&&(H=!0,F.zoom=+w.zoom),w.center!==void 0&&(F.center=o.aU.convert(w.center)),"bearing"in w&&F.bearing!==+w.bearing&&(Z=!0,F.bearing=+w.bearing),"pitch"in w&&F.pitch!==+w.pitch&&(X=!0,F.pitch=+w.pitch);const oe=typeof w.padding=="number"?this._extendPadding(w.padding):w.padding;if(w.padding!=null&&!F.isPaddingEqual(oe))if(w.retainPadding===!1){const xe=F.clone();xe.padding=oe,F.setLocationAtPoint(F.center,xe.centerPoint)}else F.padding=oe;return w.preloadOnly?(this._preloadTiles(F),this):(this.fire(new o.C("movestart",E)).fire(new o.C("move",E)),H&&this.fire(new o.C("zoomstart",E)).fire(new o.C("zoom",E)).fire(new o.C("zoomend",E)),Z&&this.fire(new o.C("rotatestart",E)).fire(new o.C("rotate",E)).fire(new o.C("rotateend",E)),X&&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(qV),this.transform.getFreeCameraOptions()}setFreeCameraOptions(w,E){const F=this.transform;if(!F.projection.supportsFreeCamera)return o.w(qV),this;this.stop();const H=F.zoom,Z=F.pitch,X=F.bearing;F.setFreeCameraOptions(w);const oe=H!==F.zoom,xe=Z!==F.pitch,Ne=X!==F.bearing;return this.fire(new o.C("movestart",E)).fire(new o.C("move",E)),oe&&this.fire(new o.C("zoomstart",E)).fire(new o.C("zoom",E)).fire(new o.C("zoomend",E)),Ne&&this.fire(new o.C("rotatestart",E)).fire(new o.C("rotate",E)).fire(new o.C("rotateend",E)),xe&&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,H=this.getZoom(),Z=this.getBearing(),X=this.getPitch(),oe=this.getPadding(),xe="zoom"in w?+w.zoom:H,Ne="bearing"in w?this._normalizeBearing(w.bearing,Z):Z,Le="pitch"in w?+w.pitch:X,We=this._extendPadding(w.padding),He=o.P.convert(w.offset);let tt,dt,it;if(F.projection.name==="globe"){const fs=o.ag.fromLngLat(F.center),Ws=He.rotate(-F.angle);fs.x+=Ws.x/F.worldSize,fs.y+=Ws.y/F.worldSize;const As=fs.toLngLat(),gn=o.aU.convert(w.center||As);this._normalizeCenter(gn),tt=F.centerPoint.add(Ws),dt=new o.P(fs.x,fs.y).mult(F.worldSize),it=new o.P(o.aH(gn.lng),o.aL(gn.lat)).mult(F.worldSize).sub(dt)}else{tt=F.centerPoint.add(He);const fs=F.pointLocation(tt),Ws=o.aU.convert(w.center||fs);this._normalizeCenter(Ws),dt=F.project(fs),it=F.project(Ws).sub(dt)}const jt=F.zoomScale(xe-H);let wt,Ot;w.around&&(wt=o.aU.convert(w.around),Ot=F.locationPoint(wt));const Vt=this._zooming||xe!==H,Ct=this._rotating||Z!==Ne,ks=this._pitching||Le!==X,ss=!F.isPaddingEqual(We),Ns=w.retainPadding===!1?F.clone():F,Gt=fs=>Ws=>{if(Vt&&(fs.zoom=o.am(H,xe,Ws)),Ct&&(fs.bearing=o.am(Z,Ne,Ws)),ks&&(fs.pitch=o.am(X,Le,Ws)),ss&&(Ns.interpolatePadding(oe,We,Ws),tt=Ns.centerPoint.add(He)),wt)fs.setLocationAtPoint(wt,Ot);else{const As=fs.zoomScale(fs.zoom-H),gn=xe>H?Math.min(2,jt):Math.max(.5,jt),an=Math.pow(gn,1-Ws),Dn=fs.unproject(dt.add(it.mult(Ws*an)).mult(As));fs.setLocationAtPoint(fs.renderWorldCopies?Dn.wrap():Dn,tt)}return w.preloadOnly||this._fireMoveEvents(E),fs};if(w.preloadOnly){const fs=this._emulate(Gt,w.duration,F);return this._preloadTiles(fs),this}const es={moving:this._moving,zooming:this._zooming,rotating:this._rotating,pitching:this._pitching};return this._zooming=Vt,this._rotating=Ct,this._pitching=ks,this._padding=ss,this._easeId=w.easeId,this._prepareEase(E,w.noMoveStart,es),this._ease(Gt(F),fs=>{F.cameraElevationReference==="sea"&&F.recenterOnTerrain(),this._afterEase(E,fs)},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,H=this._rotating,Z=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)),H&&this.fire(new o.C("rotateend",w)),Z&&this.fire(new o.C("pitchend",w)),this.fire(new o.C("moveend",w))}flyTo(w,E){if(this._prefersReducedMotion(w)){const vn=o.aJ(w,["center","zoom","bearing","pitch","around","padding","retainPadding"]);return this.jumpTo(vn,E)}this.stop(),w=Object.assign({offset:[0,0],speed:1.2,curve:1.42,easing:o.eP},w);const F=this.transform,H=this.getZoom(),Z=this.getBearing(),X=this.getPitch(),oe=this.getPadding(),xe="zoom"in w?o.aC(+w.zoom,F.minZoom,F.maxZoom):H,Ne="bearing"in w?this._normalizeBearing(w.bearing,Z):Z,Le="pitch"in w?+w.pitch:X,We=this._extendPadding(w.padding),He=F.zoomScale(xe-H),tt=o.P.convert(w.offset);let dt=F.centerPoint.add(tt);const it=F.pointLocation(dt),jt=o.aU.convert(w.center||it);this._normalizeCenter(jt);const wt=F.project(it),Ot=F.project(jt).sub(wt);let Vt=w.curve;const Ct=Math.max(F.width,F.height),ks=Ct/He,ss=Ot.mag();if("minZoom"in w){const vn=o.aC(Math.min(w.minZoom,H,xe),F.minZoom,F.maxZoom),kn=Ct/F.zoomScale(vn-H);Vt=Math.sqrt(kn/ss*2)}const Ns=Vt*Vt;function Gt(vn){const kn=(ks*ks-Ct*Ct+(vn?-1:1)*Ns*Ns*ss*ss)/(2*(vn?ks:Ct)*Ns*ss);return Math.log(Math.sqrt(kn*kn+1)-kn)}function es(vn){return(Math.exp(vn)-Math.exp(-vn))/2}function fs(vn){return(Math.exp(vn)+Math.exp(-vn))/2}const Ws=Gt(0);let As=function(vn){return fs(Ws)/fs(Ws+Vt*vn)},gn=function(vn){return Ct*((fs(Ws)*(es(kn=Ws+Vt*vn)/fs(kn))-es(Ws))/Ns)/ss;var kn},an=(Gt(1)-Ws)/Vt;if(Math.abs(ss)<1e-6||!isFinite(an)){if(Math.abs(Ct-ks)<1e-6)return this.easeTo(w,E);const vn=ksw.maxDuration&&(w.duration=0);const Dn=Z!==Ne,Gn=Le!==X,en=!F.isPaddingEqual(We),Ms=w.retainPadding===!1?F.clone():F,mn=vn=>kn=>{const _r=kn*an,cr=1/As(_r);vn.zoom=kn===1?xe:H+vn.scaleZoom(cr),Dn&&(vn.bearing=o.am(Z,Ne,kn)),Gn&&(vn.pitch=o.am(X,Le,kn)),en&&(Ms.interpolatePadding(oe,We,kn),dt=Ms.centerPoint.add(tt));const dr=kn===1?jt:vn.unproject(wt.add(Ot.mult(gn(_r))).mult(cr));return vn.setLocationAtPoint(vn.renderWorldCopies?dr.wrap():dr,dt),vn._updateCameraOnTerrain(),w.preloadOnly||this._fireMoveEvents(E),vn};if(w.preloadOnly){const vn=this._emulate(mn,w.duration,F);return this._preloadTiles(vn),this}return this._zooming=!0,this._rotating=Dn,this._pitching=Gn,this._padding=en,this._prepareEase(E,!1),this._ease(mn(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 H=Math.ceil(15*E/1e3),Z=[],X=w(F.clone());for(let oe=0;oe<=H;oe++){const xe=X(oe/H);Z.push(xe.clone())}return Z}_preloadTiles(w,E){}}class VV{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=g("div","mapboxgl-ctrl mapboxgl-ctrl-attrib"),this._compactButton=g("button","mapboxgl-ctrl-attrib-button",this._container),this._compactButton.type="button",this._compactButton.addEventListener("click",this._toggleAttribution),this._compactButton.setAttribute("aria-label",F);const H=g("span","mapboxgl-ctrl-icon",this._compactButton);return H.setAttribute("aria-hidden","true"),H.setAttribute("title",F),this._innerContainer=g("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((H,Z,X)=>(Z.value&&(H+=`${Z.key}=${Z.value}${XH.length-Z.length),w=w.filter((H,Z)=>{for(let X=Z+1;X=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(H=>function(Z){const X=new DOMParser().parseFromString(Z,"text/html");return Array.from(X.body.querySelectorAll("*")).reverse().forEach(oe=>{const xe=oe.textContent||"";if(oe.tagName!=="A")return void oe.replaceWith(...oe.childNodes);const Ne=oe.getAttribute("href");if(!Ne||!/^(https?:|mailto:)/i.test(Ne))return void oe.replaceWith(X.createTextNode(xe));const Le=X.createElement("a");Le.href=Ne,Le.textContent=xe,Le.rel="noopener nofollow";const We=oe.getAttribute("class");We&&(Le.className=We),oe.replaceWith(Le)}),X.body.innerHTML}(H)).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 HV{constructor(){o.aZ(["_updateLogo","_updateCompact"],this)}onAdd(w){this._map=w,this._container=g("div","mapboxgl-ctrl");const E=g("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 Tte{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 H of F)if(H.id===w)return void(H.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 ZTe{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 XTe={"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 sc extends o.C{constructor(w,E,F,H){const{point:Z,lngLat:X,originalEvent:oe,target:xe}=w;super(w.type,{point:Z,lngLat:X,originalEvent:oe,target:xe}),this.preventDefault=()=>{w.preventDefault()},this.id=E,this.interaction=F,this.feature=H}}class IF{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 H=E.type;F&&this.filters.set(w,o.dg(F)),H==="mouseover"&&(H="mouseenter"),H==="mouseout"&&(H="mouseleave");const Z=this.interactionsByType.get(H)||new Map;H==="mouseenter"||H==="mouseleave"?(this.delegatedInteractions.size===0&&(this.map.on("mousemove",this.handleMove),this.map.on("mouseout",this.handleOut)),this.delegatedInteractions.set(w,E)):Z.size===0&&this.map.on(H,this.handleType),Z.size===0&&this.interactionsByType.set(H,Z),Z.set(w,E),this.typeById.set(w,H)}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[H,Z]of E)Z.target&&F.push({targetId:H,target:Z.target,filter:this.filters.get(H)});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[H,{feature:Z}]of this.prevHoveredFeatures)this.hoveredFeatures.has(H)||F.set(Z.id,Z);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 H=Array.from(this.interactionsByType.get(w.type)).reverse(),Z=!!E;E=E||this.queryTargets(w.point,H);let X=!1;const oe=new Set;for(const xe of E){for(const[Ne,Le]of H){if(!Le.target)continue;const We=xe.variants?xe.variants[Ne]:null;if(We){for(const He of We){if(eh(He,xe,oe,Ne))continue;const tt=new o.di(xe,He),dt=Lf(He,xe,Ne);Z&&tt.id!==void 0&&(tt.state=this.map.getFeatureState(tt));const it=F?this.prevHoveredFeatures.get(dt):null,jt=new sc(w,Ne,Le,tt),wt=it?it.stop:Le.handler(jt);if(F&&this.hoveredFeatures.set(dt,{feature:xe,stop:wt}),wt!==!1){X=!0;break}}if(X)break}}if(X)break}if(!X)for(const[xe,Ne]of H){const{handler:Le,target:We}=Ne;if(!We&&Le(new sc(w,xe,Ne,null))!==!1)break}}}function QTe(R,w){if(Array.isArray(R)&&Array.isArray(w)){const E=new Set(R),F=new Set(w);return E.size===F.size&&R.every(H=>F.has(H))}return o.b6(R,w)}const JTe={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},e6e={showCompass:!0,showZoom:!0,visualizePitch:!1};class yM{constructor(w,E,F=!1){this._clickTolerance=10,this.element=E,this.mouseRotate=new AF({clickTolerance:w.dragRotate._mouseRotate._clickTolerance}),this.map=w,F&&(this.mousePitch=new mM({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),C()}move(w,E){const F=this.map,H=this.mouseRotate.mousemoveWindow(w,E),Z=H&&H.bearingDelta;if(Z&&F.setBearing(F.getBearing()+Z),this.mousePitch){const X=this.mousePitch.mousemoveWindow(w,E),oe=X&&X.pitchDelta;oe&&F.setPitch(F.getPitch()+oe)}}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(R);if(F.x>=0&&F.y>=0&&F.x<=E.width&&F.y<=E.height)break;R.lng>E.center.lng?R.lng-=360:R.lng+=360}return R}const vM={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%)"},Pv={rotation:0,rotationAlignment:"auto",pitchAlignment:"auto",occludedOpacity:.2,altitude:0};class Y1 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:H="#3FB1CE",scale:Z=1,draggable:X=!1,clickTolerance:oe=0,rotation:xe=Pv.rotation,rotationAlignment:Ne=Pv.rotationAlignment,pitchAlignment:Le=Pv.pitchAlignment,occludedOpacity:We=Pv.occludedOpacity,altitude:He=Pv.altitude}=w||{};this._anchor=F,this._color=H,this._scale=Z,this._draggable=X,this._clickTolerance=oe,this._rotation=xe,this._rotationAlignment=Ne,this._pitchAlignment=Le,this._occludedOpacity=We,this._altitude=He,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 tt=this._element.classList;for(const it in vM)tt.remove(`mapboxgl-marker-anchor-${it}`);tt.add(`mapboxgl-marker-anchor-${this._anchor}`);const dt=w&&w.className?w.className.trim().split(/\s+/):[];tt.add(...dt),this._popup=null}_createDefaultMarker(){const w=g("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||Pv.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 H=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":[H,-1*(38.1-13.5+H)],"bottom-right":[-H,-1*(38.1-13.5+H)],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),H=w.getFreeCameraOptions();if(!H.position)return!1;const Z=H.position.toLngLat();return Z.distanceTo(F)<.9*Z.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 H;w._showingGlobe()&&o.e$(w.transform,this._lngLat)?H=0:(H=1-w._queryFogOpacity(F),w.transform._terrainEnabled()&&w.getTerrain()&&this._behindTerrain()&&(H*=this._occludedOpacity)),this._element.style.opacity=`${H}`,this._element.style.pointerEvents=H>0?"auto":"none",this._popup&&this._popup._setOpacity(H),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) ${vM[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 xe=E.getPitch();return xe?`rotateX(${xe}deg)`:""}const H=o.cH(o.f0(E.transform,this._lngLat)),Z=w.sub(o.f1(E.transform)),X=Math.abs(Z.x)+Math.abs(Z.y);if(X===0)return"";const oe=H/X;return`rotateX(${-Z.y*oe}deg) rotateY(${Z.x*oe}deg)`}_calculateZTransform(){const w=this._pos,E=this._map;if(!E||!w)return"";let F=0;const H=this.getRotationAlignment();if(H==="map")if(E._showingGlobe()){const Z=E.project(new o.aU(this._lngLat.lng,this._lngLat.lat+.001),this._altitude),X=E.project(new o.aU(this._lngLat.lng,this._lngLat.lat-.001),this._altitude).sub(Z);F=o.cH(Math.atan2(X.y,X.x))-90}else F=-E.getBearing();else if(H==="horizon"){const Z=o.aj(4,6,E.getZoom()),X=o.f1(E.transform);X.y+=Z*E.transform.height;const oe=w.sub(X),xe=o.cH(Math.atan2(oe.y,oe.x));F=(xe>90?xe-270:xe+90)*(1-Z)}return F+=this._rotation,F?`rotateZ(${F}deg)`:""}_update(w){cancelAnimationFrame(this._updateFrameId);const E=this._map;E&&(E.transform.renderWorldCopies&&(this._lngLat=GV(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,H=this._positionDelta;if(F&&H){if(!this._isDragging){const Z=this._clickTolerance||E._clickTolerance;if(w.point.dist(F)R.maxZoom)throw new Error("maxZoom must be greater than or equal to minZoom");if(R.minPitch!=null&&R.maxPitch!=null&&R.minPitch>R.maxPitch)throw new Error("maxPitch must be greater than or equal to minPitch");if(R.minPitch!=null&&R.minPitch<0)throw new Error("minPitch must be greater than or equal to 0");if(R.maxPitch!=null&&R.maxPitch>85)throw new Error("maxPitch must be less than or equal to 85");R.antialias&&o.eZ(window)&&(R.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 yu(R.minZoom,R.maxZoom,R.minPitch,R.maxPitch,R.renderWorldCopies,null,null),R),this._repaint=!!R.repaint,this._interactive=R.interactive,this._minTileCacheSize=R.minTileCacheSize,this._maxTileCacheSize=R.maxTileCacheSize,this._failIfMajorPerformanceCaveat=R.failIfMajorPerformanceCaveat,this._preserveDrawingBuffer=R.preserveDrawingBuffer,this._antialias=R.antialias,this._trackResize=R.trackResize,this._bearingSnap=R.bearingSnap,this._refreshExpiredTiles=R.refreshExpiredTiles,this._fadeDuration=R.fadeDuration,this._isInitialLoad=!0,this._crossSourceCollisions=R.crossSourceCollisions,this._collectResourceTiming=R.collectResourceTiming,this._language=this._parseLanguage(R.language),this._worldview=R.worldview,this._renderTaskQueue=new Tte,this._domRenderTaskQueue=new Tte,this._controls=[],this._markers=[],this._popups=[],this._mapId=o.r(),this._locale=Object.assign({},XTe,R.locale),this._clickTolerance=R.clickTolerance,this._cooperativeGestures=R.cooperativeGestures,this._performanceMetricsCollection=R.performanceMetricsCollection,this._tessellationStep=R.tessellationStep,this._containerWidth=0,this._containerHeight=0,this._showParseStatus=!0,this._precompilePrograms=R.precompilePrograms,this._averageElevationLastSampledAt=-1/0,this._averageElevationExaggeration=0,this._averageElevation=new ZTe(0),this._interactionRange=[1/0,-1/0],this._visibilityHidden=0,this._useExplicitProjection=!1,this._frameId=0,this._scaleFactor=R.scaleFactor,this._requestManager=new V(R.transformRequest,R.accessToken,R.testMode);const E=ue(R.accessToken||o.g.ACCESS_TOKEN);if(E&&"atlas"in E&&typeof E.atlas=="number"&&(this._tokenExpiration=E.atlas),this._silenceAuthErrors=!!R.testMode,this._contextCreateOptions=R.contextCreateOptions?Object.assign({},R.contextCreateOptions):{},typeof R.container=="string"){const F=document.getElementById(R.container);if(!F)throw new Error(`Container '${R.container.toString()}' not found.`);this._container=F}else{if(!(R.container instanceof HTMLElement))throw new Error("Invalid type: 'container' must be a String or HTMLElement.");this._container=R.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."),R.maxBounds&&this.setMaxBounds(R.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 Ate(this,R),this._localFontFamily=R.localFontFamily,this._localIdeographFontFamily=R.localIdeographFontFamily,this._useServerFontComposition=R.useServerFontComposition,(R.style||!R.testMode)&&this.setStyle(R.style||o.g.DEFAULT_STYLE,{config:R.config,localFontFamily:this._localFontFamily,localIdeographFontFamily:this._localIdeographFontFamily,useServerFontComposition:this._useServerFontComposition}),R.projection&&this.setProjection(R.projection),R.hash&&(this._hash=new Ou(typeof R.hash=="string"&&R.hash||void 0).addTo(this)),!this._hash||!this._hash._onHashChange()){w.center==null&&w.zoom==null||(this.transform._unmodified=!1),this.jumpTo({center:R.center,zoom:R.zoom,bearing:R.bearing,pitch:R.pitch});const F=R.bounds;F&&(this.resize(),this.fitBounds(F,Object.assign({},R.fitBoundsOptions,{duration:0})))}this.resize(),R.attributionControl&&this.addControl(new VV({customAttribution:R.customAttribution})),this._logoControl=new HV,this.addControl(this._logoControl,R.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 IF(this)}_getMapId(){return this._mapId}addControl(R,w){if(w===void 0&&(w=R.getDefaultPosition?R.getDefaultPosition():"top-right"),!R||!R.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=R.onAdd(this);this._controls.push(R);const F=this._controlPositions[w];return w.indexOf("bottom")!==-1?F.insertBefore(E,F.firstChild):F.appendChild(E),this}removeControl(R){if(!R||!R.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(R);return w>-1&&this._controls.splice(w,1),R.onRemove(this),this}hasControl(R){return this._controls.indexOf(R)>-1}getContainer(){return this._container}getCanvasContainer(){return this._canvasContainer}getCanvas(){return this._canvas}resize(R){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",R)).fire(new o.C("move",R)),this.fire(new o.C("resize",R)),w&&this.fire(new o.C("moveend",R)),this}getBounds(){return this.transform.getBounds()}getMaxBounds(){return this.transform.getMaxBounds()||null}setMaxBounds(R){return this.transform.setMaxBounds(o.aK.convert(R)),this._update()}setMinZoom(R){if((R=R??-2)>=-2&&R<=this.transform.maxZoom)return this.transform.minZoom=R,this._update(),this.getZoom()=this.transform.minZoom)return this.transform.maxZoom=R,this._update(),this.getZoom()>R?this.setZoom(R):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(R){if((R=R??0)<0)throw new Error("minPitch must be greater than or equal to 0");if(R>=0&&R<=this.transform.maxPitch)return this.transform.minPitch=R,this._update(),this.getPitch()85)throw new Error("maxPitch must be less than or equal to 85");if(R>=this.transform.minPitch)return this.transform.maxPitch=R,this._update(),this.getPitch()>R?this.setPitch(R):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(R){return this._scaleFactor=R,this.painter.scaleFactor=R,this.style&&this.style._setLabelPlacementStale(),this.style._updateFilteredLayers(w=>w.type==="symbol"),this._update(!0),this}getRenderWorldCopies(){return this.transform.renderWorldCopies}setRenderWorldCopies(R){return this.transform.renderWorldCopies=R,this.transform.renderWorldCopies||this._forceMarkerAndPopupUpdate(!0),this._update()}getLanguage(){return this._language}_parseLanguage(R){return R==="auto"?navigator.language:Array.isArray(R)?R.length===0?void 0:R.map(w=>w==="auto"?navigator.language:w):R}setLanguage(R){const w=this._parseLanguage(R);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(R){return this.style&&R!==this._worldview?(this._worldview=R,this._styleDirty=!0,this.style.setWorldview(R),this):this}getProjection(){return this.transform.mercatorFromTransition?{name:"globe",center:[0,0]}:this.transform.getProjection()}_showingGlobe(){return this.transform.projection.name==="globe"}setProjection(R){return this._lazyInitEmptyStyle(),R?typeof R=="string"&&(R={name:R}):R=null,this._useExplicitProjection=!!R,this._prioritizeAndUpdateProjection(R,this.style.projection)}_updateProjectionTransition(){if(this.getProjection().name!=="globe")return;const R=this.transform,w=R.projection.name;let E;w==="globe"&&R.zoom>=o.cv?(R.setMercatorFromTransition(),E=!0):w==="mercator"&&R.zoom=o.cv?this.transform.setMercatorFromTransition():this.transform.setProjection(R),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(R,w){return this.transform.locationPoint3D(o.aU.convert(R),w)}unproject(R,w){return this.transform.pointLocation3D(o.P.convert(R),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(R,w,E){const F=H=>{let Z=[];if(Array.isArray(w)){const X=w.filter(oe=>this.getLayer(oe));Z=X.length?this.queryRenderedFeatures(H,{layers:X}):[]}else Z=this.queryRenderedFeatures(H,{target:w});return Z};if(R==="mouseenter"||R==="mouseover"){let H=!1;return{listener:E,targets:w,delegates:{mousemove:X=>{const oe=F(X.point);oe.length?H||(H=!0,E.call(this,new so(R,this,X.originalEvent,{features:oe}))):H=!1},mouseout:()=>{H=!1}}}}if(R==="mouseleave"||R==="mouseout"){let H=!1;return{listener:E,targets:w,delegates:{mousemove:oe=>{F(oe.point).length?H=!0:H&&(H=!1,E.call(this,new so(R,this,oe.originalEvent)))},mouseout:oe=>{H&&(H=!1,E.call(this,new so(R,this,oe.originalEvent)))}}}}{const H=Z=>{const X=F(Z.point);X.length&&(Z.features=X,E.call(this,Z),delete Z.features)};return{listener:E,targets:w,delegates:{[R]:H}}}}on(R,w,E){if(typeof w=="function"||E===void 0)return super.on(R,w);if(typeof w=="string"&&(w=[w]),!this._areTargetsValid(w))return this;const F=this._createDelegatedListener(R,w,E);this._delegatedListeners=this._delegatedListeners||{},this._delegatedListeners[R]=this._delegatedListeners[R]||[],this._delegatedListeners[R].push(F);for(const H in F.delegates)this.on(H,F.delegates[H]);return this}once(R,w,E){if(typeof w=="function"||E===void 0)return super.once(R,w);if(typeof w=="string"&&(w=[w]),!this._areTargetsValid(w))return this;const F=this._createDelegatedListener(R,w,E);for(const H in F.delegates)this.once(H,F.delegates[H]);return this}off(R,w,E){if(typeof w=="function"||E===void 0)return super.off(R,w);if(typeof w=="string"&&(w=[w]),!this._areTargetsValid(w))return this;const F=this._delegatedListeners?this._delegatedListeners[R]:void 0;return F&&(H=>{for(let Z=0;Z{if(E){const H=typeof E=="string"?E:E instanceof Error?E.message:E.error;o.w(`Unable to perform style diff: ${H}. Rebuilding the style from scratch.`),this._updateStyle(R,w)}else F&&this._update(!0)},()=>this._postStyleLoadEvent()),this):(this._localIdeographFontFamily=w.localIdeographFontFamily,this._localFontFamily=w.localFontFamily,this._updateStyle(R,w))}_getUIString(R){const w=this._locale[R];if(w==null)throw new Error(`Missing UI string '${R}'`);return w}_updateStyle(R,w){if(this.style&&(this.style.setEventedParent(null),this.style._remove(),this.style=void 0),R){const E=Object.assign({},w);w&&w.config&&(E.initialConfig=w.config,delete E.config),this.style=new bu(this,E).load(R),this.style.setEventedParent(this,{style:this.style})}return this._updateTerrain(),this}_lazyInitEmptyStyle(){this.style||(this.style=new bu(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(R){return R==null?(this.fire(new o.B(new Error("IDs can't be empty."))),!1):!o.db(R)||(this.fire(new o.B(new Error(`IDs can't contain special symbols: "${R}".`))),!1)}_isTargetValid(R){return"featuresetId"in R?this._isValidId("importId"in R?R.importId:R.featuresetId):"layerId"in R&&this._isValidId(R.layerId)}_areTargetsValid(R){if(Array.isArray(R)){for(const w of R)if(!this._isValidId(w))return!1;return!0}return this._isTargetValid(R)}addSource(R,w){return this._isValidId(R)?(this._lazyInitEmptyStyle(),this.style.addSource(R,w),this._update(!0)):this}isSourceLoaded(R){return!!this._isValidId(R)&&!!this.style&&this.style._isSourceCacheLoaded(R)}areTilesLoaded(){return this.style.areTilesLoaded()}addSourceType(R,w,E){this._lazyInitEmptyStyle(),this.style.addSourceType(R,w,E)}removeSource(R){return this._isValidId(R)?(this.style.removeSource(R),this._updateTerrain(),this._update(!0)):this}getSource(R){return this._isValidId(R)?this.style.getOwnSource(R):null}addImage(R,w,{pixelRatio:E=1,sdf:F=!1,stretchX:H,stretchY:Z,content:X}={}){this._lazyInitEmptyStyle();const oe=o.I.from(R);if(w instanceof HTMLImageElement||ImageBitmap&&w instanceof ImageBitmap){const{width:xe,height:Ne,data:Le}=o.o.getImageData(w);this.style.addImage(oe,{data:new o.q({width:xe,height:Ne},Le),pixelRatio:E,stretchX:H,stretchY:Z,content:X,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:xe,height:Ne}=w,Le=w;this.style.addImage(oe,{data:new o.q({width:xe,height:Ne},new Uint8Array(Le.data)),pixelRatio:E,stretchX:H,stretchY:Z,content:X,sdf:F,usvg:!1,version:0,userImage:Le}),Le.onAdd&&Le.onAdd(this,R)}}updateImage(R,w){this._lazyInitEmptyStyle();const E=o.I.from(R),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 H=w instanceof HTMLImageElement||ImageBitmap&&w instanceof ImageBitmap?o.o.getImageData(w):w,{width:Z,height:X,data:oe}=H;if(Z===void 0||X===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(Z!==(F.usvg?F.icon.usvg_tree.width:F.data.width)||X!==(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 (${Z}, ${X}) must be that same as the previous version of the image (${F.data.width}, ${F.data.height})`)));const xe=!(w instanceof HTMLImageElement||ImageBitmap&&w instanceof ImageBitmap);let Ne=!1;F.usvg?(F.data=new o.q({width:Z,height:X},new Uint8Array(oe)),F.usvg=!1,F.icon=void 0,Ne=!0):F.data.replace(oe,xe),this.style.updateImage(E,F,Ne)}hasImage(R){return R?!!this.style&&!!this.style.getImage(o.I.from(R)):(this.fire(new o.B(new Error("Missing required image id"))),!1)}removeImage(R){this.style.removeImage(o.I.from(R))}loadImage(R,w){o.n(this._requestManager.transformRequest(R,o.R.Image),(E,F)=>{w(E,F)})}listImages(){return this.style.listImages().map(R=>R.name)}addModel(R,w){this._lazyInitEmptyStyle(),this.style.addModel(R,w)}hasModel(R){return R?this.style.hasModel(R):(this.fire(new o.B(new Error("Missing required model id"))),!1)}removeModel(R){this.style.removeModel(R)}listModels(){return this.style.listModels()}addLayer(R,w){return this._isValidId(R.id)?(this._lazyInitEmptyStyle(),this.style.addLayer(R,w),this._update(!0)):this}getSlot(R){const w=this.getLayer(R);return w&&w.slot||null}setSlot(R,w){return this.style.setSlot(R,w),this.style.mergeLayers(),this._update(!0)}addImport(R,w){return this.style.addImport(R,w).catch(E=>this.fire(new o.B(new Error("Failed to add import",E)))),this}updateImport(R,w){return typeof w!="string"&&w.id!==R?(this.removeImport(R),this.addImport(w)):(this.style.updateImport(R,w),this._update(!0))}removeImport(R){return this.style.removeImport(R),this}moveImport(R,w){return this.style.moveImport(R,w),this._update(!0)}moveLayer(R,w){return this._isValidId(R)?(this.style.moveLayer(R,w),this._update(!0)):this}removeLayer(R){return this._isValidId(R)?(this.style.removeLayer(R),this._update(!0)):this}getLayer(R){if(!this._isValidId(R))return null;const w=this.style.getOwnLayer(R);return w?w.type==="custom"?w.implementation:w.serialize():void 0}getSlots(){return this.style.getSlots()}setLayerZoomRange(R,w,E){return this._isValidId(R)?(this.style.setLayerZoomRange(R,w,E),this._update(!0)):this}setFilter(R,w,E={}){return this._isValidId(R)?(this.style.setFilter(R,w,E),this._update(!0)):this}getFilter(R){return this._isValidId(R)?this.style.getFilter(R):null}setPaintProperty(R,w,E,F={}){return this._isValidId(R)?(this.style.setPaintProperty(R,w,E,F),this._update(!0)):this}getPaintProperty(R,w){return this._isValidId(R)?this.style.getPaintProperty(R,w):null}setLayoutProperty(R,w,E,F={}){return this._isValidId(R)?(this.style.setLayoutProperty(R,w,E,F),this._update(!0)):this}getLayoutProperty(R,w){return this._isValidId(R)?this.style.getLayoutProperty(R,w):null}setLayerProperty(R,w,E,F={}){return this._isValidId(R)?(w==="appearances"&&this._postAddingAppearancesToStyleEvent(),this.style.setLayerProperty(R,w,E,F),this._update(!0)):this}getGlyphsUrl(){return this.style.getGlyphsUrl()}setGlyphsUrl(R){return this.style.setGlyphsUrl(R),this._update(!0)}getSchema(R){return this.style.getSchema(R)}setSchema(R,w){return this.style.setSchema(R,w),this._update(!0)}getConfig(R){return this.style.getConfig(R)}setConfig(R,w){return this.style.setConfig(R,w),this._update(!0)}getConfigProperty(R,w){return this.style.getConfigProperty(R,w)}setConfigProperty(R,w,E){return this.style.setConfigProperty(R,w,E),this._update(!0)}getFeaturesetDescriptors(R){return this.style.getFeaturesetDescriptors(R)}setLights(R){if(this._lazyInitEmptyStyle(),R&&R.length===1&&R[0].type==="flat"){const w=R[0];w.properties?this.style.setFlatLight(w.properties,w.id,{}):this.style.setFlatLight({},"flat")}else this.style.setLights(R),this.painter.terrain&&(this.painter.terrain.invalidateRenderCache=!0);return this._update(!0)}getLights(){const R=this.style.getLights()||[];return R.length===0&&R.push({id:this.style.light.id,type:"flat",properties:this.style.getFlatLight()}),R}setLight(R,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:R}])}getLight(){return console.log("The `map.getLight` function is deprecated, prefer using `map.getLights` instead."),this.style.getFlatLight()}setTerrain(R){return this._lazyInitEmptyStyle(),!R&&this.transform.projection.requiresDraping?this.style.setTerrainForDraping():this.style.setTerrain(R),this._averageElevationLastSampledAt=-1/0,this._update(!0)}getTerrain(){return this.style?this.style.getTerrain():null}setFog(R){return this._lazyInitEmptyStyle(),this.style.setFog(R),this._update(!0)}getFog(){return this.style?this.style.getFog():null}setSnow(R){return this._lazyInitEmptyStyle(),this.style.setSnow(R),this._update(!0)}getSnow(){return this.style?this.style.getSnow():null}setRain(R){return this._lazyInitEmptyStyle(),this.style.setRain(R),this._update(!0)}getRain(){return this.style?this.style.getRain():null}setColorTheme(R){return this._lazyInitEmptyStyle(),this.style.setColorTheme(R),this._update(!0)}setImportColorTheme(R,w){return this._lazyInitEmptyStyle(),this.style.setImportColorTheme(R,w),this._update(!0)}setCamera(R){return this.style.setCamera(R),this._triggerCameraUpdate(R)}getNearClipOffset(){return this.transform.nearClipOffset}setNearClipOffset(R){const w=this.transform.nearClipOffset!==R;return this.transform.nearClipOffset=R,this._update(w)}_triggerCameraUpdate(R){return this._update(this.transform.setOrthographicProjectionAtLowPitch(R["camera-projection"]==="orthographic"))}getCamera(){return this.style.camera}_queryFogOpacity(R){return this.style&&this.style.fog?this.style.fog.getOpacityAtLatLng(o.aU.convert(R),this.transform):0}setFeatureState(R,w){return R.source&&!this._isValidId(R.source)?this:(this.style.setFeatureState(R,w),this._update())}removeFeatureState(R,w){return R.source&&!this._isValidId(R.source)?this:(this.style.removeFeatureState(R,w),this._update())}getFeatureState(R){return R.source&&!this._isValidId(R.source)?null:this.style.getFeatureState(R)}_selectIndoorFloor(R){this.style.indoorManager.selectFloor(R)}_setIndoorActiveFloorsVisibility(R){this.style.indoorManager.setActiveFloorsVisibility(R)}getIndoorTileOptions(R,w){return this.style.isIndoorEnabled()?this.style.indoorManager.getIndoorTileOptions(R,w):null}_updateContainerDimensions(){if(!this._container)return;const R=this._container.getBoundingClientRect().width||400,w=this._container.getBoundingClientRect().height||300;let E,F,H,Z=this._container;for(;Z&&(!F||!H);){const X=window.getComputedStyle(Z).transform;X&&X!=="none"&&(E=X.match(/matrix.*\((.+)\)/)[1].split(", "),E[0]&&E[0]!=="0"&&E[0]!=="1"&&(F=E[0]),E[3]&&E[3]!=="0"&&E[3]!=="1"&&(H=E[3])),Z=Z.parentElement}this._containerWidth=F?Math.abs(R/F):R,this._containerHeight=H?Math.abs(w/H):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 R=this._container;R.classList.add("mapboxgl-map"),(this._missingCSSCanary=g("div","mapboxgl-canary",R)).style.visibility="hidden",this._detectMissingCSS();const w=this._canvasContainer=g("div","mapboxgl-canvas-container",R);this._canvas=g("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=g("div","mapboxgl-control-container",R),F=this._controlPositions={};["top-left","top","top-right","right","bottom-right","bottom","bottom-left","left"].forEach(H=>{F[H]=g("div",`mapboxgl-ctrl-${H}`,E)}),this._container.addEventListener("scroll",this._onMapScroll,!1)}_resizeCanvas(R,w){const E=o.o.devicePixelRatio||1;this._canvas.width=E*Math.ceil(R),this._canvas.height=E*Math.ceil(w),this._canvas.style.width=`${R}px`,this._canvas.style.height=`${w}px`}_addMarker(R){this._markers.push(R)}_removeMarker(R){const w=this._markers.indexOf(R);w!==-1&&this._markers.splice(w,1)}_addPopup(R){this._popups.push(R)}_removePopup(R){const w=this._popups.indexOf(R);w!==-1&&this._popups.splice(w,1)}_setupPainter(){const R=Object.assign({},x.supported.webGLContextAttributes,{failIfMajorPerformanceCaveat:this._failIfMajorPerformanceCaveat,preserveDrawingBuffer:this._preserveDrawingBuffer,antialias:this._antialias||!1}),w=this._canvas.getContext("webgl2",R);w?(qe(w,!0),this.painter=new Sl(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(R){R.preventDefault(),this._frame&&(this._frame.cancel(),this._frame=null),this.fire(new o.C("webglcontextlost",{originalEvent:R}))}_contextRestored(R){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:R}))}_onMapScroll(R){if(R.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(R){return this.style?(this._styleDirty=this._styleDirty||R,this._sourcesDirty=!0,this.triggerRepaint(),this):this}_requestRenderFrame(R){return this._update(),this._renderTaskQueue.add(R)}_cancelRenderFrame(R){this._renderTaskQueue.remove(R)}_requestDomTask(R){!this.loaded()||this.loaded()&&!this.isMoving()?R():this._domRenderTaskQueue.add(R)}_render(R){let w;this.fire(new o.C("renderstart")),++this._frameId;const E=this.painter.context.extTimerQuery,F=o.o.now(),H=this.painter.context.gl;if(this.listens("gpu-timing-frame")&&(w=H.createQuery(),H.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(R),this._domRenderTaskQueue.run(R),this._removed)return;this._updateProjectionTransition();const Z=this._isInitialLoad?0:this._fadeDuration;if(this.style&&this._styleDirty){this._styleDirty=!1;const xe=this.transform.zoom,Ne=this.transform.pitch,Le=o.o.now(),We=new o.ae(xe,{now:Le,fadeDuration:Z,pitch:Ne,transition:this.style.transition,worldview:this._worldview});this.style.update(We)}this.style&&this.style.hasFogTransition()&&(this.style._markersNeedUpdate=!0,this._sourcesDirty=!0);let X=!1;if(this.style&&this._sourcesDirty?(this._sourcesDirty=!1,this.painter._updateFog(this.style),this._updateTerrain(),X=this._updateAverageElevation(F),this.style.updateSources(this.transform),this.style.updateImageProviders(),this.isMoving()||this._forceMarkerAndPopupUpdate()):X=this._updateAverageElevation(F),this.style&&(this._placementDirty=this.style._updatePlacement(this.painter.transform,this.showCollisionBoxes,Z,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:Z,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 xe=o.o.now()-F;H.endQuery(E.TIME_ELAPSED_EXT),setTimeout(()=>{const Ne=H.getQueryParameter(w,H.QUERY_RESULT)/1e6;H.deleteQuery(w),this.fire(new o.C("gpu-timing-frame",{cpuTime:xe,gpuTime:Ne}))},50)}if(this.listens("gpu-timing-layer")){const xe=this.painter.collectGpuTimers();setTimeout(()=>{const Ne=this.painter.queryGpuTimers(xe);this.fire(new o.C("gpu-timing-layer",{layerTimes:Ne}))},50)}if(this.listens("gpu-timing-deferred-render")){const xe=this.painter.collectDeferredRenderGpuQueries();setTimeout(()=>{const Ne=this.painter.queryGpuTimeDeferredRender(xe);this.fire(new o.C("gpu-timing-deferred-render",{gpuTime:Ne}))},50)}const oe=this._sourcesDirty||this._styleDirty||this._placementDirty||X;if(oe||this._repaint)this.triggerRepaint();else{const xe=this.idle();if(xe&&(X=this._updateAverageElevation(F,!0)),X)this.triggerRepaint();else if(this._triggerFrame(!1),xe&&(this.fire(new o.C("idle")),this._isInitialLoad=!1,this.speedIndexTiming)){const Ne=this._calculateSpeedIndex();this.fire(new o.C("speedindexcompleted",{speedIndex:Ne})),this.speedIndexTiming=!1}}!this._loaded||this._fullyLoaded||oe||(this._fullyLoaded=!0,u.mark(d.fullLoad),this._performanceMetricsCollection&&Se(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(R){for(const w of this._markers)R&&!this.getRenderWorldCopies()&&(w._lngLat=w._lngLat.wrap()),w._update();for(const w of this._popups)!R||this.getRenderWorldCopies()||w._trackPointer||(w._lngLat=w._lngLat.wrap()),w._update()}_updateAverageElevation(R,w=!1){const E=H=>(this.transform.averageElevation=H,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||R-this._averageElevationLastSampledAt>500)&&!this._averageElevation.isEasing(R)){const H=this.transform.averageElevation;let Z=this.transform.sampleAverageElevation();this.transform.elevation!=null&&(this._averageElevationExaggeration=this.transform.elevation.exaggeration()),isNaN(Z)?Z=0:this._averageElevationLastSampledAt=R;const X=Math.abs(H-Z);if(X>1){if(this._isInitialLoad||F)return this._averageElevation.jumpTo(Z),E(Z);this._averageElevation.easeTo(Z,R,300)}else if(X>1e-4)return this._averageElevation.jumpTo(Z),E(Z)}return!!this._averageElevation.isEasing(R)&&E(this._averageElevation.getValue(R))}_isTokenExpired(){return this._tokenExpiration!=null&&Date.now()>this._tokenExpiration}_revokeAuth(){const R=this.painter.context.gl;qe(R,!1),this._logoControl instanceof HV&&this._logoControl._updateLogo(),R&&R.clear(R.DEPTH_BUFFER_BIT|R.COLOR_BUFFER_BIT|R.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(){Ae(this._getMapId(),this._requestManager._skuToken,this._requestManager._customAccessToken,R=>{R&&(R.message!==W&&R.status!==401||this._revokeAuth())}),this._isTokenExpired()&&this._revokeAuth(),fe(this._getMapId(),this._requestManager._skuToken,this._requestManager._customAccessToken,()=>{})}_postStyleLoadEvent(){this.style.globalId&&Ee(this._requestManager._customAccessToken,{map:this,style:this.style.globalId,importedStyles:this.style.getImportGlobalIds()})}_postStyleWithAppearanceEvent(){this.style.globalId&&this.style.hasAppearances()&&De(this._requestManager._customAccessToken)}_postAddingAppearancesToStyleEvent(){ke(this._requestManager._customAccessToken)}_updateTerrain(){const R=this._isDragging();this.painter.updateTerrain(this.style,R)}_calculateSpeedIndex(){const R=this.painter.canvasCopy(),w=this.painter.getCanvasCopiesAndTimestamps();w.timeStamps.push(performance.now());const E=this.painter.context.gl,F=E.createFramebuffer();function H(Z){E.framebufferTexture2D(E.FRAMEBUFFER,E.COLOR_ATTACHMENT0,E.TEXTURE_2D,Z,0);const X=new Uint8Array(E.drawingBufferWidth*E.drawingBufferHeight*4);return E.readPixels(0,0,E.drawingBufferWidth,E.drawingBufferHeight,E.RGBA,E.UNSIGNED_BYTE,X),X}return E.bindFramebuffer(E.FRAMEBUFFER,F),this._canvasPixelComparison(H(R),w.canvasCopies.map(H),w.timeStamps)}_canvasPixelComparison(R,w,E){let F=E[1]-E[0];const H=R.length/4;for(let Z=0;Z{const E=!!this._renderNextFrame;this._frame=null,this._renderNextFrame=null,E&&this._render(w)}))}_preloadTiles(R){const w=this.style?this.style.getSourceCaches():[];return o.t(w,(E,F)=>E._preloadTiles(R,F),()=>{this.triggerRepaint()}),this}_onWindowOnline(){this._update()}_onWindowResize(R){this._trackResize&&this.resize({originalEvent:R})._update()}_onVisibilityChange(){document.visibilityState==="hidden"&&this._visibilityHidden++}get showTileBoundaries(){return!!this._showTileBoundaries}set showTileBoundaries(R){this._showTileBoundaries!==R&&(this._showTileBoundaries=R,this._update())}get showParseStatus(){return!!this._showParseStatus}set showParseStatus(R){this._showParseStatus!==R&&(this._showParseStatus=R,this._update())}get showTerrainWireframe(){return!!this._showTerrainWireframe}set showTerrainWireframe(R){this._showTerrainWireframe!==R&&(this._showTerrainWireframe=R,this._update())}get showLayers2DWireframe(){return!!this._showLayers2DWireframe}set showLayers2DWireframe(R){this._showLayers2DWireframe!==R&&(this._showLayers2DWireframe=R,this._update())}get showLayers3DWireframe(){return!!this._showLayers3DWireframe}set showLayers3DWireframe(R){this._showLayers3DWireframe!==R&&(this._showLayers3DWireframe=R,this._update())}get speedIndexTiming(){return!!this._speedIndexTiming}set speedIndexTiming(R){this._speedIndexTiming!==R&&(this._speedIndexTiming=R,this._update())}get showPadding(){return!!this._showPadding}set showPadding(R){this._showPadding!==R&&(this._showPadding=R,this._update())}get showCollisionBoxes(){return!!this._showCollisionBoxes}set showCollisionBoxes(R){this._showCollisionBoxes!==R&&(this._showCollisionBoxes=R,this.style&&R?this.style._generateCollisionBoxes():this._update())}get showOverdrawInspector(){return!!this._showOverdrawInspector}set showOverdrawInspector(R){this._showOverdrawInspector!==R&&(this._showOverdrawInspector=R,this._update())}get repaint(){return!!this._repaint}set repaint(R){this._repaint!==R&&(this._repaint=R,this.triggerRepaint())}get vertices(){return!!this._vertices}set vertices(R){this._vertices=R,this._update()}get showTileAABBs(){return!!this._showTileAABBs}set showTileAABBs(R){this._showTileAABBs!==R&&(this._showTileAABBs=R,R&&this._update())}_setCacheLimits(R,w){o.e_(R,w)}get version(){return c}},NavigationControl:class{constructor(R={}){this.options=Object.assign({},e6e,R),this._container=g("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})}),g("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})}),g("span","mapboxgl-ctrl-icon",this._zoomOutButton).setAttribute("aria-hidden","true")),this.options.showCompass&&(o.aZ(["_rotateCompassArrow"],this),this._compass=this._createButton("mapboxgl-ctrl-compass",w=>{const E=this._map;E&&(this.options.visualizePitch?E.resetNorthPitch({},{originalEvent:w}):E.resetNorth({},{originalEvent:w}))}),this._compassIcon=g("span","mapboxgl-ctrl-icon",this._compass),this._compassIcon.setAttribute("aria-hidden","true"))}_updateZoomButtons(){const R=this._map;if(!R)return;const w=R.getZoom(),E=w===R.getMaxZoom(),F=w===R.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 R=this._map;if(!R)return;const w=this.options.visualizePitch?`scale(${1/Math.pow(Math.cos(R.transform.pitch*(Math.PI/180)),.5)}) rotateX(${R.transform.pitch}deg) rotateZ(${R.transform.angle*(180/Math.PI)}deg)`:`rotate(${R.transform.angle*(180/Math.PI)}deg)`;R._requestDomTask(()=>{this._compassIcon&&(this._compassIcon.style.transform=w)})}onAdd(R){return this._map=R,this.options.showZoom&&(this._setButtonTitle(this._zoomInButton,"ZoomIn"),this._setButtonTitle(this._zoomOutButton,"ZoomOut"),R.on("zoom",this._updateZoomButtons),this._updateZoomButtons()),this.options.showCompass&&(this._setButtonTitle(this._compass,"ResetBearing"),this.options.visualizePitch&&R.on("pitch",this._rotateCompassArrow),R.on("rotate",this._rotateCompassArrow),this._rotateCompassArrow(),this._handler=new yM(R,this._compass,this.options.visualizePitch)),this._container}onRemove(){const R=this._map;R&&(this._container.remove(),this.options.showZoom&&R.off("zoom",this._updateZoomButtons),this.options.showCompass&&(this.options.visualizePitch&&R.off("pitch",this._rotateCompassArrow),R.off("rotate",this._rotateCompassArrow),this._handler&&this._handler.off(),this._handler=void 0),this._map=void 0)}_createButton(R,w){const E=g("button",R,this._container);return E.type="button",E.addEventListener("click",w),E}_setButtonTitle(R,w){if(!this._map)return;const E=this._map._getUIString(`NavigationControl.${w}`);R.setAttribute("aria-label",E),R.firstElementChild&&R.firstElementChild.setAttribute("title",E)}},GeolocateControl:class extends o.E{constructor(R={}){super();const w=navigator.geolocation;this.options=Object.assign({geolocation:w},bM,R),o.aZ(["_onSuccess","_onError","_onZoom","_finish","_setupUI","_updateCamera","_updateMarker","_updateMarkerRotation","_onDeviceOrientation"],this),this._updateMarkerRotationThrottled=yi(this._updateMarkerRotation,20),this._numberOfWatches=0}onAdd(R){return this._map=R,this._container=g("div","mapboxgl-ctrl mapboxgl-ctrl-group"),this._checkGeolocationSupport(this._setupUI),this._container}onRemove(){this._clearRequestTimeout(),this._geolocationWatchID!==void 0&&(this.options.geolocation.clearWatch(this._geolocationWatchID),this._geolocationWatchID=void 0),this.options.showUserLocation&&this._userLocationDotMarker&&this._userLocationDotMarker.remove(),this.options.showAccuracyCircle&&this._accuracyCircleMarker&&this._accuracyCircleMarker.remove(),this._container.remove(),this._map.off("zoom",this._onZoom),this._map=void 0,this._numberOfWatches=0,this._noTimeout=!1}_checkGeolocationSupport(R){const w=(E=!!this.options.geolocation)=>{this._supportsGeolocation=E,R(E)};this._supportsGeolocation!==void 0?R(this._supportsGeolocation):navigator.permissions!==void 0?navigator.permissions.query({name:"geolocation"}).then(E=>w(E.state!=="denied")).catch(()=>w()):w()}_isOutOfMapMaxBounds(R){const w=this._map.getMaxBounds(),E=R.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(R){if(this._map){if(this._clearRequestTimeout(),this._isOutOfMapMaxBounds(R))return this._setErrorState(),this.fire(new o.C("outofmaxbounds",R)),this._updateMarker(),void this._finish();if(this.options.trackUserLocation)switch(this._lastKnownPosition=R,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(R),this.options.followUserLocation&&(!this.options.trackUserLocation||this._watchState==="ACTIVE_LOCK")&&this._updateCamera(R),this.options.showUserLocation&&this._userLocationDotMarker.removeClassName("mapboxgl-user-location-dot-stale"),this.fire(new o.C("geolocate",Object.assign({coords:R.coords,timestamp:R.timestamp},R.toJSON?{toJSON:R.toJSON.bind(R)}:{}))),this._finish()}}_updateCamera(R){const w=new o.aU(R.coords.longitude,R.coords.latitude),E=R.coords.accuracy,F=this._map.getBearing(),H=Object.assign({bearing:F},this.options.fitBoundsOptions);this._map.fitBounds(w.toBounds(E),H,{geolocateSource:!0})}_updateMarker(R){if(R){const w=new o.aU(R.coords.longitude,R.coords.latitude);this._accuracyCircleMarker.setLngLat(w).addTo(this._map),this._userLocationDotMarker.setLngLat(w).addTo(this._map),this._accuracy=R.coords.accuracy,this.options.showUserLocation&&this.options.showAccuracyCircle&&this._updateCircleRadius()}else this._userLocationDotMarker.remove(),this._accuracyCircleMarker.remove()}_updateCircleRadius(){const R=this._map.transform,w=o.bU(1,R._center.lat)*R.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(R){if(this._map){if(this._clearRequestTimeout(),this.options.trackUserLocation)if(R.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(R.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:R.code,message:R.message,PERMISSION_DENIED:R.PERMISSION_DENIED,POSITION_UNAVAILABLE:R.POSITION_UNAVAILABLE,TIMEOUT:R.TIMEOUT})),this._finish()}}_finish(){this._timeoutId&&clearTimeout(this._timeoutId),this._timeoutId=void 0}_startRequestTimeout(){this._clearRequestTimeout();const R=this.options.positionOptions.timeout;R&&(this._requestTimeoutId=window.setTimeout(()=>{this._onError({code:3,message:"Geolocation request timed out"})},R))}_clearRequestTimeout(){this._requestTimeoutId!==void 0&&(clearTimeout(this._requestTimeoutId),this._requestTimeoutId=void 0)}_setupUI(R){if(this._map!==void 0){if(this._container.addEventListener("contextmenu",w=>w.preventDefault()),this._geolocateButton=g("button","mapboxgl-ctrl-geolocate",this._container),g("span","mapboxgl-ctrl-icon",this._geolocateButton).setAttribute("aria-hidden","true"),this._geolocateButton.type="button",R===!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=g("div","mapboxgl-user-location"),this._dotElement.appendChild(g("div","mapboxgl-user-location-dot")),this._dotElement.appendChild(g("div","mapboxgl-user-location-heading")),this._userLocationDotMarker=new Y1({element:this._dotElement,rotationAlignment:"map",pitchAlignment:"map"}),this._circleElement=g("div","mapboxgl-user-location-accuracy-circle"),this._accuracyCircleMarker=new Y1({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(R){this._userLocationDotMarker&&(R.webkitCompassHeading?this._heading=R.webkitCompassHeading:R.absolute===!0&&(this._heading=-1*R.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 R;this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-waiting"),this._geolocateButton.setAttribute("aria-pressed","true"),this._numberOfWatches++,this._numberOfWatches>1?(R={maximumAge:6e5,timeout:0},this._noTimeout=!0):(R=this.options.positionOptions,this._noTimeout=!1),this._geolocationWatchID=this.options.geolocation.watchPosition(this._onSuccess,this._onError,R),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(R){return this.options.followUserLocation=R??bM.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 R=()=>{const w="ondeviceorientationabsolute"in window?"deviceorientationabsolute":"deviceorientation";window.addEventListener(w,this._onDeviceOrientation)};typeof DeviceOrientationEvent.requestPermission=="function"?DeviceOrientationEvent.requestPermission().then(w=>{w==="granted"&&R()}).catch(console.error):R()}_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:VV,ScaleControl:class{constructor(R={}){this.options=Object.assign({},Fh,R),o.aZ(["_update","_setScale","setUnit"],this)}getDefaultPosition(){return"bottom-left"}_update(){const R=this.options.maxWidth||100,w=this._map,E=w._containerHeight/2,F=w._containerWidth/2-R/2,H=w.unproject([F,E]),Z=w.unproject([F+R,E]),X=H.distanceTo(Z);if(this.options.unit==="imperial"){const oe=3.2808*X;oe>5280?this._setScale(R,oe/5280,"mile"):this._setScale(R,oe,"foot")}else this.options.unit==="nautical"?this._setScale(R,X/1852,"nautical-mile"):X>=1e3?this._setScale(R,X/1e3,"kilometer"):this._setScale(R,X,"meter")}_setScale(R,w,E){this._map._requestDomTask(()=>{const F=function(Z){const X=Math.pow(10,`${Math.floor(Z)}`.length-1);let oe=Z/X;return oe=oe>=10?10:oe>=5?5:oe>=3?3:oe>=2?2:oe>=1?1:function(xe){const Ne=Math.pow(10,Math.ceil(-Math.log(xe)/Math.LN10));return Math.round(xe*Ne)/Ne}(oe),X*oe}(w),H=F/w;this._container.innerHTML=E!=="nautical-mile"?new Intl.NumberFormat(this._language,{style:"unit",unitDisplay:"short",unit:E}).format(F):`${F} ${Z1[E]}`,this._container.style.width=R*H+"px"})}onAdd(R){return this._map=R,this._language=R.getLanguage(),this._container=g("div","mapboxgl-ctrl mapboxgl-ctrl-scale",R.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(R){this._language=R,this._update()}setUnit(R){this.options.unit=R,this._update()}},FullscreenControl:class{constructor(R={}){this._fullscreen=!1,R&&R.container&&(R.container instanceof HTMLElement?this._container=R.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(R){return this._map=R,this._container||(this._container=this._map.getContainer()),this._controlContainer=g("div","mapboxgl-ctrl mapboxgl-ctrl-group"),this._checkFullscreenSupport()?this._setupUI():(this._controlContainer.style.display="none",o.w("This device does not support fullscreen mode.")),this._controlContainer}onRemove(){this._controlContainer.remove(),this._map=null,document.removeEventListener(this._fullscreenchange,this._changeIcon)}_checkFullscreenSupport(){return!(!document.fullscreenEnabled&&!document.webkitFullscreenEnabled)}_setupUI(){const R=this._fullscreenButton=g("button","mapboxgl-ctrl-fullscreen",this._controlContainer);g("span","mapboxgl-ctrl-icon",R).setAttribute("aria-hidden","true"),R.type="button",this._updateTitle(),this._fullscreenButton.addEventListener("click",this._onClickFullscreen),document.addEventListener(this._fullscreenchange,this._changeIcon)}_updateTitle(){const R=this._getTitle();this._fullscreenButton.setAttribute("aria-label",R),this._fullscreenButton.firstElementChild&&this._fullscreenButton.firstElementChild.setAttribute("title",R)}_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(R){return this._map=R,this._container=g("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 R=this._map.style.indoorManager;R.off("selector-update",this._onIndoorUpdate),R.on("selector-update",this._onIndoorUpdate),this._onIndoorUpdate(R.getControlState())}}_createButton(R,w){const E=g("button",R,this._container);return E.type="button",E.addEventListener("click",w),E}_setButtonTitle(R,w){R.setAttribute("aria-label",w),R.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(R){if(!R||!R.floors||R.floors.length===0)return this._model=R,void(this._container.style.display="none");const w=this._model;this._model=R,this._container.style.display="inline-block";const E=!w||w.floors.length!==R.floors.length||w.floors.some((F,H)=>F.id!==R.floors[H].id);if(E&&(this._visibleFloorStart=0,this._lastSelectedFloorId=null),R.selectedFloorId){if(R.selectedFloorId!==this._lastSelectedFloorId||E){const F=R.floors.findIndex(H=>H.id===R.selectedFloorId);if(F!==-1){const H=R.floors.length;let Z,X;H<=5?(Z=0,X=H-1):this._visibleFloorStart===0?(Z=0,X=3):this._visibleFloorStart>=H-3?(Z=H-3-1,X=H-1):(Z=this._visibleFloorStart,X=this._visibleFloorStart+3-1),FX&&(this._visibleFloorStart=F-2)}}this._lastSelectedFloorId=R.selectedFloorId}this._render()}_render(){if(!this._container||!this._model||!this._model.floors)return;this._container.innerHTML="";const R=this._createButton("mapboxgl-ctrl-indoor-toggle",this._toggleIndoor);g("span","mapboxgl-ctrl-icon",R).setAttribute("aria-hidden","true"),this._model.activeFloorsVisible||R.classList.add("mapboxgl-ctrl-level-button-selected"),this._container.appendChild(R);const w=this._model.floors,E=w.length;if(E<=5)return void w.forEach(X=>this._createFloorButton(X));const F=this._visibleFloorStart===0,H=this._visibleFloorStart>=E-3;if(F)this._createFloorButton(w[0]);else{const X=this._createButton("mapboxgl-ctrl-arrow-up",this._scrollUp);g("span","mapboxgl-ctrl-icon",X).setAttribute("aria-hidden","true"),this._container.appendChild(X)}let Z=[];if(Z=F?w.slice(1,4):H?w.slice(this._visibleFloorStart-1,this._visibleFloorStart+3-1):w.slice(this._visibleFloorStart,this._visibleFloorStart+3),Z.forEach(X=>this._createFloorButton(X)),H)this._createFloorButton(w[E-1]);else{const X=this._createButton("mapboxgl-ctrl-arrow-down",this._scrollDown);g("span","mapboxgl-ctrl-icon",X).setAttribute("aria-hidden","true"),this._container.appendChild(X)}}_createFloorButton(R){const w=this._createButton("mapboxgl-ctrl-level-button",()=>{const Z=R.id;this._model&&this._model.selectedFloorId===Z&&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(Z))}),E=(R.name||"").trim(),F=R.zIndex.toString(),H=E?Array.from(E).slice(0,3).join(""):F;this._setButtonTitle(w,H),this._model&&this._model.activeFloorsVisible&&R.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 R=this._model&&this._model.floors||[];if(R.length>3){const w=R.length-3;this._visibleFloorStart===w-1&&(this._visibleFloorStart=w-2)}this._render()}}_scrollDown(){if(this._model&&this._model.floors){const R=this._model.floors.length-3;this._visibleFloorStartR&&(this._visibleFloorStart=R),this._render())}}},Popup:class extends o.E{constructor(R){super(),this.options=Object.assign(Object.create(_M),R),this._altitude=this.options.altitude,o.aZ(["_update","_onClose","remove","_onMouseEvent"],this),this._classList=new Set(R&&R.className?R.className.trim().split(/\s+/):[])}addTo(R){return this._map&&this.remove(),this._map=R,this.options.closeOnClick&&R.on("preclick",this._onClose),this.options.closeOnMove&&R.on("move",this._onClose),R.on("remove",this.remove),this._update(),R._addPopup(this),this._focusFirstElement(),this._trackPointer?(R.on("mousemove",this._onMouseEvent),R.on("mouseup",this._onMouseEvent),R._canvasContainer.classList.add("mapboxgl-track-pointer")):R.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 R=this._map;return R&&(R.off("move",this._update),R.off("move",this._onClose),R.off("preclick",this._onClose),R.off("click",this._onClose),R.off("remove",this.remove),R.off("mousemove",this._onMouseEvent),R.off("mouseup",this._onMouseEvent),R.off("drag",this._onMouseEvent),R._canvasContainer&&R._canvasContainer.classList.remove("mapboxgl-track-pointer"),R._removePopup(this),this._map=void 0),this.fire(new o.C("close")),this}getLngLat(){return this._lngLat}setLngLat(R){this._lngLat=o.aU.convert(R),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(R){return this._altitude=R,this._update(),this}trackPointer(){this._trackPointer=!0,this._pos=null,this._update();const R=this._map;return R&&(R.off("move",this._update),R.on("mousemove",this._onMouseEvent),R.on("drag",this._onMouseEvent),R._canvasContainer.classList.add("mapboxgl-track-pointer")),this}getElement(){return this._container}setText(R){return this.setDOMContent(document.createTextNode(R))}setHTML(R){const w=document.createDocumentFragment(),E=document.createElement("body");let F;for(E.innerHTML=R;F=E.firstChild,F;)w.appendChild(F);return this.setDOMContent(w)}getMaxWidth(){return this._container&&this._container.style.maxWidth}setMaxWidth(R){return this.options.maxWidth=R,this._update(),this}setDOMContent(R){let w=this._content;if(w)for(;w.hasChildNodes();)w.firstChild&&w.removeChild(w.firstChild);else w=this._content=g("div","mapboxgl-popup-content",this._container||void 0);if(w.appendChild(R),this.options.closeButton){const E=this._closeButton=g("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(R){return this._classList.add(R),this._updateClassList(),this}removeClassName(R){return this._classList.delete(R),this._updateClassList(),this}setOffset(R){return this.options.offset=R,this._update(),this}toggleClassName(R){let w;return this._classList.delete(R)?w=!1:(this._classList.add(R),w=!0),this._updateClassList(),w}_onMouseEvent(R){this._update(R.point)}_getAnchor(R){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 H=E.offsetWidth,Z=E.offsetHeight,X=F.xw.transform.width-H/2;if(F.y+Rw.transform.height-Z){if(X)return"bottom-left";if(oe)return"bottom-right"}return X?"left":oe?"right":"bottom"}_updateClassList(){const R=this._container;if(!R)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"),R.className=w.join(" ")}_update(R){const w=this._map,E=this._content;if(!w||!this._lngLat&&!this._trackPointer||!E)return;let F=this._container;if(F||(F=this._container=g("div","mapboxgl-popup",w.getContainer()),this._tip=g("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=GV(this._lngLat,this._pos,w.transform)),!this._trackPointer||R){const H=this._pos=this._trackPointer&&R instanceof o.P?R:w.project(this._lngLat,this._altitude),Z=DF(this.options.offset),X=this._anchor=this._getAnchor(Z.y),oe=DF(this.options.offset,X),xe=H.add(oe).round();w._requestDomTask(()=>{this._container&&X&&(this._container.style.transform=`${vM[X]} translate(${xe.x}px,${xe.y}px)`)})}if(!this._marker&&w._showingGlobe()){const H=o.e$(w.transform,this._lngLat)?0:1;this._setOpacity(H)}this._updateClassList()}_focusFirstElement(){if(!this.options.focusAfterOpen||!this._container)return;const R=this._container.querySelector(t6e);R&&R.focus()}_onClose(){this.remove()}_setOpacity(R){this._container&&(this._container.style.opacity=`${R}`),this._content&&(this._content.style.pointerEvents=R?"auto":"none")}},Marker:Y1,Style:bu,LngLat:o.aU,LngLatBounds:o.aK,Point:o.P,MercatorCoordinate:o.ag,FreeCameraOptions:R0,Evented:o.E,config:o.g,prewarm:function(){Mt().acquire(Qe)},clearPrewarmedResources:function(){const R=ft;R&&(R.isPreloaded()&&R.numActive()===1?(R.release(Qe),ft=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(R){o.g.ACCESS_TOKEN=R},get baseApiUrl(){return o.g.API_URL},set baseApiUrl(R){o.g.API_URL=R},get workerCount(){return Ge.workerCount},set workerCount(R){Ge.workerCount=R},get maxParallelImageRequests(){return o.g.MAX_PARALLEL_IMAGE_REQUESTS},set maxParallelImageRequests(R){o.g.MAX_PARALLEL_IMAGE_REQUESTS=R},clearStorage(R){o.f7(R)},get workerUrl(){return Ue.workerUrl},set workerUrl(R){Ue.workerUrl=R},get workerClass(){return Ue.workerClass},set workerClass(R){Ue.workerClass=R},get workerParams(){return Ue.workerParams},set workerParams(R){Ue.workerParams=R},get dracoUrl(){return o.f6()},set dracoUrl(R){o.g.DRACO_URL=o.o.resolveURL(R)},get meshoptUrl(){return o.f5()},set meshoptUrl(R){const w=o.o.resolveURL(R);o.g.MESHOPT_URL=w,o.g.MESHOPT_SIMD_URL=w},get buildingGenUrl(){return o.f4()},set buildingGenUrl(R){o.g.BUILDING_GEN_URL=o.o.resolveURL(R)},setNow:o.o.setNow,restoreNow:o.o.restoreNow}});var l=a;return l})})(SAt);var u_s=SAt.exports;const Wc=Uc(u_s),uit={coming_soon:"#3B82F6",office_exclusive:"#6366F1",pre_market:"#06B6D4",active:"#10B981",price_improvement:"#F97316",under_contract:"#8B5CF6",sold:"#6B7280"},hit={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 h_s(s){return s>=1e6?`$${(s/1e6).toFixed(1)}M`:`$${(s/1e3).toFixed(0)}K`}function m_s({listings:s,isLoading:t}){const n=Vn(),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 U.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;Wc.accessToken=l;const h=s.filter(x=>x.latitude!=null&&x.longitude!=null);let m=[-98.5795,39.8283],p=4;if(h.length>0){const x=h.reduce((y,b)=>y+b.longitude,0)/h.length,g=h.reduce((y,b)=>y+b.latitude,0)/h.length;m=[x,g],p=h.length===1?12:10}return a.current=new Wc.Map({container:r.current,style:"mapbox://styles/mapbox/light-v11",zoom:p,center:m}),a.current.addControl(new Wc.NavigationControl,"top-right"),()=>{var x;(x=a.current)==null||x.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 C,A,T;const p=uit[m.status]||"#10B981",x=((C=m.photos)==null?void 0:C.find(P=>P.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}`,b=document.createElement("div");b.className="cursor-pointer",b.innerHTML=`
`;const v=new Wc.Popup({offset:25,closeButton:!0,maxWidth:"280px"}).setHTML(`
${x!=null&&x.photo_url?``:""}
${h_s(m.price)}
${m.property_address||""}
${m.city}, ${m.state}
${hit[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 Wc.Marker(b).setLngLat([m.longitude,m.latitude]).setPopup(v).addTo(a.current);i.current.push(N)}),h.length>1){const m=new Wc.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(on,{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(uit).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:hit[h]})]},h))}),e.jsx("div",{ref:r,className:"w-full h-[500px] rounded-lg shadow-lg border border-gray-200"})]})}const GLe={active:"Active",coming_soon:"Coming Soon",office_exclusive:"Office Exclusive",pre_market:"Pre-Market",price_improvement:"Price Improvement",under_contract:"Under Contract",sold:"Sold"},p_s={single_family:"Single Family",condo:"Condo",townhouse:"Townhouse",land:"Land",multi_family:"Multi-Family",luxury:"Luxury",commercial:"Commercial",other:"Other"},v7="#0d0d0d",mit="#1a1a1a",sd="#c9a84c",nA="#f0d78c";function AAt(){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}=r_s(),x=j.useMemo(()=>{if(!p)return[];const B=s.trim().toLowerCase(),q=[...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(B?q.filter(V=>V.label.toLowerCase().includes(B)||V.value.toLowerCase().includes(B)):q).slice(0,8)},[p,s]);j.useEffect(()=>{const B=q=>{u.current&&!u.current.contains(q.target)&&o(!1)};return document.addEventListener("mousedown",B),()=>document.removeEventListener("mousedown",B)},[]);const{data:g,isLoading:y}=n_s({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}),b=B=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(B),v=()=>{m({status:"",propertyType:"",minPrice:"",maxPrice:""}),t("")},N=s||h.status||h.propertyType||h.minPrice||h.maxPrice,C=typeof window<"u"&&(window.location.hostname==="listings.relevelup.com"||window.location.hostname.startsWith("listings.")),A=B=>C?`/${B.slug||B.id}`:`/public/listing/${B.slug||B.id}`,{featured:T,restListings:P,luxeCount:M,cities:I,activeCount:D}=j.useMemo(()=>{const B=g||[],q=B.filter(ve=>ve.status==="active"),W=q.length>0?q:B,V=new Intl.DateTimeFormat("en-CA",{timeZone:"America/New_York",year:"numeric",month:"2-digit",day:"2-digit"}).format(new Date),[K,Q,J]=V.split("-").map(Number),ce=Math.floor(Date.UTC(K,Q-1,J)/864e5),ue=W.length>0?W[ce%W.length]:void 0,ne=B.filter(ve=>!ue||ve.id!==ue.id),ee=Array.from(new Set(B.map(ve=>ve.city).filter(Boolean))).slice(0,8),le=B.filter(ve=>(ve.price||0)>=1e6).length,he=q.length;return{featured:ue,restListings:ne,luxeCount:le,cities:ee,activeCount:he}},[g]);return e.jsxs(e.Fragment,{children:[e.jsxs(Ul,{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:v7,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: ${sd}; } .lu-gold-line { background: linear-gradient(90deg, transparent, ${sd}, 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(Wn,{to:"/",className:"flex items-center gap-3",children:[e.jsx("img",{src:Hke,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(Wn,{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 ${sd}`,color:sd},children:"About LevelUp"})]}),e.jsx("button",{type:"button",onClick:()=>i(B=>!B),className:"md:hidden inline-flex items-center justify-center w-10 h-10 rounded-full",style:{border:`1px solid ${sd}`,color:sd},"aria-label":"Toggle menu","aria-expanded":a,children:a?e.jsx(pr,{className:"w-5 h-5"}):e.jsx(jT,{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(Wn,{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 ${sd}`,color:sd},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:d_s,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:sd}}),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:nA},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 ${sd}`,backdropFilter:"blur(12px)"},children:[e.jsxs("div",{className:"relative flex-1",children:[e.jsx(Vr,{className:"absolute left-6 top-1/2 -translate-y-1/2 h-5 w-5",style:{color:sd}}),e.jsx(be,{placeholder:"City, neighborhood, or ZIP",value:s,onChange:B=>{t(B.target.value),o(!0),d(-1)},onFocus:()=>o(!0),onKeyDown:B=>{if(!(!l||x.length===0))if(B.key==="ArrowDown")B.preventDefault(),d(q=>Math.min(q+1,x.length-1));else if(B.key==="ArrowUp")B.preventDefault(),d(q=>Math.max(q-1,0));else if(B.key==="Enter"&&c>=0){B.preventDefault();const q=x[c];t(q.value),o(!1)}else B.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(TT,{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:sd,color:v7},onClick:()=>o(!1),children:[e.jsx(Vr,{className:"h-5 w-5"}),e.jsx("span",{className:"hidden md:inline",children:"Search"})]})]}),l&&x.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:sd},children:"Suggestions"}),e.jsx("ul",{className:"max-h-80 overflow-y-auto",children:x.map((B,q)=>e.jsx("li",{children:e.jsxs("button",{type:"button",onMouseEnter:()=>d(q),onClick:()=>{t(B.value),o(!1)},className:"w-full flex items-center justify-between gap-3 px-5 py-3 text-left transition",style:{background:c===q?"rgba(201,168,76,0.12)":"transparent"},children:[e.jsxs("div",{className:"flex items-center gap-3 min-w-0",children:[B.type==="city"&&e.jsx(ai,{className:"h-4 w-4 shrink-0",style:{color:sd}}),B.type==="neighborhood"&&e.jsx(Ai,{className:"h-4 w-4 shrink-0",style:{color:sd}}),B.type==="zip"&&e.jsx(sa,{className:"h-4 w-4 shrink-0",style:{color:sd}}),e.jsx("span",{className:"text-white/90 truncate",children:B.label})]}),e.jsxs("span",{className:"text-xs text-white/50 shrink-0",children:[B.count," ",B.count===1?"listing":"listings"]})]})},`${B.type}-${B.value}-${q}`))})]}),l&&s.trim()&&x.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(vs,{value:h.status||"all",onValueChange:B=>m({...h,status:B==="all"?"":B}),children:[e.jsx(gs,{className:"lu-input-dark",children:e.jsx(bs,{})}),e.jsxs(ys,{children:[e.jsx(Ye,{value:"all",children:"Any status"}),Object.entries(GLe).map(([B,q])=>e.jsx(Ye,{value:B,children:q},B))]})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"lu-eyebrow text-white/60 mb-2 block",children:"Type"}),e.jsxs(vs,{value:h.propertyType||"all",onValueChange:B=>m({...h,propertyType:B==="all"?"":B}),children:[e.jsx(gs,{className:"lu-input-dark",children:e.jsx(bs,{})}),e.jsxs(ys,{children:[e.jsx(Ye,{value:"all",children:"Any type"}),Object.entries(p_s).map(([B,q])=>e.jsx(Ye,{value:B,children:q},B))]})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"lu-eyebrow text-white/60 mb-2 block",children:"Min Price"}),e.jsx(be,{type:"number",placeholder:"No min",value:h.minPrice,onChange:B=>m({...h,minPrice:B.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(be,{type:"number",placeholder:"No max",value:h.maxPrice,onChange:B=>m({...h,maxPrice:B.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($,{variant:"ghost",size:"sm",onClick:v,className:"text-white/70 hover:text-white gap-1",children:[e.jsx(pr,{className:"h-4 w-4"})," Clear all"]})})]})]}),e.jsx("div",{className:"lu-hero-stats mt-14 grid grid-cols-3 gap-6 max-w-2xl",children:[{label:"Listings",value:((g==null?void 0:g.length)??0).toString()},{label:"Active Now",value:D.toString()},{label:"Luxury $1M+",value:M.toString()}].map(B=>e.jsxs("div",{children:[e.jsx("div",{className:"lu-serif text-4xl md:text-5xl",style:{color:nA},children:B.value}),e.jsx("div",{className:"lu-eyebrow text-white/60 mt-1",children:B.label})]},B.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(_o,{className:"h-4 w-4 animate-bounce"})]})]})]}),I.length>0&&e.jsx("section",{className:"py-8 overflow-hidden",style:{background:mit,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((B,q)=>e.jsxs("span",{className:"flex items-center gap-3 lu-serif text-2xl md:text-3xl text-white/40",children:[B,e.jsx("span",{className:"h-1.5 w-1.5 rounded-full",style:{background:sd}})]},q))})}),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(dn,{className:"h-4 w-4",style:{color:sd}}),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:nA},children:"standout"}),"."]})]}),e.jsx("div",{className:"hidden md:block h-px flex-1 mx-8 lu-gold-line"})]}),e.jsx(Wn,{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 q,W;const B=((q=T.photos)==null?void 0:q.find(V=>V.is_primary))||((W=T.photos)==null?void 0:W[0]);return B?e.jsx("img",{src:B.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(sa,{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:sd,color:v7},children:GLe[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(ai,{className:"h-3.5 w-3.5",style:{color:sd}}),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:nA},children:b(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(tw,{className:"h-4 w-4",style:{color:sd}}),T.bedrooms," bd"]}),T.bathrooms&&e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(_g,{className:"h-4 w-4",style:{color:sd}}),T.bathrooms," ba"]}),T.square_footage&&e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(Lb,{className:"h-4 w-4",style:{color:sd}}),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:sd},children:["View Residence ",e.jsx(ni,{className:"h-4 w-4"})]})]})]})})]})}),e.jsx("section",{id:"collection",className:"py-20 md:py-28",style:{background:mit},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:sd}}),e.jsx("span",{className:"lu-eyebrow lu-gold",children:"The Collection"}),e.jsx("span",{className:"h-px w-10",style:{background:sd}})]}),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:nA},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((B,q)=>e.jsxs("div",{className:"space-y-3",children:[e.jsx(on,{className:"aspect-[4/5] bg-white/5"}),e.jsx(on,{className:"h-6 w-32 bg-white/5"}),e.jsx(on,{className:"h-4 w-full bg-white/5"})]},q))}):P.length>0?e.jsx("div",{className:"grid sm:grid-cols-2 lg:grid-cols-3 gap-x-8 gap-y-14",children:P.map(B=>{var W,V,K,Q,J;const q=((W=B.photos)==null?void 0:W.find(ce=>ce.is_primary))||((V=B.photos)==null?void 0:V[0]);return e.jsxs(Wn,{to:A(B),className:"group lu-card-hover block",children:[e.jsxs("div",{className:"relative aspect-[4/5] overflow-hidden bg-black mb-5 rounded-lg",children:[q?e.jsx("img",{src:q.photo_url,alt:B.property_address||B.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(sa,{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:sd,border:`1px solid ${sd}`},children:GLe[B.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:[B.bedrooms&&e.jsxs("span",{children:[B.bedrooms," bd"]}),B.bathrooms&&e.jsxs("span",{children:[B.bathrooms," ba"]}),B.square_footage&&e.jsxs("span",{children:[B.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(ai,{className:"h-3 w-3",style:{color:sd}}),B.city,B.state?`, ${B.state}`:""]}),e.jsx("div",{className:"lu-serif text-2xl md:text-3xl mb-1",style:{color:nA},children:b(B.price)}),B.property_address&&e.jsx("p",{className:"text-white/70 text-sm truncate",children:B.property_address}),((K=B.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(Ai,{className:"h-3 w-3"}),B.agent.name,(((Q=B.agent.brokerage)==null?void 0:Q.name)||B.agent.brokerage_name)&&e.jsxs("span",{className:"truncate",children:["· ",((J=B.agent.brokerage)==null?void 0:J.name)||B.agent.brokerage_name]})]})]})]},B.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 ${sd}`},children:e.jsx(sa,{className:"h-8 w-8",style:{color:sd}})}),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($,{onClick:v,style:{background:sd,color:v7},className:"hover:brightness-110",children:"Clear filters"})]})]})}),g&&g.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:sd}}),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:nA},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(m_s,{listings:g,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%, ${v7} 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:sd}}),e.jsx("span",{className:"lu-eyebrow lu-gold",children:"For Agents"}),e.jsx("span",{className:"h-px w-10",style:{background:sd}})]}),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:nA},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:sd,color:v7},children:["Explore LevelUp",e.jsx(ni,{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:Hke,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(Ibs,{}),e.jsx(Dbs,{})]})}const f_s=j.lazy(()=>mi(()=>import("./PublicHomeValue-DY9b04Y4.js"),[]));function x_s(){const s=Wd(),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(AAt,{}):r==="home-value"||r==="whats-my-home-worth"?e.jsx(j.Suspense,{fallback:e.jsx("div",{}),children:e.jsx(f_s,{})}):r.startsWith("public/")?null:e.jsx(kAt,{slugOverride:r})}function zCe({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 EAt=s=>ht({queryKey:["agent-card-public",s],queryFn:async()=>{if(!s)throw new Error("No slug provided");const{data:t,error:n}=await U.from("agent_cards").select("*").eq("slug",s).eq("is_published",!0).single();if(n)throw n;const{data:r}=await U.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 U.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 U.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 U.storage.from("avatars").list(`${t.user_id}`);if(c&&c.length>0){const{data:d}=U.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}),g_s=()=>ht({queryKey:["agent-cards-admin"],queryFn:async()=>{const{data:s,error:t}=await U.from("agent_cards").select("*").order("created_at",{ascending:!1});if(t)throw t;return s}}),y_s=s=>ht({queryKey:["agent-card",s],queryFn:async()=>{if(!s)return null;const{data:t,error:n}=await U.from("agent_cards").select("*").eq("user_id",s).maybeSingle();if(n)throw n;return t},enabled:!!s}),TAt=()=>{const s=ts();return yt({mutationFn:async t=>{const{data:n,error:r}=await U.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"]}),ae.success("Agent card created")},onError:t=>ae.error(t.message)})},MAt=()=>{const s=ts();return yt({mutationFn:async({id:t,...n})=>{const{data:r,error:a}=await U.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"]}),ae.success("Agent card updated")},onError:t=>ae.error(t.message)})},Kc=async(s,t,n,r)=>{const a=new URLSearchParams(window.location.search);await U.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:{}})},v_s=async(s,t)=>{const{error:n}=await U.from("agent_card_leads").insert({card_id:s,...t});if(n)throw n},LAt=s=>ht({queryKey:["agent-card-analytics",s],queryFn:async()=>{if(!s)return null;const{data:t,error:n}=await U.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 U.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 BCe({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,x]=j.useState(""),[g,y]=j.useState(!1),b=async v=>{if(v.preventDefault(),!i.trim()){ae.error("Please enter your name");return}y(!0);try{await v_s(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}),Kc(n,"lead_submitted",r),U.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)),ae.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(""),x("")}catch{ae.error("Something went wrong. Please try again.")}finally{y(!1)}};return e.jsx(Os,{open:s,onOpenChange:t,children:e.jsxs(Rs,{className:"sm:max-w-md rounded-2xl",children:[e.jsxs(Us,{children:[e.jsx(zs,{children:r==="booking"?"Book a Call":r==="connect"?"Connect with Me":"Refer a Friend"}),e.jsx(Sr,{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:b,className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(se,{htmlFor:"lead-name",children:"Name *"}),e.jsx(be,{id:"lead-name",value:i,onChange:v=>l(v.target.value),placeholder:"Your name",required:!0})]}),e.jsxs("div",{children:[e.jsx(se,{htmlFor:"lead-phone",children:"Phone"}),e.jsx(be,{id:"lead-phone",type:"tel",value:d,onChange:v=>u(v.target.value),placeholder:"(555) 123-4567"})]}),e.jsxs("div",{children:[e.jsx(se,{htmlFor:"lead-email",children:"Email"}),e.jsx(be,{id:"lead-email",type:"email",value:o,onChange:v=>c(v.target.value),placeholder:"you@example.com"})]}),r==="booking"&&e.jsxs("div",{children:[e.jsx(se,{htmlFor:"lead-intent",children:"I'm looking to..."}),e.jsxs(vs,{value:h,onValueChange:m,children:[e.jsx(gs,{children:e.jsx(bs,{placeholder:"Select one"})}),e.jsxs(ys,{children:[e.jsx(Ye,{value:"buy",children:"Buy a home"}),e.jsx(Ye,{value:"sell",children:"Sell my home"}),e.jsx(Ye,{value:"both",children:"Buy & Sell"}),e.jsx(Ye,{value:"other",children:"Something else"})]})]})]}),r!=="connect"&&e.jsxs("div",{children:[e.jsx(se,{htmlFor:"lead-message",children:r==="referral"?"Tell us about them":"Message (optional)"}),e.jsx(be,{id:"lead-message",value:p,onChange:v=>x(v.target.value),placeholder:r==="referral"?"Their name, phone, situation...":"Anything you'd like us to know"})]}),e.jsx($,{type:"submit",className:"w-full rounded-2xl",disabled:g,children:g?"Sending...":"Submit"})]})]})})}const b_s=s=>ht({queryKey:["card-blocks",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await U.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}),__s=s=>ht({queryKey:["card-blocks-all",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await U.from("card_blocks").select("*").eq("card_id",s).order("sort_order",{ascending:!0});if(n)throw n;return t||[]},enabled:!!s}),w_s=()=>{const s=ts();return yt({mutationFn:async t=>{const{data:n,error:r}=await U.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]}),ae.success("Block added")},onError:t=>ae.error(t.message)})},j_s=()=>{const s=ts();return yt({mutationFn:async({id:t,...n})=>{const{data:r,error:a}=await U.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"]}),ae.success("Block updated")},onError:t=>ae.error(t.message)})},N_s=()=>{const s=ts();return yt({mutationFn:async t=>{const{error:n}=await U.from("card_blocks").delete().eq("id",t);if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["card-blocks"]}),s.invalidateQueries({queryKey:["card-blocks-all"]}),ae.success("Block removed")},onError:t=>ae.error(t.message)})};function k_s(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 S_s(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 C_s={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 A_s({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=S_s(n.video_url),i=r||!!a,l=r?k_s(n.video_url):a||n.video_url;return e.jsx("div",{className:C_s[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 E_s={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 T_s({block:s,variant:t}){const r=s.config.testimonials||[],[a,i]=j.useState(0);if(r.length===0)return null;const l=E_s[t],o=r[a];return e.jsxs("div",{className:l.container,children:[e.jsxs("div",{className:l.card,children:[e.jsx(RN,{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(Ic,{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(Ja,{className:"h-4 w-4"})})]})]})}const M_s={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 L_s({block:s,variant:t}){const r=s.config.tags||[];if(r.length===0)return null;const a=M_s[t];return e.jsx("div",{className:a.container,children:r.map((i,l)=>e.jsx("span",{className:a.tag,children:i},l))})}const P_s={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 I_s({block:s,cardId:t,variant:n}){const a=s.config.links||[];if(a.length===0)return null;const i=P_s[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:()=>Kc(t,"button_click",`custom_link_${l.label}`),className:i.link,children:[e.jsx("span",{children:l.label}),e.jsx(Tr,{className:`h-4 w-4 ${i.icon}`})]},o))})}const zFe={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 D_s({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 R_s={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 O_s({block:s,cardId:t,variant:n}){const a=s.config.platforms||[],i=R_s[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=zFe[l.platform.toLowerCase()];return!c||!l.url?null:e.jsx("a",{href:l.url,target:"_blank",rel:"noopener noreferrer",onClick:()=>Kc(t,"button_click",`social_${l.platform}`),className:i.linkClass,title:c.label,children:e.jsx(D_s,{path:c.icon,color:c.color})},o)})})]})}function $Ce({cardId:s,variant:t}){const{data:n}=b_s(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(A_s,{block:l,variant:t},l.id);case"testimonials":return e.jsx(T_s,{block:l,variant:t},l.id);case"specialties":return e.jsx(L_s,{block:l,variant:t},l.id);case"custom_links":return e.jsx(I_s,{block:l,cardId:s,variant:t},l.id);default:return null}}),i&&e.jsx(O_s,{block:i,cardId:s,variant:t})]})}async function F_s(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 z_s(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 UCe(s){const{first:t,last:n}=z_s(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 F_s(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),ae.success("Contact saved!")}function B_s({card:s}){var b;const[t,n]=j.useState(!1),[r,a]=j.useState("booking"),i=((b=s.profile)==null?void 0:b.name)||"Agent",l=i.split(" ").map(v=>v[0]).join("").toUpperCase().slice(0,2),o=(v,N)=>{Kc(s.id,"button_click",v),N()},c=()=>o("call",()=>{var v;(v=s.profile)!=null&&v.phone?window.location.href=`tel:${s.profile.phone}`:ae.error("Phone number not available")}),d=()=>o("text",()=>{var v;(v=s.profile)!=null&&v.phone?window.location.href=`sms:${s.profile.phone}`:ae.error("Phone number not available")}),u=()=>o("email",()=>{var v;(v=s.profile)!=null&&v.email?window.location.href=`mailto:${s.profile.email}`:ae.error("Email not available")}),h=()=>{s.booking_url?o("book",()=>window.open(s.booking_url,"_blank")):(a("booking"),n(!0),Kc(s.id,"button_click","book"))},m=()=>{var v,N;Kc(s.id,"contact_saved"),UCe({name:i,phone:(v=s.profile)==null?void 0:v.phone,email:(N=s.profile)==null?void 0:N.email,brokerage:s.brokerage_name,avatarUrl:s.avatar_url,cardUrl:window.location.href})},p=async()=>{Kc(s.id,"share_event");const v=`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:v})}catch{}else await navigator.clipboard.writeText(v),ae.success("Link copied!")},x=()=>{a("referral"),n(!0),Kc(s.id,"button_click","refer")},g=()=>{a("connect"),n(!0),Kc(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(ki,{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($,{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(ya,{className:"h-5 w-5"}),e.jsx("span",{className:"text-xs font-medium",children:"Call"})]}),e.jsxs($,{onClick:d,className:"flex flex-col items-center gap-1.5 h-auto py-4 bg-primary hover:bg-primary/90 text-primary-foreground rounded-2xl shadow-sm",children:[e.jsx(Ji,{className:"h-5 w-5"}),e.jsx("span",{className:"text-xs font-medium",children:"Text"})]}),e.jsxs($,{onClick:u,className:"flex flex-col items-center gap-1.5 h-auto py-4 bg-primary hover:bg-primary/90 text-primary-foreground rounded-2xl shadow-sm",children:[e.jsx(nn,{className:"h-5 w-5"}),e.jsx("span",{className:"text-xs font-medium",children:"Email"})]})]}),e.jsxs($,{onClick:h,className:"w-full h-12 text-base font-semibold rounded-2xl shadow-sm mb-6",variant:"outline",children:[e.jsx(ia,{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(Qa,{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(zCe,{card:s,variant:"standard"}),e.jsx($Ce,{cardId:s.id,variant:"standard"}),e.jsxs("div",{className:"space-y-2 mb-6",children:[s.show_save_contact&&e.jsxs($,{variant:"ghost",onClick:m,className:"w-full justify-start h-12 rounded-2xl text-slate-700 hover:bg-slate-100",children:[e.jsx(di,{className:"h-4 w-4 mr-3 text-primary"}),"Save Contact"]}),s.show_leave_review&&s.review_source_url&&e.jsxs($,{variant:"ghost",onClick:()=>{Kc(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(Qa,{className:"h-4 w-4 mr-3 text-amber-500"}),"Leave a Review"]}),s.show_refer_friend&&e.jsxs($,{variant:"ghost",onClick:x,className:"w-full justify-start h-12 rounded-2xl text-slate-700 hover:bg-slate-100",children:[e.jsx(qn,{className:"h-4 w-4 mr-3 text-primary"}),"Refer a Friend"]}),e.jsxs($,{variant:"ghost",onClick:g,className:"w-full justify-start h-12 rounded-2xl text-slate-700 hover:bg-slate-100",children:[e.jsx(il,{className:"h-4 w-4 mr-3 text-primary"}),"Connect with Me"]}),e.jsxs($,{variant:"ghost",onClick:p,className:"w-full justify-start h-12 rounded-2xl text-slate-700 hover:bg-slate-100",children:[e.jsx(vd,{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((v,N)=>e.jsx("a",{href:v.url,target:"_blank",rel:"noopener noreferrer",onClick:()=>Kc(s.id,"button_click",`social_${v.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[v.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(BCe,{open:t,onOpenChange:n,cardId:s.id,type:r,agentName:i})]})}function $_s({card:s}){var b;const[t,n]=j.useState(!1),[r,a]=j.useState("booking"),i=((b=s.profile)==null?void 0:b.name)||"Agent",l=i.split(" ").map(v=>v[0]).join("").toUpperCase().slice(0,2),o=(v,N)=>{Kc(s.id,"button_click",v),N()},c=()=>o("call",()=>{var v;(v=s.profile)!=null&&v.phone?window.location.href=`tel:${s.profile.phone}`:ae.error("Phone number not available")}),d=()=>o("text",()=>{var v;(v=s.profile)!=null&&v.phone?window.location.href=`sms:${s.profile.phone}`:ae.error("Phone number not available")}),u=()=>o("email",()=>{var v;(v=s.profile)!=null&&v.email?window.location.href=`mailto:${s.profile.email}`:ae.error("Email not available")}),h=()=>{s.booking_url?o("book",()=>window.open(s.booking_url,"_blank")):(a("booking"),n(!0),Kc(s.id,"button_click","book"))},m=()=>{var v,N;Kc(s.id,"contact_saved"),UCe({name:i,phone:(v=s.profile)==null?void 0:v.phone,email:(N=s.profile)==null?void 0:N.email,brokerage:s.brokerage_name,avatarUrl:s.avatar_url,cardUrl:window.location.href})},p=async()=>{Kc(s.id,"share_event");const v=`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:v})}catch{}else await navigator.clipboard.writeText(v),ae.success("Link copied!")},x=()=>{a("referral"),n(!0),Kc(s.id,"button_click","refer")},g=()=>{a("connect"),n(!0),Kc(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(ki,{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:ya,label:"Call",handler:c},{icon:Ji,label:"Text",handler:d},{icon:nn,label:"Email",handler:u}].map(({icon:v,label:N,handler:C})=>e.jsxs("button",{onClick:C,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(v,{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(ia,{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(Qa,{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(zCe,{card:s,variant:"luxury"}),e.jsx($Ce,{cardId:s.id,variant:"luxury"}),e.jsxs("div",{className:"space-y-1 mb-6",children:[s.show_save_contact&&e.jsxs("button",{onClick:m,className:"w-full flex items-center gap-3 h-12 px-4 rounded-xl text-[#e2e8f0] hover:bg-[#1e2636] transition-colors text-sm",children:[e.jsx(di,{className:"h-4 w-4 text-[#c9a84c]"})," Save Contact"]}),s.show_leave_review&&s.review_source_url&&e.jsxs("button",{onClick:()=>{Kc(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(Qa,{className:"h-4 w-4 text-[#c9a84c]"})," Leave a Review"]}),s.show_refer_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(qn,{className:"h-4 w-4 text-[#c9a84c]"})," Refer a Friend"]}),e.jsxs("button",{onClick:g,className:"w-full flex items-center gap-3 h-12 px-4 rounded-xl text-[#e2e8f0] hover:bg-[#1e2636] transition-colors text-sm",children:[e.jsx(il,{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(vd,{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((v,N)=>e.jsx("a",{href:v.url,target:"_blank",rel:"noopener noreferrer",onClick:()=>Kc(s.id,"button_click",`social_${v.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[v.platform.toLowerCase()]||"🔗"},N))}),e.jsx("div",{className:"text-center",children:e.jsx("p",{className:"text-xs text-[#4a5568]",children:"Powered by LevelUp"})})]}),e.jsx(BCe,{open:t,onOpenChange:n,cardId:s.id,type:r,agentName:i})]})}function U_s({card:s}){var N,C,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(P=>P[0]).join("").toUpperCase().slice(0,2),o={accent:((C=s.bold_theme_colors)==null?void 0:C.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=(P,M)=>{const I=parseInt(P.replace("#",""),16),D=Math.max(0,(I>>16)-M),B=Math.max(0,(I>>8&255)-M),q=Math.max(0,(I&255)-M);return`#${(D<<16|B<<8|q).toString(16).padStart(6,"0")}`};c(o.accent,25),c(o.dark,-20),c(o.button,25);const d=(P,M)=>{Kc(s.id,"button_click",P),M()},u=()=>d("call",()=>{var P;(P=s.profile)!=null&&P.phone?window.location.href=`tel:${s.profile.phone}`:ae.error("Phone number not available")}),h=()=>d("text",()=>{var P;(P=s.profile)!=null&&P.phone?window.location.href=`sms:${s.profile.phone}`:ae.error("Phone number not available")}),m=()=>d("email",()=>{var P;(P=s.profile)!=null&&P.email?window.location.href=`mailto:${s.profile.email}`:ae.error("Email not available")}),p=()=>{s.booking_url?d("book",()=>window.open(s.booking_url,"_blank")):(a("booking"),n(!0),Kc(s.id,"button_click","book"))},x=()=>{var P,M;Kc(s.id,"contact_saved"),UCe({name:i,phone:(P=s.profile)==null?void 0:P.phone,email:(M=s.profile)==null?void 0:M.email,brokerage:s.brokerage_name,avatarUrl:s.avatar_url,cardUrl:window.location.href})},g=async()=>{Kc(s.id,"share_event");const P=`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:P})}catch{}else await navigator.clipboard.writeText(P),ae.success("Link copied!")},y=()=>{a("referral"),n(!0),Kc(s.id,"button_click","refer")},b=()=>{a("connect"),n(!0),Kc(s.id,"button_click","connect")},v={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(ki,{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:ya,label:"Call",handler:u},{icon:Ji,label:"Text",handler:h},{icon:nn,label:"Email",handler:m}].map(({icon:P,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(P,{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(ia,{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(Qa,{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(zCe,{card:s,variant:"bold"}),e.jsx($Ce,{cardId:s.id,variant:"bold"}),e.jsxs("div",{className:"space-y-1 mb-6",children:[s.show_save_contact&&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(di,{className:"h-4 w-4",style:{color:o.accent}})," Save Contact"]}),s.show_leave_review&&s.review_source_url&&e.jsxs("button",{onClick:()=>{Kc(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(Qa,{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(qn,{className:"h-4 w-4",style:{color:o.accent}})," Refer a Friend"]}),e.jsxs("button",{onClick:b,className:"w-full flex items-center gap-3 h-12 px-4 rounded-2xl hover:bg-gray-100 transition-colors text-sm font-bold",style:{color:o.dark},children:[e.jsx(il,{className:"h-4 w-4",style:{color:o.accent}})," Connect with Me"]}),e.jsxs("button",{onClick:g,className:"w-full flex items-center gap-3 h-12 px-4 rounded-2xl hover:bg-gray-100 transition-colors text-sm font-bold",style:{color:o.dark},children:[e.jsx(vd,{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((P,M)=>e.jsx("a",{href:P.url,target:"_blank",rel:"noopener noreferrer",onClick:()=>Kc(s.id,"button_click",`social_${P.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:v[P.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(BCe,{open:t,onOpenChange:n,cardId:s.id,type:r,agentName:i})]})}function q_s({card:s}){var b;const[t,n]=j.useState(!1),[r,a]=j.useState("booking"),i=((b=s.profile)==null?void 0:b.name)||"Agent",l=i.split(" ").map(v=>v[0]).join("").toUpperCase().slice(0,2),o=(v,N)=>{Kc(s.id,"button_click",v),N()},c=()=>o("call",()=>{var v;(v=s.profile)!=null&&v.phone?window.location.href=`tel:${s.profile.phone}`:ae.error("Phone number not available")}),d=()=>o("text",()=>{var v;(v=s.profile)!=null&&v.phone?window.location.href=`sms:${s.profile.phone}`:ae.error("Phone number not available")}),u=()=>o("email",()=>{var v;(v=s.profile)!=null&&v.email?window.location.href=`mailto:${s.profile.email}`:ae.error("Email not available")}),h=()=>{s.booking_url?o("book",()=>window.open(s.booking_url,"_blank")):(a("booking"),n(!0),Kc(s.id,"button_click","book"))},m=()=>{var v,N;Kc(s.id,"contact_saved"),UCe({name:i,phone:(v=s.profile)==null?void 0:v.phone,email:(N=s.profile)==null?void 0:N.email,brokerage:s.brokerage_name,avatarUrl:s.avatar_url,cardUrl:window.location.href})},p=async()=>{Kc(s.id,"share_event");const v=`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:v})}catch{}else await navigator.clipboard.writeText(v),ae.success("Link copied!")},x=()=>{a("referral"),n(!0),Kc(s.id,"button_click","refer")},g=()=>{a("connect"),n(!0),Kc(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(ki,{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:ya,label:"Call",handler:c},{icon:Ji,label:"Text",handler:d},{icon:nn,label:"Email",handler:u}].map(({icon:v,label:N,handler:C})=>e.jsxs("button",{onClick:C,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(v,{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(ia,{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(Qa,{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(zCe,{card:s,variant:"classic"}),e.jsx($Ce,{cardId:s.id,variant:"classic"}),e.jsxs("div",{className:"bg-white rounded-lg border border-[#d4cfc5] shadow-sm divide-y divide-[#e8e3db] mb-6",children:[s.show_save_contact&&e.jsxs("button",{onClick:m,className:"w-full flex items-center gap-3 h-12 px-4 text-[#1b3a4b] hover:bg-[#f5f1eb] transition-colors text-sm font-medium",children:[e.jsx(di,{className:"h-4 w-4 text-[#5a7a6f]"})," Save Contact"]}),s.show_leave_review&&s.review_source_url&&e.jsxs("button",{onClick:()=>{Kc(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(Qa,{className:"h-4 w-4 text-[#d4a843]"})," Leave a Review"]}),s.show_refer_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(qn,{className:"h-4 w-4 text-[#5a7a6f]"})," Refer a Friend"]}),e.jsxs("button",{onClick:g,className:"w-full flex items-center gap-3 h-12 px-4 text-[#1b3a4b] hover:bg-[#f5f1eb] transition-colors text-sm font-medium",children:[e.jsx(il,{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(vd,{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((v,N)=>e.jsx("a",{href:v.url,target:"_blank",rel:"noopener noreferrer",onClick:()=>Kc(s.id,"button_click",`social_${v.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[v.platform.toLowerCase()]||"🔗"},N))}),e.jsx("div",{className:"text-center",children:e.jsx("p",{className:"text-xs text-[#a0aec0]",children:"Powered by LevelUp"})})]}),e.jsx(BCe,{open:t,onOpenChange:n,cardId:s.id,type:r,agentName:i})]})}function CHe({card:s}){switch(s.theme){case"luxury":return e.jsx($_s,{card:s});case"bold":return e.jsx(U_s,{card:s});case"classic":return e.jsx(q_s,{card:s});case"standard":default:return e.jsx(B_s,{card:s})}}function V_s(){const s=Wd();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(H_s,{slug:t})}function H_s({slug:s}){return e.jsx(G_s,{slug:s})}function G_s({slug:s}){var i;const{data:t,isLoading:n,error:r}=EAt(s);if(j.useEffect(()=>{t!=null&&t.id&&Kc(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(on,{className:"h-28 w-28 rounded-full"}),e.jsx(on,{className:"h-6 w-48"}),e.jsx(on,{className:"h-4 w-36"})]}),e.jsx(on,{className:"h-12 w-full"}),e.jsx(on,{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(Ul,{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(CHe,{card:t})]})}function PAt({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(""),[x,g]=j.useState(""),[y,b]=j.useState(!1),[v,N]=j.useState(!1),C=async A=>{if(A.preventDefault(),!l.trim()){ae.error("Please enter your name");return}b(!0);try{const{error:T}=await U.from("smart_presentation_leads").insert({presentation_id:s,name:l.trim(),email:c.trim()||null,phone:u.trim()||null,intent:m||null,message:x.trim()||null});if(T)throw T;try{await U.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{}U.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:x.trim()||void 0}}).catch(P=>console.error("Presentation lead notify failed:",P)),N(!0)}catch{ae.error("Something went wrong. Please try again.")}finally{b(!1)}};return v?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(oa,{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:C,className:"space-y-4 max-w-md mx-auto",children:[e.jsxs("div",{children:[e.jsx(se,{htmlFor:"pres-lead-name",children:"Name *"}),e.jsx(be,{id:"pres-lead-name",value:l,onChange:A=>o(A.target.value),placeholder:"Your name",required:!0})]}),e.jsxs("div",{children:[e.jsx(se,{htmlFor:"pres-lead-phone",children:"Phone"}),e.jsx(be,{id:"pres-lead-phone",type:"tel",value:u,onChange:A=>h(A.target.value),placeholder:"(555) 123-4567"})]}),e.jsxs("div",{children:[e.jsx(se,{htmlFor:"pres-lead-email",children:"Email"}),e.jsx(be,{id:"pres-lead-email",type:"email",value:c,onChange:A=>d(A.target.value),placeholder:"you@example.com"})]}),e.jsxs("div",{children:[e.jsx(se,{htmlFor:"pres-lead-intent",children:"I'm looking to..."}),e.jsxs(vs,{value:m,onValueChange:p,children:[e.jsx(gs,{children:e.jsx(bs,{placeholder:"Select one"})}),e.jsxs(ys,{children:[e.jsx(Ye,{value:"buy",children:"Buy a home"}),e.jsx(Ye,{value:"sell",children:"Sell my home"}),e.jsx(Ye,{value:"both",children:"Buy & Sell"}),e.jsx(Ye,{value:"other",children:"Something else"})]})]})]}),e.jsxs("div",{children:[e.jsx(se,{htmlFor:"pres-lead-message",children:"Message (optional)"}),e.jsx(be,{id:"pres-lead-message",value:x,onChange:A=>g(A.target.value),placeholder:"Anything you'd like us to know"})]}),e.jsx($,{type:"submit",className:"w-full text-lg py-6 rounded-xl bg-blue-600 hover:bg-blue-700 text-white shadow-lg",disabled:y,children:y?"Sending...":t})]})}function W_s(){const s=Wd();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(K_s,{shareToken:t})}function K_s({shareToken:s}){var x;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:g,error:y}=await U.from("smart_presentations").select("*").eq("share_token",s).eq("status","published").single();if(y||!g){c(!0),a(!1);return}const{data:b}=await U.from("profiles").select("name, email, phone, avatar_url, title, brokerage_id").eq("id",g.owner_user_id).single();let v;if(b!=null&&b.brokerage_id){const{data:C}=await U.from("brokerages").select("name").eq("id",b.brokerage_id).single();v=(C==null?void 0:C.name)||void 0}let N=null;if(g.contact_id){const{data:C}=await U.from("innercircle_contacts").select("first_name, last_name, email, phone").eq("id",g.contact_id).single();N=C}n({...g,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:v,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 U.rpc("log_presentation_view",{p_presentation_id:g.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 U.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=g=>{const y=g.match(/(?:youtube\.com\/watch\?v=|youtu\.be\/)([a-zA-Z0-9_-]+)/);if(y)return`https://www.youtube.com/embed/${y[1]}?rel=0`;if(g.includes("iframe.mediadelivery.net/play/")){const N=g.replace("/play/","/embed/"),C=N.includes("?")?"&":"?";return`${N}${C}responsive=true`}if(g.includes("iframe.mediadelivery.net")){const N=g.includes("?")?"&":"?";return`${g}${N}responsive=true`}const b=g.match(/loom\.com\/share\/([a-zA-Z0-9]+)/);if(b)return`https://www.loom.com/embed/${b[1]}`;const v=g.match(/video\.bunnycdn\.com\/play\/(\d+)\/([a-f0-9-]+)/);return v?`https://iframe.mediadelivery.net/embed/${v[1]}/${v[2]}?responsive=true`:g};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(on,{className:"h-12 w-3/4 mx-auto"}),e.jsx(on,{className:"h-64 w-full"}),e.jsx(on,{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(g=>g.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((g,y)=>e.jsx("button",{onClick:()=>l(y),className:Tt("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:g.icon}),e.jsx("span",{className:"font-semibold text-gray-900",children:g.title}),e.jsx("p",{className:"text-xs text-gray-500 mt-0.5",children:g.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?"}),(x=t.cta_url)!=null&&x.trim()?e.jsxs($,{size:"lg",onClick:u,className:"text-lg px-8 py-6 rounded-xl bg-blue-600 hover:bg-blue-700 text-white shadow-lg",children:[t.cta_label,e.jsx(Tr,{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(PAt,{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 Y_s(){const{user:s}=_s(),t=Za(),{data:n}=Nw();return ht({queryKey:["open-houses",t,n==null?void 0:n.teamId,n==null?void 0:n.role],queryFn:async()=>{const{data:r,error:a}=await U.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 U.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 U.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 FXn(s){const{user:t}=_s();return ht({queryKey:["open-house",s],queryFn:async()=>{const{data:n,error:r}=await U.from("open_houses").select("*").eq("id",s).single();if(r)throw r;return n},enabled:!!t&&!!s})}function IAt(s){const{user:t}=_s(),n=ts();return j.useEffect(()=>{if(!s)return;const r=`visitors-${s}-${Math.random().toString(36).slice(2,10)}`,a=U.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()=>{U.removeChannel(a)}},[s,n]),ht({queryKey:["open-house-visitors",s],queryFn:async()=>{const{data:r,error:a}=await U.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 Z_s(){const s=ts(),t=Za();return yt({mutationFn:async n=>{const{data:r,error:a}=await U.from("open_houses").insert({...n,agent_id:t}).select().single();if(a)throw a;return r},onSuccess:()=>{s.invalidateQueries({queryKey:["open-houses"]}),ja({title:"Open house created!"})},onError:n=>{ja({title:"Error",description:n.message,variant:"destructive"})}})}function DAt(){const s=ts();return yt({mutationFn:async({id:t,...n})=>{const{error:r}=await U.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 X_s(){const s=ts();return yt({mutationFn:async t=>{const{error:n}=await U.from("open_houses").delete().eq("id",t);if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["open-houses"]}),ja({title:"Open house deleted"})}})}function RAt(s){return ht({queryKey:["public-open-house",s],queryFn:async()=>{const{data:t,error:n}=await U.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 U.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 Q_s(s){const{user:t}=_s();return ht({queryKey:["survey-questions",s],queryFn:async()=>{const{data:n,error:r}=await U.from("open_house_survey_questions").select("*").eq("open_house_id",s).order("sort_order");if(r)throw r;return n},enabled:!!t&&!!s})}function J_s(s){return ht({queryKey:["public-survey-questions",s],queryFn:async()=>{const{data:t,error:n}=await U.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 ews(){return yt({mutationFn:async s=>{const{error:t}=await U.from("open_house_survey_responses").insert(s);if(t)throw t}})}function tws(s){const{user:t}=_s();return ht({queryKey:["survey-responses",s],queryFn:async()=>{const{data:n,error:r}=await U.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 U.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 sws(){const s=ts();return yt({mutationFn:async t=>{const{data:n,error:r}=await U.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 nws(){const s=ts();return yt({mutationFn:async({id:t,open_house_id:n,...r})=>{const{error:a}=await U.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 rws(){const s=ts();return yt({mutationFn:async({id:t,open_house_id:n})=>{const{error:r}=await U.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 aws(){const s=ts();return yt({mutationFn:async t=>{const{error:n}=await U.rpc("seed_default_survey_questions",{_open_house_id:t});if(n)throw n},onSuccess:(t,n)=>{s.invalidateQueries({queryKey:["survey-questions",n]})}})}function iws(){return yt({mutationFn:async s=>{const{data:t,error:n}=await U.from("open_house_visitors").insert(s).select("id").single();if(n)throw n;return t}})}function ows(){return yt({mutationFn:async({visitor_id:s,...t})=>{const{error:n}=await U.from("open_house_visitors").update(t).eq("id",s);if(n)throw n}})}function lws(){return yt({mutationFn:async s=>{await U.rpc("increment_open_house_scan",{_slug:s})}})}async function OAt(s){const{data:t,error:n}=await U.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 U.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 cws(s){const{user:t}=_s();return ht({queryKey:["open-house-rooms",s],queryFn:()=>OAt(s),enabled:!!t&&!!s})}function dws(s){return ht({queryKey:["public-open-house-rooms",s],queryFn:()=>OAt(s),enabled:!!s})}function uws(){const s=ts();return yt({mutationFn:async t=>{const{data:n,error:r}=await U.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 hws(){const s=ts();return yt({mutationFn:async({id:t,open_house_id:n,...r})=>{const{error:a}=await U.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 mws(){const s=ts();return yt({mutationFn:async({id:t,open_house_id:n})=>{const{error:r}=await U.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 pws(){const s=ts();return yt({mutationFn:async({open_house_id:t,...n})=>{const{data:r,error:a}=await U.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 fws(){const s=ts();return yt({mutationFn:async({id:t,open_house_id:n})=>{const{error:r}=await U.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 xws(s){const{user:t}=_s();return ht({queryKey:["open-house-leads",s],queryFn:async()=>{const{data:n,error:r}=await U.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 gws(){const s=ts();return yt({mutationFn:async({id:t,status:n,open_house_id:r})=>{const{error:a}=await U.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 qCe="Switch",[yws,zXn]=ip(qCe),[vws,bws]=yws(qCe),FAt=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),x=Po(t,N=>p(N)),g=j.useRef(!1),y=m?u||!!m.closest("form"):!0,[b,v]=Ux({prop:a,defaultProp:i??!1,onChange:d,caller:qCe});return e.jsxs(vws,{scope:n,checked:b,disabled:o,children:[e.jsx(Ka.button,{type:"button",role:"switch","aria-checked":b,"aria-required":l,"data-state":UAt(b),"data-disabled":o?"":void 0,disabled:o,value:c,...h,ref:x,onClick:xa(s.onClick,N=>{v(C=>!C),y&&(g.current=N.isPropagationStopped(),g.current||N.stopPropagation())})}),y&&e.jsx($At,{control:m,bubbles:!g.current,name:r,value:c,checked:b,required:l,disabled:o,form:u,style:{transform:"translateX(-100%)"}})]})});FAt.displayName=qCe;var zAt="SwitchThumb",BAt=j.forwardRef((s,t)=>{const{__scopeSwitch:n,...r}=s,a=bws(zAt,n);return e.jsx(Ka.span,{"data-state":UAt(a.checked),"data-disabled":a.disabled?"":void 0,...r,ref:t})});BAt.displayName=zAt;var _ws="SwitchBubbleInput",$At=j.forwardRef(({__scopeSwitch:s,control:t,checked:n,bubbles:r=!0,...a},i)=>{const l=j.useRef(null),o=Po(l,i),c=mee(n),d=JJ(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 x=new Event("click",{bubbles:r});p.call(u,n),u.dispatchEvent(x)}},[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}})});$At.displayName=_ws;function UAt(s){return s?"checked":"unchecked"}var qAt=FAt,wws=BAt;const Tn=j.forwardRef(({className:s,...t},n)=>e.jsx(qAt,{className:Tt("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(wws,{className:Tt("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")})}));Tn.displayName=qAt.displayName;const jws=["Excellent","Good","Neutral","Bad","Very Bad"],Nws=[5,4,3,2,1];function kws({questions:s,visitorId:t,onComplete:n,onSkip:r}){const a=ews(),[i,l]=j.useState({}),o=s.filter(m=>m.question_type==="rating"),c=s.filter(m=>m.question_type!=="rating"),d=(m,p)=>{l(x=>({...x,[m]:{rating_value:p}}))},u=(m,p)=>{l(x=>({...x,[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,x])=>{var g;return{visitor_id:t,question_id:p,rating_value:x.rating_value??null,text_value:((g=x.text_value)==null?void 0:g.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"}),jws.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}),Nws.map(p=>{var x;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 ${((x=i[m.id])==null?void 0:x.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(Is,{value:((p=i[m.id])==null?void 0:p.text_value)||"",onChange:x=>u(m.id,x.target.value),placeholder:"Your thoughts...",className:"h-16 text-sm resize-none rounded-xl border-slate-200"})]},m.id)}),e.jsx($,{onClick:h,disabled:a.isPending,className:"w-full h-12 text-base bg-slate-900 hover:bg-slate-800 text-white rounded-xl",children:a.isPending?e.jsx(Ht,{className:"h-5 w-5 animate-spin"}):"Submit Feedback"})]})}function BFe(s){return/iframe\.mediadelivery\.net\/embed\//.test(s)}function Sws({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:Tt("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:[BFe(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(Xr,{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(Ic,{className:"h-6 w-6"})}),l.kind==="video"?BFe(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(Ja,{className:"h-6 w-6"})})]})]}):null}function Cws({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:Tt("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"?BFe(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(Ic,{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(Ja,{className:"h-4 w-4"})]})]})]})}const WLe={question:{label:"Ask a Question",title:"Ask the agent",placeholder:"What would you like to know about the home?",icon:Ji},showing:{label:"Schedule a Showing",title:"Request a private showing",placeholder:"Anything specific to focus on during the showing? (optional)",icon:ia},disclosure:{label:"Request Disclosures",title:"Request seller disclosures",placeholder:"Any specific documents? (optional)",icon:Wr},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:qd}},Aws=["Seller's Property Disclosure","HOA Documents & Bylaws","Inspection Reports","Title / CC&Rs","Utility & Tax History"];function Ews(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 Tws({openHouse:s,visitorId:t,visitorName:n,visitorEmail:r,visitorPhone:a,previewMode:i=!1}){var ze;const l=s.profiles,o=((ze=l==null?void 0:l.name)==null?void 0:ze.split(" ").map(ke=>ke[0]).join("").slice(0,2))||"?",c=s.brand_color_override||null,[d,u]=j.useState(null),[h,m]=j.useState(""),[p,x]=j.useState(r||""),[g,y]=j.useState(a||""),[b,v]=j.useState(!1),[N,C]=j.useState(null),[A,T]=j.useState(""),[P,M]=j.useState(""),[I,D]=j.useState(""),[B,q]=j.useState([]),[W,V]=j.useState(""),[K,Q]=j.useState(""),[J,ce]=j.useState(""),[ue,ne]=j.useState(""),ee=Ews(s.price),le=s.tour_mode==="rooms",{data:he=[]}=dws(le?s.id:void 0),ve=[s.enable_question&&"question",s.enable_showing&&"showing",s.enable_disclosures&&"disclosure",s.enable_offer&&"offer"].filter(Boolean),ge=ke=>{u(ke),m(""),T(""),M(""),D(""),q([]),V(""),Q(""),ce(""),ne("")},fe=()=>{u(null)},je=ke=>{q(Xe=>Xe.includes(ke)?Xe.filter(Se=>Se!==ke):[...Xe,ke])},Ee=ke=>ke==="showing"?{preferred_date:A||null,preferred_time:P||null,alternate_date:I||null}:ke==="disclosure"?{requested_documents:B}:ke==="offer"?{offer_amount:W||null,financing:K||null,timeline:J||null,pre_approved:ue||null}:{},Me=d?d==="showing"?!!A:d==="question"?h.trim().length>0:!0:!1,De=async()=>{if(d){if(i){ja({title:"Preview mode",description:"Lead not sent — this is just a preview."}),C(d),setTimeout(()=>{u(null),C(null)},1500);return}v(!0);try{const ke=Ee(d),{error:Xe}=await U.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:g.trim()||null,visitor_name:n,...ke}});if(Xe)throw Xe;U.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:g.trim()||null,extras:ke}}).catch(()=>{}),C(d),ja({title:"Sent!",description:"The agent has been notified."}),setTimeout(()=>{fe(),C(null)},1400)}catch(ke){ja({title:"Something went wrong",description:ke.message,variant:"destructive"})}finally{v(!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(ai,{className:"h-3.5 w-3.5"}),s.city,s.state?`, ${s.state}`:""," ",s.zip]}),ee&&e.jsx("p",{className:"text-3xl font-bold text-white mt-3",children:ee}),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(tw,{className:"h-4 w-4"}),s.beds," bd"]}),s.baths!=null&&e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(_g,{className:"h-4 w-4"}),s.baths," ba"]}),s.sqft!=null&&e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(Lb,{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(ki,{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(ya,{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(nn,{className:"h-4 w-4"})})]})]}),le&&he.length>0&&e.jsxs("div",{className:"mt-8",children:[e.jsx(Sws,{rooms:he}),e.jsx(Cws,{rooms:he})]}),ve.length>0&&e.jsx("div",{className:"mt-5 grid grid-cols-1 sm:grid-cols-2 gap-3",children:ve.map(ke=>{const Xe=WLe[ke],Se=Xe.icon;return e.jsxs("button",{onClick:()=>ge(ke),className:"flex items-center gap-3 p-4 rounded-xl bg-white text-slate-900 hover:bg-white/90 transition-colors text-left",children:[e.jsx("div",{className:"w-10 h-10 rounded-lg flex items-center justify-center shrink-0",style:c?{backgroundColor:`${c}1a`,color:c}:{backgroundColor:"#f1f5f9",color:"#334155"},children:e.jsx(Se,{className:"h-5 w-5"})}),e.jsx("span",{className:"font-medium text-sm",children:Xe.label})]},ke)})}),e.jsx("p",{className:"text-center text-white/30 text-xs mt-8",children:"Powered by LevelUp Virtual Open House"})]}),e.jsx(Ub,{open:!!d,onOpenChange:ke=>!ke&&fe(),children:e.jsx(T1,{side:"bottom",className:"rounded-t-2xl max-h-[92vh] overflow-y-auto",children:d&&e.jsxs(e.Fragment,{children:[e.jsxs(kw,{className:"text-left",children:[e.jsx(Sw,{children:WLe[d].title}),e.jsxs(dee,{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(Fr,{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(se,{className:"text-xs",children:"Email"}),e.jsx(be,{type:"email",value:p,onChange:ke=>x(ke.target.value),placeholder:"you@example.com",className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-xs",children:"Phone"}),e.jsx(be,{type:"tel",value:g,onChange:ke=>y(ke.target.value),placeholder:"(555) 123-4567",className:"mt-1"})]})]}),d==="showing"&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(se,{className:"text-xs",children:"Preferred date *"}),e.jsx(be,{type:"date",value:A,onChange:ke=>T(ke.target.value),className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-xs",children:"Preferred time"}),e.jsx(be,{type:"time",value:P,onChange:ke=>M(ke.target.value),className:"mt-1"})]})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-xs",children:"Alternate date (optional)"}),e.jsx(be,{type:"date",value:I,onChange:ke=>D(ke.target.value),className:"mt-1"})]})]}),d==="disclosure"&&e.jsxs("div",{children:[e.jsx(se,{className:"text-xs",children:"Which documents? (select all that apply)"}),e.jsx("div",{className:"mt-2 space-y-2",children:Aws.map(ke=>e.jsxs("label",{className:"flex items-center gap-2 text-sm cursor-pointer",children:[e.jsx(ui,{checked:B.includes(ke),onCheckedChange:()=>je(ke)}),e.jsx("span",{children:ke})]},ke))})]}),d==="offer"&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(se,{className:"text-xs",children:"Estimated offer"}),e.jsx(be,{value:W,onChange:ke=>V(ke.target.value),placeholder:"$",className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-xs",children:"Financing"}),e.jsxs(vs,{value:K,onValueChange:Q,children:[e.jsx(gs,{className:"mt-1",children:e.jsx(bs,{placeholder:"Select..."})}),e.jsxs(ys,{children:[e.jsx(Ye,{value:"Cash",children:"Cash"}),e.jsx(Ye,{value:"Conventional",children:"Conventional"}),e.jsx(Ye,{value:"FHA",children:"FHA"}),e.jsx(Ye,{value:"VA",children:"VA"}),e.jsx(Ye,{value:"Other",children:"Other"})]})]})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(se,{className:"text-xs",children:"Timeline"}),e.jsxs(vs,{value:J,onValueChange:ce,children:[e.jsx(gs,{className:"mt-1",children:e.jsx(bs,{placeholder:"Select..."})}),e.jsxs(ys,{children:[e.jsx(Ye,{value:"ASAP",children:"ASAP"}),e.jsx(Ye,{value:"30 days",children:"30 days"}),e.jsx(Ye,{value:"60 days",children:"60 days"}),e.jsx(Ye,{value:"90+ days",children:"90+ days"})]})]})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-xs",children:"Pre-approved?"}),e.jsxs(vs,{value:ue,onValueChange:ne,children:[e.jsx(gs,{className:"mt-1",children:e.jsx(bs,{placeholder:"Select..."})}),e.jsxs(ys,{children:[e.jsx(Ye,{value:"Yes",children:"Yes"}),e.jsx(Ye,{value:"No",children:"No"}),e.jsx(Ye,{value:"In progress",children:"In progress"})]})]})]})]})]}),e.jsxs("div",{children:[e.jsxs(se,{className:"text-xs",children:["Message",d==="question"?" *":" (optional)"]}),e.jsx(Is,{value:h,onChange:ke=>m(ke.target.value),placeholder:WLe[d].placeholder,rows:4,className:"mt-1"})]}),e.jsx($,{onClick:De,disabled:b||!Me,className:"w-full h-12 text-white hover:opacity-90",style:c?{backgroundColor:c}:void 0,children:b?e.jsx(Ht,{className:"h-4 w-4 animate-spin"}):"Send to agent"})]})]})})})]})}const Mws=tk({first_name:rl().trim().min(1,"First name is required").max(50),last_name:rl().trim().max(50).optional(),email:rl().trim().email("Please enter a valid email").max(255).optional().or(Sx("")),phone:rl().trim().max(20).optional().or(Sx(""))}),Lws=[{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 VAt({slug:s}={}){var qe;const t=Vi(),n=s||t.slug,[r]=oc(),a=r.get("kiosk")==="1"||r.get("mode")==="kiosk",i=8,{data:l,isLoading:o,error:c}=RAt(n),d=iws(),u=ows(),h=lws(),m=j.useRef(!1),[p,x]=j.useState("welcome"),[g,y]=j.useState(null),[b,v]=j.useState({first_name:"",last_name:"",email:"",phone:"",visitor_address:""}),[N,C]=j.useState(""),[A,T]=j.useState(!1),[P,M]=j.useState(!1),[I,D]=j.useState(""),[B,q]=j.useState(""),[W,V]=j.useState(i),K=j.useCallback(()=>{y(null),v({first_name:"",last_name:"",email:"",phone:"",visitor_address:""}),C(""),T(!1),M(!1),D(""),q(""),V(i),x(a?"info":"welcome")},[a]),Q=j.useCallback((Ke,Ze)=>{l!=null&&l.id&&U.functions.invoke("guestbook-lead-notify",{body:{open_house_id:l.id,visitor_id:Ke,first_name:Ze.first_name??b.first_name,last_name:Ze.last_name??b.last_name,email:Ze.email??b.email,phone:Ze.phone??b.phone,visitor_intent:Ze.visitor_intent??N,message:Ze.message,wants_market_updates:Ze.wants_market_updates??A,has_agent:Ze.has_agent??P,working_with_agent_name:Ze.working_with_agent_name??I,visitor_address:Ze.visitor_address??b.visitor_address}}).catch(Ue=>console.error("Guest book lead notify failed:",Ue))},[l==null?void 0:l.id,b,N,A,P,I]);j.useEffect(()=>{if(!a||p!=="done")return;V(i);const Ke=setInterval(()=>{V(Ze=>Ze<=1?(clearInterval(Ke),K(),0):Ze-1)},1e3);return()=>clearInterval(Ke)},[a,p,K]),j.useEffect(()=>{if(!a)return;x(Ze=>Ze==="welcome"?"info":Ze);let Ke=null;return(async()=>{var Ze,Ue;try{Ke=await((Ue=(Ze=navigator.wakeLock)==null?void 0:Ze.request)==null?void 0:Ue.call(Ze,"screen"))}catch{}})(),()=>{var Ze;try{(Ze=Ke==null?void 0:Ke.release)==null||Ze.call(Ke)}catch{}}},[a]);const J=j.useCallback(()=>{var Ze;const Ke=document.documentElement;document.fullscreenElement||(Ze=Ke.requestFullscreen||Ke.webkitRequestFullscreen)==null||Ze.call(Ke).catch(()=>{})},[]),{data:ce,isLoading:ue}=J_s(l==null?void 0:l.id),ne=!!(l!=null&&l.enable_survey),ee=(l==null?void 0:l.ask_visitor_intent)!==!1,le=(l==null?void 0:l.ask_visitor_address)===!0;j.useEffect(()=>{if(!n||!(l!=null&&l.id)||m.current)return;const Ke=`oh_scan_${l.id}`;if(sessionStorage.getItem(Ke)){m.current=!0;return}m.current=!0,sessionStorage.setItem(Ke,"1"),h.mutate(n)},[n,l==null?void 0:l.id]),j.useEffect(()=>{p==="pending_survey"&&(ue||x(ne&&((ce==null?void 0:ce.length)??0)>0?"survey":"done"))},[p,ue,ne,ce]);const he=Ke=>{if(!Ke)return"";const[Ze,Ue]=Ke.split(":"),et=parseInt(Ze),Qe=et>=12?"PM":"AM";return`${et>12?et-12:et||12}:${Ue} ${Qe}`},ve=async()=>{q("");const Ke=Mws.safeParse(b);if(!Ke.success){q(Ke.error.issues[0].message);return}if(!b.email&&!b.phone){q("Please provide either an email or phone number");return}const Ze=(l==null?void 0:l.kind)==="virtual";let Ue=null;if(!g&&(l!=null&&l.id))try{const et=await d.mutateAsync({open_house_id:l.id,first_name:b.first_name.trim(),last_name:b.last_name.trim()||void 0,email:b.email.trim()||void 0,phone:b.phone.trim()||void 0,visitor_address:le&&b.visitor_address.trim()?b.visitor_address.trim():void 0,wants_market_updates:A,has_agent:P,working_with_agent_name:P&&I.trim()?I.trim():void 0,partial_signin:Ze?!1:ee});Ue=et.id,y(et.id)}catch{if(Ze){q("We could not start the virtual tour. Please try again.");return}}if(Ze){ee?x("intent"):(Ue&&Q(Ue,{}),x("done"));return}if(!ee){Ue&&Q(Ue,{}),ne?!ue&&ce&&ce.length>0?x("survey"):x("pending_survey"):x("done");return}x("intent")},ge=async Ke=>{C(Ke);try{let Ze=g;if(Ze?await u.mutateAsync({visitor_id:Ze,visitor_intent:Ke,wants_market_updates:A,has_agent:P,working_with_agent_name:P&&I.trim()?I.trim():null,partial_signin:!1}):(Ze=(await d.mutateAsync({open_house_id:l.id,first_name:b.first_name.trim(),last_name:b.last_name.trim()||void 0,email:b.email.trim()||void 0,phone:b.phone.trim()||void 0,visitor_address:le&&b.visitor_address.trim()?b.visitor_address.trim():void 0,visitor_intent:Ke,wants_market_updates:A,has_agent:P,working_with_agent_name:P&&I.trim()?I.trim():void 0,partial_signin:!1})).id,y(Ze)),Ze&&Q(Ze,{visitor_intent:Ke,wants_market_updates:A,has_agent:P,working_with_agent_name:P&&I.trim()?I.trim():null}),(l==null?void 0:l.kind)==="virtual"){x("done");return}ne?!ue&&ce&&ce.length>0?x("survey"):x("pending_survey"):x("done")}catch{q("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(sa,{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 fe=l.profiles,je=((qe=fe==null?void 0:fe.name)==null?void 0:qe.split(" ").map(Ke=>Ke[0]).join("").slice(0,2))||"?",Ee=l.event_type==="community",Me=l.kind==="virtual",De=typeof window<"u"&&new URLSearchParams(window.location.search).get("preview")==="1";if(Me&&(De||p==="done"))return!De&&!g?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(Ul,{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"})]}),De&&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(Tws,{openHouse:l,visitorId:De?"preview":g,visitorName:De?"Preview Visitor":`${b.first_name} ${b.last_name}`.trim(),visitorEmail:De?"":b.email,visitorPhone:De?"":b.phone,previewMode:De})]});const ke=`${Me?"Virtual Open House":Ee?"Community Event":"Open House"} — ${l.property_address}`,Se=[[l.city,l.state].filter(Boolean).join(", "),l.event_date?Hs(new Date(l.event_date+"T00:00:00"),"EEE, MMM d"):null,fe!=null&&fe.name?`Hosted by ${fe.name}`:null].filter(Boolean).join(" · "),Re=l.photo_url||"",Ae=Re&&Re.includes("/storage/v1/object/public/")?Re.replace("/object/public/","/render/image/public/")+"?width=1200&height=630&resize=cover":Re||"https://dashboard.relevelup.com/og-image.png",Be=typeof window<"u"?window.location.href:`https://guestbook.relevelup.com/${n}`;return e.jsxs(e.Fragment,{children:[e.jsxs(Ul,{children:[e.jsx("title",{children:ke}),e.jsx("meta",{name:"description",content:Se||`Sign in to ${l.property_address}`}),e.jsx("meta",{property:"og:type",content:"website"}),e.jsx("meta",{property:"og:title",content:ke}),e.jsx("meta",{property:"og:description",content:Se||`Sign in to ${l.property_address}`}),e.jsx("meta",{property:"og:image",content:Ae}),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:Be}),e.jsx("meta",{property:"og:site_name",content:"ReLevel Up"}),e.jsx("meta",{name:"twitter:card",content:"summary_large_image"}),e.jsx("meta",{name:"twitter:title",content:ke}),e.jsx("meta",{name:"twitter:description",content:Se||`Sign in to ${l.property_address}`}),e.jsx("meta",{name:"twitter:image",content:Ae}),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(ki,{src:(fe==null?void 0:fe.avatar_url)||"",alt:(fe==null?void 0:fe.name)||""}),e.jsx(Ta,{className:"bg-white/10 text-white text-lg",children:je})]}),e.jsx("p",{className:"text-white/60 text-sm",children:fe==null?void 0:fe.name}),(fe==null?void 0:fe.title)&&e.jsx("p",{className:"text-white/40 text-xs",children:fe.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(ai,{className:"h-3 w-3"}),l.city,l.state?`, ${l.state}`:""," ",l.zip]}),!Me&&e.jsxs(e.Fragment,{children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(ia,{className:"h-3 w-3"}),Hs(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(Hr,{className:"h-3 w-3"}),he(l.start_time),l.end_time?` – ${he(l.end_time)}`:""]})]})]})]})]}),!l.photo_url&&e.jsx("div",{className:"bg-gradient-to-r from-slate-800 to-slate-700 px-6 py-5",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:"w-10 h-10 rounded-xl bg-white/10 flex items-center justify-center shrink-0 mt-0.5",children:Ee?e.jsx(Ai,{className:"h-5 w-5 text-white"}):e.jsx(sa,{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(ai,{className:"h-3 w-3"}),l.city,l.state?`, ${l.state}`:""," ",l.zip]}),!Me&&e.jsxs(e.Fragment,{children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(ia,{className:"h-3 w-3"}),Hs(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(Hr,{className:"h-3 w-3"}),he(l.start_time),l.end_time?` – ${he(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($,{onClick:()=>x("info"),className:"w-full h-14 text-base bg-slate-900 hover:bg-slate-800 text-white rounded-xl",children:["Sign In ",e.jsx(ni,{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:()=>x("welcome"),className:"text-slate-400 hover:text-slate-600",children:e.jsx(ka,{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(se,{className:"text-slate-600 text-xs",children:"First Name *"}),e.jsx(be,{value:b.first_name,onChange:Ke=>v(Ze=>({...Ze,first_name:Ke.target.value})),placeholder:"First",className:"mt-1 h-12 rounded-xl border-slate-200 text-base",autoFocus:!0})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-slate-600 text-xs",children:"Last Name"}),e.jsx(be,{value:b.last_name,onChange:Ke=>v(Ze=>({...Ze,last_name:Ke.target.value})),placeholder:"Last",className:"mt-1 h-12 rounded-xl border-slate-200 text-base"})]})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-slate-600 text-xs",children:"Email"}),e.jsx(be,{type:"email",value:b.email,onChange:Ke=>v(Ze=>({...Ze,email:Ke.target.value})),placeholder:"your@email.com",className:"mt-1 h-12 rounded-xl border-slate-200 text-base"})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-slate-600 text-xs",children:"Phone"}),e.jsx(be,{type:"tel",value:b.phone,onChange:Ke=>v(Ze=>({...Ze,phone:Ke.target.value})),placeholder:"(555) 123-4567",className:"mt-1 h-12 rounded-xl border-slate-200 text-base"})]}),le&&e.jsxs("div",{children:[e.jsx(se,{className:"text-slate-600 text-xs",children:"Your Home Address"}),e.jsx(be,{value:b.visitor_address,onChange:Ke=>v(Ze=>({...Ze,visitor_address:Ke.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:Ke=>T(Ke.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:P?"Yes":"No"}),e.jsx(Tn,{checked:P,onCheckedChange:M})]})]}),P&&e.jsx(be,{value:I,onChange:Ke=>D(Ke.target.value),placeholder:"Agent's name",className:"mt-1 h-10 rounded-xl border-slate-200 text-sm"})]}),B&&e.jsx("p",{className:"text-destructive text-sm",children:B}),e.jsxs($,{onClick:ve,className:"w-full h-14 text-base bg-slate-900 hover:bg-slate-800 text-white rounded-xl",children:["Continue ",e.jsx(ni,{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:()=>x("info"),className:"text-slate-400 hover:text-slate-600",children:e.jsx(ka,{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:Lws.map(Ke=>e.jsxs("button",{onClick:()=>ge(Ke.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:Ke.emoji}),e.jsx("span",{className:"text-sm font-medium text-slate-700 group-hover:text-slate-900",children:Ke.label})]},Ke.value))}),B&&e.jsx("p",{className:"text-destructive text-sm text-center",children:B})]}),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"&&g&&ce&&e.jsx(kws,{questions:ce,visitorId:g,onComplete:()=>x("done"),onSkip:()=>x("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(Fr,{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, ",b.first_name,". ",Ee?"Enjoy the event!":"Enjoy the open house!"]})]}),(l==null?void 0:l.disclosure_pdf_url)&&e.jsxs("a",{href:`https://docs.google.com/gview?url=${encodeURIComponent(l.disclosure_pdf_url)}&embedded=true`,target:"_blank",rel:"noopener noreferrer",className:"inline-flex items-center gap-2 px-5 py-3 rounded-xl bg-slate-100 hover:bg-slate-200 text-slate-800 font-medium text-sm transition-colors",children:[e.jsx(Wr,{className:"h-4 w-4"}),"View Seller's Disclosures"]}),(fe==null?void 0:fe.name)&&e.jsxs("p",{className:"text-sm text-slate-400",children:["Your host today: ",e.jsx("strong",{className:"text-slate-600",children:fe.name})]}),a&&e.jsxs("div",{className:"pt-4 space-y-3",children:[e.jsx($,{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 ",W,"s…"]})]})]})]})]}),e.jsx("p",{className:"text-center text-white/30 text-xs mt-6",children:"Powered by LevelUp Guest Book"}),a&&e.jsxs("div",{className:"fixed top-3 right-3 flex items-center gap-2 z-50",children:[e.jsxs("span",{className:"inline-flex items-center gap-1.5 rounded-full bg-white/10 backdrop-blur-sm text-white/80 text-[11px] px-2.5 py-1 border border-white/10",children:[e.jsx(qz,{className:"h-3 w-3"})," Tablet Mode"]}),e.jsx("button",{onClick:J,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(PK,{className:"h-3 w-3"})})]})]})})]})}function Pws(s){return ht({queryKey:["open-house-rsvps",s],queryFn:async()=>{const{data:t,error:n}=await U.from("open_house_rsvps").select("*").eq("open_house_id",s).order("created_at",{ascending:!1});if(n)throw n;return t||[]},enabled:!!s})}function Iws(){const s=ts();return yt({mutationFn:async t=>{const{error:n}=await U.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 Dws(s){const t=ts();return yt({mutationFn:async n=>{const{error:r}=await U.from("open_house_rsvps").delete().eq("id",n);if(r)throw r},onSuccess:()=>t.invalidateQueries({queryKey:["open-house-rsvps",s]})})}function Rws(s){const t=ts();return yt({mutationFn:async({id:n,checkedIn:r})=>{const{error:a}=await U.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 Ows=tk({first_name:rl().trim().min(1,"First name is required").max(50),last_name:rl().trim().max(50).optional(),email:rl().trim().email("Please enter a valid email").max(255),phone:rl().trim().max(20).optional().or(Sx("")),message:rl().trim().max(500).optional().or(Sx(""))}),KLe=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}`},Fws=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 HAt({slug:s}={}){const t=Vi(),n=s||t.slug,{data:r,isLoading:a,error:i}=RAt(n),l=Iws(),[o,c]=j.useState({first_name:"",last_name:"",email:"",phone:"",message:""}),[d,u]=j.useState(!1),[h,m]=j.useState(""),[p,x]=j.useState(""),[g,y]=j.useState(!1),b=j.useMemo(()=>Fws(r==null?void 0:r.event_date),[r==null?void 0:r.event_date]),v=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,C=[r==null?void 0:r.city,r==null?void 0:r.state].filter(Boolean).join(", "),A=async()=>{x("");const M=Ows.safeParse(o);if(!M.success){x(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){x((I==null?void 0:I.message)||"Something went wrong. Please try again.")}},T=j.useMemo(()=>{if(!r||!b)return"";const M=V=>String(V).padStart(2,"0"),I=`${b.getFullYear()}${M(b.getMonth()+1)}${M(b.getDate())}`,D=(r.start_time||"12:00").slice(0,5).replace(":","")+"00",B=(r.end_time||"14:00").slice(0,5).replace(":","")+"00",q=encodeURIComponent(`Open House — ${r.property_address}`),W=encodeURIComponent([r.property_address,C,r.zip].filter(Boolean).join(", "));return`https://calendar.google.com/calendar/render?action=TEMPLATE&text=${q}&dates=${I}T${D}/${I}T${B}&location=${W}`},[r,b,C]);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(sa,{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 P=`https://www.google.com/maps/search/?api=1&query=${encodeURIComponent([r.property_address,C,r.zip].filter(Boolean).join(", "))}`;return e.jsxs("div",{className:"min-h-screen bg-[#f6f2ee]",children:[e.jsxs(Ul,{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}${b?` on ${Hs(b,"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:[v&&e.jsx("img",{src:v,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}),C&&e.jsxs("p",{className:"mt-1 text-white/70",children:[C," ",r.zip||""]}),e.jsxs("div",{className:"mt-4 flex flex-wrap gap-x-5 gap-y-2 text-sm text-white/85",children:[b&&e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(ia,{className:"h-4 w-4 text-[#d4b978]"}),Hs(b,"EEEE, MMMM d, yyyy")]}),r.start_time&&e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(Hr,{className:"h-4 w-4 text-[#d4b978]"}),KLe(r.start_time),r.end_time?` – ${KLe(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(kne,{icon:e.jsx(sa,{className:"h-4 w-4"}),label:"Price",value:`$${Number(r.price).toLocaleString()}`}):null,r.beds?e.jsx(kne,{icon:e.jsx(JS,{className:"h-4 w-4"}),label:"Beds",value:String(r.beds)}):null,r.baths?e.jsx(kne,{icon:e.jsx(_g,{className:"h-4 w-4"}),label:"Baths",value:String(r.baths)}):null,r.sqft?e.jsx(kne,{icon:e.jsx(o5,{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:g?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(Fr,{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 ",b?Hs(b,"EEEE, MMMM d"):"soon",r.start_time?` at ${KLe(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($,{asChild:!0,className:"bg-[#1b3a4b] hover:bg-[#25505f]",children:e.jsxs("a",{href:T,target:"_blank",rel:"noreferrer",children:[e.jsx(gg,{className:"mr-2 h-4 w-4"}),"Add to calendar"]})}),e.jsx($,{asChild:!0,variant:"outline",children:e.jsxs("a",{href:P,target:"_blank",rel:"noreferrer",children:[e.jsx(ai,{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(se,{htmlFor:"rsvp-first",children:"First name *"}),e.jsx(be,{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(se,{htmlFor:"rsvp-last",children:"Last name"}),e.jsx(be,{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(se,{htmlFor:"rsvp-email",children:"Email *"}),e.jsx(be,{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(se,{htmlFor:"rsvp-phone",children:"Phone"}),e.jsx(be,{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(Tn,{checked:d,onCheckedChange:u})]}),d&&e.jsx(be,{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(se,{htmlFor:"rsvp-msg",children:"Anything you'd like us to know?"}),e.jsx(Is,{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($,{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(ni,{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(ki,{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:P,target:"_blank",rel:"noreferrer",className:"inline-flex items-center gap-1.5 text-sm text-[#406E71] hover:underline",children:[e.jsx(ai,{className:"h-4 w-4"}),"Get directions to ",r.property_address]})})]})]})}function kne({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 BXn(s){const{user:t}=_s();return ht({queryKey:["cohost-tokens",s],queryFn:async()=>{const{data:n,error:r}=await U.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 $Xn(){const s=ts(),{user:t}=_s();return yt({mutationFn:async({openHouseId:n,label:r})=>{const{data:a,error:i}=await U.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 UXn(){const s=ts();return yt({mutationFn:async({id:t,openHouseId:n})=>{const{error:r}=await U.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 zws(s){return ht({queryKey:["cohost-validate",s],queryFn:async()=>{const{data:t,error:n}=await U.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 _5=(s,t,n)=>n>t?t:n{},tU=()=>{};const a6={},WAt=s=>/^-?(?:\d+(?:\.\d+)?|\.\d+)$/u.test(s);function KAt(s){return typeof s=="object"&&s!==null}const YAt=s=>/^0[^.\s]+$/u.test(s);function ZAt(s){let t;return()=>(t===void 0&&(t=s()),t)}const Xj=s=>s,$ws=(s,t)=>n=>t(s(n)),xee=(...s)=>s.reduce($ws),VZ=(s,t,n)=>{const r=t-s;return r===0?1:(n-s)/r};class MHe{constructor(){this.subscriptions=[]}add(t){return THe(this.subscriptions,t),()=>Gke(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,Dj=s=>s/1e3;function XAt(s,t){return t?s*(1e3/t):0}const QAt=(s,t,n)=>(((1-3*n+3*t)*s+(3*n-6*t))*s+3*t)*s,Uws=1e-7,qws=12;function Vws(s,t,n,r,a){let i,l,o=0;do l=t+(n-t)/2,i=QAt(l,r,a)-s,i>0?n=l:t=l;while(Math.abs(i)>Uws&&++oVws(i,0,1,s,n);return i=>i===0||i===1?i:QAt(a(i),t,r)}const JAt=s=>t=>t<=.5?s(2*t)/2:(2-s(2*(1-t)))/2,eEt=s=>t=>1-s(1-t),tEt=gee(.33,1.53,.69,.99),LHe=eEt(tEt),sEt=JAt(LHe),nEt=s=>s>=1?1:(s*=2)<1?.5*LHe(s):.5*(2-Math.pow(2,-10*(s-1))),PHe=s=>1-Math.sin(Math.acos(s)),rEt=eEt(PHe),aEt=JAt(PHe),Hws=gee(.42,0,1,1),Gws=gee(0,0,.58,1),iEt=gee(.42,0,.58,1),Wws=s=>Array.isArray(s)&&typeof s[0]!="number",oEt=s=>Array.isArray(s)&&typeof s[0]=="number",pit={linear:Xj,easeIn:Hws,easeInOut:iEt,easeOut:Gws,circIn:PHe,circInOut:aEt,circOut:rEt,backIn:LHe,backInOut:sEt,backOut:tEt,anticipate:nEt},Kws=s=>typeof s=="string",fit=s=>{if(oEt(s)){tU(s.length===4,"Cubic bezier arrays must contain four numerical values.","cubic-bezier-length");const[t,n,r,a]=s;return gee(t,n,r,a)}else if(Kws(s))return tU(pit[s]!==void 0,`Invalid easing type '${s}'`,"invalid-easing-type"),pit[s];return s},Sne=["setup","read","resolveKeyframes","preUpdate","update","preRender","render","postRender"],xit={value:null,addProjectionMetrics:null};function Yws(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 g=p&&a?n:r;return m&&l.add(h),g.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&&xit.value&&xit.value.frameloop[t].push(c),c=0,n.clear(),a=!1,i&&(i=!1,u.process(h))}};return u}const Zws=40;function lEt(s,t){let n=!1,r=!0;const a={delta:0,timestamp:0,isProcessing:!1},i=()=>n=!0,l=Sne.reduce((N,C)=>(N[C]=Yws(i,t?C:void 0),N),{}),{setup:o,read:c,resolveKeyframes:d,preUpdate:u,update:h,preRender:m,render:p,postRender:x}=l,g=()=>{const N=a6.useManualTiming,C=N?a.timestamp:performance.now();n=!1,N||(a.delta=r?1e3/60:Math.max(Math.min(C-a.timestamp,Zws),1)),a.timestamp=C,a.isProcessing=!0,o.process(a),c.process(a),d.process(a),u.process(a),h.process(a),m.process(a),p.process(a),x.process(a),a.isProcessing=!1,n&&t&&(r=!1,s(g))},y=()=>{n=!0,r=!0,a.isProcessing||s(g)};return{schedule:Sne.reduce((N,C)=>{const A=l[C];return N[C]=(T,P=!1,M=!1)=>(n||y(),A.schedule(T,P,M)),N},{}),cancel:N=>{for(let C=0;C(b2e===void 0&&i1.set(iy.isProcessing||a6.useManualTiming?iy.timestamp:performance.now()),b2e),set:s=>{b2e=s,queueMicrotask(Xws)}},cEt=s=>t=>typeof t=="string"&&t.startsWith(s),dEt=cEt("--"),Qws=cEt("var(--"),IHe=s=>Qws(s)?Jws.test(s.split("/*")[0].trim()):!1,Jws=/var\(--(?:[\w-]+\s*|[\w-]+\s*,(?:\s*[^)(\s]|\s*\((?:[^)(]|\([^)(]*\))*\))+\s*)\)$/iu;function git(s){return typeof s!="string"?!1:s.split("/*")[0].includes("var(--")}const Eq={test:s=>typeof s=="number",parse:parseFloat,transform:s=>s},HZ={...Eq,transform:s=>_5(0,1,s)},Cne={...Eq,default:1},xY=s=>Math.round(s*1e5)/1e5,DHe=/-?(?:\d+(?:\.\d+)?|\.\d+)/gu;function ejs(s){return s==null}const tjs=/^(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))$/iu,RHe=(s,t)=>n=>!!(typeof n=="string"&&tjs.test(n)&&n.startsWith(s)||t&&!ejs(n)&&Object.prototype.hasOwnProperty.call(n,t)),uEt=(s,t,n)=>r=>{if(typeof r!="string")return r;const[a,i,l,o]=r.match(DHe);return{[s]:parseFloat(a),[t]:parseFloat(i),[n]:parseFloat(l),alpha:o!==void 0?parseFloat(o):1}},sjs=s=>_5(0,255,s),ZLe={...Eq,transform:s=>Math.round(sjs(s))},M8={test:RHe("rgb","red"),parse:uEt("red","green","blue"),transform:({red:s,green:t,blue:n,alpha:r=1})=>"rgba("+ZLe.transform(s)+", "+ZLe.transform(t)+", "+ZLe.transform(n)+", "+xY(HZ.transform(r))+")"};function njs(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 $Fe={test:RHe("#"),parse:njs,transform:M8.transform},yee=s=>({test:t=>typeof t=="string"&&t.endsWith(s)&&t.split(" ").length===1,parse:parseFloat,transform:t=>`${t}${s}`}),NA=yee("deg"),u5=yee("%"),ao=yee("px"),rjs=yee("vh"),ajs=yee("vw"),yit={...u5,parse:s=>u5.parse(s)/100,transform:s=>u5.transform(s*100)},U9={test:RHe("hsl","hue"),parse:uEt("hue","saturation","lightness"),transform:({hue:s,saturation:t,lightness:n,alpha:r=1})=>"hsla("+Math.round(s)+", "+u5.transform(xY(t))+", "+u5.transform(xY(n))+", "+xY(HZ.transform(r))+")"},kx={test:s=>M8.test(s)||$Fe.test(s)||U9.test(s),parse:s=>M8.test(s)?M8.parse(s):U9.test(s)?U9.parse(s):$Fe.parse(s),transform:s=>typeof s=="string"?s:s.hasOwnProperty("red")?M8.transform(s):U9.transform(s),getAnimatableNone:s=>{const t=kx.parse(s);return t.alpha=0,kx.transform(t)}},ijs=/(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))/giu;function ojs(s){var t,n;return isNaN(s)&&typeof s=="string"&&(((t=s.match(DHe))==null?void 0:t.length)||0)+(((n=s.match(ijs))==null?void 0:n.length)||0)>0}const hEt="number",mEt="color",ljs="var",cjs="var(",vit="${}",djs=/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 sU(s){const t=s.toString(),n=[],r={color:[],number:[],var:[]},a=[];let i=0;const o=t.replace(djs,c=>(kx.test(c)?(r.color.push(i),a.push(mEt),n.push(kx.parse(c))):c.startsWith(cjs)?(r.var.push(i),a.push(ljs),n.push(c)):(r.number.push(i),a.push(hEt),n.push(parseFloat(c))),++i,vit)).split(vit);return{values:n,split:o,indexes:r,types:a}}function ujs(s){return sU(s).values}function pEt({split:s,types:t}){const n=s.length;return r=>{let a="";for(let i=0;itypeof s=="number"?0:kx.test(s)?kx.getAnimatableNone(s):s,pjs=(s,t)=>typeof s=="number"?t!=null&&t.trim().endsWith("/")?s:0:mjs(s);function fjs(s){const t=sU(s);return pEt(t)(t.values.map((r,a)=>pjs(r,t.split[a])))}const zN={test:ojs,parse:ujs,createTransformer:hjs,getAnimatableNone:fjs};function XLe(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 xjs({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=XLe(c,o,s+1/3),i=XLe(c,o,s),l=XLe(c,o,s-1/3)}return{red:Math.round(a*255),green:Math.round(i*255),blue:Math.round(l*255),alpha:r}}function Wke(s,t){return n=>n>0?t:s}const jm=(s,t,n)=>s+(t-s)*n,QLe=(s,t,n)=>{const r=s*s,a=n*(t*t-r)+r;return a<0?0:Math.sqrt(a)},gjs=[$Fe,M8,U9],yjs=s=>gjs.find(t=>t.test(s));function bit(s){const t=yjs(s);if(HCe(!!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===U9&&(n=xjs(n)),n}const _it=(s,t)=>{const n=bit(s),r=bit(t);if(!n||!r)return Wke(s,t);const a={...n};return i=>(a.red=QLe(n.red,r.red,i),a.green=QLe(n.green,r.green,i),a.blue=QLe(n.blue,r.blue,i),a.alpha=jm(n.alpha,r.alpha,i),M8.transform(a))},UFe=new Set(["none","hidden"]);function vjs(s,t){return UFe.has(s)?n=>n<=0?s:t:n=>n>=1?t:s}function bjs(s,t){return n=>jm(s,t,n)}function OHe(s){return typeof s=="number"?bjs:typeof s=="string"?IHe(s)?Wke:kx.test(s)?_it:jjs:Array.isArray(s)?fEt:typeof s=="object"?kx.test(s)?_it:_js:Wke}function fEt(s,t){const n=[...s],r=n.length,a=s.map((i,l)=>OHe(i)(i,t[l]));return i=>{for(let l=0;l{for(const i in r)n[i]=r[i](a);return n}}function wjs(s,t){const n=[],r={color:0,var:0,number:0};for(let a=0;a{const n=zN.createTransformer(t),r=sU(s),a=sU(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?UFe.has(s)&&!a.values.length||UFe.has(t)&&!r.values.length?vjs(s,t):xee(fEt(wjs(r,a),a.values),n):(HCe(!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"),Wke(s,t))};function xEt(s,t,n){return typeof s=="number"&&typeof t=="number"&&typeof n=="number"?jm(s,t,n):OHe(s)(s,t)}const Njs=s=>{const t=({timestamp:n})=>s(n);return{start:(n=!0)=>Th.update(t,n),stop:()=>i6(t),now:()=>iy.isProcessing?iy.timestamp:i1.now()}},gEt=(s,t,n=10)=>{let r="";const a=Math.max(Math.round(t/n),2);for(let i=0;i=Kke?1/0:t}function kjs(s,t=100,n){const r=n({...s,keyframes:[0,t]}),a=Math.min(FHe(r),Kke);return{type:"keyframes",ease:i=>r.next(a*i).value/t,duration:Dj(a)}}const Ap={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 qFe(s,t){return s*Math.sqrt(1-t*t)}const Sjs=12;function Cjs(s,t,n){let r=n;for(let a=1;a{const u=d*l,h=u*s,m=u-n,p=qFe(d,l),x=Math.exp(-h);return JLe-m/p*x},i=d=>{const h=d*l*s,m=h*n+n,p=Math.pow(l,2)*Math.pow(d,2)*s,x=Math.exp(-h),g=qFe(Math.pow(d,2),l);return(-a(d)+JLe>0?-1:1)*((m-p)*x)/g}):(a=d=>{const u=Math.exp(-d*s),h=(d-n)*s+1;return-JLe+u*h},i=d=>{const u=Math.exp(-d*s),h=(n-d)*(s*s);return u*h});const o=5/s,c=Cjs(a,i,o);if(s=Ib(s),isNaN(c))return{stiffness:Ap.stiffness,damping:Ap.damping,duration:s};{const d=Math.pow(c,2)*r;return{stiffness:d,damping:l*2*Math.sqrt(r*d),duration:s}}}const Ejs=["duration","bounce"],Tjs=["stiffness","damping","mass"];function wit(s,t){return t.some(n=>s[n]!==void 0)}function Mjs(s){let t={velocity:Ap.velocity,stiffness:Ap.stiffness,damping:Ap.damping,mass:Ap.mass,isResolvedFromDuration:!1,...s};if(!wit(s,Tjs)&&wit(s,Ejs))if(t.velocity=0,s.visualDuration){const n=s.visualDuration,r=2*Math.PI/(n*1.2),a=r*r,i=2*_5(.05,1,1-(s.bounce||0))*Math.sqrt(a);t={...t,mass:Ap.mass,stiffness:a,damping:i}}else{const n=Ajs({...s,velocity:0});t={...t,...n,mass:Ap.mass},t.isResolvedFromDuration=!0}return t}function Yke(s=Ap.visualDuration,t=Ap.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}=Mjs({...n,velocity:-Dj(n.velocity||0)}),x=m||0,g=d/(2*Math.sqrt(c*u)),y=l-i,b=Dj(Math.sqrt(c/u)),v=Math.abs(y)<5;r||(r=v?Ap.restSpeed.granular:Ap.restSpeed.default),a||(a=v?Ap.restDelta.granular:Ap.restDelta.default);let N,C,A,T,P,M;if(g<1)A=qFe(b,g),T=(x+g*b*y)/A,N=D=>{const B=Math.exp(-g*b*D);return l-B*(T*Math.sin(A*D)+y*Math.cos(A*D))},P=g*b*T+y*A,M=g*b*y-T*A,C=D=>Math.exp(-g*b*D)*(P*Math.sin(A*D)+M*Math.cos(A*D));else if(g===1){N=B=>l-Math.exp(-b*B)*(y+(x+b*y)*B);const D=x+b*y;C=B=>Math.exp(-b*B)*(b*D*B-x)}else{const D=b*Math.sqrt(g*g-1);N=V=>{const K=Math.exp(-g*b*V),Q=Math.min(D*V,300);return l-K*((x+g*b*y)*Math.sinh(Q)+D*y*Math.cosh(Q))/D};const B=(x+g*b*y)/D,q=g*b*B-y*D,W=g*b*y-B*D;C=V=>{const K=Math.exp(-g*b*V),Q=Math.min(D*V,300);return K*(q*Math.sinh(Q)+W*Math.cosh(Q))}}const I={calculatedDuration:p&&h||null,velocity:D=>Ib(C(D)),next:D=>{if(!p&&g<1){const q=Math.exp(-g*b*D),W=Math.sin(A*D),V=Math.cos(A*D),K=l-q*(T*W+y*V),Q=Ib(q*(P*W+M*V));return o.done=Math.abs(Q)<=r&&Math.abs(l-K)<=a,o.value=o.done?l:K,o}const B=N(D);if(p)o.done=D>=h;else{const q=Ib(C(D));o.done=Math.abs(q)<=r&&Math.abs(l-B)<=a}return o.value=o.done?l:B,o},toString:()=>{const D=Math.min(FHe(I),Kke),B=gEt(q=>I.next(D*q).value,D,30);return D+"ms "+B},toTransition:()=>{}};return I}Yke.applyToOptions=s=>{const t=kjs(s,100,Yke);return s.ease=t.ease,s.duration=Ib(t.duration),s.type="keyframes",s};const Ljs=5;function yEt(s,t,n){const r=Math.max(t-Ljs,0);return XAt(n-s(r),t-r)}function VFe({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,x=M=>o===void 0?c:c===void 0||Math.abs(o-M)-g*Math.exp(-M/r),N=M=>b+v(M),C=M=>{const I=v(M),D=N(M);m.done=Math.abs(I)<=d,m.value=m.done?b:D};let A,T;const P=M=>{p(m.value)&&(A=M,T=Yke({keyframes:[m.value,x(m.value)],velocity:yEt(N,M,m.value),damping:a,stiffness:i,restDelta:d,restSpeed:u}))};return P(0),{calculatedDuration:null,next:M=>{let I=!1;return!T&&A===void 0&&(I=!0,C(M),P(M)),A!==void 0&&M>=A?T.next(M-A):(!I&&C(M),m)}}}function Pjs(s,t,n){const r=[],a=n||a6.mix||xEt,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=Pjs(t,r,a),c=o.length,d=u=>{if(l&&u1)for(;hd(_5(s[0],s[i-1],u)):d}function Djs(s,t){const n=s[s.length-1];for(let r=1;r<=t;r++){const a=VZ(0,t,r);s.push(jm(n,1,a))}}function Rjs(s){const t=[0];return Djs(t,s.length-1),t}function Ojs(s,t){return s.map(n=>n*t)}function Fjs(s,t){return s.map(()=>t||iEt).splice(0,s.length-1)}function gY({duration:s=300,keyframes:t,times:n,ease:r="easeInOut"}){const a=Wws(r)?r.map(fit):fit(r),i={done:!1,value:t[0]},l=Ojs(n&&n.length===t.length?n:Rjs(t),s),o=Ijs(l,t,{ease:Array.isArray(a)?a:Fjs(t,a)});return{calculatedDuration:s,next:c=>(i.value=o(c),i.done=c>=s,i)}}const zjs=s=>s!==null;function GCe(s,{repeat:t,repeatType:n="loop"},r,a=1){const i=s.filter(zjs),o=a<0||t&&n!=="loop"&&t%2===1?0:i.length-1;return!o||r===void 0?i[o]:r}const Bjs={decay:VFe,inertia:VFe,tween:gY,keyframes:gY,spring:Yke};function vEt(s){typeof s.type=="string"&&(s.type=Bjs[s.type])}class zHe{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 $js=s=>s/100;class Zke extends zHe{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!==i1.now()&&this.tick(i1.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;vEt(t);const{type:n=gY,repeat:r=0,repeatDelay:a=0,repeatType:i,velocity:l=0}=t;let{keyframes:o}=t;const c=n||gY;c!==gY&&typeof o[0]!="number"&&(this.mixKeyframes=xee($js,xEt(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=FHe(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:x,onUpdate:g,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 b=this.currentTime-d*(this.playbackSpeed>=0?1:-1),v=this.playbackSpeed>=0?b<0:b>a;this.currentTime=Math.max(b,0),this.state==="finished"&&this.holdTime===null&&(this.currentTime=a);let N=this.currentTime,C=r;if(h){const M=Math.min(this.currentTime,a)/o;let I=Math.floor(M),D=M%1;!D&&M>=1&&(D=1),D===1&&I--,I=Math.min(I,h+1),!!(I%2)&&(m==="reverse"?(D=1-D,p&&(D-=p/o)):m==="mirror"&&(C=l)),N=_5(0,1,D)*o}let A;v?(this.delayState.value=u[0],A=this.delayState):A=C.next(N),i&&!v&&(A.value=i(A.value));let{done:T}=A;!v&&c!==null&&(T=this.playbackSpeed>=0?this.currentTime>=a:this.currentTime<=0);const P=this.holdTime===null&&(this.state==="finished"||this.state==="running"&&T);return P&&x!==VFe&&(A.value=GCe(u,this.options,y,this.speed)),g&&g(A.value),P&&this.finish(),A}then(t,n){return this.finished.then(t,n)}get duration(){return Dj(this.calculatedDuration)}get iterationDuration(){const{delay:t=0}=this.options||{};return this.duration+Dj(t)}get time(){return Dj(this.currentTime)}set time(t){t=Ib(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 yEt(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(i1.now()),this.playbackSpeed=t,n&&this.driver&&(this.time=Dj(this.currentTime))}play(){var a,i;if(this.isStopped)return;const{driver:t=Njs,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(i1.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 Ujs(s){for(let t=1;ts*180/Math.PI,HFe=s=>{const t=L8(Math.atan2(s[1],s[0]));return GFe(t)},qjs={x:4,y:5,translateX:4,translateY:5,scaleX:0,scaleY:3,scale:s=>(Math.abs(s[0])+Math.abs(s[3]))/2,rotate:HFe,rotateZ:HFe,skewX:s=>L8(Math.atan(s[1])),skewY:s=>L8(Math.atan(s[2])),skew:s=>(Math.abs(s[1])+Math.abs(s[2]))/2},GFe=s=>(s=s%360,s<0&&(s+=360),s),jit=HFe,Nit=s=>Math.sqrt(s[0]*s[0]+s[1]*s[1]),kit=s=>Math.sqrt(s[4]*s[4]+s[5]*s[5]),Vjs={x:12,y:13,z:14,translateX:12,translateY:13,translateZ:14,scaleX:Nit,scaleY:kit,scale:s=>(Nit(s)+kit(s))/2,rotateX:s=>GFe(L8(Math.atan2(s[6],s[5]))),rotateY:s=>GFe(L8(Math.atan2(-s[2],s[0]))),rotateZ:jit,rotate:jit,skewX:s=>L8(Math.atan(s[4])),skewY:s=>L8(Math.atan(s[1])),skew:s=>(Math.abs(s[1])+Math.abs(s[4]))/2};function WFe(s){return s.includes("scale")?1:0}function KFe(s,t){if(!s||s==="none")return WFe(t);const n=s.match(/^matrix3d\(([-\d.e\s,]+)\)$/u);let r,a;if(n)r=Vjs,a=n;else{const o=s.match(/^matrix\(([-\d.e\s,]+)\)$/u);r=qjs,a=o}if(!a)return WFe(t);const i=r[t],l=a[1].split(",").map(Gjs);return typeof i=="function"?i(l):l[i]}const Hjs=(s,t)=>{const{transform:n="none"}=getComputedStyle(s);return KFe(n,t)};function Gjs(s){return parseFloat(s.trim())}const Tq=["transformPerspective","x","y","z","translateX","translateY","translateZ","scale","scaleX","scaleY","rotate","rotateX","rotateY","rotateZ","skew","skewX","skewY"],Mq=new Set(Tq),Sit=s=>s===Eq||s===ao,Wjs=new Set(["x","y","z"]),Kjs=Tq.filter(s=>!Wjs.has(s));function Yjs(s){const t=[];return Kjs.forEach(n=>{const r=s.getValue(n);r!==void 0&&(t.push([n,r.get()]),r.set(n.startsWith("scale")?1:0))}),t}const WE={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})=>KFe(t,"x"),y:(s,{transform:t})=>KFe(t,"y")};WE.translateX=WE.x;WE.translateY=WE.y;const ER=new Set;let YFe=!1,ZFe=!1,XFe=!1;function bEt(){if(ZFe){const s=Array.from(ER).filter(r=>r.needsMeasurement),t=new Set(s.map(r=>r.element)),n=new Map;t.forEach(r=>{const a=Yjs(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)})}ZFe=!1,YFe=!1,ER.forEach(s=>s.complete(XFe)),ER.clear()}function _Et(){ER.forEach(s=>{s.readKeyframes(),s.needsMeasurement&&(ZFe=!0)})}function Zjs(){XFe=!0,_Et(),bEt(),XFe=!1}class BHe{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?(ER.add(this),YFe||(YFe=!0,Th.read(_Et),Th.resolveKeyframes(bEt))):(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])}Ujs(t)}setFinalKeyframe(){}measureInitialState(){}renderEndStyles(){}measureEndState(){}complete(t=!1){this.state="complete",this.onComplete(this.unresolvedKeyframes,this.finalKeyframe,t),ER.delete(this)}cancel(){this.state==="scheduled"&&(ER.delete(this),this.state="pending")}resume(){this.state==="pending"&&this.scheduleResolve()}}const Xjs=s=>s.startsWith("--");function wEt(s,t,n){Xjs(t)?s.style.setProperty(t,n):s.style[t]=n}const Qjs={};function jEt(s,t){const n=ZAt(s);return()=>Qjs[t]??n()}const Jjs=jEt(()=>window.ScrollTimeline!==void 0,"scrollTimeline"),NEt=jEt(()=>{try{document.createElement("div").animate({opacity:0},{easing:"linear(0, 1)"})}catch{return!1}return!0},"linearEasing"),gW=([s,t,n,r])=>`cubic-bezier(${s}, ${t}, ${n}, ${r})`,Cit={linear:"linear",ease:"ease",easeIn:"ease-in",easeOut:"ease-out",easeInOut:"ease-in-out",circIn:gW([0,.65,.55,1]),circOut:gW([.55,0,1,.45]),backIn:gW([.31,.01,.66,-.59]),backOut:gW([.33,1.53,.69,.99])};function kEt(s,t){if(s)return typeof s=="function"?NEt()?gEt(s,t):"ease-out":oEt(s)?gW(s):Array.isArray(s)?s.map(n=>kEt(n,t)||Cit.easeOut):Cit[s]}function e2s(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=kEt(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 SEt(s){return typeof s=="function"&&"applyToOptions"in s}function t2s({type:s,...t}){return SEt(s)&&NEt()?s.applyToOptions(t):(t.duration??(t.duration=300),t.ease??(t.ease="easeOut"),t)}class CEt extends zHe{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,tU(typeof t.type!="string",`Mini animate() doesn't support "type" as a string.`,"mini-spring");const d=t2s(t);this.animation=e2s(n,r,a,d,i),d.autoplay===!1&&this.animation.pause(),this.animation.onfinish=()=>{if(this.finishedTime=this.time,!i){const u=GCe(a,this.options,o,this.speed);this.updateMotionValue&&this.updateMotionValue(u),wEt(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 Dj(Number(t))}get iterationDuration(){const{delay:t=0}=this.options||{};return this.duration+Dj(t)}get time(){return Dj(Number(this.animation.currentTime)||0)}set time(t){const n=this.finishedTime!==null;this.manualStartTime=null,this.finishedTime=null,this.animation.currentTime=Ib(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&&Jjs()?(this.animation.timeline=t,n&&(this.animation.rangeStart=n),r&&(this.animation.rangeEnd=r),Xj):a(this)}}const AEt={anticipate:nEt,backInOut:sEt,circInOut:aEt};function s2s(s){return s in AEt}function n2s(s){typeof s.ease=="string"&&s2s(s.ease)&&(s.ease=AEt[s.ease])}const ePe=10;class r2s extends CEt{constructor(t){n2s(t),vEt(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 Zke({...l,autoplay:!1}),c=Math.max(ePe,i1.now()-this.startTime),d=_5(0,ePe,c-ePe),u=o.sample(c).value,{name:h}=this.options;i&&h&&wEt(i,h,u),n.setWithVelocity(o.sample(Math.max(0,c-d)).value,u,d),o.stop()}}const Ait=(s,t)=>t==="zIndex"?!1:!!(typeof s=="number"||Array.isArray(s)||typeof s=="string"&&(zN.test(s)||s==="0")&&!s.startsWith("url("));function a2s(s){const t=s[0];if(s.length===1)return!0;for(let n=0;nObject.hasOwnProperty.call(Element.prototype,"animate"));function u2s(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 d2s()&&n&&(EEt.has(n)||c2s.has(n)&&l2s(o))&&(n!=="transform"||!u)&&!d&&!r&&a!=="mirror"&&i!==0&&l!=="inertia"}const h2s=40;class m2s extends zHe{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 x;super(),this.stop=()=>{var g,y;this._animation&&(this._animation.stop(),(g=this.stopTimeline)==null||g.call(this)),(y=this.keyframeResolver)==null||y.cancel()},this.createdAt=i1.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)||BHe;this.keyframeResolver=new p(o,(g,y,b)=>this.onKeyframesResolved(g,y,m,!b),c,d,u),(x=this.keyframeResolver)==null||x.scheduleResolve()}onKeyframesResolved(t,n,r,a){var b,v;this.keyframeResolver=void 0;const{name:i,type:l,velocity:o,delay:c,isHandoff:d,onUpdate:u}=r;this.resolvedAt=i1.now();let h=!0;i2s(t,i,l,o)||(h=!1,(a6.instantAnimations||!c)&&(u==null||u(GCe(t,r,n))),t[0]=t[t.length-1],QFe(r),r.repeat=0);const p={startTime:a?this.resolvedAt?this.resolvedAt-this.createdAt>h2s?this.resolvedAt:this.createdAt:this.createdAt:void 0,finalKeyframe:n,...r,keyframes:t},x=h&&!d&&u2s(p),g=(v=(b=p.motionValue)==null?void 0:b.owner)==null?void 0:v.current;let y;if(x)try{y=new r2s({...p,element:g})}catch{y=new Zke(p)}else y=new Zke(p);y.finished.then(()=>{this.notifyFinished()}).catch(Xj),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(),Zjs()),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 TEt(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 p2s=/^var\(--(?:([\w-]+)|([\w-]+), ?([a-zA-Z\d ()%#.,-]+))\)/u;function f2s(s){const t=p2s.exec(s);if(!t)return[,];const[,n,r,a]=t;return[`--${n??r}`,a]}const x2s=4;function MEt(s,t,n=1){tU(n<=x2s,`Max CSS variable fallback depth detected in property "${s}". This may indicate a circular fallback dependency.`,"max-css-var-depth");const[r,a]=f2s(s);if(!r)return;const i=window.getComputedStyle(t).getPropertyValue(r);if(i){const l=i.trim();return WAt(l)?parseFloat(l):l}return IHe(a)?MEt(a,t,n+1):a}const g2s={type:"spring",stiffness:500,damping:25,restSpeed:10},y2s=s=>({type:"spring",stiffness:550,damping:s===0?2*Math.sqrt(550):30,restSpeed:10}),v2s={type:"keyframes",duration:.8},b2s={type:"keyframes",ease:[.25,.1,.35,1],duration:.3},_2s=(s,{keyframes:t})=>t.length>2?v2s:Mq.has(s)?s.startsWith("scale")?y2s(t[1]):g2s:b2s;function LEt(s,t){if(s!=null&&s.inherit&&t){const{inherit:n,...r}=s;return{...t,...r}}return s}function $He(s,t){const n=(s==null?void 0:s[t])??(s==null?void 0:s.default)??s;return n!==s?LEt(n,s):n}const w2s=new Set(["when","delay","delayChildren","staggerChildren","staggerDirection","repeat","repeatType","repeatDelay","from","elapsed"]);function j2s(s){for(const t in s)if(!w2s.has(t))return!0;return!1}const UHe=(s,t,n,r={},a,i)=>l=>{const o=$He(r,s)||{},c=o.delay||r.delay||0;let{elapsed:d=0}=r;d=d-Ib(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};j2s(o)||Object.assign(u,_2s(s,u)),u.duration&&(u.duration=Ib(u.duration)),u.repeatDelay&&(u.repeatDelay=Ib(u.repeatDelay)),u.from!==void 0&&(u.keyframes[0]=u.from);let h=!1;if((u.type===!1||u.duration===0&&!u.repeatDelay)&&(QFe(u),u.delay===0&&(h=!0)),(a6.instantAnimations||a6.skipAnimations||a!=null&&a.shouldSkipAnimations)&&(h=!0,QFe(u),u.delay=0),u.allowFlatten=!o.type&&!o.ease,h&&!i&&t.get()!==void 0){const m=GCe(u.keyframes,o);if(m!==void 0){Th.update(()=>{u.onUpdate(m),u.onComplete()});return}}return o.isSync?new Zke(u):new m2s(u)};function Eit(s){const t=[{},{}];return s==null||s.values.forEach((n,r)=>{t[0][r]=n.get(),t[1][r]=n.getVelocity()}),t}function qHe(s,t,n,r){if(typeof t=="function"){const[a,i]=Eit(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]=Eit(r);t=t(n!==void 0?n:s.custom,a,i)}return t}function TR(s,t,n){const r=s.getProps();return qHe(r,t,n!==void 0?n:r.custom,s)}const PEt=new Set(["width","height","top","left","right","bottom",...Tq]),Tit=30,N2s=s=>!isNaN(parseFloat(s));class k2s{constructor(t,n={}){this.canTrackVelocity=null,this.events={},this.updateAndNotify=r=>{var i;const a=i1.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=i1.now(),this.canTrackVelocity===null&&t!==void 0&&(this.canTrackVelocity=N2s(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 MHe);const r=this.events[t].add(n);return t==="change"?()=>{r(),Th.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=i1.now();if(!this.canTrackVelocity||this.prevFrameValue===void 0||t-this.updatedAt>Tit)return 0;const n=Math.min(this.updatedAt-this.prevUpdatedAt,Tit);return XAt(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 nU(s,t){return new k2s(s,t)}const JFe=s=>Array.isArray(s);function S2s(s,t,n){s.hasValue(t)?s.getValue(t).set(n):s.addValue(t,nU(n))}function C2s(s){return JFe(s)?s[s.length-1]||0:s}function A2s(s,t){const n=TR(s,t);let{transitionEnd:r={},transition:a={},...i}=n||{};i={...i,...r};for(const l in i){const o=C2s(i[l]);S2s(s,l,o)}}const py=s=>!!(s&&s.getVelocity);function E2s(s){return!!(py(s)&&s.add)}function e7e(s,t){const n=s.getValue("willChange");if(E2s(n))return n.add(t);if(!n&&a6.WillChange){const r=new a6.WillChange("auto");s.addValue("willChange",r),r.add(t)}}function VHe(s){return s.replace(/([A-Z])/g,t=>`-${t.toLowerCase()}`)}const T2s="framerAppearId",IEt="data-"+VHe(T2s);function DEt(s){return s.props[IEt]}function M2s({protectedKeys:s,needsAnimating:t},n){const r=s.hasOwnProperty(n)&&t[n]!==!0;return t[n]=!1,r}function REt(s,t,{delay:n=0,transitionOverride:r,type:a}={}){let{transition:i,transitionEnd:l,...o}=t;const c=s.getDefaultTransition();i=i?LEt(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),x=o[m];if(x===void 0||h&&M2s(h,m))continue;const g={delay:n,...$He(i||{},m)},y=p.get();if(y!==void 0&&!p.isAnimating()&&!Array.isArray(x)&&x===y&&!g.velocity){Th.update(()=>p.set(x));continue}let b=!1;if(window.MotionHandoffAnimation){const C=DEt(s);if(C){const A=window.MotionHandoffAnimation(C,m,Th);A!==null&&(g.startTime=A,b=!0)}}e7e(s,m);const v=d??s.shouldReduceMotion;p.start(UHe(m,p,x,v&&PEt.has(m)?{type:!1}:g,s,b));const N=p.animation;N&&u.push(N)}if(l){const m=()=>Th.update(()=>{l&&A2s(s,l)});u.length?Promise.all(u).then(m):m()}return u}function t7e(s,t,n={}){var c;const r=TR(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(REt(s,r,n)):()=>Promise.resolve(),l=s.variantChildren&&s.variantChildren.size?(d=0)=>{const{delayChildren:u=0,staggerChildren:h,staggerDirection:m}=a;return L2s(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 L2s(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(t7e(c,t,{...l,delay:n+(typeof r=="function"?0:r)+TEt(s.variantChildren,c,r,a,i)}).then(()=>c.notify("AnimationComplete",t)));return Promise.all(o)}function P2s(s,t,n={}){s.notify("AnimationStart",t);let r;if(Array.isArray(t)){const a=t.map(i=>t7e(s,i,n));r=Promise.all(a)}else if(typeof t=="string")r=t7e(s,t,n);else{const a=typeof t=="function"?TR(s,t,n.custom):t;r=Promise.all(REt(s,a,n))}return r.then(()=>{s.notify("AnimationComplete",t)})}const I2s={test:s=>s==="auto",parse:s=>s},OEt=s=>t=>t.test(s),FEt=[Eq,ao,u5,NA,ajs,rjs,I2s],Mit=s=>FEt.find(OEt(s));function D2s(s){return typeof s=="number"?s===0:s!==null?s==="none"||s==="0"||YAt(s):!0}const R2s=new Set(["brightness","contrast","saturate","opacity"]);function O2s(s){const[t,n]=s.slice(0,-1).split("(");if(t==="drop-shadow")return s;const[r]=n.match(DHe)||[];if(!r)return s;const a=n.replace(r,"");let i=R2s.has(t)?1:0;return r!==n&&(i*=100),t+"("+i+a+")"}const F2s=/\b([a-z-]*)\(.*?\)/gu,s7e={...zN,getAnimatableNone:s=>{const t=s.match(F2s);return t?t.map(O2s).join(" "):s}},n7e={...zN,getAnimatableNone:s=>{const t=zN.parse(s);return zN.createTransformer(s)(t.map(r=>typeof r=="number"?0:typeof r=="object"?{...r,alpha:1}:r))}},Lit={...Eq,transform:Math.round},z2s={rotate:NA,rotateX:NA,rotateY:NA,rotateZ:NA,scale:Cne,scaleX:Cne,scaleY:Cne,scaleZ:Cne,skew:NA,skewX:NA,skewY:NA,distance:ao,translateX:ao,translateY:ao,translateZ:ao,x:ao,y:ao,z:ao,perspective:ao,transformPerspective:ao,opacity:HZ,originX:yit,originY:yit,originZ:ao},HHe={borderWidth:ao,borderTopWidth:ao,borderRightWidth:ao,borderBottomWidth:ao,borderLeftWidth:ao,borderRadius:ao,borderTopLeftRadius:ao,borderTopRightRadius:ao,borderBottomRightRadius:ao,borderBottomLeftRadius:ao,width:ao,maxWidth:ao,height:ao,maxHeight:ao,top:ao,right:ao,bottom:ao,left:ao,inset:ao,insetBlock:ao,insetBlockStart:ao,insetBlockEnd:ao,insetInline:ao,insetInlineStart:ao,insetInlineEnd:ao,padding:ao,paddingTop:ao,paddingRight:ao,paddingBottom:ao,paddingLeft:ao,paddingBlock:ao,paddingBlockStart:ao,paddingBlockEnd:ao,paddingInline:ao,paddingInlineStart:ao,paddingInlineEnd:ao,margin:ao,marginTop:ao,marginRight:ao,marginBottom:ao,marginLeft:ao,marginBlock:ao,marginBlockStart:ao,marginBlockEnd:ao,marginInline:ao,marginInlineStart:ao,marginInlineEnd:ao,fontSize:ao,backgroundPositionX:ao,backgroundPositionY:ao,...z2s,zIndex:Lit,fillOpacity:HZ,strokeOpacity:HZ,numOctaves:Lit},B2s={...HHe,color:kx,backgroundColor:kx,outlineColor:kx,fill:kx,stroke:kx,borderColor:kx,borderTopColor:kx,borderRightColor:kx,borderBottomColor:kx,borderLeftColor:kx,filter:s7e,WebkitFilter:s7e,mask:n7e,WebkitMask:n7e},zEt=s=>B2s[s],$2s=new Set([s7e,n7e]);function BEt(s,t){let n=zEt(s);return $2s.has(n)||(n=zN),n.getAnimatableNone?n.getAnimatableNone(t):void 0}const U2s=new Set(["auto","none","0"]);function q2s(s,t,n){let r=0,a;for(;r{t.getValue(c).set(d)}),this.resolveNoneKeyframes()}}function GHe(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 $Et=(s,t)=>t&&typeof s=="number"?t.transform(s):s;function _2e(s){return KAt(s)&&"offsetHeight"in s&&!("ownerSVGElement"in s)}const{schedule:WHe,cancel:qXn}=lEt(queueMicrotask,!1),K2={x:!1,y:!1};function UEt(){return K2.x||K2.y}function H2s(s){return s==="x"||s==="y"?K2[s]?null:(K2[s]=!0,()=>{K2[s]=!1}):K2.x||K2.y?null:(K2.x=K2.y=!0,()=>{K2.x=K2.y=!1})}function qEt(s,t){const n=GHe(s),r=new AbortController,a={passive:!0,...t,signal:r.signal};return[n,a,()=>r.abort()]}function G2s(s){return!(s.pointerType==="touch"||UEt())}function W2s(s,t,n={}){const[r,a,i]=qEt(s,n);return r.forEach(l=>{let o=!1,c=!1,d;const u=()=>{l.removeEventListener("pointerleave",x)},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)},x=y=>{if(y.pointerType!=="touch"){if(o){c=!0;return}h(y)}},g=y=>{if(!G2s(y))return;c=!1;const b=t(l,y);typeof b=="function"&&(d=b,l.addEventListener("pointerleave",x,a))};l.addEventListener("pointerenter",g,a),l.addEventListener("pointerdown",p,a)}),i}const VEt=(s,t)=>t?s===t?!0:VEt(s,t.parentElement):!1,KHe=s=>s.pointerType==="mouse"?typeof s.button!="number"||s.button<=0:s.isPrimary!==!1,K2s=new Set(["BUTTON","INPUT","SELECT","TEXTAREA","A"]);function Y2s(s){return K2s.has(s.tagName)||s.isContentEditable===!0}const Z2s=new Set(["INPUT","SELECT","TEXTAREA"]);function X2s(s){return Z2s.has(s.tagName)||s.isContentEditable===!0}const w2e=new WeakSet;function Pit(s){return t=>{t.key==="Enter"&&s(t)}}function tPe(s,t){s.dispatchEvent(new PointerEvent("pointer"+t,{isPrimary:!0,bubbles:!0}))}const Q2s=(s,t)=>{const n=s.currentTarget;if(!n)return;const r=Pit(()=>{if(w2e.has(n))return;tPe(n,"down");const a=Pit(()=>{tPe(n,"up")}),i=()=>tPe(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 Iit(s){return KHe(s)&&!UEt()}const Dit=new WeakSet;function J2s(s,t,n={}){const[r,a,i]=qEt(s,n),l=o=>{const c=o.currentTarget;if(!Iit(o)||Dit.has(o))return;w2e.add(c),n.stopPropagation&&Dit.add(o);const d=t(c,o),u=(p,x)=>{window.removeEventListener("pointerup",h),window.removeEventListener("pointercancel",m),w2e.has(c)&&w2e.delete(c),Iit(p)&&typeof d=="function"&&d(p,{success:x})},h=p=>{u(p,c===window||c===document||n.useGlobalTarget||VEt(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),_2e(o)&&(o.addEventListener("focus",d=>Q2s(d,a)),!Y2s(o)&&!o.hasAttribute("tabindex")&&(o.tabIndex=0))}),i}function YHe(s){return KAt(s)&&"ownerSVGElement"in s}const j2e=new WeakMap;let kA;const HEt=(s,t,n)=>(r,a)=>a&&a[0]?a[0][s+"Size"]:YHe(r)&&"getBBox"in r?r.getBBox()[t]:r[n],eNs=HEt("inline","width","offsetWidth"),tNs=HEt("block","height","offsetHeight");function sNs({target:s,borderBoxSize:t}){var n;(n=j2e.get(s))==null||n.forEach(r=>{r(s,{get width(){return eNs(s,t)},get height(){return tNs(s,t)}})})}function nNs(s){s.forEach(sNs)}function rNs(){typeof ResizeObserver>"u"||(kA=new ResizeObserver(nNs))}function aNs(s,t){kA||rNs();const n=GHe(s);return n.forEach(r=>{let a=j2e.get(r);a||(a=new Set,j2e.set(r,a)),a.add(t),kA==null||kA.observe(r)}),()=>{n.forEach(r=>{const a=j2e.get(r);a==null||a.delete(t),a!=null&&a.size||kA==null||kA.unobserve(r)})}}const N2e=new Set;let q9;function iNs(){q9=()=>{const s={get width(){return window.innerWidth},get height(){return window.innerHeight}};N2e.forEach(t=>t(s))},window.addEventListener("resize",q9)}function oNs(s){return N2e.add(s),q9||iNs(),()=>{N2e.delete(s),!N2e.size&&typeof q9=="function"&&(window.removeEventListener("resize",q9),q9=void 0)}}function Rit(s,t){return typeof s=="function"?oNs(s):aNs(s,t)}function lNs(s){return YHe(s)&&s.tagName==="svg"}const cNs=[...FEt,kx,zN],dNs=s=>cNs.find(OEt(s)),Oit=()=>({translate:0,scale:1,origin:0,originPoint:0}),V9=()=>({x:Oit(),y:Oit()}),Fit=()=>({min:0,max:0}),ig=()=>({x:Fit(),y:Fit()}),uNs=new WeakMap;function WCe(s){return s!==null&&typeof s=="object"&&typeof s.start=="function"}function GZ(s){return typeof s=="string"||Array.isArray(s)}const ZHe=["animate","whileInView","whileFocus","whileHover","whileTap","whileDrag","exit"],XHe=["initial",...ZHe];function KCe(s){return WCe(s.animate)||XHe.some(t=>GZ(s[t]))}function GEt(s){return!!(KCe(s)||s.variants)}function hNs(s,t,n){for(const r in t){const a=t[r],i=n[r];if(py(a))s.addValue(r,a);else if(py(i))s.addValue(r,nU(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,nU(l!==void 0?l:a,{owner:s}))}}for(const r in n)t[r]===void 0&&s.removeValue(r);return t}const r7e={current:null},WEt={current:!1},mNs=typeof window<"u";function pNs(){if(WEt.current=!0,!!mNs)if(window.matchMedia){const s=window.matchMedia("(prefers-reduced-motion)"),t=()=>r7e.current=s.matches;s.addEventListener("change",t),t()}else r7e.current=!1}const zit=["AnimationStart","AnimationComplete","Update","BeforeLayoutMeasure","LayoutMeasure","LayoutAnimationStart","LayoutAnimationComplete"];let Xke={};function KEt(s){Xke=s}function fNs(){return Xke}class xNs{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=BHe,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=i1.now();this.renderScheduledAtthis.bindToMotionValue(i,a)),this.reducedMotionConfig==="never"?this.shouldReduceMotion=!1:this.reducedMotionConfig==="always"?this.shouldReduceMotion=!0:(WEt.current||pNs(),this.shouldReduceMotion=r7e.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(),i6(this.notifyUpdate),i6(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&&EEt.has(t)&&this.current instanceof HTMLElement){const{factory:l,keyframes:o,times:c,ease:d,duration:u}=n.accelerate,h=new CEt({element:this.current,name:t,keyframes:o,times:c,ease:d,duration:Ib(u)}),m=l(h);this.valueSubscriptions.set(t,()=>{m(),h.cancel()});return}const r=Mq.has(t);r&&this.onBindTransform&&this.onBindTransform();const a=n.on("change",l=>{this.latestValues[t]=l,this.props.onUpdate&&Th.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 Xke){const n=Xke[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):ig()}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=nU(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"&&(WAt(r)||YAt(r))?r=parseFloat(r):!dNs(r)&&zN.test(n)&&(r=BEt(t,n)),this.setBaseTarget(t,py(r)?r.get():r)),py(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=qHe(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&&!py(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 MHe),this.events[t].add(n)}notify(t,...n){this.events[t]&&this.events[t].notify(...n)}scheduleRenderMicrotask(){WHe.render(this.render)}}class YEt extends xNs{constructor(){super(...arguments),this.KeyframeResolver=V2s}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;py(t)&&(this.childSubscription=t.on("change",n=>{this.current&&(this.current.textContent=`${n}`)}))}}class M6{constructor(t){this.isMounted=!1,this.node=t}update(){}}function ZEt({top:s,left:t,right:n,bottom:r}){return{x:{min:t,max:n},y:{min:s,max:r}}}function gNs({x:s,y:t}){return{top:t.min,right:s.max,bottom:t.max,left:s.min}}function yNs(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 sPe(s){return s===void 0||s===1}function a7e({scale:s,scaleX:t,scaleY:n}){return!sPe(s)||!sPe(t)||!sPe(n)}function a8(s){return a7e(s)||XEt(s)||s.z||s.rotate||s.rotateX||s.rotateY||s.skewX||s.skewY}function XEt(s){return Bit(s.x)||Bit(s.y)}function Bit(s){return s&&s!=="0%"}function Qke(s,t,n){const r=s-n,a=t*r;return n+a}function $it(s,t,n,r,a){return a!==void 0&&(s=Qke(s,a,r)),Qke(s,n,r)+t}function i7e(s,t=0,n=1,r,a){s.min=$it(s.min,t,n,r,a),s.max=$it(s.max,t,n,r,a)}function QEt(s,{x:t,y:n}){i7e(s.x,t.translate,t.scale,t.originPoint),i7e(s.y,n.translate,n.scale,n.originPoint)}const Uit=.999999999999,qit=1.0000000000001;function vNs(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;cUit&&(t.x=1),t.yUit&&(t.y=1)}function MS(s,t){s.min+=t,s.max+=t}function Vit(s,t,n,r,a=.5){const i=jm(s.min,s.max,a);i7e(s,t,n,i,r)}function Hit(s,t){return typeof s=="string"?parseFloat(s)/100*(t.max-t.min):s}function k2e(s,t,n){const r=n??s;Vit(s.x,Hit(t.x,r.x),t.scaleX,t.scale,t.originX),Vit(s.y,Hit(t.y,r.y),t.scaleY,t.scale,t.originY)}function JEt(s,t){return ZEt(yNs(s.getBoundingClientRect(),t))}function bNs(s,t,n){const r=JEt(s,n),{scroll:a}=t;return a&&(MS(r.x,a.offset.x),MS(r.y,a.offset.y)),r}const _Ns={x:"translateX",y:"translateY",z:"translateZ",transformPerspective:"perspective"},wNs=Tq.length;function jNs(s,t,n){let r="",a=!0;for(let i=0;i{if(!t.target)return s;if(typeof s=="string")if(ao.test(s))s=parseFloat(s);else return s;const n=Git(s,t.target.x),r=Git(s,t.target.y);return`${n}% ${r}%`}},NNs={correct:(s,{treeScale:t,projectionDelta:n})=>{const r=s,a=zN.parse(s);if(a.length>5)return r;const i=zN.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=jm(o,c,.5);return typeof a[2+l]=="number"&&(a[2+l]/=d),typeof a[3+l]=="number"&&(a[3+l]/=d),i(a)}},o7e={borderRadius:{...tG,applyTo:["borderTopLeftRadius","borderTopRightRadius","borderBottomLeftRadius","borderBottomRightRadius"]},borderTopLeftRadius:tG,borderTopRightRadius:tG,borderBottomLeftRadius:tG,borderBottomRightRadius:tG,boxShadow:NNs};function tTt(s,{layout:t,layoutId:n}){return Mq.has(s)||s.startsWith("origin")||(t||n!==void 0)&&(!!o7e[s]||s==="opacity")}function JHe(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)(py(r[o])||a&&py(a[o])||tTt(o,s)||((l=n==null?void 0:n.getValue(o))==null?void 0:l.liveStyle)!==void 0)&&(i[o]=r[o]);return i}function kNs(s){return window.getComputedStyle(s)}class SNs extends YEt{constructor(){super(...arguments),this.type="html",this.renderInstance=eTt}readValueFromInstance(t,n){var r;if(Mq.has(n))return(r=this.projection)!=null&&r.isProjecting?WFe(n):Hjs(t,n);{const a=kNs(t),i=(dEt(n)?a.getPropertyValue(n):a[n])||0;return typeof i=="string"?i.trim():i}}measureInstanceViewportBox(t,{transformPagePoint:n}){return JEt(t,n)}build(t,n,r){QHe(t,n,r.transformTemplate)}scrapeMotionValuesFromProps(t,n,r){return JHe(t,n,r)}}const CNs={offset:"stroke-dashoffset",array:"stroke-dasharray"},ANs={offset:"strokeDashoffset",array:"strokeDasharray"};function ENs(s,t,n=1,r=0,a=!0){s.pathLength=1;const i=a?CNs:ANs;s[i.offset]=`${-r}`,s[i.array]=`${t} ${n}`}const TNs=["offsetDistance","offsetPath","offsetRotate","offsetAnchor"];function sTt(s,{attrX:t,attrY:n,attrScale:r,pathLength:a,pathSpacing:i=1,pathOffset:l=0,...o},c,d,u){if(QHe(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 TNs)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&&ENs(h,a,i,l,!1)}const nTt=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"]),rTt=s=>typeof s=="string"&&s.toLowerCase()==="svg";function MNs(s,t,n,r){eTt(s,t,void 0,r);for(const a in t.attrs)s.setAttribute(nTt.has(a)?a:VHe(a),t.attrs[a])}function aTt(s,t,n){const r=JHe(s,t,n);for(const a in s)if(py(s[a])||py(t[a])){const i=Tq.indexOf(a)!==-1?"attr"+a.charAt(0).toUpperCase()+a.substring(1):a;r[i]=s[a]}return r}class LNs extends YEt{constructor(){super(...arguments),this.type="svg",this.isSVGTag=!1,this.measureInstanceViewportBox=ig}getBaseTargetFromProps(t,n){return t[n]}readValueFromInstance(t,n){if(Mq.has(n)){const r=zEt(n);return r&&r.default||0}return n=nTt.has(n)?n:VHe(n),t.getAttribute(n)}scrapeMotionValuesFromProps(t,n,r){return aTt(t,n,r)}build(t,n,r){sTt(t,n,this.isSVGTag,r.transformTemplate,r.style)}renderInstance(t,n,r,a){MNs(t,n,r,a)}mount(t){this.isSVGTag=rTt(t.tagName),super.mount(t)}}const PNs=XHe.length;function iTt(s){if(!s)return;if(!s.isControllingVariants){const n=s.parent?iTt(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})=>P2s(s,n,r)))}function ONs(s){let t=RNs(s),n=Wit(),r=!0,a=!1;const i=d=>(u,h)=>{var p;const m=TR(s,h,d==="exit"?(p=s.presenceContext)==null?void 0:p.custom:void 0);if(m){const{transition:x,transitionEnd:g,...y}=m;u={...u,...y,...g}}return u};function l(d){t=d(s)}function o(d){const{props:u}=s,h=iTt(s.parent)||{},m=[],p=new Set;let x={},g=1/0;for(let b=0;bg&&A,D=!1;const B=Array.isArray(C)?C:[C];let q=B.reduce(i(v),{});T===!1&&(q={});const{prevResolvedValues:W={}}=N,V={...W,...q},K=ce=>{I=!0,p.has(ce)&&(D=!0,p.delete(ce)),N.needsAnimating[ce]=!0;const ue=s.getValue(ce);ue&&(ue.liveStyle=!1)};for(const ce in V){const ue=q[ce],ne=W[ce];if(x.hasOwnProperty(ce))continue;let ee=!1;JFe(ue)&&JFe(ne)?ee=!oTt(ue,ne):ee=ue!==ne,ee?ue!=null?K(ce):p.add(ce):ue!==void 0&&p.has(ce)?K(ce):N.protectedKeys[ce]=!0}N.prevProp=C,N.prevResolvedValues=q,N.isActive&&(x={...x,...q}),(r||a)&&s.blockInitialAnimation&&(I=!1);const Q=P&&M;I&&(!Q||D)&&m.push(...B.map(ce=>{const ue={type:v};if(typeof ce=="string"&&(r||a)&&!Q&&s.manuallyAnimateOnMount&&s.parent){const{parent:ne}=s,ee=TR(ne,ce);if(ne.enteringChildren&&ee){const{delayChildren:le}=ee.transition||{};ue.delay=TEt(ne.enteringChildren,s,le)}}return{animation:ce,options:ue}}))}if(p.size){const b={};if(typeof u.initial!="boolean"){const v=TR(s,Array.isArray(u.initial)?u.initial[0]:u.initial);v&&v.transition&&(b.transition=v.transition)}p.forEach(v=>{const N=s.getBaseTarget(v),C=s.getValue(v);C&&(C.liveStyle=!0),b[v]=N??null}),m.push({animation:b})}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 x;return(x=p.animationState)==null?void 0:x.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=Wit(),a=!0}}}function FNs(s,t){return typeof t=="string"?t!==s:Array.isArray(t)?!oTt(t,s):!1}function RM(s=!1){return{isActive:s,protectedKeys:{},needsAnimating:{},prevResolvedValues:{}}}function Wit(){return{animate:RM(!0),whileInView:RM(),whileHover:RM(),whileTap:RM(),whileDrag:RM(),whileFocus:RM(),exit:RM()}}function l7e(s,t){s.min=t.min,s.max=t.max}function U2(s,t){l7e(s.x,t.x),l7e(s.y,t.y)}function Kit(s,t){s.translate=t.translate,s.scale=t.scale,s.originPoint=t.originPoint,s.origin=t.origin}const lTt=1e-4,zNs=1-lTt,BNs=1+lTt,cTt=.01,$Ns=0-cTt,UNs=0+cTt;function o1(s){return s.max-s.min}function qNs(s,t,n){return Math.abs(s-t)<=n}function Yit(s,t,n,r=.5){s.origin=r,s.originPoint=jm(t.min,t.max,s.origin),s.scale=o1(n)/o1(t),s.translate=jm(n.min,n.max,s.origin)-s.originPoint,(s.scale>=zNs&&s.scale<=BNs||isNaN(s.scale))&&(s.scale=1),(s.translate>=$Ns&&s.translate<=UNs||isNaN(s.translate))&&(s.translate=0)}function yY(s,t,n,r){Yit(s.x,t.x,n.x,r?r.originX:void 0),Yit(s.y,t.y,n.y,r?r.originY:void 0)}function Zit(s,t,n,r=0){const a=r?jm(n.min,n.max,r):n.min;s.min=a+t.min,s.max=s.min+o1(t)}function VNs(s,t,n,r){Zit(s.x,t.x,n.x,r==null?void 0:r.x),Zit(s.y,t.y,n.y,r==null?void 0:r.y)}function Xit(s,t,n,r=0){const a=r?jm(n.min,n.max,r):n.min;s.min=t.min-a,s.max=s.min+o1(t)}function Jke(s,t,n,r){Xit(s.x,t.x,n.x,r==null?void 0:r.x),Xit(s.y,t.y,n.y,r==null?void 0:r.y)}function Qit(s,t,n,r,a){return s-=t,s=Qke(s,1/n,r),a!==void 0&&(s=Qke(s,1/a,r)),s}function HNs(s,t=0,n=1,r=.5,a,i=s,l=s){if(u5.test(t)&&(t=parseFloat(t),t=jm(l.min,l.max,t/100)-l.min),typeof t!="number")return;let o=jm(i.min,i.max,r);s===i&&(o-=t),s.min=Qit(s.min,t,n,o,a),s.max=Qit(s.max,t,n,o,a)}function Jit(s,t,[n,r,a],i,l){HNs(s,t[n],t[r],t[a],t.scale,i,l)}const GNs=["x","scaleX","originX"],WNs=["y","scaleY","originY"];function eot(s,t,n,r){Jit(s.x,t,GNs,n?n.x:void 0,r?r.x:void 0),Jit(s.y,t,WNs,n?n.y:void 0,r?r.y:void 0)}function tot(s){return s.translate===0&&s.scale===1}function dTt(s){return tot(s.x)&&tot(s.y)}function sot(s,t){return s.min===t.min&&s.max===t.max}function KNs(s,t){return sot(s.x,t.x)&&sot(s.y,t.y)}function not(s,t){return Math.round(s.min)===Math.round(t.min)&&Math.round(s.max)===Math.round(t.max)}function uTt(s,t){return not(s.x,t.x)&¬(s.y,t.y)}function rot(s){return o1(s.x)/o1(s.y)}function aot(s,t){return s.translate===t.translate&&s.scale===t.scale&&s.originPoint===t.originPoint}function eS(s){return[s("x"),s("y")]}function YNs(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:x}=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) `),x&&(r+=`skewY(${x}deg) `)}const o=s.x.scale*t.x,c=s.y.scale*t.y;return(o!==1||c!==1)&&(r+=`scale(${o}, ${c})`),r||"none"}const hTt=["borderTopLeftRadius","borderTopRightRadius","borderBottomLeftRadius","borderBottomRightRadius"],ZNs=hTt.length,iot=s=>typeof s=="string"?parseFloat(s):s,oot=s=>typeof s=="number"||ao.test(s);function XNs(s,t,n,r,a,i){a?(s.opacity=jm(0,n.opacity??1,QNs(r)),s.opacityExit=jm(t.opacity??1,0,JNs(r))):i&&(s.opacity=jm(t.opacity??1,n.opacity??1,r));for(let l=0;lrt?1:n(VZ(s,t,r))}function eks(s,t,n){const r=py(s)?s:nU(s);return r.start(UHe("",r,t,n)),r.animation}function WZ(s,t,n,r={passive:!0}){return s.addEventListener(t,n,r),()=>s.removeEventListener(t,n)}const tks=(s,t)=>s.depth-t.depth;class sks{constructor(){this.children=[],this.isDirty=!1}add(t){THe(this.children,t),this.isDirty=!0}remove(t){Gke(this.children,t),this.isDirty=!0}forEach(t){this.isDirty&&this.children.sort(tks),this.isDirty=!1,this.children.forEach(t)}}function nks(s,t){const n=i1.now(),r=({timestamp:a})=>{const i=a-n;i>=t&&(i6(r),s(i-t))};return Th.setup(r,!0),()=>i6(r)}function S2e(s){return py(s)?s.get():s}class rks{constructor(){this.members=[]}add(t){THe(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&&(Gke(this.members,r),r.unmount())}t.scheduleRender()}remove(t){if(Gke(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 C2e={hasAnimatedSinceResize:!0,hasEverUpdated:!1},nPe=["","X","Y","Z"],aks=1e3;let iks=0;function rPe(s,t,n,r){const{latestValues:a}=t;a[s]&&(n[s]=a[s],t.setStaticValue(s,0),r&&(r[s]=0))}function pTt(s){if(s.hasCheckedOptimisedAppear=!0,s.root===s)return;const{visualElement:t}=s.options;if(!t)return;const n=DEt(t);if(window.MotionHasOptimisedAnimation(n,"transform")){const{layout:a,layoutId:i}=s.options;window.MotionCancelOptimisedAnimation(n,"transform",Th,!(a||i))}const{parent:r}=s;r&&!r.hasCheckedOptimisedAppear&&pTt(r)}function fTt({attachResizeListener:s,defaultParent:t,measureScroll:n,checkIsScrollRoot:r,resetTransform:a}){return class{constructor(l={},o=t==null?void 0:t()){this.id=iks++,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(cks),this.nodes.forEach(fks),this.nodes.forEach(xks),this.nodes.forEach(dks)},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;Th.read(()=>{h=window.innerWidth}),s(l,()=>{const p=window.innerWidth;p!==h&&(h=p,this.root.updateBlockedByResize=!0,u&&u(),u=nks(m,250),C2e.hasAnimatedSinceResize&&(C2e.hasAnimatedSinceResize=!1,this.nodes.forEach(uot)))})}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 x=this.options.transition||d.getDefaultTransition()||_ks,{onLayoutAnimationStart:g,onLayoutAnimationComplete:y}=d.getProps(),b=!this.targetLayout||!uTt(this.targetLayout,p),v=!h&&m;if(this.options.layoutRoot||this.resumeFrom||v||h&&(b||!this.currentAnimation)){this.resumeFrom&&(this.resumingFrom=this.resumeFrom,this.resumingFrom.resumingFrom=void 0);const N={...$He(x,"layout"),onPlay:g,onComplete:y};(d.shouldReduceMotion||this.options.layoutRoot)&&(N.delay=0,N.type=!1),this.startAnimation(N),this.setAnimationOrigin(u,v)}else h||uot(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(),i6(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(gks),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&&pTt(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&&!o1(this.snapshot.measuredBox.x)&&!o1(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=C/1e3;hot(h.x,l.x,A),hot(h.y,l.y,A),this.setTargetDelta(h),this.relativeTarget&&this.relativeTargetOrigin&&this.layout&&this.relativeParent&&this.relativeParent.layout&&(Jke(m,this.layout.layoutBox,this.relativeParent.layout.layoutBox,this.options.layoutAnchor||void 0),vks(this.relativeTarget,this.relativeTargetOrigin,m,A),N&&KNs(this.relativeTarget,N)&&(this.isProjectionDirty=!1),N||(N=ig()),U2(N,this.relativeTarget)),g&&(this.animationValues=u,XNs(u,d,this.latestValues,A,v,b)),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&&(i6(this.pendingAnimation),this.pendingAnimation=void 0),this.pendingAnimation=Th.update(()=>{C2e.hasAnimatedSinceResize=!0,this.motionValue||(this.motionValue=nU(0)),this.motionValue.jump(0,!1),this.currentAnimation=eks(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(aks),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&&xTt(this.options.animationType,this.layout.layoutBox,d.layoutBox)){c=this.target||ig();const h=o1(this.layout.layoutBox.x);c.x.min=l.target.x.min,c.x.max=c.x.min+h;const m=o1(this.layout.layoutBox.y);c.y.min=l.target.y.min,c.y.max=c.y.min+m}U2(o,c),k2e(o,u),yY(this.projectionDeltaWithTransform,this.layoutCorrected,o,u)}}registerSharedNode(l,o){this.sharedNodes.has(l)||this.sharedNodes.set(l,new rks),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&&rPe("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(cot),this.root.sharedNodes.clear()}}}function oks(s){s.updateLayout()}function lks(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")eS(h=>{const m=l?t.measuredBox[h]:t.layoutBox[h],p=o1(m);m.min=r[h].min,m.max=m.min+p});else if(i==="x"||i==="y"){const h=i==="x"?"y":"x";l7e(l?t.measuredBox[h]:t.layoutBox[h],r[h])}else xTt(i,t.layoutBox,r)&&eS(h=>{const m=l?t.measuredBox[h]:t.layoutBox[h],p=o1(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=V9();yY(o,r,t.layoutBox);const c=V9();l?yY(c,s.applyTransform(a,!0),t.measuredBox):yY(c,r,t.layoutBox);const d=!dTt(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 x=s.options.layoutAnchor||void 0,g=ig();Jke(g,t.layoutBox,m.layoutBox,x);const y=ig();Jke(y,r,p.layoutBox,x),uTt(g,y)||(u=!0),h.options.layoutRoot&&(s.relativeTarget=y,s.relativeTargetOrigin=g,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 cks(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 dks(s){s.isProjectionDirty=s.isSharedProjectionDirty=s.isTransformDirty=!1}function uks(s){s.clearSnapshot()}function cot(s){s.clearMeasurements()}function hks(s){s.isLayoutDirty=!0,s.updateLayout()}function dot(s){s.isLayoutDirty=!1}function mks(s){s.isAnimationBlocked&&s.layout&&!s.isLayoutDirty&&(s.snapshot=s.layout,s.isLayoutDirty=!0)}function pks(s){const{visualElement:t}=s.options;t&&t.getProps().onBeforeLayoutMeasure&&t.notify("BeforeLayoutMeasure"),s.resetTransform()}function uot(s){s.finishAnimation(),s.targetDelta=s.relativeTarget=s.target=void 0,s.isProjectionDirty=!0}function fks(s){s.resolveTargetDelta()}function xks(s){s.calcProjection()}function gks(s){s.resetSkewAndRotation()}function yks(s){s.removeLeadSnapshot()}function hot(s,t,n){s.translate=jm(t.translate,0,n),s.scale=jm(t.scale,1,n),s.origin=t.origin,s.originPoint=t.originPoint}function mot(s,t,n,r){s.min=jm(t.min,n.min,r),s.max=jm(t.max,n.max,r)}function vks(s,t,n,r){mot(s.x,t.x,n.x,r),mot(s.y,t.y,n.y,r)}function bks(s){return s.animationValues&&s.animationValues.opacityExit!==void 0}const _ks={duration:.45,ease:[.4,0,.1,1]},pot=s=>typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().includes(s),fot=pot("applewebkit/")&&!pot("chrome/")?Math.round:Xj;function xot(s){s.min=fot(s.min),s.max=fot(s.max)}function wks(s){xot(s.x),xot(s.y)}function xTt(s,t,n){return s==="position"||s==="preserve-aspect"&&!qNs(rot(t),rot(n),.2)}function jks(s){var t;return s!==s.root&&((t=s.scroll)==null?void 0:t.wasRoot)}const Nks=fTt({attachResizeListener:(s,t)=>WZ(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}),aPe={current:void 0},gTt=fTt({measureScroll:s=>({x:s.scrollLeft,y:s.scrollTop}),defaultParent:()=>{if(!aPe.current){const s=new Nks({});s.mount(window),s.setOptions({layoutScroll:!0}),aPe.current=s}return aPe.current},resetTransform:(s,t)=>{s.style.transform=t!==void 0?t:"none"},checkIsScrollRoot:s=>window.getComputedStyle(s).position==="fixed"}),eGe=j.createContext({transformPagePoint:s=>s,isStatic:!1,reducedMotion:"never"});function got(s,t){if(typeof s=="function")return s(t);s!=null&&(s.current=t)}function kks(...s){return t=>{let n=!1;const r=s.map(a=>{const i=got(a,t);return!n&&typeof i=="function"&&(n=!0),i});if(n)return()=>{for(let a=0;a{const{width:p,height:x,top:g,left:y,right:b,bottom:v}=c.current;if(t||i===!1||!o.current||!p||!x)return;const N=n==="left"?`left: ${y}`:`right: ${b}`,C=r==="bottom"?`bottom: ${v}`:`top: ${g}`;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: ${x}px !important; ${N}px !important; ${C}px !important; } `),()=>{var P;(P=o.current)==null||P.removeAttribute("data-motion-pop-id"),T.contains(A)&&T.removeChild(A)}},[t]),e.jsx(Cks,{isPresent:t,childRef:o,sizeRef:c,pop:i,children:i===!1?s:j.cloneElement(s,{ref:h})})}const Eks=({children:s,initial:t,isPresent:n,onExitComplete:r,custom:a,presenceAffectsLayout:i,mode:l,anchorX:o,anchorY:c,root:d})=>{const u=EHe(Tks),h=j.useId();let m=!0,p=j.useMemo(()=>(m=!1,{id:h,initial:t,isPresent:n,custom:a,onExitComplete:x=>{u.set(x,!0);for(const g of u.values())if(!g)return;r&&r()},register:x=>(u.set(x,!1),()=>u.delete(x))}),[n,u,r]);return i&&m&&(p={...p}),j.useMemo(()=>{u.forEach((x,g)=>u.set(g,!1))},[n]),j.useEffect(()=>{!n&&!u.size&&r&&r()},[n]),s=e.jsx(Aks,{pop:l==="popLayout",isPresent:n,anchorX:o,anchorY:c,root:d,children:s}),e.jsx(VCe.Provider,{value:p,children:s})};function Tks(){return new Map}function yTt(s=!0){const t=j.useContext(VCe);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 Ane=s=>s.key||"";function yot(s){const t=[];return j.Children.forEach(s,n=>{j.isValidElement(n)&&t.push(n)}),t}const Lq=({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]=yTt(l),m=j.useMemo(()=>yot(s),[s]),p=l&&!u?[]:m.map(Ane),x=j.useRef(!0),g=j.useRef(m),y=EHe(()=>new Map),b=j.useRef(new Set),[v,N]=j.useState(m),[C,A]=j.useState(m);GAt(()=>{x.current=!1,g.current=m;for(let M=0;M{const I=Ane(M),D=l&&!u?!1:m===C||p.includes(I),B=()=>{if(b.current.has(I))return;if(y.has(I))b.current.add(I),y.set(I,!0);else return;let q=!0;y.forEach(W=>{W||(q=!1)}),q&&(P==null||P(),A(g.current),l&&(h==null||h()),r&&r())};return e.jsx(Eks,{isPresent:D,initial:!x.current||n?void 0:!1,custom:t,presenceAffectsLayout:a,mode:i,root:d,onExitComplete:D?void 0:B,anchorX:o,anchorY:c,children:M},I)})})},vTt=j.createContext({strict:!1}),vot={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 bot=!1;function Mks(){if(bot)return;const s={};for(const t in vot)s[t]={isEnabled:n=>vot[t].some(r=>!!n[r])};KEt(s),bot=!0}function bTt(){return Mks(),fNs()}function Lks(s){const t=bTt();for(const n in s)t[n]={...t[n],...s[n]};KEt(t)}const Pks=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 eSe(s){return s.startsWith("while")||s.startsWith("drag")&&s!=="draggable"||s.startsWith("layout")||s.startsWith("onTap")||s.startsWith("onPan")||s.startsWith("onLayout")||Pks.has(s)}let _Tt=s=>!eSe(s);function Iks(s){typeof s=="function"&&(_Tt=t=>t.startsWith("on")?!eSe(t):s(t))}try{Iks(require("@emotion/is-prop-valid").default)}catch{}function Dks(s,t,n){const r={};for(const a in s)a==="values"&&typeof s.values=="object"||py(s[a])||(_Tt(a)||n===!0&&eSe(a)||!t&&!eSe(a)||s.draggable&&a.startsWith("onDrag"))&&(r[a]=s[a]);return r}const YCe=j.createContext({});function Rks(s,t){if(KCe(s)){const{initial:n,animate:r}=s;return{initial:n===!1||GZ(n)?n:void 0,animate:GZ(r)?r:void 0}}return s.inherit!==!1?t:{}}function Oks(s){const{initial:t,animate:n}=Rks(s,j.useContext(YCe));return j.useMemo(()=>({initial:t,animate:n}),[_ot(t),_ot(n)])}function _ot(s){return Array.isArray(s)?s.join(" "):s}const tGe=()=>({style:{},transform:{},transformOrigin:{},vars:{}});function wTt(s,t,n){for(const r in t)!py(t[r])&&!tTt(r,n)&&(s[r]=t[r])}function Fks({transformTemplate:s},t){return j.useMemo(()=>{const n=tGe();return QHe(n,t,s),Object.assign({},n.vars,n.style)},[t])}function zks(s,t){const n=s.style||{},r={};return wTt(r,n,s),Object.assign(r,Fks(s,t)),r}function Bks(s,t){const n={},r=zks(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 jTt=()=>({...tGe(),attrs:{}});function $ks(s,t,n,r){const a=j.useMemo(()=>{const i=jTt();return sTt(i,t,rTt(r),s.transformTemplate,s.style),{...i.attrs,style:{...i.style}}},[t]);if(s.style){const i={};wTt(i,s.style,s),a.style={...i,...a.style}}return a}const Uks=["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 sGe(s){return typeof s!="string"||s.includes("-")?!1:!!(Uks.indexOf(s)>-1||/[A-Z]/u.test(s))}function qks(s,t,n,{latestValues:r},a,i=!1,l){const c=(l??sGe(s)?$ks:Bks)(t,r,a,s),d=Dks(t,typeof s=="string",i),u=s!==j.Fragment?{...d,...c,ref:n}:{},{children:h}=t,m=j.useMemo(()=>py(h)?h.get():h,[h]);return j.createElement(s,{...u,children:m})}function Vks({scrapeMotionValuesFromProps:s,createRenderState:t},n,r,a){return{latestValues:Hks(n,r,a,s),renderState:t()}}function Hks(s,t,n,r){const a={},i=r(s,{});for(const m in i)a[m]=S2e(i[m]);let{initial:l,animate:o}=s;const c=KCe(s),d=GEt(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"&&!WCe(h)){const m=Array.isArray(h)?h:[h];for(let p=0;p(t,n)=>{const r=j.useContext(YCe),a=j.useContext(VCe),i=()=>Vks(s,t,r,a);return n?i():EHe(i)},Gks=NTt({scrapeMotionValuesFromProps:JHe,createRenderState:tGe}),Wks=NTt({scrapeMotionValuesFromProps:aTt,createRenderState:jTt}),Kks=Symbol.for("motionComponentSymbol");function Yks(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 kTt=j.createContext({});function d9(s){return s&&typeof s=="object"&&Object.prototype.hasOwnProperty.call(s,"current")}function Zks(s,t,n,r,a,i){var N,C;const{visualElement:l}=j.useContext(YCe),o=j.useContext(vTt),c=j.useContext(VCe),d=j.useContext(eGe),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 x=m.current,g=j.useContext(kTt);x&&!x.projection&&a&&(x.type==="html"||x.type==="svg")&&Xks(m.current,n,a,g);const y=j.useRef(!1);j.useInsertionEffect(()=>{x&&y.current&&x.update(n,c)});const b=n[IEt],v=j.useRef(!!b&&typeof window<"u"&&!((N=window.MotionHandoffIsComplete)!=null&&N.call(window,b))&&((C=window.MotionHasOptimisedAnimation)==null?void 0:C.call(window,b)));return GAt(()=>{p.current=!0,x&&(y.current=!0,window.MotionIsMounted=!0,x.updateFeatures(),x.scheduleRenderMicrotask(),v.current&&x.animationState&&x.animationState.animateChanges())}),j.useEffect(()=>{x&&(!v.current&&x.animationState&&x.animationState.animateChanges(),v.current&&(queueMicrotask(()=>{var A;(A=window.MotionHandoffMarkAsComplete)==null||A.call(window,b)}),v.current=!1),x.enteringChildren=void 0)}),x}function Xks(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:STt(s.parent)),s.projection.setOptions({layoutId:a,layout:i,alwaysMeasureLayout:!!l||o&&d9(o),visualElement:s,animationType:typeof i=="string"?i:"both",initialPromotionConfig:r,crossfade:h,layoutScroll:c,layoutRoot:d,layoutAnchor:u})}function STt(s){if(s)return s.options.allowProjection!==!1?s.projection:STt(s.parent)}function iPe(s,{forwardMotionProps:t=!1,type:n}={},r,a){r&&Lks(r);const i=n?n==="svg":sGe(s),l=i?Wks:Gks;function o(d,u){let h;const m={...j.useContext(eGe),...d,layoutId:Qks(d)},{isStatic:p}=m,x=Oks(d),g=l(d,p);if(!p&&typeof window<"u"){Jks();const y=eSs(m);h=y.MeasureLayout,x.visualElement=Zks(s,g,m,a,y.ProjectionNode,i)}return e.jsxs(YCe.Provider,{value:x,children:[h&&x.visualElement?e.jsx(h,{visualElement:x.visualElement,...m}):null,qks(s,d,Yks(g,x.visualElement,u),g,p,t,i)]})}o.displayName=`motion.${typeof s=="string"?s:`create(${s.displayName??s.name??""})`}`;const c=j.forwardRef(o);return c[Kks]=s,c}function Qks({layoutId:s}){const t=j.useContext(AHe).id;return t&&s!==void 0?t+"-"+s:s}function Jks(s,t){j.useContext(vTt).strict}function eSs(s){const t=bTt(),{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 tSs(s,t){if(typeof Proxy>"u")return iPe;const n=new Map,r=(i,l)=>iPe(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,iPe(l,void 0,s,t)),n.get(l))})}const sSs=(s,t)=>t.isSVG??sGe(s)?new LNs(t):new SNs(t,{allowProjection:s!==j.Fragment});class nSs extends M6{constructor(t){super(t),t.animationState||(t.animationState=ONs(t))}updateAnimationControlsSubscription(){const{animate:t}=this.node.getProps();WCe(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 rSs=0;class aSs extends M6{constructor(){super(...arguments),this.id=rSs++,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=TR(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 iSs={animation:{Feature:nSs},exit:{Feature:aSs}};function vee(s){return{point:{x:s.pageX,y:s.pageY}}}const oSs=s=>t=>KHe(t)&&s(t,vee(t));function vY(s,t,n,r){return WZ(s,t,oSs(n),r)}const CTt=({current:s})=>s?s.ownerDocument.defaultView:null,wot=(s,t)=>Math.abs(s-t);function lSs(s,t){const n=wot(s.x,t.x),r=wot(s.y,t.y);return Math.sqrt(n**2+r**2)}const jot=new Set(["auto","scroll"]);class ATt{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=Ene(this.lastRawMoveEventInfo,this.transformPagePoint));const p=oPe(this.lastMoveEventInfo,this.history),x=this.startEvent!==null,g=lSs(p.offset,{x:0,y:0})>=this.distanceThreshold;if(!x&&!g)return;const{point:y}=p,{timestamp:b}=iy;this.history.push({...y,timestamp:b});const{onStart:v,onMove:N}=this.handlers;x||(v&&v(this.lastMoveEvent,p),this.startEvent=this.lastMoveEvent),N&&N(this.lastMoveEvent,p)},this.handlePointerMove=(p,x)=>{this.lastMoveEvent=p,this.lastRawMoveEventInfo=x,this.lastMoveEventInfo=Ene(x,this.transformPagePoint),Th.update(this.updatePoint,!0)},this.handlePointerUp=(p,x)=>{this.end();const{onEnd:g,onSessionEnd:y,resumeAnimation:b}=this.handlers;if((this.dragSnapToOrigin||!this.startEvent)&&b&&b(),!(this.lastMoveEvent&&this.lastMoveEventInfo))return;const v=oPe(p.type==="pointercancel"?this.lastMoveEventInfo:Ene(x,this.transformPagePoint),this.history);this.startEvent&&g&&g(p,v),y&&y(p,v)},!KHe(t))return;this.dragSnapToOrigin=i,this.handlers=n,this.transformPagePoint=r,this.distanceThreshold=l,this.contextWindow=a||window;const c=vee(t),d=Ene(c,this.transformPagePoint),{point:u}=d,{timestamp:h}=iy;this.history=[{...u,timestamp:h}];const{onSessionStart:m}=n;m&&m(t,oPe(d,this.history)),this.removeListeners=xee(vY(this.contextWindow,"pointermove",this.handlePointerMove),vY(this.contextWindow,"pointerup",this.handlePointerUp),vY(this.contextWindow,"pointercancel",this.handlePointerUp)),o&&this.startScrollTracking(o)}startScrollTracking(t){let n=t.parentElement;for(;n;){const r=getComputedStyle(n);(jot.has(r.overflowX)||jot.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),Th.update(this.updatePoint,!0))}updateHandlers(t){this.handlers=t}end(){this.removeListeners&&this.removeListeners(),this.removeScrollListeners&&this.removeScrollListeners(),this.scrollPositions.clear(),i6(this.updatePoint)}}function Ene(s,t){return t?{point:t(s.point)}:s}function Not(s,t){return{x:s.x-t.x,y:s.y-t.y}}function oPe({point:s},t){return{point:s,delta:Not(s,ETt(t)),offset:Not(s,cSs(t)),velocity:dSs(t,.1)}}function cSs(s){return s[0]}function ETt(s){return s[s.length-1]}function dSs(s,t){if(s.length<2)return{x:0,y:0};let n=s.length-1,r=null;const a=ETt(s);for(;n>=0&&(r=s[n],!(a.timestamp-r.timestamp>Ib(t)));)n--;if(!r)return{x:0,y:0};r===s[0]&&s.length>2&&a.timestamp-r.timestamp>Ib(t)*2&&(r=s[1]);const i=Dj(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 uSs(s,{min:t,max:n},r){return t!==void 0&&sn&&(s=r?jm(n,s,r.max):Math.min(s,n)),s}function kot(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 hSs(s,{top:t,left:n,bottom:r,right:a}){return{x:kot(s.x,n,a),y:kot(s.y,t,r)}}function Sot(s,t){let n=t.min-s.min,r=t.max-s.max;return t.max-t.minr?n=VZ(t.min,t.max-r,s.min):r>a&&(n=VZ(s.min,s.max-a,t.min)),_5(0,1,n)}function fSs(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 c7e=.35;function xSs(s=c7e){return s===!1?s=0:s===!0&&(s=c7e),{x:Cot(s,"left","right"),y:Cot(s,"top","bottom")}}function Cot(s,t,n){return{min:Aot(s,t),max:Aot(s,n)}}function Aot(s,t){return typeof s=="number"?s:s[t]||0}const gSs=new WeakMap;class ySs{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=ig(),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(vee(h).point),this.stopAnimation()},l=(h,m)=>{const{drag:p,dragPropagation:x,onDragStart:g}=this.getProps();if(p&&!x&&(this.openDragLock&&this.openDragLock(),this.openDragLock=H2s(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),eS(b=>{let v=this.getAxisMotionValue(b).get()||0;if(u5.test(v)){const{projection:N}=this.visualElement;if(N&&N.layout){const C=N.layout.layoutBox[b];C&&(v=o1(C)*(parseFloat(v)/100))}}this.originPoint[b]=v}),g&&Th.update(()=>g(h,m),!1,!0),e7e(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:x,onDirectionLock:g,onDrag:y}=this.getProps();if(!p&&!this.openDragLock)return;const{offset:b}=m;if(x&&this.currentDirection===null){this.currentDirection=bSs(b),this.currentDirection!==null&&g&&g(this.currentDirection);return}this.updateAxis("x",m.point,b),this.updateAxis("y",m.point,b),this.visualElement.render(),y&&Th.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 ATt(t,{onSessionStart:i,onStart:l,onMove:o,onSessionEnd:c,resumeAnimation:d},{transformPagePoint:this.visualElement.getTransformPagePoint(),dragSnapToOrigin:u,distanceThreshold:r,contextWindow:CTt(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&&Th.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||!Tne(t,a,this.currentDirection))return;const i=this.getAxisMotionValue(t);let l=this.originPoint[t]+r[t];this.constraints&&this.constraints[t]&&(l=uSs(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&&d9(t)?this.constraints||(this.constraints=this.resolveRefConstraints()):t&&r?this.constraints=hSs(r.layoutBox,t):this.constraints=!1,this.elastic=xSs(n),a!==this.constraints&&!d9(t)&&r&&this.constraints&&!this.hasMutatedConstraints&&eS(l=>{this.constraints!==!1&&this.getAxisMotionValue(l)&&(this.constraints[l]=fSs(r.layoutBox[l],this.constraints[l]))})}resolveRefConstraints(){const{dragConstraints:t,onMeasureDragConstraints:n}=this.getProps();if(!t||!d9(t))return!1;const r=t.current;tU(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=bNs(r,a.root,this.visualElement.getTransformPagePoint());let l=mSs(a.layout.layoutBox,i);if(n){const o=n(gNs(l));this.hasMutatedConstraints=!!o,o&&(l=ZEt(o))}return l}startAnimation(t){const{drag:n,dragMomentum:r,dragElastic:a,dragTransition:i,dragSnapToOrigin:l,onDragTransitionEnd:o}=this.getProps(),c=this.constraints||{},d=eS(u=>{if(!Tne(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,x={type:"inertia",velocity:r?t[u]:0,bounceStiffness:m,bounceDamping:p,timeConstant:750,restDelta:1,restSpeed:10,...i,...h};return this.startAxisValueAnimation(u,x)});return Promise.all(d).then(o)}startAxisValueAnimation(t,n){const r=this.getAxisMotionValue(t);return e7e(this.visualElement,t),r.start(UHe(t,r,0,n,this.visualElement,!1))}stopAnimation(){eS(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){eS(n=>{const{drag:r}=this.getProps();if(!Tne(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]-jm(l,o,.5)+c)}})}scalePositionWithinConstraints(){if(!this.visualElement.current)return;const{drag:t,dragConstraints:n}=this.getProps(),{projection:r}=this.visualElement;if(!d9(n)||!r||!this.constraints)return;this.stopAnimation();const a={x:0,y:0};eS(l=>{const o=this.getAxisMotionValue(l);if(o&&this.constraints!==!1){const c=o.get();a[l]=pSs({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(),eS(l=>{if(!Tne(l,t,null))return;const o=this.getAxisMotionValue(l),{min:c,max:d}=this.constraints[l];o.set(jm(c,d,a[l]))}),this.visualElement.render()}addListeners(){if(!this.visualElement.current)return;gSs.set(this.visualElement,this);const t=this.visualElement.current,n=vY(t,"pointerdown",d=>{const{drag:u,dragListener:h=!0}=this.getProps(),m=d.target,p=m!==t&&X2s(m);u&&h&&!p&&this.start(d)});let r;const a=()=>{const{dragConstraints:d}=this.getProps();d9(d)&&d.current&&(this.constraints=this.resolveRefConstraints(),r||(r=vSs(t,d.current,()=>this.scalePositionWithinConstraints())))},{projection:i}=this.visualElement,l=i.addEventListener("measure",a);i&&!i.layout&&(i.root&&i.root.updateScroll(),i.updateLayout()),Th.read(a);const o=WZ(window,"resize",()=>this.scalePositionWithinConstraints()),c=i.addEventListener("didUpdate",({delta:d,hasLayoutChanged:u})=>{this.isDragging&&u&&(eS(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=c7e,dragMomentum:o=!0}=t;return{...t,drag:n,dragDirectionLock:r,dragPropagation:a,dragConstraints:i,dragElastic:l,dragMomentum:o}}}function Eot(s){let t=!0;return()=>{if(t){t=!1;return}s()}}function vSs(s,t,n){const r=Rit(s,Eot(n)),a=Rit(t,Eot(n));return()=>{r(),a()}}function Tne(s,t,n){return(t===!0||t===s)&&(n===null||n===s)}function bSs(s,t=10){let n=null;return Math.abs(s.y)>t?n="y":Math.abs(s.x)>t&&(n="x"),n}class _Ss extends M6{constructor(t){super(t),this.removeGroupControls=Xj,this.removeListeners=Xj,this.controls=new ySs(t)}mount(){const{dragControls:t}=this.node.getProps();t&&(this.removeGroupControls=t.subscribe(this.controls)),this.removeListeners=this.controls.addListeners()||Xj}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 lPe=s=>(t,n)=>{s&&Th.update(()=>s(t,n),!1,!0)};class wSs extends M6{constructor(){super(...arguments),this.removePointerDownListener=Xj}onPointerDown(t){this.session=new ATt(t,this.createPanHandlers(),{transformPagePoint:this.node.getTransformPagePoint(),contextWindow:CTt(this.node)})}createPanHandlers(){const{onPanSessionStart:t,onPanStart:n,onPan:r,onPanEnd:a}=this.node.getProps();return{onSessionStart:lPe(t),onStart:lPe(n),onMove:lPe(r),onEnd:(i,l)=>{delete this.session,a&&Th.postRender(()=>a(i,l))}}}mount(){this.removePointerDownListener=vY(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 cPe=!1;class jSs 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),cPe&&i.root.didUpdate(),i.addEventListener("animationComplete",()=>{this.safeToRemove()}),i.setOptions({...i.options,layoutDependency:this.props.layoutDependency,onExitComplete:()=>this.safeToRemove()})),C2e.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}),cPe=!0,a||t.layoutDependency!==n||n===void 0||t.isPresent!==i?l.willUpdate():this.safeToRemove(),t.isPresent!==i&&(i?l.promote():l.relegate()||Th.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(),WHe.postRender(()=>{!r.currentAnimation&&r.isLead()&&this.safeToRemove()}))}componentWillUnmount(){const{visualElement:t,layoutGroup:n,switchLayoutGroup:r}=this.props,{projection:a}=t;cPe=!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 TTt(s){const[t,n]=yTt(),r=j.useContext(AHe);return e.jsx(jSs,{...s,layoutGroup:r,switchLayoutGroup:j.useContext(kTt),isPresent:t,safeToRemove:n})}const NSs={pan:{Feature:wSs},drag:{Feature:_Ss,ProjectionNode:gTt,MeasureLayout:TTt}};function Tot(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&&Th.postRender(()=>i(t,vee(t)))}class kSs extends M6{mount(){const{current:t}=this.node;t&&(this.unmount=W2s(t,(n,r)=>(Tot(this.node,r,"Start"),a=>Tot(this.node,a,"End"))))}unmount(){}}class SSs extends M6{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=xee(WZ(this.node.current,"focus",()=>this.onFocus()),WZ(this.node.current,"blur",()=>this.onBlur()))}unmount(){}}function Mot(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&&Th.postRender(()=>i(t,vee(t)))}class CSs extends M6{mount(){const{current:t}=this.node;if(!t)return;const{globalTapTarget:n,propagate:r}=this.node.props;this.unmount=J2s(t,(a,i)=>(Mot(this.node,i,"Start"),(l,{success:o})=>Mot(this.node,l,o?"End":"Cancel")),{useGlobalTarget:n,stopPropagation:(r==null?void 0:r.tap)===!1})}unmount(){}}const d7e=new WeakMap,dPe=new WeakMap,ASs=s=>{const t=d7e.get(s.target);t&&t(s)},ESs=s=>{s.forEach(ASs)};function TSs({root:s,...t}){const n=s||document;dPe.has(n)||dPe.set(n,{});const r=dPe.get(n),a=JSON.stringify(t);return r[a]||(r[a]=new IntersectionObserver(ESs,{root:s,...t})),r[a]}function MSs(s,t,n){const r=TSs(t);return d7e.set(s,n),r.observe(s),()=>{d7e.delete(s),r.unobserve(s)}}const LSs={some:0,all:1};class PSs extends M6{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:LSs[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=MSs(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(ISs(t,n))&&this.startObserver()}unmount(){var t;(t=this.stopObserver)==null||t.call(this),this.hasEnteredView=!1,this.isInView=!1}}function ISs({viewport:s={}},{viewport:t={}}={}){return n=>s[n]!==t[n]}const DSs={inView:{Feature:PSs},tap:{Feature:CSs},focus:{Feature:SSs},hover:{Feature:kSs}},RSs={layout:{ProjectionNode:gTt,MeasureLayout:TTt}},OSs={...iSs,...DSs,...NSs,...RSs},jr=tSs(OSs,sSs),FSs={some:0,all:1};function zSs(s,t,{root:n,margin:r,amount:a="some"}={}){const i=GHe(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:FSs[a]});return i.forEach(d=>c.observe(d)),()=>c.disconnect()}function BSs(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 zSs(s.current,c,d)},[t,s,n,a,r]),l}function $Ss(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 Lot(s){return s.visitor_intent==="buying"&&!s.has_agent}function USs({token:s}={}){var x;const t=Vi(),n=s||t.token,{data:r,isLoading:a,isError:i}=zws(n),l=ts(),o=(x=r==null?void 0:r.open_houses)==null?void 0:x.id,{data:c}=ht({queryKey:["cohost-visitors",o],queryFn:async()=>{const{data:g,error:y}=await U.from("open_house_visitors").select("*").eq("open_house_id",o).order("created_at",{ascending:!1});if(y)throw y;return g},enabled:!!o});if(j.useEffect(()=>{if(!o)return;const g=U.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()=>{U.removeChannel(g)}},[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(g=>g.visitor_intent==="buying").length)||0,m=(c==null?void 0:c.filter(Lot).length)||0,p=g=>{if(!g)return"";const[y,b]=g.split(":"),v=parseInt(y);return`${v>12?v-12:v||12}:${b} ${v>=12?"PM":"AM"}`};return e.jsxs("div",{className:"fixed inset-0 bg-gradient-to-br from-slate-950 via-slate-900 to-slate-950 flex flex-col",children:[e.jsxs("div",{className:"border-b border-white/10 px-4 sm:px-6 py-3 flex items-center justify-between bg-black/30 backdrop-blur-xl",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"w-2 h-2 rounded-full bg-emerald-400 animate-pulse"}),e.jsx("span",{className:"text-xs font-medium text-emerald-400 uppercase tracking-wider",children:"Live · Co-Host View"})]}),e.jsx("h1",{className:"text-white font-bold text-sm sm:text-base truncate",children: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(qn,{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(yd,{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(sa,{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:Hs(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(Oi,{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(Lq,{children:c.map((g,y)=>{var N;const b=$Ss(g.visitor_intent),v=Lot(g);return e.jsxs(jr.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 ${v?"bg-orange-500/10 border-orange-500/30":"bg-white/5 border-white/10"}`,children:[e.jsx("div",{className:`w-11 h-11 rounded-full flex items-center justify-center text-lg font-bold shrink-0 ${v?"bg-gradient-to-br from-orange-500 to-amber-500 text-white":"bg-white/10 text-white/80"}`,children:(N=g.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:[g.first_name," ",g.last_name||""]}),v&&e.jsx($e,{className:"bg-orange-500/20 text-orange-300 border-orange-500/40 text-[10px] px-1.5 py-0",children:"🔥 HOT"}),g.has_agent&&e.jsx($e,{variant:"outline",className:"text-[10px] px-1.5 py-0 border-yellow-500/40 text-yellow-400",children:"⚠️ Has Agent"})]}),e.jsxs("div",{className:"flex items-center gap-2 mt-0.5",children:[e.jsxs($e,{variant:"outline",className:`text-[10px] px-1.5 py-0 ${b.color}`,children:[b.emoji," ",b.label]}),e.jsx("span",{className:"text-white/30 text-xs",children:Hs(new Date(g.created_at),"h:mm a")})]})]})]},g.id)})})}):e.jsxs("div",{className:"flex flex-col items-center justify-center h-full text-center py-20",children:[e.jsx("div",{className:"w-20 h-20 rounded-full bg-white/5 flex items-center justify-center mb-4",children:e.jsx(Cg,{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 qSs(){const t=Wd().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(USs,{token:n})}if(t.startsWith("rsvp/")){const n=t.slice(5);if(n)return e.jsx(HAt,{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(VAt,{slug:t})}function VSs({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(jr.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(jr.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(jr.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(sa,{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(ai,{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(ya,{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(nn,{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(Ed,{className:"w-4 h-4"}),e.jsx("span",{className:"text-sm font-medium",children:"Text"})]})]})})})]})}function MTt({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=r2(a,new Date);if(d5(a)&&!x0(a))return null;const o=x0(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(jr.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(jr.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 LTt({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(jr.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 mu(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`)}const HSs=[{key:"contract_date",label:"Contract Accepted",icon:n5},{key:"earnest_money_due_date",label:"Earnest Money",icon:qd},{key:"inspection_date",label:"Inspection",icon:Vr},{key:"inspection_contingency_date",label:"Inspection Deadline",icon:Wr},{key:"appraisal_date",label:"Appraisal",icon:sa},{key:"loan_approval_date",label:"Loan Approval",icon:jz},{key:"title_docs_due_date",label:"Title & Disclosures",icon:Wr},{key:"final_walkthrough_date",label:"Final Walkthrough",icon:q3},{key:"target_close_date",label:"Target Close",icon:ia}];function GSs(s,t){const n=Hs(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 WSs(s,t){const n=Hs(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 ITt({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=HSs.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,x,g)=>{const y=mu(x);if(g==="google")window.open(GSs(p,y),"_blank");else{const b=WSs(p,y),v=document.createElement("a");v.href=b,v.download=`${p.replace(/\s+/g,"-").toLowerCase()}.ics`,v.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:x,done:g,icon:y})=>{const b=mu(x),v=d5(b)&&!x0(b),N=x0(b),C=!v&&!N,A=g?"Completed":N?"Today":v?"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:g?"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:g?e.jsx(oa,{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:g?"hsl(var(--portal-ink-muted))":"hsl(var(--portal-ink))"},children:Hs(b,"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:g||N?"hsl(var(--portal-gold))":"hsl(var(--portal-ink-dim))",border:`1px solid hsl(var(--portal-gold) / ${g||N?.5:.18})`},children:A})]}),C&&e.jsxs("div",{className:"flex items-center gap-1 mt-1",children:[e.jsx("button",{onClick:()=>h(p,x,"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(gg,{className:"w-3.5 h-3.5"})}),e.jsx("button",{onClick:()=>h(p,x,"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 DTt({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 U.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(Wr,{className:"w-4 h-4",style:{color:"hsl(var(--portal-gold))"}})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm portal-serif truncate",style:{color:"hsl(var(--portal-ink))",fontSize:"1rem"},children:r.file_name}),e.jsx("p",{className:"text-[10px] tracking-widest uppercase mt-0.5",style:{color:"hsl(var(--portal-ink-dim))"},children:t(r.file_size)})]}),e.jsx(di,{className:"w-4 h-4 flex-shrink-0",style:{color:"hsl(var(--portal-gold) / 0.5)"}})]},r.id))})]})}function RTt({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(Tx,{className:"w-3.5 h-3.5",style:{color:"hsl(var(--portal-gold))"}}):e.jsx(Dx,{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:Hs(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 Pq=[{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"}],KSs=[{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 YSs(s){return ht({queryKey:["vendors","brokerage",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await U.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 ZSs(){const s=Za(),{brokerageId:t}=_s();return ht({queryKey:["vendors","library",s,t],queryFn:async()=>{if(!s)return{vendors:[],selections:[]};let n=U.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}),U.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 XSs(){const s=ts();return yt({mutationFn:async t=>{if(t.id){const{id:n,created_at:r,...a}=t,{data:i,error:l}=await U.from("vendors").update(a).eq("id",n).select().single();if(l)throw l;return i}else{const{data:n,error:r}=await U.from("vendors").insert(t).select().single();if(r)throw r;return n}},onSuccess:()=>s.invalidateQueries({queryKey:["vendors"]})})}function OTt(){const s=ts();return yt({mutationFn:async t=>{const{error:n}=await U.from("vendors").delete().eq("id",t);if(n)throw n},onSuccess:()=>s.invalidateQueries({queryKey:["vendors"]})})}function QSs(){const s=Za(),t=ts();return yt({mutationFn:async({vendorId:n,isVisible:r})=>{if(!s)throw new Error("No user");const{data:a}=await U.from("agent_vendor_selections").select("id").eq("agent_user_id",s).eq("vendor_id",n).maybeSingle();if(a){const{error:i}=await U.from("agent_vendor_selections").update({is_visible:r}).eq("id",a.id);if(i)throw i}else{const{error:i}=await U.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 FTt(s){return ht({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 U.from("profiles").select("brokerage_id").eq("id",t).maybeSingle(),r=n==null?void 0:n.brokerage_id,a=U.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}),U.from("agent_vendor_selections").select("vendor_id, display_order, is_visible").eq("agent_user_id",t),U.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 x=u.get(p.id);return!(x&&x.is_visible===!1&&!p.is_required)}).map(p=>{var x;return{...p,display_order:((x=u.get(p.id))==null?void 0:x.display_order)??p.sort_order??0}}).sort((p,x)=>(p.display_order||0)-(x.display_order||0))},enabled:!!(s!=null&&s.id)&&!!(s!=null&&s.owner_user_id)})}async function Pot(s){try{await U.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 zTt(s,t){return ht({queryKey:["vendor-clicks",s,t],queryFn:async()=>{if(!t)return{};const{data:n}=await U.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 U.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 BTt({portalId:s,ownerUserId:t,currentStage:n,brandingColor:r,layout:a="list"}){const{data:i=[],isLoading:l}=FTt({id:s,owner_user_id:t});if(l||i.length===0)return null;const o=i.filter(v=>!v.stage_filter||v.stage_filter.length===0||!n?!0:v.stage_filter.includes(n));if(o.length===0)return null;const c=r||"#406E71",d=(v,N)=>{switch(N){case"book":return v.booking_url;case"website":return v.website;case"call":return v.phone?`tel:${v.phone.replace(/[^\d+]/g,"")}`:null;case"email":case"quote":return v.email?`mailto:${v.email}`:null}},u=v=>{const N=d(v,v.action_type);Pot({vendorId:v.id,portalId:s,agentUserId:t,actionTaken:v.action_type}),N&&window.open(N,v.action_type==="call"||v.action_type==="email"||v.action_type==="quote"?"_self":"_blank")},h=v=>{const N=d(v,v.action_type);return[{action:"website",label:"Website",icon:e.jsx(Gl,{className:"w-3.5 h-3.5"})},{action:"email",label:"Email",icon:e.jsx(nn,{className:"w-3.5 h-3.5"})},{action:"call",label:"Call",icon:e.jsx(ya,{className:"w-3.5 h-3.5"})},{action:"book",label:"Book",icon:e.jsx(ia,{className:"w-3.5 h-3.5"})}].filter(A=>A.action!==v.action_type).map(A=>{const T=d(v,A.action);return!T||T===N?null:e.jsxs("button",{onClick:()=>{Pot({vendorId:v.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=v=>{switch(v.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=v=>{switch(v.action_type){case"book":return e.jsx(ia,{className:"w-3.5 h-3.5"});case"call":return e.jsx(ya,{className:"w-3.5 h-3.5"});case"email":case"quote":return e.jsx(nn,{className:"w-3.5 h-3.5"});case"website":return e.jsx(Gl,{className:"w-3.5 h-3.5"})}},x=v=>{var N;return((N=Pq.find(C=>C.value===v))==null?void 0:N.label)||v},g=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(dn,{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(v=>v.disclosure_text)&&e.jsx("div",{className:"mt-4 pt-3 border-t border-slate-100 space-y-1",children:o.filter(v=>v.disclosure_text).map(v=>e.jsxs("p",{className:"text-[10px] text-slate-400",children:[e.jsxs("span",{className:"font-medium",children:[v.company||v.name,":"]})," ",v.disclosure_text]},v.id))});if(a==="grid")return e.jsxs(_e,{className:"p-5 sm:p-6 rounded-2xl border-slate-200/80 shadow-sm bg-white/70 backdrop-blur",children:[g,e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-3",children:o.map(v=>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:v.logo_url?e.jsx("img",{src:v.logo_url,alt:v.name,className:"w-full h-full object-cover"}):e.jsx("span",{className:"text-base font-semibold text-slate-500",children:(v.company||v.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:v.company||v.name}),v.company&&v.name&&e.jsx("p",{className:"text-xs text-slate-500 truncate",children:v.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:x(v.category)})]})]}),v.description&&e.jsx("p",{className:"text-xs text-slate-500 mt-3 line-clamp-2",children:v.description}),e.jsxs("div",{className:"mt-auto pt-4 flex flex-col gap-2",children:[e.jsxs($,{size:"sm",onClick:()=>u(v),style:{backgroundColor:c},className:"text-white hover:opacity-90 w-full",children:[p(v),e.jsx("span",{className:"ml-1.5 text-xs",children:m(v)})]}),h(v).length>0&&e.jsx("div",{className:"flex flex-wrap items-center justify-center gap-3",children:h(v)})]})]},v.id))}),y]});const b=o.reduce((v,N)=>((v[N.category]=v[N.category]||[]).push(N),v),{});return e.jsxs(_e,{className:"p-5 rounded-2xl border-slate-200/80 shadow-sm",children:[g,e.jsx("div",{className:"space-y-4",children:Object.entries(b).map(([v,N])=>e.jsxs("div",{children:[e.jsx("p",{className:"text-[11px] uppercase tracking-wide text-slate-400 font-medium mb-2",children:x(v)}),e.jsx("div",{className:"space-y-2",children:N.map(C=>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:C.logo_url?e.jsx("img",{src:C.logo_url,alt:C.name,className:"w-full h-full object-cover"}):e.jsx("span",{className:"text-sm font-semibold text-slate-500",children:C.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:C.company||C.name}),C.company&&C.name&&e.jsx("p",{className:"text-xs text-slate-500 truncate",children:C.name}),C.description&&e.jsx("p",{className:"text-xs text-slate-500 truncate mt-0.5",children:C.description})]}),e.jsxs($,{size:"sm",onClick:()=>u(C),style:{backgroundColor:c},className:"text-white hover:opacity-90 shrink-0",children:[p(C),e.jsx("span",{className:"ml-1.5 text-xs",children:m(C)})]})]},C.id))})]},v))}),y]})}function JSs(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 e5s(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 $Tt({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=JSs(t);j.useEffect(()=>{h.current||(h.current=!0,U.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 U.from("portal_referral_clicks").insert({portal_id:s,owner_user_id:n,click_type:T,user_agent:navigator.userAgent.slice(0,500)})},x=()=>`${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}`,g=async()=>{await navigator.clipboard.writeText(m),u(!0),p("copy_link"),setTimeout(()=>u(!1),2e3)},y=()=>{p("share_sms");const T=encodeURIComponent(x());window.location.href=`sms:?&body=${T}`},b=()=>{p("share_email");const T=encodeURIComponent("A referral you'll thank me for"),P=encodeURIComponent(x());window.location.href=`mailto:?subject=${T}&body=${P}`},v=()=>{p("open_form"),window.open(m,"_blank")},N=a||"Know someone buying or selling?",C=c?e5s(c):null,A=C==null?void 0:C.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."})]}),C&&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(dn,{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:C,controls:!0,className:"w-full h-full",playsInline:!0}):e.jsx("iframe",{src:C,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(Co,{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:v,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(ni,{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(Ed,{className:"w-3.5 h-3.5"}),"Text"]}),e.jsxs("button",{onClick:b,className:"flex items-center justify-center gap-1.5 bg-white/10 hover:bg-white/20 backdrop-blur-sm rounded-lg py-2.5 text-xs font-medium transition-colors",children:[e.jsx(nn,{className:"w-3.5 h-3.5"}),"Email"]}),e.jsxs("button",{onClick:g,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(oa,{className:"w-3.5 h-3.5"}):e.jsx(Ca,{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(ni,{className:"w-4 h-4 text-slate-400"})]})})]})}function t5s(s){return s==="buy-side"?"Home Search in Progress":s==="listing"?"Your Home Is On The Market":"Active Phase"}function s5s(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 n5s={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. 🎉"}},UTt=["Lead","Consultation","Agreement Signed","Active","Under Contract","Closing","Closed Won"];function ZCe(s){return UTt.map(t=>{if(t==="Active")return{key:"Active",label:t5s(s),description:s5s(s)};const n=n5s[t];return{key:t,label:n.label,description:n.description}})}function tSe(s){if(!s)return 0;const t=UTt.indexOf(s);return t>=0?t:0}function r5s({portal:s,linkedPortal:t,activePortal:n,activeTab:r,onTabChange:a,agentProfile:i,branding:l,updates:o,documents:c}){var K,Q,J;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,x=p==null?void 0:p.is_won_stage,g=m==null?void 0:m.deal_type,y=n==null?void 0:n.stage_mapping;let b=ZCe(g);y&&y.length>0&&(b=y.map((ce,ue)=>{var ne,ee;return{key:`custom-${ue}`,label:ce.label||((ne=b[ue])==null?void 0:ne.label)||`Stage ${ue+1}`,description:ce.description||((ee=b[ue])==null?void 0:ee.description)||"",video_url:ce.video_url||void 0}}));const v=y&&y.length>0?Math.min(tSe(p==null?void 0:p.name),b.length-1):tSe(p==null?void 0:p.name),N=b[v],C=N==null?void 0:N.video_url,A=x&&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,P=!!t,M=(K=s==null?void 0:s.deal_pipeline)==null?void 0:K.deal_type,I=(Q=t==null?void 0:t.deal_pipeline)==null?void 0:Q.deal_type,D=ce=>ce==="listing"?"Your Sale":ce==="buy-side"?"Your Purchase":"Transaction",B=b.length>1?Math.round((v+1)/b.length*100):0,{data:q=[]}=FTt({id:n==null?void 0:n.id,owner_user_id:n==null?void 0:n.owner_user_id}),W=q.some(ce=>!ce.stage_filter||ce.stage_filter.length===0||!(p!=null&&p.name)?!0:ce.stage_filter.includes(p.name)),V=()=>{var ce;(ce=document.getElementById("trusted-vendors"))==null||ce.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(jr.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(kf,{className:"w-3 h-3",style:{color:"hsl(var(--portal-gold))"}}),"Secure & Encrypted"]})]}),e.jsxs(jr.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(sa,{className:"w-3 h-3"}),g==="listing"?"Sale":g==="buy-side"?"Purchase":"Transaction",x&&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(ai,{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(a5s,{pct:B}),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 ",v+1," of ",b.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)"}})]}),P&&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(ce=>{const ue=ce==="primary"?M:I,ne=r===ce;return e.jsx("button",{onClick:()=>a(ce),className:"portal-serif px-5 py-2 rounded-lg transition-all",style:{fontSize:"1rem",background:ne?"hsl(var(--portal-surface-3))":"transparent",color:ne?"hsl(var(--portal-gold))":"hsl(var(--portal-ink-muted))",borderBottom:ne?"1px solid hsl(var(--portal-gold))":"1px solid transparent"},children:D(ue)},ce)})}),e.jsxs(jr.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(rA,{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:((J=i==null?void 0:i.name)==null?void 0:J.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(uPe,{href:`tel:${i.phone}`,icon:ya,label:"Call",sub:i.phone}),(i==null?void 0:i.phone)&&e.jsx(uPe,{href:`sms:${i.phone}`,icon:Ed,label:"Text message"}),(i==null?void 0:i.email)&&e.jsx(uPe,{href:`mailto:${i.email}`,icon:nn,label:"Email",sub:i.email})]})]}),e.jsxs(rA,{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(hPe,{icon:ia,label:"Target close",value:Iot(m.target_close_date)}),(m==null?void 0:m.contract_date)&&e.jsx(hPe,{icon:Hr,label:"Under contract",value:Iot(m.contract_date)}),e.jsx(hPe,{icon:_o,label:"Progress",value:`${B}%`})]})]})]})}),e.jsxs("main",{className:"col-span-6 space-y-5",children:[A&&e.jsx($Tt,{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(MTt,{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(rA,{children:e.jsx(PTt,{currentStage:N,nextStepText:n.next_step_text,nextStepVideoUrl:C||n.next_step_video_url})}),e.jsx(rA,{children:e.jsx(LTt,{journeyStages:b,currentIndex:v})}),o&&o.length>0&&e.jsx(rA,{children:e.jsx(RTt,{updates:o})})]}),e.jsxs("aside",{className:"col-span-3 space-y-5",children:[e.jsx(rA,{children:e.jsx(ITt,{deal:m,portal:n})}),c&&c.length>0&&e.jsx(rA,{children:e.jsx(DTt,{documents:c})}),W&&e.jsx(rA,{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:ce=>{ce.currentTarget.style.background="hsl(var(--portal-gold) / 0.12)"},onMouseLeave:ce=>{ce.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(Bz,{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(_o,{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(BTt,{portalId:n.id,ownerUserId:n.owner_user_id,currentStage:p==null?void 0:p.name,brandingColor:"hsl(var(--portal-gold))",layout:"grid"})})]})]})}function rA({children:s}){return e.jsx(jr.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 uPe({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 hPe({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 a5s({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(jr.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 Iot(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 i5s({portal:s,dealData:t,agentProfile:n,customQuestions:r,deviceFingerprint:a,onComplete:i}){var y,b;const[l,o]=j.useState({first_name:((y=s.client_name)==null?void 0:y.split(" ")[0])||"",last_name:((b=s.client_name)==null?void 0:b.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:v}=await U.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(v)throw v},onSuccess:i,onError:v=>{console.error("[PortalOnboarding] Submit failed:",v),ae.error("Something went wrong. Please try again.")}}),p=t!=null&&t.property_address?`${t.property_address}, ${t.city||""}, ${t.state||""}`:null,x="mt-1 rounded-xl bg-white text-slate-900 placeholder:text-slate-400 border-slate-200 focus-visible:ring-slate-400",g="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(ai,{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:v=>{v.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(se,{className:"text-xs font-medium text-slate-700",children:"First Name *"}),e.jsx(be,{required:!0,value:l.first_name,onChange:v=>o(N=>({...N,first_name:v.target.value})),className:x,placeholder:"John"})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-xs font-medium text-slate-700",children:"Last Name"}),e.jsx(be,{value:l.last_name,onChange:v=>o(N=>({...N,last_name:v.target.value})),className:x,placeholder:"Doe"})]})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-xs font-medium text-slate-700",children:"Email"}),e.jsx(be,{type:"email",value:l.email,onChange:v=>o(N=>({...N,email:v.target.value})),className:x,placeholder:"john@example.com"})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-xs font-medium text-slate-700",children:"Phone"}),e.jsx(be,{type:"tel",value:l.phone,onChange:v=>o(N=>({...N,phone:v.target.value})),className:x,placeholder:"(555) 123-4567"})]}),e.jsxs("div",{children:[e.jsx(se,{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(v=>e.jsx("button",{type:"button",onClick:()=>o(N=>({...N,preferred_contact_method:v.value})),className:`px-3.5 py-1.5 rounded-full text-xs font-medium border transition-colors ${l.preferred_contact_method===v.value?"bg-slate-800 text-white border-slate-800":"bg-white text-slate-600 border-slate-200 hover:border-slate-300"}`,children:v.label},v.value))})]}),e.jsxs("div",{children:[e.jsx(se,{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(v=>e.jsx("button",{type:"button",onClick:()=>o(N=>({...N,client_role:v})),className:`px-3.5 py-1.5 rounded-full text-xs font-medium border transition-colors ${l.client_role===v?"bg-slate-800 text-white border-slate-800":"bg-white text-slate-600 border-slate-200 hover:border-slate-300"}`,children:v.charAt(0).toUpperCase()+v.slice(1)},v))})]}),r.map(v=>e.jsxs("div",{children:[e.jsxs(se,{className:"text-xs font-medium text-slate-700",children:[v.question_text," ",v.is_required&&"*"]}),v.field_type==="text"&&e.jsx(be,{required:v.is_required,value:c[v.id]||"",onChange:N=>d(C=>({...C,[v.id]:N.target.value})),className:x}),v.field_type==="textarea"&&e.jsx("textarea",{required:v.is_required,value:c[v.id]||"",onChange:N=>d(C=>({...C,[v.id]:N.target.value})),className:`${g} min-h-[80px]`}),v.field_type==="dropdown"&&e.jsxs("select",{required:v.is_required,value:c[v.id]||"",onChange:N=>d(C=>({...C,[v.id]:N.target.value})),className:`${g} h-10`,children:[e.jsx("option",{value:"",children:"Select..."}),(v.options||[]).map(N=>e.jsx("option",{value:N,children:N},N))]}),v.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(C=>({...C,[v.id]:N})),className:`px-3.5 py-1.5 rounded-full text-xs font-medium border transition-colors ${c[v.id]===N?"bg-slate-800 text-white border-slate-800":"bg-white text-slate-600 border-slate-200"}`,children:N},N))})]},v.id)),e.jsxs("div",{children:[e.jsx(se,{className:"text-xs font-medium text-slate-700",children:"Notes for your agent"}),e.jsx("textarea",{value:l.notes,onChange:v=>o(N=>({...N,notes:v.target.value})),className:`${g} 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(se,{className:"text-xs font-medium text-slate-700",children:"First Name"}),e.jsx(be,{value:l.spouse_first_name,onChange:v=>o(N=>({...N,spouse_first_name:v.target.value})),className:x})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-xs font-medium text-slate-700",children:"Last Name"}),e.jsx(be,{value:l.spouse_last_name,onChange:v=>o(N=>({...N,spouse_last_name:v.target.value})),className:x})]})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-xs font-medium text-slate-700",children:"Email"}),e.jsx(be,{type:"email",value:l.spouse_email,onChange:v=>o(N=>({...N,spouse_email:v.target.value})),className:x})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-xs font-medium text-slate-700",children:"Phone"}),e.jsx(be,{type:"tel",value:l.spouse_phone,onChange:v=>o(N=>({...N,spouse_phone:v.target.value})),className:x})]})]})]}),e.jsx($,{type:"submit",disabled:m.isPending||!l.first_name,className:"w-full h-12 rounded-full text-sm font-semibold bg-slate-900 hover:bg-slate-800",children:m.isPending?"Submitting...":"Access My Portal"})]})]})})}function o5s(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 qTt(){const s=Za();return ht({queryKey:["agent-portal-branding",s],queryFn:async()=>{if(!s)return null;const{data:t,error:n}=await U.from("agent_portal_branding").select("*").eq("user_id",s).maybeSingle();if(n)throw n;return t},enabled:!!s})}function l5s(s){return ht({queryKey:["agent-portal-branding-public",s],queryFn:async()=>{if(!s)return null;const{data:t,error:n}=await U.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 c5s(){const s=Za(),t=ts();return yt({mutationFn:async n=>{if(!s)throw new Error("Not authenticated");const{data:r,error:a}=await U.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 VTt(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 U.storage.from("portal-branding").upload(a,t,{upsert:!0,cacheControl:"3600"});if(i)throw i;const{data:l}=U.storage.from("portal-branding").getPublicUrl(a);return l.publicUrl}function d5s(s,t){return ht({queryKey:["client-portal-public",s],queryFn:async()=>{if(!s)return null;const{data:n,error:r}=await U.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 u5s(s){return ht({queryKey:["client-portal-by-id",s],queryFn:async()=>{if(!s)return null;const{data:t,error:n}=await U.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 HTt({slug:s}){var ce,ue,ne,ee,le,he;const[t,n]=j.useState(!1),[r,a]=j.useState("primary"),[i]=j.useState(()=>{const ve=`portal_fp_${s}`;let ge=localStorage.getItem(ve);return ge||(ge=localStorage.getItem("portal_fp"),ge?localStorage.setItem(ve,ge):(ge=crypto.randomUUID(),localStorage.setItem(ve,ge),localStorage.setItem("portal_fp",ge))),ge});j.useEffect(()=>(document.body.classList.add("client-portal-page"),()=>document.body.classList.remove("client-portal-page")),[]);const{data:l,isLoading:o,error:c}=d5s(s,!0),d=l==null?void 0:l.linked_portal_id,{data:u}=u5s(d),h=(ce=l==null?void 0:l.deal_pipeline)==null?void 0:ce.owner_user_id;ht({queryKey:["portal-stages",h],queryFn:async()=>{const{data:ve,error:ge}=await U.from("deal_pipeline_stages").select("*").eq("owner_user_id",h).order("sort_order",{ascending:!0});if(ge)throw ge;return ve},enabled:!!h});const{data:m}=ht({queryKey:["portal-agent",h],queryFn:async()=>{const{data:ve,error:ge}=await U.from("profiles").select("id, name, avatar_url, phone, email").eq("id",h).single();if(ge)throw ge;return ve},enabled:!!h}),{data:p}=l5s(h),x=r==="linked"&&u?u:l,g=x==null?void 0:x.id,y=o5s(p,x==null?void 0:x.branding_override),b=y.portal_theme==="azure"?"azure":"noir";j.useEffect(()=>{const ve=`portal-theme-${b}`;return document.body.classList.add(ve),()=>document.body.classList.remove(ve)},[b]);const{data:v}=ht({queryKey:["portal-updates-public",g],queryFn:async()=>{const{data:ve,error:ge}=await U.from("portal_updates").select("*").eq("portal_id",g).order("created_at",{ascending:!1});if(ge)throw ge;return ve},enabled:!!g}),N=(ue=x==null?void 0:x.deal_pipeline)==null?void 0:ue.id,{data:C}=ht({queryKey:["portal-documents",N],queryFn:async()=>{const{data:ve,error:ge}=await U.from("deal_files").select("*").eq("deal_id",N).eq("visible_on_portal",!0).order("created_at",{ascending:!1});if(ge)throw ge;return ve},enabled:!!N}),A=l==null?void 0:l.id,T=A?`portal_onboarded_${A}_${i}`:null,P=T?localStorage.getItem(T)==="1":!1,{data:M,isLoading:I}=ht({queryKey:["portal-onboarding-check",A,i],queryFn:async()=>{const{data:ve,error:ge}=await U.from("portal_onboarding_submissions").select("id").eq("portal_id",A).eq("device_fingerprint",i).maybeSingle();if(ge)throw ge;return ve&&T&&localStorage.setItem(T,"1"),ve},enabled:!!A&&!!(l!=null&&l.require_onboarding)&&!P,staleTime:5*60*1e3}),D=!!(l!=null&&l.require_onboarding)&&!P&&!M&&!t,{data:B}=ht({queryKey:["portal-custom-questions-public",h],queryFn:async()=>{const{data:ve,error:ge}=await U.from("portal_custom_questions").select("*").eq("owner_user_id",h).eq("is_active",!0).order("sort_order",{ascending:!0});if(ge)throw ge;return ve},enabled:!!h&&D}),q=P||!!M||t||!(l!=null&&l.require_onboarding);if(o||l!=null&&l.require_onboarding&&!P&&I)return e.jsx("div",{className:"min-h-screen flex items-center justify-center",style:{background:"hsl(var(--portal-bg))"},children:e.jsx(Ht,{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(kf,{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(!q){const ve=l==null?void 0:l.deal_pipeline;return e.jsx("div",{className:"min-h-screen bg-gradient-to-b from-slate-50 to-slate-100",children:e.jsx(i5s,{portal:l,dealData:ve,agentProfile:m,customQuestions:B||[],deviceFingerprint:i,onComplete:()=>{T&&localStorage.setItem(T,"1"),n(!0)}})})}const W=(ne=l==null?void 0:l.deal_pipeline)==null?void 0:ne.deal_type,V=(ee=u==null?void 0:u.deal_pipeline)==null?void 0:ee.deal_type,K=!!u,Q=ve=>ve==="listing"?"Your Sale":ve==="buy-side"?"Your Purchase":"Transaction",J=ve=>ve==="listing"?e.jsx(sa,{className:"w-3.5 h-3.5"}):e.jsx(Mb,{className:"w-3.5 h-3.5"});return e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"hidden lg:block",children:e.jsx(r5s,{portal:l,linkedPortal:u,activePortal:x,activeTab:r,onTabChange:a,agentProfile:m,branding:y,updates:v,documents:C})}),e.jsxs("div",{className:"lg:hidden min-h-screen pb-16",style:{background:"var(--portal-gradient-noir)"},children:[e.jsx(VSs,{dealData:x==null?void 0:x.deal_pipeline,agentProfile:m,welcomeMessage:(x==null?void 0:x.welcome_message)||y.welcome_message,isWon:(he=(le=x==null?void 0:x.deal_pipeline)==null?void 0:le.deal_pipeline_stages)==null?void 0:he.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(ve=>{const ge=r===ve,fe=ve==="primary"?W:V;return e.jsxs("button",{onClick:()=>a(ve),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:ge?"hsl(var(--portal-surface-3))":"transparent",color:ge?"hsl(var(--portal-gold))":"hsl(var(--portal-ink-muted))",boxShadow:ge?"0 1px 0 hsl(var(--portal-gold) / 0.3) inset":"none"},children:[J(fe),e.jsx("span",{style:{fontSize:"1rem"},children:Q(fe)})]},ve)})}),e.jsx(h5s,{portal:x,updates:v,documents:C,agentProfile:m}),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(kf,{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 h5s({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=ZCe(c);d&&d.length>0&&(u=d.map((g,y)=>{var b,v;return{key:`custom-${y}`,label:g.label||((b=u[y])==null?void 0:b.label)||`Stage ${y+1}`,description:g.description||((v=u[y])==null?void 0:v.description)||"",video_url:g.video_url||void 0}}));const h=d&&d.length>0?Math.min(tSe(l==null?void 0:l.name),u.length-1):tSe(l==null?void 0:l.name),m=u[h],p=m==null?void 0:m.video_url,x=o&&s.show_post_close_tips!==!1&&s.referral_enabled!==!1;return e.jsxs(e.Fragment,{children:[x&&e.jsx($Tt,{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(MTt,{targetCloseDate:i==null?void 0:i.target_close_date,actualCloseDate:i==null?void 0:i.actual_close_date,clientName:s.client_name}),e.jsx(LTt,{journeyStages:u,currentIndex:h}),m&&e.jsx(PTt,{currentStage:m,nextStepText:s.next_step_text,nextStepVideoUrl:p||s.next_step_video_url}),e.jsx(ITt,{deal:i,portal:s}),n&&n.length>0&&e.jsx(DTt,{documents:n}),(s==null?void 0:s.id)&&(s==null?void 0:s.owner_user_id)&&e.jsx(BTt,{portalId:s.id,ownerUserId:s.owner_user_id,currentStage:l==null?void 0:l.name}),t&&t.length>0&&e.jsx(RTt,{updates:t})]})}function GTt({slug:s}){const t=Vi(),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,x]=j.useState(""),[g,y]=j.useState(""),[b,v]=j.useState("buying"),[N,C]=j.useState("");j.useEffect(()=>(document.body.classList.add("client-portal-page"),()=>document.body.classList.remove("client-portal-page")),[]);const{data:A,isLoading:T,error:P}=ht({queryKey:["portal-referral-target",n],queryFn:async()=>{if(!n)return null;const{data:D,error:B}=await U.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(B)throw B;return D},enabled:!!n}),{data:M}=ht({queryKey:["portal-referral-agent",A==null?void 0:A.owner_user_id],queryFn:async()=>{const{data:D}=await U.from("profiles").select("id, name, avatar_url").eq("id",A.owner_user_id).single();return D},enabled:!!(A!=null&&A.owner_user_id)}),I=async D=>{if(D.preventDefault(),!A||!h.trim()){ae.error("Please enter your friend's name");return}if(!p.trim()&&!g.trim()){ae.error("Please add at least an email or phone for your friend");return}a(!0);try{const{error:B}=await U.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:g.trim()||null,friend_interest:b,friend_message:N.trim()||null});if(B)throw B;l(!0)}catch(B){ae.error(B.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(on,{className:"h-96 w-full max-w-lg rounded-2xl mx-4"})}):P||!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(oa,{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(ka,{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(Co,{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(Co,{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(se,{htmlFor:"friend_name",className:"text-sm",children:["Their name ",e.jsx("span",{className:"text-red-500",children:"*"})]}),e.jsx(be,{id:"friend_name",value:h,onChange:D=>m(D.target.value),placeholder:"Jane Smith",required:!0,className:"mt-1"})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(se,{htmlFor:"friend_email",className:"text-sm",children:"Email"}),e.jsx(be,{id:"friend_email",type:"email",value:p,onChange:D=>x(D.target.value),placeholder:"jane@email.com",className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx(se,{htmlFor:"friend_phone",className:"text-sm",children:"Phone"}),e.jsx(be,{id:"friend_phone",type:"tel",value:g,onChange:D=>y(D.target.value),placeholder:"(555) 123-4567",className:"mt-1"})]})]}),e.jsx("p",{className:"text-[11px] text-slate-400",children:"Add at least an email or phone so we can reach them."}),e.jsxs("div",{children:[e.jsx(se,{className:"text-sm",children:"They're interested in..."}),e.jsx("div",{className:"mt-2 grid grid-cols-2 gap-2",children:[{v:"buying",l:"Buying"},{v:"selling",l:"Selling"},{v:"both",l:"Both"},{v:"unsure",l:"Not sure"}].map(D=>e.jsx("button",{type:"button",onClick:()=>v(D.v),className:`rounded-lg border px-3 py-2 text-sm font-medium transition-colors ${b===D.v?"bg-[#406E71] text-white border-[#406E71]":"bg-white text-slate-600 border-slate-200 hover:border-slate-300"}`,children:D.l},D.v))})]}),e.jsxs("div",{children:[e.jsx(se,{htmlFor:"friend_message",className:"text-sm",children:"A note (optional)"}),e.jsx("textarea",{id:"friend_message",value:N,onChange:D=>C(D.target.value),placeholder:"They're moving from Boston in the spring...",rows:3,className:"mt-1 w-full rounded-md border border-input bg-background px-3 py-2 text-sm focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"})]})]})]}),e.jsxs("div",{className:"border-t pt-4",children:[e.jsx("p",{className:"text-xs font-semibold uppercase tracking-wide text-slate-500 mb-3",children:"Your info"}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx(se,{htmlFor:"referrer_name",className:"text-sm",children:"Your name"}),e.jsx(be,{id:"referrer_name",value:o,onChange:D=>c(D.target.value),placeholder:A.client_name||"Your name",className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx(se,{htmlFor:"referrer_email",className:"text-sm",children:"Your email"}),e.jsx(be,{id:"referrer_email",type:"email",value:d,onChange:D=>u(D.target.value),placeholder:"So we can thank you!",className:"mt-1"})]})]})]}),e.jsxs("button",{type:"submit",disabled:r,className:"w-full bg-[#406E71] hover:bg-[#345e7a] disabled:opacity-60 text-white font-semibold rounded-xl py-3.5 px-4 flex items-center justify-center gap-2 transition-colors",children:[r?e.jsx(Ht,{className:"w-4 h-4 animate-spin"}):e.jsx(Co,{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 m5s(){const t=Wd().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(GTt,{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(HTt,{slug:t})}function p5s(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 sSe({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(()=>p5s(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(sa,{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 WTt({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(Os,{open:t,onOpenChange:u=>{u||n()},children:e.jsxs(Rs,{className:"max-w-4xl max-h-[90vh] overflow-y-auto p-0",children:[e.jsxs(Us,{className:"px-6 pt-6 pb-2",children:[e.jsx(zs,{className:"text-xl",children:s.address}),e.jsxs("div",{className:"text-sm text-muted-foreground flex items-center gap-1",children:[e.jsx(ai,{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(sSe,{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(sSe,{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(sa,{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(qd,{className:"w-6 h-6 text-muted-foreground"}),(l||0).toLocaleString()]}),o&&e.jsxs("div",{className:"text-xs text-muted-foreground",children:["$",o,"/sqft"]})]}),e.jsxs("div",{className:"flex flex-col items-end gap-1",children:[e.jsx($e,{variant:"outline",children:s.status}),s.daysOnMarket!=null&&e.jsxs("span",{className:"text-xs text-muted-foreground",children:[s.daysOnMarket," DOM"]})]})]}),(s.listDate||s.statusChangeDate||s.soldDate)&&e.jsxs("div",{className:"px-6 pt-4",children:[e.jsx("div",{className:"text-xs font-semibold uppercase tracking-wide text-muted-foreground mb-2",children:"Timeline"}),e.jsxs("div",{className:"grid grid-cols-3 gap-2",children:[e.jsx(mPe,{label:"Active",date:c(s.listDate),active:!0}),e.jsx(mPe,{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(mPe,{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(Mne,{icon:e.jsx(tw,{className:"w-4 h-4"}),label:"Beds",value:s.bedrooms??"—"}),e.jsx(Mne,{icon:e.jsx(_g,{className:"w-4 h-4"}),label:"Baths",value:s.bathrooms??"—"}),e.jsx(Mne,{icon:e.jsx(o5,{className:"w-4 h-4"}),label:"SqFt",value:((d=s.sqft)==null?void 0:d.toLocaleString())??"—"}),e.jsx(Mne,{icon:e.jsx(ia,{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(Uv,{label:"MLS #",value:s.mlsNumber}),e.jsx(Uv,{label:"Property Type",value:s.propertySubType||s.propertyType}),e.jsx(Uv,{label:"Lot Size",value:s.lotSize}),e.jsx(Uv,{label:"Garage",value:s.garageSpaces}),e.jsx(Uv,{label:"Stories",value:s.stories}),e.jsx(Uv,{label:"HOA",value:s.hoaFee?`$${s.hoaFee}/${(s.hoaFrequency||"mo").toLowerCase()}`:null}),e.jsx(Uv,{label:"Tax (annual)",value:s.taxAmount?`$${s.taxAmount.toLocaleString()}`:null}),e.jsx(Uv,{label:"Heating",value:s.heating}),e.jsx(Uv,{label:"Cooling",value:s.cooling}),e.jsx(Uv,{label:"Parking",value:s.parking}),e.jsx(Uv,{label:"Elementary",value:s.elementarySchool}),e.jsx(Uv,{label:"Middle",value:s.middleSchool}),e.jsx(Uv,{label:"High",value:s.highSchool}),e.jsx(Uv,{label:"Listed By",value:s.listAgentFullName}),e.jsx(Uv,{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 Mne({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 Uv({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 mPe({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 Lne({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=x=>{d||(d=x);const g=x-d,y=Math.min(1,g/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 f5s({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:x,closing:g,net:y}=j.useMemo(()=>{const N=Math.round(l*u/100),C=Math.round(l*m/100);return{commission:N,closing:C,net:Math.max(0,l-N-C-(c||0))}},[l,u,m,c]),b=N=>`$${N.toLocaleString()}`,v=n>s?(l-s)/(n-s)*100:50;return e.jsxs(_e,{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(Il,{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(Oe,{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:b(l)})]}),e.jsxs("div",{className:"relative",children:[e.jsx(rx,{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:b(s)}),e.jsxs("span",{children:["Suggested ",b(t)]}),e.jsx("span",{children:b(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,v))}%`}})})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-3 gap-3",children:[e.jsxs("div",{children:[e.jsx(se,{className:"text-xs",children:"Mortgage payoff"}),e.jsx(be,{type:"number",inputMode:"numeric",value:c||"",placeholder:"$0",onChange:N=>d(Number(N.target.value)||0)})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-xs",children:"Commission %"}),e.jsx(be,{type:"number",step:"0.25",value:u,onChange:N=>h(Number(N.target.value)||0)})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-xs",children:"Closing costs %"}),e.jsx(be,{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:b(l)}),e.jsxs("span",{className:"text-muted-foreground",children:["Commission (",u,"%)"]}),e.jsxs("span",{className:"text-right tabular-nums text-rose-600",children:["−",b(x)]}),e.jsxs("span",{className:"text-muted-foreground",children:["Closing (",m,"%)"]}),e.jsxs("span",{className:"text-right tabular-nums text-rose-600",children:["−",b(g)]}),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:["−",b(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(aY,{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:b(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 KTt({tokenOverride:s}={}){var De,ze,ke,Xe,Se,Re,Ae,Be,qe,Ke,Ze,Ue;const t=Vi(),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,x]=j.useState(""),[g,y]=j.useState(""),[b,v]=j.useState(!1),[N,C]=j.useState(!1),[A,T]=j.useState(null),[P,M]=j.useState(null),[I,D]=j.useState(!1),{toast:B}=gi();j.useEffect(()=>{n&&(async()=>{const{data:et}=await U.from("cmas").select("*").eq("share_token",n).eq("status","shared").maybeSingle();if(!et){u(!1);return}a(et);const[{data:Qe},{data:Ge}]=await Promise.all([U.from("cma_comps").select("*").eq("cma_id",et.id).order("position"),U.from("profiles").select("id,name,email,phone,avatar_url,brokerage_name,website_url,title,bio").eq("id",et.agent_id).maybeSingle()]);c((Qe||[]).filter(ft=>ft.selected)),l(Ge);const nt=localStorage.getItem("cma_visitor_token")||crypto.randomUUID();localStorage.setItem("cma_visitor_token",nt),await U.from("cma_views").insert({cma_id:et.id,visitor_token:nt,user_agent:navigator.userAgent}),u(!1)})()},[n]);const q=async et=>{if(!r)return;const Qe=localStorage.getItem("cma_visitor_token")||"";await U.from("cma_views").insert({cma_id:r.id,visitor_token:Qe,reactions:{[et]:!0}}),U.functions.invoke("cma-reply-notify",{body:{shareToken:n,reaction:et,visitorToken:Qe}}).catch(()=>{}),B({title:"Thanks — your agent just got notified ✨"})},W=!(r!=null&&r.contact_id),V=async()=>{if(!r||!h.trim())return;if(W&&(!p.trim()||!g.trim())){B({title:"Please add your name and email",variant:"destructive"});return}v(!0);const et=localStorage.getItem("cma_visitor_token")||"",{data:Qe,error:Ge}=await U.functions.invoke("cma-reply-notify",{body:{shareToken:n,message:h,visitorToken:et,viewerName:p.trim()||void 0,viewerEmail:g.trim()||void 0}});if(v(!1),Ge||!(Qe!=null&&Qe.success)){B({title:"Could not send",description:(Ge==null?void 0:Ge.message)||(Qe==null?void 0:Qe.error),variant:"destructive"});return}m(""),C(!0),B({title:"Message sent to your agent"})},K=j.useMemo(()=>{const et=o.map(Qe=>{const Ge=Qe.snapshot,nt=(Ge==null?void 0:Ge.soldPrice)||(Ge==null?void 0:Ge.price);return nt&&(Ge!=null&&Ge.sqft)?nt/Ge.sqft:null}).filter(Qe=>!!Qe).sort((Qe,Ge)=>Qe-Ge);return et.length?Math.round(et[Math.floor(et.length/2)]):null},[o]);if(d)return e.jsx("div",{className:"min-h-screen flex items-center justify-center",children:e.jsx(Ht,{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(sa,{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 Q=r.subject||{},J=(De=r.settings)==null?void 0:De.personalVideo,ce=(ze=Q.photos)==null?void 0:ze[0],ue=r.contact_first_name?r.contact_first_name:null,ne=((i==null?void 0:i.name)||"A").split(" ").map(et=>et[0]).slice(0,2).join("").toUpperCase(),ee=i!=null&&i.phone?`tel:${String(i.phone).replace(/[^\d+]/g,"")}`:null,le=i!=null&&i.email?`mailto:${i.email}`:null,he=i!=null&&i.phone?`sms:${String(i.phone).replace(/[^\d+]/g,"")}`:null,ve=r.price_low??null,ge=r.price_likely??null,fe=r.price_high??null,je=ve&&ge&&fe,Ee=ge&&Q.sqft?Math.round(ge/Q.sqft):null,Me=Ee&&K?Math.round((Ee-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:ne}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"font-semibold leading-tight truncate text-sm",children:i.name}),(i.title||i.brokerage_name)&&e.jsxs("div",{className:"text-[11px] text-muted-foreground flex items-center gap-1 truncate",children:[i.brokerage_name&&e.jsx(Ai,{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:[ee&&e.jsx($,{variant:"outline",size:"sm",asChild:!0,children:e.jsxs("a",{href:ee,children:[e.jsx(ya,{className:"w-4 h-4 mr-1"}),"Call"]})}),le&&e.jsx($,{variant:"outline",size:"sm",asChild:!0,children:e.jsxs("a",{href:le,children:[e.jsx(nn,{className:"w-4 h-4 mr-1"}),"Email"]})})]})]})}),e.jsxs("div",{className:"relative overflow-hidden",children:[ce?e.jsxs("div",{className:"absolute inset-0",children:[e.jsx("img",{src:ce,alt:Q.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:`${J!=null&&J.url?"md:col-span-3":"md:col-span-5"} text-white animate-fade-in`,children:[e.jsxs($e,{className:"mb-4 bg-white/15 text-white border-white/20 backdrop-blur-sm hover:bg-white/20",children:[e.jsx(dn,{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:Q.address}),e.jsxs("p",{className:"text-white/70 mt-2 text-base md:text-lg flex items-center gap-2",children:[e.jsx(ai,{className:"w-4 h-4"}),Q.city,", ",Q.state," ",Q.zip]}),je&&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(Lne,{to:ge,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(Lne,{to:ve,prefix:"$",delayMs:500})})]}),e.jsx("div",{className:"h-8 w-px bg-white/20"}),e.jsxs("div",{children:[e.jsx("span",{className:"block text-[11px] uppercase tracking-wider text-white/50",children:"Likely"}),e.jsx("span",{className:"tabular-nums font-medium",children:e.jsx(Lne,{to:ge,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(Lne,{to:fe,prefix:"$",delayMs:800})})]})]})]})]}),(J==null?void 0:J.url)&&e.jsx("div",{className:"md:col-span-2 animate-scale-in",children:e.jsxs("button",{onClick:()=>D(!0),className:"group relative w-full aspect-[4/5] md:aspect-[4/5] rounded-2xl overflow-hidden shadow-2xl ring-1 ring-white/20 bg-black",children:[J.thumb?e.jsx("img",{src:J.thumb,alt:"",className:"w-full h-full object-cover"}):e.jsx("video",{src:J.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(Td,{className:"w-7 h-7 md:w-8 md:h-8 ml-1",fill:"currentColor"})}),e.jsxs("p",{className:"mt-4 text-sm font-medium tracking-wide",children:["A message from ",((ke=i==null?void 0:i.name)==null?void 0:ke.split(" ")[0])||"your agent"]})]})]})})]})})]}),I&&(J==null?void 0:J.url)&&e.jsx("div",{className:"fixed inset-0 z-50 bg-black/90 flex items-center justify-center p-4 animate-fade-in",onClick:()=>D(!1),children:e.jsxs("div",{className:"relative w-full max-w-4xl",onClick:et=>et.stopPropagation(),children:[e.jsx("video",{src:J.url,controls:!0,autoPlay:!0,className:"w-full rounded-xl"}),e.jsx($,{variant:"ghost",className:"absolute -top-12 right-0 text-white hover:bg-white/10",onClick:()=>D(!1),children:"Close"})]})}),e.jsxs("div",{className:"container mx-auto max-w-6xl px-4 md:px-8 py-10 md:py-16 space-y-10 md:space-y-14",children:[e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-3 md:gap-4 -mt-20 md:-mt-24 relative z-10",children:[{label:"Beds",value:Q.bedrooms??"—"},{label:"Baths",value:Q.bathrooms??"—"},{label:"Sq Ft",value:((Xe=Q.sqft)==null?void 0:Xe.toLocaleString())??"—"},{label:"Year Built",value:Q.yearBuilt??"—"}].map((et,Qe)=>e.jsx(_e,{className:"shadow-lg animate-fade-in",style:{animationDelay:`${Qe*80}ms`},children:e.jsxs(Oe,{className:"p-4 md:p-6 text-center",children:[e.jsx("div",{className:"text-2xl md:text-3xl font-bold",children:et.value}),e.jsx("div",{className:"text-xs text-muted-foreground mt-1 uppercase tracking-wider",children:et.label})]})},Qe))}),((Re=(Se=r.settings)==null?void 0:Se.priceOverride)==null?void 0:Re.enabled)&&((Be=(Ae=r.settings)==null?void 0:Ae.priceOverride)==null?void 0:Be.note)&&e.jsx(_e,{className:"border-primary/30 bg-gradient-to-br from-primary/5 to-transparent",children:e.jsxs(Oe,{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})]})}),je&&e.jsx(f5s,{low:ve,likely:ge,high:fe}),K&&Ee&&e.jsxs("div",{className:"grid md:grid-cols-3 gap-4",children:[e.jsx(_e,{className:"md:col-span-2",children:e.jsxs(Oe,{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 ",Q.city,", the median sale rate is ",e.jsxs("strong",{className:"text-foreground",children:["$",K,"/sqft"]}),". Applied to your home's ",(qe=Q.sqft)==null?void 0:qe.toLocaleString()," sqft, the comps support a value near ",e.jsxs("strong",{className:"text-foreground",children:["$",(K*(Q.sqft||0)).toLocaleString()]}),". Your agent's suggested price reflects local nuance and condition."]})]})}),e.jsx(_e,{className:"bg-gradient-to-br from-primary/10 to-primary/5 border-primary/20",children:e.jsxs(Oe,{className:"p-6 md:p-8 h-full flex flex-col justify-center",children:[e.jsx("p",{className:"text-xs uppercase tracking-widest text-muted-foreground mb-1",children:"Your home"}),e.jsxs("div",{className:"text-3xl font-bold tabular-nums",children:["$",Ee,e.jsx("span",{className:"text-base font-normal text-muted-foreground",children:"/sqft"})]}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-3",children:["Neighborhood avg: ",e.jsxs("span",{className:"font-medium text-foreground",children:["$",K,"/sqft"]})]}),Me!==null&&Me!==0&&e.jsxs("p",{className:`text-sm font-medium mt-1 ${Me>0?"text-emerald-600":"text-rose-600"}`,children:[Me>0?"▲":"▼"," ",Math.abs(Me),"% ",Me>0?"above":"below"," the median"]})]})})]}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-baseline justify-between mb-4",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-xs uppercase tracking-widest text-primary font-semibold",children:"Homes like yours"}),e.jsx("h2",{className:"text-2xl md:text-3xl font-bold",children:"The Comparables"})]}),e.jsxs($e,{variant:"outline",className:"text-xs",children:[o.length," comps"]})]}),e.jsx("div",{className:"grid md:grid-cols-2 lg:grid-cols-3 gap-4",children:o.map((et,Qe)=>{var ft;const Ge=et.snapshot,nt=Ge.soldPrice||Ge.price;return e.jsxs(_e,{className:`overflow-hidden cursor-pointer transition-all duration-300 hover:shadow-xl hover:-translate-y-1 animate-fade-in ${P===Qe?"ring-2 ring-primary":""}`,style:{animationDelay:`${Qe*60}ms`},onClick:()=>T(Qe),onMouseEnter:()=>M(Qe),onMouseLeave:()=>M(null),children:[e.jsxs("div",{className:"relative",children:[e.jsx(sSe,{photos:Ge.photos,className:"w-full h-44"}),e.jsxs($e,{className:"absolute top-2 left-2 bg-black/70 text-white border-0 backdrop-blur-sm",children:["#",Qe+1]}),e.jsx($e,{variant:"outline",className:"absolute top-2 right-2 bg-white/95 border-0",children:Ge.status})]}),e.jsxs(Oe,{className:"p-4",children:[e.jsx("div",{className:"font-semibold leading-tight truncate",children:Ge.address}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:[Ge.city,", ",Ge.state]}),e.jsx("div",{className:"flex justify-between items-center mt-3 text-sm",children:e.jsxs("span",{className:"text-muted-foreground",children:[Ge.bedrooms??"?","bd · ",Ge.bathrooms??"?","ba · ",((ft=Ge.sqft)==null?void 0:ft.toLocaleString())??"?"," sqft"]})}),e.jsxs("div",{className:"flex justify-between items-center mt-3 pt-3 border-t",children:[e.jsxs("span",{className:"text-xl font-bold tabular-nums",children:["$",nt==null?void 0:nt.toLocaleString()]}),Ge.sqft&&nt?e.jsxs("span",{className:"text-xs text-muted-foreground tabular-nums",children:["$",Math.round(nt/Ge.sqft),"/sqft"]}):null]})]})]},Qe)})})]}),e.jsx(WTt,{comp:A!==null?(Ke=o[A])==null?void 0:Ke.snapshot:null,open:A!==null,onClose:()=>T(null)}),e.jsx(_e,{className:"border-primary/20 bg-gradient-to-br from-primary/5 via-background to-background overflow-hidden",children:e.jsxs(Oe,{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:fo,label:"I love this price"},{kind:"fair",icon:Ox,label:"Seems fair"},{kind:"lower",icon:FN,label:"I'd price lower"},{kind:"higher",icon:Il,label:"I'd price higher"},{kind:"ready_to_list",icon:IN,label:"Ready to list"},{kind:"want_walkthrough",icon:ga,label:"Want a walkthrough"},{kind:"need_time",icon:ia,label:"Need more time"},{kind:"have_questions",icon:Z4,label:"I have questions"}].map(({kind:et,icon:Qe,label:Ge})=>e.jsxs($,{variant:"outline",className:"bg-card hover:bg-primary hover:text-primary-foreground hover:scale-105 transition-all",onClick:()=>q(et),children:[e.jsx(Qe,{className:"w-4 h-4 mr-2"}),Ge]},et))}),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(Ed,{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:[W&&e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-2 mb-2",children:[e.jsx("input",{className:"border rounded-md p-2 text-sm bg-background",placeholder:"Your name",value:p,onChange:et=>x(et.target.value)}),e.jsx("input",{type:"email",className:"border rounded-md p-2 text-sm bg-background",placeholder:"Your email",value:g,onChange:et=>y(et.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:et=>m(et.target.value)}),e.jsx($,{onClick:V,disabled:!h.trim()||b,className:"mt-2",children:b?"Sending…":"Send to agent"})]})]})]})}),i&&e.jsx(_e,{className:"overflow-hidden border-primary/20",children:e.jsx("div",{className:"bg-gradient-to-br from-primary/10 to-primary/5 p-6 md:p-10",children:e.jsxs("div",{className:"flex flex-col md:flex-row gap-6 items-start",children:[i.avatar_url?e.jsx("img",{src:i.avatar_url,alt:i.name,className:"w-24 h-24 md:w-32 md:h-32 rounded-2xl object-cover ring-4 ring-background shadow-lg"}):e.jsx("div",{className:"w-24 h-24 md:w-32 md:h-32 rounded-2xl bg-primary/20 flex items-center justify-center text-3xl font-bold text-primary ring-4 ring-background shadow-lg",children:ne}),e.jsxs("div",{className:"flex-1",children:[e.jsx("p",{className:"text-xs uppercase tracking-widest text-muted-foreground",children:"Prepared by"}),e.jsx("h2",{className:"text-2xl md:text-3xl font-bold mt-1",children:i.name}),(i.title||i.brokerage_name)&&e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:[i.title,i.brokerage_name].filter(Boolean).join(" · ")}),i.bio&&e.jsx("p",{className:"text-sm text-muted-foreground mt-3 leading-relaxed",children:i.bio}),e.jsxs("div",{className:"flex flex-wrap gap-2 mt-4",children:[ee&&e.jsx($,{asChild:!0,children:e.jsxs("a",{href:ee,children:[e.jsx(ya,{className:"w-4 h-4 mr-2"}),i.phone]})}),le&&e.jsx($,{variant:"outline",asChild:!0,children:e.jsxs("a",{href:le,children:[e.jsx(nn,{className:"w-4 h-4 mr-2"}),"Email"]})}),i.website_url&&e.jsx($,{variant:"outline",asChild:!0,children:e.jsxs("a",{href:i.website_url,target:"_blank",rel:"noreferrer",children:[e.jsx(Gl,{className:"w-4 h-4 mr-2"}),"Website"]})})]})]})]})})})]}),i&&(ee||he||le)&&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:[ee&&e.jsx($,{className:"flex-1",asChild:!0,children:e.jsxs("a",{href:ee,children:[e.jsx(ya,{className:"w-4 h-4 mr-1.5"}),"Call"]})}),he&&e.jsx($,{variant:"outline",className:"flex-1",asChild:!0,children:e.jsxs("a",{href:he,children:[e.jsx(Ed,{className:"w-4 h-4 mr-1.5"}),"Text"]})}),le&&e.jsx($,{variant:"outline",className:"flex-1",asChild:!0,children:e.jsxs("a",{href:le,children:[e.jsx(nn,{className:"w-4 h-4 mr-1.5"}),"Email"]})})]})]})}function x5s(){const t=Wd().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(KTt,{tokenOverride:t})}const u7e="levelup_affiliate_ref",g5s=30,y5s=()=>{const[s]=oc();j.useEffect(()=>{const t=s.get("ref");if(t){const n={code:t.toUpperCase(),timestamp:Date.now()};localStorage.setItem(u7e,JSON.stringify(n)),console.log("[Affiliate] Stored referral code:",t)}},[s])},v5s=()=>{try{const s=localStorage.getItem(u7e);if(!s)return null;const t=JSON.parse(s),n=g5s*24*60*60*1e3;return Date.now()-t.timestamp>n?(localStorage.removeItem(u7e),console.log("[Affiliate] Referral code expired"),null):t.code}catch{return null}},nSe="/assets/levelup-logo-header-_ZX7DvlA.png",b5s="/assets/scale-your-team-ku4MPatU.png";function _5s({open:s,onOpenChange:t}){return e.jsx(Os,{open:s,onOpenChange:t,children:e.jsxs(Rs,{className:"max-w-3xl max-h-[90vh] overflow-hidden",children:[e.jsx(Us,{children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-2 bg-[#4a6b6d]/10 rounded-lg",children:e.jsx(Ai,{className:"h-5 w-5 text-[#4a6b6d]"})}),e.jsxs("div",{children:[e.jsx(zs,{children:"Schedule a Brokerage Interest Meeting"}),e.jsx(Sr,{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 Qg={individual_agent:{name:"Individual Agent",price:"$39",period:"/month",description:"Perfect for independent agents ready to level up",features:["Full dashboard access","300+ professional templates","Academy training library","Community & networking","Live events & workshops","Social media content","Newsletter resources","Email support"],trial:"7-day free trial",popular:!1},brokerage_under_25:{name:"Brokerage",subtitle:"Under 25 Agents",price:"$299",period:"/month",description:"Empower your entire team to succeed",features:["Everything in Individual","Brokerage manager dashboard","Invite & manage up to 25 agents","Exclusive brokerage resources","Team performance analytics","Agent onboarding tools","Resource sharing","Priority support"],popular:!0},brokerage_over_25:{name:"Brokerage",subtitle:"Over 25 Agents",price:"$499",period:"/month",description:"Scale your brokerage without limits",features:["Everything in Brokerage","Unlimited agents","Advanced team analytics","Dedicated account manager","Custom onboarding sessions","White-glove support"],popular:!1}},w5s=[{icon:Sh,title:"Academy Training",description:"Access a library of on-demand video training covering lead generation, marketing, technology, and more."},{icon:Rc,title:"300+ Templates",description:"Professional Canva templates for social media, flyers, postcards, and marketing materials."},{icon:ia,title:"Live Events",description:"Weekly live training sessions, workshops, and Q&A events with industry experts."},{icon:Ed,title:"Agent Community",description:"Connect with fellow agents, share wins, ask questions, and network in our private community."},{icon:Wr,title:"Resource Kits",description:"Downloadable toolkits with scripts, checklists, guides, and everything you need to close more deals."},{icon:Co,title:"Social Swag",description:"Fresh social media content and designs updated regularly to help you stand out online."}],j5s=[{icon:qn,title:"Contact Management",description:"Organize your sphere into relationship tiers—Top 25, Past Clients, Referral Partners, and more."},{icon:dn,title:"Smart Touchpoint Plans",description:"Automated action plans that tell you exactly who to contact and how, based on relationship type."},{icon:ya,title:"One-Tap Actions",description:"Call, text, or email contacts directly with pre-written scripts tailored to each relationship."},{icon:np,title:"Birthday & Anniversary Alerts",description:"Never miss an important date—get reminders for birthdays and home anniversaries."},{icon:ai,title:"Pop-by Map",description:"See all your contacts on a map and plan efficient pop-by routes in your area."},{icon:ml,title:"Momentum Tracking",description:"Track your touch streaks, weekly goals, and relationship health scores."},{icon:fo,title:"Relationship Health",description:"Visual dashboard showing which contacts need attention based on last touch date."},{icon:ox,title:"Daily Action Cards",description:"Wake up to a prioritized list of exactly who to reach out to today."}],N5s=[{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."}],k5s=()=>{const{user:s,loading:t}=_s(),n=Vn(),[r]=oc();j.useEffect(()=>{const P=window.location.host==="listings.relevelup.com",M=window.location.pathname==="/";if(P&&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(""),[x,g]=j.useState(""),[y,b]=j.useState(!1),[v,N]=j.useState(!1),C=(P,M=!1)=>{o({tier:P,skipTrial:M}),d(!0)};y5s(),j.useEffect(()=>{const P=window.location.host==="listings.relevelup.com",M=location.pathname.startsWith("/public/");!t&&s&&!P&&!M&&n("/dashboard")},[s,t,n,location.pathname]),j.useEffect(()=>{r.get("canceled")==="true"&&ae.error("Checkout was canceled. Feel free to try again when you're ready!")},[r]);const A=async(P,M=!1)=>{if(!u){ae.error("Please enter your email address");return}if(!m.trim()){ae.error("Please enter your full name");return}b(!0),i(P+(M?"_direct":""));const I=v5s();try{const{data:D,error:B}=await U.functions.invoke("create-checkout",{body:{tier:P,email:u,name:m.trim(),couponCode:x.trim()||void 0,skipTrial:M,referralCode:I}});if(B)throw B;if(D!=null&&D.url)window.open(D.url,"_blank","noopener,noreferrer"),ae.success("Checkout opened in a new tab");else throw new Error("No checkout URL returned")}catch(D){console.error("Checkout error:",D),ae.error(D.message||"Failed to start checkout. Please try again.")}finally{b(!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:nSe,alt:"LevelUp",className:"h-8 md:h-10"})}),e.jsxs("div",{className:"flex items-center gap-2 md:gap-4",children:[e.jsx($,{variant:"ghost",className:"text-white/90 hover:text-white hover:bg-white/10 hidden sm:inline-flex",onClick:()=>{var P;return(P=document.getElementById("features"))==null?void 0:P.scrollIntoView({behavior:"smooth"})},children:"Features"}),e.jsx($,{variant:"ghost",className:"text-white/90 hover:text-white hover:bg-white/10 hidden sm:inline-flex",onClick:()=>{var P;return(P=document.getElementById("pricing"))==null?void 0:P.scrollIntoView({behavior:"smooth"})},children:"Pricing"}),e.jsx($,{onClick:()=>n("/auth"),className:"bg-white text-[#4a6b6d] hover:bg-gray-100 font-medium shadow-md",children:"Sign In"})]})]})}),e.jsxs("section",{className:"relative pt-24 pb-20 bg-gradient-to-br from-[#1e3a4c] via-[#2a4f5f] to-[#3d6b6b] overflow-hidden",children:[e.jsx("div",{className:"absolute inset-0 opacity-10",children:e.jsx("div",{className:"absolute inset-0 bg-[url('data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iNjAiIGhlaWdodD0iNjAiIHZpZXdCb3g9IjAgMCA2MCA2MCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj48ZyBmaWxsPSJub25lIiBmaWxsLXJ1bGU9ImV2ZW5vZGQiPjxnIGZpbGw9IiNmZmZmZmYiIGZpbGwtb3BhY2l0eT0iMC40Ij48cGF0aCBkPSJNMzYgMzRoLTJ2LTRoMnY0em0wLTZ2LTRoLTJ2NGgyem0tNiA2aC0ydi00aDJ2NHptMC02di00aC0ydjRoMnoiLz48L2c+PC9nPjwvc3ZnPg==')]"})}),e.jsx("div",{className:"container mx-auto px-4 relative",children:e.jsxs("div",{className:"max-w-5xl mx-auto text-center space-y-8",children:[e.jsx("div",{className:"flex justify-center mb-8",children:e.jsx("img",{alt:"LevelUp Consulting Group",className:"h-[136px] md:h-[164px] drop-shadow-lg",src:"/lovable-uploads/3a0c7ef9-9e79-411f-a9af-6f2a99e8bd7b.webp"})}),e.jsxs("p",{className:"text-lg text-white/80 max-w-3xl mx-auto leading-relaxed font-sans font-bold md:text-4xl",children:["The tools you need to get it done.",e.jsx("br",{}),e.jsx("em",{children:"The platform you need to keep it going."})]}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-4 justify-center items-center pt-4",children:[e.jsxs($,{size:"lg",onClick:()=>{var P;return(P=document.getElementById("free-trial"))==null?void 0:P.scrollIntoView({behavior:"smooth"})},className:"px-8 py-7 text-lg font-semibold bg-white text-[#1e3a4c] hover:bg-white/90 shadow-2xl transition-all hover:scale-105 group rounded-full",children:["Start Your Free Trial",e.jsx(ni,{className:"ml-2 w-5 h-5 group-hover:translate-x-1 transition-transform"})]}),e.jsx($,{size:"lg",variant:"outline",onClick:()=>{var P;return(P=document.getElementById("features"))==null?void 0:P.scrollIntoView({behavior:"smooth"})},className:"px-8 py-7 text-lg font-semibold border-2 border-white text-white bg-transparent hover:bg-white hover:text-[#1e3a4c] rounded-full",children:"See What's Included"})]})]})})]}),e.jsx("section",{className:"py-20 bg-background",children:e.jsx("div",{className:"container mx-auto px-4",children:e.jsxs("div",{className:"max-w-4xl mx-auto text-center space-y-8",children:[e.jsx("h2",{className:"text-3xl md:text-5xl leading-tight font-sans font-semibold text-secondary",children:"We help brokerages and agents grow with training, tools, and built-in execution."}),e.jsxs("div",{className:"space-y-2 text-lg text-muted-foreground",children:[e.jsx("p",{children:"Agents get weekly coaching + plug-and-play marketing."}),e.jsx("p",{children:"Brokerages get higher adoption, consistency, and real engagement."})]}),e.jsx("p",{className:"text-2xl md:text-4xl text-[#4a6b6d] pt-4 font-sans font-bold",children:"LEVELUP EQUIPS BOTH TO THRIVE."}),e.jsx("p",{className:"text-lg text-muted-foreground",children:"Learn how we support agents and empower brokerages to grow—together."}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-4 justify-center pt-4",children:[e.jsxs($,{size:"lg",variant:"outline",onClick:()=>{var P;return(P=document.getElementById("brokerage"))==null?void 0:P.scrollIntoView({behavior:"smooth"})},className:"border-[#4a6b6d] text-[#4a6b6d] hover:bg-[#4a6b6d]/5",children:[e.jsx(Ai,{className:"mr-2 h-5 w-5"}),"Brokerage Partnership"]}),e.jsxs($,{size:"lg",onClick:()=>{var P;return(P=document.getElementById("pricing"))==null?void 0:P.scrollIntoView({behavior:"smooth"})},className:"bg-[#4a6b6d] hover:bg-[#3d5a5c]",children:[e.jsx(Lo,{className:"mr-2 h-5 w-5"}),"Individual Membership"]})]})]})})}),e.jsx("section",{id:"features",className:"py-20 bg-muted/30",children:e.jsxs("div",{className:"container mx-auto px-4",children:[e.jsxs("div",{className:"text-center max-w-3xl mx-auto mb-16",children:[e.jsx("h2",{className:"text-3xl md:text-4xl mb-6 font-sans font-bold",children:"What's inside our members only portal?"}),e.jsx("p",{className:"text-lg text-muted-foreground",children:"Everything you need to grow your business, all in one place."})]}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-8 max-w-6xl mx-auto",children:w5s.map((P,M)=>e.jsxs(_e,{className:"group relative overflow-hidden border hover:border-[#4a6b6d]/50 transition-all duration-300 hover:shadow-lg bg-background",children:[e.jsxs(Bt,{children:[e.jsx("div",{className:"w-14 h-14 rounded-2xl bg-[#4a6b6d]/10 flex items-center justify-center mb-4",children:e.jsx(P.icon,{className:"w-7 h-7 text-[#4a6b6d]"})}),e.jsx(Ut,{className:"text-xl font-sans",children:P.title})]}),e.jsx(Oe,{children:e.jsx("p",{className:"text-muted-foreground leading-relaxed",children:P.description})})]},M))})]})}),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(dn,{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:j5s.map((P,M)=>e.jsxs(_e,{className:"group relative overflow-hidden border-0 bg-white/10 backdrop-blur-sm hover:bg-white/20 transition-all duration-300",children:[e.jsxs(Bt,{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(P.icon,{className:"w-6 h-6 text-white"})}),e.jsx(Ut,{className:"text-lg font-semibold text-white",children:P.title})]}),e.jsx(Oe,{children:e.jsx("p",{className:"text-white/70 text-sm leading-relaxed",children:P.description})})]},M))}),e.jsx("div",{className:"text-center mt-12",children:e.jsxs($,{size:"lg",onClick:()=>{var P;return(P=document.getElementById("pricing"))==null?void 0:P.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(ni,{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(Ai,{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((P,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(oa,{className:"w-4 h-4 text-[#4a6b6d]"})}),e.jsx("span",{className:"text-foreground",children:P})]},M))}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-3 mt-4",children:[e.jsxs($,{size:"lg",onClick:()=>{var P;return(P=document.getElementById("pricing"))==null?void 0:P.scrollIntoView({behavior:"smooth"})},className:"bg-[#4a6b6d] hover:bg-[#3d5a5c]",children:["See Brokerage Plans",e.jsx(Ja,{className:"ml-2 w-5 h-5"})]}),e.jsxs($,{size:"lg",variant:"outline",onClick:()=>N(!0),className:"border-[#4a6b6d] text-[#4a6b6d] hover:bg-[#4a6b6d]/10",children:[e.jsx(ia,{className:"mr-2 w-5 h-5"}),"Schedule Info Session"]})]})]}),e.jsx("div",{className:"relative hidden md:block",children:e.jsx("img",{src:b5s,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:N5s.map((P,M)=>e.jsx(_e,{className:"bg-muted/30 border-0",children:e.jsxs(Oe,{className:"pt-8",children:[e.jsx("div",{className:"flex gap-1 mb-4",children:[1,2,3,4,5].map(I=>e.jsx(Qa,{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:['"',P.quote,'"']}),e.jsxs("div",{children:[e.jsx("p",{className:"font-semibold",children:P.name}),e.jsx("p",{className:"text-sm text-muted-foreground",children:P.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($,{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:()=>C("individual_agent"),children:["Start Free Trial",e.jsx(ni,{className:"ml-2 w-5 h-5 group-hover:translate-x-1 transition-transform"})]})})]})})]}),e.jsx("section",{id:"pricing",className:"py-20 bg-muted/30",children:e.jsxs("div",{className:"container mx-auto px-4",children:[e.jsxs("div",{className:"text-center mb-16",children:[e.jsxs("h2",{className:"text-3xl mb-6 font-sans md:text-5xl font-bold",children:["Simple, Transparent ",e.jsx("span",{className:"italic text-[#4a6b6d]",children:"Pricing"})]}),e.jsx("p",{className:"text-lg text-muted-foreground max-w-2xl mx-auto",children:"Choose the plan that fits your needs. All plans include everything you need to succeed."})]}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-3 gap-8 max-w-6xl mx-auto",children:[e.jsxs(_e,{className:"relative flex flex-col border hover:border-[#4a6b6d]/50 transition-all hover:shadow-xl bg-background",children:[e.jsxs(Bt,{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(Lo,{className:"w-5 h-5 text-[#4a6b6d]"})}),e.jsx(Ut,{className:"text-xl font-sans",children:Qg.individual_agent.name})]}),e.jsxs("div",{className:"flex items-baseline gap-1 mt-4",children:[e.jsx("span",{className:"text-5xl font-bold",children:Qg.individual_agent.price}),e.jsx("span",{className:"text-muted-foreground text-lg",children:Qg.individual_agent.period})]}),e.jsx(vr,{className:"text-base mt-2",children:Qg.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(Hr,{className:"w-4 h-4"}),Qg.individual_agent.trial]})]}),e.jsx(Oe,{className:"flex-1 pt-0",children:e.jsx("ul",{className:"space-y-3",children:Qg.individual_agent.features.map((P,M)=>e.jsxs("li",{className:"flex items-center gap-3",children:[e.jsx(oa,{className:"w-5 h-5 text-[#4a6b6d] flex-shrink-0"}),e.jsx("span",{children:P})]},M))})}),e.jsxs(uY,{className:"flex flex-col gap-3 pt-4",children:[e.jsx($,{className:"w-full py-6 text-lg bg-[#4a6b6d] hover:bg-[#3d5a5c]",onClick:()=>C("individual_agent"),children:"Start Free Trial"}),e.jsx($,{variant:"outline",className:"w-full rounded-full border-2 border-[#4a6b6d] text-[#4a6b6d] bg-white hover:bg-[#4a6b6d]/5 uppercase text-sm font-medium tracking-wide",onClick:()=>C("individual_agent",!0),children:"Skip Trial, Subscribe Now"})]})]}),e.jsxs(_e,{className:"relative flex flex-col border-2 border-[#4a6b6d] shadow-2xl scale-105 bg-background",children:[e.jsx("div",{className:"absolute -top-4 left-1/2 -translate-x-1/2 px-6 py-2 bg-[#4a6b6d] text-white text-sm font-semibold rounded-full shadow-lg",children:"Most Popular"}),e.jsxs(Bt,{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(Ai,{className:"w-5 h-5 text-[#4a6b6d]"})}),e.jsxs("div",{children:[e.jsx(Ut,{className:"text-xl font-sans",children:Qg.brokerage_under_25.name}),e.jsx("span",{className:"text-sm text-muted-foreground",children:Qg.brokerage_under_25.subtitle})]})]}),e.jsxs("div",{className:"flex items-baseline gap-1 mt-4",children:[e.jsx("span",{className:"text-5xl font-bold",children:Qg.brokerage_under_25.price}),e.jsx("span",{className:"text-muted-foreground text-lg",children:Qg.brokerage_under_25.period})]}),e.jsx(vr,{className:"text-base mt-2",children:Qg.brokerage_under_25.description})]}),e.jsx(Oe,{className:"flex-1 pt-0",children:e.jsx("ul",{className:"space-y-3",children:Qg.brokerage_under_25.features.map((P,M)=>e.jsxs("li",{className:"flex items-center gap-3",children:[e.jsx(oa,{className:"w-5 h-5 text-[#4a6b6d] flex-shrink-0"}),e.jsx("span",{children:P})]},M))})}),e.jsx(uY,{className:"pt-4",children:e.jsx($,{className:"w-full py-6 text-lg shadow-lg bg-[#4a6b6d] hover:bg-[#3d5a5c]",onClick:()=>C("brokerage_under_25"),children:"Get Started"})})]}),e.jsxs(_e,{className:"relative flex flex-col border hover:border-[#4a6b6d]/50 transition-all hover:shadow-xl bg-background",children:[e.jsxs(Bt,{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(Ai,{className:"w-5 h-5 text-[#4a6b6d]"})}),e.jsxs("div",{children:[e.jsx(Ut,{className:"text-xl font-sans",children:Qg.brokerage_over_25.name}),e.jsx("span",{className:"text-sm text-muted-foreground",children:Qg.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:Qg.brokerage_over_25.price}),e.jsx("span",{className:"text-muted-foreground text-lg",children:Qg.brokerage_over_25.period})]}),e.jsx(vr,{className:"text-base mt-2",children:Qg.brokerage_over_25.description})]}),e.jsx(Oe,{className:"flex-1 pt-0",children:e.jsx("ul",{className:"space-y-3",children:Qg.brokerage_over_25.features.map((P,M)=>e.jsxs("li",{className:"flex items-center gap-3",children:[e.jsx(oa,{className:"w-5 h-5 text-[#4a6b6d] flex-shrink-0"}),e.jsx("span",{children:P})]},M))})}),e.jsx(uY,{className:"pt-4",children:e.jsx($,{className:"w-full py-6 text-lg bg-[#4a6b6d] hover:bg-[#3d5a5c]",onClick:()=>C("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(kf,{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(_e,{className:"border-[#4a6b6d]/20 bg-[#4a6b6d]/[0.03]",children:e.jsxs(Oe,{className:"p-6 flex items-start gap-4",children:[e.jsx("div",{className:"w-10 h-10 rounded-lg bg-[#4a6b6d]/10 flex items-center justify-center shrink-0",children:e.jsx(Ai,{className:"w-5 h-5 text-[#4a6b6d]"})}),e.jsx("p",{className:"text-foreground font-medium leading-relaxed",children:"LevelUp serves all brokerages."})]})}),e.jsx(_e,{className:"border-[#4a6b6d]/20 bg-[#4a6b6d]/[0.03]",children:e.jsxs(Oe,{className:"p-6 flex items-start gap-4",children:[e.jsx("div",{className:"w-10 h-10 rounded-lg bg-[#4a6b6d]/10 flex items-center justify-center shrink-0",children:e.jsx(Ad,{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(_e,{className:"border-[#4a6b6d]/20 bg-[#4a6b6d]/[0.03]",children:e.jsxs(Oe,{className:"p-6 flex items-start gap-4",children:[e.jsx("div",{className:"w-10 h-10 rounded-lg bg-[#4a6b6d]/10 flex items-center justify-center shrink-0",children:e.jsx(Yj,{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(_e,{className:"border-[#4a6b6d]/20 bg-[#4a6b6d]/[0.03]",children:e.jsxs(Oe,{className:"p-6 flex items-start gap-4",children:[e.jsx("div",{className:"w-10 h-10 rounded-lg bg-[#4a6b6d]/10 flex items-center justify-center shrink-0",children:e.jsx(Wr,{className:"w-5 h-5 text-[#4a6b6d]"})}),e.jsx("p",{className:"text-foreground font-medium leading-relaxed",children:"LevelUp does not use LevelUp events, trainings, webinars, CRM data, or member lists for recruiting purposes."})]})})]})]})})}),e.jsxs("section",{className:"py-20 bg-gradient-to-br from-[#1e3a4c] via-[#2a4f5f] to-[#3d6b6b] relative overflow-hidden",children:[e.jsx("div",{className:"absolute inset-0 opacity-10",children:e.jsx("div",{className:"absolute inset-0 bg-[url('data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iNjAiIGhlaWdodD0iNjAiIHZpZXdCb3g9IjAgMCA2MCA2MCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj48ZyBmaWxsPSJub25lIiBmaWxsLXJ1bGU9ImV2ZW5vZGQiPjxnIGZpbGw9IiNmZmZmZmYiIGZpbGwtb3BhY2l0eT0iMC40Ij48cGF0aCBkPSJNMzYgMzRoLTJ2LTRoMnY0em0wLTZ2LTRoLTJ2NGgyem0tNiA2aC0ydi00aDJ2NHptMC02di00aC0ydjRoMnoiLz48L2c+PC9nPjwvc3ZnPg==')]"})}),e.jsx("div",{className:"container mx-auto px-4 relative",children:e.jsxs("div",{className:"max-w-4xl mx-auto text-center space-y-8",children:[e.jsx("h2",{className:"text-3xl text-white font-sans md:text-5xl",children:"Ready to Level Up?"}),e.jsx("p",{className:"text-lg text-white/80 max-w-2xl mx-auto",children:"Join thousands of agents who are closing more deals, saving time, and growing their business with LevelUp."}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-4 justify-center",children:[e.jsxs($,{size:"lg",onClick:()=>{var P;return(P=document.getElementById("pricing"))==null?void 0:P.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(ni,{className:"ml-2 w-5 h-5"})]}),e.jsx($,{size:"lg",onClick:()=>n("/auth"),className:"px-10 py-7 text-lg font-semibold border-2 border-white text-white bg-transparent hover:bg-white hover:text-[#4a6b6d]",children:"Sign In"})]})]})})]}),e.jsx("footer",{className:"py-12 bg-[#3d5a5c] text-white/80",children:e.jsx("div",{className:"container mx-auto px-4",children:e.jsxs("div",{className:"flex flex-col md:flex-row items-center justify-between gap-4",children:[e.jsx("img",{src:nSe,alt:"LevelUp",className:"h-8"}),e.jsxs("p",{className:"text-sm",children:["© ",new Date().getFullYear()," LevelUp. All rights reserved."]}),e.jsxs("div",{className:"flex items-center gap-6",children:[e.jsx("a",{href:"/privacy-policy",className:"text-white/60 hover:text-white transition-colors text-sm",children:"Privacy Policy"}),e.jsx("a",{href:"mailto:support@relevelup.com",className:"text-white/60 hover:text-white transition-colors text-sm",children:"Contact Support"})]})]})})}),e.jsx(_5s,{open:v,onOpenChange:N}),e.jsx(Os,{open:c,onOpenChange:d,children:e.jsxs(Rs,{className:"sm:max-w-md",children:[e.jsxs(Us,{children:[e.jsx(zs,{className:"text-xl font-sans font-semibold",children:"Enter your details to get started"}),e.jsx(Sr,{children:(l==null?void 0:l.tier)==="individual_agent"&&!(l!=null&&l.skipTrial)?"Start your 7-day free trial":(l==null?void 0:l.tier)==="individual_agent"?"Subscribe to Individual Agent":(l==null?void 0:l.tier)==="brokerage_under_25"?"Subscribe to Brokerage (Under 25 Agents)":"Subscribe to Brokerage (Over 25 Agents)"})]}),e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{children:[e.jsxs(se,{htmlFor:"dialog-name",children:["Full Name ",e.jsx("span",{className:"text-red-500",children:"*"})]}),e.jsx(be,{id:"dialog-name",type:"text",placeholder:"John Smith",value:m,onChange:P=>p(P.target.value),className:"mt-1",required:!0})]}),e.jsxs("div",{children:[e.jsxs(se,{htmlFor:"dialog-email",children:["Email Address ",e.jsx("span",{className:"text-red-500",children:"*"})]}),e.jsx(be,{id:"dialog-email",type:"email",placeholder:"you@example.com",value:u,onChange:P=>h(P.target.value),className:"mt-1",required:!0})]}),e.jsxs("div",{children:[e.jsxs(se,{htmlFor:"dialog-coupon",children:["Discount Code ",e.jsx("span",{className:"text-muted-foreground",children:"(Optional)"})]}),e.jsx(be,{id:"dialog-coupon",type:"text",placeholder:"Enter discount code",value:x,onChange:P=>g(P.target.value),className:"mt-1"})]})]}),e.jsx($,{className:"w-full py-6 text-lg bg-[#4a6b6d] hover:bg-[#3d5a5c]",onClick:T,disabled:y,children:y?"Loading...":"Continue to Checkout"})]})})]})},Dot=()=>e.jsxs(e.Fragment,{children:[e.jsxs(Ul,{children:[e.jsx("title",{children:"Privacy Policy | LevelUp"}),e.jsx("meta",{name:"description",content:"Privacy Policy for LevelUp platform"})]}),e.jsx("div",{className:"min-h-screen bg-background py-12 px-4 sm:px-6 lg:px-8",children:e.jsxs("div",{className:"max-w-3xl mx-auto",children:[e.jsx("h1",{className:"text-3xl font-bold text-foreground mb-8",children:"Privacy Policy"}),e.jsxs("div",{className:"prose prose-sm max-w-none text-muted-foreground space-y-6",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Last updated: January 17, 2026"}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"1. Introduction"}),e.jsx("p",{children:'Welcome to LevelUp ("we," "our," or "us"). We are committed to protecting your personal information and your right to privacy. This Privacy Policy explains how we collect, use, disclose, and safeguard your information when you use our platform.'})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"2. Information We Collect"}),e.jsx("p",{children:"We collect information that you provide directly to us, including:"}),e.jsxs("ul",{className:"list-disc pl-6 mt-2 space-y-1",children:[e.jsx("li",{children:"Name and contact information (email address, phone number)"}),e.jsx("li",{children:"Account credentials"}),e.jsx("li",{children:"Profile information"}),e.jsx("li",{children:"Transaction and billing information"}),e.jsx("li",{children:"Communications you send to us"})]})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"3. How We Use Your Information"}),e.jsx("p",{children:"We use the information we collect to:"}),e.jsxs("ul",{className:"list-disc pl-6 mt-2 space-y-1",children:[e.jsx("li",{children:"Provide, maintain, and improve our services"}),e.jsx("li",{children:"Process transactions and send related information"}),e.jsx("li",{children:"Send you technical notices and support messages"}),e.jsx("li",{children:"Respond to your comments and questions"}),e.jsx("li",{children:"Communicate with you about products, services, and events"})]})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"4. Information Sharing"}),e.jsx("p",{children:"We do not sell, trade, or otherwise transfer your personal information to third parties without your consent, except as described in this policy or as required by law."})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"5. Data Security"}),e.jsx("p",{children:"We implement appropriate technical and organizational measures to protect the security of your personal information. However, no method of transmission over the Internet is 100% secure."})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"6. Your Rights"}),e.jsx("p",{children:"You have the right to:"}),e.jsxs("ul",{className:"list-disc pl-6 mt-2 space-y-1",children:[e.jsx("li",{children:"Access your personal information"}),e.jsx("li",{children:"Correct inaccurate data"}),e.jsx("li",{children:"Request deletion of your data"}),e.jsx("li",{children:"Opt-out of marketing communications"})]})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"7. SMS / Text Messaging Program & Mobile Information"}),e.jsx("p",{children:"Your privacy is important to us. This section outlines how we collect, use, and protect your information when you use our services, including our SMS/text messaging program."}),e.jsxs("p",{className:"mt-3",children:[e.jsx("strong",{className:"text-foreground",children:"Information We Collect:"})," We collect personal information you provide, including your name, email address, phone number, and mobile number when you opt in to receive text messages from us."]}),e.jsxs("p",{className:"mt-3",children:[e.jsx("strong",{className:"text-foreground",children:"How We Use Your Information:"})," If you opt in, we use your mobile number to send SMS account notifications, real-time lead alerts, service updates, and customer support communications related to your LevelUp account."]}),e.jsxs("p",{className:"mt-3",children:[e.jsx("strong",{className:"text-foreground",children:"No Sharing of Mobile Information:"})," No mobile information will be shared with third parties/affiliates for marketing/promotional purposes. All the above categories exclude text messaging originator opt-in data and consent; this information will not be shared with any third parties."]}),e.jsxs("p",{className:"mt-3",children:[e.jsx("strong",{className:"text-foreground",children:"Your Rights:"})," You have the right to access, modify, or delete your personal information at any time. You may opt out of text messages at any time by replying STOP to any message. Reply HELP for help. Message and data rates may apply. Message frequency varies."]}),e.jsxs("p",{className:"mt-3",children:["For questions about this policy, contact us at"," ",e.jsx("a",{href:"mailto:support@relevelup.com",className:"text-primary hover:underline",children:"support@relevelup.com"}),"."]})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"8. Third-Party Services"}),e.jsx("p",{children:"Our platform may integrate with third-party services such as Facebook and Instagram for social media posting features. When you connect these accounts, you are subject to their respective privacy policies."})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"10. SMS Privacy Policy"}),e.jsx("p",{children:"We collect contact information you provide to us, including your name, email address, phone number, and business details, in order to provide our services, respond to inquiries, and deliver requested communications."}),e.jsx("p",{className:"mt-3",children:"If you choose to opt in to SMS communications from LevelUp, we may send you text messages including account notifications, real-time lead alerts, service updates, and customer support communications related to your LevelUp account."}),e.jsx("p",{className:"mt-3",children:"SMS consent is not shared with third parties or affiliates for marketing purposes. Mobile information will not 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 vendors, aggregators, and providers that help us deliver these text messages."}),e.jsx("p",{className:"mt-3",children:"Message frequency may vary depending on your activity and use of our services. Message and data rates may apply."}),e.jsxs("p",{className:"mt-3",children:["You can opt out at any time by replying STOP. For help, reply HELP or contact us at"," ",e.jsx("a",{href:"mailto:hello@relevelup.com",className:"text-primary hover:underline",children:"hello@relevelup.com"}),"."]})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"11. Contact Us"}),e.jsxs("p",{children:["If you have questions about this Privacy Policy, please contact us at"," ",e.jsx("a",{href:"mailto:support@relevelup.com",className:"text-primary hover:underline",children:"support@relevelup.com"})]})]})]})]})})]}),Rot=()=>e.jsxs(e.Fragment,{children:[e.jsxs(Ul,{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"})]})]})]})]})})]}),S5s=()=>e.jsxs(e.Fragment,{children:[e.jsxs(Ul,{children:[e.jsx("title",{children:"Data Deletion | LevelUp"}),e.jsx("meta",{name:"description",content:"Data deletion instructions for LevelUp platform"})]}),e.jsx("div",{className:"min-h-screen bg-background py-12 px-4 sm:px-6 lg:px-8",children:e.jsxs("div",{className:"max-w-3xl mx-auto",children:[e.jsx("h1",{className:"text-3xl font-bold text-foreground mb-8",children:"Data Deletion Instructions"}),e.jsxs("div",{className:"prose prose-sm max-w-none text-muted-foreground space-y-6",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Last updated: January 17, 2026"}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"How to Request Data Deletion"}),e.jsx("p",{children:"If you wish to have your data deleted from LevelUp, you can request deletion through one of the following methods:"})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"Option 1: Email Request"}),e.jsxs("p",{children:["Send an email to"," ",e.jsx("a",{href:"mailto:support@relevelup.com",className:"text-primary hover:underline",children:"support@relevelup.com"})," ",'with the subject line "Data Deletion Request" and include:']}),e.jsxs("ul",{className:"list-disc pl-6 mt-2 space-y-1",children:[e.jsx("li",{children:"Your full name"}),e.jsx("li",{children:"The email address associated with your account"}),e.jsx("li",{children:"A clear statement requesting deletion of your data"})]})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"Option 2: Account Settings"}),e.jsx("p",{children:"If you have an active account, you can request data deletion through your account settings:"}),e.jsxs("ol",{className:"list-decimal pl-6 mt-2 space-y-1",children:[e.jsx("li",{children:"Log in to your LevelUp account"}),e.jsx("li",{children:"Navigate to your Profile settings"}),e.jsx("li",{children:"Contact support through the Support page to request account deletion"})]})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"What Data Will Be Deleted"}),e.jsx("p",{children:"Upon a valid deletion request, we will delete:"}),e.jsxs("ul",{className:"list-disc pl-6 mt-2 space-y-1",children:[e.jsx("li",{children:"Your account information (name, email, profile data)"}),e.jsx("li",{children:"Any content you have created or uploaded"}),e.jsx("li",{children:"Your activity history and preferences"}),e.jsx("li",{children:"Connected social media account tokens and data"})]})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"Data Retention"}),e.jsx("p",{children:"Some data may be retained for legal or legitimate business purposes, such as:"}),e.jsxs("ul",{className:"list-disc pl-6 mt-2 space-y-1",children:[e.jsx("li",{children:"Transaction records required for financial reporting"}),e.jsx("li",{children:"Data necessary to comply with legal obligations"}),e.jsx("li",{children:"Anonymized or aggregated data that cannot identify you"})]})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"Facebook/Instagram Data"}),e.jsx("p",{children:"If you have connected your Facebook or Instagram account to LevelUp, you can also manage your data through Facebook's settings:"}),e.jsxs("ol",{className:"list-decimal pl-6 mt-2 space-y-1",children:[e.jsx("li",{children:"Go to your Facebook Settings & Privacy → Settings"}),e.jsx("li",{children:'Click on "Apps and Websites"'}),e.jsx("li",{children:'Find LevelUp and click "Remove"'}),e.jsx("li",{children:"This will revoke our access to your Facebook/Instagram data"})]})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"Processing Time"}),e.jsx("p",{children:"We will process your data deletion request within 30 days of receiving it. You will receive a confirmation email once your data has been deleted."})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"Contact Us"}),e.jsxs("p",{children:["If you have questions about data deletion, please contact us at"," ",e.jsx("a",{href:"mailto:support@relevelup.com",className:"text-primary hover:underline",children:"support@relevelup.com"})]})]})]})]})})]}),Oot="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.",C5s=tk({name:rl().trim().min(1,"Name is required").max(200),phone:rl().trim().min(10,"Enter a valid mobile number").max(30).regex(/^[+\d\s()\-.]+$/,"Enter a valid mobile number"),email:rl().trim().email("Enter a valid email").max(320).optional().or(Sx(""))});function A5s(){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),x=Vn(),g=async y=>{var N;if(y.preventDefault(),!l){ae.error("Please check the consent box to opt in.");return}const b=C5s.safeParse({name:s,phone:n,email:a});if(!b.success){ae.error(((N=b.error.issues[0])==null?void 0:N.message)??"Please check your inputs.");return}d(!0);const{error:v}=await U.from("sms_opt_in_consents").insert({name:b.data.name,phone:b.data.phone,email:b.data.email||null,consent_text:Oot,source:"web_form",user_agent:navigator.userAgent.slice(0,500)});if(d(!1),v){ae.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(Ul,{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(Ji,{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(_e,{className:"p-8 text-center",children:[e.jsx(Fr,{className:"w-14 h-14 text-primary mx-auto mb-4"}),e.jsx("h2",{className:"text-2xl font-semibold mb-2",children:"No text messages — you're all set"}),e.jsx("p",{className:"text-muted-foreground",children:"You declined SMS notifications. No mobile number or consent was recorded, and you can continue using LevelUp normally."}),e.jsx($,{className:"mt-6",onClick:()=>x("/auth"),children:"Continue to LevelUp"})]}):u?e.jsxs(_e,{className:"p-8 text-center",children:[e.jsx(Fr,{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(_e,{className:"p-6 md:p-8",children:e.jsxs("form",{onSubmit:g,className:"space-y-5",children:[e.jsxs("div",{children:[e.jsx(se,{htmlFor:"name",children:"Full Name (only if you opt in to SMS)"}),e.jsx(be,{id:"name",value:s,onChange:y=>t(y.target.value),maxLength:200,autoComplete:"name",className:"mt-1.5"})]}),e.jsxs("div",{children:[e.jsx(se,{htmlFor:"phone",children:"Mobile Number (only if you opt in to SMS)"}),e.jsx(be,{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(se,{htmlFor:"email",children:"Email (optional)"}),e.jsx(be,{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(ui,{id:"consent",checked:l,onCheckedChange:y=>o(y===!0),className:"mt-0.5"}),e.jsx(se,{htmlFor:"consent",className:"text-sm leading-relaxed font-normal cursor-pointer",children:Oot})]})}),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(Wn,{to:"/terms-of-service",className:"text-primary underline underline-offset-2",children:"SMS Terms & Conditions"})," ","and"," ",e.jsx(Wn,{to:"/privacy-policy",className:"text-primary underline underline-offset-2",children:"Privacy Policy"}),"."]}),e.jsxs("p",{children:[e.jsx("strong",{children:"Message types:"})," account notifications, real-time lead alerts, service updates, customer support."," ",e.jsx("strong",{children:"Frequency:"})," varies."," ",e.jsx("strong",{children:"Msg & data rates may apply."})," ","Reply ",e.jsx("strong",{children:"STOP"})," to opt out, ",e.jsx("strong",{children:"HELP"})," for help."]}),e.jsx("p",{children:"No mobile information will be shared with third parties or affiliates for marketing or promotional purposes. Text messaging originator opt-in data and consent will not be shared with any third parties."})]}),e.jsx($,{type:"submit",disabled:!l||c,className:"w-full",size:"lg",children:c?"Submitting…":"Opt in to SMS"}),e.jsx($,{type:"button",variant:"outline",size:"lg",className:"w-full",disabled:c,onClick:()=>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(j0,{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 YTt="/assets/levelup-logo-horizontal-DEFNc0ms.png",E5s=tk({email:rl().email("Invalid email address"),password:rl().min(6,"Password must be at least 6 characters")}),T5s="https://dashboard.relevelup.com",Pne="/oauth-connect",A2e="levelupOAuthRouteHistory";function Fot(s){return s.startsWith("/")&&!s.startsWith("//")&&!s.includes("://")}function M5s(s){const t=Date.now(),n=15e3;try{const i=[...JSON.parse(sessionStorage.getItem(A2e)??"[]").filter(o=>t-o.ato.route));return i.length>=6&&l.has("auth")&&l.has("consent")}catch{return sessionStorage.setItem(A2e,JSON.stringify([{route:s,at:t}])),!1}}function L5s(){sessionStorage.removeItem(A2e)}const P5s=()=>{const{signIn:s,user:t,loading:n}=_s(),r=(t==null?void 0:t.id)??null,a=Vn(),[i]=oc(),l=i.get("authorization_id")??"",o=i.get("next")??"",[c,d]=j.useState(!1),[u,h]=j.useState({}),[m,p]=j.useState(""),[x,g]=j.useState(!1),[y,b]=j.useState(!1),[v,N]=j.useState(null),C=j.useRef(!1);j.useEffect(()=>{if(l&&window.location.hostname==="tile-portal.lovable.app"){const P=new URL("/auth",T5s);P.searchParams.set("next",`${Pne}?authorization_id=${encodeURIComponent(l)}`),window.location.replace(P.toString());return}if(l){const P=`${Pne}?authorization_id=${encodeURIComponent(l)}`;sessionStorage.setItem("redirectAfterLogin",P);return}o&&Fot(o)&&sessionStorage.setItem("redirectAfterLogin",o)},[l,o]),j.useEffect(()=>{if(n||!r||C.current)return;const P=l?`${Pne}?authorization_id=${encodeURIComponent(l)}`:sessionStorage.getItem("redirectAfterLogin")||"/dashboard";if(!Fot(P)){sessionStorage.removeItem("redirectAfterLogin"),C.current=!0,a("/dashboard",{replace:!0});return}const M=P.startsWith(Pne)||P.startsWith("/oauth/consent")||P.startsWith("/.lovable/oauth/consent");if(M&&M5s("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}C.current=!0,M||(L5s(),sessionStorage.removeItem("redirectAfterLogin")),a(P,{replace:!0})},[l,n,a,r]);const A=async P=>{P.preventDefault(),h({}),d(!0);const M=new FormData(P.currentTarget),I=M.get("email"),D=M.get("password");try{E5s.parse({email:I,password:D}),await s(I,D)}catch(B){if(B instanceof Yxs){const q={};B.issues.forEach(W=>{W.path[0]&&(q[W.path[0]]=W.message)}),h(q)}}finally{d(!1)}},T=async()=>{if(!m){ae.error("Please enter your email address");return}g(!0);try{const{error:P}=await U.functions.invoke("send-password-reset",{body:{email:m,redirectTo:"https://dashboard.relevelup.com/profile?reset=true"}});if(P)throw P;ae.success("Password reset email sent! Check your inbox."),b(!1),p("")}catch(P){ae.error(P instanceof Error?P.message:"Failed to send reset email")}finally{g(!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(Wn,{to:"/",className:"inline-flex items-center gap-2 text-sm text-white/80 hover:text-white transition-colors",children:[e.jsx(ka,{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:YTt,alt:"LevelUp",className:"h-12 w-auto"})})}),e.jsxs(_e,{className:"border-0 shadow-2xl bg-white/95 backdrop-blur-sm",children:[e.jsxs(Bt,{className:"space-y-1 text-center pb-4",children:[e.jsx(Ut,{className:"text-3xl font-bold text-[#2a4347]",style:{fontFamily:"'Libre Baskerville', serif"},children:"Welcome Back"}),e.jsx(vr,{className:"text-gray-600",children:v||"Sign in to access your dashboard"})]}),e.jsx(Oe,{children:e.jsxs("form",{onSubmit:A,className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"signin-email",className:"text-gray-700",children:"Email"}),e.jsx(be,{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(se,{htmlFor:"signin-password",className:"text-gray-700",children:"Password"}),e.jsx(be,{id:"signin-password",name:"password",type:"password",required:!0,className:"border-gray-300 focus:border-[#4a6b6d] focus:ring-[#4a6b6d]"}),u.password&&e.jsx("p",{className:"text-sm text-red-600",children:u.password})]}),e.jsx($,{type:"submit",className:"w-full bg-[#4a6b6d] hover:bg-[#3d5a5c] text-white font-semibold py-6 text-lg transition-all duration-200 shadow-lg hover:shadow-xl",disabled:c,children:c?"Signing in...":"Sign In"}),e.jsxs(Os,{open:y,onOpenChange:b,children:[e.jsx(Ko,{asChild:!0,children:e.jsx($,{variant:"link",className:"w-full text-sm text-[#4a6b6d] hover:text-[#3d5a5c]",children:"Forgot password?"})}),e.jsxs(Rs,{className:"bg-white",children:[e.jsxs(Us,{children:[e.jsx(zs,{className:"text-[#2a4347]",style:{fontFamily:"'Libre Baskerville', serif"},children:"Reset Password"}),e.jsx(Sr,{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(se,{htmlFor:"reset-email",className:"text-gray-700",children:"Email"}),e.jsx(be,{id:"reset-email",type:"email",placeholder:"your@email.com",value:m,onChange:P=>p(P.target.value),className:"border-gray-300 focus:border-[#4a6b6d] focus:ring-[#4a6b6d]"})]}),e.jsx($,{onClick:T,className:"w-full bg-[#4a6b6d] hover:bg-[#3d5a5c] text-white",disabled:x,children:x?"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(Wn,{to:"/",className:"text-white hover:underline font-medium",children:"View Plans"})]})]})})]})]})},zot=()=>U.auth.oauth,I5s="https://dashboard.relevelup.com",D5s="/oauth-connect",E2e="levelupOAuthRouteHistory",R5s="https://relzejiswnotikjgvjhz.supabase.co/auth/v1",O5s="eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6InJlbHplamlzd25vdGlramd2amh6Iiwicm9sZSI6ImFub24iLCJpYXQiOjE3NjE5NTAzNDQsImV4cCI6MjA3NzUyNjM0NH0.dzIkIr_oFSbFE3oWS0ktIr83iKHHkZxt40Gc7SpC_mM";function F5s(s){return s.startsWith("/")&&!s.startsWith("//")&&!s.includes("://")}function z5s(s){const t=Date.now(),n=15e3;try{const i=[...JSON.parse(sessionStorage.getItem(E2e)??"[]").filter(o=>t-o.ato.route));return i.length>=6&&l.has("auth")&&l.has("consent")}catch{return sessionStorage.setItem(E2e,JSON.stringify([{route:s,at:t}])),!1}}function B5s(){sessionStorage.removeItem(E2e)}async function Bot(s,t,n){const r=await fetch(`${R5s}${s}`,{...n,headers:{Authorization:`Bearer ${t}`,apikey:O5s,"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 pPe(){var g;const{user:s,session:t,loading:n}=_s(),r=(s==null?void 0:s.id)??null,a=(t==null?void 0:t.access_token)??null,[i]=oc(),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 b=`${D5s}?authorization_id=${encodeURIComponent(l)}`;if(window.location.hostname==="tile-portal.lovable.app"){window.location.href=`${I5s}${b}`;return}if(n)return;if(!r){if(z5s("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}F5s(b)&&sessionStorage.setItem("redirectAfterLogin",b),window.location.replace(`/auth?next=${encodeURIComponent(b)}`);return}if(!a)return;B5s(),sessionStorage.removeItem("redirectAfterLogin");const v=zot(),{data:N,error:C}=v?await v.getAuthorizationDetails(l):await Bot(`/oauth/authorizations/${encodeURIComponent(l)}`,a);if(!y)return;if(C){u(C.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 b=zot(),{data:v,error:N}=b?y?await b.approveAuthorization(l,{skipBrowserRedirect:!0}):await b.denyAuthorization(l,{skipBrowserRedirect:!0}):await Bot(`/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 C=(v==null?void 0:v.redirect_url)??(v==null?void 0:v.redirect_to);if(!C){m(!1),u("No redirect returned by the authorization server.");return}window.location.href=C}if(d)return e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-background p-4",children:e.jsx(_e,{className:"w-full max-w-md",children:e.jsxs(Bt,{children:[e.jsx(Ut,{children:"Authorization error"}),e.jsx(vr,{children:d})]})})});if(!o)return e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-background",children:e.jsx(Ht,{className:"h-8 w-8 animate-spin text-primary"})});const x=((g=o.client)==null?void 0:g.name)??"An app";return e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-background p-4",children:e.jsxs(_e,{className:"w-full max-w-md",children:[e.jsxs(Bt,{children:[e.jsxs(Ut,{children:["Connect ",x," to LevelUp"]}),e.jsxs(vr,{children:[x," is requesting access to use LevelUp tools on your behalf. You can revoke access at any time."]})]}),e.jsxs(Oe,{className:"flex gap-3 justify-end",children:[e.jsx($,{variant:"outline",disabled:h,onClick:()=>p(!1),children:"Deny"}),e.jsx($,{disabled:h,onClick:()=>p(!0),children:h?e.jsx(Ht,{className:"h-4 w-4 animate-spin"}):"Approve"})]})]})})}const $ot="https://relzejiswnotikjgvjhz.supabase.co/functions/v1/mcp",$5s="https://tile-portal.lovable.app/mcp-oauth-bridge.html",U5s=[{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 q5s(){const[s,t]=j.useState(!1),n=async()=>{try{await navigator.clipboard.writeText($ot),t(!0),ae.success("MCP URL copied to clipboard"),setTimeout(()=>t(!1),2e3)}catch{ae.error("Could not copy URL")}};return e.jsx(Ks,{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(t5,{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:"Let ChatGPT use LevelUp tools while you are signed in."})]})]}),e.jsxs(_e,{children:[e.jsxs(Bt,{children:[e.jsx(Ut,{children:"Use this exact MCP server URL"}),e.jsx(vr,{children:"Paste only this URL into ChatGPT's Server URL field."})]}),e.jsx(Oe,{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:$ot}),e.jsx($,{variant:"outline",size:"icon",onClick:n,"aria-label":"Copy MCP URL",children:s?e.jsx(Ro,{className:"h-4 w-4 text-green-600"}):e.jsx(Ca,{className:"h-4 w-4"})})]})})]}),e.jsx(_e,{className:"border-destructive/30 bg-destructive/5",children:e.jsx(Oe,{className:"pt-6",children:e.jsxs("div",{className:"flex gap-3",children:[e.jsx(mc,{className:"h-5 w-5 text-destructive shrink-0 mt-0.5"}),e.jsxs("div",{className:"space-y-2 text-sm",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:$5s}),e.jsx("p",{className:"text-muted-foreground",children:"Delete that plugin attempt and create a new one with the MCP server URL above."})]})]})})}),e.jsxs(_e,{children:[e.jsxs(Bt,{children:[e.jsx(Ut,{children:"Quick steps"}),e.jsx(vr,{children:"ChatGPT adds MCP servers as a new plugin / custom tool. Share these steps with any agent who wants to connect."})]}),e.jsx(Oe,{children:e.jsx("ol",{className:"space-y-4",children:U5s.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("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(Tr,{className:"h-4 w-4"}),e.jsx("span",{children:"Only basic tools are exposed today. More LevelUp actions will be added over time."})]})]})})}const V5s=()=>{const[s]=oc(),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(_e,{className:"max-w-lg w-full",children:[e.jsxs(Bt,{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(Ro,{className:"w-10 h-10 text-green-500"})}),e.jsx(Ut,{className:"text-2xl",children:"Welcome to LevelUp!"}),e.jsx(vr,{className:"text-lg",children:"Your subscription has been activated successfully."})]}),e.jsxs(Oe,{className:"space-y-6",children:[e.jsxs("div",{className:"p-4 rounded-lg bg-primary/10 border border-primary/20 space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2 text-primary",children:[e.jsx(nn,{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."})})]})]})})},H5s=()=>{const{user:s}=_s(),[t,n]=j.useState(!1),[r,a]=j.useState(null),[i,l]=j.useState(""),o=async h=>{var m;if(!(s!=null&&s.email)){ae.error("Please sign in to upgrade");return}n(!0),a(h);try{const{data:p,error:x}=await U.functions.invoke("create-checkout",{body:{tier:h,email:s.email,name:((m=s.user_metadata)==null?void 0:m.full_name)||s.email,couponCode:i.trim()||void 0,skipTrial:!0}});if(x)throw x;if(p!=null&&p.url)window.open(p.url,"_blank","noopener,noreferrer"),ae.success("Checkout opened in a new tab");else throw new Error("No checkout URL returned")}catch(p){console.error("Checkout error:",p),ae.error(p.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","Up to 25 agent seats","Brokerage admin dashboard","Team performance analytics","Custom branding options","Priority support","Agent onboarding tools","Brokerage-wide announcements"],u=["Everything in Brokerage plan","Unlimited agent seats","Dedicated account manager","Advanced analytics & reporting","White-label options","API access","Custom integrations","Enterprise-level support"];return e.jsx(Ks,{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(se,{htmlFor:"coupon",className:"text-sm font-medium",children:"Have a discount code?"}),e.jsx(be,{id:"coupon",placeholder:"Enter discount code",value:i,onChange:h=>l(h.target.value),className:"mt-1"})]}),e.jsxs("div",{className:"grid md:grid-cols-3 gap-6 mb-8",children:[e.jsxs(_e,{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(Bt,{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(qn,{className:"h-7 w-7 text-primary"})}),e.jsx(Ut,{className:"text-xl",children:"Individual Agent"}),e.jsx(vr,{children:"Perfect for solo agents ready to level up"})]}),e.jsxs(Oe,{className:"space-y-6",children:[e.jsxs("div",{className:"text-center",children:[e.jsx("span",{className:"text-4xl font-bold text-primary",children:"$39"}),e.jsx("span",{className:"text-muted-foreground",children:"/month"})]}),e.jsx("ul",{className:"space-y-2",children:c.map((h,m)=>e.jsxs("li",{className:"flex items-start gap-2 text-sm",children:[e.jsx(oa,{className:"h-4 w-4 text-primary mt-0.5 shrink-0"}),e.jsx("span",{children:h})]},m))}),e.jsxs($,{className:"w-full",size:"lg",onClick:()=>o("individual_agent"),disabled:t,children:[t&&r==="individual_agent"?e.jsx(Ht,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(dn,{className:"h-4 w-4 mr-2"}),"Get Started"]})]})]}),e.jsxs(_e,{className:"border-2 border-amber-500/20 hover:border-amber-500/50 transition-colors",children:[e.jsxs(Bt,{className:"text-center pb-2",children:[e.jsx("div",{className:"mx-auto mb-3 h-14 w-14 rounded-full bg-amber-500/10 flex items-center justify-center",children:e.jsx(Ai,{className:"h-7 w-7 text-amber-600"})}),e.jsx(Ut,{className:"text-xl",children:"Brokerage"}),e.jsx(vr,{children:"For teams and brokerages up to 25 agents"})]}),e.jsxs(Oe,{className:"space-y-6",children:[e.jsxs("div",{className:"text-center",children:[e.jsx("span",{className:"text-4xl font-bold text-amber-600",children:"$299"}),e.jsx("span",{className:"text-muted-foreground",children:"/month"})]}),e.jsx("ul",{className:"space-y-2",children:d.map((h,m)=>e.jsxs("li",{className:"flex items-start gap-2 text-sm",children:[e.jsx(oa,{className:"h-4 w-4 text-amber-600 mt-0.5 shrink-0"}),e.jsx("span",{children:h})]},m))}),e.jsxs($,{variant:"outline",className:"w-full border-amber-500 text-amber-600 hover:bg-amber-50",size:"lg",onClick:()=>o("brokerage_under_25"),disabled:t,children:[t&&r==="brokerage_under_25"?e.jsx(Ht,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(Ai,{className:"h-4 w-4 mr-2"}),"Get Started"]})]})]}),e.jsxs(_e,{className:"border-2 border-purple-500/20 hover:border-purple-500/50 transition-colors",children:[e.jsxs(Bt,{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(Ai,{className:"h-7 w-7 text-purple-600"})}),e.jsx(Ut,{className:"text-xl",children:"Brokerage 25+"}),e.jsx(vr,{children:"For larger brokerages with 25+ agents"})]}),e.jsxs(Oe,{className:"space-y-6",children:[e.jsxs("div",{className:"text-center",children:[e.jsx("span",{className:"text-4xl font-bold text-purple-600",children:"$499"}),e.jsx("span",{className:"text-muted-foreground",children:"/month"})]}),e.jsx("ul",{className:"space-y-2",children:u.map((h,m)=>e.jsxs("li",{className:"flex items-start gap-2 text-sm",children:[e.jsx(oa,{className:"h-4 w-4 text-purple-600 mt-0.5 shrink-0"}),e.jsx("span",{children:h})]},m))}),e.jsxs($,{variant:"outline",className:"w-full border-purple-500 text-purple-600 hover:bg-purple-50",size:"lg",onClick:()=>o("brokerage_over_25"),disabled:t,children:[t&&r==="brokerage_over_25"?e.jsx(Ht,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(Ai,{className:"h-4 w-4 mr-2"}),"Get Started"]})]})]})]}),e.jsx(_e,{className:"bg-muted/50",children:e.jsxs(Oe,{className:"py-6",children:[e.jsx("p",{className:"text-center font-medium mb-4",children:"Questions? We're here to help!"}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-4 justify-center",children:[e.jsxs("a",{href:"tel:1-866-527-8668",className:"flex items-center justify-center gap-2 text-primary hover:underline",children:[e.jsx(ya,{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(nn,{className:"h-4 w-4"}),e.jsx("span",{children:"support@relevelup.com"})]})]})]})})]})})},G5s=()=>{const{user:s,loading:t,isBrokerageManager:n,brokerageId:r}=_s(),a=Vn(),[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()){ae.error("Please enter a brokerage name");return}const{data:m}=await U.auth.getSession(),p=m.session;if(!s||!p){ae.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:x,error:g}=await U.functions.invoke("create-brokerage",{body:{name:i.trim()}});if(console.log("[SetupBrokerage] create-brokerage response",{data:x,error:g}),g)throw g;if(!(x!=null&&x.ok))throw new Error((x==null?void 0:x.error)||"Failed to create brokerage");c(!1),u(!0),ae.success("Brokerage created! Setting up your account..."),setTimeout(()=>{a("/profile?setup=true")},2e3)}catch(x){console.error("Error creating brokerage:",x),ae.error(x.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(_e,{className:"max-w-lg w-full",children:[e.jsxs(Bt,{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(Ht,{className:"w-10 h-10 text-primary animate-spin"})}),e.jsx(Ut,{className:"text-2xl",children:"Setting Up Your Brokerage"}),e.jsx(vr,{className:"text-lg",children:"We're assigning you as the brokerage manager and preparing your dashboard..."})]}),e.jsxs(Oe,{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-center gap-2 text-muted-foreground",children:[e.jsx(Ro,{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(Ht,{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(_e,{className:"max-w-lg w-full",children:[e.jsxs(Bt,{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(Ai,{className:"w-10 h-10 text-primary"})}),e.jsx(Ut,{className:"text-2xl",children:"Set Up Your Brokerage"}),e.jsx(vr,{className:"text-lg",children:"Create your brokerage to start managing your team"})]}),e.jsxs(Oe,{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"brokerage-name",children:"Brokerage Name"}),e.jsx(be,{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(qn,{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(Ro,{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(Ro,{className:"w-4 h-4 text-green-500"}),"Access exclusive brokerage resources"]}),e.jsxs("li",{className:"flex items-center gap-2",children:[e.jsx(Ro,{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(Ro,{className:"w-4 h-4 text-green-500"}),"Share resources with your agents"]})]})]}),e.jsxs($,{onClick:h,className:"w-full",disabled:o||!i.trim(),children:[o?"Creating...":"Create Brokerage",e.jsx(ni,{className:"w-4 h-4 ml-2"})]})]})]})})},Uot=()=>{const s=Vn(),[t,n]=j.useState("verifying"),[r,a]=j.useState("");j.useEffect(()=>{(async()=>{try{const{data:{session:o},error:c}=await U.auth.getSession();if(c)throw c;if(o!=null&&o.user){const{data:d}=await U.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 U.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(_e,{className:"w-full max-w-md",children:[e.jsxs(Bt,{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(Ut,{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(vr,{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(Oe,{children:e.jsx($,{onClick:i,className:"w-full",children:"Go to Login"})})]})})},W5s=()=>{const[s,t]=j.useState(!1),n=j.useMemo(()=>new URLSearchParams(window.location.search).get("link"),[]),r=j.useMemo(()=>{if(!n)return!1;try{const i=new URL(n);return i.hostname.endsWith(".supabase.co")&&i.pathname.startsWith("/auth/v1/verify")}catch{return!1}},[n]);j.useEffect(()=>{document.title="Reset Your Password"},[]);const a=()=>{!r||!n||(t(!0),window.location.href=n)};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:YTt,alt:"LevelUp",className:"h-12 w-auto"})})}),e.jsxs(_e,{className:"border-0 shadow-2xl bg-white/95 backdrop-blur-sm",children:[e.jsxs(Bt,{className:"text-center",children:[e.jsx(Ut,{className:"text-2xl font-bold text-[#2a4347]",style:{fontFamily:"'Libre Baskerville', serif"},children:"Reset Your Password"}),e.jsx(vr,{className:"text-gray-600 pt-2",children:r?"Click the button below to continue resetting your password.":"This link is invalid or has expired. Please request a new password reset email."})]}),e.jsxs(Oe,{className:"space-y-4",children:[r?e.jsx($,{onClick:a,disabled:s,className:"w-full bg-[#4a6b6d] hover:bg-[#3d5a5c] text-white font-semibold py-6 text-lg shadow-lg hover:shadow-xl",children:s?"Continuing…":"Continue to Reset Password"}):e.jsx($,{onClick:()=>window.location.href="/auth",className:"w-full bg-[#4a6b6d] hover:bg-[#3d5a5c] text-white font-semibold py-6 text-lg",children:"Go to Sign In"}),e.jsx("p",{className:"text-xs text-center text-gray-500 pt-2",children:"For your security, password reset links expire and can only be used once."})]})]})]})})]})},K5s=()=>{const s=Vn(),[t]=oc(),[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),[x,g]=j.useState(!1),[y,b]=j.useState(!1),[v,N]=j.useState(null),[C,A]=j.useState(null),[T,P]=j.useState(null),[M,I]=j.useState(null);j.useEffect(()=>{const W=t.get("code");W&&(r(W),D(W))},[t]);const D=async W=>{g(!0);const{data:V,error:K}=await U.from("invite_codes").select("id, code, max_uses, uses_count, expires_at, is_active, brokerage_id, trial_days").eq("code",W.toUpperCase().trim()).single();if(K||!V){ae.error("Invalid invite code"),g(!1);return}if(!V.is_active){ae.error("This invite code is no longer active"),g(!1);return}if(V.max_uses&&V.uses_count>=V.max_uses){ae.error("This invite code has reached its maximum uses"),g(!1);return}if(V.expires_at&&new Date(V.expires_at){W.preventDefault(),D(n)},q=async W=>{var V;if(W.preventDefault(),!c.trim()){ae.error("Please enter your name");return}if(l.length<6){ae.error("Password must be at least 6 characters");return}p(!0);try{const K=`${window.location.origin}/`,{data:Q,error:J}=await U.auth.signUp({email:a.trim(),password:l,options:{emailRedirectTo:K,data:{name:c.trim()}}});if(J){J.message.includes("already registered")?ae.error("This email is already registered. Please sign in instead."):ae.error(J.message);return}if(Q.user){await U.rpc("add_default_signup_tag",{user_id:Q.user.id});const ce=n.toUpperCase().trim();C?await U.functions.invoke("assign-brokerage",{body:{userId:Q.user.id,brokerageId:C,inviteCode:ce}}):M?await U.functions.invoke("assign-brokerage",{body:{userId:Q.user.id,trialDays:M,inviteCode:ce}}):await U.functions.invoke("assign-brokerage",{body:{userId:Q.user.id,grandfathered:!0,inviteCode:ce}}),v&&await U.from("invite_codes").update({uses_count:((V=(await U.from("invite_codes").select("uses_count").eq("id",v).single()).data)==null?void 0:V.uses_count)+1}).eq("id",v),ae.success("Account created! You can now access the dashboard."),s("/dashboard")}}catch(K){console.error("Signup error:",K),ae.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(_e,{className:"w-full max-w-md",children:[e.jsxs(Bt,{className:"text-center",children:[e.jsx(Ut,{className:"text-2xl font-bold text-primary",children:T?`Join ${T}`:"Join LevelUp"}),e.jsx(vr,{children:y?T?`Create your account to join ${T}`:"Create your account to get started":"Enter your invite code to continue"})]}),e.jsx(Oe,{children:y?e.jsxs("form",{onSubmit:q,className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"name",children:"Full Name"}),e.jsx(be,{id:"name",type:"text",placeholder:"John Doe",value:c,onChange:W=>d(W.target.value),required:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"email",children:"Email"}),e.jsx(be,{id:"email",type:"email",placeholder:"you@example.com",value:a,onChange:W=>i(W.target.value),required:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"password",children:"Password"}),e.jsxs("div",{className:"relative",children:[e.jsx(be,{id:"password",type:u?"text":"password",placeholder:"••••••••",value:l,onChange:W=>o(W.target.value),required:!0,minLength:6}),e.jsx("button",{type:"button",className:"absolute right-3 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground",onClick:()=>h(!u),children:u?e.jsx(b0,{className:"h-4 w-4"}):e.jsx(ga,{className:"h-4 w-4"})})]})]}),e.jsx($,{type:"submit",className:"w-full",disabled:m,children:m?e.jsxs(e.Fragment,{children:[e.jsx(Ht,{className:"mr-2 h-4 w-4 animate-spin"}),"Creating Account..."]}):"Create Account"})]}):e.jsxs("form",{onSubmit:B,className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"inviteCode",children:"Invite Code"}),e.jsx(be,{id:"inviteCode",type:"text",placeholder:"Enter your invite code",value:n,onChange:W=>r(W.target.value),required:!0,autoFocus:!0})]}),e.jsx($,{type:"submit",className:"w-full",disabled:x,children:x?e.jsxs(e.Fragment,{children:[e.jsx(Ht,{className:"mr-2 h-4 w-4 animate-spin"}),"Verifying..."]}):"Verify Code"})]})})]})})},bee=()=>{const{user:s,isCoach:t}=_s();return ht({queryKey:["my-coach-profile",s==null?void 0:s.id],enabled:!!s&&t,queryFn:async()=>{const{data:n,error:r}=await U.from("coaches").select("*").eq("user_id",s.id).maybeSingle();if(r)throw r;return n}})},Y5s=()=>{const{data:s}=bee();return ht({queryKey:["coach-roster",s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await U.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 U.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}))}})},nGe=()=>{const{user:s}=_s();return ht({queryKey:["my-coaching-assignment",s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await U.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 U.from("coaches").select("*").eq("id",r.coach_id).maybeSingle();let i=null;if(a!=null&&a.user_id){const{data:l}=await U.from("profiles").select("id, name, email, avatar_url").eq("id",a.user_id).maybeSingle();i=l}return{...r,coach:a,coachProfile:i}}})},Z5s=s=>ht({queryKey:["coaching-assignment",s],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await U.from("coaching_assignments").select("*").eq("id",s).maybeSingle();if(n)throw n;if(!t)return null;const{data:r}=await U.from("profiles").select("id, name, email, avatar_url").eq("id",t.agent_id).maybeSingle();return{...t,agent:r}}}),rGe=s=>ht({queryKey:["coaching-sessions",s],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await U.from("coaching_sessions").select("*").eq("assignment_id",s).order("scheduled_at",{ascending:!1});if(n)throw n;return t||[]}}),aGe=s=>ht({queryKey:["coaching-action-items",s],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await U.from("coaching_action_items").select("*").eq("assignment_id",s).order("due_date",{ascending:!0,nullsFirst:!1});if(n)throw n;return t||[]}}),X5s=[{key:"onboarding",label:"Onboarding"},{key:"active",label:"Active"},{key:"thriving",label:"Thriving"},{key:"at_risk",label:"At Risk"},{key:"graduated",label:"Graduated"}];function Q5s(){const s=Vn(),{data:t,isLoading:n}=bee(),{data:r=[],isLoading:a}=Y5s();if(n)return e.jsx(Ks,{title:"Coaching",children:e.jsx("div",{className:"p-8",children:"Loading…"})});if(!t)return e.jsx(Ks,{title:"Coaching",children:e.jsxs("div",{className:"max-w-2xl mx-auto p-8 text-center",children:[e.jsx(Ph,{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."})]})});X5s.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(Ks,{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(dn,{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(fPe,{icon:Ph,label:"Active agents",value:i}),e.jsx(fPe,{icon:Nl,label:"This month",value:"—"}),e.jsx(fPe,{icon:yd,label:"Momentum",value:"🔥"})]})]})]}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-4",children:[e.jsx("h2",{className:"text-xl font-semibold",children:"Your Roster"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx($,{size:"sm",variant:"outline",onClick:()=>s("/coaching/waitlist"),children:"Waitlist"}),e.jsx($,{size:"sm",variant:"outline",onClick:()=>s("/coaching/settings"),children:"Profile Settings"}),e.jsx($,{size:"sm",variant:"outline",onClick:()=>s("/coaching/billing"),children:"Billing & Packages"})]})]}),a?e.jsx("div",{className:"text-muted-foreground",children:"Loading roster…"}):r.length===0?e.jsx(_e,{children:e.jsx(Oe,{className:"p-8 text-center",children:e.jsx("p",{className:"text-muted-foreground",children:"No agents assigned yet. An admin or you can invite agents to get started."})})}):e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-4",children:r.map(l=>{var o,c,d,u;return e.jsx(_e,{className:"cursor-pointer hover:shadow-lg transition-all hover:-translate-y-0.5",onClick:()=>s(`/coaching/agent/${l.id}`),children:e.jsx(Oe,{className:"p-5",children:e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsxs(Ea,{className:"h-14 w-14",children:[e.jsx(ki,{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(ni,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:(u=l.agent)==null?void 0:u.email}),e.jsxs("div",{className:"flex items-center gap-2 mt-3",children:[e.jsx($e,{variant:"secondary",className:"capitalize",children:(l.pipeline_stage||"active").replace("_"," ")}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:["Started ",fc(new Date(l.started_at),{addSuffix:!0})]})]})]})]})})},l.id)})})]})]})})}function fPe({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 ZTt({assignmentId:s}){const{user:t}=_s(),n=ts(),[r,a]=j.useState(""),[i,l]=j.useState(!1),o=j.useRef(null),{data:c=[]}=ht({queryKey:["coaching-messages",s],enabled:!!s,queryFn:async()=>{const{data:u,error:h}=await U.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=U.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()=>{U.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 U.from("coaching_messages").insert({assignment_id:s,sender_id:t.id,body:u});l(!1),h||a("")};return e.jsxs(_e,{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:Tt("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:Tt("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:Tt("text-[10px] mt-1",h?"text-white/70":"text-muted-foreground"),children:fc(new Date(u.created_at),{addSuffix:!0})})]})]},u.id)})}),e.jsx(Oe,{className:"border-t p-3",children:e.jsxs("div",{className:"flex gap-2 items-end",children:[e.jsx(Is,{value:r,onChange:u=>a(u.target.value),onKeyDown:u=>{u.key==="Enter"&&!u.shiftKey&&(u.preventDefault(),d())},placeholder:"Type a message…",rows:1,className:"resize-none min-h-[40px]"}),e.jsx($,{onClick:d,disabled:i||!r.trim(),size:"icon",className:"bg-[#406E71] hover:bg-[#2a4c64]",children:e.jsx(Br,{className:"h-4 w-4"})})]})})]})}var iGe="Progress",oGe=100,[J5s,HXn]=ip(iGe),[e4s,t4s]=J5s(iGe),XTt=j.forwardRef((s,t)=>{const{__scopeProgress:n,value:r=null,max:a,getValueLabel:i=s4s,...l}=s;(a||a===0)&&!qot(a)&&console.error(n4s(`${a}`,"Progress"));const o=qot(a)?a:oGe;r!==null&&!Vot(r,o)&&console.error(r4s(`${r}`,"Progress"));const c=Vot(r,o)?r:null,d=rSe(c)?i(c,o):void 0;return e.jsx(e4s,{scope:n,value:c,max:o,children:e.jsx(Ka.div,{"aria-valuemax":o,"aria-valuemin":0,"aria-valuenow":rSe(c)?c:void 0,"aria-valuetext":d,role:"progressbar","data-state":e6t(c,o),"data-value":c??void 0,"data-max":o,...l,ref:t})})});XTt.displayName=iGe;var QTt="ProgressIndicator",JTt=j.forwardRef((s,t)=>{const{__scopeProgress:n,...r}=s,a=t4s(QTt,n);return e.jsx(Ka.div,{"data-state":e6t(a.value,a.max),"data-value":a.value??void 0,"data-max":a.max,...r,ref:t})});JTt.displayName=QTt;function s4s(s,t){return`${Math.round(s/t*100)}%`}function e6t(s,t){return s==null?"indeterminate":s===t?"complete":"loading"}function rSe(s){return typeof s=="number"}function qot(s){return rSe(s)&&!isNaN(s)&&s>0}function Vot(s,t){return rSe(s)&&!isNaN(s)&&s<=t&&s>=0}function n4s(s,t){return`Invalid prop \`max\` of value \`${s}\` supplied to \`${t}\`. Only numbers greater than 0 are valid max values. Defaulting to \`${oGe}\`.`}function r4s(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 ${oGe} if no \`max\` prop is set) - \`null\` or \`undefined\` if the progress is indeterminate. Defaulting to \`null\`.`}var t6t=XTt,a4s=JTt;const Ki=j.forwardRef(({className:s,value:t,...n},r)=>e.jsx(t6t,{ref:r,className:Tt("relative h-4 w-full overflow-hidden rounded-full bg-secondary",s),...n,children:e.jsx(a4s,{className:"h-full w-full flex-1 bg-primary transition-all",style:{transform:`translateX(-${100-(t||0)}%)`}})}));Ki.displayName=t6t.displayName;function s6t({agentUserId:s}){const t=new Date().getFullYear(),n=`${t}-01-01`,r=`${t}-12-31`,{data:a=[]}=ht({queryKey:["coaching-kpi-txns",s,t],enabled:!!s,queryFn:async()=>{const{data:g,error:y}=await U.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 g||[]}}),{data:i}=ht({queryKey:["coaching-kpi-goal",s,t],enabled:!!s,queryFn:async()=>{const{data:g}=await U.from("scorecard_goals").select("*").eq("owner_user_id",s).eq("year",t).maybeSingle();return g}}),l=a.filter(g=>g.is_win),o=l.length,c=l.reduce((g,y)=>g+(Number(y.sale_price)||0),0),d=l.reduce((g,y)=>g+(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,x=g=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(g);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(Il,{className:"h-5 w-5"})," ",t," KPIs"]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-3",children:[e.jsx(xPe,{icon:pu,label:"Transactions",value:o.toString(),goal:h,current:o,suffix:h?`/ ${h}`:""}),e.jsx(xPe,{icon:Il,label:"Volume",value:x(c),goal:m,current:c,suffix:m?`of ${x(m)}`:""}),e.jsx(xPe,{icon:qd,label:"GCI",value:x(d),goal:p,current:d,suffix:p?`of ${x(p)}`:""})]}),o===0&&e.jsx(_e,{children:e.jsxs(Oe,{className:"p-4 text-sm text-muted-foreground text-center",children:["No transactions logged for ",t," yet."]})})]})}function xPe({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(_e,{children:e.jsxs(Oe,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-2",children:[e.jsx(s,{className:"h-4 w-4"}),e.jsx("span",{className:"text-xs uppercase tracking-wider",children:t})]}),e.jsx("div",{className:"text-2xl font-bold",children:n}),r>0&&e.jsxs("div",{className:"mt-2 space-y-1",children:[e.jsx(Ki,{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 n6t({assignmentId:s,canEdit:t}){const n=ts(),[r,a]=j.useState(!1),[i,l]=j.useState(null),{data:o=[]}=ht({queryKey:["coaching-goals",s],enabled:!!s,queryFn:async()=>{const{data:d,error:u}=await U.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(Mu,{className:"h-5 w-5"})," Goals"]}),t&&e.jsxs($,{size:"sm",onClick:()=>{l(null),a(!0)},children:[e.jsx(sn,{className:"h-4 w-4 mr-1"})," New Goal"]})]}),o.length===0?e.jsx(_e,{children:e.jsx(Oe,{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(_e,{children:e.jsxs(Oe,{className:"p-4",children:[e.jsxs("div",{className:"flex items-start justify-between gap-2",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("h3",{className:"font-semibold",children:d.title}),e.jsx($e,{variant:"outline",className:"capitalize",children:d.status||"active"})]}),d.description&&e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:d.description})]}),t&&e.jsx($,{variant:"ghost",size:"icon",onClick:()=>{l(d),a(!0)},children:e.jsx(Ya,{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(Ki,{value:m})]}),d.due_date&&e.jsxs("p",{className:"text-xs text-muted-foreground mt-2",children:["Due ",Hs(new Date(d.due_date),"PP")]})]})},d.id)}),t&&e.jsx(i4s,{open:r,onOpenChange:a,assignmentId:s,goal:i,onSaved:c})]})}function i4s({open:s,onOpenChange:t,assignmentId:n,goal:r,onSaved:a}){var C,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(((C=r==null?void 0:r.target_value)==null?void 0:C.toString())||""),[p,x]=j.useState(((A=r==null?void 0:r.current_value)==null?void 0:A.toString())||"0"),[g,y]=j.useState((r==null?void 0:r.due_date)||""),[b,v]=j.useState(!1);j.useState(()=>{var T,P;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())||""),x(((P=r==null?void 0:r.current_value)==null?void 0:P.toString())||"0"),y((r==null?void 0:r.due_date)||"")});const N=async()=>{if(!i.trim())return;v(!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:g||null},{error:P}=r!=null&&r.id?await U.from("coaching_goals").update(T).eq("id",r.id):await U.from("coaching_goals").insert(T);if(v(!1),P)return ae.error(P.message);ae.success(r!=null&&r.id?"Goal updated":"Goal created"),a==null||a(),t(!1)};return e.jsx(Os,{open:s,onOpenChange:t,children:e.jsxs(Rs,{children:[e.jsx(Us,{children:e.jsx(zs,{children:r!=null&&r.id?"Edit Goal":"New Goal"})}),e.jsxs("div",{className:"space-y-3",children:[e.jsx(be,{placeholder:"Title",value:i,onChange:T=>l(T.target.value)}),e.jsx(Is,{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(be,{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(be,{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(be,{type:"number",value:p,onChange:T=>x(T.target.value)})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs text-muted-foreground",children:"Due date"}),e.jsx(be,{type:"date",value:g,onChange:T=>y(T.target.value)})]})]}),e.jsxs(kr,{children:[e.jsx($,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsx($,{onClick:N,disabled:b,children:r!=null&&r.id?"Save":"Create"})]})]})})}function r6t({assignmentId:s}){const t=ts(),{user:n}=_s(),r=j.useRef(null),[a,i]=j.useState(!1),{data:l=[]}=ht({queryKey:["coaching-files",s],enabled:!!s,queryFn:async()=>{const{data:h,error:m}=await U.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 x=`${s}/${Date.now()}-${m.name}`,{error:g}=await U.storage.from("coaching-files").upload(x,m);if(g)throw g;const{error:y}=await U.from("coaching_shared_files").insert({assignment_id:s,uploaded_by:n.id,file_url:x,file_name:m.name,file_size_bytes:m.size,mime_type:m.type});if(y)throw y;ae.success("File uploaded"),o()}catch(x){ae.error(x.message||"Upload failed")}finally{i(!1),r.current&&(r.current.value="")}}},d=async h=>{const{data:m,error:p}=await U.storage.from("coaching-files").createSignedUrl(h.file_url,60);if(p||!m)return ae.error("Could not get download link");window.open(m.signedUrl,"_blank")},u=async h=>{await Yi("Delete this file?")&&(await U.storage.from("coaching-files").remove([h.file_url]),await U.from("coaching_shared_files").delete().eq("id",h.id),o())};return e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsx("h2",{className:"text-lg font-semibold",children:"Shared Files"}),e.jsxs($,{size:"sm",onClick:()=>{var h;return(h=r.current)==null?void 0:h.click()},disabled:a,children:[e.jsx(si,{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(_e,{children:e.jsx(Oe,{className:"p-6 text-center text-muted-foreground",children:"No files yet."})}):e.jsx("div",{className:"space-y-2",children:l.map(h=>e.jsx(_e,{children:e.jsxs(Oe,{className:"p-3 flex items-center gap-3",children:[e.jsx("div",{className:"h-10 w-10 rounded-lg bg-muted flex items-center justify-center",children:e.jsx(Wr,{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 · `:"",Hs(new Date(h.created_at),"PP")]})]}),e.jsx($,{variant:"ghost",size:"icon",onClick:()=>d(h),children:e.jsx(di,{className:"h-4 w-4"})}),h.uploaded_by===(n==null?void 0:n.id)&&e.jsx($,{variant:"ghost",size:"icon",onClick:()=>u(h),children:e.jsx(Pn,{className:"h-4 w-4"})})]})},h.id))})]})}function o4s(){var m,p,x,g;const{id:s}=Vi(),t=Vn(),n=ts(),{data:r,isLoading:a}=Z5s(s),{data:i=[]}=rGe(s),{data:l=[]}=aGe(s),[o,c]=j.useState(!1),[d,u]=j.useState(!1);if(a)return e.jsx(Ks,{title:"Coaching",children:e.jsx("div",{className:"p-8",children:"Loading…"})});if(!r)return e.jsx(Ks,{title:"Coaching",children:e.jsx("div",{className:"p-8",children:"Assignment not found."})});const h=r;return e.jsxs(Ks,{title:"Coaching",children:[e.jsxs("div",{className:"p-4 md:p-8 max-w-6xl mx-auto space-y-6",children:[e.jsxs($,{variant:"ghost",size:"sm",onClick:()=>t("/coaching"),children:[e.jsx(ka,{className:"h-4 w-4 mr-2"})," Back to roster"]}),e.jsxs(_e,{className:"overflow-hidden",children:[e.jsx("div",{className:"h-24 bg-gradient-to-br from-[#2a4c64] to-[#406E71]"}),e.jsx(Oe,{className:"pt-0 -mt-12 pb-6",children:e.jsxs("div",{className:"flex flex-col md:flex-row gap-4 md:items-end",children:[e.jsxs(Ea,{className:"h-24 w-24 ring-4 ring-background",children:[e.jsx(ki,{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:((x=h.agent)==null?void 0:x.name)||"Unknown"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:(g=h.agent)==null?void 0:g.email}),e.jsxs("div",{className:"flex items-center gap-2 mt-2",children:[e.jsx($e,{variant:"secondary",className:"capitalize",children:(h.pipeline_stage||"active").replace("_"," ")}),e.jsx($e,{variant:"outline",className:"capitalize",children:h.status})]})]}),e.jsx("div",{className:"flex gap-2",children:e.jsx(c4s,{value:h.pipeline_stage||"active",onChange:async y=>{await U.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(l4s,{assignment:h}),e.jsxs(ua,{defaultValue:"sessions",children:[e.jsxs(ha,{className:"w-full flex flex-wrap justify-start h-auto",children:[e.jsxs(Qt,{value:"sessions",children:[e.jsx(ia,{className:"h-4 w-4 mr-2"}),"Sessions"]}),e.jsxs(Qt,{value:"actions",children:[e.jsx(Jh,{className:"h-4 w-4 mr-2"}),"Actions"]}),e.jsxs(Qt,{value:"goals",children:[e.jsx(Mu,{className:"h-4 w-4 mr-2"}),"Goals"]}),e.jsxs(Qt,{value:"kpis",children:[e.jsx(Il,{className:"h-4 w-4 mr-2"}),"KPIs"]}),e.jsxs(Qt,{value:"messages",children:[e.jsx(Ji,{className:"h-4 w-4 mr-2"}),"Messages"]}),e.jsxs(Qt,{value:"files",children:[e.jsx(cv,{className:"h-4 w-4 mr-2"}),"Files"]}),e.jsxs(Qt,{value:"notes",children:[e.jsx(Wr,{className:"h-4 w-4 mr-2"}),"Private Notes"]})]}),e.jsxs(Jt,{value:"sessions",className:"space-y-4",children:[e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsx("h2",{className:"text-lg font-semibold",children:"Sessions"}),e.jsxs($,{size:"sm",onClick:()=>c(!0),children:[e.jsx(sn,{className:"h-4 w-4 mr-1"})," New Session"]})]}),i.length===0?e.jsx(_e,{children:e.jsx(Oe,{className:"p-6 text-muted-foreground text-center",children:"No sessions yet."})}):e.jsx("div",{className:"space-y-3",children:i.map(y=>e.jsx(_e,{children:e.jsx(Oe,{className:"p-4",children:e.jsx("div",{className:"flex items-start justify-between gap-3",children:e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx("span",{className:"font-medium",children:Hs(new Date(y.scheduled_at),"PPp")}),e.jsx($e,{variant:"outline",className:"capitalize",children:y.status}),y.template&&e.jsx($e,{variant:"secondary",children:y.template}),y.zoom_join_url&&e.jsx("a",{href:y.zoom_join_url,target:"_blank",rel:"noopener noreferrer",className:"text-xs text-primary underline",children:"Join Zoom"})]}),y.agenda&&e.jsxs("p",{className:"text-sm mb-1",children:[e.jsx("span",{className:"text-muted-foreground",children:"Agent's agenda:"})," ",y.agenda]}),y.summary&&e.jsx("p",{className:"text-sm text-muted-foreground whitespace-pre-wrap",children:y.summary}),y.private_notes&&e.jsxs("div",{className:"mt-2 p-2 rounded bg-muted/50 text-xs",children:[e.jsxs("div",{className:"flex items-center gap-1 text-muted-foreground mb-1",children:[e.jsx(Ad,{className:"h-3 w-3"})," Private"]}),e.jsx("p",{className:"whitespace-pre-wrap",children:y.private_notes})]})]})})})},y.id))})]}),e.jsxs(Jt,{value:"actions",className:"space-y-4",children:[e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsx("h2",{className:"text-lg font-semibold",children:"Action Items"}),e.jsxs($,{size:"sm",onClick:()=>u(!0),children:[e.jsx(sn,{className:"h-4 w-4 mr-1"})," Add"]})]}),l.length===0?e.jsx(_e,{children:e.jsx(Oe,{className:"p-6 text-muted-foreground text-center",children:"No action items yet."})}):e.jsx("div",{className:"space-y-2",children:l.map(y=>e.jsx(_e,{children:e.jsxs(Oe,{className:"p-3 flex items-center gap-3",children:[e.jsx(ui,{checked:y.status==="done",onCheckedChange:async b=>{await U.from("coaching_action_items").update({status:b?"done":"open",completed_at:b?new Date().toISOString():null}).eq("id",y.id),n.invalidateQueries({queryKey:["coaching-action-items",h.id]})}}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:y.status==="done"?"line-through text-muted-foreground":"font-medium",children:y.title}),y.description&&e.jsx("div",{className:"text-xs text-muted-foreground",children:y.description})]}),y.due_date&&e.jsx($e,{variant:"outline",children:Hs(new Date(y.due_date),"MMM d")}),e.jsx($e,{variant:"secondary",className:"capitalize",children:y.priority})]})},y.id))})]}),e.jsx(Jt,{value:"goals",children:e.jsx(n6t,{assignmentId:h.id,canEdit:!0})}),e.jsx(Jt,{value:"kpis",children:h.agent_id&&e.jsx(s6t,{agentUserId:h.agent_id})}),e.jsx(Jt,{value:"messages",children:e.jsx(ZTt,{assignmentId:h.id})}),e.jsx(Jt,{value:"files",children:e.jsx(r6t,{assignmentId:h.id})}),e.jsx(Jt,{value:"notes",className:"space-y-4",children:e.jsx(_e,{children:e.jsx(Oe,{className:"p-6 text-muted-foreground",children:"Private notes per session live under the Sessions tab. General-relationship notes coming soon."})})})]})]}),e.jsx(d4s,{open:o,onOpenChange:c,assignmentId:h.id,onSaved:()=>n.invalidateQueries({queryKey:["coaching-sessions",h.id]})}),e.jsx(u4s,{open:d,onOpenChange:u,assignmentId:h.id,onSaved:()=>n.invalidateQueries({queryKey:["coaching-action-items",h.id]})})]})}function l4s({assignment:s}){const t=ts(),[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 U.from("coaching_assignments").update({sessions_per_month:o}).eq("id",s.id);if(i(!1),c)return ae.error(c.message);ae.success("Session allowance updated"),t.invalidateQueries({queryKey:["coaching-assignment",s.id]})};return e.jsx(_e,{children:e.jsxs(Oe,{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(ia,{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(be,{type:"number",min:1,max:31,placeholder:"Default",value:n,onChange:o=>r(o.target.value),className:"w-28"}),e.jsxs($,{size:"sm",variant:"outline",onClick:l,disabled:a,children:[e.jsx(Jo,{className:"h-4 w-4 mr-1"})," Save"]})]})})}function c4s({value:s,onChange:t}){return e.jsxs(vs,{value:s,onValueChange:t,children:[e.jsx(gs,{className:"w-40",children:e.jsx(bs,{})}),e.jsxs(ys,{children:[e.jsx(Ye,{value:"onboarding",children:"Onboarding"}),e.jsx(Ye,{value:"active",children:"Active"}),e.jsx(Ye,{value:"thriving",children:"Thriving"}),e.jsx(Ye,{value:"at_risk",children:"At Risk"}),e.jsx(Ye,{value:"graduated",children:"Graduated"})]})]})}function d4s({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(""),[x,g]=j.useState(!1),[y,b]=j.useState(!0),[v,N]=j.useState(null),[C,A]=j.useState(!1),T=async()=>{A(!0);const{data:M,error:I}=await U.functions.invoke("coaching-prep-brief",{body:{assignmentId:n}});if(A(!1),I||M!=null&&M.error)return ae.error((M==null?void 0:M.error)||(I==null?void 0:I.message)||"Failed to generate brief");N(M.brief||"No brief returned.")},P=async()=>{g(!0);const{data:M,error:I}=await U.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 g(!1),ae.error(I.message);if(ae.success("Session saved"),y&&u.trim()&&(M!=null&&M.id)){const{error:D}=await U.functions.invoke("coaching-send-recap",{body:{sessionId:M.id}});D?ae.error("Saved, but recap email failed: "+D.message):ae.success("Recap emailed to agent")}g(!1),r==null||r(),t(!1),h(""),p(""),N(null)};return e.jsx(Os,{open:s,onOpenChange:t,children:e.jsxs(Rs,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsx(Us,{children:e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx(zs,{children:"New Session"}),e.jsxs($,{size:"sm",variant:"outline",onClick:T,disabled:C,children:[C?e.jsx(Ht,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(dn,{className:"h-4 w-4 mr-1"}),"Pre-session brief"]})]})}),e.jsxs("div",{className:"space-y-3",children:[v&&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(dn,{className:"h-3 w-3"})," AI Brief"]}),v]}),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(be,{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(be,{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(vs,{value:c,onValueChange:d,children:[e.jsx(gs,{children:e.jsx(bs,{})}),e.jsxs(ys,{children:[e.jsx(Ye,{value:"weekly_1on1",children:"Weekly 1:1"}),e.jsx(Ye,{value:"grow",children:"GROW Model"}),e.jsx(Ye,{value:"goal_review",children:"Goal Review"}),e.jsx(Ye,{value:"breakthrough",children:"Breakthrough Session"})]})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium",children:"Summary (agent sees this)"}),e.jsx(Is,{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(Ad,{className:"h-3 w-3"})," Private notes (only you)"]}),e.jsx(Is,{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(ui,{checked:y,onCheckedChange:M=>b(!!M)}),e.jsx(Br,{className:"h-3.5 w-3.5 text-muted-foreground"}),"Email recap to agent on save"]})]}),e.jsxs(kr,{children:[e.jsx($,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsxs($,{onClick:P,disabled:x,children:[e.jsx(Jo,{className:"h-4 w-4 mr-1"})," Save Session"]})]})]})})}function u4s({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),x=async()=>{if(!a.trim())return;p(!0);const{error:g}=await U.from("coaching_action_items").insert({assignment_id:n,title:a,description:l||null,due_date:c||null,priority:u});if(p(!1),g)return ae.error(g.message);ae.success("Action item added"),r==null||r(),t(!1),i(""),o(""),d("")};return e.jsx(Os,{open:s,onOpenChange:t,children:e.jsxs(Rs,{children:[e.jsx(Us,{children:e.jsx(zs,{children:"New Action Item"})}),e.jsxs("div",{className:"space-y-3",children:[e.jsx(be,{placeholder:"Title",value:a,onChange:g=>i(g.target.value)}),e.jsx(Is,{rows:3,placeholder:"Description (optional)",value:l,onChange:g=>o(g.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(be,{type:"date",value:c,onChange:g=>d(g.target.value)})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium",children:"Priority"}),e.jsxs(vs,{value:u,onValueChange:h,children:[e.jsx(gs,{children:e.jsx(bs,{})}),e.jsxs(ys,{children:[e.jsx(Ye,{value:"low",children:"Low"}),e.jsx(Ye,{value:"medium",children:"Medium"}),e.jsx(Ye,{value:"high",children:"High"})]})]})]})]})]}),e.jsxs(kr,{children:[e.jsx($,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsx($,{onClick:x,disabled:m,children:"Add"})]})]})})}function h7e({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(Qa,{style:{width:t,height:t},className:r<=s?"fill-yellow-400 text-yellow-400":"text-muted-foreground/40"})},r))})}function h4s({coachId:s}){const[t,n]=j.useState([]),[r,a]=j.useState(!0);j.useEffect(()=>{(async()=>{const{data:l}=await U.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 U.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(h7e,{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(_e,{children:e.jsx(Oe,{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(ki,{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(h7e,{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 m4s({coachId:s,assignmentId:t}){const{user:n}=_s(),[r,a]=j.useState(null),[i,l]=j.useState(0),[o,c]=j.useState(""),[d,u]=j.useState(""),[h,m]=j.useState(!1);j.useEffect(()=>{n&&(async()=>{const{data:x}=await U.from("coaching_reviews").select("*").eq("coach_id",s).eq("agent_id",n.id).maybeSingle();x&&(a(x),l(x.rating),c(x.title||""),u(x.body||""))})()},[n,s]);const p=async()=>{if(!n)return;if(!i)return ae.error("Pick a rating");m(!0);const x={coach_id:s,agent_id:n.id,assignment_id:t||null,rating:i,title:o||null,body:d||null},{error:g}=r?await U.from("coaching_reviews").update(x).eq("id",r.id):await U.from("coaching_reviews").insert(x);if(m(!1),g)return ae.error(g.message);ae.success("Thanks for your review!"),a({...x,id:r==null?void 0:r.id})};return e.jsx(_e,{children:e.jsxs(Oe,{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(h7e,{value:i,size:28,onChange:l}),e.jsx(be,{placeholder:"Title (optional)",value:o,onChange:x=>c(x.target.value)}),e.jsx(Is,{rows:4,placeholder:"What was your experience like?",value:d,onChange:x=>u(x.target.value)}),e.jsx($,{onClick:p,disabled:h,className:"bg-[#406E71] hover:bg-[#2a4c64]",children:h?"Saving…":r?"Update review":"Submit review"})]})})}const Ine=async s=>{var r,a;const{data:t,error:n}=await U.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},gPe=s=>Hs(s,"yyyy-MM-dd"),Hot=s=>{const[t,n]=s.split(":").map(Number),r=t>=12?"PM":"AM";return`${t%12||12}:${String(n).padStart(2,"0")} ${r}`};function p4s({assignmentId:s,upcoming:t=[]}){const n=ts(),[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:x}=ht({queryKey:["coaching-booking-context",s],queryFn:()=>Ine({action:"context"})});j.useEffect(()=>{var ce;!r&&((ce=p==null?void 0:p.booking_types)!=null&&ce.length)&&a(p.booking_types[0].id)},[p,r]);const g=j.useMemo(()=>new Date,[]),[y,b]=j.useState(()=>Hu(new Date)),v=(p==null?void 0:p.max_advance_days)||30,N=j.useMemo(()=>Bd(ep(g),v-1),[g,v]),C=j.useMemo(()=>{const ce=Hu(y);return ce{const ce=e1(y);return ce>N?N:ce},[y,N]),T=Math.max(0,av(A,C)+1),{data:P={},isFetching:M}=ht({queryKey:["coaching-availability",r,gPe(C),T],enabled:!!r&&T>0,queryFn:async()=>(await Ine({action:"availability",booking_type_id:r,start:gPe(C),days:T})).availability||{}}),I=j.useMemo(()=>{const ce=Hu(y),ue=e1(y).getDate(),ne=ce.getDay(),ee=Array.from({length:ne},()=>null);for(let le=0;leObject.entries(P).filter(([,ce])=>ce.length>0),[P]),B=i?P[i]||[]:[],q=M,W=j.useMemo(()=>{const ce=[{label:"Morning",items:[]},{label:"Afternoon",items:[]},{label:"Evening",items:[]}];for(const ue of B){const ne=Number(ue.split(":")[0]);ne<12?ce[0].items.push(ue):ne<17?ce[1].items.push(ue):ce[2].items.push(ue)}return ce.filter(ue=>ue.items.length>0)},[B]),V=(p==null?void 0:p.booking_types.find(ce=>ce.id===r))||null,K=((p==null?void 0:p.sessions_remaining)??0)<=0,Q=async()=>{if(!(!r||!i||!o)){m(!0);try{await Ine({action:"book",booking_type_id:r,date:i,time:o,agenda:d||null}),ae.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(ce){ae.error(ce.message||"Could not book that session")}finally{m(!1)}}},J=async ce=>{if(await Yi("Cancel this coaching session?"))try{await Ine({action:"cancel",session_id:ce}),ae.success("Session cancelled"),n.invalidateQueries({queryKey:["coaching-booking-context",s]}),n.invalidateQueries({queryKey:["coaching-sessions",s]})}catch(ue){ae.error(ue.message||"Could not cancel")}};return x?e.jsx(_e,{children:e.jsxs(Oe,{className:"p-8 flex items-center justify-center text-muted-foreground gap-2",children:[e.jsx(Ht,{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(_e,{children:e.jsxs(Oe,{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(Nl,{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($e,{variant:"secondary",children:"All booked up"})]})}),t.length>0&&e.jsx(_e,{children:e.jsxs(Oe,{className:"p-4 space-y-3",children:[e.jsx("h3",{className:"font-semibold",children:"Upcoming sessions"}),t.map(ce=>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:Hs(new Date(ce.scheduled_at),"EEE, MMM d · p")}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[ce.duration_minutes||30," minutes"]})]}),ce.zoom_join_url&&e.jsx($,{size:"sm",variant:"outline",asChild:!0,children:e.jsxs("a",{href:ce.zoom_join_url,target:"_blank",rel:"noopener noreferrer",children:[e.jsx(Xr,{className:"h-4 w-4 mr-1"})," Join"]})}),e.jsxs($,{size:"sm",variant:"ghost",onClick:()=>J(ce.id),children:[e.jsx($d,{className:"h-4 w-4 mr-1"})," Cancel"]})]},ce.id))]})}),e.jsx(_e,{children:e.jsxs(Oe,{className:"p-4 md:p-6 space-y-5",children:[e.jsxs("div",{children:[e.jsx(se,{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(ce=>e.jsxs("button",{onClick:()=>{a(ce.id),c(null)},className:`text-left p-3 rounded-lg border transition-colors ${r===ce.id?"border-primary bg-primary/5":"hover:bg-muted/50"}`,children:[e.jsx("div",{className:"font-medium",children:ce.name}),e.jsxs("div",{className:"text-xs text-muted-foreground flex items-center gap-1 mt-1",children:[e.jsx(Hr,{className:"h-3 w-3"})," ",ce.duration_minutes," min"]}),ce.description&&e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:ce.description})]},ce.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(se,{className:"block",children:"Pick a day"}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx($,{size:"icon",variant:"ghost",className:"h-7 w-7",disabled:Cq(y,g),onClick:()=>b(zx(y,-1)),"aria-label":"Previous month",children:e.jsx(Ic,{className:"h-4 w-4"})}),e.jsx("span",{className:"text-sm font-medium w-28 text-center",children:Hs(y,"MMMM yyyy")}),e.jsx($,{size:"icon",variant:"ghost",className:"h-7 w-7",disabled:Hu(zx(y,1))>N,onClick:()=>b(zx(y,1)),"aria-label":"Next month",children:e.jsx(Ja,{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((ce,ue)=>e.jsx("div",{className:"text-[11px] text-muted-foreground text-center py-1",children:ce},ue))}),e.jsx("div",{className:"grid grid-cols-7 gap-1",children:I.map((ce,ue)=>{if(!ce)return e.jsx("div",{},`b${ue}`);const ne=gPe(ce),ee=(P[ne]||[]).length,he=ce>=ep(g)&&ce<=N&&ee>0,ve=i===ne;return e.jsxs("button",{disabled:!he,onClick:()=>{l(ne),c(null)},className:`aspect-square rounded-lg border text-sm flex flex-col items-center justify-center gap-1 transition-colors ${ve?"border-primary bg-primary text-primary-foreground":he?"border-primary/30 bg-primary/5 hover:bg-primary/10 font-medium":"border-transparent text-muted-foreground/50 cursor-not-allowed"}`,title:he?`${ee} opening${ee===1?"":"s"}`:"No openings",children:[e.jsx("span",{className:"leading-none",children:Hs(ce,"d")}),e.jsx("span",{className:`h-1.5 w-1.5 rounded-full ${ve?"bg-primary-foreground":he?"bg-primary":"bg-transparent"}`})]},ne)})}),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(Ht,{className:"h-3 w-3 animate-spin"})," Loading your coach's openings…"]}):e.jsxs(e.Fragment,{children:[e.jsx(dn,{className:"h-3 w-3 text-primary"}),D.length===0?"No openings this month — try the next month.":`${D.length} day${D.length===1?"":"s"} with openings this month`]})})]}),e.jsxs("div",{children:[e.jsx(se,{className:"mb-2 block",children:i?`Available times · ${Hs(new Date(`${i}T12:00:00`),"EEE, MMM d")}`:"Available times"}),i?q?e.jsxs("div",{className:"text-sm text-muted-foreground flex items-center gap-2",children:[e.jsx(Ht,{className:"h-4 w-4 animate-spin"})," Checking availability…"]}):B.length===0?e.jsx("p",{className:"text-sm text-muted-foreground",children:"No openings on this day — try another date."}):e.jsx("div",{className:"space-y-3 max-h-[320px] overflow-y-auto pr-1",children:W.map(ce=>e.jsxs("div",{children:[e.jsx("div",{className:"text-[11px] uppercase tracking-wide text-muted-foreground mb-1",children:ce.label}),e.jsx("div",{className:"grid grid-cols-3 gap-2",children:ce.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:Hot(ue)},ue))})]},ce.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&&D.length>0&&e.jsx("div",{className:"mt-3 flex flex-wrap gap-2",children:D.slice(0,3).map(([ce,ue])=>e.jsxs($,{size:"sm",variant:"outline",onClick:()=>{l(ce),c(null)},children:[Hs(new Date(`${ce}T12:00:00`),"EEE MMM d")," · ",ue.length," open"]},ce))})]})]}),o&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx(se,{htmlFor:"agenda",children:"What do you want to work on? (optional)"}),e.jsx(Is,{id:"agenda",rows:3,value:d,onChange:ce=>u(ce.target.value),placeholder:"Share context so your coach can prep."})]}),e.jsxs($,{onClick:Q,disabled:h||K,className:"bg-[#406E71] hover:bg-[#2a4c64]",children:[h?e.jsx(Ht,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(Fr,{className:"h-4 w-4 mr-1"}),"Book ",V==null?void 0:V.name," — ",i&&Hs(new Date(`${i}T12:00:00`),"MMM d")," at ",Hot(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(_e,{children:e.jsx(Oe,{className:"p-8 text-center text-muted-foreground",children:"Your coach hasn't opened their coaching calendar yet. Check back soon."})})}function f4s(){const{user:s}=_s(),{isMember:t,pkg:n}=ek(),{data:r}=ht({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([U.from("coaching_onboarding_forms").select("submitted_at").eq("user_id",s.id).maybeSingle(),U.from("coaching_prep_checklist_items").select("*").eq("package_id",n.id).eq("is_active",!0).order("sort_order"),U.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(_e,{children:[e.jsxs(Bt,{className:"flex flex-row items-center justify-between gap-2 space-y-0",children:[e.jsxs(Ut,{className:"text-base flex items-center gap-2",children:[e.jsx(v0,{className:"h-4 w-4 text-primary"})," Coaching prep"]}),a.length>0&&e.jsxs($e,{variant:"secondary",children:[i,"/",a.length," done"]})]}),e.jsxs(Oe,{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3 rounded-lg border border-border/60 p-3",children:[e.jsxs("div",{className:"text-sm",children:[e.jsx("div",{className:"font-medium",children:"Onboarding questionnaire"}),e.jsx("div",{className:"text-muted-foreground text-xs",children:r!=null&&r.submitted?"Submitted — your coach has it.":"Complete this before session one."})]}),e.jsx($,{asChild:!0,size:"sm",variant:r!=null&&r.submitted?"outline":"default",children:e.jsx(Wn,{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(Fr,{className:"h-4 w-4 mt-0.5 text-primary"}):e.jsx(Bp,{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 x4s(){var m,p,x,g,y,b;const{user:s}=_s(),{data:t,isLoading:n,refetch:r}=nGe(),a=ts(),i=t==null?void 0:t.id,{data:l=[]}=rGe(i),{data:o=[]}=aGe(i);if(j.useEffect(()=>{new URLSearchParams(window.location.search).get("subscribed")==="1"&&U.functions.invoke("coaching-verify-checkout").then(()=>{r(),a.invalidateQueries({queryKey:["my-coaching-assignment"]})})},[r,a]),n)return e.jsx(Ks,{title:"My Coach",children:e.jsx("div",{className:"p-8",children:"Loading…"})});if(!t)return e.jsx(Ks,{title:"My Coach",children:e.jsxs("div",{className:"max-w-2xl mx-auto p-8 text-center",children:[e.jsx(Ph,{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(v=>v.status!=="done"),u=o.length-d.length,h=l.filter(v=>v.status!=="cancelled"&&new Date(v.scheduled_at).getTime()>Date.now());return e.jsx(Ks,{title:"My Coach",children:e.jsxs("div",{className:"p-4 md:p-8 max-w-5xl mx-auto space-y-6",children:[e.jsx(_e,{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(ki,{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(dn,{className:"h-4 w-4"}),e.jsx("span",{className:"text-sm uppercase tracking-wider",children:"Your Coach"})]}),e.jsx("h1",{className:"text-3xl font-bold",children:((x=c.coachProfile)==null?void 0:x.name)||"Your Coach"}),((g=c.coach)==null?void 0:g.headline)&&e.jsx("p",{className:"text-white/80 mt-1",children:c.coach.headline}),e.jsxs("div",{className:"flex gap-2 mt-3",children:[((y=c.coach)==null?void 0:y.is_certified)&&e.jsx($e,{className:"bg-yellow-400/20 text-yellow-100 border-yellow-300/30",children:"LevelUp Certified"}),e.jsx($e,{variant:"secondary",className:"bg-white/15 text-white border-white/20",children:"Active Program"})]})]})]})]})}),e.jsxs("div",{className:"grid grid-cols-3 gap-4",children:[e.jsx(yPe,{icon:Jh,label:"Open action items",value:d.length}),e.jsx(yPe,{icon:Mu,label:"Completed",value:u}),e.jsx(yPe,{icon:ia,label:"Sessions",value:l.length})]}),e.jsx(f4s,{}),((b=c.coach)==null?void 0:b.id)&&e.jsx(m4s,{coachId:c.coach.id,assignmentId:i}),e.jsxs(ua,{defaultValue:"book",children:[e.jsxs(ha,{className:"flex flex-wrap h-auto w-full justify-start",children:[e.jsxs(Qt,{value:"book",children:[e.jsx(gg,{className:"h-4 w-4 mr-1 md:mr-2"}),e.jsx("span",{className:"hidden sm:inline",children:"Book"})]}),e.jsxs(Qt,{value:"actions",children:[e.jsx(Jh,{className:"h-4 w-4 mr-1 md:mr-2"}),e.jsx("span",{className:"hidden sm:inline",children:"Actions"})]}),e.jsxs(Qt,{value:"sessions",children:[e.jsx(ia,{className:"h-4 w-4 mr-1 md:mr-2"}),e.jsx("span",{className:"hidden sm:inline",children:"Recaps"})]}),e.jsxs(Qt,{value:"goals",children:[e.jsx(Mu,{className:"h-4 w-4 mr-1 md:mr-2"}),e.jsx("span",{className:"hidden sm:inline",children:"Goals"})]}),e.jsxs(Qt,{value:"kpis",children:[e.jsx(Il,{className:"h-4 w-4 mr-1 md:mr-2"}),e.jsx("span",{className:"hidden sm:inline",children:"KPIs"})]}),e.jsxs(Qt,{value:"messages",children:[e.jsx(Ji,{className:"h-4 w-4 mr-1 md:mr-2"}),e.jsx("span",{className:"hidden sm:inline",children:"Messages"})]}),e.jsxs(Qt,{value:"files",children:[e.jsx(cv,{className:"h-4 w-4 mr-1 md:mr-2"}),e.jsx("span",{className:"hidden sm:inline",children:"Files"})]})]}),e.jsx(Jt,{value:"book",children:e.jsx(p4s,{assignmentId:i,upcoming:h})}),e.jsx(Jt,{value:"actions",className:"space-y-2",children:o.length===0?e.jsx(_e,{children:e.jsx(Oe,{className:"p-6 text-center text-muted-foreground",children:"Your coach hasn't assigned any action items yet."})}):o.map(v=>e.jsx(_e,{children:e.jsxs(Oe,{className:"p-3 flex items-center gap-3",children:[e.jsx(ui,{checked:v.status==="done",onCheckedChange:async N=>{await U.from("coaching_action_items").update({status:N?"done":"open",completed_at:N?new Date().toISOString():null}).eq("id",v.id),a.invalidateQueries({queryKey:["coaching-action-items",i]})}}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:v.status==="done"?"line-through text-muted-foreground":"font-medium",children:v.title}),v.description&&e.jsx("div",{className:"text-xs text-muted-foreground",children:v.description})]}),v.due_date&&e.jsx($e,{variant:"outline",children:Hs(new Date(v.due_date),"MMM d")}),e.jsx($e,{variant:"secondary",className:"capitalize",children:v.priority})]})},v.id))}),e.jsx(Jt,{value:"sessions",className:"space-y-3",children:l.length===0?e.jsx(_e,{children:e.jsx(Oe,{className:"p-6 text-center text-muted-foreground",children:"No sessions logged yet."})}):l.map(v=>e.jsx(_e,{children:e.jsxs(Oe,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx("span",{className:"font-medium",children:Hs(new Date(v.scheduled_at),"PPp")}),e.jsx($e,{variant:"outline",className:"capitalize",children:v.status})]}),v.summary?e.jsx("p",{className:"text-sm whitespace-pre-wrap",children:v.summary}):e.jsx("p",{className:"text-sm text-muted-foreground italic",children:"Recap coming soon."})]})},v.id))}),e.jsx(Jt,{value:"goals",children:e.jsx(n6t,{assignmentId:i,canEdit:!1})}),e.jsx(Jt,{value:"kpis",children:s&&e.jsx(s6t,{agentUserId:s.id})}),e.jsx(Jt,{value:"messages",children:e.jsx(ZTt,{assignmentId:i})}),e.jsx(Jt,{value:"files",children:e.jsx(r6t,{assignmentId:i})})]})]})})}function yPe({icon:s,label:t,value:n}){return e.jsx(_e,{children:e.jsxs(Oe,{className:"p-4 flex items-center gap-3",children:[e.jsx("div",{className:"h-10 w-10 rounded-lg bg-primary/10 flex items-center justify-center",children:e.jsx(s,{className:"h-5 w-5 text-primary"})}),e.jsxs("div",{children:[e.jsx("div",{className:"text-2xl font-bold leading-none",children:n}),e.jsx("div",{className:"text-xs text-muted-foreground mt-1",children:t})]})]})})}const Got="coaching_access",vPe=s=>((s==null?void 0:s.name)||(s==null?void 0:s.email)||"?").trim().slice(0,2).toUpperCase(),bPe=s=>!!s.expires_at&&new Date(s.expires_at).getTime()<=Date.now();function g4s(){const s=ts(),[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}=ht({queryKey:["coaching-entitlements"],queryFn:async()=>{const{data:D,error:B}=await U.from("feature_entitlements").select("id, user_id, enabled, expires_at, tier, notes, enabled_at").eq("feature_key",Got).order("enabled_at",{ascending:!1});if(B)throw B;return D||[]}}),{data:p=[]}=ht({queryKey:["coaching-assigned-agents"],queryFn:async()=>{const{data:D,error:B}=await U.from("coaching_assignments").select("agent_id, coach_id, status").eq("status","active");if(B)throw B;return D||[]}}),x=j.useMemo(()=>{const D=new Set;return h.forEach(B=>D.add(B.user_id)),p.forEach(B=>D.add(B.agent_id)),Array.from(D)},[h,p]),{data:g={}}=ht({queryKey:["coaching-access-profiles",x.join(",")],enabled:x.length>0,queryFn:async()=>{const D={};for(let B=0;B{D[W.id]=W})}return D}});j.useEffect(()=>{const D=t.trim();if(D.length<2){a([]),l(!1);return}l(!0);const B=setTimeout(async()=>{const{data:q}=await U.from("profiles").select("id, name, email, avatar_url").or(`email.ilike.%${D}%,name.ilike.%${D}%`).limit(12);a(q||[]),l(!1)},250);return()=>clearTimeout(B)},[t]);const y=j.useMemo(()=>{const D=new Map;return h.forEach(B=>D.set(B.user_id,B)),D},[h]),b=j.useMemo(()=>new Set(p.map(D=>D.agent_id)),[p]),v=()=>{s.invalidateQueries({queryKey:["coaching-entitlements"]}),s.invalidateQueries({queryKey:["coaching-access-profiles"]}),s.invalidateQueries({queryKey:["coaching-access"]})},N=async(D,B={})=>{var V;const{data:q}=await U.auth.getUser(),{error:W}=await U.from("feature_entitlements").upsert({user_id:D,feature_key:Got,enabled:B.enabled??!0,expires_at:B.expires_at??null,notes:B.notes??null,tier:B.tier??null,enabled_by:((V=q==null?void 0:q.user)==null?void 0:V.id)??null,enabled_at:new Date().toISOString(),updated_at:new Date().toISOString()},{onConflict:"user_id,feature_key"});return W?(ae.error(W.message),!1):(v(),!0)},C=async D=>{await N(D.id)&&ae.success(`Coaching access granted to ${D.name||D.email}`),n(""),a([])},A=async(D,B)=>{const{error:q}=await U.from("feature_entitlements").update({enabled:B,updated_at:new Date().toISOString()}).eq("id",D.id);if(q)return ae.error(q.message);ae.success(B?"Access enabled":"Access paused"),v()},T=async D=>{if(!await Yi({title:"Revoke coaching access?",description:`${D.profile.name||D.profile.email||"This member"} will lose access to the coaching area unless they're assigned to a coach.`,confirmText:"Revoke access",destructive:!0}))return;const{error:q}=await U.from("feature_entitlements").delete().eq("id",D.entitlement.id);if(q)return ae.error(q.message);ae.success("Coaching access revoked"),v()},P=j.useMemo(()=>{const D=d.trim().toLowerCase(),B=h.map(q=>({entitlement:q,profile:g[q.user_id]}));return D?B.filter(({profile:q})=>`${(q==null?void 0:q.name)||""} ${(q==null?void 0:q.email)||""}`.toLowerCase().includes(D)):B},[h,g,d]),M=h.filter(D=>D.enabled&&!bPe(D)).length,I=p.filter(D=>!y.has(D.agent_id));return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-3 gap-3",children:[e.jsx(_Pe,{icon:j0,label:"Granted access",value:M,hint:"Standalone entitlements"}),e.jsx(_Pe,{icon:qn,label:"Coached members",value:b.size,hint:"Active coach assignments"}),e.jsx(_Pe,{icon:dn,label:"Total with access",value:new Set([...h.filter(D=>D.enabled&&!bPe(D)).map(D=>D.user_id),...b]).size,hint:"Unique members"})]}),e.jsx(_e,{children:e.jsxs(Oe,{className:"p-4 space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(q3,{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(Vr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(be,{className:"pl-9",placeholder:"Search members by name or email…",value:t,onChange:D=>n(D.target.value)})]}),t.trim().length>=2&&e.jsx("div",{className:"border rounded-lg divide-y max-h-80 overflow-auto",children:i?e.jsxs("div",{className:"p-3 text-sm text-muted-foreground flex items-center gap-2",children:[e.jsx(Ht,{className:"h-4 w-4 animate-spin"})," Searching…"]}):r.length===0?e.jsx("div",{className:"p-3 text-sm text-muted-foreground",children:"No members found"}):r.map(D=>{const B=y.get(D.id),q=b.has(D.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(ki,{src:D.avatar_url||void 0}),e.jsx(Ta,{className:"text-xs",children:vPe(D)})]}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("div",{className:"font-medium truncate",children:D.name||D.email}),e.jsx("div",{className:"text-xs text-muted-foreground truncate",children:D.email})]}),B?e.jsx($e,{variant:"outline",className:"shrink-0",children:"Already granted"}):q?e.jsxs($e,{variant:"outline",className:"shrink-0",children:[e.jsx(Dc,{className:"h-3 w-3 mr-1"}),"Has coach"]}):e.jsxs("div",{className:"flex gap-1.5 shrink-0",children:[e.jsx($,{size:"sm",variant:"outline",onClick:()=>c({profile:D}),children:"Options"}),e.jsxs($,{size:"sm",className:"bg-[#406E71] hover:bg-[#2a4c64]",onClick:()=>C(D),children:[e.jsx(il,{className:"h-4 w-4 mr-1"})," Grant"]})]})]},D.id)})})]})}),e.jsx(_e,{children:e.jsxs(Oe,{className:"p-4 space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx(j0,{className:"h-5 w-5 text-primary"}),e.jsx("h2",{className:"text-lg font-semibold",children:"Members with granted access"}),e.jsx($e,{variant:"outline",children:h.length}),e.jsx("div",{className:"ml-auto w-full sm:w-64",children:e.jsx(be,{placeholder:"Filter list…",value:d,onChange:D=>u(D.target.value)})})]}),m?e.jsxs("div",{className:"p-6 text-sm text-muted-foreground flex items-center gap-2",children:[e.jsx(Ht,{className:"h-4 w-4 animate-spin"})," Loading…"]}):P.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:P.map(({entitlement:D,profile:B})=>{const q=bPe(D);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(ki,{src:(B==null?void 0:B.avatar_url)||void 0}),e.jsx(Ta,{className:"text-xs",children:vPe(B)})]}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("div",{className:"font-medium truncate",children:(B==null?void 0:B.name)||(B==null?void 0:B.email)||D.user_id}),e.jsx("div",{className:"text-xs text-muted-foreground truncate",children:B==null?void 0:B.email}),e.jsxs("div",{className:"flex items-center gap-2 mt-1 flex-wrap",children:[q?e.jsx($e,{className:"bg-rose-500/15 text-rose-700 border-rose-300/40",children:"Expired"}):D.enabled?e.jsx($e,{className:"bg-emerald-500/15 text-emerald-700 border-emerald-300/40",children:"Active"}):e.jsx($e,{variant:"outline",children:"Paused"}),b.has(D.user_id)&&e.jsxs($e,{variant:"outline",children:[e.jsx(Dc,{className:"h-3 w-3 mr-1"}),"Has coach"]}),D.tier&&e.jsx($e,{variant:"outline",children:D.tier}),D.expires_at&&e.jsxs("span",{className:"text-xs text-muted-foreground inline-flex items-center gap-1",children:[e.jsx(Xu,{className:"h-3 w-3"}),q?"Expired":"Expires"," ",new Date(D.expires_at).toLocaleDateString()]})]}),D.notes&&e.jsx("p",{className:"text-xs text-muted-foreground mt-1 italic truncate",children:D.notes})]}),e.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[e.jsx(Tn,{checked:D.enabled&&!q,onCheckedChange:W=>A(D,W)}),e.jsx($,{size:"sm",variant:"outline",onClick:()=>c({profile:B||{id:D.user_id,name:null,email:null},entitlement:D}),children:"Edit"}),e.jsx($,{size:"sm",variant:"ghost",className:"text-rose-600 hover:bg-rose-50",onClick:()=>T({profile:B||{id:D.user_id,name:null,email:null},entitlement:D}),children:e.jsx(pr,{className:"h-4 w-4"})})]})]},D.id)})})]})}),e.jsx(_e,{children:e.jsxs(Oe,{className:"p-4 space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(qn,{className:"h-5 w-5 text-primary"}),e.jsx("h2",{className:"text-lg font-semibold",children:"Access through a coach assignment"}),e.jsx($e,{variant:"outline",children: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(D=>{const B=g[D.agent_id];return e.jsxs("div",{className:"flex items-center gap-2 border rounded-full pl-1 pr-3 py-1",children:[e.jsxs(Ea,{className:"h-6 w-6",children:[e.jsx(ki,{src:(B==null?void 0:B.avatar_url)||void 0}),e.jsx(Ta,{className:"text-[10px]",children:vPe(B)})]}),e.jsx("span",{className:"text-sm",children:(B==null?void 0:B.name)||(B==null?void 0:B.email)||D.agent_id})]},D.agent_id)})})]})}),e.jsx(y4s,{state:o,onClose:()=>c(null),onSave:async D=>{if(!o)return;await N(o.profile.id,D)&&(ae.success("Coaching access saved"),c(null))}})]})}function _Pe({icon:s,label:t,value:n,hint:r}){return e.jsx(_e,{children:e.jsxs(Oe,{className:"p-4 flex items-center gap-3",children:[e.jsx("div",{className:"h-10 w-10 rounded-lg bg-primary/10 flex items-center justify-center",children:e.jsx(s,{className:"h-5 w-5 text-primary"})}),e.jsxs("div",{children:[e.jsx("div",{className:"text-2xl font-bold leading-none",children:n}),e.jsx("div",{className:"text-sm font-medium",children:t}),e.jsx("div",{className:"text-xs text-muted-foreground",children:r})]})]})})}function y4s({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 x=s.entitlement;a(x!=null&&x.expires_at?x.expires_at.slice(0,10):""),l((x==null?void 0:x.notes)||""),c((x==null?void 0:x.tier)||""),u(x?x.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(Os,{open:!!s,onOpenChange:x=>!x&&t(),children:e.jsxs(Rs,{children:[e.jsx(Us,{children:e.jsx(zs,{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(se,{children:"Access enabled"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Turn off to pause without removing the grant."})]}),e.jsx(Tn,{checked:d,onCheckedChange:u})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Expires on (optional)"}),e.jsx(be,{type:"date",value:r,onChange:x=>a(x.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(se,{children:"Tier / plan label (optional)"}),e.jsx(be,{value:o,onChange:x=>c(x.target.value),placeholder:"e.g. Premium, Beta, Comp"})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Internal notes"}),e.jsx(Is,{value:i,onChange:x=>l(x.target.value),rows:3,placeholder:"Why this member has access…"})]})]}),e.jsxs(kr,{children:[e.jsx($,{variant:"outline",onClick:t,children:"Cancel"}),e.jsx($,{onClick:p,disabled:h,className:"bg-[#406E71] hover:bg-[#2a4c64]",children:h?"Saving…":"Save access"})]})]})})}function v4s(){const s=ts(),[t,n]=j.useState(""),[r,a]=j.useState("active"),{data:i=[]}=ht({queryKey:["admin-coaches-lite"],queryFn:async()=>{const{data:p,error:x}=await U.from("coaches").select("id, user_id");if(x)throw x;const g=(p||[]).map(v=>v.user_id);if(!g.length)return[];const{data:y}=await U.from("profiles").select("id, name, email").in("id",g),b=new Map((y||[]).map(v=>[v.id,v]));return(p||[]).map(v=>{var N,C;return{id:v.id,label:((N=b.get(v.user_id))==null?void 0:N.name)||((C=b.get(v.user_id))==null?void 0:C.email)||v.user_id}})}}),{data:l=[],isLoading:o}=ht({queryKey:["admin-coaching-assignments"],queryFn:async()=>{const{data:p,error:x}=await U.from("coaching_assignments").select("*").order("created_at",{ascending:!1});if(x)throw x;const g=[...new Set((p||[]).map(v=>v.agent_id))],{data:y}=g.length?await U.from("profiles").select("id, name, email").in("id",g):{data:[]},b=new Map((y||[]).map(v=>[v.id,v]));return(p||[]).map(v=>({...v,agent:b.get(v.agent_id)}))}}),c=p=>{var x;return((x=i.find(g=>g.id===p))==null?void 0:x.label)||"—"},d=j.useMemo(()=>{const p=t.trim().toLowerCase();return l.filter(x=>{var g,y;return r!=="all"&&x.status!==r?!1:p?(((g=x.agent)==null?void 0:g.name)||"").toLowerCase().includes(p)||(((y=x.agent)==null?void 0:y.email)||"").toLowerCase().includes(p)||c(x.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,x)=>{var b,v;if(x===p.coach_id||!await Yi({title:"Switch coach?",description:`${((b=p.agent)==null?void 0:b.name)||((v=p.agent)==null?void 0:v.email)} will move from ${c(p.coach_id)} to ${c(x)}. Session history stays with the assignment.`,confirmText:"Switch coach"}))return;const{error:y}=await U.from("coaching_assignments").update({coach_id:x}).eq("id",p.id);if(y)return ae.error(y.message);ae.success("Coach switched"),u()},m=async(p,x)=>{var y,b;if(x==="ended"&&!await Yi({title:"End assignment?",description:`${((y=p.agent)==null?void 0:y.name)||((b=p.agent)==null?void 0:b.email)} will lose access to the coaching workspace unless they have standalone access.`,confirmText:"End assignment",destructive:!0}))return;const{error:g}=await U.from("coaching_assignments").update({status:x,ended_at:x==="ended"?new Date().toISOString():null}).eq("id",p.id);if(g)return ae.error(g.message);ae.success(x==="ended"?"Assignment ended":"Assignment reactivated"),u()};return e.jsx(_e,{children:e.jsxs(Oe,{className:"p-4 space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(qn,{className:"h-5 w-5 text-primary"}),e.jsx("h2",{className:"text-lg font-semibold",children:"Coach assignments"}),e.jsx($e,{variant:"secondary",className:"ml-auto",children:d.length})]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Switch an agent to a different coach, end an assignment, or reactivate a past one."}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-2",children:[e.jsx(be,{placeholder:"Search by agent or coach…",value:t,onChange:p=>n(p.target.value)}),e.jsxs(vs,{value:r,onValueChange:p=>a(p),children:[e.jsx(gs,{className:"sm:w-40",children:e.jsx(bs,{})}),e.jsxs(ys,{children:[e.jsx(Ye,{value:"active",children:"Active"}),e.jsx(Ye,{value:"ended",children:"Ended"}),e.jsx(Ye,{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 x,g,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:((x=p.agent)==null?void 0:x.name)||((g=p.agent)==null?void 0:g.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(fK,{className:"h-4 w-4 text-muted-foreground shrink-0"}),e.jsxs(vs,{value:p.coach_id,onValueChange:b=>h(p,b),children:[e.jsx(gs,{className:"w-full md:w-56 h-9",children:e.jsx(bs,{})}),e.jsx(ys,{children:i.map(b=>e.jsx(Ye,{value:b.id,children:b.label},b.id))})]}),p.status==="active"?e.jsxs($,{variant:"outline",size:"sm",onClick:()=>m(p,"ended"),children:[e.jsx(Hz,{className:"h-4 w-4 mr-1"})," End"]}):e.jsxs($,{variant:"outline",size:"sm",onClick:()=>m(p,"active"),children:[e.jsx(Ih,{className:"h-4 w-4 mr-1"})," Reactivate"]})]})]},p.id)})})]})})}function b4s(){const s=ts(),[t,n]=j.useState(""),[r,a]=j.useState([]),[i,l]=j.useState(null),{data:o=[],isLoading:c}=ht({queryKey:["admin-coaches"],queryFn:async()=>{const{data:h,error:m}=await U.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:x}=await U.from("profiles").select("id, name, email, avatar_url").in("id",p),g=new Map((x||[]).map(y=>[y.id,y]));return h.map(y=>({...y,profile:g.get(y.user_id)}))}});j.useEffect(()=>{const h=t.trim();if(h.length<2){a([]);return}const m=setTimeout(async()=>{const{data:p}=await U.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 U.functions.invoke("manage-user-roles",{body:{userId:h.id,role:"coach",action:"add"}});if(m)return ae.error(m.message);const{error:p}=await U.from("coaches").insert({user_id:h.id});if(p&&!String(p.message).includes("duplicate"))return ae.error(p.message);ae.success(`${h.name||h.email} is now a coach`),n(""),a([]),s.invalidateQueries({queryKey:["admin-coaches"]})},u=async(h,m)=>{const{error:p}=await U.from("coaches").update({is_certified:m}).eq("id",h);if(p)return ae.error(p.message);ae.success(m?"Marked Certified":"Removed certification"),s.invalidateQueries({queryKey:["admin-coaches"]})};return e.jsxs(Ks,{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(Ph,{className:"h-7 w-7 text-primary"}),e.jsx("h1",{className:"text-2xl font-bold",children:"LevelUp Coaching"})]}),e.jsxs(ua,{defaultValue:"coaches",className:"space-y-6",children:[e.jsxs(ha,{className:"flex-wrap h-auto",children:[e.jsx(Qt,{value:"coaches",children:"Coaches"}),e.jsx(Qt,{value:"assignments",children:"Assignments"}),e.jsx(Qt,{value:"access",children:"Coaching Access"}),e.jsx(Qt,{value:"applications",children:"Applications"}),e.jsx(Qt,{value:"settings",children:"Settings"})]}),e.jsx(Jt,{value:"assignments",className:"space-y-6",children:e.jsx(v4s,{})}),e.jsx(Jt,{value:"access",className:"space-y-6",children:e.jsx(g4s,{})}),e.jsx(Jt,{value:"applications",className:"space-y-6",children:e.jsx(j4s,{})}),e.jsx(Jt,{value:"settings",className:"space-y-6",children:e.jsx(_4s,{})}),e.jsxs(Jt,{value:"coaches",className:"space-y-6",children:[e.jsx(_e,{children:e.jsxs(Oe,{className:"p-4 space-y-3",children:[e.jsx(be,{placeholder:"Search by user email or name…",value:t,onChange:h=>n(h.target.value)}),t.trim().length>=2&&e.jsx("div",{className:"border rounded-md divide-y max-h-72 overflow-auto",children:r.length===0?e.jsx("div",{className:"p-3 text-sm text-muted-foreground",children:"No users found"}):r.map(h=>e.jsxs("div",{className:"flex items-center justify-between p-2 hover:bg-muted/40",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"font-medium truncate",children:h.name||h.email}),e.jsx("div",{className:"text-xs text-muted-foreground truncate",children:h.email})]}),e.jsxs($,{size:"sm",onClick:()=>d(h),children:[e.jsx(sn,{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(_e,{children:e.jsx(Oe,{className:"p-6 text-center text-muted-foreground",children:"No coaches yet. Search for a user above to promote them."})}):e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3",children:o.map(h=>{var m,p,x;return e.jsx(_e,{children:e.jsxs(Oe,{className:"p-4 space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"font-medium",children:((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:(x=h.profile)==null?void 0:x.email}),e.jsxs("div",{className:"flex gap-2 mt-2 flex-wrap",children:[h.is_certified&&e.jsxs($e,{className:"bg-yellow-500/15 text-yellow-700 border-yellow-300/40",children:[e.jsx(dn,{className:"h-3 w-3 mr-1"}),"Certified"]}),h.accepting_clients&&e.jsx($e,{variant:"outline",children:"Accepting clients"})]})]}),e.jsxs($,{size:"sm",variant:"outline",onClick:()=>l(h.id),children:[e.jsx(il,{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(Tn,{checked:h.is_certified,onCheckedChange:g=>u(h.id,g)})]})]})},h.id)})})]})]})]})]}),e.jsx(w4s,{coachId:i,onClose:()=>l(null)})]})}function _4s(){const[s,t]=j.useState("1500"),[n,r]=j.useState(!1),[a,i]=j.useState(!1);j.useEffect(()=>{(async()=>{const{data:c}=await U.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 ae.error("Enter a value between 0 and 5000 bps (0–50%)");r(!0);const{error:d}=await U.from("settings").upsert({key:"coaching_platform_fee_bps",value:String(c)});if(r(!1),d)return ae.error(d.message);ae.success("Platform fee updated")};if(!a)return null;const o=(parseInt(s,10)/100).toFixed(2);return e.jsx(_e,{children:e.jsxs(Oe,{className:"p-4 space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ST,{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(se,{children:"Fee (bps)"}),e.jsx(be,{type:"number",value:s,onChange:c=>t(c.target.value),min:0,max:5e3}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-1",children:["= ",o,"%"]})]}),e.jsx($,{onClick:l,disabled:n,className:"bg-[#406E71] hover:bg-[#2a4c64] self-end",children:n?"Saving…":"Save"})]})]})})}function w4s({coachId:s,onClose:t}){const[n,r]=j.useState(""),[a,i]=j.useState([]),[l,o]=j.useState(!1),c=ts();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 U.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 U.from("coaching_assignments").insert({coach_id:s,agent_id:u,status:"active",source:"admin",pipeline_stage:"onboarding"});if(h)return ae.error(h.message);ae.success("Agent assigned"),c.invalidateQueries({queryKey:["coach-roster"]}),t()};return e.jsx(Os,{open:!!s,onOpenChange:u=>!u&&t(),children:e.jsxs(Rs,{children:[e.jsx(Us,{children:e.jsx(zs,{children:"Assign Agent"})}),e.jsx(be,{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(kr,{children:e.jsx($,{variant:"outline",onClick:t,children:"Close"})})]})})}function j4s(){const s=ts(),[t,n]=j.useState("pending"),[r,a]=j.useState(null),{data:i=[],isLoading:l}=ht({queryKey:["coach-applications",t],queryFn:async()=>{let u=U.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}=ht({queryKey:["coach-applications-pending-count"],queryFn:async()=>{const{count:u}=await U.from("coach_applications").select("id",{count:"exact",head:!0}).eq("status","pending");return u||0}}),c=async(u,h)=>{const{error:m}=await U.from("coach_applications").update({status:h,reviewed_at:new Date().toISOString()}).eq("id",u);if(m)return ae.error(m.message);ae.success(`Marked ${h}`),s.invalidateQueries({queryKey:["coach-applications"]}),s.invalidateQueries({queryKey:["coach-applications-pending-count"]}),a(null)},d=u=>u==="approved"?e.jsxs($e,{className:"bg-emerald-500/15 text-emerald-700 border-emerald-300/40",children:[e.jsx(oa,{className:"h-3 w-3 mr-1"}),"Approved"]}):u==="rejected"?e.jsxs($e,{className:"bg-rose-500/15 text-rose-700 border-rose-300/40",children:[e.jsx(pr,{className:"h-3 w-3 mr-1"}),"Rejected"]}):e.jsxs($e,{className:"bg-yellow-500/15 text-yellow-700 border-yellow-300/40",children:[e.jsx(Hr,{className:"h-3 w-3 mr-1"}),"Pending"]});return e.jsxs(_e,{children:[e.jsxs(Oe,{className:"p-4 space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx(bT,{className:"h-5 w-5 text-primary"}),e.jsx("h2",{className:"text-lg font-semibold",children:"Coach Applications"}),o>0&&e.jsxs($e,{className:"bg-yellow-500/15 text-yellow-700 border-yellow-300/40",children:[o," pending"]}),e.jsx("div",{className:"ml-auto flex gap-1 flex-wrap",children:["pending","approved","rejected","all"].map(u=>e.jsx($,{size:"sm",variant:t===u?"default":"outline",onClick:()=>n(u),className:t===u?"bg-[#406E71] hover:bg-[#2a4c64]":"",children:u.charAt(0).toUpperCase()+u.slice(1)},u))})]}),l?e.jsx("div",{className:"text-sm text-muted-foreground",children:"Loading…"}):i.length===0?e.jsxs("div",{className:"text-sm text-muted-foreground p-6 text-center border rounded-md",children:["No applications ",t!=="all"?`with status "${t}"`:"yet","."]}):e.jsx("div",{className:"divide-y border rounded-md",children:i.map(u=>e.jsx("button",{onClick:()=>a(u),className:"w-full text-left p-3 hover:bg-muted/40 transition-colors",children:e.jsxs("div",{className:"flex items-center justify-between gap-3 flex-wrap",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"font-medium",children:u.full_name}),e.jsxs("div",{className:"text-xs text-muted-foreground flex items-center gap-3 mt-0.5",children:[e.jsxs("span",{className:"inline-flex items-center gap-1",children:[e.jsx(nn,{className:"h-3 w-3"}),u.email]}),u.brokerage&&e.jsxs("span",{children:["· ",u.brokerage]}),u.years_experience&&e.jsxs("span",{children:["· ",u.years_experience," yrs"]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[d(u.status),e.jsx("span",{className:"text-xs text-muted-foreground",children:new Date(u.created_at).toLocaleDateString()})]})]})},u.id))})]}),e.jsx(Os,{open:!!r,onOpenChange:u=>!u&&a(null),children:e.jsx(Rs,{className:"max-w-2xl max-h-[85vh] overflow-y-auto",children:r&&e.jsxs(e.Fragment,{children:[e.jsx(Us,{children:e.jsxs(zs,{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(b7,{icon:nn,label:"Email",value:r.email,link:`mailto:${r.email}`}),r.phone&&e.jsx(b7,{icon:ya,label:"Phone",value:r.phone,link:`tel:${r.phone}`}),r.brokerage&&e.jsx(b7,{label:"Brokerage",value:r.brokerage}),r.years_experience&&e.jsx(b7,{label:"Years",value:r.years_experience}),r.website_url&&e.jsx(b7,{icon:Tr,label:"Website",value:r.website_url,link:r.website_url}),r.linkedin_url&&e.jsx(b7,{icon:Tr,label:"LinkedIn",value:r.linkedin_url,link:r.linkedin_url})]}),r.specialties&&e.jsx(wPe,{label:"Specialties",children:r.specialties}),e.jsx(wPe,{label:"Why they want to coach",children:r.why_coach}),r.results_story&&e.jsx(wPe,{label:"Results story",children:r.results_story}),e.jsxs("div",{children:[e.jsx(se,{className:"text-xs font-semibold uppercase text-muted-foreground",children:"Admin notes"}),e.jsx(Is,{defaultValue:r.admin_notes||"",rows:3,onBlur:async u=>{const h=u.target.value;h!==(r.admin_notes||"")&&(await U.from("coach_applications").update({admin_notes:h}).eq("id",r.id),s.invalidateQueries({queryKey:["coach-applications"]}))},placeholder:"Internal notes (saved on blur)…"})]})]}),e.jsxs(kr,{className:"gap-2 flex-wrap",children:[r.status!=="rejected"&&e.jsxs($,{variant:"outline",onClick:()=>c(r.id,"rejected"),className:"text-rose-600 border-rose-200 hover:bg-rose-50",children:[e.jsx(pr,{className:"h-4 w-4 mr-1"})," Reject"]}),r.status!=="pending"&&e.jsxs($,{variant:"outline",onClick:()=>c(r.id,"pending"),children:[e.jsx(Hr,{className:"h-4 w-4 mr-1"})," Move to pending"]}),r.status!=="approved"&&e.jsxs($,{onClick:()=>c(r.id,"approved"),className:"bg-emerald-600 hover:bg-emerald-700",children:[e.jsx(oa,{className:"h-4 w-4 mr-1"})," Approve"]})]})]})})})]})}function b7({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 wPe({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 N4s(){const s=Vn(),{data:t}=bee(),n=ts(),[r,a]=j.useState(!1),[i,l]=j.useState(!1),[o,c]=j.useState(null),{data:d,refetch:u}=ht({queryKey:["coach-stripe-status",t==null?void 0:t.id],enabled:!!t,queryFn:async()=>{const{data:y}=await U.functions.invoke("coach-stripe-status");return y}}),{data:h=[]}=ht({queryKey:["coach-packages",t==null?void 0:t.id],enabled:!!t,queryFn:async()=>{const{data:y}=await U.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,C;a(!0);const{data:y,error:b}=await U.functions.invoke("coach-stripe-connect");a(!1);let v=y==null?void 0:y.error;if(!v&&b)try{const A=await((C=(N=b==null?void 0:b.context)==null?void 0:N.json)==null?void 0:C.call(N));v=(A==null?void 0:A.error)||b.message}catch{v=b.message}if(v)return ae.error(v,{duration:1e4});y!=null&&y.url&&(window.location.href=y.url)},p=d||{},x=!!(t!=null&&t.use_platform_stripe),g=x||p.connected&&p.charges_enabled;return e.jsx(Ks,{title:"Coaching · Billing",children:e.jsxs("div",{className:"max-w-3xl mx-auto p-4 md:p-8 space-y-6",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx($,{variant:"ghost",size:"icon",onClick:()=>s("/coaching"),children:e.jsx(ka,{className:"h-5 w-5"})}),e.jsx("h1",{className:"text-2xl font-bold",children:"Billing & Packages"})]}),e.jsx(_e,{children:e.jsxs(Oe,{className:"p-6 space-y-3",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{children:[e.jsxs("h2",{className:"text-lg font-semibold flex items-center gap-2",children:[e.jsx(yy,{className:"h-5 w-5"})," Stripe Connect"]}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:x?"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."})]}),g?e.jsxs($e,{className:"bg-emerald-500/15 text-emerald-700 border-emerald-300/40 flex items-center gap-1",children:[e.jsx(Fr,{className:"h-3 w-3"})," ",x?"Using LevelUp billing":"Connected"]}):p.connected?e.jsxs($e,{variant:"secondary",className:"flex items-center gap-1",children:[e.jsx(xo,{className:"h-3 w-3"})," Setup incomplete"]}):e.jsx($e,{variant:"outline",children:"Not connected"})]}),!x&&e.jsxs($,{onClick:m,disabled:r,className:"bg-[#406E71] hover:bg-[#2a4c64]",children:[g?"Update Stripe details":p.connected?"Finish Stripe setup":"Connect Stripe",e.jsx(Tr,{className:"h-4 w-4 ml-1"})]})]})}),e.jsx(_e,{children:e.jsxs(Oe,{className:"p-6 space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("h2",{className:"text-lg font-semibold",children:"Packages"}),e.jsxs($,{size:"sm",onClick:()=>{c(null),l(!0)},disabled:!g,children:[e.jsx(sn,{className:"h-4 w-4 mr-1"})," New Package"]})]}),!g&&e.jsx("p",{className:"text-sm text-muted-foreground",children:"Connect Stripe before creating packages."}),h.length===0?e.jsx("p",{className:"text-sm text-muted-foreground text-center py-6",children:"No packages yet."}):e.jsx("div",{className:"space-y-2",children:h.map(y=>e.jsxs("div",{className:"flex items-center gap-3 p-3 border rounded-lg",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"font-medium flex items-center gap-2",children:[y.name,y.is_active&&y.accepting_clients===!1&&e.jsx("span",{className:"text-[10px] px-1.5 py-0.5 rounded-full bg-amber-100 text-amber-800 font-semibold",children:"Booked full"})]}),e.jsxs("div",{className:"text-sm text-muted-foreground",children:["$",(y.price_cents/100).toFixed(0)," / ",y.billing_interval,!y.is_active&&" · Inactive"]})]}),e.jsx($,{variant:"ghost",size:"icon",onClick:()=>{c(y),l(!0)},children:e.jsx(Ya,{className:"h-4 w-4"})}),e.jsx($,{variant:"ghost",size:"icon",onClick:async()=>{await Yi("Delete this package?")&&(await U.from("coaching_packages").delete().eq("id",y.id),n.invalidateQueries({queryKey:["coach-packages",t==null?void 0:t.id]}))},children:e.jsx(Pn,{className:"h-4 w-4"})})]},y.id))})]})}),e.jsx(k4s,{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 k4s({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,x]=j.useState(!0),[g,y]=j.useState(!0),[b,v]=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"),x((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 ae.error("Name and price required");v(!0);const C={coach_id:n,name:i,description:o||null,price_cents:Math.round(Number(d)*100),billing_interval:h,is_active:p,accepting_clients:g},{error:A}=r!=null&&r.id?await U.from("coaching_packages").update(C).eq("id",r.id):await U.from("coaching_packages").insert(C);if(v(!1),A)return ae.error(A.message);ae.success("Saved"),a==null||a(),t(!1)};return e.jsx(Os,{open:s,onOpenChange:t,children:e.jsxs(Rs,{children:[e.jsx(Us,{children:e.jsx(zs,{children:r!=null&&r.id?"Edit Package":"New Package"})}),e.jsxs("div",{className:"space-y-3",children:[e.jsx(be,{placeholder:"Name (e.g. Accelerator)",value:i,onChange:C=>l(C.target.value)}),e.jsx(Is,{rows:3,placeholder:"What's included",value:o,onChange:C=>c(C.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(be,{type:"number",value:d,onChange:C=>u(C.target.value)})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs text-muted-foreground",children:"Interval"}),e.jsxs(vs,{value:h,onValueChange:m,children:[e.jsx(gs,{children:e.jsx(bs,{})}),e.jsxs(ys,{children:[e.jsx(Ye,{value:"month",children:"Monthly"}),e.jsx(Ye,{value:"year",children:"Yearly"}),e.jsx(Ye,{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:C=>x(C.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:g,onChange:C=>y(C.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(kr,{children:[e.jsx($,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsx($,{onClick:N,disabled:b,children:r!=null&&r.id?"Save":"Create"})]})]})})}function Wot({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([]),[x,g]=j.useState(!1),y=s==="photo"?"image/*":"video/*",b=s==="photo"?10*1024*1024:200*1024*1024,v=async(M,I)=>{var K;const{data:D}=await U.auth.getUser(),B=(K=D.user)==null?void 0:K.id;if(!B)return ae.error("Not signed in");if(M.size>b)return ae.error(`File too large. Max ${s==="photo"?"10MB":"200MB"}.`);i(!0);const q=`${B}/${s}-${Date.now()}.${I}`,{error:W}=await U.storage.from("coach-media").upload(q,M,{upsert:!0,contentType:M.type||(s==="photo"?"image/jpeg":"video/webm")});if(W)return i(!1),ae.error(W.message);const{data:V}=await U.storage.from("coach-media").createSignedUrl(q,60*60*24*365*10);i(!1),V!=null&&V.signedUrl&&(n(V.signedUrl),ae.success("Uploaded"),d(null))},N=async M=>{const I=M.name.split(".").pop()||(s==="photo"?"jpg":"webm");await v(M,I)},C=async()=>{try{const M=await navigator.mediaDevices.getUserMedia({video:!0,audio:!0});h.current=M,g(!0),setTimeout(()=>{u.current&&(u.current.srcObject=M,u.current.play())},50);const I=new MediaRecorder(M,{mimeType:"video/webm"});p.current=[],I.ondataavailable=D=>D.data.size>0&&p.current.push(D.data),I.onstop=()=>{const D=new Blob(p.current,{type:"video/webm"});d(D),M.getTracks().forEach(B=>B.stop())},m.current=I,I.start(),o(!0)}catch(M){ae.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()),g(!1),o(!1),d(null)},P=async()=>{c&&(await v(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 D;const I=(D=M.target.files)==null?void 0:D[0];I&&N(I),M.target.value=""}}),e.jsxs($,{type:"button",variant:"outline",size:"sm",disabled:a,onClick:()=>{var M;return(M=r.current)==null?void 0:M.click()},children:[a?e.jsx(Ht,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(si,{className:"h-4 w-4 mr-1"}),s==="photo"?"Upload photo":"Upload video"]}),s==="video"&&e.jsxs($,{type:"button",variant:"outline",size:"sm",onClick:C,disabled:a||x,children:[e.jsx(y0,{className:"h-4 w-4 mr-1"})," Record intro"]}),t&&e.jsxs($,{type:"button",variant:"ghost",size:"sm",onClick:()=>n(""),children:[e.jsx(Pn,{className:"h-4 w-4 mr-1"})," Remove"]})]}),x&&e.jsxs("div",{className:"rounded-lg border p-3 space-y-3 bg-background",children:[c?e.jsx("video",{src:URL.createObjectURL(c),controls:!0,className:"w-full max-h-64 rounded bg-black"}):e.jsx("video",{ref:u,muted:!0,playsInline:!0,className:"w-full max-h-64 rounded bg-black"}),e.jsxs("div",{className:"flex gap-2",children:[!c&&l&&e.jsxs($,{type:"button",size:"sm",onClick:A,className:"bg-red-600 hover:bg-red-700",children:[e.jsx(Lb,{className:"h-4 w-4 mr-1"})," Stop"]}),!c&&!l&&e.jsxs($,{type:"button",size:"sm",onClick:()=>{var M;return(M=m.current)==null?void 0:M.start()},children:[e.jsx(Xr,{className:"h-4 w-4 mr-1"})," Start"]}),c&&e.jsxs(e.Fragment,{children:[e.jsxs($,{type:"button",size:"sm",onClick:P,disabled:a,className:"bg-[#406E71] hover:bg-[#2a4c64]",children:[a?e.jsx(Ht,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(si,{className:"h-4 w-4 mr-1"}),"Use this recording"]}),e.jsx($,{type:"button",size:"sm",variant:"outline",onClick:()=>{d(null),C()},children:"Re-record"})]}),e.jsx($,{type:"button",size:"sm",variant:"ghost",onClick:T,children:"Cancel"})]})]})]})}function a6t(){const{user:s}=_s(),t=ts(),n=ht({queryKey:["booking-settings",s==null?void 0:s.id],queryFn:async()=>{const{data:y,error:b}=await U.from("agent_booking_settings").select("*").eq("user_id",s.id).maybeSingle();if(b)throw b;return y},enabled:!!s}),r=ht({queryKey:["booking-types",s==null?void 0:s.id],queryFn:async()=>{const{data:y,error:b}=await U.from("agent_booking_types").select("*").eq("user_id",s.id).order("sort_order");if(b)throw b;return y},enabled:!!s}),a=ht({queryKey:["availability-slots",s==null?void 0:s.id],queryFn:async()=>{const{data:y,error:b}=await U.from("agent_availability_slots").select("*").eq("user_id",s.id).order("day_of_week").order("start_time");if(b)throw b;return y},enabled:!!s}),i=ht({queryKey:["blocked-dates",s==null?void 0:s.id],queryFn:async()=>{const{data:y,error:b}=await U.from("agent_blocked_dates").select("*").eq("user_id",s.id).order("blocked_date");if(b)throw b;return y},enabled:!!s}),l=ht({queryKey:["bookings",s==null?void 0:s.id],queryFn:async()=>{const{data:y,error:b}=await U.from("bookings").select("*, booking_type:agent_booking_types(*)").eq("agent_user_id",s.id).order("booking_date",{ascending:!1});if(b)throw b;return y},enabled:!!s}),o=yt({mutationFn:async()=>{const{data:y,error:b}=await U.from("agent_booking_settings").insert({user_id:s.id,slug:""}).select().single();if(b)throw b;const v=[{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 U.from("agent_booking_types").insert(v.map(T=>({...T,user_id:s.id})));if(N)throw N;const C=[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 U.from("agent_availability_slots").insert(C);if(A)throw A;return y},onSuccess:()=>{t.invalidateQueries({queryKey:["booking-settings"]}),t.invalidateQueries({queryKey:["booking-types"]}),t.invalidateQueries({queryKey:["availability-slots"]}),ae.success("Scheduler set up successfully!")},onError:y=>ae.error(y.message)}),c=yt({mutationFn:async y=>{const{error:b}=await U.from("agent_booking_settings").update(y).eq("user_id",s.id);if(b)throw b},onSuccess:()=>{t.invalidateQueries({queryKey:["booking-settings"]}),ae.success("Settings updated")},onError:y=>ae.error(y.message)}),d=yt({mutationFn:async y=>{const b={...y,user_id:s.id};if(y.id){const{error:v}=await U.from("agent_booking_types").update(b).eq("id",y.id);if(v)throw v}else{const{error:v}=await U.from("agent_booking_types").insert(b);if(v)throw v}},onSuccess:()=>{t.invalidateQueries({queryKey:["booking-types"]}),ae.success("Booking type saved")},onError:y=>ae.error(y.message)}),u=yt({mutationFn:async y=>{const{error:b}=await U.from("agent_booking_types").delete().eq("id",y);if(b)throw b},onSuccess:()=>{t.invalidateQueries({queryKey:["booking-types"]}),ae.success("Booking type deleted")},onError:y=>ae.error(y.message)}),h=yt({mutationFn:async y=>{const b={...y,user_id:s.id};if(y.id){const{error:v}=await U.from("agent_availability_slots").update(b).eq("id",y.id);if(v)throw v}else{const{error:v}=await U.from("agent_availability_slots").insert(b);if(v)throw v}},onSuccess:()=>{t.invalidateQueries({queryKey:["availability-slots"]})},onError:y=>ae.error(y.message)}),m=yt({mutationFn:async y=>{const{error:b}=await U.from("agent_availability_slots").delete().eq("id",y);if(b)throw b},onSuccess:()=>{t.invalidateQueries({queryKey:["availability-slots"]})},onError:y=>ae.error(y.message)}),p=yt({mutationFn:async y=>{const{blocked_date:b,end_date:v,reason:N}=y,C=D=>{const[B,q,W]=D.split("-").map(Number);return new Date(B,q-1,W)},A=D=>`${D.getFullYear()}-${String(D.getMonth()+1).padStart(2,"0")}-${String(D.getDate()).padStart(2,"0")}`,T=C(b),P=v?C(v):T;if(P366)throw new Error("Range too large (max 1 year)");const{error:I}=await U.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"]}),ae.success(y&&y>1?`${y} dates blocked`:"Date blocked")},onError:y=>ae.error(y.message)}),x=yt({mutationFn:async y=>{const{error:b}=await U.from("agent_blocked_dates").delete().eq("id",y);if(b)throw b},onSuccess:()=>{t.invalidateQueries({queryKey:["blocked-dates"]})},onError:y=>ae.error(y.message)}),g=yt({mutationFn:async({id:y,reason:b})=>{const{error:v}=await U.from("bookings").update({status:"cancelled",cancelled_at:new Date().toISOString(),cancel_reason:b}).eq("id",y);if(v)throw v;await U.functions.invoke("agent-booking",{body:{action:"cancel",booking_id:y}}).catch(N=>console.error("Google calendar cleanup failed:",N))},onSuccess:()=>{t.invalidateQueries({queryKey:["bookings"]}),ae.success("Booking cancelled")},onError:y=>ae.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:x,cancelBooking:g}}const Kot=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"];function i6t({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=Kot.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(_e,{children:[e.jsxs(Bt,{children:[e.jsxs(Ut,{className:"flex items-center gap-2",children:[e.jsx(Hr,{className:"h-5 w-5"}),"Weekly Availability"]}),e.jsx(vr,{children:"Set your available hours for each day"})]}),e.jsx(Oe,{className:"space-y-2",children:Kot.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(x=>{var g,y;return e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(be,{type:"time",className:"w-28 h-8 text-sm",defaultValue:(g=x.start_time)==null?void 0:g.slice(0,5),onBlur:b=>t({id:x.id,start_time:b.target.value})}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"to"}),e.jsx(be,{type:"time",className:"w-28 h-8 text-sm",defaultValue:(y=x.end_time)==null?void 0:y.slice(0,5),onBlur:b=>t({id:x.id,end_time:b.target.value})}),e.jsx(Tn,{checked:x.is_active,onCheckedChange:b=>t({id:x.id,is_active:b})}),e.jsx($,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:()=>n(x.id),children:e.jsx(Pn,{className:"h-3.5 w-3.5 text-muted-foreground"})})]},x.id)}),r===m?e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(be,{type:"time",className:"w-28 h-8 text-sm",value:i,onChange:x=>l(x.target.value)}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"to"}),e.jsx(be,{type:"time",className:"w-28 h-8 text-sm",value:o,onChange:x=>c(x.target.value)}),e.jsx($,{size:"sm",className:"h-8",onClick:u,children:"Add"}),e.jsx($,{variant:"ghost",size:"sm",className:"h-8",onClick:()=>a(null),children:"Cancel"})]}):e.jsxs($,{variant:"ghost",size:"sm",className:"h-7 text-xs text-muted-foreground",onClick:()=>a(m),children:[e.jsx(sn,{className:"h-3 w-3 mr-1"})," Add hours"]})]})]},h)})})]})}function Yot(s){const[t,n,r]=s.split("-").map(Number);return Hs(new Date(t,n-1,r),"MMM d, yyyy")}function S4s(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 o6t({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(_e,{children:[e.jsxs(Bt,{className:"flex flex-row items-center justify-between",children:[e.jsxs("div",{children:[e.jsxs(Ut,{className:"flex items-center gap-2",children:[e.jsx(xz,{className:"h-5 w-5"}),"Blocked Dates"]}),e.jsx(vr,{children:"Block a single day or a full date range (vacations, holidays, etc.)"})]}),e.jsxs($,{size:"sm",variant:"outline",onClick:()=>a(!0),children:[e.jsx(sn,{className:"h-4 w-4 mr-1"})," Block Dates"]})]}),e.jsxs(Oe,{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(be,{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(be,{type:"date",value:o,min:i||void 0,onChange:m=>c(m.target.value),className:"w-40",placeholder:"Optional"})]}),e.jsx(be,{placeholder:"Reason (optional)",value:d,onChange:m=>u(m.target.value),className:"flex-1 min-w-[180px]"}),e.jsx($,{size:"sm",onClick:h,children:"Add"}),e.jsx($,{size:"sm",variant:"ghost",onClick:()=>a(!1),children:"Cancel"})]}),s.length===0?e.jsx("p",{className:"text-sm text-muted-foreground text-center py-4",children:"No blocked dates"}):e.jsx("div",{className:"flex flex-wrap gap-2",children:S4s(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:[Yot(m.start),m.end!==m.start&&` – ${Yot(m.end)}`]}),m.ids.length>1&&e.jsxs("span",{className:"text-xs text-muted-foreground",children:["(",m.ids.length," days)"]}),m.reason&&e.jsxs("span",{className:"text-muted-foreground",children:["(",m.reason,")"]}),e.jsx("button",{onClick:()=>m.ids.forEach(n),className:"ml-1 text-muted-foreground hover:text-destructive",children:e.jsx(pr,{className:"h-3.5 w-3.5"})})]},m.ids[0]))})]})]})}function C4s(){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}=a6t(),[p,x]=j.useState("1-on-1 Coaching Session"),[g,y]=j.useState(45),b=j.useMemo(()=>t.filter(N=>N.is_coaching_only),[t]);if(a)return e.jsx(_e,{children:e.jsxs(Oe,{className:"p-6 flex items-center gap-2 text-muted-foreground",children:[e.jsx(Ht,{className:"h-4 w-4 animate-spin"})," Loading your calendar…"]})});if(!s)return e.jsxs(_e,{children:[e.jsxs(Bt,{children:[e.jsxs(Ut,{className:"flex items-center gap-2",children:[e.jsx(Xu,{className:"h-5 w-5"})," Coaching calendar"]}),e.jsx(vr,{children:"Set up your scheduler once, then open availability for the members assigned to you."})]}),e.jsx(Oe,{children:e.jsxs($,{onClick:()=>i.mutate(),disabled:i.isPending,children:[i.isPending&&e.jsx(Ht,{className:"h-4 w-4 mr-2 animate-spin"}),"Set up my calendar"]})})]});const v=()=>{p.trim()&&(o.mutate({name:p.trim(),description:"Private coaching session",duration_minutes:g,color:"#406E71",icon:"Video",is_active:!0,qualification_enabled:!1,is_coaching_only:!0,sort_order:99}),x("1-on-1 Coaching Session"),y(45))};return e.jsxs("div",{className:"space-y-4",children:[e.jsxs(_e,{children:[e.jsxs(Bt,{children:[e.jsxs(Ut,{className:"flex items-center gap-2",children:[e.jsx(Xr,{className:"h-5 w-5"})," Coaching session types"]}),e.jsx(vr,{children:"Only assigned members can book these. They stay hidden from your public booking page."})]}),e.jsxs(Oe,{className:"space-y-3",children:[b.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."}):b.map(N=>e.jsxs("div",{className:"flex flex-wrap items-center gap-3 rounded-lg border p-3",children:[e.jsx(be,{className:"h-9 max-w-[240px]",defaultValue:N.name,onBlur:C=>C.target.value!==N.name&&o.mutate({id:N.id,name:C.target.value})}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(be,{type:"number",min:10,max:240,step:5,className:"h-9 w-20",defaultValue:N.duration_minutes,onBlur:C=>o.mutate({id:N.id,duration_minutes:parseInt(C.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(Tn,{checked:N.is_active,onCheckedChange:C=>o.mutate({id:N.id,is_active:C})}),e.jsx("span",{className:"text-sm text-muted-foreground",children:N.is_active?"Bookable":"Paused"})]}),e.jsx($e,{variant:"secondary",children:"Coaching only"}),e.jsx($,{variant:"ghost",size:"sm",className:"ml-auto h-8 w-8 p-0",onClick:async()=>{await Yi({title:"Delete session type?",description:`"${N.name}" will no longer be bookable.`,confirmText:"Delete",destructive:!0})&&c.mutate(N.id)},children:e.jsx(Pn,{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(se,{className:"text-xs",children:"New session type"}),e.jsx(be,{value:p,onChange:N=>x(N.target.value),className:"h-9"})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-xs",children:"Minutes"}),e.jsx(be,{type:"number",min:10,max:240,step:5,className:"h-9 w-24",value:g,onChange:N=>y(parseInt(N.target.value)||30)})]}),e.jsxs($,{onClick:v,disabled:o.isPending,children:[e.jsx(sn,{className:"h-4 w-4 mr-1"})," Add"]})]})]})]}),e.jsx(i6t,{slots:n,onSave:N=>d.mutate(N),onDelete:N=>u.mutate(N)}),e.jsx(o6t,{blockedDates:r,onAdd:N=>h.mutate(N),onRemove:N=>m.mutate(N)}),e.jsxs(_e,{children:[e.jsxs(Bt,{children:[e.jsx(Ut,{children:"Scheduling rules"}),e.jsx(vr,{children:"Applies to coaching bookings on your calendar."})]}),e.jsxs(Oe,{className:"grid gap-4 sm:grid-cols-3",children:[e.jsxs("div",{children:[e.jsx(se,{className:"text-xs",children:"Buffer between sessions (min)"}),e.jsx(be,{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(se,{className:"text-xs",children:"Minimum notice (hours)"}),e.jsx(be,{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(se,{className:"text-xs",children:"Bookable up to (days out)"}),e.jsx(be,{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 sG(s,t){const n=s==="agent"?"agent-google-calendar":"coach-google-calendar",{data:r,error:a}=await U.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 l6t(s=!0,t="coach"){const n=ts(),r=ht({queryKey:["google-calendar-connection",t],enabled:s,queryFn:async()=>await sG(t,{action:"status"})}),a=()=>n.invalidateQueries({queryKey:["google-calendar-connection",t]}),i=yt({mutationFn:async()=>{const d=await sG(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:()=>sG(t,{action:"disconnect"}),onSuccess:a}),o=yt({mutationFn:d=>sG(t,{action:"settings",...d}),onSuccess:a}),c=yt({mutationFn:()=>sG(t,{action:"refresh_calendars"}),onSuccess:a});return{status:r,connect:i,disconnect:l,updateSettings:o,refreshCalendars:c}}function c6t({scope:s="coach"}){const{status:t,connect:n,disconnect:r,updateSettings:a,refreshCalendars:i}=l6t(!0,s),l=s==="agent";j.useEffect(()=>{const d=new URLSearchParams(window.location.search),u=d.get("google_calendar");if(!u)return;u==="connected"?(ae.success("Google Calendar connected"),t.refetch()):ae.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(_e,{children:[e.jsx(Bt,{children:e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{children:[e.jsxs(Ut,{className:"flex items-center gap-2",children:[e.jsx(gy,{className:"h-5 w-5"})," Google Calendar"]}),e.jsx(vr,{children:l?"Hide times you're already booked on Google, and push every new booking straight onto your calendar.":"Hide times you're already booked on Google, and push new coaching sessions straight onto your calendar."})]}),(o==null?void 0:o.connected)&&e.jsxs($e,{className:"bg-emerald-600 hover:bg-emerald-600 shrink-0",children:[e.jsx(Fr,{className:"h-3.5 w-3.5 mr-1"})," Connected"]})]})}),e.jsxs(Oe,{className:"space-y-4",children:[t.isLoading&&e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(Ht,{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(xo,{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(xo,{className:"h-4 w-4 mt-0.5 text-amber-600 shrink-0"}),e.jsx("span",{children:"Google Calendar isn't switched on for LevelUp yet. Once an admin finishes the one-time Google setup, you'll be able to connect right here."})]}),(o==null?void 0:o.configured)&&!o.connected&&e.jsxs("div",{className:"space-y-3",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Not connected. Your availability comes only from the hours you set in LevelUp."}),e.jsxs($,{onClick:()=>n.mutate(void 0,{onSuccess:()=>ae.success("Google Calendar connected"),onError:d=>ae.error(d.message)}),disabled:n.isPending,className:"bg-[#406E71] hover:bg-[#2a4c64]",children:[n.isPending?e.jsx(Ht,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(gy,{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(se,{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(Tn,{checked:o.sync_enabled,onCheckedChange:d=>a.mutate({sync_enabled:d},{onError:u=>ae.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(se,{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(Tn,{checked:o.invite_guest!==!1,onCheckedChange:d=>a.mutate({invite_guest:d},{onError:u=>ae.error(u.message)})})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{className:"text-xs",children:"Calendar to use"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(vs,{value:o.selected_calendar_id||"primary",onValueChange:d=>a.mutate({calendar_id:d},{onError:u=>ae.error(u.message)}),children:[e.jsx(gs,{className:"h-9",children:e.jsx(bs,{placeholder:"Primary calendar"})}),e.jsxs(ys,{children:[e.jsx(Ye,{value:"primary",children:"Primary calendar"}),o.calendars.filter(d=>!d.primary).map(d=>e.jsx(Ye,{value:d.id,children:d.summary||d.id},d.id))]})]}),e.jsx($,{variant:"outline",size:"icon",className:"h-9 w-9 shrink-0",onClick:()=>i.mutate(void 0,{onSuccess:()=>ae.success("Calendars refreshed"),onError:d=>ae.error(d.message)}),disabled:i.isPending,children:e.jsx(Wi,{className:`h-4 w-4 ${i.isPending?"animate-spin":""}`})})]})]}),e.jsxs("div",{className:"flex flex-wrap gap-2 pt-1",children:[e.jsxs($,{variant:"outline",size:"sm",onClick:()=>n.mutate(void 0,{onSuccess:()=>ae.success("Google Calendar reconnected"),onError:d=>ae.error(d.message)}),disabled:n.isPending,children:[n.isPending?e.jsx(Ht,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(Wi,{className:"h-4 w-4 mr-2"}),"Reconnect"]}),e.jsxs($,{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:()=>ae.success("Google Calendar disconnected"),onError:u=>ae.error(u.message)})},children:[e.jsx(tY,{className:"h-4 w-4 mr-2"})," Disconnect"]})]})]})]})]})}function A4s(){const s=Vn(),{data:t,isLoading:n}=bee(),r=ts(),[a,i]=j.useState(""),[l,o]=j.useState(""),[c,d]=j.useState(""),[u,h]=j.useState(""),[m,p]=j.useState(""),[x,g]=j.useState(!1),[y,b]=j.useState([]),[v,N]=j.useState(""),[C,A]=j.useState(2),[T,P]=j.useState(!1);j.useEffect(()=>{if(!t)return;const q=t;i(q.slug||""),o(q.headline||""),d(q.bio||""),h(q.photo_url||""),p(q.intro_video_url||""),g(!!q.accepting_clients),b(q.specialties||[]),A(q.default_sessions_per_month??2)},[t]);const M=async()=>{if(!t)return;P(!0);const{error:q}=await U.from("coaches").update({slug:a.trim()||null,headline:l||null,bio:c||null,photo_url:u||null,intro_video_url:m||null,accepting_clients:x,specialties:y,default_sessions_per_month:C}).eq("id",t.id);if(P(!1),q)return ae.error(q.message);ae.success("Profile saved"),r.invalidateQueries({queryKey:["my-coach-profile"]})},I=()=>{const q=v.trim();if(q){if(y.includes(q))return N("");b([...y,q]),N("")}};if(n)return e.jsx(Ks,{title:"Coach Settings",children:e.jsx("div",{className:"p-8",children:"Loading…"})});if(!t)return e.jsx(Ks,{title:"Coach Settings",children:e.jsx("div",{className:"max-w-2xl mx-auto p-8 text-center text-muted-foreground",children:"You don't have a coach profile yet."})});const D=t,B=D.slug?`${window.location.origin}/coaches/${D.slug}`:null;return e.jsx(Ks,{title:"Coach Settings",children:e.jsxs("div",{className:"max-w-3xl mx-auto p-4 md:p-8 space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx($,{variant:"ghost",size:"icon",onClick:()=>s("/coaching"),children:e.jsx(ka,{className:"h-5 w-5"})}),e.jsx("h1",{className:"text-2xl font-bold",children:"Coach Profile"})]}),e.jsxs("div",{className:"flex gap-2",children:[B&&e.jsxs($,{variant:"outline",size:"sm",onClick:()=>window.open(B,"_blank"),children:[e.jsx(Tr,{className:"h-4 w-4 mr-1"})," View public"]}),e.jsxs($,{onClick:M,disabled:T,className:"bg-[#406E71] hover:bg-[#2a4c64]",children:[e.jsx(Jo,{className:"h-4 w-4 mr-1"})," ",T?"Saving…":"Save"]})]})]}),D.is_certified&&e.jsxs("div",{className:"rounded-lg border border-yellow-300/50 bg-yellow-50 dark:bg-yellow-950/20 px-4 py-3 text-sm",children:["✨ ",e.jsx("strong",{children:"LevelUp Certified"})," — Your profile displays a verified badge."]}),e.jsx(_e,{children:e.jsxs(Oe,{className:"p-6 space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between p-3 rounded-lg border bg-muted/30",children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:"Accepting new clients"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"When off, you're hidden from the public directory."})]}),e.jsx(Tn,{checked:x,onCheckedChange:g})]}),e.jsxs("div",{children:[e.jsx(se,{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(be,{value:a,onChange:q=>i(q.target.value.toLowerCase().replace(/[^a-z0-9-]/g,"")),placeholder:"your-name"})]})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Headline"}),e.jsx(be,{value:l,onChange:q=>o(q.target.value),placeholder:"e.g. Helping new agents close their first 10 deals",maxLength:140})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Bio"}),e.jsx(Is,{rows:6,value:c,onChange:q=>d(q.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(se,{children:"Profile photo"}),e.jsx(Wot,{kind:"photo",value:u,onChange:h})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Intro video"}),e.jsx(Wot,{kind:"video",value:m,onChange:p})]})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Specialties"}),e.jsx("div",{className:"flex flex-wrap gap-2 mb-2",children:y.map(q=>e.jsxs($e,{variant:"secondary",className:"gap-1",children:[q,e.jsx("button",{onClick:()=>b(y.filter(W=>W!==q)),children:e.jsx(pr,{className:"h-3 w-3"})})]},q))}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(be,{value:v,onChange:q=>N(q.target.value),placeholder:"Add a specialty…",onKeyDown:q=>{q.key==="Enter"&&(q.preventDefault(),I())}}),e.jsx($,{type:"button",variant:"outline",onClick:I,children:e.jsx(sn,{className:"h-4 w-4"})})]})]})]})}),e.jsx(_e,{children:e.jsxs(Oe,{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(se,{children:"Sessions each agent can book per month"}),e.jsx(be,{type:"number",min:1,max:31,value:C,onChange:q=>A(Math.max(1,parseInt(q.target.value)||1)),className:"max-w-[140px]"}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"You can override this for individual agents on their workspace page."})]}),e.jsx($,{variant:"outline",onClick:()=>s("/mission-control/scheduler"),children:"Open full Scheduler"})]})]})}),e.jsx(c6t,{}),e.jsx(C4s,{}),e.jsx(_e,{children:e.jsx(Oe,{className:"p-6",children:e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-lg font-semibold",children:"Packages & Stripe"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Manage your monetized packages on the Billing page."})]}),e.jsx($,{variant:"outline",onClick:()=>s("/coaching/billing"),children:"Go to Billing"})]})})}),e.jsx(E4s,{coachId:D.id})]})})}function E4s({coachId:s}){const[t,n]=j.useState("");ts();const{data:r=[],refetch:a}=ht({queryKey:["coach-invites",s],queryFn:async()=>{const{data:c}=await U.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 ae.error("Email required");const{error:d}=await U.from("coaching_invites").insert({coach_id:s,email:c});if(d)return ae.error(d.message);n(""),ae.success("Invite created"),a()},l=c=>{const d=`${window.location.origin}/auth?coach_invite=${c}`;navigator.clipboard.writeText(d),ae.success("Link copied")},o=async c=>{await Yi("Revoke this invite?")&&(await U.from("coaching_invites").delete().eq("id",c),a())};return e.jsx(_e,{children:e.jsxs(Oe,{className:"p-6 space-y-3",children:[e.jsxs("div",{children:[e.jsxs("h2",{className:"text-lg font-semibold flex items-center gap-2",children:[e.jsx(kc,{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(be,{placeholder:"agent@email.com",value:t,onChange:c=>n(c.target.value),onKeyDown:c=>c.key==="Enter"&&i()}),e.jsxs($,{onClick:i,children:[e.jsx(sn,{className:"h-4 w-4 mr-1"})," Create"]})]}),e.jsxs("div",{className:"space-y-2",children:[r.map(c=>e.jsxs("div",{className:"flex items-center gap-2 p-3 border rounded-lg",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"font-medium truncate",children:c.email}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:[c.status," · expires ",new Date(c.expires_at).toLocaleDateString()]})]}),e.jsx($,{variant:"ghost",size:"icon",onClick:()=>l(c.token),children:e.jsx(Ca,{className:"h-4 w-4"})}),e.jsx($,{variant:"ghost",size:"icon",onClick:()=>o(c.id),children:e.jsx(Pn,{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 T4s="google_calendar";function M4s(){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:T4s,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"}})();U.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(Ht,{className:"h-6 w-6 animate-spin mx-auto text-[#406E71]"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:s})]})})}const Dne=[{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 L4s(){const s=Vn(),t=ts(),{data:n,isLoading:r}=bee(),[a,i]=j.useState("pending"),[l,o]=j.useState(""),[c,d]=j.useState(null),[u,h]=j.useState(!1),[m,p]=j.useState(""),[x,g]=j.useState(!1),[y,b]=j.useState(""),{data:v=[],isLoading:N}=ht({queryKey:["coaching-waitlist",n==null?void 0:n.id],enabled:!!(n!=null&&n.id),queryFn:async()=>{const{data:D,error:B}=await U.from("coaching_waitlist").select("*").eq("coach_id",n.id).order("created_at",{ascending:!1});if(B)throw B;return D||[]}}),C=j.useMemo(()=>v.filter(D=>{if(a!=="all"&&D.status!==a)return!1;if(l){const B=l.toLowerCase();return(D.name||"").toLowerCase().includes(B)||(D.email||"").toLowerCase().includes(B)||(D.brokerage||"").toLowerCase().includes(B)}return!0}),[v,a,l]),A=j.useMemo(()=>{const D={all:v.length};for(const B of Dne)D[B.value]=0;for(const B of v)D[B.status]=(D[B.status]||0)+1;return D},[v]),T=async(D,B)=>{const{error:q}=await U.from("coaching_waitlist").update(B).eq("id",D);if(q)return ae.error(q.message);t.invalidateQueries({queryKey:["coaching-waitlist",n==null?void 0:n.id]}),(c==null?void 0:c.id)===D&&d(W=>({...W,...B}))},P=async D=>{if(!await Yi("Remove this person from the waitlist?"))return;const{error:B}=await U.from("coaching_waitlist").delete().eq("id",D);if(B)return ae.error(B.message);ae.success("Removed"),t.invalidateQueries({queryKey:["coaching-waitlist",n==null?void 0:n.id]}),d(null)},M=async()=>{if(!c)return;const{data:D,error:B}=await U.functions.invoke("coaching-waitlist-invite",{body:{waitlistId:c.id,message:m}});if(B||D!=null&&D.error)return ae.error((D==null?void 0:D.error)||(B==null?void 0:B.message)||"Could not send invite");ae.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:D,error:B}=await U.functions.invoke("coaching-waitlist-invite",{body:{coachId:n.id,notifyAll:!0,message:y}});if(B||D!=null&&D.error)return ae.error((D==null?void 0:D.error)||(B==null?void 0:B.message)||"Could not notify");ae.success(`Notified ${(D==null?void 0:D.count)||0} agents`),g(!1),b(""),t.invalidateQueries({queryKey:["coaching-waitlist",n==null?void 0:n.id]})};return r?e.jsx(Ks,{title:"Waitlist",children:e.jsx("div",{className:"p-8",children:"Loading…"})}):n?e.jsxs(Ks,{title:"Coaching Waitlist",children:[e.jsxs("div",{className:"p-4 md:p-8 max-w-7xl mx-auto space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3 flex-wrap",children:[e.jsxs("div",{children:[e.jsxs($,{variant:"ghost",size:"sm",className:"mb-2 -ml-2",onClick:()=>s("/coaching"),children:[e.jsx(ka,{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(v0,{className:"h-6 w-6 text-[#406E71]"}),"Waitlist"]}),e.jsx("p",{className:"text-muted-foreground text-sm mt-1",children:"Agents waiting for a spot to open up with you."})]}),e.jsxs($,{variant:"outline",onClick:()=>g(!0),disabled:!A.pending,title:A.pending?"":"No pending applicants",children:[e.jsx(Sz,{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,")"]}),Dne.map(D=>e.jsxs("button",{onClick:()=>i(D.value),className:`px-3 py-1.5 rounded-full text-sm border ${a===D.value?"bg-[#406E71] text-white border-[#406E71]":"bg-white hover:bg-muted"}`,children:[D.label," (",A[D.value]||0,")"]},D.value))]}),e.jsx(be,{placeholder:"Search by name, email, brokerage…",value:l,onChange:D=>o(D.target.value),className:"max-w-md"}),N?e.jsx("div",{className:"text-muted-foreground",children:"Loading…"}):C.length===0?e.jsx(_e,{children:e.jsx(Oe,{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:C.map(D=>{const B=Dne.find(q=>q.value===D.status);return e.jsx(_e,{className:"cursor-pointer hover:shadow-md transition-shadow",onClick:()=>d(D),children:e.jsxs(Oe,{className:"p-4",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"font-semibold truncate",children:D.name}),e.jsx("div",{className:"text-xs text-muted-foreground truncate",children:D.email}),D.brokerage&&e.jsx("div",{className:"text-xs text-muted-foreground truncate",children:D.brokerage})]}),e.jsx($e,{className:(B==null?void 0:B.tone)||"",children:(B==null?void 0:B.label)||D.status})]}),e.jsxs("div",{className:"flex items-center justify-between mt-3 text-xs text-muted-foreground",children:[e.jsxs("span",{children:["Joined ",fc(new Date(D.created_at),{addSuffix:!0})]}),D.preferred_package&&e.jsxs("span",{className:"truncate ml-2",children:["→ ",D.preferred_package]})]})]})},D.id)})})]}),e.jsx(Os,{open:!!c,onOpenChange:D=>!D&&d(null),children:e.jsx(Rs,{className:"max-w-lg max-h-[90vh] overflow-y-auto",children:c&&e.jsxs(e.Fragment,{children:[e.jsxs(Us,{children:[e.jsx(zs,{children:c.name}),e.jsxs(Sr,{children:["Joined ",fc(new Date(c.created_at),{addSuffix:!0})]})]}),e.jsxs("div",{className:"space-y-3 text-sm",children:[e.jsx(nG,{label:"Email",value:c.email}),e.jsx(nG,{label:"Phone",value:c.phone}),e.jsx(nG,{label:"Brokerage",value:c.brokerage}),e.jsx(nG,{label:"Years",value:c.years_in_business}),e.jsx(nG,{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 ",fc(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(vs,{value:c.status,onValueChange:D=>T(c.id,{status:D}),children:[e.jsx(gs,{children:e.jsx(bs,{})}),e.jsx(ys,{children:Dne.map(D=>e.jsx(Ye,{value:D.value,children:D.label},D.value))})]})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-xs font-medium text-muted-foreground mb-1",children:"Private notes"}),e.jsx(Is,{rows:3,defaultValue:c.coach_notes||"",onBlur:D=>{D.target.value!==(c.coach_notes||"")&&T(c.id,{coach_notes:D.target.value})}})]})]}),e.jsxs(kr,{className:"flex-wrap gap-2",children:[e.jsxs($,{variant:"outline",className:"text-destructive",onClick:()=>P(c.id),children:[e.jsx(Pn,{className:"h-4 w-4 mr-1"})," Remove"]}),e.jsx($,{variant:"outline",asChild:!0,children:e.jsxs("a",{href:`mailto:${c.email}`,children:[e.jsx(nn,{className:"h-4 w-4 mr-1"})," Email directly"]})}),e.jsxs($,{className:"bg-[#406E71] hover:bg-[#2a4c64]",onClick:()=>{p(""),h(!0)},children:[e.jsx(Br,{className:"h-4 w-4 mr-1"})," Invite to subscribe"]})]})]})})}),e.jsx(Os,{open:u,onOpenChange:h,children:e.jsxs(Rs,{children:[e.jsxs(Us,{children:[e.jsx(zs,{children:"Invite to subscribe"}),e.jsxs(Sr,{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(Is,{rows:4,placeholder:"Hey! A spot just opened up and I'd love to work with you…",value:m,onChange:D=>p(D.target.value)})]}),e.jsxs(kr,{children:[e.jsx($,{variant:"outline",onClick:()=>h(!1),children:"Cancel"}),e.jsxs($,{className:"bg-[#406E71] hover:bg-[#2a4c64]",onClick:M,children:[e.jsx(Br,{className:"h-4 w-4 mr-1"})," Send invite"]})]})]})}),e.jsx(Os,{open:x,onOpenChange:g,children:e.jsxs(Rs,{children:[e.jsxs(Us,{children:[e.jsx(zs,{children:"Notify all pending applicants"}),e.jsx(Sr,{children:"Send everyone with status “Pending” an email letting them know spots are opening up. They'll each be marked “Invited”."})]}),e.jsx(Is,{rows:4,placeholder:"Good news — I just opened up new coaching spots…",value:y,onChange:D=>b(D.target.value)}),e.jsxs(kr,{children:[e.jsx($,{variant:"outline",onClick:()=>g(!1),children:"Cancel"}),e.jsxs($,{className:"bg-[#406E71] hover:bg-[#2a4c64]",onClick:I,children:[e.jsx(Sz,{className:"h-4 w-4 mr-1"})," Send to ",A.pending||0," agents"]})]})]})})]}):e.jsx(Ks,{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 nG({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 P4s(){const{data:s=[],isLoading:t}=ht({queryKey:["coaches-directory"],queryFn:async()=>{const{data:n,error:r}=await U.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 U.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(dn,{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(Fr,{className:"h-4 w-4 text-yellow-300"})," Vetted by LevelUp"]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(pl,{className:"h-4 w-4 text-yellow-300"})," Top-producer experience"]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Qa,{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(Wn,{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(dn,{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(ni,{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(dn,{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(Fr,{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(Fr,{className:"h-4 w-4 text-yellow-300"})," Recurring revenue"]}),e.jsxs("span",{className:"inline-flex items-center gap-1.5",children:[e.jsx(Fr,{className:"h-4 w-4 text-yellow-300"})," Certified status"]})]})]}),e.jsxs("div",{className:"mt-8 md:mt-0",children:[e.jsxs(Wn,{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(ni,{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 I4s=tk({name:rl().trim().min(1,"Name required").max(120),email:rl().trim().email("Invalid email").max(255),phone:rl().trim().max(40).optional().or(Sx("")),brokerage:rl().trim().max(160).optional().or(Sx("")),years_in_business:rl().max(40).optional().or(Sx("")),biggest_challenge:rl().trim().max(1e3).optional().or(Sx("")),preferred_package:rl().max(120).optional().or(Sx("")),message:rl().trim().max(1500).optional().or(Sx(""))});function D4s({open:s,onOpenChange:t,coachId:n,coachName:r,packages:a=[]}){const{user:i}=_s(),[l,o]=j.useState(!1),[c,d]=j.useState({name:"",email:(i==null?void 0:i.email)||"",phone:"",brokerage:"",years_in_business:"",biggest_challenge:"",preferred_package:"",message:""}),u=(m,p)=>d(x=>({...x,[m]:p})),h=async()=>{var x;const m=I4s.safeParse(c);if(!m.success){ae.error(((x=m.error.issues[0])==null?void 0:x.message)||"Please check your entries");return}o(!0);const{error:p}=await U.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){ae.error(p.message||"Could not join waitlist");return}ae.success(`You're on the waitlist${r?` for ${r}`:""}. We'll be in touch when a spot opens.`),t(!1),d({...c,biggest_challenge:"",message:""})};return e.jsx(Os,{open:s,onOpenChange:t,children:e.jsxs(Rs,{className:"max-w-lg max-h-[90vh] overflow-y-auto",children:[e.jsxs(Us,{children:[e.jsxs(zs,{children:["Join the waitlist",r?` — ${r}`:""]}),e.jsx(Sr,{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(se,{children:"Name *"}),e.jsx(be,{value:c.name,onChange:m=>u("name",m.target.value)})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Email *"}),e.jsx(be,{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(se,{children:"Phone"}),e.jsx(be,{value:c.phone,onChange:m=>u("phone",m.target.value)})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Brokerage"}),e.jsx(be,{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(se,{children:"Years in business"}),e.jsxs(vs,{value:c.years_in_business,onValueChange:m=>u("years_in_business",m),children:[e.jsx(gs,{children:e.jsx(bs,{placeholder:"Select…"})}),e.jsxs(ys,{children:[e.jsx(Ye,{value:"< 1 year",children:"Less than 1 year"}),e.jsx(Ye,{value:"1-3 years",children:"1-3 years"}),e.jsx(Ye,{value:"4-7 years",children:"4-7 years"}),e.jsx(Ye,{value:"8-15 years",children:"8-15 years"}),e.jsx(Ye,{value:"15+ years",children:"15+ years"})]})]})]}),a.length>0&&e.jsxs("div",{children:[e.jsx(se,{children:"Preferred package"}),e.jsxs(vs,{value:c.preferred_package,onValueChange:m=>u("preferred_package",m),children:[e.jsx(gs,{children:e.jsx(bs,{placeholder:"Any"})}),e.jsx(ys,{children:a.map(m=>e.jsx(Ye,{value:m.name,children:m.name},m.id))})]})]})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Biggest challenge right now"}),e.jsx(Is,{rows:2,value:c.biggest_challenge,onChange:m=>u("biggest_challenge",m.target.value)})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Anything else?"}),e.jsx(Is,{rows:2,value:c.message,onChange:m=>u("message",m.target.value)})]})]}),e.jsxs(kr,{children:[e.jsx($,{variant:"outline",onClick:()=>t(!1),disabled:l,children:"Cancel"}),e.jsx($,{className:"bg-[#406E71] hover:bg-[#2a4c64]",onClick:h,disabled:l,children:l?"Submitting…":"Join Waitlist"})]})]})})}function R4s(){var g;const{slug:s}=Vi(),t=Vn(),{user:n}=_s(),[r,a]=j.useState(null),[i,l]=j.useState(!1),{data:o,isLoading:c}=ht({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||""),b=U.from("coaches").select("*"),{data:v}=y?await b.eq("id",s).maybeSingle():await b.eq("slug",s).maybeSingle();if(!v)return null;const[{data:N},{data:C}]=await Promise.all([U.from("profiles").select("id, name, avatar_url").eq("id",v.user_id).maybeSingle(),U.from("coaching_packages").select("*").eq("coach_id",v.id).eq("is_active",!0).order("sort_order")]);return{coach:v,profile:N,packages:C||[]}}}),d=async y=>{if(!n){ae.error("Please sign in to subscribe"),t(`/auth?redirect=/coaches/${s}`);return}a(y);const{data:b,error:v}=await U.functions.invoke("create-coaching-checkout",{body:{packageId:y}});if(a(null),v||b!=null&&b.error){ae.error((b==null?void 0:b.error)||(v==null?void 0:v.message)||"Checkout failed");return}b!=null&&b.url&&(window.location.href=b.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,x=(y,b)=>{const v=(y/100).toLocaleString("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0});return b==="one_time"?v:`${v} / ${b}`};return e.jsxs("div",{className:"min-h-screen bg-background",children:[e.jsx("div",{className:"bg-gradient-to-br from-[#2a4c64] to-[#406E71] text-white",children:e.jsxs("div",{className:"max-w-5xl mx-auto px-4 py-12 md:py-20",children:[e.jsxs($,{variant:"ghost",size:"sm",className:"text-white/80 hover:text-white hover:bg-white/10 mb-6",onClick:()=>t("/coaches"),children:[e.jsx(ka,{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(ki,{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(dn,{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}),((g=p.specialties)==null?void 0:g.length)>0&&e.jsx("div",{className:"flex flex-wrap gap-2 mt-4",children:p.specialties.map(y=>e.jsx($e,{className:"bg-white/15 text-white border-white/20",children:y},y))})]})]})]})}),e.jsxs("div",{className:"max-w-5xl mx-auto px-4 py-12 grid grid-cols-1 md:grid-cols-3 gap-8",children:[e.jsxs("div",{className:"md:col-span-2 space-y-6",children:[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(h4s,{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(_e,{children:e.jsx(Oe,{className:"p-6 text-sm text-muted-foreground text-center",children:"No packages available yet."})}):m.map(y=>{const b=y.accepting_clients===!1;return e.jsx(_e,{className:`border-2 transition-colors ${b?"border-amber-200 bg-amber-50/30":"hover:border-[#406E71]"}`,children:e.jsxs(Oe,{className:"p-5",children:[e.jsxs("div",{className:"flex items-start justify-between gap-2",children:[e.jsx("h3",{className:"font-semibold text-lg",children:y.name}),b&&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:x(y.price_cents,y.billing_interval)}),b?e.jsxs("div",{className:"mt-4 space-y-2",children:[e.jsx("div",{className:"rounded-md bg-amber-100 border border-amber-200 text-amber-900 px-3 py-2.5 text-sm text-center",children:"Currently not accepting new clients."}),e.jsxs($,{variant:"outline",className:"w-full",onClick:()=>l(!0),children:[e.jsx(v0,{className:"h-4 w-4 mr-1"})," Join Waitlist"]})]}):e.jsxs($,{className:"w-full mt-4 bg-[#406E71] hover:bg-[#2a4c64]",onClick:()=>d(y.id),disabled:r===y.id,children:[r===y.id?"Loading…":"Get Started",e.jsx(oa,{className:"h-4 w-4 ml-1"})]})]})},y.id)}),e.jsx("p",{className:"text-xs text-muted-foreground text-center",children:"Secure checkout powered by Stripe."}),e.jsxs($,{variant:"ghost",size:"sm",className:"w-full text-muted-foreground",onClick:()=>l(!0),children:[e.jsx(v0,{className:"h-4 w-4 mr-1"})," Join the waitlist instead"]})]})]}),e.jsx(D4s,{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 O4s=tk({full_name:rl().trim().min(2,"Please enter your full name").max(100),email:rl().trim().email("Enter a valid email").max(255),phone:rl().trim().max(40).optional().or(Sx("")),brokerage:rl().trim().max(150).optional().or(Sx("")),years_experience:rl().trim().max(40).optional().or(Sx("")),specialties:rl().trim().max(500).optional().or(Sx("")),why_coach:rl().trim().min(20,"Tell us a bit more — at least 20 characters").max(2e3),results_story:rl().trim().max(2e3).optional().or(Sx("")),website_url:rl().trim().max(300).optional().or(Sx("")),linkedin_url:rl().trim().max(300).optional().or(Sx(""))});function F4s(){const s=Vn(),[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=O4s.safeParse(i);if(!u.success){const p=(m=Object.values(u.error.flatten().fieldErrors)[0])==null?void 0:m[0];return ae.error(p||"Please check the form and try again")}n(!0);const{error:h}=await U.from("coach_applications").insert(u.data);if(n(!1),h)return ae.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(Fr,{className:"h-10 w-10"})}),e.jsx("h1",{className:"text-4xl md:text-5xl font-bold mb-4",children:"Application received."}),e.jsx("p",{className:"text-white/80 text-lg leading-relaxed mb-8",children:"Thank you for applying to the LevelUp Coaching program. Our team personally reviews every application — we'll be in touch within 5 business days."}),e.jsx($,{onClick:()=>s("/coaches"),className:"bg-yellow-300 text-[#1c3447] hover:bg-yellow-200 font-semibold",children:"Browse our coaches"})]})}):e.jsxs("div",{className:"min-h-screen bg-white",children:[e.jsxs("section",{className:"relative overflow-hidden bg-gradient-to-br from-[#1c3447] via-[#2a4c64] to-[#406E71] text-white",children:[e.jsx("div",{className:"absolute -top-32 -left-24 h-96 w-96 rounded-full bg-[#5a9ea2]/20 blur-3xl"}),e.jsx("div",{className:"absolute -bottom-32 -right-24 h-96 w-96 rounded-full bg-yellow-400/10 blur-3xl"}),e.jsx("div",{className:"absolute inset-0 opacity-[0.04]",style:{backgroundImage:"radial-gradient(white 1px, transparent 1px)",backgroundSize:"22px 22px"}}),e.jsxs("div",{className:"relative max-w-5xl mx-auto px-4 py-16 md:py-20",children:[e.jsxs(Wn,{to:"/coaches",className:"inline-flex items-center gap-2 text-white/70 hover:text-white text-sm mb-8",children:[e.jsx(ka,{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(dn,{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(qn,{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(Il,{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(pu,{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(Fr,{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(pl,{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(Qa,{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(Fk,{label:"Full name *",children:e.jsx(be,{value:i.full_name,onChange:d=>o("full_name",d.target.value),required:!0,maxLength:100})}),e.jsx(Fk,{label:"Email *",children:e.jsx(be,{type:"email",value:i.email,onChange:d=>o("email",d.target.value),required:!0,maxLength:255})}),e.jsx(Fk,{label:"Phone",children:e.jsx(be,{value:i.phone,onChange:d=>o("phone",d.target.value),maxLength:40})}),e.jsx(Fk,{label:"Current brokerage",children:e.jsx(be,{value:i.brokerage,onChange:d=>o("brokerage",d.target.value),maxLength:150})}),e.jsx(Fk,{label:"Years in real estate",children:e.jsx(be,{value:i.years_experience,onChange:d=>o("years_experience",d.target.value),placeholder:"e.g. 8",maxLength:40})}),e.jsx(Fk,{label:"Coaching specialties",children:e.jsx(be,{value:i.specialties,onChange:d=>o("specialties",d.target.value),placeholder:"Lead gen, listings, luxury, teams…",maxLength:500})}),e.jsx(Fk,{label:"Website",children:e.jsx(be,{value:i.website_url,onChange:d=>o("website_url",d.target.value),placeholder:"https://",maxLength:300})}),e.jsx(Fk,{label:"LinkedIn",children:e.jsx(be,{value:i.linkedin_url,onChange:d=>o("linkedin_url",d.target.value),placeholder:"https://linkedin.com/in/",maxLength:300})})]}),e.jsx(Fk,{label:"Why do you want to coach with LevelUp? *",children:e.jsx(Is,{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(Fk,{label:"Tell us about results you've created — for yourself or other agents.",children:e.jsx(Is,{value:i.results_story,onChange:d=>o("results_story",d.target.value),rows:5,maxLength:2e3,placeholder:"Production numbers, agent breakthroughs, testimonials — anything that shows the impact you've had."})}),e.jsxs("div",{className:"flex flex-col sm:flex-row items-stretch sm:items-center gap-3 pt-2",children:[e.jsx($,{type:"submit",disabled:t,className:"bg-gradient-to-r from-[#406E71] to-[#2a4c64] hover:opacity-95 text-white font-semibold px-8 py-6 text-base flex-1 sm:flex-none",children:t?"Submitting…":"Submit application"}),e.jsx("p",{className:"text-xs text-slate-500",children:"We review every application within 5 business days."})]})]})]})]})}function Fk({label:s,children:t}){return e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{className:"text-sm font-semibold text-[#1c3447]",children:s}),t]})}const z4s="/assets/testimonial-avatar-1-BsCQFauB.jpg",B4s="/assets/testimonial-avatar-2-B6VPVc2t.jpg",$4s="/assets/testimonial-avatar-3-GuEFwYUE.jpg",U4s="/assets/testimonial-avatar-4-98iKMtkB.jpg",q4s="/assets/testimonial-avatar-5-ZsZfyxMX.jpg",V4s=[z4s,B4s,$4s,U4s,q4s],H4s=tk({name:rl().trim().min(2,"Name must be at least 2 characters").max(100),email:rl().trim().email("Please enter a valid email address").max(255),phone:rl().trim().min(10,"Please enter a valid phone number").max(20).optional().or(Sx("")),brokerage:rl().trim().max(200).optional().or(Sx(""))}),G4s=[{icon:Sh,title:"Academy Training",description:"Access a library of on-demand video training covering lead generation, marketing, technology, and more."},{icon:Rc,title:"300+ Templates",description:"Professional Canva templates for social media, flyers, postcards, and marketing materials."},{icon:ia,title:"Live Events",description:"Weekly live training sessions, workshops, and Q&A events with industry experts."},{icon:Ed,title:"Agent Community",description:"Connect with fellow agents, share wins, ask questions, and network in our private community."},{icon:Wr,title:"Resource Kits",description:"Downloadable toolkits with scripts, checklists, guides, and everything you need to close more deals."},{icon:Co,title:"Social Swag",description:"Fresh social media content and designs updated regularly to help you stand out online."}],W4s=[{icon:qn,title:"Contact Management",description:"Organize your sphere into relationship tiers—Top 25, Past Clients, Referral Partners, and more."},{icon:dn,title:"Smart TouchPlans",description:"Automated action plans that tell you exactly who to contact and how, based on relationship type."},{icon:ya,title:"One-Tap Actions",description:"Call, text, or email contacts directly with pre-written scripts tailored to each relationship."},{icon:np,title:"Birthday Alerts",description:"Never miss an important date—get reminders for birthdays and home anniversaries."},{icon:ai,title:"Pop-by Map",description:"See all your contacts on a map and plan efficient pop-by routes in your area."},{icon:ml,title:"Momentum Tracking",description:"Track your touch streaks, weekly goals, and relationship health scores."},{icon:fo,title:"Relationship Health",description:"Visual dashboard showing which contacts need attention based on last touch date."},{icon:ox,title:"Daily Action Cards",description:"Wake up to a prioritized list of exactly who to reach out to today."}],K4s=[{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."}],Y4s=()=>{const s=Vn(),[t,n]=j.useState(!1),[r,a]=j.useState({name:"",email:"",phone:"",brokerage:""}),[i,l]=j.useState({}),o=async c=>{var u,h;c.preventDefault(),l({});const d=H4s.safeParse(r);if(!d.success){const m={};d.error.issues.forEach(p=>{p.path[0]&&(m[p.path[0]]=p.message)}),l(m);return}n(!0);try{const m=typeof window<"u"&&localStorage.getItem("levelup_referral_code")||void 0,{data:p,error:x}=await U.functions.invoke("create-trial-signup",{body:{name:r.name.trim(),email:r.email.trim().toLowerCase(),phone:((u=r.phone)==null?void 0:u.trim())||void 0,brokerage:((h=r.brokerage)==null?void 0:h.trim())||void 0,referral_code:m}});if(x){console.error("Trial signup error:",x),ae.error(x.message||"Something went wrong. Please try again.");return}if(p!=null&&p.error){ae.error(p.error);return}ae.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(m){console.error("Trial signup error:",m),ae.error("Something went wrong. Please try again.")}finally{n(!1)}};return e.jsxs(e.Fragment,{children:[e.jsxs(Ul,{children:[e.jsx("title",{children:"Start Your Free 7-Day Trial | LevelUp Dashboard"}),e.jsx("meta",{name:"description",content:"Take LevelUp for a free 7-day test drive. No credit card required. The all-in-one platform for real estate agents and brokerages."}),e.jsx("meta",{property:"og:title",content:"Start Your Free 7-Day Trial | LevelUp"}),e.jsx("meta",{property:"og:description",content:"Take LevelUp for a free 7-day test drive. No credit card required."}),e.jsx("meta",{property:"og:type",content:"website"}),e.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("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:nSe,alt:"LevelUp",className:"h-8 md:h-10"})}),e.jsxs("div",{className:"flex items-center gap-2 md:gap-4",children:[e.jsx($,{variant:"ghost",className:"text-white/90 hover:text-white hover:bg-white/10 hidden sm:inline-flex",onClick:()=>{var c;return(c=document.getElementById("features"))==null?void 0:c.scrollIntoView({behavior:"smooth"})},children:"Features"}),e.jsx($,{onClick:()=>s("/auth"),className:"bg-white text-[#4a6b6d] hover:bg-gray-100 font-medium shadow-md",children:"Sign In"})]})]})}),e.jsxs("section",{className:"relative pt-24 pb-20 bg-gradient-to-br from-[#1e3a4c] via-[#2a4f5f] to-[#3d6b6b] overflow-hidden",children:[e.jsx("div",{className:"absolute inset-0 opacity-10",children:e.jsx("div",{className:"absolute inset-0 bg-[url('data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iNjAiIGhlaWdodD0iNjAiIHZpZXdCb3g9IjAgMCA2MCA2MCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj48ZyBmaWxsPSJub25lIiBmaWxsLXJ1bGU9ImV2ZW5vZGQiPjxnIGZpbGw9IiNmZmZmZmYiIGZpbGwtb3BhY2l0eT0iMC40Ij48cGF0aCBkPSJNMzYgMzRoLTJ2LTRoMnY0em0wLTZ2LTRoLTJ2NGgyem0tNiA2aC0ydi00aDJ2NHptMC02di00aC0ydjRoMnoiLz48L2c+PC9nPjwvc3ZnPg==')]"})}),e.jsx("div",{className:"container mx-auto px-4 relative",children:e.jsxs("div",{className:"grid lg:grid-cols-2 gap-12 items-center",children:[e.jsxs("div",{className:"space-y-8 text-center lg:text-left",children:[e.jsx("div",{className:"flex justify-center lg:justify-start",children:e.jsx("img",{alt:"LevelUp Consulting Group",className:"h-24 md:h-32 drop-shadow-lg",src:"/lovable-uploads/3a0c7ef9-9e79-411f-a9af-6f2a99e8bd7b.webp"})}),e.jsxs("div",{className:"inline-flex items-center gap-2 px-4 py-2 rounded-full bg-white/10 text-white text-sm font-medium",children:[e.jsx(dn,{className:"h-4 w-4 text-yellow-400"}),e.jsx("span",{children:"7-Day Free Trial • No Credit Card Required"})]}),e.jsxs("h1",{className:"text-3xl md:text-4xl lg:text-5xl font-bold text-white leading-tight font-sans",children:["Take LevelUp for a"," ",e.jsx("span",{className:"italic",children:"Free Test Drive"})]}),e.jsxs("p",{className:"text-lg md:text-xl text-white/80 max-w-xl mx-auto lg:mx-0 font-sans",children:["The tools you need to get it done.",e.jsx("br",{}),e.jsx("em",{children:"The platform you need to keep it going."})]}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-4 justify-center lg:justify-start",children:[e.jsxs("div",{className:"flex items-center gap-2 text-white/80",children:[e.jsx(Fr,{className:"h-5 w-5 text-green-400"}),e.jsx("span",{children:"No credit card required"})]}),e.jsxs("div",{className:"flex items-center gap-2 text-white/80",children:[e.jsx(Fr,{className:"h-5 w-5 text-green-400"}),e.jsx("span",{children:"Full access to all features"})]})]}),e.jsxs("div",{className:"flex items-center gap-4 justify-center lg:justify-start pt-4",children:[e.jsx("div",{className:"flex -space-x-3",children:V4s.map((c,d)=>e.jsx("img",{src:c,alt:`Agent ${d+1}`,className:"w-10 h-10 rounded-full border-2 border-white/20 object-cover"},d))}),e.jsxs("div",{children:[e.jsx("div",{className:"flex gap-0.5",children:[1,2,3,4,5].map(c=>e.jsx(Qa,{className:"h-4 w-4 fill-yellow-400 text-yellow-400"},c))}),e.jsx("p",{className:"text-sm text-white/60",children:"Trusted by 3,000+ agents"})]})]})]}),e.jsx("div",{className:"lg:pl-8",children:e.jsx(_e,{className:"bg-white shadow-2xl border-0",children:e.jsxs(Oe,{className:"p-8",children:[e.jsxs("div",{className:"text-center mb-8",children:[e.jsx("div",{className:"inline-flex items-center justify-center w-16 h-16 rounded-full bg-[#4a6b6d] mb-4",children:e.jsx(w0,{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(se,{htmlFor:"name",children:"Full Name *"}),e.jsx(be,{id:"name",type:"text",placeholder:"John Smith",value:r.name,onChange:c=>a({...r,name:c.target.value}),required:!0}),i.name&&e.jsx("p",{className:"text-sm text-destructive",children:i.name})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"email",children:"Email Address *"}),e.jsx(be,{id:"email",type:"email",placeholder:"john@example.com",value:r.email,onChange:c=>a({...r,email:c.target.value}),required:!0}),i.email&&e.jsx("p",{className:"text-sm text-destructive",children:i.email})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"phone",children:"Phone Number"}),e.jsx(be,{id:"phone",type:"tel",placeholder:"(555) 123-4567",value:r.phone,onChange:c=>a({...r,phone:c.target.value})}),i.phone&&e.jsx("p",{className:"text-sm text-destructive",children:i.phone})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"brokerage",children:"Brokerage Name"}),e.jsx(be,{id:"brokerage",type:"text",placeholder:"Your brokerage or team name",value:r.brokerage,onChange:c=>a({...r,brokerage:c.target.value})}),i.brokerage&&e.jsx("p",{className:"text-sm text-destructive",children:i.brokerage})]}),e.jsx($,{type:"submit",className:"w-full h-12 text-lg font-semibold bg-[#4a6b6d] hover:bg-[#3d5a5c]",disabled:t,children:t?e.jsxs(e.Fragment,{children:[e.jsx(Ht,{className:"mr-2 h-5 w-5 animate-spin"}),"Creating Your Account..."]}):e.jsxs(e.Fragment,{children:["Start My Free Trial",e.jsx(ni,{className:"ml-2 h-5 w-5"})]})}),e.jsxs("p",{className:"text-center text-sm text-muted-foreground",children:["By signing up, you agree to our"," ",e.jsx("a",{href:"/terms-of-service",className:"text-[#4a6b6d] hover:underline",children:"Terms"})," ","and"," ",e.jsx("a",{href:"/privacy-policy",className:"text-[#4a6b6d] hover:underline",children:"Privacy Policy"})]})]})]})})})]})})]}),e.jsx("section",{className:"py-20 bg-background",children:e.jsx("div",{className:"container mx-auto px-4",children:e.jsxs("div",{className:"max-w-4xl mx-auto text-center space-y-8",children:[e.jsx("h2",{className:"text-3xl md:text-5xl leading-tight font-sans font-semibold text-secondary",children:"We help brokerages and agents grow with training, tools, and built-in execution."}),e.jsxs("div",{className:"space-y-2 text-lg text-muted-foreground",children:[e.jsx("p",{children:"Agents get weekly coaching + plug-and-play marketing."}),e.jsx("p",{children:"Brokerages get higher adoption, consistency, and real engagement."})]}),e.jsx("p",{className:"text-2xl md:text-4xl text-[#4a6b6d] pt-4 font-sans font-bold",children:"LEVELUP EQUIPS BOTH TO THRIVE."})]})})}),e.jsx("section",{id:"features",className:"py-20 bg-muted/30",children:e.jsxs("div",{className:"container mx-auto px-4",children:[e.jsxs("div",{className:"text-center max-w-3xl mx-auto mb-16",children:[e.jsx("h2",{className:"text-3xl md:text-4xl mb-6 font-sans font-bold",children:"What's inside our members only portal?"}),e.jsx("p",{className:"text-lg text-muted-foreground",children:"Everything you need to grow your business, all in one place."})]}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-8 max-w-6xl mx-auto",children:G4s.map((c,d)=>e.jsxs(_e,{className:"group relative overflow-hidden border hover:border-[#4a6b6d]/50 transition-all duration-300 hover:shadow-lg bg-background",children:[e.jsxs(Bt,{children:[e.jsx("div",{className:"w-14 h-14 rounded-2xl bg-[#4a6b6d]/10 flex items-center justify-center mb-4",children:e.jsx(c.icon,{className:"w-7 h-7 text-[#4a6b6d]"})}),e.jsx(Ut,{className:"text-xl font-sans",children:c.title})]}),e.jsx(Oe,{children:e.jsx("p",{className:"text-muted-foreground leading-relaxed",children:c.description})})]},d))})]})}),e.jsxs("section",{className:"py-20 bg-gradient-to-br from-[#4a6b6d] to-[#3d5a5c] relative overflow-hidden",children:[e.jsx("div",{className:"absolute inset-0 opacity-10",children:e.jsx("div",{className:"absolute inset-0 bg-[url('data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iNjAiIGhlaWdodD0iNjAiIHZpZXdCb3g9IjAgMCA2MCA2MCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj48ZyBmaWxsPSJub25lIiBmaWxsLXJ1bGU9ImV2ZW5vZGQiPjxnIGZpbGw9IiNmZmZmZmYiIGZpbGwtb3BhY2l0eT0iMC40Ij48cGF0aCBkPSJNMzYgMzRoLTJ2LTRoMnY0em0wLTZ2LTRoLTJ2NGgyem0tNiA2aC0ydi00aDJ2NHptMC02di00aC0ydjRoMnoiLz48L2c+PC9nPjwvc3ZnPg==')]"})}),e.jsxs("div",{className:"container mx-auto px-4 relative",children:[e.jsxs("div",{className:"text-center max-w-3xl mx-auto mb-16",children:[e.jsxs("div",{className:"inline-flex items-center gap-2 px-4 py-2 rounded-full bg-white/10 text-white text-sm font-medium mb-6",children:[e.jsx(dn,{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:W4s.map((c,d)=>e.jsxs(_e,{className:"group relative overflow-hidden border-0 bg-white/10 backdrop-blur-sm hover:bg-white/20 transition-all duration-300",children:[e.jsxs(Bt,{className:"pb-3",children:[e.jsx("div",{className:"w-12 h-12 rounded-xl bg-white/20 flex items-center justify-center mb-3",children:e.jsx(c.icon,{className:"w-6 h-6 text-white"})}),e.jsx(Ut,{className:"text-lg font-semibold text-white",children:c.title})]}),e.jsx(Oe,{children:e.jsx("p",{className:"text-white/70 text-sm leading-relaxed",children:c.description})})]},d))})]})]}),e.jsx("section",{className:"py-20 bg-background",children:e.jsxs("div",{className:"container mx-auto px-4",children:[e.jsxs("div",{className:"text-center mb-16",children:[e.jsx("h2",{className:"text-3xl md:text-4xl font-bold mb-4 font-sans",children:"Loved by Top Producers"}),e.jsx("p",{className:"text-lg text-muted-foreground",children:"See what agents are saying about LevelUp"})]}),e.jsx("div",{className:"grid md:grid-cols-3 gap-8 max-w-5xl mx-auto",children:K4s.map((c,d)=>e.jsx(_e,{className:"border hover:shadow-lg transition-shadow",children:e.jsxs(Oe,{className:"p-6",children:[e.jsx("div",{className:"flex gap-1 mb-4",children:[1,2,3,4,5].map(u=>e.jsx(Qa,{className:"h-4 w-4 fill-yellow-400 text-yellow-400"},u))}),e.jsxs("p",{className:"text-muted-foreground mb-4 italic",children:['"',c.quote,'"']}),e.jsxs("div",{children:[e.jsx("p",{className:"font-semibold",children:c.name}),e.jsx("p",{className:"text-sm text-muted-foreground",children:c.role})]})]})},d))})]})}),e.jsx("section",{className:"py-16 bg-muted/30",children:e.jsx("div",{className:"container mx-auto px-4",children:e.jsxs("div",{className:"flex flex-wrap justify-center gap-8 md:gap-16",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-12 h-12 rounded-full bg-[#4a6b6d]/10 flex items-center justify-center",children:e.jsx(kf,{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(ox,{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(qn,{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(_e,{className:"bg-gradient-to-br from-[#1e3a4c] via-[#2a4f5f] to-[#3d6b6b] border-0 shadow-2xl overflow-hidden relative",children:[e.jsx("div",{className:"absolute inset-0 opacity-10",children:e.jsx("div",{className:"absolute inset-0 bg-[url('data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iNjAiIGhlaWdodD0iNjAiIHZpZXdCb3g9IjAgMCA2MCA2MCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj48ZyBmaWxsPSJub25lIiBmaWxsLXJ1bGU9ImV2ZW5vZGQiPjxnIGZpbGw9IiNmZmZmZmYiIGZpbGwtb3BhY2l0eT0iMC40Ij48cGF0aCBkPSJNMzYgMzRoLTJ2LTRoMnY0em0wLTZ2LTRoLTJ2NGgyem0tNiA2aC0ydi00aDJ2NHptMC02di00aC0ydjRoMnoiLz48L2c+PC9nPjwvc3ZnPg==')]"})}),e.jsxs(Oe,{className:"p-12 text-center relative",children:[e.jsx("h2",{className:"text-3xl md:text-4xl font-bold text-white mb-4 font-sans",children:"Ready to Level Up Your Business?"}),e.jsx("p",{className:"text-xl text-white/80 mb-8 max-w-2xl mx-auto",children:"Join thousands of successful agents. Start your free 7-day trial today."}),e.jsxs($,{onClick:()=>window.scrollTo({top:0,behavior:"smooth"}),size:"lg",className:"h-14 px-8 text-lg font-semibold bg-white text-[#1e3a4c] hover:bg-white/90 shadow-2xl transition-all hover:scale-105 rounded-full",children:["Start Your Free Trial Now",e.jsx(ni,{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:Hke,alt:"LevelUp",className:"h-8"}),e.jsxs("div",{className:"flex gap-6 text-sm text-white/60",children:[e.jsx("a",{href:"/privacy-policy",className:"hover:text-white transition-colors",children:"Privacy Policy"}),e.jsx("a",{href:"/terms-of-service",className:"hover:text-white transition-colors",children:"Terms of Service"})]}),e.jsx("p",{className:"text-sm text-white/40",children:"© 2025 LevelUp Consulting Group. All rights reserved."})]})})})]})]})},Z4s=()=>{const s=Vn();return e.jsxs(e.Fragment,{children:[e.jsx(Ul,{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:nSe,alt:"LevelUp",className:"h-8 md:h-10"})}),e.jsx($,{onClick:()=>s("/auth"),className:"bg-white text-[#4a6b6d] hover:bg-gray-100 font-medium shadow-md",children:"Sign In"})]})}),e.jsxs("section",{className:"relative pt-24 pb-12 bg-gradient-to-br from-[#1e3a4c] via-[#2a4f5f] to-[#3d6b6b] overflow-hidden flex-1 flex items-center",children:[e.jsx("div",{className:"absolute inset-0 opacity-10",children:e.jsx("div",{className:"absolute inset-0 bg-[url('data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iNjAiIGhlaWdodD0iNjAiIHZpZXdCb3g9IjAgMCA2MCA2MCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj48ZyBmaWxsPSJub25lIiBmaWxsLXJ1bGU9ImV2ZW5vZGQiPjxnIGZpbGw9IiNmZmZmZmYiIGZpbGwtb3BhY2l0eT0iMC40Ij48cGF0aCBkPSJNMzYgMzRoLTJ2LTRoMnY0em0wLTZ2LTRoLTJ2NGgyem0tNiA2aC0ydi00aDJ2NHptMC02di00aC0ydjRoMnoiLz48L2c+PC9nPjwvc3ZnPg==')]"})}),e.jsx("div",{className:"container mx-auto px-4 relative",children:e.jsx("div",{className:"flex justify-center",children:e.jsx(_e,{className:"max-w-lg w-full bg-white shadow-2xl border-0",children:e.jsxs(Oe,{className:"p-8 md:p-12 text-center",children:[e.jsxs("div",{className:"relative inline-block mb-8",children:[e.jsx("div",{className:"w-24 h-24 rounded-full bg-gradient-to-br from-[#4a6b6d] to-[#3d5a5c] flex items-center justify-center",children:e.jsx(Fr,{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(Nf,{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(nn,{className:"h-6 w-6 text-[#4a6b6d]"})}),e.jsx("h2",{className:"text-lg font-semibold text-foreground",children:"Check Your Inbox"})]}),e.jsx("p",{className:"text-muted-foreground",children:"We just sent you a magic link to claim your account and set up your password. Click the link in your email to get started!"})]}),e.jsxs("div",{className:"text-left space-y-3 mb-8",children:[e.jsx("p",{className:"text-sm text-muted-foreground font-medium uppercase tracking-wide",children:"What happens next:"}),e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:"w-6 h-6 rounded-full bg-[#4a6b6d] flex items-center justify-center flex-shrink-0 mt-0.5",children:e.jsx("span",{className:"text-xs font-bold text-white",children:"1"})}),e.jsx("p",{className:"text-foreground",children:"Check your email for the welcome message"})]}),e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:"w-6 h-6 rounded-full bg-[#4a6b6d] flex items-center justify-center flex-shrink-0 mt-0.5",children:e.jsx("span",{className:"text-xs font-bold text-white",children:"2"})}),e.jsx("p",{className:"text-foreground",children:'Click "Claim Your Account" to set your password'})]}),e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:"w-6 h-6 rounded-full bg-[#4a6b6d] flex items-center justify-center flex-shrink-0 mt-0.5",children:e.jsx("span",{className:"text-xs font-bold text-white",children:"3"})}),e.jsx("p",{className:"text-foreground",children:"Start exploring all the features!"})]})]}),e.jsxs("p",{className:"text-sm text-muted-foreground mb-6",children:["Didn't receive the email? Check your spam folder or"," ",e.jsx("button",{onClick:()=>s("/trial"),className:"text-[#4a6b6d] hover:underline font-medium",children:"try again"})]}),e.jsxs($,{onClick:()=>s("/auth"),className:"bg-[#4a6b6d] hover:bg-[#3d5a5c]",children:["Go to Sign In",e.jsx(ni,{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:Hke,alt:"LevelUp",className:"h-8"}),e.jsxs("p",{className:"text-sm text-white/40",children:["© ",new Date().getFullYear()," LevelUp Consulting Group. All rights reserved."]})]})})})]})]})},X4s=tk({viewerName:rl().min(1,"Name is required").max(100,"Name must be less than 100 characters"),viewerEmail:rl().email("Please enter a valid email").max(255,"Email must be less than 255 characters"),viewerPhone:rl().max(20,"Phone must be less than 20 characters").optional(),message:rl().min(1,"Message is required").max(1e3,"Message must be less than 1000 characters")});function Q4s({shareToken:s,agentName:t,hasContact:n}){const[r,a]=j.useState(!1),[i,l]=j.useState(!1),[o,c]=j.useState(null),d=xCe({resolver:gCe(X4s),defaultValues:{viewerName:"",viewerEmail:"",viewerPhone:"",message:""}}),u=async h=>{a(!0),c(null);try{const{data:m,error:p}=await U.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(_e,{className:"border-2 border-primary/20 bg-gradient-to-br from-primary/5 to-primary/10",children:e.jsxs(Oe,{className:"py-8 text-center",children:[e.jsx("div",{className:"inline-flex items-center justify-center w-16 h-16 rounded-full bg-primary/20 mb-4",children:e.jsx(Fr,{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(_e,{children:[e.jsxs(Bt,{className:"pb-4",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx(Ed,{className:"h-5 w-5 text-primary"}),e.jsx(Ut,{className:"text-lg",children:"Reply to this video"})]}),e.jsx(vr,{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(Oe,{children:e.jsx(_Ce,{...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(Cp,{control:d.control,name:"viewerName",render:({field:h})=>e.jsxs(Ym,{children:[e.jsx(Zm,{children:"Your Name *"}),e.jsx(Xm,{children:e.jsx(be,{placeholder:"John Smith",...h})}),e.jsx(a1,{})]})}),e.jsx(Cp,{control:d.control,name:"viewerEmail",render:({field:h})=>e.jsxs(Ym,{children:[e.jsx(Zm,{children:"Email *"}),e.jsx(Xm,{children:e.jsx(be,{type:"email",placeholder:"john@example.com",...h})}),e.jsx(a1,{})]})})]}),!n&&e.jsx(Cp,{control:d.control,name:"viewerPhone",render:({field:h})=>e.jsxs(Ym,{children:[e.jsx(Zm,{children:"Phone (optional)"}),e.jsx(Xm,{children:e.jsx(be,{type:"tel",placeholder:"(555) 123-4567",...h})}),e.jsx(a1,{})]})}),e.jsx(Cp,{control:d.control,name:"message",render:({field:h})=>e.jsxs(Ym,{children:[e.jsx(Zm,{children:"Message *"}),e.jsx(Xm,{children:e.jsx(Is,{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(a1,{})]})}),o&&e.jsx("p",{className:"text-sm text-destructive",children:o}),e.jsx($,{type:"submit",className:"w-full gap-2",disabled:r,children:r?e.jsxs(e.Fragment,{children:[e.jsx(Ht,{className:"h-4 w-4 animate-spin"}),"Sending..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Br,{className:"h-4 w-4"}),"Send Message"]})})]})})})]})}const J4s=()=>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(Qa,{className:"absolute top-[5%] left-[8%] w-6 h-6 text-blue-600/30 fill-blue-600/20"}),e.jsx(Qa,{className:"absolute top-[15%] left-[20%] w-4 h-4 text-blue-600/25 fill-blue-600/15"}),e.jsx(Qa,{className:"absolute top-[8%] left-[28%] w-5 h-5 text-blue-600/30 fill-blue-600/20"}),e.jsx(Qa,{className:"absolute top-[25%] left-[12%] w-4 h-4 text-blue-600/20 fill-blue-600/10"}),e.jsx(Qa,{className:"absolute top-[20%] right-[15%] w-5 h-5 text-red-500/25 fill-red-500/15 animate-pulse"}),e.jsx(U3,{className:"absolute bottom-[20%] right-[10%] w-12 h-12 text-blue-600/15 rotate-12"})]}),e3s=()=>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(dn,{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(Qa,{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(dn,{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(Qa,{className:"absolute bottom-[25%] left-[10%] w-6 h-6 text-blue-500/25 fill-blue-500/15 animate-pulse"}),e.jsx(Qa,{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(U3,{className:"absolute top-[8%] left-[5%] w-10 h-10 text-red-500/20 rotate-12"})]}),t3s=()=>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(CN,{className:"w-20 h-20 text-pink-400 rotate-12"})}),e.jsx("div",{className:"absolute top-[2%] right-[8%] opacity-15",children:e.jsx(CN,{className:"w-16 h-16 text-rose-400 -rotate-12"})}),e.jsx("div",{className:"absolute bottom-[15%] left-[8%] opacity-15",children:e.jsx(CN,{className:"w-14 h-14 text-purple-400 rotate-45"})}),e.jsx("div",{className:"absolute bottom-[20%] right-[5%] opacity-20",children:e.jsx(CN,{className:"w-16 h-16 text-pink-300 -rotate-6"})}),e.jsx(fo,{className:"absolute top-[15%] left-[30%] w-5 h-5 text-rose-300/40 fill-rose-300/20 animate-pulse"}),e.jsx(fo,{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(fo,{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"})]}),s3s=()=>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(pu,{className:"absolute top-[8%] left-[12%] w-12 h-12 text-blue-600/15"}),e.jsx(Qa,{className:"absolute top-[15%] left-[22%] w-5 h-5 text-amber-500/25 fill-amber-500/15"}),e.jsx(pu,{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(Qa,{className:"absolute bottom-[25%] left-[15%] w-6 h-6 text-blue-500/20 fill-blue-500/10 animate-pulse"}),e.jsx(Qa,{className:"absolute top-[20%] right-[22%] w-5 h-5 text-indigo-400/20 fill-indigo-400/10 animate-pulse",style:{animationDelay:"0.5s"}})]}),n3s=()=>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(CN,{className:"absolute top-[20%] left-[32%] w-7 h-7 text-purple-400/30"}),e.jsx(CN,{className:"absolute top-[12%] right-[28%] w-6 h-6 text-pink-400/30"}),e.jsx(yz,{className:"absolute top-[18%] left-[52%] w-5 h-5 text-sky-400/35"})]}),r3s=()=>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(mR,{className:"absolute top-[5%] left-[10%] w-16 h-16 text-orange-400/25"}),e.jsx(mR,{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(dn,{className:"absolute top-[8%] left-[55%] w-6 h-6 text-purple-400/35 animate-pulse"}),e.jsx(dn,{className:"absolute bottom-[28%] right-[25%] w-5 h-5 text-orange-400/30 animate-pulse",style:{animationDelay:"0.5s"}})]}),a3s=()=>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(LT,{className:"absolute bottom-[8%] left-[5%] w-20 h-20 text-green-600/18"}),e.jsx(LT,{className:"absolute bottom-[12%] right-[8%] w-16 h-16 text-emerald-600/15"}),e.jsx(LT,{className:"absolute bottom-[10%] left-[28%] w-12 h-12 text-green-500/12"}),e.jsx(Z_,{className:"absolute top-[5%] left-[15%] w-10 h-10 text-sky-300/30 animate-pulse"}),e.jsx(Z_,{className:"absolute top-[10%] right-[20%] w-8 h-8 text-blue-300/25 animate-pulse",style:{animationDelay:"0.3s"}}),e.jsx(Z_,{className:"absolute top-[18%] left-[45%] w-6 h-6 text-sky-200/25 animate-pulse",style:{animationDelay:"0.6s"}}),e.jsx(Z_,{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(Qa,{className:"absolute top-[3%] left-[50%] -translate-x-1/2 w-10 h-10 text-amber-400/35 fill-amber-400/25"})]}),i3s=()=>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(fo,{className:"absolute top-[8%] left-[55%] w-6 h-6 text-red-400/22 fill-red-400/12"}),e.jsx(fo,{className:"absolute top-[20%] right-[25%] w-5 h-5 text-orange-400/22 fill-orange-400/12"})]}),o3s=()=>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(Qa,{className:"absolute top-[5%] left-[15%] w-12 h-12 text-yellow-400/35 fill-yellow-400/25 animate-pulse"}),e.jsx(Qa,{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(Qa,{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(Qa,{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(dn,{className:"absolute top-[3%] left-[50%] w-10 h-10 text-yellow-400/40"}),e.jsx(Nf,{className:"absolute bottom-[18%] left-[10%] w-12 h-12 text-purple-400/18 rotate-12"}),e.jsx(Nf,{className:"absolute bottom-[20%] right-[12%] w-10 h-10 text-amber-400/15 -rotate-12"})]}),l3s=()=>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(Qa,{className:"absolute top-[8%] left-[50%] -translate-x-1/2 w-14 h-14 text-yellow-400/28 fill-yellow-400/18"}),e.jsx(dn,{className:"absolute top-[5%] left-[20%] w-7 h-7 text-blue-400/35"}),e.jsx(dn,{className:"absolute top-[10%] right-[18%] w-6 h-6 text-sky-400/30"})]}),c3s=()=>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(L3,{className:"absolute top-[5%] left-[10%] w-16 h-16 text-green-500/25"}),e.jsx(L3,{className:"absolute top-[8%] right-[12%] w-12 h-12 text-emerald-500/20"}),e.jsx(L3,{className:"absolute bottom-[18%] left-[12%] w-14 h-14 text-green-400/22"}),e.jsx(L3,{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"})]})]})]}),d3s=()=>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(Qa,{className:"absolute top-[5%] left-[42%] w-10 h-10 text-amber-400/30 fill-amber-400/20"}),e.jsx(Qa,{className:"absolute top-[15%] right-[25%] w-7 h-7 text-yellow-400/25 fill-yellow-400/15"}),e.jsx(pu,{className:"absolute bottom-[20%] right-[12%] w-12 h-12 text-blue-500/18"}),e.jsx(pu,{className:"absolute top-[18%] left-[28%] w-8 h-8 text-indigo-400/15"}),e.jsx(U3,{className:"absolute top-[8%] left-[60%] w-10 h-10 text-indigo-400/18"})]}),u3s=()=>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(np,{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(Nf,{className:"absolute top-[8%] left-[45%] w-10 h-10 text-purple-400/22 rotate-12"}),e.jsx(Co,{className:"absolute bottom-[18%] right-[15%] w-12 h-12 text-rose-400/18"})]}),h3s=()=>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(fo,{className:"absolute top-[5%] left-[10%] w-16 h-16 text-rose-400/28 fill-rose-400/18"}),e.jsx(fo,{className:"absolute top-[8%] right-[12%] w-14 h-14 text-pink-400/25 fill-pink-400/15"}),e.jsx(fo,{className:"absolute bottom-[15%] left-[12%] w-12 h-12 text-red-400/22 fill-red-400/12"}),e.jsx(fo,{className:"absolute bottom-[18%] right-[10%] w-13 h-13 text-rose-300/25 fill-rose-300/15"}),e.jsx(fo,{className:"absolute top-[15%] left-[30%] w-6 h-6 text-pink-300/35 fill-pink-300/20 animate-pulse"}),e.jsx(fo,{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(fo,{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(fo,{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"})]}),m3s=()=>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(Kj,{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(Kj,{className:"absolute top-[15%] left-[18%] w-10 h-10 text-yellow-400/30"}),e.jsx(dn,{className:"absolute top-[10%] left-[42%] w-7 h-7 text-amber-400/35"}),e.jsx(Kj,{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"})]}),p3s=()=>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(sa,{className:"absolute top-[8%] left-[10%] w-14 h-14 text-teal-500/22"}),e.jsx(sa,{className:"absolute bottom-[15%] right-[8%] w-16 h-16 text-emerald-500/18"}),e.jsx(Mb,{className:"absolute top-[12%] right-[18%] w-10 h-10 text-amber-400/25"}),e.jsx(Mb,{className:"absolute bottom-[22%] left-[22%] w-8 h-8 text-yellow-400/22"}),e.jsx(fo,{className:"absolute top-[18%] left-[40%] w-6 h-6 text-rose-400/22 fill-rose-400/12"}),e.jsx(fo,{className:"absolute top-[22%] right-[35%] w-5 h-5 text-teal-400/20 fill-teal-400/10"}),e.jsx(dn,{className:"absolute top-[5%] left-[55%] w-8 h-8 text-teal-400/30"}),e.jsx(Nf,{className:"absolute bottom-[20%] left-[48%] w-10 h-10 text-cyan-400/18 rotate-12"})]}),f3s=()=>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(Nf,{className:"absolute top-[5%] left-[12%] w-14 h-14 text-emerald-400/25 rotate-12"}),e.jsx(Nf,{className:"absolute top-[8%] right-[10%] w-12 h-12 text-teal-400/22 -rotate-12"}),e.jsx(Mb,{className:"absolute bottom-[18%] left-[18%] w-12 h-12 text-amber-400/25"}),e.jsx(sa,{className:"absolute bottom-[15%] right-[12%] w-14 h-14 text-teal-500/18"}),e.jsx(dn,{className:"absolute top-[15%] left-[42%] w-10 h-10 text-emerald-400/35"}),e.jsx(dn,{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"})]}),x3s=()=>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(Mb,{className:"absolute bottom-[12%] left-[50%] -translate-x-1/2 w-24 h-24 text-amber-400/25 rotate-45"}),e.jsx(Mb,{className:"absolute top-[10%] left-[12%] w-10 h-10 text-yellow-400/30"}),e.jsx(Mb,{className:"absolute top-[12%] right-[15%] w-9 h-9 text-amber-300/25"}),e.jsx(sa,{className:"absolute top-[8%] left-[42%] w-12 h-12 text-teal-500/18"}),e.jsx(Nf,{className:"absolute bottom-[22%] right-[18%] w-12 h-12 text-orange-400/18 rotate-12"}),e.jsx(dn,{className:"absolute top-[5%] right-[35%] w-8 h-8 text-yellow-400/35"}),e.jsx(Qa,{className:"absolute top-[18%] left-[28%] w-6 h-6 text-amber-400/25 fill-amber-400/15"})]}),g3s=()=>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(sa,{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(Mb,{className:"absolute top-[10%] right-[12%] w-10 h-10 text-amber-400/28"}),e.jsx(fo,{className:"absolute top-[8%] left-[18%] w-8 h-8 text-rose-400/25 fill-rose-400/15"}),e.jsx(dn,{className:"absolute top-[12%] left-[45%] w-8 h-8 text-teal-400/30"}),e.jsx(zj,{className:"absolute top-[15%] right-[28%] w-10 h-10 text-emerald-400/20"})]}),Zot=()=>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"})]}),y3s=()=>e.jsxs("div",{className:"absolute inset-0 overflow-hidden pointer-events-none",children:[e.jsx(fo,{className:"absolute top-6 left-[12%] w-4 h-4 text-rose-300/50 fill-rose-300/30 animate-pulse"}),e.jsx(fo,{className:"absolute top-10 right-[18%] w-3 h-3 text-pink-300/50 fill-pink-300/30 animate-pulse delay-150"}),e.jsx(fo,{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(fo,{className:"absolute top-14 right-[35%] w-3.5 h-3.5 text-pink-300/40 fill-pink-300/20 animate-pulse delay-200"})]}),v3s=()=>e.jsxs("div",{className:"absolute inset-0 overflow-hidden pointer-events-none",children:[e.jsx(zj,{className:"absolute top-5 left-[10%] w-4 h-4 text-blue-400/50 animate-pulse"}),e.jsx(dn,{className:"absolute top-10 right-[15%] w-3 h-3 text-amber-400/50 animate-pulse delay-100"}),e.jsx(sa,{className:"absolute top-8 left-[38%] w-3 h-3 text-teal-300/40 animate-pulse delay-200"})]}),b3s=()=>e.jsxs("div",{className:"absolute inset-0 overflow-hidden pointer-events-none",children:[e.jsx(Tb,{className:"absolute top-5 left-[12%] w-4 h-4 text-amber-500/50 animate-pulse"}),e.jsx(Az,{className:"absolute top-10 right-[15%] w-3 h-3 text-rose-400/50 animate-pulse delay-100"}),e.jsx(Tb,{className:"absolute top-8 left-[40%] w-3 h-3 text-amber-400/40 animate-pulse delay-200"})]}),rG=()=>e.jsxs("div",{className:"absolute inset-0 overflow-hidden pointer-events-none",children:[e.jsx(dn,{className:"absolute top-5 left-[10%] w-4 h-4 text-emerald-400/50 animate-pulse"}),e.jsx(Nf,{className:"absolute top-10 right-[12%] w-5 h-5 text-amber-400/50 animate-pulse delay-150"}),e.jsx(dn,{className:"absolute top-8 left-[45%] w-3 h-3 text-sky-400/40 animate-pulse delay-300"})]}),Xot=()=>e.jsxs("div",{className:"absolute inset-0 overflow-hidden pointer-events-none",children:[e.jsx(sa,{className:"absolute top-6 left-[12%] w-4 h-4 text-teal-400/40 animate-pulse"}),e.jsx(dn,{className:"absolute top-10 right-[15%] w-3 h-3 text-emerald-400/50 animate-pulse delay-100"}),e.jsx(sa,{className:"absolute top-4 right-[40%] w-3 h-3 text-cyan-400/30 animate-pulse delay-200"})]}),m7e=[{id:"default",name:"Classic",description:"Clean, professional look for any occasion",icon:e.jsx(dn,{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(fo,{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(y3s,{})},{id:"thinking_of_you",name:"Thinking of You",description:"Let them know they're on your mind",icon:e.jsx(yK,{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(rG,{})},{id:"check_in",name:"Check-in",description:"Touch base with your contacts",icon:e.jsx(Tb,{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(b3s,{})},{id:"market_update",name:"Market Update",description:"Share real estate market insights",icon:e.jsx(ml,{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(qn,{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(rG,{})},{id:"congratulations",name:"Congratulations",description:"Celebrate their achievements",icon:e.jsx(pu,{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(Zot,{})},{id:"welcome_neighborhood",name:"Welcome to the Neighborhood",description:"Greet new neighbors",icon:e.jsx(ai,{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(Xot,{})},{id:"just_because",name:"Just Because",description:"No reason needed to connect",icon:e.jsx(Az,{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(rG,{})},{id:"birthday",name:"Birthday",description:"Celebrate their special day",icon:e.jsx(np,{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(u3s,{})},{id:"valentines_day",name:"Valentine's Day",description:"Show appreciation on this special day",icon:e.jsx(fo,{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(h3s,{})},{id:"groundhog_day",name:"Groundhog Day",description:"A fun seasonal greeting",icon:e.jsx(Kj,{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(m3s,{})},{id:"new_years",name:"New Year's Day",description:"Ring in the new year",icon:e.jsx(Qa,{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(o3s,{})},{id:"easter",name:"Easter",description:"Celebrate the spring season",icon:e.jsx(yz,{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(n3s,{})},{id:"mothers_day",name:"Mother's Day",description:"Celebrate the amazing moms",icon:e.jsx(CN,{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(t3s,{})},{id:"fathers_day",name:"Father's Day",description:"Celebrate the amazing dads",icon:e.jsx(pu,{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(s3s,{})},{id:"memorial_day",name:"Memorial Day",description:"Honor those who served",icon:e.jsx(U3,{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(J4s,{})},{id:"independence_day",name:"4th of July",description:"Celebrate Independence Day",icon:e.jsx(yd,{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(e3s,{})},{id:"labor_day",name:"Labor Day",description:"Celebrate the workers",icon:e.jsx(pu,{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(d3s,{})},{id:"halloween",name:"Halloween",description:"Spooky seasonal greetings",icon:e.jsx(mR,{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(r3s,{})},{id:"thanksgiving",name:"Thanksgiving",description:"Express gratitude this season",icon:e.jsx(fo,{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(i3s,{})},{id:"christmas",name:"Christmas",description:"Spread holiday cheer",icon:e.jsx(LT,{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(a3s,{})},{id:"hanukkah",name:"Hanukkah",description:"Celebrate the Festival of Lights",icon:e.jsx(dn,{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(l3s,{})},{id:"st_patricks_day",name:"St. Patrick's Day",description:"Celebrate the luck of the Irish",icon:e.jsx(L3,{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(c3s,{})},{id:"home_anniversary",name:"Home Anniversary",description:"Celebrate their home ownership milestone",icon:e.jsx(sa,{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(p3s,{})},{id:"under_contract",name:"Under Contract",description:"Celebrate this exciting milestone",icon:e.jsx(Nf,{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(f3s,{})},{id:"just_listed",name:"Just Listed",description:"Announce a new listing",icon:e.jsx(ia,{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(Xot,{})},{id:"just_sold",name:"Just Sold",description:"Celebrate a successful sale",icon:e.jsx(qd,{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(rG,{})},{id:"price_reduction",name:"Price Reduction",description:"Notify about a price change",icon:e.jsx(FN,{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(zj,{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(v3s,{})},{id:"closing_day",name:"Closing Day",description:"Celebrate their closing day",icon:e.jsx(Mb,{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(x3s,{})},{id:"move_in_day",name:"Move-in Day",description:"Welcome them to their new home",icon:e.jsx(sa,{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(g3s,{})},{id:"offer_accepted",name:"Offer Accepted",description:"Celebrate their accepted offer",icon:e.jsx(Ox,{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(rG,{})},{id:"pre_approval",name:"Pre-Approval Congrats",description:"Congratulate on pre-approval",icon:e.jsx(pu,{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(Zot,{})}],_3s=[{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 w3s(s){return m7e.filter(t=>t.category===s)}function sB(s){return m7e.find(t=>t.id===s)||m7e[0]}function Qot(){const{shareToken:s,recipientToken:t}=Vi(),[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),x=j.useRef(null),g=j.useRef(0),y=j.useRef(0),b=(()=>{const q=new URLSearchParams(window.location.search);return t||q.get("rt")||null})(),v=j.useCallback((q,W=!1)=>{if(!b||q<=0)return;const V=Math.max(1,Math.round(q));if(V<=y.current)return;const Q=`https://relzejiswnotikjgvjhz.supabase.co/functions/v1/track-video-share?t=${encodeURIComponent(b)}&e=watch&ws=${V}`;W&&navigator.sendBeacon?navigator.sendBeacon(Q):fetch(Q,{method:"GET",keepalive:W}).catch(()=>{}),y.current=Math.max(y.current,V)},[b]);j.useEffect(()=>{var ce;if(!m||!(n!=null&&n.playback_url)||!b)return;let q=!1;const W=()=>{g.current>0&&v(g.current,!0)},V=()=>{document.visibilityState==="hidden"&&W()},K=()=>{W()},Q=()=>{var ne;if(q||!x.current||!((ne=window.playerjs)!=null&&ne.Player))return;const ue=new window.playerjs.Player(x.current);ue.on("timeupdate",ee=>{const le=Math.floor(Number((ee==null?void 0:ee.seconds)??0));!Number.isFinite(le)||le<=0||(g.current=Math.max(g.current,le))}),ue.on("pause",()=>{g.current>0&&v(g.current)}),ue.on("ended",()=>{g.current>0&&v(g.current,!0)})},J=document.querySelector('script[data-bunny-playerjs="true"]');if((ce=window.playerjs)!=null&&ce.Player)Q();else if(J)J.addEventListener("load",Q,{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=Q,document.body.appendChild(ue)}return document.addEventListener("visibilitychange",V),window.addEventListener("beforeunload",K),()=>{q=!0,document.removeEventListener("visibilitychange",V),window.removeEventListener("beforeunload",K),W()}},[m,n==null?void 0:n.playback_url,b,v]),j.useEffect(()=>{g.current=0,y.current=0},[b,s]),j.useEffect(()=>{const q=()=>{['[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(Q=>{document.querySelectorAll(Q).forEach(J=>{J.style.display="none"})})};q();const W=[setTimeout(q,500),setTimeout(q,1500),setTimeout(q,3e3)],V=new MutationObserver(q);return V.observe(document.body,{childList:!0,subtree:!0}),()=>{W.forEach(clearTimeout),V.disconnect()}},[]),j.useEffect(()=>{(async()=>{if(!s){h("Invalid share link"),d(!1);return}const{data:W,error:V}=await U.from("agent_videos").select("id, title, playback_url, thumbnail_url, preview_url, duration_seconds, share_token, owner_user_id, contact_id, page_template, recipient_name").eq("share_token",s).eq("is_deleted",!1).single();if(V||!W){h("Video not found or has been removed"),d(!1);return}r(W);try{await U.rpc("log_video_view",{p_video_id:W.id,p_user_agent:navigator.userAgent,p_referrer:document.referrer||null})}catch(K){console.warn("Failed to log video view:",K)}if(W.owner_user_id){const{data:K}=await U.from("profiles").select("id, name, email, phone").eq("id",W.owner_user_id).single();if(K){i(K);try{const{data:Q}=await U.storage.from("avatars").list(`${W.owner_user_id}`);if(Q&&Q.length>0){const{data:J}=U.storage.from("avatars").getPublicUrl(`${W.owner_user_id}/${Q[0].name}`);o(J.publicUrl)}}catch{}}}d(!1)})()},[s]);const N=q=>{if(!q)return"0:00";const W=Math.floor(q/60),V=q%60;return`${W}:${V.toString().padStart(2,"0")}`},C=q=>q.includes("iframe.mediadelivery.net/play/")?q.replace("/play/","/embed/")+"?autoplay=true&responsive=true":q,A=q=>{if(!q)return"?";const W=q.split(" ");return W.length>=2?`${W[0][0]}${W[1][0]}`.toUpperCase():q.substring(0,2).toUpperCase()},T=sB((n==null?void 0:n.page_template)||"default"),P=(n==null?void 0:n.recipient_name)||null,M=T.headerText(P),D=`https://dashboard.relevelup.com/share/video/${s}`;if(c)return e.jsx("div",{className:"min-h-screen bg-background flex items-center justify-center",children:e.jsx(Ht,{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(_e,{className:"max-w-md w-full",children:e.jsxs(Oe,{className:"py-12 text-center",children:[e.jsx(Xr,{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 B=T.id!=="default";return e.jsxs(e.Fragment,{children:[e.jsxs(Ul,{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:D}),n.preview_url&&e.jsx("meta",{property:"og:image",content:n.preview_url}),!n.preview_url&&n.thumbnail_url&&e.jsx("meta",{property:"og:image",content:n.thumbnail_url}),n.playback_url&&e.jsxs(e.Fragment,{children:[e.jsx("meta",{property:"og:video",content:n.playback_url}),e.jsx("meta",{property:"og:video:type",content:"text/html"}),e.jsx("meta",{property:"og:video:width",content:"1280"}),e.jsx("meta",{property:"og:video:height",content:"720"})]}),e.jsx("meta",{name:"twitter:card",content:"player"}),e.jsx("meta",{name:"twitter:title",content: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:Tt("min-h-screen flex items-center justify-center p-4 bg-gradient-to-b relative",T.gradientClasses),children:[B&&T.decorativeElement,e.jsxs("div",{className:"max-w-2xl w-full space-y-6 relative z-10",children:[B&&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:Tt("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(ki,{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:B?"A special video from":"A personal video from"}),e.jsx("h2",{className:"text-lg font-semibold truncate",children:a.name||"Your Agent"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Your Real Estate Professional"})]}),e.jsxs("div",{className:"flex gap-2 shrink-0",children:[a.phone&&e.jsx($,{variant:"outline",size:"icon",asChild:!0,className:"h-10 w-10",children:e.jsx("a",{href:`tel:${a.phone}`,"aria-label":"Call agent",children:e.jsx(ya,{className:"h-4 w-4"})})}),a.email&&e.jsx($,{variant:"outline",size:"icon",asChild:!0,className:"h-10 w-10",children:e.jsx("a",{href:`mailto:${a.email}`,"aria-label":"Email agent",children:e.jsx(nn,{className:"h-4 w-4"})})})]})]}),e.jsx(_e,{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:x,src:C(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:q=>{var V;q.currentTarget.style.display="none";const W=(V=q.currentTarget.parentElement)==null?void 0:V.querySelector(".video-fallback");W&&(W.style.display="flex")}}):null,e.jsx("div",{className:"video-fallback w-full h-full items-center justify-center bg-gradient-to-br from-primary/20 to-primary/5",style:{display:n.preview_url||n.thumbnail_url?"none":"flex"},children:e.jsx(Xr,{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(Td,{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)})]})}),!B&&e.jsxs("div",{className:"text-center",children:[e.jsx("h1",{className:"text-2xl font-bold",children:n.title||"Video Message"}),e.jsx("p",{className:"text-muted-foreground mt-2",children:m?"Enjoy the video!":"Click to play the video"})]}),!m&&e.jsx("div",{className:"flex justify-center",children:e.jsxs($,{size:"lg",onClick:()=>p(!0),className:"gap-2",children:[e.jsx(Td,{className:"h-5 w-5"}),"Watch Video"]})}),e.jsx(Q4s,{shareToken:s,agentName:(a==null?void 0:a.name)||null,hasContact:!!n.contact_id})]})]})]})}function j3s(){return j.useEffect(()=>(document.body.classList.add("video-landing-page"),()=>{document.body.classList.remove("video-landing-page")}),[]),e.jsx(mSt,{})}function N3s(){const{token:s}=Vi();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(Ht,{className:"h-5 w-5 animate-spin"}),e.jsx("span",{children:"Loading video preview…"})]})})}const k3s={office_exclusive:"Office Exclusive",coming_soon:"Coming Soon",pre_market:"Pre-Market",active:"Active"},S3s=s=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(s||0);function C3s(){var le;const[s]=oc(),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,x]=j.useState(""),[g,y]=j.useState(""),[b,v]=j.useState(""),[N,C]=j.useState(""),[A,T]=j.useState("tour"),[P,M]=j.useState(!1),[I,D]=j.useState(!1),B=async()=>{if(!p.trim()||!g.trim()){ae.error("Please enter your name and email");return}M(!0);try{const ve=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/private-listing-lead",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({r:t,m:n,name:p.trim(),email:g.trim(),phone:b.trim()||null,message:N.trim()||null,intent:A})}),ge=await ve.json();if(!ve.ok||!(ge!=null&&ge.success))throw new Error((ge==null?void 0:ge.error)||"Could not send");D(!0),ae.success("Sent! The agent will be in touch shortly.")}catch(he){ae.error((he==null?void 0:he.message)||"Could not send")}finally{M(!1)}};if(j.useEffect(()=>{if(!t||!n){l("Invalid link"),c(!1);return}const he=`https://relzejiswnotikjgvjhz.supabase.co/functions/v1/private-listing-view?r=${encodeURIComponent(t)}&m=${encodeURIComponent(n)}`;fetch(he).then(ve=>ve.json()).then(ve=>{ve.error?l("This private listing link is no longer valid."):a({listing:ve.listing,agent:ve.agent})}).catch(()=>l("Unable to load listing.")).finally(()=>c(!1))},[t,n]),o)return e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-slate-50",children:e.jsx("div",{className:"text-slate-500",children:"Loading…"})});if(i||!r)return e.jsxs(e.Fragment,{children:[e.jsx(Ul,{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(Ad,{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:q,agent:W}=r,V=(le=q.photos)!=null&&le.length?q.photos:[],K=V[0],Q=k3s[q.status]||q.status,J=(W==null?void 0:W.sender_name)||(W==null?void 0:W.name)||"Your Agent",ce=(W==null?void 0:W.sender_email)||null,ue=encodeURIComponent(`Interested in ${q.address}`),ne=encodeURIComponent(`Hi ${J}, I'd love to learn more about ${q.address}, ${q.city}. Thanks!`),ee=W!=null&&W.booking_slug?`https://dashboard.relevelup.com/book/${W.booking_slug}`:null;return e.jsxs(e.Fragment,{children:[e.jsxs(Ul,{children:[e.jsxs("title",{children:["Private Listing · ",q.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(Ad,{className:"h-3.5 w-3.5"}),e.jsxs("span",{className:"font-medium tracking-wide uppercase",children:["Private listing · Shared by ",J]})]}),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:q.address,className:"w-full h-[42vh] md:h-[60vh] object-cover"})}):e.jsx("div",{className:"w-full h-[42vh] md:h-[60vh] bg-slate-200 flex items-center justify-center text-slate-400",children:"No photos available"}),e.jsx("div",{className:"absolute top-4 left-4",children:e.jsx($e,{className:"bg-indigo-600 text-white border-0 text-xs px-2.5 py-1 shadow",children:Q})}),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(_e,{className:"shadow-xl border-slate-200",children:e.jsxs(Oe,{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:q.address}),e.jsxs("p",{className:"text-slate-600 mt-1 flex items-center gap-1.5",children:[e.jsx(ai,{className:"h-4 w-4"}),q.city,", ",q.state," ",q.zip]})]}),e.jsx("div",{className:"text-right",children:e.jsx("p",{className:"text-3xl sm:text-4xl font-bold text-indigo-600",children:S3s(q.price)})})]}),e.jsxs("div",{className:"grid grid-cols-3 gap-3 mt-6",children:[q.bedrooms?e.jsxs("div",{className:"bg-slate-50 rounded-lg p-3 text-center",children:[e.jsx(tw,{className:"h-5 w-5 mx-auto text-slate-500 mb-1"}),e.jsx("p",{className:"text-lg font-semibold text-slate-900",children:q.bedrooms}),e.jsx("p",{className:"text-xs text-slate-500",children:"Beds"})]}):null,q.bathrooms?e.jsxs("div",{className:"bg-slate-50 rounded-lg p-3 text-center",children:[e.jsx(_g,{className:"h-5 w-5 mx-auto text-slate-500 mb-1"}),e.jsx("p",{className:"text-lg font-semibold text-slate-900",children:q.bathrooms}),e.jsx("p",{className:"text-xs text-slate-500",children:"Baths"})]}):null,q.sqft?e.jsxs("div",{className:"bg-slate-50 rounded-lg p-3 text-center",children:[e.jsx(Lb,{className:"h-5 w-5 mx-auto text-slate-500 mb-1"}),e.jsx("p",{className:"text-lg font-semibold text-slate-900",children:q.sqft.toLocaleString()}),e.jsx("p",{className:"text-xs text-slate-500",children:"Sq Ft"})]}):null]}),q.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:q.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((he,ve)=>e.jsx("button",{type:"button",onClick:()=>{u(ve),m(!0)},className:"aspect-[4/3] overflow-hidden rounded-lg bg-slate-100",children:e.jsx("img",{src:he,alt:"",className:"w-full h-full object-cover hover:scale-105 transition"})},ve))})]})]})}),e.jsxs(_e,{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:[J," will get back to you personally."]})]}),e.jsx(Oe,{className:"p-6 sm:p-8",children:I?e.jsxs("div",{className:"flex flex-col items-center text-center py-6",children:[e.jsx(Fr,{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:[J," 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(he=>e.jsx("button",{type:"button",onClick:()=>T(he.id),className:`px-3 py-2 rounded-lg border text-sm font-medium transition ${A===he.id?"bg-indigo-600 text-white border-indigo-600":"bg-white text-slate-700 border-slate-200 hover:border-indigo-300"}`,children:he.label},he.id))}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(se,{htmlFor:"pl-name",children:"Your name *"}),e.jsx(be,{id:"pl-name",value:p,onChange:he=>x(he.target.value),placeholder:"Jane Doe",maxLength:120})]}),e.jsxs("div",{children:[e.jsx(se,{htmlFor:"pl-email",children:"Email *"}),e.jsx(be,{id:"pl-email",type:"email",value:g,onChange:he=>y(he.target.value),placeholder:"you@email.com",maxLength:255})]})]}),e.jsxs("div",{children:[e.jsx(se,{htmlFor:"pl-phone",children:"Phone (optional)"}),e.jsx(be,{id:"pl-phone",value:b,onChange:he=>v(he.target.value),placeholder:"(555) 555-5555",maxLength:40})]}),e.jsxs("div",{children:[e.jsx(se,{htmlFor:"pl-msg",children:"Message (optional)"}),e.jsx(Is,{id:"pl-msg",value:N,onChange:he=>C(he.target.value),placeholder:`I'd love to see ${q.address}…`,rows:4,maxLength:2e3})]}),e.jsx($,{onClick:B,disabled:P,className:"w-full bg-indigo-600 hover:bg-indigo-700 h-11 text-base",children:P?"Sending…":"Send to "+J.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(_e,{className:"mt-6 mb-12 shadow-lg border-slate-200",children:e.jsxs(Oe,{className:"p-6 sm:p-8",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row items-center sm:items-start gap-5",children:[W!=null&&W.avatar_url?e.jsx("img",{src:W.avatar_url,alt:J,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:J.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:J}),(W==null?void 0:W.brokerage_name)&&e.jsx("p",{className:"text-slate-600 text-sm",children:W.brokerage_name}),e.jsx("p",{className:"text-slate-600 text-sm mt-2",children:"Want a private tour or more info? Reach out — I'm happy to help."})]})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-3 gap-2 mt-6",children:[ce&&e.jsx($,{asChild:!0,className:"bg-indigo-600 hover:bg-indigo-700",children:e.jsxs("a",{href:`mailto:${ce}?subject=${ue}&body=${ne}`,children:[e.jsx(nn,{className:"h-4 w-4 mr-1.5"}),"Email"]})}),(W==null?void 0:W.phone)&&e.jsx($,{asChild:!0,variant:"outline",children:e.jsxs("a",{href:`tel:${W.phone}`,children:[e.jsx(ya,{className:"h-4 w-4 mr-1.5"}),W.phone]})}),ee&&e.jsx($,{asChild:!0,variant:"outline",children:e.jsxs("a",{href:ee,target:"_blank",rel:"noreferrer",children:[e.jsx(Xu,{className:"h-4 w-4 mr-1.5"}),"Book a tour"]})})]})]})})]}),h&&V.length>0&&e.jsxs("div",{className:"fixed inset-0 z-50 bg-black/95 flex items-center justify-center",children:[e.jsx("button",{className:"absolute top-4 right-4 text-white p-2 hover:bg-white/10 rounded-full",onClick:()=>m(!1),"aria-label":"Close",children:e.jsx(pr,{className:"h-6 w-6"})}),e.jsx("button",{className:"absolute left-4 text-white p-2 hover:bg-white/10 rounded-full",onClick:()=>u(he=>(he-1+V.length)%V.length),"aria-label":"Previous",children:e.jsx(Ic,{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(he=>(he+1)%V.length),"aria-label":"Next",children:e.jsx(Ja,{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 A3s(){var i;const{slug:s}=Vi(),{data:t,isLoading:n,error:r}=EAt(s);if(j.useEffect(()=>(document.body.classList.add("agent-card-page"),()=>{document.body.classList.remove("agent-card-page")}),[]),j.useEffect(()=>{t!=null&&t.id&&Kc(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(on,{className:"h-28 w-28 rounded-full"}),e.jsx(on,{className:"h-6 w-48"}),e.jsx(on,{className:"h-4 w-36"})]}),e.jsx(on,{className:"h-12 w-full"}),e.jsx(on,{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(Ul,{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(CHe,{card:t})]})}const E3s="https://images.unsplash.com/photo-1507525428034-b723cf961d3e?w=1600&q=80",T3s="https://images.unsplash.com/photo-1616486338812-3dadae4b4ace?w=1600&q=80",M3s="https://images.unsplash.com/photo-1500534314209-a25ddb2bd429?w=1600&q=80",L3s="https://images.unsplash.com/photo-1600585154340-be6161a56a0c?w=1600&q=80",P3s="https://images.unsplash.com/photo-1519741497674-611481863552?w=1600&q=80",I3s="https://images.unsplash.com/photo-1494526585095-c41746248156?w=1600&q=80",T2e={"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:I3s},"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:E3s},"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:T3s},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:M3s},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:L3s},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:P3s}},D3s=["#111111","#2f7a7d","#c9a84c","#d84a7a","#3b6fa0","#9b72cf","#e85d3a","#4a6741"];function d6t(s){return s&&s in T2e?T2e[s]:T2e["minimal-mono"]}function R3s(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 u6t({slugOverride:s}={}){var _n;const{slug:t}=Vi(),n=s||t,[r]=oc(),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,x]=j.useState(null),[g,y]=j.useState(null),[b,v]=j.useState(!1),[N,C]=j.useState(!1),[A,T]=j.useState(0),[P,M]=j.useState(!1),[I,D]=j.useState(""),[B,q]=j.useState(""),[W,V]=j.useState(""),[K,Q]=j.useState(""),[J,ce]=j.useState(""),[ue,ne]=j.useState(""),[ee,le]=j.useState(""),[he,ve]=j.useState(""),[ge,fe]=j.useState(""),[je,Ee]=j.useState(""),[Me,De]=j.useState(""),[ze,ke]=j.useState(""),[Xe,Se]=j.useState(""),[Re,Ae]=j.useState([]),[Be,qe]=j.useState([]),[Ke,Ze]=j.useState(""),[Ue,et]=j.useState(""),[Qe,Ge]=j.useState(""),[nt,ft]=j.useState([]);j.useEffect(()=>{lt()},[n,a]);const lt=async()=>{if(!n)return;l(!0);const{data:Zs,error:gr}=await U.from("contact_intake_pages").select("*").eq("slug",n).eq("is_active",!0).maybeSingle();if(gr||!Zs){M(!0),l(!1);return}u(Zs),m.current=Zs;const{data:Un}=await U.from("profiles").select("name, avatar_url, title, phone, email, brokerage_id").eq("id",Zs.user_id).single();if(Un){let In;if(Un.brokerage_id){const{data:qs}=await U.from("brokerages").select("name").eq("id",Un.brokerage_id).single();In=(qs==null?void 0:qs.name)||void 0}let Ar=Un.avatar_url||null;if(!Ar){const{data:qs}=U.storage.from("avatars").getPublicUrl(`${Zs.user_id}/avatar.jpg`);qs!=null&&qs.publicUrl&&(Ar=`${qs.publicUrl}?t=${Date.now()}`)}const or={...Un,avatar_url:Ar,brokerage_name:In};c(or),h.current=or}if(a)try{console.log("[ConnectPage] Resolving token:",a,"for page:",Zs.id);const{data:In,error:Ar}=await U.functions.invoke("process-intake-submissions",{body:{action:"resolve_token",token:a,page_id:Zs.id}});if(console.log("[ConnectPage] Resolve result:",{resolved:In,resolveErr:Ar}),!Ar&&(In!=null&&In.contact_id)){y(In.contact_id);const or=In.contact;or&&(x(or),D(or.first_name||""),q(or.last_name||""),V(or.email||""),Q(or.phone||""),ce(or.address||""),ne(or.city||""),le(or.state||""),ve(or.zip||""),fe(or.birthday||""),Ee(or.home_anniversary||""))}}catch(In){console.error("Failed to resolve token:",In)}l(!1)},Mt=async()=>{var Zs,gr;if(!I.trim()){ae.error("Please enter your first name");return}if(!n){ae.error("Invalid page. Please refresh.");return}C(!0);try{let Un=(Zs=m.current)==null?void 0:Zs.id,In=(gr=m.current)==null?void 0:gr.user_id;if(!Un||!In){const{data:qs}=await U.from("contact_intake_pages").select("id, user_id").eq("slug",n).eq("is_active",!0).maybeSingle();if(!qs){ae.error("This page is no longer active. Please contact the agent directly."),C(!1);return}Un=qs.id,In=qs.user_id}const Ar={intake_page_id:Un,agent_user_id:In,existing_contact_id:g,first_name:I.trim(),last_name:B.trim()||null,email:W.trim()||null,phone:K.trim()||null,address:J.trim()||null,city:ue.trim()||null,state:ee.trim()||null,zip:he.trim()||null,birthday:ge||null,home_anniversary:je||null,real_estate_interest:Me||null,message:ze.trim()||null,life_events:{spouse_name:Xe.trim()||null,kids:Re.filter(qs=>qs.name.trim()),pets:Be.filter(qs=>qs.name.trim()),favorite_spots:Ke.trim()||null,dream_neighborhood:Ue.trim()||null,wedding_anniversary:Qe||null},referrals:nt.filter(qs=>qs.name.trim()&&qs.contact.trim())},{error:or}=await U.from("contact_intake_submissions").insert(Ar);if(console.log("[ConnectPage] Insert result:",{error:or}),or)throw or;a&&await U.from("contact_intake_tokens").update({used_at:new Date().toISOString()}).eq("token",a);try{const qs=[I.trim(),B.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:In,contactName:qs,contactEmail:W.trim()||null,contactPhone:K.trim()||null,slug:n})})}catch(qs){console.warn("Connect page notification failed (non-blocking):",qs)}v(!0)}catch(Un){console.error(Un),ae.error("Something went wrong. Please try again.")}finally{C(!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(Ht,{className:"h-8 w-8 animate-spin text-slate-400"})});if(P)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(b)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(Ul,{children:e.jsxs("title",{children:["Thank You | ",o==null?void 0:o.name]})}),e.jsxs(jr.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(jr.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(Fr,{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(fo,{className:"h-3.5 w-3.5"}),e.jsx("span",{children:"Powered by ReLevelUp"})]})]})]});const Ft=!!a&&!!p,Ts=(d==null?void 0:d.show_little_things)??!0,js=[{title:Ft?"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:Zs=>D(Zs.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:B,onChange:Zs=>q(Zs.target.value),placeholder:"Smith",className:"connect-input"})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium mb-1.5",style:{color:"var(--c-text-muted)"},children:"Email"}),e.jsx("input",{type:"email",value:W,onChange:Zs=>V(Zs.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:Zs=>Q(Zs.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:J,onChange:Zs=>ce(Zs.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:Zs=>ne(Zs.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:ee,onChange:Zs=>le(Zs.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:he,onChange:Zs=>ve(Zs.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:ge,onChange:Zs=>fe(Zs.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:je,onChange:Zs=>Ee(Zs.target.value),className:"connect-input"})]})]})]})},...Ts?[{title:"The Little Things",subtitle:"Optional — helps me remember what matters to you.",fields:e.jsxs("div",{className:"space-y-5",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium mb-1.5",style:{color:"var(--c-text-muted)"},children:"Spouse / partner's name"}),e.jsx("input",{type:"text",value:Xe,onChange:Zs=>Se(Zs.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:Qe,onChange:Zs=>Ge(Zs.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:()=>Ae(Zs=>[...Zs,{name:"",age:""}]),className:"text-xs inline-flex items-center gap-1",style:{color:"var(--c-accent)"},children:[e.jsx(sn,{className:"h-3 w-3"})," Add"]})]}),e.jsxs("div",{className:"space-y-2",children:[Re.length===0&&e.jsx("p",{className:"text-xs",style:{color:"var(--c-text-muted)"},children:"None to add? Skip this."}),Re.map((Zs,gr)=>e.jsxs("div",{className:"flex gap-2 items-center",children:[e.jsx("input",{type:"text",value:Zs.name,onChange:Un=>Ae(In=>In.map((Ar,or)=>or===gr?{...Ar,name:Un.target.value}:Ar)),placeholder:"Child's name",className:"connect-input min-w-0",style:{flex:"1 1 0%"}}),e.jsx("input",{type:"text",value:Zs.age,onChange:Un=>Ae(In=>In.map((Ar,or)=>or===gr?{...Ar,age:Un.target.value}:Ar)),placeholder:"Age",className:"connect-input shrink-0",style:{width:"5rem"}}),e.jsx("button",{type:"button",onClick:()=>Ae(Un=>Un.filter((In,Ar)=>Ar!==gr)),className:"p-2 rounded-md hover:bg-black/5 shrink-0","aria-label":"Remove",children:e.jsx(pr,{className:"h-3.5 w-3.5",style:{color:"var(--c-text-muted)"}})})]},gr))]})]}),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:()=>qe(Zs=>[...Zs,{name:"",kind:""}]),className:"text-xs inline-flex items-center gap-1",style:{color:"var(--c-accent)"},children:[e.jsx(sn,{className:"h-3 w-3"})," Add"]})]}),e.jsxs("div",{className:"space-y-2",children:[Be.length===0&&e.jsx("p",{className:"text-xs",style:{color:"var(--c-text-muted)"},children:"None to add? Skip this."}),Be.map((Zs,gr)=>e.jsxs("div",{className:"flex gap-2 items-center",children:[e.jsx("input",{type:"text",value:Zs.name,onChange:Un=>qe(In=>In.map((Ar,or)=>or===gr?{...Ar,name:Un.target.value}:Ar)),placeholder:"Pet's name",className:"connect-input min-w-0",style:{flex:"1 1 0%"}}),e.jsx("input",{type:"text",value:Zs.kind,onChange:Un=>qe(In=>In.map((Ar,or)=>or===gr?{...Ar,kind:Un.target.value}:Ar)),placeholder:"Dog, cat…",className:"connect-input shrink-0",style:{width:"7rem"}}),e.jsx("button",{type:"button",onClick:()=>qe(Un=>Un.filter((In,Ar)=>Ar!==gr)),className:"p-2 rounded-md hover:bg-black/5 shrink-0","aria-label":"Remove",children:e.jsx(pr,{className:"h-3.5 w-3.5",style:{color:"var(--c-text-muted)"}})})]},gr))]})]}),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:Ke,onChange:Zs=>Ze(Zs.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:Zs=>et(Zs.target.value),placeholder:"Where you'd love to live someday",className:"connect-input"})]}),e.jsxs("div",{className:"rounded-xl p-4",style:{background:"color-mix(in srgb, var(--c-accent) 8%, transparent)"},children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium",style:{color:"var(--c-text)"},children:"Know someone who'd love an agent like me?"}),e.jsx("p",{className:"text-xs",style:{color:"var(--c-text-muted)"},children:"Refer a friend — up to 3."})]}),nt.length<3&&e.jsxs("button",{type:"button",onClick:()=>ft(Zs=>[...Zs,{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(sn,{className:"h-3 w-3"})," Add"]})]}),e.jsx("div",{className:"space-y-2",children:nt.map((Zs,gr)=>e.jsxs("div",{className:"flex gap-2 items-center",children:[e.jsx("input",{type:"text",value:Zs.name,onChange:Un=>ft(In=>In.map((Ar,or)=>or===gr?{...Ar,name:Un.target.value}:Ar)),placeholder:"Their name",className:"connect-input min-w-0",style:{flex:"1 1 0%"}}),e.jsx("input",{type:"text",value:Zs.contact,onChange:Un=>ft(In=>In.map((Ar,or)=>or===gr?{...Ar,contact:Un.target.value}:Ar)),placeholder:"Phone or email",className:"connect-input min-w-0",style:{flex:"1 1 0%"}}),e.jsx("button",{type:"button",onClick:()=>ft(Un=>Un.filter((In,Ar)=>Ar!==gr)),className:"p-2 rounded-md hover:bg-black/5","aria-label":"Remove",children:e.jsx(pr,{className:"h-3.5 w-3.5",style:{color:"var(--c-text-muted)"}})})]},gr))})]})]})}]:[],{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(Zs=>e.jsxs("button",{type:"button",onClick:()=>De(Me===Zs.value?"":Zs.value),className:`p-3.5 rounded-xl border-2 text-left transition-all ${Me===Zs.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:Zs.label}),e.jsx("span",{className:"block text-xs text-slate-500 mt-0.5",children:Zs.desc})]},Zs.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:ze,onChange:Zs=>ke(Zs.target.value),placeholder:"Feel free to drop a note...",rows:3,className:"connect-input resize-none"})]})]})}],zt=js.length,Nt=d6t(d==null?void 0:d.theme),Ds=R3s(Nt,(d==null?void 0:d.accent_color)||null),_t=(d==null?void 0:d.cover_image_url)||Nt.defaultCover,Xs=(d==null?void 0:d.headline)||"Let's stay connected",rn=(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)||""),Ps=["deep-luxe"].includes((d==null?void 0:d.theme)||"");return e.jsxs("div",{className:"min-h-screen connect-shell",style:Ds,children:[e.jsxs(Ul,{children:[e.jsxs("title",{children:["Connect with ",(o==null?void 0:o.name)||"Agent"]}),e.jsx("meta",{name:"description",content:`${Xs} — ${(o==null?void 0:o.name)||"your agent"}`}),_t&&e.jsx("meta",{property:"og:image",content:_t}),e.jsx("meta",{property:"og:title",content:`Connect with ${(o==null?void 0:o.name)||"me"}`}),e.jsx("meta",{property:"og:description",content:Xs}),e.jsx("meta",{name:"twitter:card",content:"summary_large_image"})]}),e.jsx("style",{children:` .connect-shell { font-family: var(--c-body-font); color: var(--c-text); } .connect-shell h1, .connect-shell h2 { font-family: var(--c-heading-font); } .connect-input { width: 100%; padding: 0.75rem 1rem; border-radius: 0.75rem; border: 1px solid var(--c-border); background: var(--c-surface); color: var(--c-text); font-family: var(--c-body-font); font-size: 0.95rem; transition: border-color 150ms, box-shadow 150ms; } .connect-input::placeholder { color: var(--c-text-muted); opacity: 0.7; } .connect-input:focus { outline: none; border-color: var(--c-accent); box-shadow: 0 0 0 3px color-mix(in srgb, var(--c-accent) 25%, transparent); } `}),e.jsxs("div",{className:"relative w-full overflow-hidden",style:{height:"clamp(200px, 30vh, 320px)"},children:[e.jsx(jr.img,{src:_t,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(jr.h1,{initial:{opacity:0,y:12},animate:{opacity:1,y:0},transition:{delay:.15,duration:.6},style:{color:"#fff",fontFamily:Nt.headingFont,fontWeight:500,letterSpacing:"-0.01em"},className:"text-3xl sm:text-4xl leading-tight",children:Xs}),rn&&e.jsx(jr.p,{initial:{opacity:0},animate:{opacity:.9},transition:{delay:.35,duration:.6},style:{color:"#fff"},className:"text-sm mt-2",children:rn})]})]}),e.jsxs("div",{className:"max-w-lg mx-auto px-4 pb-12 -mt-12 relative",children:[e.jsxs(jr.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:Nt.accent,color:Nt.accentText,border:"4px solid var(--c-surface)"},children:e.jsx("span",{className:"text-3xl font-bold",children:((_n=o==null?void 0:o.name)==null?void 0:_n.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(ya,{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(nn,{className:"h-4 w-4"})})]})]}),e.jsx(jr.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((Zs,gr)=>e.jsx("div",{className:"h-1 flex-1 rounded-full transition-all duration-500",style:{background:gr<=A?"var(--c-accent)":"color-mix(in srgb, var(--c-text) 12%, transparent)"}},gr))}),e.jsxs(jr.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:Ps?"0 20px 40px -20px rgba(0,0,0,0.5)":"0 20px 40px -20px rgba(0,0,0,0.15)"},children:[e.jsx(Lq,{mode:"wait",children:e.jsxs(jr.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(dn,{className:"h-4 w-4",style:{color:"var(--c-accent)"}}),e.jsx("h2",{className:"text-lg font-semibold",style:{color:"var(--c-text)"},children:js[A].title})]}),js[A].subtitle&&e.jsx("p",{className:"text-xs mt-1 ml-6",style:{color:"var(--c-text-muted)"},children:js[A].subtitle})]}),js[A].fields]},A)}),e.jsxs("div",{className:"flex justify-between mt-8",children:[A>0?e.jsx("button",{type:"button",onClick:()=>T(Zs=>Zs-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()){ae.error("Please enter your first name");return}T(Zs=>Zs+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:()=>Mt(),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(Ht,{className:"h-4 w-4 animate-spin"}),"Sending..."]}):"Submit"})]}),A>0&&AT(Zs=>Zs+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(fo,{className:"h-3 w-3"}),e.jsx("span",{children:"Powered by ReLevelUp"})]})})]})]})}const Iq=()=>({trackEngagement:j.useCallback(async(t,n,r,a="view")=>{try{const{data:{user:i}}=await U.auth.getUser();if(!i)return;await U.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 aG({banners:s,autoPlayInterval:t=5e3,className:n}){const[r,a]=j.useState(0),[i,l]=j.useState(!1),{trackEngagement:o}=Iq(),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:Tt("relative w-full overflow-hidden rounded-xl",n),onMouseEnter:()=>l(!0),onMouseLeave:()=>l(!1),children:[e.jsxs("div",{className:"relative aspect-[21/9] md:aspect-[3/1] w-full",children:[e.jsx("img",{src:m.image_url,alt:m.title,className:"w-full h-full object-cover rounded-t-xl"}),s.length>1&&e.jsxs(e.Fragment,{children:[e.jsx($,{variant:"ghost",size:"icon",className:Tt("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(Ic,{className:"h-6 w-6"})}),e.jsx($,{variant:"ghost",size:"icon",className:Tt("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(Ja,{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,x)=>e.jsx("button",{onClick:()=>h(x),className:Tt("w-2 h-2 rounded-full transition-all duration-300",x===r?"bg-white w-6":"bg-white/50 hover:bg-white/70"),"aria-label":`Go to slide ${x+1}`},x))})]}),e.jsxs("div",{className:"bg-foreground rounded-b-xl px-5 py-3 flex items-center justify-between gap-4",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("h2",{className:"text-sm md:text-base font-semibold text-background truncate",children:m.title}),m.description&&e.jsx("p",{className:"text-xs text-background/70 truncate",children:m.description})]}),m.link_url&&e.jsx("a",{href:m.link_url,target:"_blank",rel:"noopener noreferrer",className:"shrink-0",onClick:()=>c(m),children:e.jsx($,{size:"sm",className:"bg-primary text-primary-foreground font-semibold transition-colors hover:bg-background hover:text-foreground",children:m.link_text||"Learn More"})})]})]})}const O3s=["reserved","scheduled_for_charge","paid","payment_failed","completed"],rU=s=>!!s&&(s.access_override||O3s.includes(s.status)),Mp=(s,t="usd")=>new Intl.NumberFormat("en-US",{style:"currency",currency:t.toUpperCase(),maximumFractionDigits:s%100===0?0:2}).format(s/100),KZ=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`},p7e=(s,t="usd",n)=>`One-time payment: ${Mp(s,t)} for the ${KZ(n)}`,lGe=[{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}],YZ=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:[]}},F3s=(s,t)=>!s.hidden.includes(t),Jot=(s,t)=>s.required.includes(t)&&!s.hidden.includes(t),gd=(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,XCe=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&&rht({queryKey:["programs"],queryFn:async()=>{const{data:s,error:t}=await U.from("programs").select("*").eq("status","published").order("is_featured",{ascending:!1}).order("sort_order",{ascending:!0});if(t)throw t;return s||[]}}),cGe=s=>ht({queryKey:["program",s],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await U.from("programs").select("*").eq("slug",s).maybeSingle();if(n)throw n;return t||null}}),m6t=s=>ht({queryKey:["program-seats",s],enabled:!!s,refetchInterval:6e4,queryFn:async()=>{const{data:t,error:n}=await U.rpc("program_seats_remaining",{_program_id:s});if(n)throw n;return t??0}}),dGe=()=>{const{user:s}=_s();return ht({queryKey:["program-enrollments",s==null?void 0:s.id],enabled:!!(s!=null&&s.id),queryFn:async()=>{const{data:t,error:n}=await U.from("program_enrollments").select("*").eq("user_id",s.id);if(n)throw n;return t||[]}})},uGe=s=>{const{data:t=[],...n}=dGe();return{...n,data:s&&t.find(r=>r.program_id===s)||null}},z3s=()=>{const{user:s}=_s(),t=ts();return yt({mutationFn:async n=>{const{data:r,error:a}=await U.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=>ae.error(n.message||"Could not save your answers")})},p6t=s=>{const{user:t}=_s();return ht({queryKey:["program-intake",s,t==null?void 0:t.id],enabled:!!s&&!!(t!=null&&t.id),queryFn:async()=>{const{data:n,error:r}=await U.from("program_intake_responses").select("*").eq("program_id",s).eq("user_id",t.id).maybeSingle();if(r)throw r;return n}})},B3s=()=>{const s=ts();return yt({mutationFn:async t=>{const{data:n,error:r}=await U.rpc("program_claim_seat",{_program_id:t});if(r)throw r;return n},onSuccess:()=>{s.invalidateQueries({queryKey:["program-enrollments"]}),s.invalidateQueries({queryKey:["program-seats"]})}})},$3s=(s,t)=>{const{user:n}=_s(),r=t||(n==null?void 0:n.id);return ht({queryKey:["program-workspace",s,r],enabled:!!s&&!!r,queryFn:async()=>{const a=r,[i,l,o,c,d,u,h,m,p,x,g]=await Promise.all([U.from("program_weeks").select("*").eq("program_id",s).order("week_number"),U.from("program_lessons").select("*").eq("program_id",s).order("sort_order"),U.from("program_resources").select("*").eq("program_id",s).order("sort_order"),U.from("program_events").select("*").eq("program_id",s).order("starts_at"),U.from("program_announcements").select("*").eq("program_id",s).order("published_at",{ascending:!1}),U.from("program_lesson_completions").select("*").eq("program_id",s).eq("user_id",a),U.from("program_weekly_progress").select("*").eq("program_id",s).eq("user_id",a).order("week_number"),U.from("program_video_logs").select("*").eq("program_id",s).eq("user_id",a).order("posted_at",{ascending:!1}),U.from("program_badge_awards").select("*").eq("program_id",s).eq("user_id",a),U.from("program_profile_analyses").select("*").eq("program_id",s).eq("user_id",a).maybeSingle(),U.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:g.data||[],events:c.data||[],announcements:d.data||[],completions:u.data||[],progress:h.data||[],videoLogs:m.data||[],badges:p.data||[],analysis:x.data||null}}})},U3s=s=>{const{user:t}=_s(),n=ts();return yt({mutationFn:async({lessonId:r,done:a})=>{if(a){const{error:i}=await U.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 U.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=>ae.error(r.message||"Could not update progress")})},q3s=s=>{const{user:t}=_s(),n=ts();return yt({mutationFn:async r=>{const{error:a}=await U.from("program_video_logs").insert({...r,program_id:s,user_id:t.id});if(a)throw a},onSuccess:()=>{ae.success("Video logged — nice work"),n.invalidateQueries({queryKey:["program-workspace"]})},onError:r=>ae.error(r.message||"Could not log the video")})},V3s=s=>{const{user:t}=_s(),n=ts();return yt({mutationFn:async r=>{const{error:a}=await U.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:()=>{ae.success("Weekly check-in saved"),n.invalidateQueries({queryKey:["program-workspace"]})},onError:r=>ae.error(r.message||"Could not save your check-in")})},H3s=s=>{const{user:t}=_s(),n=ts();return yt({mutationFn:async({eventId:r,optIn:a})=>{const{error:i}=await U.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=>ae.error(r.message||"Could not update your RSVP")})},G3s=s=>ht({queryKey:["program-discount-codes",s],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await U.from("program_discount_codes").select("*").eq("program_id",s).order("created_at",{ascending:!1});if(n)throw n;return t||[]}}),W3s=s=>{const t=ts();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 U.from("program_discount_codes").update(r).eq("id",n.id);if(a)throw a}else{const{error:a}=await U.from("program_discount_codes").insert(r);if(a)throw a}},onSuccess:()=>{ae.success("Discount code saved"),t.invalidateQueries({queryKey:["program-discount-codes"]})},onError:n=>{var r;return ae.error((r=n.message)!=null&&r.includes("duplicate")?"That code already exists for this program":n.message||"Could not save the code")}})},K3s=()=>{const s=ts();return yt({mutationFn:async t=>{const{error:n}=await U.from("program_discount_codes").delete().eq("id",t);if(n)throw n},onSuccess:()=>{ae.success("Discount code deleted"),s.invalidateQueries({queryKey:["program-discount-codes"]})},onError:t=>ae.error(t.message||"Could not delete the code")})},Y3s=()=>yt({mutationFn:async({enrollmentId:s,code:t})=>{const{data:n,error:r}=await U.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}}),Z3s=()=>yt({mutationFn:async s=>{const{error:t}=await U.rpc("program_clear_discount",{_enrollment_id:s});if(t)throw t}}),X3s=s=>ht({queryKey:["admin-program-events",s],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await U.from("program_events").select("*").eq("program_id",s).order("starts_at",{ascending:!0});if(n)throw n;return t||[]}}),Q3s=s=>{const t=ts();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 U.from("program_events").update(r).eq("id",n.id);if(a)throw a}else{const{error:a}=await U.from("program_events").insert(r);if(a)throw a}},onSuccess:()=>{ae.success("Session saved"),t.invalidateQueries({queryKey:["admin-program-events"]}),t.invalidateQueries({queryKey:["program-workspace"]})},onError:n=>ae.error(n.message||"Could not save the session")})},J3s=()=>{const s=ts();return yt({mutationFn:async t=>{const{error:n}=await U.from("program_events").delete().eq("id",t);if(n)throw n},onSuccess:()=>{ae.success("Session removed"),s.invalidateQueries({queryKey:["admin-program-events"]}),s.invalidateQueries({queryKey:["program-workspace"]})},onError:t=>ae.error(t.message||"Could not remove the session")})},eCs=s=>ht({queryKey:["admin-program-lessons",s],enabled:!!s,queryFn:async()=>{const[t,n]=await Promise.all([U.from("program_lessons").select("*").eq("program_id",s).order("sort_order"),U.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||[]}}}),tCs=s=>{const t=ts();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 U.from("program_lessons").update(r).eq("id",n.id);if(a)throw a}else{const{error:a}=await U.from("program_lessons").insert(r);if(a)throw a}},onSuccess:()=>{ae.success("Video saved"),t.invalidateQueries({queryKey:["admin-program-lessons"]}),t.invalidateQueries({queryKey:["program-workspace"]})},onError:n=>ae.error(n.message||"Could not save the video")})},sCs=()=>{const s=ts();return yt({mutationFn:async t=>{const{error:n}=await U.from("program_lessons").delete().eq("id",t);if(n)throw n},onSuccess:()=>{ae.success("Video removed"),s.invalidateQueries({queryKey:["admin-program-lessons"]}),s.invalidateQueries({queryKey:["program-workspace"]})},onError:t=>ae.error(t.message||"Could not remove the video")})},f6t=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},bY=s=>!!s&&/\.(mp4|webm|mov|m4v)(\?|$)/i.test(s),x6t=[{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"}],Dq="event-images",_ee=s=>{if(s.file_path){const{data:t}=U.storage.from(Dq).getPublicUrl(s.file_path);return t.publicUrl}return s.url||null},_Y=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 U.storage.from(Dq).download(s.file_path);if(r||!n){const c=_ee(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)},g6t=s=>ht({queryKey:["admin-program-resources",s],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await U.from("program_resources").select("*").eq("program_id",s).order("sort_order");if(n)throw n;return t||[]}}),nCs=s=>{const t=ts();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 U.from("program_resources").update(r).eq("id",n.id);if(a)throw a}else{const{error:a}=await U.from("program_resources").insert(r);if(a)throw a}},onSuccess:()=>{ae.success("Resource saved"),t.invalidateQueries({queryKey:["admin-program-resources"]}),t.invalidateQueries({queryKey:["program-workspace"]})},onError:n=>ae.error(n.message||"Could not save the resource")})},rCs=()=>{const s=ts();return yt({mutationFn:async t=>{t.file_path&&await U.storage.from(Dq).remove([t.file_path]);const{error:n}=await U.from("program_resources").delete().eq("id",t.id);if(n)throw n},onSuccess:()=>{ae.success("Resource removed"),s.invalidateQueries({queryKey:["admin-program-resources"]}),s.invalidateQueries({queryKey:["program-workspace"]})},onError:t=>ae.error(t.message||"Could not remove the resource")})},aCs=(s,t)=>ht({queryKey:["admin-program-member-resources",s,t],enabled:!!s&&!!t,queryFn:async()=>{const{data:n,error:r}=await U.from("program_member_resources").select("*").eq("program_id",s).eq("user_id",t).order("sort_order");if(r)throw r;return n||[]}}),iCs=(s,t)=>{const n=ts(),{user:r}=_s();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 U.from("program_member_resources").update(i).eq("id",a.id);if(l)throw l}else{const{error:l}=await U.from("program_member_resources").insert(i);if(l)throw l}},onSuccess:()=>{ae.success("Personal resource saved"),n.invalidateQueries({queryKey:["admin-program-member-resources"]}),n.invalidateQueries({queryKey:["program-workspace"]})},onError:a=>ae.error(a.message||"Could not save the resource")})},oCs=()=>{const s=ts();return yt({mutationFn:async t=>{t.file_path&&await U.storage.from(Dq).remove([t.file_path]);const{error:n}=await U.from("program_member_resources").delete().eq("id",t.id);if(n)throw n},onSuccess:()=>{ae.success("Personal resource removed"),s.invalidateQueries({queryKey:["admin-program-member-resources"]}),s.invalidateQueries({queryKey:["program-workspace"]})},onError:t=>ae.error(t.message||"Could not remove the resource")})},lCs=s=>{const{user:t}=_s();return ht({queryKey:["program-interest",s,t==null?void 0:t.id],enabled:!!s&&!!(t!=null&&t.id),queryFn:async()=>{const{data:n,error:r}=await U.from("program_interest").select("*").eq("program_id",s).eq("user_id",t.id).maybeSingle();if(r)throw r;return n||null}})},cCs=s=>{const t=ts(),{user:n}=_s();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 U.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 U.from("program_interest").delete().eq("program_id",s).eq("user_id",n.id);if(a)throw a}return r},onSuccess:r=>{ae.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=>ae.error(r.message||"Could not update your notify preference")})},dCs=s=>ht({queryKey:["admin-program-interest",s],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await U.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 U.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}})}}),uCs=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)},hCs=()=>{const{data:s=[]}=h6t(),{data:t=[]}=dGe(),n=new Set(t.filter(rU).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=uCs(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(w0,{className:"h-6 w-6 text-primary"})}),e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx("h3",{className:"text-lg font-semibold leading-tight",children:a.name}),l&&e.jsx($e,{variant:"secondary",children:l})]}),e.jsxs("p",{className:"mt-0.5 text-sm text-muted-foreground",children:[a.kickoff_at?`Starts ${gd(a.kickoff_at)} · `:"","Your program dashboard is live — lessons, resources and sessions inside."]})]})]}),e.jsx($,{asChild:!0,size:"lg",className:"shrink-0",children:e.jsxs(Wn,{to:`/programs/${a.slug}/workspace`,children:["Open program dashboard",e.jsx(ni,{className:"ml-1.5 h-4 w-4"})]})})]},a.id)})})},mCs={url:"/exp-agent-advantage.webp"};function pCs({className:s}){const{isMember:t,program:n,packageName:r}=ek();return!t||!((n==null?void 0:n.name)||"").toLowerCase().includes("exp")?null:e.jsxs(_e,{className:Tt("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:mCs.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(dn,{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 fCs({className:s}){var T,P,M;const{user:t}=_s(),{isMember:n,program:r,pkg:a,packageName:i}=ek(),l=j.useMemo(()=>!n||!(a!=null&&a.includes_coaching)?!1:((r==null?void 0:r.name)||"").toLowerCase().includes("exp"),[n,a,r]),{data:o}=nGe(),c=o==null?void 0:o.id,{data:d=[]}=rGe(c),{data:u=[]}=aGe(c),{data:h}=ht({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:D},{data:B}]=await Promise.all([U.from("coaching_onboarding_forms").select("submitted_at").eq("user_id",t.id).maybeSingle(),U.from("coaching_prep_checklist_items").select("id, title, sort_order").eq("package_id",a.id).eq("is_active",!0).order("sort_order"),U.from("coaching_prep_checklist_state").select("item_id").eq("user_id",t.id)]),q=new Set((B||[]).map(W=>W.item_id));return{submitted:!!(I!=null&&I.submitted_at),items:(D||[]).map(W=>({...W,done:q.has(W.id)}))}}});if(!l)return null;const m=((T=o==null?void 0:o.coachProfile)==null?void 0:T.name)||"Your LevelUp Coach",p=((P=o==null?void 0:o.coachProfile)==null?void 0:P.avatar_url)||void 0,x=(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,D)=>new Date(I.scheduled_at).getTime()-new Date(D.scheduled_at).getTime())[0],b=u.filter(I=>I.status!=="done"),v=u.length-b.length,N=(h==null?void 0:h.items)||[],C=N.filter(I=>I.done).length,A=N.length?Math.round(C/N.length*100):0;return e.jsxs(_e,{className:Tt("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(ki,{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(dn,{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:x||"1:1 accountability coaching included with your eXp Agent Advantage membership."})]}),e.jsxs("div",{className:"flex flex-col gap-2 md:items-end",children:[e.jsx($,{asChild:!0,className:"bg-white text-[#2a4c64] hover:bg-white/90",children:e.jsxs(Wn,{to:"/my-coach",children:[e.jsx(gg,{className:"mr-2 h-4 w-4"})," Book a session"]})}),e.jsx($,{asChild:!0,variant:"outline",className:"border-white/40 bg-white/10 text-white hover:bg-white/20 hover:text-white",children:e.jsxs(Wn,{to:"/my-coach",children:[e.jsx(Ji,{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(Xr,{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:Hs(new Date(y.scheduled_at),"EEE, MMM d")}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[Hs(new Date(y.scheduled_at),"h:mm a"),y.title?` · ${y.title}`:""]}),y.meeting_url&&e.jsx($,{asChild:!0,size:"sm",variant:"outline",className:"mt-3",children:e.jsx("a",{href:y.meeting_url,target:"_blank",rel:"noreferrer",children:"Join meeting"})})]}):e.jsxs(e.Fragment,{children:[e.jsxs("p",{className:"mt-2 text-sm text-muted-foreground",children:["Nothing on the calendar yet — grab a time with ",m.split(" ")[0],"."]}),e.jsx($,{asChild:!0,size:"sm",className:"mt-3",children:e.jsx(Wn,{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(Jh,{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:b.length}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"open"}),v>0&&e.jsxs($e,{variant:"secondary",className:"ml-auto",children:[v," done"]})]}),e.jsxs("ul",{className:"mt-2 space-y-1",children:[b.slice(0,3).map(I=>e.jsxs("li",{className:"flex items-start gap-2 text-sm text-muted-foreground",children:[e.jsx(Bp,{className:"mt-1 h-3 w-3 shrink-0"}),e.jsx("span",{className:"line-clamp-1",children:I.title||I.description})]},I.id)),b.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(v0,{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:[C,"/",N.length," complete"]}),e.jsxs("span",{className:"text-muted-foreground",children:[A,"%"]})]}),e.jsx(Ki,{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(Fr,{className:"mt-0.5 h-3.5 w-3.5 shrink-0 text-primary"}):e.jsx(Bp,{className:"mt-0.5 h-3.5 w-3.5 shrink-0 text-muted-foreground/50"}),e.jsx("span",{className:Tt("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(Ph,{className:"mt-0.5 h-4 w-4 shrink-0"})," Questionnaire submitted — your coach is building your plan."]}):e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"mt-2 text-sm text-muted-foreground",children:"Complete your onboarding questionnaire before session one."}),e.jsx($,{asChild:!0,size:"sm",className:"mt-3",children:e.jsx(Wn,{to:"/coaching/onboarding",children:"Start questionnaire"})})]})]})]})]})}function xCs(s){return"EST"}function ZZ(s){const n=new Intl.DateTimeFormat("en-US",{hour:"numeric",minute:"2-digit",hour12:!0,timeZone:"America/New_York"}).format(s),r=xCs();return`${n} ${r}`}function P8(s){const t=new Date,n=new Date(s),r=Vat(n,-15),a=Vat(n,30);return t>a?"ended":xN(t,{start:n,end:a})?"live":xN(t,{start:r,end:n})?"starting_soon":"upcoming"}function hGe(s){const t=P8(s);return t==="starting_soon"||t==="live"}const gCs=hGe,yCs=({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=>hGe(p.event_date));if(i.length===0)return null;const l=i[0],o=P8(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(Cg,{className:"h-4 w-4"}),"Live Now"]}):e.jsxs(e.Fragment,{children:[e.jsx(Hr,{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 ${ZZ(new Date(l.event_date))}`:`Starts at ${ZZ(new Date(l.event_date))}`})]}),e.jsx("div",{className:"flex items-center gap-2",children:u?e.jsxs($,{onClick:()=>window.open(d,"_blank"),className:`${m.button} text-white gap-2`,children:[e.jsx(Tr,{className:"h-4 w-4"}),h?"Join Now":"Join When Live"]}):e.jsxs($,{variant:"outline",onClick:n,className:`${m.outlineButton} gap-2`,children:[e.jsx(qn,{className:"h-4 w-4"}),"Register & Join"]})})]})})]})};function ux(){const{user:s}=_s(),{data:t,isLoading:n}=ht({queryKey:["gmail-integration",s==null?void 0:s.id],enabled:!!(s!=null&&s.id),queryFn:async()=>{const{data:h,error:m}=await U.from("gmail_integrations").select("*").eq("user_id",s.id).maybeSingle();if(m)throw m;return h}}),{data:r,isLoading:a}=ht({queryKey:["user-verified-ses-sender",s==null?void 0:s.id],enabled:!!s,staleTime:60*1e3,queryFn:async()=>{const{data:h}=await U.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 vCs(){var A;const{user:s}=_s(),{isGmailConnected:t,hasVerifiedSes:n,isLoading:r}=ux(),a=ek(),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&&U.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}=ht({queryKey:["new-agent-onboarding",s==null?void 0:s.id],enabled:!!(s!=null&&s.id),staleTime:3e4,queryFn:async()=>{const[T,P,M,I,D,B]=await Promise.all([U.from("profiles").select("avatar_url, phone, bio, name").eq("id",s.id).maybeSingle(),U.from("innercircle_contacts").select("id",{count:"exact",head:!0}).eq("owner_user_id",s.id),U.from("event_registrations").select("id",{count:"exact",head:!0}).eq("user_id",s.id),U.from("community_posts").select("id",{count:"exact",head:!0}).eq("user_id",s.id),U.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(),U.from("coaching_assignments").select("id").eq("agent_id",s.id).eq("status","active").limit(1)]),q=(B.data||[]).map(ue=>ue.id);let W=!1;if(q.length){const{count:ue}=await U.from("coaching_sessions").select("id",{count:"exact",head:!0}).in("assignment_id",q);W=(ue||0)>0}const V=T.data,K=!!(V!=null&&V.avatar_url&&(V!=null&&V.phone)&&(V!=null&&V.bio)),Q=P.count||0,J=(M.count||0)>0,ce=I.count||0;return{profile:V,profileComplete:K,contactsCount:Q,contactsComplete:Q>=5,eventsRegistered:J,communityComplete:ce>0,nextOnboardingEvent:D.data||null,coachingBooked:W}}}),p=t||n,x=[{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)}],g=l?x.filter(T=>T.id!=="community"&&T.id!=="event"):x;i&&g.push({id:"coaching",complete:!!(h!=null&&h.coachingBooked)});const y=g.filter(T=>T.complete).length,b=g.length;return{steps:g,completedCount:y,totalCount:b,allComplete:y===b,dismissed:o,dismiss:async()=>{s!=null&&s.id&&(c(!0),await U.from("onboarding_checklist_dismissed").insert({user_id:s.id}))},reopen:async()=>{s!=null&&s.id&&(c(!1),await U.from("onboarding_checklist_dismissed").delete().eq("user_id",s.id))},data:h,isGmailConnected:t,hasVerifiedSes:n,loading:m||r||!d||a.isLoading}}const bCs={profile:{title:"Complete Your Profile",description:"Add your headshot, phone, and short bio so contacts recognize you.",icon:Lo,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:nn,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:qn,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:ia,accent:"from-[#8b5cf6] to-[#a78bfa]",cta:"Register"},community:{title:"Say Hi in the Community",description:"Introduce yourself and connect with other LevelUp agents.",icon:Ji,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:Ph,accent:"from-[#0ea5e9] to-[#38bdf8]",cta:"Book Session"}};function _Cs(){var g,y;const s=Vn(),{user:t}=_s(),{steps:n,completedCount:r,totalCount:a,allComplete:i,dismissed:l,dismiss:o,data:c,loading:d}=vCs(),[u,h]=j.useState(!0);if(d||l||i)return null;const m=(((g=c==null?void 0:c.profile)==null?void 0:g.name)||((y=t==null?void 0:t.user_metadata)==null?void 0:y.name)||"there").split(" ")[0],p=r/a*100,x=async b=>{switch(b){case"profile":s("/profile");break;case"email":s("/mission-control/integrations");break;case"contacts":s("/mission-control/contacts");break;case"event":{const v=c==null?void 0:c.nextOnboardingEvent;if(!v){s("/events");return}if(!(t!=null&&t.id))return;const{error:N}=await U.from("event_registrations").insert({user_id:t.id,event_id:v.id});N&&!String(N.message).toLowerCase().includes("duplicate")?(ae.error("Could not register — opening events page."),s("/events")):ae.success(`You're registered for ${v.title}!`);break}case"community":s("/community");break;case"coaching":s("/my-coach");break}};return e.jsxs(_e,{className:"mb-6 overflow-hidden border-0 shadow-lg",children:[e.jsxs("div",{className:"relative bg-gradient-to-br from-[#2a4c64] via-[#345a75] to-[#406E71] p-6 md:p-8 text-white",children:[e.jsx("button",{onClick:o,className:"absolute top-4 right-4 p-1.5 rounded-full hover:bg-white/10 transition","aria-label":"Dismiss",children:e.jsx(pr,{className:"h-4 w-4"})}),e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsx("div",{className:"hidden sm:flex h-12 w-12 rounded-xl bg-white/15 backdrop-blur items-center justify-center shrink-0",children:e.jsx(dn,{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(Ki,{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($,{onClick:()=>h(!0),className:"bg-[#f5f0e0] text-[#2a4c64] hover:bg-white font-semibold",children:["Continue Setup ",e.jsx(ni,{className:"h-4 w-4 ml-1.5"})]}),e.jsx("button",{onClick:()=>h(b=>!b),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(jg,{className:"h-4 w-4"})]}):e.jsxs(e.Fragment,{children:["Show steps ",e.jsx(_o,{className:"h-4 w-4"})]})})]})]})]})]}),u&&e.jsx(Oe,{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(b=>{const v=bCs[b.id],N=v.icon;return e.jsx("div",{className:Tt("relative rounded-xl border p-4 transition-all group",b.complete?"bg-muted/40 border-muted":"bg-card hover:shadow-md hover:border-primary/40 cursor-pointer"),onClick:()=>!b.complete&&x(b.id),children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:Tt("h-10 w-10 rounded-lg flex items-center justify-center shrink-0 bg-gradient-to-br text-white",b.complete?"from-emerald-500 to-emerald-600":v.accent),children:b.complete?e.jsx(Fr,{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:Tt("font-semibold text-sm",b.complete&&"text-muted-foreground line-through"),children:v.title})}),e.jsx("p",{className:Tt("text-xs text-muted-foreground mt-1 leading-relaxed",b.complete&&"line-through"),children:v.description}),b.id==="event"&&!b.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"]}),!b.complete&&e.jsxs($,{size:"sm",variant:"ghost",className:"mt-2 h-7 px-2 -ml-2 text-primary hover:text-primary hover:bg-primary/10",onClick:C=>{C.stopPropagation(),x(b.id)},children:[v.cta," ",e.jsx(ni,{className:"h-3 w-3 ml-1"})]})]}),b.complete&&e.jsx("span",{className:"text-xs font-medium text-emerald-600 shrink-0",children:"✓ Done"})]})},b.id)})})})]})}function wCs(s){return ht({queryKey:["brokerage-content-categories",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await U.from("brokerage_content_categories").select("*").eq("brokerage_id",s).order("sort_order");if(n)throw n;return t},enabled:!!s})}function jCs(s,t){return ht({queryKey:["brokerage-content",s,t],queryFn:async()=>{if(!s)return[];let n=U.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 NCs(s,t=4){return ht({queryKey:["brokerage-content-recent",s,t],queryFn:async()=>{if(!s)return[];const{data:n,error:r}=await U.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 kCs(s){const t=ts();return yt({mutationFn:async n=>{const{data:r,error:a}=await U.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 SCs(){const s=ts();return yt({mutationFn:async t=>{const{error:n}=await U.from("brokerage_content").delete().eq("id",t);if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["brokerage-content"]}),s.invalidateQueries({queryKey:["brokerage-content-recent"]})}})}function CCs(s){const t=ts();return yt({mutationFn:async n=>{const{data:r,error:a}=await U.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 ACs(){const s=ts();return yt({mutationFn:async t=>{const{error:n}=await U.from("brokerage_content_categories").delete().eq("id",t);if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["brokerage-content-categories"]})}})}function ECs(s){const t=ts();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 U.from("brokerage_content_categories").upsert(n,{onConflict:"brokerage_id,name"});if(r)throw r},onSuccess:()=>{t.invalidateQueries({queryKey:["brokerage-content-categories"]})}})}const TCs={video:Td,pdf:Wr,link:Dc,event:ia,graphic:Rc},MCs={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 LCs(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 PCs(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 ICs({item:s}){const t=Vn(),n=TCs[s.content_type]||Dc,r=MCs[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"?LCs(s.url):null);j.useEffect(()=>{l||!s.url||s.content_type!=="video"||!PCs(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(_e,{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(Oe,{className:"p-3",children:[e.jsx("div",{className:"flex items-center gap-1.5 mb-1.5",children:e.jsxs($e,{variant:"secondary",className:`text-[10px] px-1.5 py-0 ${r}`,children:[e.jsx(n,{className:"h-3 w-3 mr-0.5"}),s.content_type]})}),e.jsx("h4",{className:"font-medium text-sm text-foreground truncate group-hover:text-primary transition-colors",children:s.title}),s.content_type==="event"&&s.event_date&&e.jsx("p",{className:"text-xs text-primary mt-1 font-medium",children:Hs(new Date(s.event_date),"MMM d · h:mm a")})]})]})}function DCs(){const{brokerageId:s}=_s(),t=Vn(),{data:n=[],isLoading:r}=NCs(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(Ai,{className:"h-5 w-5 text-primary"}),e.jsx("h3",{className:"text-lg font-semibold text-foreground",children:"Brokerage Content"})]}),e.jsxs($,{variant:"ghost",size:"sm",onClick:()=>t("/brokerage-content"),className:"gap-1 text-muted-foreground hover:text-foreground",children:["View All ",e.jsx(ni,{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(ICs,{item:a},a.id))})]})}const y6t=()=>ht({queryKey:["listing-exchange-enabled"],queryFn:async()=>{const{data:s,error:t}=await U.from("feature_flags").select("enabled").eq("key","listing_exchange_enabled").maybeSingle();if(t)throw t;return(s==null?void 0:s.enabled)??!1}}),v6t=s=>{const{user:t,brokerageId:n}=_s();return ht({queryKey:["listings",s,n],queryFn:async()=>{let r=U.from("listings").select(` *, photos:listing_photos(*), agent:profiles!listings_agent_id_fkey(id, name, email, brokerage_id, brokerage:brokerages(name)) `).eq("is_approved",!0).eq("is_public",!0);s!=null&&s.status&&(r=r.eq("status",s.status)),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 U.from("profiles").select("id").eq("brokerage_id",n);if(o&&o.length>0){const c=o.map(h=>h.id);let d=U.from("listings").select(` *, photos:listing_photos(*), agent:profiles!listings_agent_id_fkey(id, name, email, brokerage_id, brokerage:brokerages(name)) `).eq("is_approved",!0).eq("share_with_brokerage",!0).eq("is_public",!1).eq("site_only",!1).in("agent_id",c);s!=null&&s.status&&(d=d.eq("status",s.status)),s!=null&&s.propertyType&&(d=d.eq("property_type",s.propertyType)),s!=null&&s.city&&(d=d.ilike("city",`%${s.city}%`)),s!=null&&s.minPrice&&(d=d.gte("price",s.minPrice)),s!=null&&s.maxPrice&&(d=d.lte("price",s.maxPrice)),s!=null&&s.openToReferrals&&(d=d.eq("open_to_referrals",!0));const{data: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}})},b6t=()=>{const{user:s}=_s();return ht({queryKey:["my-listings",s==null?void 0:s.id],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await U.from("listings").select(` *, photos:listing_photos(*) `).eq("agent_id",s.id).order("created_at",{ascending:!1});if(n)throw n;return t},enabled:!!s})},mGe=s=>{const{user:t}=_s();return ht({queryKey:["listing",s],queryFn:async()=>{const{data:n,error:r}=await U.from("listings").select(` *, photos:listing_photos(*), agent:profiles!listings_agent_id_fkey(id, name, email, brokerage_id, brokerage:brokerages(name)), video:agent_videos!listings_video_id_fkey(id, playback_url, thumbnail_url, title, duration_seconds) `).eq("id",s).single();if(r)throw r;return t&&await U.from("listing_views").insert({listing_id:s,viewer_id:t.id}),n},enabled:!!s})},RCs=()=>{const s=ts(),{user:t}=_s();return yt({mutationFn:async n=>{if(!t)throw new Error("Not authenticated");const{data:r,error:a}=await U.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"]})}})},OCs=()=>{const s=ts();return yt({mutationFn:async({agentId:t,...n})=>{const{data:r,error:a}=await U.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"]})}})},FCs=()=>{const s=ts();return yt({mutationFn:async({id:t,...n})=>{const{data:r,error:a}=await U.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]})}})},_6t=()=>{const s=ts();return yt({mutationFn:async t=>{const{error:n}=await U.from("listings").delete().eq("id",t);if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["listings"]}),s.invalidateQueries({queryKey:["my-listings"]})}})},zCs=()=>{const s=ts();return yt({mutationFn:async({listingId:t,photoUrl:n,isPrimary:r=!1})=>{const{data:a,error:i}=await U.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"]})}})},BCs=()=>{const s=ts();return yt({mutationFn:async({photoId:t,listingId:n})=>{const{error:r}=await U.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"]})}})},$Cs=()=>{const s=ts();return yt({mutationFn:async({photos:t})=>{var i;const n=t.map(l=>U.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"]})}})},UCs=()=>{const s=ts();return yt({mutationFn:async({photoId:t,listingId:n})=>{const{error:r}=await U.from("listing_photos").update({is_primary:!1}).eq("listing_id",n);if(r)throw r;const{error:a}=await U.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"]})}})},qCs=()=>{const{user:s}=_s();return ht({queryKey:["saved-listings",s==null?void 0:s.id],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await U.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})},w6t=()=>{const s=ts(),{user:t}=_s();return yt({mutationFn:async n=>{if(!t)throw new Error("Not authenticated");const{data:r}=await U.from("listing_saves").select("id").eq("listing_id",n).eq("agent_id",t.id).maybeSingle();return r?(await U.from("listing_saves").delete().eq("id",r.id),{saved:!1}):(await U.from("listing_saves").insert({listing_id:n,agent_id:t.id}),{saved:!0})},onSuccess:()=>{s.invalidateQueries({queryKey:["saved-listings"]}),s.invalidateQueries({queryKey:["listings"]})}})},j6t=s=>{const{user:t}=_s();return ht({queryKey:["listing-saved",s,t==null?void 0:t.id],queryFn:async()=>{if(!t)return!1;const{data:n}=await U.from("listing_saves").select("id").eq("listing_id",s).eq("agent_id",t.id).maybeSingle();return!!n},enabled:!!t&&!!s})},VCs=()=>{const s=ts(),{user:t}=_s();return yt({mutationFn:async n=>{if(!t)throw new Error("Not authenticated");const{data:r}=await U.from("listing_follows").select("id").eq("listing_id",n).eq("agent_id",t.id).maybeSingle();return r?(await U.from("listing_follows").delete().eq("id",r.id),{following:!1}):(await U.from("listing_follows").insert({listing_id:n,agent_id:t.id}),{following:!0})},onSuccess:()=>{s.invalidateQueries({queryKey:["listing-following"]})}})},HCs=s=>{const{user:t}=_s();return ht({queryKey:["listing-following",s,t==null?void 0:t.id],queryFn:async()=>{if(!t)return!1;const{data:n}=await U.from("listing_follows").select("id").eq("listing_id",s).eq("agent_id",t.id).maybeSingle();return!!n},enabled:!!t&&!!s})},GCs=()=>{const{user:s}=_s();return yt({mutationFn:async({listingId:t,shareType:n})=>{if(!s)throw new Error("Not authenticated");const{error:r}=await U.from("listing_shares").insert({listing_id:t,sharing_agent_id:s.id,share_type:n});if(r)throw r}})},WCs=()=>{const{user:s}=_s();return ht({queryKey:["my-referrals",s==null?void 0:s.id],queryFn:async()=>{if(!s)return{sent:[],received:[]};const[t,n]=await Promise.all([U.from("listing_referrals").select(` *, listing:listings(*,photos:listing_photos(*)) `).eq("sender_agent_id",s.id).order("created_at",{ascending:!1}),U.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})},KCs=()=>{const s=ts(),{user:t}=_s();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 U.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"]})}})},YCs=()=>ht({queryKey:["listing-leaderboard"],queryFn:async()=>{const{data:s}=await U.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 U.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}}}),ZCs=()=>{const{user:s,brokerageId:t}=_s();return ht({queryKey:["brokerage-listings",t],queryFn:async()=>{if(!s||!t)return[];const{data:n}=await U.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 U.from("listings").select(` *, photos:listing_photos(*), 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})},N6t=({className:s,variant:t="default"})=>e.jsx($e,{variant:"outline",className:Tt("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"}),XCs={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"},QCs={coming_soon:"Coming Soon",office_exclusive:"Office Exclusive",pre_market:"Pre-Market",active:"Active",under_contract:"Under Contract",sold:"Sold",withdrawn:"Withdrawn"};function JCs(s){return s>=1e6?`$${(s/1e6).toFixed(1)}M`:`$${(s/1e3).toFixed(0)}K`}function eAs(){const s=Vn(),{data:t,isLoading:n}=y6t(),{data:r,isLoading:a}=v6t({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(_e,{className:"bg-gradient-to-br from-emerald-500/5 via-emerald-500/10 to-emerald-500/5 border-emerald-500/20",children:e.jsx(Oe,{className:"p-4",children:e.jsxs("div",{className:"animate-pulse flex items-center gap-4",children:[e.jsx("div",{className:"h-12 w-12 bg-emerald-500/20 rounded-lg"}),e.jsxs("div",{className:"flex-1 space-y-2",children:[e.jsx("div",{className:"h-4 bg-emerald-500/20 rounded w-1/3"}),e.jsx("div",{className:"h-3 bg-emerald-500/10 rounded w-1/2"})]})]})})}):e.jsxs("section",{className:"mb-10",children:[e.jsxs("div",{className:"flex items-center justify-between mb-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("h3",{className:"text-lg font-semibold text-foreground",children:"Listing Exchange"}),e.jsx(N6t,{})]}),e.jsxs($,{variant:"ghost",size:"sm",onClick:()=>s("/mission-control/listings"),className:"gap-1 text-muted-foreground hover:text-foreground",children:["View All ",e.jsx(ni,{className:"h-4 w-4"})]})]}),c.length===0?e.jsx(_e,{className:"bg-muted/30 border-dashed",children:e.jsx(Oe,{className:"flex items-center justify-center py-8",children:e.jsxs("div",{className:"text-center",children:[e.jsx(sa,{className:"h-8 w-8 text-muted-foreground/50 mx-auto mb-2"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"No listings available yet"}),e.jsx($,{variant:"link",size:"sm",onClick:()=>s("/mission-control/listings/new"),className:"mt-2",children:"Add the first listing"})]})})}):e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-3 lg:grid-cols-6 gap-3",children:c.map(u=>{var m,p;const h=((m=u.photos)==null?void 0:m.find(x=>x.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(sa,{className:"h-8 w-8 text-muted-foreground/50"})}),u.is_featured&&e.jsx("div",{className:"absolute top-1.5 left-1.5",children:e.jsxs($e,{className:"gap-1 bg-amber-500 text-white border-0 text-[10px] px-1.5 py-0.5",children:[e.jsx(Qa,{className:"h-2.5 w-2.5 fill-current"}),"Featured"]})}),e.jsx("div",{className:"absolute top-1.5 right-1.5",children:e.jsx($e,{className:`text-[10px] px-1.5 py-0.5 ${XCs[u.status]}`,children:QCs[u.status]})})]}),e.jsxs("div",{className:"p-2",children:[e.jsx("p",{className:"font-bold text-sm text-foreground",children:JCs(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 k6t(s=10,t){return ht({queryKey:["event-leaderboard",s,t],queryFn:async()=>{const{data:n}=await U.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 U.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 U.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 U.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 S6t(s){return ht({queryKey:["user-attendance-stats",s],queryFn:async()=>{if(!s)return null;const{data:t,error:n}=await U.from("agent_attendance_stats").select("*").eq("user_id",s).single();if(n&&n.code!=="PGRST116")throw n;return t},enabled:!!s})}function C6t(s){return ht({queryKey:["user-badges",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await U.from("agent_badges").select("*").eq("user_id",s).order("earned_at",{ascending:!1});if(n)throw n;return t},enabled:!!s})}function A6t(s,t){return ht({queryKey:["user-rank",s,t],queryFn:async()=>{if(!s)return null;const{data:n}=await U.from("agent_attendance_stats").select("total_points").eq("user_id",s).single();if(!n)return null;const{data:r}=await U.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 U.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 U.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 tAs(){const{user:s,brokerageId:t,isAdmin:n}=_s();Vn();const r=!!t,[a,i]=j.useState("brokerage"),l=()=>{if(n)return null;if(r)return a==="global"?null:t},{data:o,isLoading:c}=k6t(5,l()),{data:d}=S6t(s==null?void 0:s.id),{data:u}=A6t(s==null?void 0:s.id,l()),{data:h}=C6t(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(_e,{children:[e.jsx(Bt,{className:"pb-2",children:e.jsxs(Ut,{className:"text-base flex items-center gap-2",children:[e.jsx(pl,{className:"h-4 w-4 text-yellow-500"}),p()]})}),e.jsx(Oe,{children:e.jsx("div",{className:"space-y-2",children:[...Array(m?5:3)].map((g,y)=>e.jsx(on,{className:"h-10 w-full"},y))})})]});const x=g=>g===0?e.jsx(pl,{className:"h-4 w-4 text-yellow-500 mx-auto"}):g===1?e.jsx("span",{className:"text-sm font-medium text-gray-400",children:"2"}):g===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:g+1});if(m){const g=(o==null?void 0:o.slice(0,5))||[];return e.jsxs(_e,{children:[e.jsxs(Bt,{className:"pb-2",children:[e.jsxs(Ut,{className:"text-base flex items-center gap-2",children:[e.jsx(pl,{className:"h-4 w-4 text-yellow-500"}),p()]}),!n&&r&&e.jsxs("div",{className:"flex gap-1 mt-2",children:[e.jsx($,{variant:a==="brokerage"?"default":"outline",size:"sm",className:"text-xs h-7 flex-1",onClick:()=>i("brokerage"),children:"My Brokerage"}),e.jsx($,{variant:a==="global"?"default":"outline",size:"sm",className:"text-xs h-7 flex-1",onClick:()=>i("global"),children:"All LevelUp"})]})]}),e.jsxs(Oe,{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:[g.map((y,b)=>{var v,N,C;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":b===0?"bg-yellow-500/10":""}`,children:[e.jsx("div",{className:"w-5 text-center",children:x(b)}),e.jsx(Ea,{className:"h-6 w-6",children:e.jsx(Ta,{className:"text-xs",children:((N=(v=y.profile)==null?void 0:v.name)==null?void 0:N.charAt(0))||"?"})}),e.jsx("span",{className:"flex-1 text-sm font-medium truncate",children:((C=y.profile)==null?void 0:C.name)||"Unknown"}),e.jsx("span",{className:"text-sm font-bold text-primary",children:y.total_points})]},y.user_id)}),g.length===0&&e.jsx("div",{className:"text-center text-muted-foreground py-2 text-sm",children:"No data yet"})]}),e.jsxs(Wn,{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(Co,{className:"h-4 w-4"}),"Spend Points in Reward Store",e.jsx(Ja,{className:"h-4 w-4"})]})]})]})}return e.jsxs(_e,{children:[e.jsx(Bt,{className:"pb-2",children:e.jsxs(Ut,{className:"text-base flex items-center gap-2",children:[e.jsx(pl,{className:"h-4 w-4 text-yellow-500"}),"My Points"]})}),e.jsx(Oe,{children:d?e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"p-3 rounded-lg bg-primary/5 border border-primary/10 text-center",children:[e.jsx("div",{className:"text-2xl font-bold text-primary",children:d.total_points}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Total Points"})]}),e.jsxs("div",{className:"p-3 rounded-lg bg-muted/50 text-center",children:[e.jsx("div",{className:"text-2xl font-bold",children:d.total_events_attended}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Events Attended"})]})]}),e.jsxs("div",{className:"flex items-center justify-between p-2 rounded-lg bg-orange-500/10 border border-orange-500/20",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(yd,{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(pu,{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(g=>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:g.badge_name},g.id)),h.length>4&&e.jsxs("span",{className:"text-xs text-muted-foreground px-2 py-1",children:["+",h.length-4," more"]})]})]}),e.jsxs(Wn,{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(Co,{className:"h-4 w-4"}),"Spend Points in Reward Store",e.jsx(Ja,{className:"h-4 w-4"})]})]}):e.jsxs("div",{className:"text-center text-muted-foreground py-4 text-sm",children:[e.jsx(Qa,{className:"h-8 w-8 mx-auto mb-2 text-muted-foreground/50"}),e.jsx("p",{children:"Attend events to earn points!"}),e.jsxs(Wn,{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(Co,{className:"h-4 w-4"}),"Visit Reward Store",e.jsx(Ja,{className:"h-4 w-4"})]})]})})]})}const Hb=()=>ht({queryKey:["relationship-types"],queryFn:async()=>{const{data:s,error:t}=await U.from("relationship_types").select("*").order("sort_order");if(t)throw t;return s}}),E6t=()=>{const s=Za(),t=1e3;return ht({queryKey:["innercircle-contacts-lite",s],queryFn:async()=>{const n=[];let r=0;for(;;){const{data:a,error:i}=await U.from("innercircle_contacts").select("id, first_name, last_name, email, phone, address, 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=Za(),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=U.from("innercircle_contacts").select(` *, lead_source_ref:lead_sources(id, name), tags:innercircle_contact_tags( id, contact_id, relationship_type_id, relationship_type:relationship_types(*) ) `).eq("owner_user_id",t).order("created_at",{ascending:!1}).order("first_name");return await r(a)},enabled:!!t})},sAs=s=>ht({queryKey:["innercircle-contact",s],queryFn:async()=>{const{data:t,error:n}=await U.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}),T6t=()=>{const s=Za();return ht({queryKey:["innercircle-contact-counts",s],queryFn:async()=>{const{data:t,error:n}=await U.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})},QCe=()=>{const s=ts(),t=Za();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 U.from("innercircle_contacts").insert(i).select().single();if(o)throw o;if(r&&r.length>0){const{error:c}=await U.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"]}),ja({title:"Contact created successfully"})},onError:n=>{ja({title:"Error creating contact",description:n.message,variant:"destructive"})}})},pGe=()=>{const s=ts();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 U.from("innercircle_contacts").update(o).eq("id",t).select().single();if(d)throw d;if(r!==void 0&&(await U.from("innercircle_contact_tags").delete().eq("contact_id",t),r.length>0)){const{error:u}=await U.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"]}),ja({title:"Contact updated successfully"})},onError:t=>{ja({title:"Error updating contact",description:t.message,variant:"destructive"})}})},M6t=()=>{const s=ts();return yt({mutationFn:async({contactId:t,spouseContactId:n})=>{if(n){const{error:r}=await U.from("innercircle_contacts").update({spouse_contact_id:n}).eq("id",t);if(r)throw r;const{error:a}=await U.from("innercircle_contacts").update({spouse_contact_id:t}).eq("id",n);if(a)throw a}else{const{data:r}=await U.from("innercircle_contacts").select("spouse_contact_id").eq("id",t).single(),a=r==null?void 0:r.spouse_contact_id,{error:i}=await U.from("innercircle_contacts").update({spouse_contact_id:null}).eq("id",t);if(i)throw i;if(a){const{error:l}=await U.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"]}),ja({title:"Spouse link updated"})},onError:t=>{ja({title:"Error linking spouse",description:t.message,variant:"destructive"})}})},fGe=()=>{const s=ts();return yt({mutationFn:async t=>{const{error:n}=await U.from("innercircle_contacts").delete().eq("id",t);if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["innercircle-contacts"]}),s.invalidateQueries({queryKey:["innercircle-contact-counts"]}),ja({title:"Contact deleted successfully"})},onError:t=>{ja({title:"Error deleting contact",description:t.message,variant:"destructive"})}})},wee=()=>ht({queryKey:["action-types"],queryFn:async()=>{const{data:s,error:t}=await U.from("action_types").select("*").order("sort_order");if(t)throw t;return s}}),nAs=s=>ht({queryKey:["action-scripts",s],queryFn:async()=>{let t=U.from("action_scripts").select("*, action_type:action_types(*)");const{data:n,error:r}=await t;if(r)throw r;return n}}),rAs=()=>ht({queryKey:["touchpoint-plans"],queryFn:async()=>{const{data:s,error:t}=await U.from("touchpoint_plans").select(` *, items:touchpoint_plan_items( *, action_type:action_types(*), default_script:action_scripts(*) ) `).order("name");if(t)throw t;return s}}),aAs=()=>{const s=ts(),t=Za();return yt({mutationFn:async({name:n,description:r})=>{const{data:a,error:i}=await U.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"]}),ja({title:"Plan created successfully"})},onError:n=>{ja({title:"Error creating plan",description:n.message,variant:"destructive"})}})},iAs=()=>{const s=ts(),t=Za();return yt({mutationFn:async({sourcePlanId:n,newName:r})=>{const{data:a,error:i}=await U.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 U.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 U.from("touchpoint_plan_items").insert(c);if(d)throw d}return l},onSuccess:()=>{s.invalidateQueries({queryKey:["touchpoint-plans"]}),ja({title:"Plan duplicated successfully",description:"You can now edit your copy of this plan."})},onError:n=>{ja({title:"Error duplicating plan",description:n.message,variant:"destructive"})}})},oAs=()=>{const s=ts();return yt({mutationFn:async({id:t,name:n,description:r})=>{const{data:a,error:i}=await U.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"]}),ja({title:"Plan updated successfully"})}})},lAs=()=>{const s=ts();return yt({mutationFn:async t=>{const{error:n}=await U.from("touchpoint_plans").delete().eq("id",t);if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["touchpoint-plans"]}),ja({title:"Plan deleted successfully"})}})},cAs=()=>{const s=ts();return yt({mutationFn:async({planId:t,items:n})=>{if(await U.from("touchpoint_plan_items").delete().eq("plan_id",t),n.length>0){const{error:r}=await U.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"]}),ja({title:"Plan schedule updated"})}})},dAs=()=>{const s=ts();return yt({mutationFn:async({actionTypeId:t,title:n,scriptBody:r,emailSubject:a,tone:i})=>{const{data:{user:l}}=await U.auth.getUser(),{data:o,error:c}=await U.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"]}),ja({title:"Script created successfully"})},onError:t=>{ja({title:"Error creating script",description:t.message,variant:"destructive"})}})},uAs=()=>{const s=Za();return ht({queryKey:["user-plan-enrollments",s],queryFn:async()=>{const{data:t,error:n}=await U.from("user_plan_enrollments").select(` *, plan:touchpoint_plans(*), relationship_type:relationship_types(*) `);if(n)throw n;return t},enabled:!!s})},hAs=()=>{const s=ts(),t=Za();return yt({mutationFn:async({planId:n,relationshipTypeId:r,active:a})=>{const{data:i}=await U.from("user_plan_enrollments").select("id").eq("plan_id",n).eq("relationship_type_id",r).maybeSingle();if(i){const{error:l}=await U.from("user_plan_enrollments").update({active:a}).eq("id",i.id);if(l)throw l}else if(a){const{error:l}=await U.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"]}),ja({title:"Plan enrollment updated"})}})},Rq=(s=7)=>{const t=Za();return ht({queryKey:["contact-touch-logs",t,s],queryFn:async()=>{const n=new Date;n.setDate(n.getDate()-s);const{data:r,error:a}=await U.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})},L6t=()=>{const s=Za();return ht({queryKey:["contacts-last-touch",s],queryFn:async()=>{const{data:t,error:n}=await U.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})},mAs=(s=90)=>{const{data:t}=M1(),{data:n}=L6t();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=ts(),t=Za();return yt({mutationFn:async({contactId:n,actionTypeId:r,scriptUsedId:a,notes:i,completedAt:l})=>{const{data:o,error:c}=await U.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"]}),ja({title:"Action completed!"});try{const[l,o]=await Promise.all([U.from("innercircle_contacts").select("email").eq("id",r.contactId).single(),U.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)&&U.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&&U.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{}}})},P6t="agentos_weekly_touch_goal",elt=20,I6t=()=>{if(typeof window>"u")return elt;const s=localStorage.getItem(P6t);if(s){const t=parseInt(s,10);if(!isNaN(t)&&t>0)return t}return elt},pAs=s=>{localStorage.setItem(P6t,s.toString())},eAe=()=>{const{data:s}=Rq(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=I6t();return{actionsThisWeek:r,weeklyGoal:i,streak:a,progress:Math.min(r/i*100,100)}},fAs=()=>{const s=Za();return ht({queryKey:["contact-plan-cycles",s],queryFn:async()=>{const{data:t,error:n}=await U.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})},xAs=()=>{const s=ts();return Za(),yt({mutationFn:async()=>{var c;const{data:t}=await U.from("user_plan_enrollments").select("*").eq("active",!0);if(!t||t.length===0)return;const{data:n}=await U.auth.getUser(),r=(c=n==null?void 0:n.user)==null?void 0:c.id;if(!r)return;const{data:a}=await U.from("innercircle_contacts").select(` id, tags:innercircle_contact_tags(relationship_type_id) `).eq("owner_user_id",r);if(!a)return;const{data:i}=await U.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 U.from("contact_plan_cycles").insert(o);if(d)throw d}return o.length},onSuccess:t=>{s.invalidateQueries({queryKey:["contact-plan-cycles"]}),t&&t>0&&ja({title:`${t} contact(s) enrolled in plans`})}})},xGe=()=>{const s=Za(),{data:t}=fAs(),{data:n}=Rq(30);return ht({queryKey:["today-actions",s,t==null?void 0:t.length,n==null?void 0:n.length],queryFn:async()=>{var x;if(!t||t.length===0)return[];const{data:r}=await U.from("contact_snoozes").select("contact_id").gte("snoozed_until",new Date().toISOString()),a=new Set((r==null?void 0:r.map(g=>g.contact_id))||[]),i=new Date,l=[],o=new Date(i.getFullYear(),i.getMonth(),1),c=new Set((n==null?void 0:n.filter(g=>new Date(g.completed_at)>=o).map(g=>`${g.contact_id}-${g.action_type_id}`))||[]);for(const g of t){if(!((x=g.plan)!=null&&x.items)||g.plan.items.length===0||!g.contact||a.has(g.contact_id))continue;const y=new Date(g.cycle_start_date),v=Math.floor((i.getTime()-y.getTime())/(30.44*24*60*60*1e3))%12+1,N=g.plan.items.find(C=>C.month_number===v);if(N&&N.action_type){const C=`${g.contact_id}-${N.action_type_id}`;if(!c.has(C)){const{data:A}=await U.from("relationship_types").select("name").eq("id",g.relationship_type_id).single();l.push({contact:g.contact,actionType:N.action_type,script:N.default_script||void 0,planName:g.plan.name,relationshipTypeName:(A==null?void 0:A.name)||"",monthNumber:v})}}}const d=5,u=i.getDate(),h=l.sort((g,y)=>g.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})},XO=()=>ht({queryKey:["lead-sources"],queryFn:async()=>{const{data:s,error:t}=await U.from("lead_sources").select("*").eq("is_active",!0).order("sort_order");if(t)throw t;return s}}),gGe=()=>{const s=ts(),{user:t}=_s();return yt({mutationFn:async n=>{const{data:r}=await U.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 U.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"]}),ae.success("Lead source added")},onError:n=>{ae.error("Failed to add lead source"),console.error(n)}})},gAs=()=>{const s=ts();return yt({mutationFn:async({id:t,name:n})=>{const{error:r}=await U.from("lead_sources").update({name:n}).eq("id",t);if(r)throw r},onSuccess:()=>{s.invalidateQueries({queryKey:["lead-sources"]}),ae.success("Lead source updated")},onError:t=>{ae.error(t.message||"Failed to update lead source")}})},yAs=()=>{const s=ts();return yt({mutationFn:async t=>{const{error:n}=await U.from("lead_sources").update({is_active:!1}).eq("id",t);if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["lead-sources"]}),ae.success("Lead source removed")},onError:t=>{ae.error(t.message||"Failed to remove lead source")}})},yGe=(s,t)=>{const{user:n,isAdmin:r}=_s(),a=r&&t?t:n==null?void 0:n.id;return ht({queryKey:["scorecard-transactions",s,a],queryFn:async()=>{let i=U.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})},vGe=s=>{const{user:t,isAdmin:n}=_s(),r=n&&s?s:t==null?void 0:t.id;return ht({queryKey:["scorecard-transactions-all",r],queryFn:async()=>{const{data:a,error:i}=await U.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})},tAe=()=>{const s=ts(),{user:t}=_s();return yt({mutationFn:async n=>{const{data:r,error:a}=await U.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"]}),ae.success("Transaction added")},onError:n=>{ae.error("Failed to add transaction"),console.error(n)}})},vAs=()=>{const s=ts();return yt({mutationFn:async({id:t,...n})=>{const{data:r,error:a}=await U.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"]}),ae.success("Transaction updated")},onError:t=>{ae.error("Failed to update transaction"),console.error(t)}})},bAs=()=>{const s=ts();return yt({mutationFn:async t=>{const{error:n}=await U.from("scorecard_transactions").delete().eq("id",t);if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["scorecard-transactions"]}),s.invalidateQueries({queryKey:["scorecard-transactions-all"]}),ae.success("Transaction deleted")},onError:t=>{ae.error("Failed to delete transaction"),console.error(t)}})},D6t=(s,t)=>{const{user:n,isAdmin:r}=_s(),a=r&&t?t:n==null?void 0:n.id;return ht({queryKey:["scorecard-goals",s,a],queryFn:async()=>{const{data:i,error:l}=await U.from("scorecard_goals").select("*").eq("owner_user_id",a).eq("year",s).maybeSingle();if(l)throw l;return i},enabled:!!a})},_As=()=>{const s=ts(),{user:t}=_s();return yt({mutationFn:async n=>{const{data:r,error:a}=await U.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]}),ae.success("Goals saved")},onError:n=>{ae.error("Failed to save goals"),console.error(n)}})},sAe=()=>{const{user:s}=_s();return ht({queryKey:["scorecard-settings",s==null?void 0:s.id],queryFn:async()=>{const{data:t,error:n}=await U.from("scorecard_settings").select("*").eq("user_id",s.id).maybeSingle();if(n)throw n;return t},enabled:!!(s!=null&&s.id)})},wAs=()=>{const s=ts(),{user:t}=_s();return yt({mutationFn:async n=>{const{data:r,error:a}=await U.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"]}),ae.success("Settings saved")},onError:n=>{ae.error("Failed to save settings"),console.error(n)}})},R6t=(s,t)=>{const{data:n,isLoading:r}=yGe(s,t),{data:a,isLoading:i}=vGe(t),{data:l}=sAe(),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),x=d.reduce((A,T)=>{const P=Number(T.commission_amount)||0;if(!P)return A;let M=P;return T.brokerage_split_pct&&(M-=P*(T.brokerage_split_pct/100)),T.team_split_pct&&(M-=P*(T.team_split_pct/100)),T.franchise_fee_pct&&(M-=P*(T.franchise_fee_pct/100)),T.referral_fee_pct&&(M-=P*(T.referral_fee_pct/100)),T.transaction_fee&&(M-=T.transaction_fee),A+Math.max(0,M)},0),g={};d.forEach(A=>{var P;const T=((P=A.lead_source)==null?void 0:P.name)||"Unknown";g[T]=(g[T]||0)+1});const y=Object.entries(g).map(([A,T])=>({name:A,count:T})).sort((A,T)=>T.count-A.count),b=y[0]||null,v={};d.forEach(A=>{const T=mu(A.close_date).toLocaleString("default",{month:"short"});v[T]=(v[T]||0)+1});const C=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"].map(A=>({month:A,count:v[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?x:0,topLeadSource:b,transactionsByMonth:C,leadSourceBreakdown:y}};return{yearStats:c(n),lifetimeStats:c(a),isLoading:r||i,showCommission:o}},jAs=()=>{const{isAdmin:s}=_s();return ht({queryKey:["agents-with-transactions"],queryFn:async()=>{const{data:t,error:n}=await U.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 U.from("profiles").select("id, name, email").in("id",r);if(i)throw i;return a},enabled:s})},FA={recency:40,touchpoints:30,transactions:20,referrals:10},tlt={warm:70,cooling:40};function NAs(s){return s===null?0:s<=14?FA.recency:s<=30?FA.recency*.85:s<=60?FA.recency*.65:s<=90?FA.recency*.4:s<=180?FA.recency*.2:FA.recency*.05}function kAs(s){const t=Math.min(s/12,1);return Math.round(FA.touchpoints*t)}function SAs(s){return s?FA.transactions:0}function CAs(){return 0}function AAs(s){return s>=tlt.warm?"warm":s>=tlt.cooling?"cooling":"at-risk"}function jee(){const{data:s,isLoading:t}=M1(),{data:n}=L6t(),{data:r}=Rq(365),{data:a}=vGe(),i=j.useMemo(()=>{if(!s)return[];const o=new Date,c=T8(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?r2(o,new Date(m)):null,x=d[h.id]||0,g=u.has(h.id),y=NAs(p),b=kAs(x),v=SAs(g),N=CAs(),C=Math.round(y+b+v+N),A={score:C,status:AAs(C),breakdown:{recency:Math.round(y),touchpoints:Math.round(b),transactions:Math.round(v),referrals:Math.round(N)},lastTouchDate:m,daysSinceTouch:p,touchCountLast12Months:x,hasTransaction:g};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 EAs(s){const{contactsWithScores:t,isLoading:n}=jee(),r=j.useMemo(()=>t.find(a=>a.id===s),[t,s]);return{score:r==null?void 0:r.relationshipScore,isLoading:n}}function O6t(){const s=Vn(),{stats:t,contactsWithScores:n,isLoading:r}=jee();if(r)return e.jsxs(_e,{children:[e.jsx(Bt,{className:"pb-2",children:e.jsx(on,{className:"h-5 w-40"})}),e.jsxs(Oe,{className:"space-y-4",children:[e.jsx(on,{className:"h-20 w-full"}),e.jsx(on,{className:"h-16 w-full"})]})]});if(t.total===0)return e.jsxs(_e,{children:[e.jsx(Bt,{className:"pb-2",children:e.jsxs(Ut,{className:"text-lg flex items-center gap-2",children:[e.jsx(qn,{className:"h-5 w-5"}),"Relationship Health"]})}),e.jsxs(Oe,{children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Add contacts to see your relationship health scores."}),e.jsx($,{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(_e,{children:[e.jsxs(Bt,{className:"pb-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(Ut,{className:"text-lg flex items-center gap-2",children:[e.jsx(Il,{className:"h-5 w-5 text-emerald-500"}),"Relationship Health"]}),e.jsx("span",{className:"text-2xl font-bold",children:t.averageScore})]}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Average score across ",t.total," contacts"]})]}),e.jsxs(Oe,{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"flex items-center justify-between text-sm",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"h-2.5 w-2.5 rounded-full bg-emerald-500"}),e.jsx("span",{children:"Warm"})]}),e.jsxs("span",{className:"font-medium",children:[t.warm," (",a,"%)"]})]}),e.jsx(Ki,{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(Ki,{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(Ki,{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(FN,{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(Ja,{className:"h-3 w-3"})]})]},c.id))})]}),e.jsxs($,{variant:"outline",size:"sm",className:"w-full",onClick:()=>s("/mission-control/contacts?filter=at-risk"),children:["View All At-Risk Contacts",e.jsx(Ja,{className:"h-4 w-4 ml-1"})]})]})]})}const TAs=()=>{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"},MAs=()=>new Intl.DateTimeFormat("en-US",{weekday:"long",month:"long",day:"numeric",timeZone:"America/New_York"}).format(new Date);function LAs({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 PAs({name:s,eventsThisWeek:t=0}){const n=Vn(),{user:r}=_s(),{data:a}=xGe(),{data:i}=E6t(),l=eAe(),{hasAccess:o,hasAssignment:c}=xCt(),{hasFeature:d}=ek(),{data:u}=ht({queryKey:["hub-active-listings",r==null?void 0:r.id],enabled:!!(r!=null&&r.id),queryFn:async()=>{const{count:N,error:C}=await U.from("listings").select("id",{count:"exact",head:!0}).eq("agent_id",r.id);return C?0:N||0}}),h=j.useMemo(()=>{if(!i)return 0;const N=Date.now()-7*24*60*60*1e3;return i.filter(C=>C.created_at&&new Date(C.created_at).getTime()>=N).length},[i]),m=(a==null?void 0:a.length)||0,p=(l==null?void 0:l.streak)||0,x=(l==null?void 0:l.actionsThisWeek)||0,g=(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(" • "),b=[{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:yd}],v=[{label:"Add Contact",icon:il,to:"/mission-control/contacts?new=true"},...d("social")?[{label:"Create Post",icon:vd,to:"/social-swag-2"}]:[],...d("presentations")?[{label:"Listing Presentation",icon:by,to:"/mission-control/listing-presentations"}]:[],...o?[{label:"Book Coaching",icon:Xu,to:c?"/my-coach":"/coaching"}]:[],{label:"Ask AI",icon:dn,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:MAs()}),e.jsxs("h1",{className:"mt-1 text-2xl sm:text-3xl font-bold",children:[TAs(),", ",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:b.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(LAs,{value:x,goal:g}),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:x>=g?"Goal crushed 🎉":`${g-x} 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(ni,{className:"h-3 w-3"})]})]})]})]}),e.jsx("div",{className:"hub-scroll relative mt-5 flex gap-2 overflow-x-auto pb-1",children:v.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 H9=24*60*60*1e3,IAs=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}},Rne=s=>{const t=IAs(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,RAs=s=>s===0?"today":s===1?"tomorrow":`in ${s} days`,OAs={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}},FAs=(s=5)=>{const t=Za(),{data:n,isLoading:r}=xGe(),{data:a,isLoading:i}=M1(),l=ht({queryKey:["smart-queue",t,n==null?void 0:n.length,a==null?void 0:a.length],queryFn:async()=>{var P;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 D;d({key:`plan-${M.contact.id}-${I}`,contact:M.contact,kind:"plan",actionLabel:((D=M.actionType)==null?void 0:D.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:x}]=await Promise.all([U.from("contact_snoozes").select("contact_id").gte("snoozed_until",new Date().toISOString()),U.from("contact_touch_logs").select("contact_id").eq("owner_user_id",t).gte("completed_at",new Date(Date.now()-14*H9).toISOString()),U.from("contact_touch_logs").select("contact_id").eq("owner_user_id",t).gte("completed_at",new Date(Date.now()-90*H9).toISOString())]),g=new Set([...(m||[]).map(M=>M.contact_id),...(p||[]).map(M=>M.contact_id)]),y=new Set((x||[]).map(M=>M.contact_id)),b=M=>!g.has(M)&&!c.has(M);for(const M of u){if(!b(M.id))continue;const D=[{days:Rne(M.birthday),label:"Birthday"},{days:Rne(M.home_anniversary),label:"Home anniversary"},{days:Rne(M.wedding_anniversary),label:"Wedding anniversary"},{days:Rne(M.spouse_birthday),label:`${M.spouse_name||"Spouse"}'s birthday`}].find(B=>DAs(B.days,7));D&&d({key:`milestone-${M.id}`,contact:M,kind:"milestone",actionLabel:"Send wishes",reason:`${D.label} ${RAs(D.days)}`,priority:D.days===0?1:5+D.days})}const{data:v}=await U.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 v||[]){const I=h.get(M.contact_id);if(!I||!b(M.contact_id))continue;const D=OAs[M.signal_type]||{reason:M.title||"Recent activity",action:"Follow up",priority:27};d({key:`signal-${M.contact_id}`,contact:I,kind:"signal",actionLabel:D.action,reason:D.reason,priority:D.priority})}const{data:N}=await U.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||!b(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 C=Date.now()-3*H9;for(const M of u)b(M.id)&&(y.has(M.id)||new Date(M.created_at).getTime()b(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}},zAs=()=>{const s=Za(),t=ts();return yt({mutationFn:async n=>{const r=new Date(Date.now()+14*H9).toISOString(),{error:a}=await U.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"]}),ja({title:"Snoozed for 14 days"})},onError:n=>ja({title:"Could not snooze",description:n.message,variant:"destructive"})})},BAs=s=>(s||"?").split(" ").map(t=>t[0]).slice(0,2).join("").toUpperCase(),$As={plan:{icon:gy,tint:"var(--nav-crm)"},milestone:{icon:np,tint:"var(--nav-events)"},signal:{icon:yd,tint:"var(--nav-marketing)"},deal:{icon:ix,tint:"var(--nav-listings)"},new:{icon:dn,tint:"var(--nav-apps)"},cold:{icon:Z_,tint:"var(--nav-more)"}};function UAs(){const s=Vn(),{data:t,isLoading:n}=FAs(5),r=zAs(),a=eAe(),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(Mu,{className:"h-4 w-4",style:{color:"hsl(var(--nav-crm))"}})}),"Today's Top 5"]}),e.jsx("p",{className:"mt-1 text-sm text-muted-foreground",children:o.length>0?"Picked for you from your plans, milestones and live activity.":"Your queue is clear."})]}),e.jsxs($,{variant:"ghost",size:"sm",className:"gap-1",onClick:()=>s("/mission-control"),children:["Agent OS ",e.jsx(Ja,{className:"h-4 w-4"})]})]}),n?e.jsx("div",{className:"space-y-2",children:[0,1,2].map(c=>e.jsx(on,{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(Fr,{className:"mx-auto mb-2 h-7 w-7 text-muted-foreground/50"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Nothing due today. Add a new contact to your database to keep the pipeline full."}),e.jsxs($,{size:"sm",variant:"outline",className:"mt-3 gap-1.5",onClick:()=>s("/mission-control/contacts?new=true"),children:[e.jsx(il,{className:"h-3.5 w-3.5"})," Add Contact"]})]}):e.jsx(JN,{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=$As[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:BAs(u)}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:"truncate text-sm font-medium text-foreground",children:u}),e.jsxs("div",{className:"mt-0.5 flex flex-wrap items-center gap-1.5",children:[e.jsxs($e,{variant:"secondary",className:"gap-1 text-[10px]",style:{background:`hsl(${h.tint} / 0.12)`,color:`hsl(${h.tint})`},children:[e.jsx(m,{className:"h-3 w-3"}),c.actionLabel]}),e.jsx("span",{className:"truncate text-xs text-muted-foreground",children:c.reason})]})]}),e.jsxs("div",{className:"flex shrink-0 items-center gap-1",children:[e.jsx(qAs,{contact:d,onOpen:()=>s(`/mission-control/contacts/${d.id}`)}),e.jsxs(Mx,{children:[e.jsx(Lx,{asChild:!0,children:e.jsx($,{size:"icon",variant:"ghost",className:"h-8 w-8 text-muted-foreground opacity-0 transition-opacity group-hover:opacity-100 focus-visible:opacity-100","aria-label":"Not now",disabled:r.isPending,onClick:()=>r.mutate(d.id),children:e.jsx(pr,{className:"h-4 w-4"})})}),e.jsx(tx,{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(Ki,{value:Math.min(i/l*100,100),className:"h-2"})]})]})}function qAs({contact:s,onOpen:t}){const n=(s==null?void 0:s.phone)||(s==null?void 0:s.mobile_phone),r=s==null?void 0:s.email;return e.jsxs(e.Fragment,{children:[n&&e.jsx($,{asChild:!0,size:"icon",variant:"ghost",className:"h-8 w-8","aria-label":"Call",children:e.jsx("a",{href:`tel:${n}`,onClick:a=>a.stopPropagation(),children:e.jsx(ya,{className:"h-4 w-4"})})}),n&&e.jsx($,{asChild:!0,size:"icon",variant:"ghost",className:"h-8 w-8","aria-label":"Text",children:e.jsx("a",{href:`sms:${n}`,onClick:a=>a.stopPropagation(),children:e.jsx(Ji,{className:"h-4 w-4"})})}),r&&e.jsx($,{asChild:!0,size:"icon",variant:"ghost",className:"h-8 w-8","aria-label":"Email",children:e.jsx("a",{href:`mailto:${r}`,onClick:a=>a.stopPropagation(),children:e.jsx(nn,{className:"h-4 w-4"})})}),e.jsx($,{size:"icon",variant:"ghost",className:"h-8 w-8","aria-label":"Open contact",onClick:t,children:e.jsx(Ja,{className:"h-4 w-4"})})]})}const VAs=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 HAs({events:s,registrations:t}){const n=Vn(),{data:r}=nGe(),{data:a}=ht({queryKey:["hub-upcoming-sessions",r==null?void 0:r.id],enabled:!!(r!=null&&r.id),queryFn:async()=>{const{data:l,error:o}=await U.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:gCs(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(Nl,{className:"h-4 w-4",style:{color:"hsl(var(--nav-events))"}})}),"Up Next"]}),e.jsxs($,{variant:"ghost",size:"sm",className:"gap-1",onClick:()=>n("/events"),children:["All ",e.jsx(Ja,{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(Nl,{className:"mx-auto mb-2 h-7 w-7 text-muted-foreground/50"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Nothing scheduled yet."}),e.jsx($,{size:"sm",variant:"outline",className:"mt-3",onClick:()=>n("/events"),children:"Browse Events"})]}):e.jsx("ol",{className:"relative space-y-1",children:i.map(l=>e.jsx("li",{children:e.jsxs("button",{onClick:l.onClick,className:"group flex w-full items-start gap-3 rounded-xl p-2.5 text-left transition-colors hover:bg-muted/50",children:[e.jsx("span",{className:"mt-0.5 flex h-9 w-9 shrink-0 items-center justify-center rounded-lg",style:{background:l.kind==="coaching"?"hsl(var(--nav-academy) / 0.14)":"hsl(var(--nav-events) / 0.14)"},children:l.live?e.jsx(Cg,{className:"h-4 w-4 text-destructive"}):l.kind==="coaching"?e.jsx(Ph,{className:"h-4 w-4",style:{color:"hsl(var(--nav-academy))"}}):e.jsx(Xr,{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":`${VAs(l.date)} · ${ZZ(l.date)}`," ·"," ",l.subtitle]})]}),l.joinUrl&&e.jsxs($,{size:"sm",variant:l.live?"destructive":"secondary",className:"h-7 shrink-0 gap-1 px-2 text-xs",onClick:o=>{o.stopPropagation(),window.open(l.joinUrl,"_blank")},children:[e.jsx(Tr,{className:"h-3 w-3"})," Join"]})]})},l.id))})]})}const slt=s=>s>=1e6?`$${(s/1e6).toFixed(1)}M`:s>=1e3?`$${Math.round(s/1e3)}K`:`$${s}`;function GAs(){const s=Vn(),{data:t,isLoading:n}=ht({queryKey:["hub-pipeline-snapshot"],queryFn:async()=>{const{data:r,error:a}=await U.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,x;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:((x=u.stage)==null?void 0:x.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(a5,{className:"h-4 w-4",style:{color:"hsl(var(--nav-listings))"}})}),"Pipeline"]}),e.jsxs($,{variant:"ghost",size:"sm",className:"gap-1",onClick:()=>s("/mission-control/pipeline"),children:["Open ",e.jsx(Ja,{className:"h-4 w-4"})]})]}),n?e.jsxs("div",{className:"space-y-2",children:[e.jsx(on,{className:"h-12 w-full"}),e.jsx(on,{className:"h-16 w-full"})]}):!t||t.openCount+t.wonCount===0?e.jsxs("div",{className:"flex flex-1 flex-col items-center justify-center rounded-xl border border-dashed border-border bg-muted/30 p-5 text-center",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"No deals yet. Start tracking your buyers and sellers."}),e.jsx($,{size:"sm",variant:"outline",className:"mt-3",onClick:()=>s("/mission-control/pipeline"),children:"Create a Deal"})]}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"rounded-xl bg-muted/40 p-3",children:[e.jsx("p",{className:"text-2xl font-bold text-foreground",children:t.openCount}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Open deals"})]}),e.jsxs("div",{className:"rounded-xl bg-muted/40 p-3",children:[e.jsx("p",{className:"text-2xl font-bold text-foreground",children:slt(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:slt(t.wonVolume)})," volume"]})]})]})}function WAs(){const s=Vn(),{user:t}=_s(),{hasFeature:n}=ek(),{data:r}=ht({queryKey:["hub-jump-back-in",t==null?void 0:t.id],enabled:!!(t!=null&&t.id),queryFn:async()=>{const i=[],l=U,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:by,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:sa,hue:"--nav-websites",to:`/mission-control/listings/${u.id}`})),i.push({id:"marketing",label:"Create a post",sub:"Marketing Studio",icon:Eh,hue:"--nav-marketing",to:"/marketing-studio"}),i.slice(0,8)}}),a=(r||[]).filter(i=>{const l=o4t(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(Hr,{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(ni,{className:"h-4 w-4 shrink-0 text-muted-foreground opacity-0 transition-opacity group-hover:opacity-100"})]},i.id))})]})}function KAs({videos:s,kits:t,templates:n,services:r}){const a=Vn(),i=[{id:"videos",label:"Academy",icon:Sh,hue:"--nav-academy",items:s,viewAll:"/academy",emptyText:"No new videos yet."},{id:"kits",label:"Resource Kits",icon:cv,hue:"--nav-apps",items:t,viewAll:"/toolbox",emptyText:"No resource kits yet."},{id:"templates",label:"Templates",icon:gT,hue:"--nav-marketing",items:n,viewAll:"/templates",emptyText:"No new templates yet.",fit:"contain"},{id:"services",label:"Services",icon:dn,hue:"--nav-crm",items:r,viewAll:"/additional-services",emptyText:"No additional services yet."}],[l,o]=j.useState(i[0].id),c=i.find(d=>d.id===l)||i[0];return e.jsxs("section",{className:"mb-10",children:[e.jsxs("div",{className:"mb-4 flex flex-wrap items-center justify-between gap-3",children:[e.jsx("h3",{className:"text-lg font-semibold text-foreground",children:"Fresh for you"}),e.jsxs($,{variant:"ghost",size:"sm",className:"gap-1 text-muted-foreground hover:text-foreground",onClick:()=>a(c.viewAll),children:["View All ",e.jsx(ni,{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 YAs=()=>{var ne;const{user:s,isAdmin:t}=_s(),n=Vn(),{hasFeature:r}=ek(),[a,i]=j.useState([]),[l,o]=j.useState([]),[c,d]=j.useState([]),[u,h]=j.useState([]),[m,p]=j.useState([]),[x,g]=j.useState([]),[y,b]=j.useState(new Set),[v,N]=j.useState([]),[C,A]=j.useState([]),[T,P]=j.useState([]),[M,I]=j.useState(null),[D,B]=j.useState(!0);j.useEffect(()=>{q()},[s]);const q=async()=>{var ee,le,he,ve,ge;try{const[fe,je,Ee,Me,De,ze,ke,Xe,Se,Re,Ae]=await Promise.all([U.from("user_tags").select("tag").eq("user_id",s==null?void 0:s.id),U.from("app_tiles").select("*").order("name"),U.from("user_favorites").select("app_id").eq("user_id",s==null?void 0:s.id),U.from("events").select("*").order("event_date",{ascending:!0}),U.from("event_registrations").select("event_id, zoom_join_url").eq("user_id",s==null?void 0:s.id),U.from("canva_templates").select("id, name, preview_image_url, publish_date").order("publish_date",{ascending:!1}).limit(4),U.from("resource_kits").select("id, name, description, featured_image_url, publish_date").eq("is_published",!0).order("publish_date",{ascending:!1}).limit(4),U.from("academy_videos").select("id, title, description, thumbnail_url, duration, publish_date").eq("is_published",!0).order("publish_date",{ascending:!1}).limit(4),U.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),U.from("dashboard_banners").select("id, title, description, image_url, link_url, link_text, placement, section_after").eq("is_active",!0).order("sort_order"),U.from("profiles").select("name").eq("id",s==null?void 0:s.id).single()]);(ee=Ae.data)!=null&&ee.name&&I(Ae.data.name);const Be=((le=fe.data)==null?void 0:le.map(Qe=>Qe.tag))||[],qe=new Set(((he=Ee.data)==null?void 0:he.map(Qe=>Qe.app_id))||[]);b(qe);const Ze=(((ve=je.data)==null?void 0:ve.filter(Qe=>!Qe.required_tags||Qe.required_tags.length===0?!0:Qe.required_tags.some(Ge=>Be.includes(Ge))))||[]).sort((Qe,Ge)=>Qe.name==="LevelUp Members Portal"?-1:Ge.name==="LevelUp Members Portal"?1:0);i(Ze.slice(0,6));const Ue=((ge=Me.data)==null?void 0:ge.filter(Qe=>P8(Qe.event_date)!=="ended"))||[];o(Ue.slice(0,4)),N(De.data||[]),d(ze.data||[]),h(ke.data||[]),p(Xe.data||[]),g(Se.data||[]);const et=Re.data||[];A(et.filter(Qe=>Qe.placement==="top")),P(et.filter(Qe=>Qe.placement==="between"))}catch(fe){console.error("Error loading dashboard:",fe),ae.error("Failed to load dashboard data")}finally{B(!1)}},W=async ee=>{var he;const le=window.open("about:blank","_blank");try{await U.from("activity_logs").insert({user_id:s==null?void 0:s.id,app_id:ee.app_id,app_name:ee.name,user_agent:navigator.userAgent});const{data:ve,error:ge}=await U.functions.invoke("sso-launch",{body:{app_id:ee.app_id}});if(ge)throw ge;ve!=null&&ve.redirect_url?le&&!le.closed?(le.location.href=ve.redirect_url,(he=le.focus)==null||he.call(le)):window.location.assign(ve.redirect_url):(le==null||le.close(),ae.error("Launch link unavailable"))}catch(ve){le==null||le.close(),console.error("Error launching app:",ve),ae.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(ee=>{const le=V[ee.name]||V[ee.app_id];return!le||r(le)}),Q=ee=>T.filter(le=>le.section_after===ee),J=(M||((ne=s==null?void 0:s.user_metadata)==null?void 0:ne.name)||"there").split(" ")[0],ce=Date.now()+7*24*60*60*1e3,ue=l.filter(ee=>new Date(ee.event_date).getTime()<=ce).length;return e.jsxs(Ks,{title:"Dashboard",children:[r("learn")&&e.jsx(yCs,{events:l,registrations:v,onNavigateToEvents:()=>n("/events")}),e.jsx(hCs,{}),e.jsx(pCs,{}),e.jsx(fCs,{}),e.jsx(PAs,{name:J,eventsThisWeek:ue}),e.jsx(_Cs,{}),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(UAs,{})}),r("learn")&&e.jsx(HAs,{events:l,registrations:v})]}),e.jsxs("div",{className:"grid grid-cols-1 gap-4 mb-8 lg:grid-cols-3",children:[e.jsx(O6t,{}),r("deals")&&e.jsx(GAs,{}),r("learn")&&e.jsx(tAs,{})]}),e.jsx(WAs,{}),C.length>0&&e.jsx("div",{className:"mb-8",children:e.jsx(aG,{banners:C})}),e.jsx(DCs,{}),D?e.jsx("div",{className:"mb-10 grid grid-cols-2 gap-4 md:grid-cols-4",children:[0,1,2,3].map(ee=>e.jsx("div",{className:"h-44 rounded-2xl bg-muted/40 animate-pulse"},ee))}):e.jsx(KAs,{videos:(r("learn")?m:[]).map(ee=>({id:ee.id,title:ee.title,image:ee.thumbnail_url,meta:ee.duration,onOpen:()=>n(`/academy/${ee.id}`)})),kits:(r("learn")?u:[]).map(ee=>({id:ee.id,title:ee.name,image:ee.featured_image_url,onOpen:()=>n(`/toolbox/${ee.id}`)})),templates:(r("marketing_studio")?c:[]).map(ee=>({id:ee.id,title:ee.name,image:ee.preview_image_url,onOpen:()=>n("/templates")})),services:x.map(ee=>({id:ee.id,title:ee.name,image:ee.preview_image_url,onOpen:()=>window.open(ee.signup_link_url,"_blank")}))}),Q("academy").length>0&&e.jsx("div",{className:"mb-10",children:e.jsx(aG,{banners:Q("academy")})}),r("listing_exchange")&&e.jsx("div",{className:"mb-10",children:e.jsx(eAs,{})}),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($,{variant:"ghost",size:"sm",onClick:()=>n("/apps"),className:"gap-1 text-muted-foreground hover:text-foreground",children:["View All ",e.jsx(ni,{className:"h-4 w-4"})]})]}),K.length===0?e.jsx(_e,{className:"bg-muted/30 border-dashed",children:e.jsx(Oe,{className:"flex items-center justify-center py-12",children:e.jsxs("div",{className:"text-center",children:[e.jsx(wg,{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(ee=>{const le=y.has(ee.id);return e.jsxs("div",{onClick:()=>W(ee),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:ee.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:ee.name}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1 line-clamp-2",children:ee.description})]}),le&&e.jsx(wg,{className:"h-5 w-5 text-primary fill-current flex-shrink-0"})]},ee.id)})})]}),Q("templates").length>0&&e.jsx("div",{className:"mb-10",children:e.jsx(aG,{banners:Q("templates")})}),Q("events").length>0&&e.jsx("div",{className:"mb-10",children:e.jsx(aG,{banners:Q("events")})}),Q("toolbox").length>0&&e.jsx("div",{className:"mb-10",children:e.jsx(aG,{banners:Q("toolbox")})})]})},ZAs=[{key:"contacts",label:"Contacts",icon:ya,description:"View, add, and edit contacts"},{key:"pipeline",label:"Deal Pipeline",icon:gR,description:"View, add, and move deals"},{key:"client_portal",label:"Client Portals",icon:cv,description:"Manage client portals on deals"},{key:"videos",label:"Videos",icon:Xr,description:"View and upload videos"},{key:"listings",label:"Listings",icon:sa,description:"View, create, and edit listings"},{key:"scorecard",label:"Scorecard",icon:v0,description:"View and add transactions"},{key:"popbys",label:"Pop-bys",icon:ai,description:"View and log pop-bys"},{key:"digital_card",label:"Digital Card",icon:yy,description:"Create and edit digital business card"},{key:"guest_book",label:"Guest Book",icon:wf,description:"Manage open house guest books"},{key:"presentations",label:"Presentations",icon:by,description:"Create and manage smart presentations"}];function XAs(){var P;const{user:s}=_s(),[t,n]=j.useState([]),[r,a]=j.useState(!0),[i,l]=j.useState(!1),[o,c]=j.useState(!1),[d,u]=j.useState(null),[h,m]=j.useState({email:"",name:"",password:""}),[p,x]=j.useState("create"),[g,y]=j.useState(!1),[b,v]=j.useState(null);j.useEffect(()=>{s&&N()},[s]);const N=async()=>{if(s){a(!0);try{const{data:M,error:I}=await U.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 D=M.map(W=>W.assistant_id),{data:B}=await U.from("profiles").select("id, name, email").in("id",D),q=M.map(W=>{const V=B==null?void 0:B.find(K=>K.id===W.assistant_id);return{...W,permissions:W.permissions,assistant_profile:V?{name:V.name||"",email:V.email||""}:void 0}});n(q)}else n([])}catch(M){console.error("Error loading assistants:",M)}finally{a(!1)}}},C=async()=>{if(s){if(p==="link"){if(!h.email.trim()){ae.error("Please enter the assistant's email");return}y(!0);try{const{data:{session:M}}=await U.auth.getSession();if(!M)throw new Error("Not authenticated");const{data:I,error:D}=await U.from("profiles").select("id, name, email").eq("email",h.email.trim().toLowerCase()).single();if(D||!I){ae.error("No account found with that email. Try creating a new assistant instead.");return}const{data:B}=await U.from("agent_assistant_assignments").select("id").eq("agent_id",s.id).eq("assistant_id",I.id);if(B&&B.length>0){ae.error("This assistant is already assigned to you");return}const q=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})}),W=await q.json();if(!q.ok)throw new Error(W.error||"Failed to assign assistant role");const{error:V}=await U.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;ae.success(`${I.name||I.email} linked as your assistant`),l(!1),m({email:"",name:"",password:""}),N()}catch(M){console.error("Error linking assistant:",M),ae.error(M.message||"Failed to link assistant")}finally{y(!1)}return}if(!h.email.trim()||!h.name.trim()||!h.password.trim()){ae.error("Please fill in all fields");return}if(h.password.length<6){ae.error("Password must be at least 6 characters");return}y(!0);try{const{data:{session:M}}=await U.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"})}),D=await I.json();if(!I.ok)throw new Error(D.error||"Failed to create assistant account");const B=D.userId||D.id;if(!B)throw new Error("No user ID returned");const q=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:B,role:"assistant",action:"add",agentId:s.id})}),W=await q.json();if(!q.ok)throw new Error(W.error||"Failed to assign assistant role");const{error:V}=await U.from("agent_assistant_assignments").insert({agent_id:s.id,assistant_id:B,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;ae.success(`Assistant account created for ${h.name.trim()}`),l(!1),m({email:"",name:"",password:""}),N()}catch(M){console.error("Error adding assistant:",M),ae.error(M.message||"Failed to add assistant")}finally{y(!1)}}},A=async()=>{if(!(!d||!s))try{const{data:{session:M}}=await U.auth.getSession();if(!M)throw new Error("Not authenticated");const{error:I}=await U.from("agent_assistant_assignments").delete().eq("id",d.id);if(I)throw I;const{data:D}=await U.from("agent_assistant_assignments").select("id").eq("assistant_id",d.assistant_id);(!D||D.length===0)&&await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/manage-user-roles",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${M.access_token}`},body:JSON.stringify({userId:d.assistant_id,role:"assistant",action:"remove"})}),ae.success("Assistant removed"),c(!1),u(null),N()}catch(M){console.error("Error removing assistant:",M),ae.error(M.message||"Failed to remove assistant")}},T=async(M,I,D)=>{v(M);try{const B=t.find(V=>V.id===M);if(!B)return;const q={...B.permissions,[I]:D},{error:W}=await U.from("agent_assistant_assignments").update({permissions:q}).eq("id",M);if(W)throw W;n(V=>V.map(K=>K.id===M?{...K,permissions:q}:K))}catch(B){console.error("Error updating permissions:",B),ae.error("Failed to update permissions")}finally{v(null)}};return r?e.jsxs(_e,{children:[e.jsx(Bt,{children:e.jsxs(Ut,{className:"flex items-center gap-2",children:[e.jsx(qn,{className:"h-5 w-5"}),"My Assistants"]})}),e.jsx(Oe,{children:e.jsx("div",{className:"flex items-center justify-center py-4",children:e.jsx(Ht,{className:"h-6 w-6 animate-spin text-muted-foreground"})})})]}):e.jsxs(e.Fragment,{children:[e.jsxs(_e,{children:[e.jsx(Bt,{children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsxs(Ut,{className:"flex items-center gap-2",children:[e.jsx(qn,{className:"h-5 w-5"}),"My Assistants"]}),e.jsx(vr,{children:"Add assistants to help manage your Agent OS"})]}),e.jsxs($,{size:"sm",onClick:()=>{x("create"),l(!0)},children:[e.jsx(sn,{className:"h-4 w-4 mr-1"}),"Add Assistant"]})]})}),e.jsx(Oe,{children:t.length===0?e.jsx("p",{className:"text-sm text-muted-foreground text-center py-4",children:"No assistant assigned. Add one to help manage your contacts, deals, and more."}):e.jsx("div",{className:"space-y-4",children:t.map(M=>{var I,D,B,q;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:((D=(I=M.assistant_profile)==null?void 0:I.name)==null?void 0:D.split(" ").map(W=>W[0]).join("").toUpperCase())||"A"})}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:((B=M.assistant_profile)==null?void 0:B.name)||"Unknown"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:((q=M.assistant_profile)==null?void 0:q.email)||""})]}),e.jsxs($e,{variant:"secondary",className:"ml-2",children:[e.jsx(kf,{className:"h-3 w-3 mr-1"}),"Assistant"]})]}),e.jsx($,{variant:"ghost",size:"sm",className:"text-destructive hover:text-destructive",onClick:()=>{u(M),c(!0)},children:e.jsx(Pn,{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:ZAs.map(W=>{const V=W.icon;return e.jsxs("div",{className:"flex items-center justify-between p-2 rounded-md border",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(V,{className:"h-4 w-4 text-muted-foreground"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium",children:W.label}),e.jsx("p",{className:"text-xs text-muted-foreground",children:W.description})]})]}),e.jsx(Tn,{checked:M.permissions[W.key]||!1,onCheckedChange:K=>T(M.id,W.key,K),disabled:b===M.id})]},W.key)})})]})]},M.id)})})})]}),e.jsx(Os,{open:i,onOpenChange:l,children:e.jsxs(Rs,{children:[e.jsxs(Us,{children:[e.jsx(zs,{children:"Add Assistant"}),e.jsx(Sr,{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($,{variant:p==="create"?"default":"outline",size:"sm",onClick:()=>x("create"),children:[e.jsx(sn,{className:"h-3 w-3 mr-1"}),"Create New"]}),e.jsxs($,{variant:p==="link"?"default":"outline",size:"sm",onClick:()=>x("link"),children:[e.jsx(kc,{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(se,{htmlFor:"assistant-name",children:"Name"}),e.jsx(be,{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(se,{htmlFor:"assistant-email",children:"Email"}),e.jsx(be,{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(se,{htmlFor:"assistant-password",children:"Temporary Password"}),e.jsx(be,{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(kr,{children:[e.jsx($,{variant:"outline",onClick:()=>l(!1),children:"Cancel"}),e.jsxs($,{onClick:C,disabled:g,children:[g&&e.jsx(Ht,{className:"h-4 w-4 mr-2 animate-spin"}),p==="create"?"Create Assistant":"Link Assistant"]})]})]})}),e.jsx(Ll,{open:o,onOpenChange:c,children:e.jsxs(yl,{children:[e.jsxs(vl,{children:[e.jsx(_l,{children:"Remove Assistant?"}),e.jsxs(wl,{children:["This will remove ",(P=d==null?void 0:d.assistant_profile)==null?void 0:P.name,"'s access to your Agent OS. Their account will remain active but they won't be able to manage your data."]})]}),e.jsxs(bl,{children:[e.jsx(jl,{children:"Cancel"}),e.jsx(fl,{onClick:A,className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Remove"})]})]})})]})}function ry(s){this.content=s}ry.prototype={constructor:ry,find:function(s){for(var t=0;t>1}};ry.from=function(s){if(s instanceof ry)return s;var t=[];if(s)for(var n in s)t.push(n,s[n]);return new ry(t)};function F6t(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=F6t(a.content,i.content,n+1);if(l!=null)return l}n+=a.nodeSize}}function z6t(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 Vv(r,a)}cutByIndex(t,n){return t==n?Vv.empty:t==0&&n==this.content.length?this:new Vv(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 Vv(a,i)}addToStart(t){return new Vv([t].concat(this.content),this.size+t.nodeSize)}addToEnd(t){return new Vv(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?One(n+1,i):One(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 Vv.empty;if(!Array.isArray(n))throw new RangeError("Invalid input for Fragment.fromJSON");return new Vv(n.map(t.nodeFromJSON))}static fromArray(t){if(!t.length)return Vv.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}};Ah.none=[];class iSe extends Error{}class xi{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=$6t(this.content,t+this.openStart,n);return r&&new xi(r,this.openStart,this.openEnd)}removeBetween(t,n){return new xi(B6t(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 xi.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 xi(Ia.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 xi(t,r,a)}}xi.empty=new xi(Ia.empty,0,0);function B6t(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(B6t(i.content,t-a-1,n-a-1)))}function $6t(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=$6t(l.content,t-i-1,n,l);return o&&s.replaceChild(a,l.copy(o))}function QAs(s,t,n){if(n.openStart>s.depth)throw new iSe("Inserted content deeper than insertion position");if(s.depth-n.openStart!=t.depth-n.openEnd)throw new iSe("Inconsistent open depths");return U6t(s,t,n,0)}function U6t(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 wY(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&&(MR(s.nodeAfter,r),i++));for(let o=i;oa&&x7e(s,t,a+1),l=r.depth>a&&x7e(n,r,a+1),o=[];return wY(null,s,a,o),i&&l&&t.index(a)==n.index(a)?(q6t(i,l),MR(LR(i,V6t(s,t,n,r,a+1)),o)):(i&&MR(LR(i,oSe(s,t,a+1)),o),wY(t,n,a,o),l&&MR(LR(l,oSe(n,r,a+1)),o)),wY(r,null,a,o),new Ia(o)}function oSe(s,t,n){let r=[];if(wY(null,s,n,r),s.depth>n){let a=x7e(s,t,n+1);MR(LR(a,oSe(s,t,n+1)),r)}return wY(t,null,n,r),new Ia(r)}function JAs(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(Ia.from(a));return{start:a.resolveNoCache(s.openStart+n),end:a.resolveNoCache(a.content.size-s.openEnd-n)}}class XZ{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 lSe(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 XZ(n,r,i)}static resolveCached(t,n){let r=nlt.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()+")"),H6t(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=Ia.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=Ia.fromJSON(t,n.content),i=t.nodeType(n.type).create(n.attrs,a,r);return i.type.checkAttrs(i.attrs),i}};FT.prototype.text=void 0;class cSe extends FT{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):H6t(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 cSe(this.type,this.attrs,this.text,t)}withText(t){return t==this.text?this:new cSe(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 H6t(s,t){for(let n=s.length-1;n>=0;n--)t=s[n].type.name+"("+t+")";return t}class hO{constructor(t){this.validEnd=t,this.next=[],this.wrapCache=[]}static parse(t,n){let r=new nEs(t,n);if(r.next==null)return hO.empty;let a=G6t(r);r.next&&r.err("Unexpected trailing text");let i=dEs(cEs(a));return uEs(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(` `)}}hO.empty=new hO(!0);class nEs{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 G6t(s){let t=[];do t.push(rEs(s));while(s.eat("|"));return t.length==1?t[0]:{type:"choice",exprs:t}}function rEs(s){let t=[];do t.push(aEs(s));while(s.next&&s.next!=")"&&s.next!="|");return t.length==1?t[0]:{type:"seq",exprs:t}}function aEs(s){let t=lEs(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=iEs(s,t);else break;return t}function rlt(s){/\D/.test(s.next)&&s.err("Expected number, got '"+s.next+"'");let t=Number(s.next);return s.pos++,t}function iEs(s,t){let n=rlt(s),r=n;return s.eat(",")&&(s.next!="}"?r=rlt(s):r=-1),s.eat("}")||s.err("Unclosed braced range"),{type:"range",min:n,max:r,expr:t}}function oEs(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 lEs(s){if(s.eat("(")){let t=G6t(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=oEs(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 cEs(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 hO(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:Y6t(this.attrs,t)}create(t=null,n,r){if(this.isText)throw new Error("NodeType.create can't construct text nodes");return new FT(this,this.computeAttrs(t),Ia.from(n),Ah.setFrom(r))}createChecked(t=null,n,r){return n=Ia.from(n),this.checkContent(n),new FT(this,this.computeAttrs(t),n,Ah.setFrom(r))}createAndFill(t=null,n,r){if(t=this.computeAttrs(t),n=Ia.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(Ia.empty,!0);return i?new FT(this,t,n.append(i),Ah.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 Q6t(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 hEs(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 mEs{constructor(t,n,r){this.hasDefault=Object.prototype.hasOwnProperty.call(r,"default"),this.default=r.default,this.validate=typeof r.validate=="string"?hEs(t,n,r.validate):r.validate}get isRequired(){return!this.hasDefault}}class nAe{constructor(t,n,r,a){this.name=t,this.rank=n,this.schema=r,this.spec=a,this.attrs=X6t(t,a.attrs),this.excluded=null;let i=K6t(this.attrs);this.instance=i?new Ah(this,i):null}create(t=null){return!t&&this.instance?this.instance:new Ah(this,Y6t(this.attrs,t))}static compile(t,n){let r=Object.create(null),a=0;return t.forEach((i,l)=>r[i]=new nAe(i,a++,n,l)),r}removeFromSet(t){for(var n=0;n-1}}let J6t=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=ry.from(t.nodes),n.marks=ry.from(t.marks||{}),this.nodes=ilt.compile(this.spec.nodes,this),this.marks=nAe.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]=hO.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?olt(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==""?[]:olt(this,l.split(" "))}this.nodeFromJSON=a=>FT.fromJSON(this,a),this.markFromJSON=a=>Ah.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 ilt){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 cSe(r,r.defaultAttrs,t,Ah.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 olt(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 pEs(s){return s.tag!=null}function fEs(s){return s.style!=null}let jY=class y7e{constructor(t,n){this.schema=t,this.rules=n,this.tags=[],this.styles=[];let r=this.matchedStyles=[];n.forEach(a=>{if(pEs(a))this.tags.push(a);else if(fEs(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 clt(this,n,!1);return r.addAll(t,Ah.none,n.from,n.to),r.finish()}parseSlice(t,n={}){let r=new clt(this,n,!0);return r.addAll(t,Ah.none,n.from,n.to),xi.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=dlt(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=dlt(l)),l.node||l.ignore||l.mark||(l.node=a)})}return n}static fromSchema(t){return t.cached.domParser||(t.cached.domParser=new y7e(t,y7e.schemaRules(t)))}};const eMt={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},xEs={head:!0,noscript:!0,object:!0,script:!0,style:!0,title:!0},tMt={ol:!0,ul:!0},QZ=1,v7e=2,NY=4;function llt(s,t,n){return t!=null?(t?QZ:0)|(t==="full"?v7e:0):s&&s.whitespace=="pre"?QZ|v7e:n&~NY}class Fne{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=Ah.none,this.match=i||(l&NY?null:t.contentMatch)}findWrapping(t){if(!this.match){if(!this.type)return[];let n=this.type.contentMatch.fillBefore(Ia.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&QZ)){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=Ia.from(this.content);return!t&&this.match&&(n=n.append(this.match.fillBefore(Ia.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&&!eMt.hasOwnProperty(t.parentNode.nodeName.toLowerCase())}}class clt{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=llt(null,n.preserveWhitespace,0)|(r?NY:0);a?i=new Fne(a.type,a.attrs,Ah.none,!0,n.topMatch||a.type.contentMatch,l):r?i=new Fne(null,null,Ah.none,!0,null,l):i=new Fne(t.schema.topNodeType,null,Ah.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&v7e?"full":this.localPreserveWS||(a.options&QZ)>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):ult(d.type,t))?(c=d.addToSet(c),!1):!0),this.nodes.push(new Fne(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|=QZ)}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 gEs(s){for(let t=s.firstChild,n=null;t;t=t.nextSibling){let r=t.nodeType==1?t.nodeName.toLowerCase():null;r&&tMt.hasOwnProperty(r)&&n?(n.appendChild(t),t=n):r=="li"?n=t:r&&(n=null)}}function yEs(s,t){return(s.matches||s.msMatchesSelector||s.webkitMatchesSelector||s.mozMatchesSelector).call(s,t)}function dlt(s){let t={};for(let n in s)t[n]=s[n];return t}function ult(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&&M2e(NPe(r),a(t,n),null,t.attrs)}static renderSpec(t,n,r=null,a){return M2e(t,n,r,a)}static fromSchema(t){return t.cached.domSerializer||(t.cached.domSerializer=new QO(this.nodesFromSchema(t),this.marksFromSchema(t)))}static nodesFromSchema(t){let n=hlt(t.nodes);return n.text||(n.text=r=>r.text),n}static marksFromSchema(t){return hlt(t.marks)}}function hlt(s){let t={};for(let n in s){let r=s[n].spec.toDOM;r&&(t[n]=r)}return t}function NPe(s){return s.document||window.document}const mlt=new WeakMap;function vEs(s){let t=mlt.get(s);return t===void 0&&mlt.set(s,t=bEs(s)),t}function bEs(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:x}=M2e(s,m,n,r);if(c.appendChild(p),x){if(o)throw new RangeError("Multiple content holes");o=x}}}return{dom:c,contentDOM:o}}const sMt=65535,nMt=Math.pow(2,16);function _Es(s,t){return s+t*nMt}function plt(s){return s&sMt}function wEs(s){return(s-(s&sMt))/nMt}const rMt=1,aMt=2,L2e=4,iMt=8;class b7e{constructor(t,n,r){this.pos=t,this.delInfo=n,this.recover=r}get deleted(){return(this.delInfo&iMt)>0}get deletedBefore(){return(this.delInfo&(rMt|L2e))>0}get deletedAfter(){return(this.delInfo&(aMt|L2e))>0}get deletedAcross(){return(this.delInfo&L2e)>0}}class H_{constructor(t,n=!1){if(this.ranges=t,this.inverted=n,!t.length&&H_.empty)return H_.empty}recover(t){let n=0,r=plt(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 x=t==(n<0?c:h)?null:_Es(o/3,t-c),g=t==c?aMt:t==h?rMt:L2e;return(n<0?t!=c:t!=h)&&(g|=iMt),new b7e(p,g,x)}a+=u-d}return r?t+a:new b7e(t+a,0,null)}touches(t,n){let r=0,a=plt(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 JZ;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 Px.fromReplace(t,this.from,this.to,i)}invert(){return new US(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 KE(n.pos,r.pos,this.mark)}merge(t){return t instanceof KE&&t.mark.eq(this.mark)&&this.from<=t.to&&this.to>=t.from?new KE(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 KE(n.from,n.to,t.markFromJSON(n.mark))}}yv.jsonID("addMark",KE);class US extends yv{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 xi(bGe(n.content,a=>a.mark(this.mark.removeFromSet(a.marks)),t),n.openStart,n.openEnd);return Px.fromReplace(t,this.from,this.to,r)}invert(){return new KE(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 US(n.pos,r.pos,this.mark)}merge(t){return t instanceof US&&t.mark.eq(this.mark)&&this.from<=t.to&&this.to>=t.from?new US(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 US(n.from,n.to,t.markFromJSON(n.mark))}}yv.jsonID("removeMark",US);class YE extends yv{constructor(t,n){super(),this.pos=t,this.mark=n}apply(t){let n=t.nodeAt(this.pos);if(!n)return Px.fail("No node at mark step's position");let r=n.type.create(n.attrs,null,this.mark.addToSet(n.marks));return Px.fromReplace(t,this.pos,this.pos+1,new xi(Ia.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 N0(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 N0(n.from,n.to,n.gapFrom,n.gapTo,xi.fromJSON(t,n.slice),n.insert,!!n.structure)}}yv.jsonID("replaceAround",N0);function _7e(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 jEs(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),x=r.addToSet(h);for(let g=0;gs.step(c)),i.forEach(c=>s.step(c))}function NEs(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 nAe){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 US(l.from,l.to,l.style)))}function _Ge(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 kEs(s,t,n){return(t==0||s.canReplace(t,s.childCount))&&(n==s.childCount||s.canReplace(0,n))}function Oq(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;x--)g||r.index(x)>0?(g=!0,u=Ia.from(r.node(x).copy(u)),h++):c--;let m=Ia.empty,p=0;for(let x=i,g=!1;x>n;x--)g||a.after(x+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=Ia.from(n[l].type.create(n[l].attrs,r))}let a=t.start,i=t.end;s.step(new N0(a,i,a,i,new xi(r,0,0),n.length,!0))}function TEs(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)&&MEs(s.doc,s.mapping.slice(i).map(o),r)){let d=null;if(r.schema.linebreakReplacement){let p=r.whitespace=="pre",x=!!r.contentMatch.matchType(r.schema.linebreakReplacement);p&&!x?d=!1:!p&&x&&(d=!0)}d===!1&&lMt(s,l,o,i),_Ge(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 N0(h,m,h+1,m-1,new xi(Ia.from(r.create(c,null,l.marks)),0,0),1,!0)),d===!0&&oMt(s,l,o,i),!1}})}function oMt(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 lMt(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 MEs(s,t,n){let r=s.resolve(t),a=r.index();return r.parent.canReplaceWith(a,a+1,n)}function LEs(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 N0(t,t+i.nodeSize,t+1,t+i.nodeSize-1,new xi(Ia.from(l),0,0),1,!0))}function nB(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),x=r&&r[u+1];x&&(p=p.replaceChild(0,x.type.create(x.attrs)));let g=r&&r[u]||h;if(!h.canReplace(m+1,h.childCount)||!g.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 PEs(s,t,n=1,r){let a=s.doc.resolve(t),i=Ia.empty,l=Ia.empty;for(let o=a.depth,c=a.depth-n,d=n-1;o>c;o--,d--){i=Ia.from(a.node(o).copy(i));let u=r&&r[d];l=Ia.from(u?u.type.create(u.attrs,l):a.node(o).copy(l))}s.step(new Cx(t,t,new xi(i.append(l),n,n),!0))}function L6(s,t){let n=s.resolve(t),r=n.index();return cMt(n.nodeBefore,n.nodeAfter)&&n.parent.canReplace(r,r+1)}function IEs(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&&cMt(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 DEs(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);lMt(s,u.node(),u.before(),o)}l.inlineContent&&_Ge(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 Cx(d,c.map(t+n,-1),xi.empty,!0)),r===!0){let u=s.doc.resolve(d);oMt(s,u.node(),u.before(),s.steps.length)}return s}function REs(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 aAe(s,t,n=t,r=xi.empty){if(t==n&&!r.size)return null;let a=s.resolve(t),i=s.resolve(n);return uMt(a,i,r)?new Cx(t,n,r):new OEs(a,i,r).fit()}function uMt(s,t,n){return!n.openStart&&!n.openEnd&&s.start()==t.start()&&s.parent.canReplace(s.index(),t.index(),n.content)}class OEs{constructor(t,n,r){this.$from=t,this.$to=n,this.unplaced=r,this.frontier=[],this.placed=Ia.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=Ia.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 xi(i,l,o);return t>-1?new N0(r.pos,t,this.$to.pos,this.$to.end(),c,n):c.size||r.pos!=this.$to.pos?new Cx(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=SPe(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(Ia.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=SPe(t,n);return!a.childCount||a.firstChild.isLeaf?!1:(this.unplaced=new xi(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=SPe(t,n);if(a.childCount<=1&&n>0){let i=t.size-n<=n+a.size;this.unplaced=new xi(yW(t,n-1,1),n-1,i?n-1:r)}else this.unplaced=new xi(yW(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 g=0;g1||c==0||g.content.size)&&(h=y,u.push(hMt(g.mark(m.allowedMarks(g.marks)),d==1?c:0,d==o.childCount?p:-1)))}let x=d==o.childCount;x||(p=-1),this.placed=vW(this.placed,n,Ia.from(u)),this.frontier[n].match=h,x&&p<0&&r&&r.type==this.frontier[this.depth].type&&this.frontier.length>1&&this.closeFrontierNode();for(let g=0,y=o;g1&&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=CPe(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=vW(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=vW(this.placed,this.depth,Ia.from(t.create(n,r))),this.frontier.push({type:t,match:t.contentMatch})}closeFrontierNode(){let n=this.frontier.pop().match.fillBefore(Ia.empty,!0);n.childCount&&(this.placed=vW(this.placed,this.frontier.length,n))}}function yW(s,t,n){return t==0?s.cutByIndex(n,s.childCount):s.replaceChild(0,s.firstChild.copy(yW(s.firstChild.content,t-1,n)))}function vW(s,t,n){return t==0?s.append(n):s.replaceChild(s.childCount-1,s.lastChild.copy(vW(s.lastChild.content,t-1,n)))}function SPe(s,t){for(let n=0;n1&&(r=r.replaceChild(0,hMt(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(Ia.empty,!0)))),s.copy(r)}function CPe(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&&!FEs(n,i.content,l)?o:null}function FEs(s,t,n){for(let r=n;r0;m--,p--){let x=a.node(m).type.spec;if(x.defining||x.definingAsContext||x.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 x=m.firstChild;if(d.push(x),p==r.openStart)break;m=x.content}for(let m=u-1;m>=0;m--){let p=d[m],x=zEs(p.type);if(x&&!p.sameMarkup(a.node(Math.abs(o)-1)))u=m;else if(x||!p.type.isTextblock)break}for(let m=r.openStart;m>=0;m--){let p=(m+u+1)%(r.openStart+1),x=d[p];if(x)for(let g=0;g=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 mMt(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(Ia.empty,!0))}return s}function $Es(s,t,n,r){if(!r.isInline&&t==n&&s.doc.resolve(t).parent.content.size){let a=REs(s.doc,t,r.type);a!=null&&(t=n=a)}s.replaceRange(t,n,new xi(Ia.from(r),0,0))}function UEs(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=pMt(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 pMt(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 rB extends yv{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 Px.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 Px.fromReplace(t,this.pos,this.pos+1,new xi(Ia.from(a),0,n.isLeaf?0:1))}getMap(){return H_.empty}invert(t){return new rB(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 rB(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 rB(n.pos,n.attr,n.value)}}yv.jsonID("attr",rB);class eX extends yv{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 Px.ok(r)}getMap(){return H_.empty}invert(t){return new eX(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 eX(n.attr,n.value)}}yv.jsonID("docAttr",eX);let aU=class extends Error{};aU=function s(t){let n=Error.call(this,t);return n.__proto__=s.prototype,n};aU.prototype=Object.create(Error.prototype);aU.prototype.constructor=aU;aU.prototype.name="TransformError";let jGe=class{constructor(t){this.doc=t,this.steps=[],this.docs=[],this.mapping=new JZ}get before(){return this.docs.length?this.docs[0]:this.doc}step(t){let n=this.maybeStep(t);if(n.failed)throw new aU(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=xi.empty){let a=aAe(this.doc,t,n,r);return a&&this.step(a),this}replaceWith(t,n,r){return this.replace(t,n,new xi(Ia.from(r),0,0))}delete(t,n){return this.replace(t,n,xi.empty)}insert(t,n){return this.replaceWith(t,t,n)}replaceRange(t,n,r){return BEs(this,t,n,r),this}replaceRangeWith(t,n,r){return $Es(this,t,n,r),this}deleteRange(t,n){return UEs(this,t,n),this}lift(t,n){return SEs(this,t,n),this}join(t,n=1){return DEs(this,t,n),this}wrap(t,n){return EEs(this,t,n),this}setBlockType(t,n=t,r,a=null){return TEs(this,t,n,r,a),this}setNodeMarkup(t,n,r=null,a){return LEs(this,t,n,r,a),this}setNodeAttribute(t,n,r){return this.step(new rB(t,n,r)),this}setDocAttribute(t,n){return this.step(new eX(t,n)),this}addNodeMark(t,n){return this.step(new YE(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 Ah)n.isInSet(r.marks)&&this.step(new mO(t,n));else{let a=r.marks,i,l=[];for(;i=n.isInSet(a);)l.push(new mO(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 PEs(this,t,n,r),this}addMark(t,n,r){return jEs(this,t,n,r),this}removeMark(t,n,r){return NEs(this,t,n,r),this}clearIncompatible(t,n,r){return _Ge(this,t,n,r),this}};const APe=Object.create(null);class hl{constructor(t,n,r){this.$anchor=t,this.$head=n,this.ranges=r||[new fMt(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?u9(t.node(0),t.node(i),t.before(i+1),t.index(i),n,r):u9(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 Qj(t.node(0))}static atStart(t){return u9(t,t,0,0,1)||new Qj(t)}static atEnd(t){return u9(t,t,t.content.size,t.childCount,-1)||new Qj(t)}static fromJSON(t,n){if(!n||!n.type)throw new RangeError("Invalid input for Selection.fromJSON");let r=APe[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 APe)throw new RangeError("Duplicate use of selection JSON ID "+t);return APe[t]=n,n.prototype.jsonID=t,n}getBookmark(){return Qo.between(this.$anchor,this.$head).getBookmark()}}hl.prototype.visible=!0;class fMt{constructor(t,n){this.$from=t,this.$to=n}}let xlt=!1;function glt(s){!xlt&&!s.parent.inlineContent&&(xlt=!0,console.warn("TextSelection endpoint not pointing into a node with inline content ("+s.parent.type.name+")"))}class Qo extends hl{constructor(t,n=t){glt(t),glt(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 hl.near(r);let a=t.resolve(n.map(this.anchor));return new Qo(a.parent.inlineContent?a:r,r)}replace(t,n=xi.empty){if(super.replace(t,n),n==xi.empty){let r=this.$from.marksAcross(this.$to);r&&t.ensureMarks(r)}}eq(t){return t instanceof Qo&&t.anchor==this.anchor&&t.head==this.head}getBookmark(){return new iAe(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 Qo(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=hl.findFrom(n,r,!0)||hl.findFrom(n,-r,!0);if(i)n=i.$head;else return hl.near(n,r)}return t.parent.inlineContent||(a==0?t=n:(t=(hl.findFrom(t,-r,!0)||hl.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&&qo.isSelectable(o))return qo.create(s,n-(a<0?o.nodeSize:0))}else{let c=u9(s,o,n+a,a<0?o.childCount:0,a,i);if(c)return c}n+=o.nodeSize*a}return null}function ylt(s,t,n){let r=s.steps.length-1;if(r{l==null&&(l=u)}),s.setSelection(hl.near(s.doc.resolve(l),n))}const vlt=1,zne=2,blt=4;class VEs extends jGe{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|=zne,this}ensureMarks(t){return Ah.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&zne)>0}addStep(t,n){super.addStep(t,n),this.updated=this.updated&~zne,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)||Ah.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(hl.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|=blt,this}get scrolledIntoView(){return(this.updated&blt)>0}}function _lt(s,t){return!t||!s?s:s.bind(t)}class bW{constructor(t,n,r){this.name=t,this.init=_lt(n.init,r),this.apply=_lt(n.apply,r)}}const HEs=[new bW("doc",{init(s){return s.doc||s.schema.topNodeType.createAndFill()},apply(s){return s.doc}}),new bW("selection",{init(s,t){return s.selection||hl.atStart(t.doc)},apply(s){return s.selection}}),new bW("storedMarks",{init(s){return s.storedMarks||null},apply(s,t,n,r){return r.selection.$cursor?s.storedMarks:null}}),new bW("scrollToSelection",{init(){return 0},apply(s,t){return s.scrolledIntoView?t+1:t}})];class EPe{constructor(t,n){this.schema=t,this.plugins=[],this.pluginsByKey=Object.create(null),this.fields=HEs.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 bW(r.key,r.spec.state,r))})}}class G9{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 EPe(t.schema,t.plugins),i=new G9(a);return a.fields.forEach(l=>{if(l.name=="doc")i.doc=FT.fromJSON(t.schema,n.doc);else if(l.name=="selection")i.selection=hl.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 xMt(s,t,n){for(let r in s){let a=s[r];a instanceof Function?a=a.bind(t):r=="handleDOMEvents"&&(a=xMt(a,t,{})),n[r]=a}return n}class Lg{constructor(t){this.spec=t,this.props={},t.props&&xMt(t.props,this,this.props),this.key=t.key?t.key.key:gMt("plugin")}getState(t){return t[this.key]}}const TPe=Object.create(null);function gMt(s){return s in TPe?s+"$"+ ++TPe[s]:(TPe[s]=0,s+"$")}class vv{constructor(t="key"){this.key=gMt(t)}get(t){return t.config.pluginsByKey[this.key]}getState(t){return t[this.key]}}const dy=function(s){for(var t=0;;t++)if(s=s.previousSibling,!s)return t},iU=function(s){let t=s.assignedSlot||s.parentNode;return t&&t.nodeType==11?t.host:t};let w7e=null;const q4=function(s,t,n){let r=w7e||(w7e=document.createRange());return r.setEnd(s,n??s.nodeValue.length),r.setStart(s,t||0),r},GEs=function(){w7e=null},pO=function(s,t,n,r){return n&&(wlt(s,t,n,r,-1)||wlt(s,t,n,r,1))},WEs=/^(img|br|input|textarea|hr)$/i;function wlt(s,t,n,r,a){for(var i;;){if(s==n&&t==r)return!0;if(t==(a<0?0:Cj(s))){let l=s.parentNode;if(!l||l.nodeType!=1||Nee(s)||WEs.test(s.nodeName)||s.contentEditable=="false")return!1;t=dy(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?Cj(s):0}else return!1}}function Cj(s){return s.nodeType==3?s.nodeValue.length:s.childNodes.length}function KEs(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=Cj(s)}else if(s.parentNode&&!Nee(s))t=dy(s),s=s.parentNode;else return null}}function YEs(s,t){for(;;){if(s.nodeType==3&&t2),_j=oU||(w5?/Mac/.test(w5.platform):!1),bMt=w5?/Win/.test(w5.platform):!1,I3=/Android \d/.test(P6),kee=!!jlt&&"webkitFontSmoothing"in jlt.documentElement.style,JEs=kee?+(/\bAppleWebKit\/(\d+)/.exec(navigator.userAgent)||[0,0])[1]:0;function eTs(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 b4(s,t){return typeof s=="number"?s:s[t]}function tTs(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 Nlt(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=iU(l);continue}let o=l,c=o==i.body,d=c?eTs(i):tTs(o),u=0,h=0;if(t.topd.bottom-b4(r,"bottom")&&(h=t.bottom-t.top>d.bottom-d.top?t.top+b4(a,"top")-d.top:t.bottom-d.bottom+b4(a,"bottom")),t.leftd.right-b4(r,"right")&&(u=t.right-d.right+b4(a,"right")),u||h)if(c)i.defaultView.scrollBy(u,h);else{let p=o.scrollLeft,x=o.scrollTop;h&&(o.scrollTop+=h),u&&(o.scrollLeft+=u);let g=o.scrollLeft-p,y=o.scrollTop-x;t={left:t.left-g,top:t.top-y,right:t.right-g,bottom:t.bottom-y}}let m=c?"fixed":getComputedStyle(l).position;if(/^(fixed|sticky)$/.test(m))break;l=m=="absolute"?l.offsetParent:iU(l)}}function sTs(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:_Mt(s.dom)}}function _Mt(s){let t=[],n=s.ownerDocument;for(let r=s;r&&(t.push({dom:r,top:r.scrollTop,left:r.scrollLeft}),s!=n);r=iU(r));return t}function nTs({refDOM:s,refTop:t,stack:n}){let r=s?s.getBoundingClientRect().top:0;wMt(n,r==0?0:r-t)}function wMt(s,t){for(let n=0;n=o){l=Math.max(x.bottom,l),o=Math.min(x.top,o);let g=x.left>t.left?x.left-t.left:x.right=(x.left+x.right)/2?1:0));continue}}else x.top>t.top&&!c&&x.left<=t.left&&x.right>=t.left&&(c=u,d={left:Math.max(x.left,Math.min(x.right,t.left)),top:x.top});!n&&(t.left>=x.right&&t.top>=x.top||t.left>=x.left&&t.top>=x.bottom)&&(i=h+1)}}return!n&&c&&(n=c,a=d,r=0),n&&n.nodeType==3?aTs(n,a):!n||r&&n.nodeType==1?{node:s,offset:i}:jMt(n,a)}function aTs(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 kGe(s,t){return s.left>=t.left-1&&s.left<=t.right+1&&s.top>=t.top-1&&s.top<=t.bottom+1}function iTs(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 lTs(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 NMt(s,t,n){let r=s.childNodes.length;if(r&&n.topt.top&&a++}let d;kee&&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=lTs(s,r,a,t))}o==null&&(o=oTs(s,l,t));let c=s.docView.nearestDesc(l,!0);return{pos:o,inside:c?c.posAtStart-c.border:-1}}function klt(s){return s.top=0&&a==r.nodeValue.length?(c--,u=1):n<0?c--:d++,iG(SA(q4(r,c,d),u),u<0)}if(!s.state.doc.resolve(t-(i||0)).parent.inlineContent){if(i==null&&a&&(n<0||a==Cj(r))){let c=r.childNodes[a-1];if(c.nodeType==1)return MPe(c.getBoundingClientRect(),!1)}if(i==null&&a=0)}if(i==null&&a&&(n<0||a==Cj(r))){let c=r.childNodes[a-1],d=c.nodeType==3?q4(c,Cj(c)-(l?0:1)):c.nodeType==1&&(c.nodeName!="BR"||!c.nextSibling)?c:null;if(d)return iG(SA(d,1),!1)}if(i==null&&a=0)}function iG(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 MPe(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 SMt(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 uTs(s,t,n){let r=t.selection,a=n=="up"?r.$from:r.$to;return SMt(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=kMt(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=q4(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 hTs=/[\u0590-\u08ac]/;function mTs(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?!hTs.test(r.parent.textContent)||!o.modify?n=="left"||n=="backward"?i:l:SMt(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:x,focusOffset:g}=s.domSelectionRange(),y=x&&!p.contains(x.nodeType==1?x:x.parentNode)||c==x&&d==g;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 Slt=null,Clt=null,Alt=!1;function pTs(s,t,n){return Slt==t&&Clt==n?Alt:(Slt=t,Clt=n,Alt=n=="up"||n=="down"?uTs(s,t,n):mTs(s,t,n))}const e2=0,Elt=1,I8=2,j5=3;class See{constructor(t,n,r,a){this.parent=t,this.children=n,this.dom=r,this.contentDOM=a,this.dirty=e2,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;ndy(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 AMt){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 CMt&&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?dy(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=dy(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;ux&&ln){let x=o;o=c,c=x}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?I8:Elt,t==o&&n==c&&(i.contentLost||i.dom.parentNode!=this.contentDOM)?i.dirty=j5:i.markDirty(t-o,n-o);return}else i.dirty=i.dom==i.contentDOM&&i.dom.parentNode==this.contentDOM&&!i.children.length?I8:j5}r=l}this.dirty=I8}markParentsDirty(){let t=1;for(let n=this.parent;n;n=n.parent,t++){let r=t==1?I8:Elt;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==e2&&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 fTs extends See{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 fO extends See{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=QO.renderSpec(document,n.type.spec.toDOM(n,r),null,n.attrs)),new fO(t,n,l.dom,l.contentDOM||l.dom,l)}parseRule(){return this.dirty&j5||this.mark.type.spec.reparseInView?null:{mark:this.mark.type.name,attrs:this.mark.attrs,contentElement:this.contentDOM}}matchesMark(t){return this.dirty!=j5&&this.mark.eq(t)}markDirty(t,n){if(super.markDirty(t,n),this.dirty!=e2){let r=this.parent;for(;!r.node;)r=r.parent;r.dirty0&&(i=C7e(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}=QO.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=MMt(u,r,n),d?c=new xTs(t,n,r,a,u,h||null,m,d,i,l+1):n.isText?new lAe(t,n,r,a,u,m,i):new BT(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=()=>Ia.empty)}return t}matchesNode(t,n,r){return this.dirty==e2&&t.eq(this.node)&&dSe(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 yTs(this,l&&l.node,t);_Ts(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?Ah.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==I8)&&(l&&this.protectLocalComposition(t,l),EMt(this.contentDOM,this.children,t),oU&&wTs(this.dom))}localCompositionInfo(t,n){let{from:r,to:a}=t.state.selection;if(!(t.state.selection instanceof Qo)||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=jTs(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 fTs(this,i,n,a);t.input.compositionNodes.push(l),this.children=C7e(this.children,r,r+a.length,t,l)}update(t,n,r,a){return this.dirty==j5||!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=e2}updateOuterDeco(t){if(dSe(t,this.outerDeco))return;let n=this.nodeDOM.nodeType!=1,r=this.dom;this.dom=TMt(this.dom,this.nodeDOM,S7e(this.outerDeco,this.node,n),S7e(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 Tlt(s,t,n,r,a){MMt(r,t,s);let i=new BT(void 0,s,t,n,r,r,r,a,0);return i.contentDOM&&i.updateChildren(a,0),i}class lAe extends BT{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==j5||this.dirty!=e2&&!this.inParent()||!t.sameMarkup(this.node)?!1:(this.updateOuterDeco(n),(this.dirty!=e2||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=e2,!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 lAe(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=j5)}get domAtom(){return!1}isText(t){return this.node.text==t}}class AMt extends See{parseRule(){return{ignore:!0}}matchesHack(t){return this.dirty==e2&&this.dom.nodeName==t}get domAtom(){return!0}get ignoreForCoords(){return this.dom.nodeName=="IMG"}}class xTs extends BT{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==j5)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 EMt(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=fO.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 fO)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 bTs(s,t){return s.type.side-t.type.side}function _Ts(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 x=i+m.nodeSize;if(m.isText){let y=x;l!y.inline):o.slice();r(m,g,t.forChild(i,m),p),i=x}}function wTs(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 jTs(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 C7e(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 SGe(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(oAe(n)){for(c=l;a&&!a.node;)a=a.parent;let h=a.node;if(a&&h.isAtom&&qo.isSelectable(h)&&a.parent&&!(h.isInline&&ZEs(n.focusNode,n.focusOffset,a.dom))){let m=a.posBefore;d=new qo(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(()=>{(!LMt(s)||s.state.selection.visible)&&s.dom.classList.remove("ProseMirror-hideselection")},20))})}function kTs(s){let t=s.domSelection();if(!t)return;let n=s.cursorWrapper.dom,r=n.nodeName=="IMG";r?t.collapse(n.parentNode,dy(n)+1):t.collapse(n,0),!r&&!s.state.selection.visible&&Db&&zT<=11&&(n.disabled=!0,n.disabled=!1)}function PMt(s,t){if(t instanceof qo){let n=s.docView.descAt(t.from);n!=s.lastSelectedViewDesc&&(Dlt(s),n&&n.selectNode(),s.lastSelectedViewDesc=n)}else Dlt(s)}function Dlt(s){s.lastSelectedViewDesc&&(s.lastSelectedViewDesc.parent&&s.lastSelectedViewDesc.deselectNode(),s.lastSelectedViewDesc=void 0)}function CGe(s,t,n,r){return s.someProp("createSelectionBetween",a=>a(s,t,n))||Qo.between(t,n,r)}function Rlt(s){return s.editable&&!s.hasFocus()?!1:IMt(s)}function IMt(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 STs(s){let t=s.docView.domFromPos(s.state.selection.anchor,0),n=s.domSelectionRange();return pO(t.node,t.offset,n.anchorNode,n.anchorOffset)}function A7e(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&&hl.findFrom(i,t)}function zA(s,t){return s.dispatch(s.state.tr.setSelection(t).scrollIntoView()),!0}function Olt(s,t,n){let r=s.state.selection;if(r instanceof Qo)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 zA(s,new Qo(r.$anchor,l))}else if(r.empty){if(s.endOfTextblock(t>0?"forward":"backward")){let a=A7e(s.state,t);return a&&a instanceof qo?zA(s,a):!1}else if(!(_j&&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?qo.isSelectable(i)?zA(s,new qo(t<0?s.state.doc.resolve(a.pos-i.nodeSize):a)):kee?zA(s,new Qo(s.state.doc.resolve(t<0?o:o+i.nodeSize))):!1:!1}}else return!1;else{if(r instanceof qo&&r.node.isInline)return zA(s,new Qo(t>0?r.$to:r.$from));{let a=A7e(s.state,t);return a?zA(s,a):!1}}}function uSe(s){return s.nodeType==3?s.nodeValue.length:s.childNodes.length}function SY(s,t){let n=s.pmViewDesc;return n&&n.size==0&&(t<0||s.nextSibling||s.nodeName!="BR")}function w7(s,t){return t<0?CTs(s):ATs(s)}function CTs(s){let t=s.domSelectionRange(),n=t.focusNode,r=t.focusOffset;if(!n)return;let a,i,l=!1;for(Jj&&n.nodeType==1&&r0){if(n.nodeType!=1)break;{let o=n.childNodes[r-1];if(SY(o,-1))a=n,i=--r;else if(o.nodeType==3)n=o,r=n.nodeValue.length;else break}}else{if(DMt(n))break;{let o=n.previousSibling;for(;o&&SY(o,-1);)a=n.parentNode,i=dy(o),o=o.previousSibling;if(o)n=o,r=uSe(n);else{if(n=n.parentNode,n==s.dom)break;r=0}}}l?E7e(s,n,r):a&&E7e(s,a,i)}function ATs(s){let t=s.domSelectionRange(),n=t.focusNode,r=t.focusOffset;if(!n)return;let a=uSe(n),i,l;for(;;)if(r{s.state==a&&K3(s)},50)}function Flt(s,t){let n=s.state.doc.resolve(t);if(!(fy||bMt)&&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 zlt(s,t,n){let r=s.state.selection;if(r instanceof Qo&&!r.empty||n.indexOf("s")>-1||_j&&n.indexOf("m")>-1)return!1;let{$from:a,$to:i}=r;if(!a.parent.inlineContent||s.endOfTextblock(t<0?"up":"down")){let l=A7e(s.state,t);if(l&&l instanceof qo)return zA(s,l)}if(!a.parent.inlineContent){let l=t<0?a:i,o=r instanceof Qj?hl.near(l,t):hl.findFrom(l,t);return o?zA(s,o):!1}return!1}function Blt(s,t){if(!(s.state.selection instanceof Qo))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 $lt(s,t,n){s.domObserver.stop(),t.contentEditable=n,s.domObserver.start()}function MTs(s){if(!fv||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;$lt(s,r,"true"),setTimeout(()=>$lt(s,r,"false"),20)}return!1}function LTs(s){let t="";return s.ctrlKey&&(t+="c"),s.metaKey&&(t+="m"),s.altKey&&(t+="a"),s.shiftKey&&(t+="s"),t}function PTs(s,t){let n=t.keyCode,r=LTs(t);if(n==8||_j&&n==72&&r=="c")return Blt(s,-1)||w7(s,-1);if(n==46&&!t.shiftKey||_j&&n==68&&r=="c")return Blt(s,1)||w7(s,1);if(n==13||n==27)return!0;if(n==37||_j&&n==66&&r=="c"){let a=n==37?Flt(s,s.state.selection.from)=="ltr"?-1:1:-1;return Olt(s,a,r)||w7(s,a)}else if(n==39||_j&&n==70&&r=="c"){let a=n==39?Flt(s,s.state.selection.from)=="ltr"?1:-1:1;return Olt(s,a,r)||w7(s,a)}else{if(n==38||_j&&n==80&&r=="c")return zlt(s,-1,r)||w7(s,-1);if(n==40||_j&&n==78&&r=="c")return MTs(s)||zlt(s,1,r)||w7(s,1);if(r==(_j?"m":"c")&&(n==66||n==73||n==89||n==90))return!0}return!1}function AGe(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")||QO.fromSchema(s.state.schema),o=$Mt(),c=o.createElement("div");c.appendChild(l.serializeFragment(r,{document:o}));let d=c.firstChild,u,h=0;for(;d&&d.nodeType==1&&(u=BMt[d.nodeName.toLowerCase()]);){for(let p=u.length-1;p>=0;p--){let x=o.createElement(u[p]);for(;c.firstChild;)x.appendChild(c.firstChild);c.appendChild(x),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 RMt(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 xi(Ia.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,x=QO.fromSchema(p);l=document.createElement("div"),t.split(/(?:\r\n?|\n)+/).forEach(g=>{let y=l.appendChild(document.createElement("p"));g&&y.appendChild(x.serializeNode(p.text(g,m)))})}}else s.someProp("transformPastedHTML",h=>{n=h(n,s)}),l=OTs(n),kee&&FTs(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")||jY.fromSchema(s.state.schema)).parseSlice(l,{preserveWhitespace:!!(c||u),context:a,ruleFromNode(m){return m.nodeName=="BR"&&!m.nextSibling&&m.parentNode&&!ITs.test(m.parentNode.nodeName)?{ignore:!0}:null}})),u)o=zTs(Ult(o,+u[1],+u[2]),u[4]);else if(o=xi.maxOpen(DTs(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 ITs=/^(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 DTs(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&&FMt(c,i,o,l[l.length-1],0))l[l.length-1]=d;else{l.length&&(l[l.length-1]=zMt(l[l.length-1],i.length));let u=OMt(o,c);l.push(u),a=a.matchType(u.type),i=c}}),l)return Ia.from(l)}return s}function OMt(s,t,n=0){for(let r=t.length-1;r>=n;r--)s=t[r].create(null,Ia.from(s));return s}function FMt(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(Ia.empty,!0))),s.replaceChild(t<0?0:s.childCount-1,l.copy(o))}function Ult(s,t,n){return tn})),PPe.createHTML(s)):s}function OTs(s){let t=/^(\s*]*>)*/.exec(s);t&&(s=s.slice(t[0].length));let n=$Mt().createElement("div"),r=/<([a-z][^>\s]+)/i.exec(s),a;if((a=r&&BMt[r[1].toLowerCase()])&&(s=a.map(i=>"<"+i+">").join("")+s+a.map(i=>"").reverse().join("")),n.innerHTML=RTs(s),a)for(let i=0;i=0;o-=2){let c=n.nodes[r[o]];if(!c||c.hasRequiredAttrs())break;a=Ia.from(c.create(r[o+1],a)),i++,l++}return new xi(a,i,l)}const j1={},N1={},BTs={touchstart:!0,touchmove:!0};class $Ts{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 UTs(s){for(let t in j1){let n=j1[t];s.dom.addEventListener(t,s.input.eventHandlers[t]=r=>{VTs(s,r)&&!EGe(s,r)&&(s.editable||!(r.type in N1))&&n(s,r)},BTs[t]?{passive:!0}:void 0)}fv&&s.dom.addEventListener("input",()=>null),M7e(s)}function ZE(s,t){s.input.lastSelectionOrigin=t,s.input.lastSelectionTime=Date.now()}function qTs(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 M7e(s){s.someProp("handleDOMEvents",t=>{for(let n in t)s.input.eventHandlers[n]||s.dom.addEventListener(n,s.input.eventHandlers[n]=r=>EGe(s,r))})}function EGe(s,t){return s.someProp("handleDOMEvents",n=>{let r=n[t.type];return r?r(s,t)||t.defaultPrevented:!1})}function VTs(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 HTs(s,t){!EGe(s,t)&&j1[t.type]&&(s.editable||!(t.type in N1))&&j1[t.type](s,t)}N1.keydown=(s,t)=>{let n=t;if(s.input.shiftKey=n.keyCode==16||n.shiftKey,!qMt(s,n)&&(s.input.lastKeyCode=n.keyCode,s.input.lastKeyCodeTime=Date.now(),!(I3&&fy&&n.keyCode==13)))if(n.keyCode!=229&&s.domObserver.forceFlush(),oU&&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,v8(13,"Enter"))),s.input.lastIOSEnter=0)},200)}else s.someProp("handleKeyDown",r=>r(s,n))||PTs(s,n)?n.preventDefault():ZE(s,"key")};N1.keyup=(s,t)=>{t.keyCode==16&&(s.input.shiftKey=!1)};N1.keypress=(s,t)=>{let n=t;if(qMt(s,n)||!n.charCode||n.ctrlKey&&!n.altKey||_j&&n.metaKey)return;if(s.someProp("handleKeyPress",a=>a(s,n))){n.preventDefault();return}let r=s.state.selection;if(!(r instanceof Qo)||!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 cAe(s){return{left:s.clientX,top:s.clientY}}function GTs(s,t){let n=t.x-s.clientX,r=t.y-s.clientY;return n*n+r*r<100}function TGe(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 aB(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 WTs(s,t){if(t==-1)return!1;let n=s.state.doc.resolve(t),r=n.nodeAfter;return r&&r.isAtom&&qo.isSelectable(r)?(aB(s,new qo(n)),!0):!1}function KTs(s,t){if(t==-1)return!1;let n=s.state.selection,r,a;n instanceof qo&&(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(qo.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?(aB(s,qo.create(s.state.doc,a)),!0):!1}function YTs(s,t,n,r,a){return TGe(s,"handleClickOn",t,n,r)||s.someProp("handleClick",i=>i(s,t,r))||(a?KTs(s,n):WTs(s,n))}function ZTs(s,t,n,r){return TGe(s,"handleDoubleClickOn",t,n,r)||s.someProp("handleDoubleClick",a=>a(s,t,r))}function XTs(s,t,n,r){return TGe(s,"handleTripleClickOn",t,n,r)||s.someProp("handleTripleClick",a=>a(s,t,r))||QTs(s,n,r)}function QTs(s,t,n){if(n.button!=0)return!1;let r=s.state.doc;if(t==-1)return r.inlineContent?(aB(s,Qo.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)aB(s,Qo.create(r,o+1,o+1+l.content.size));else if(qo.isSelectable(l))aB(s,qo.create(r,o));else continue;return!0}}function MGe(s){return hSe(s)}const UMt=_j?"metaKey":"ctrlKey";j1.mousedown=(s,t)=>{let n=t;s.input.shiftKey=n.shiftKey;let r=MGe(s),a=Date.now(),i="singleClick";a-s.input.lastClick.time<500&>s(n,s.input.lastClick)&&!n[UMt]&&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(cAe(n));l&&(i=="singleClick"?(s.input.mouseDown&&s.input.mouseDown.done(),s.input.mouseDown=new JTs(s,l,n,!!r)):(i=="doubleClick"?ZTs:XTs)(s,l.pos,l.inside,n)?n.preventDefault():ZE(s,"pointer"))};class JTs{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[UMt],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 qo&&d.from<=l&&d.to>l)&&(this.mightDrag={node:i,pos:l,addAttr:!!(this.target&&!this.target.draggable),setUneditable:!!(this.target&&Jj&&!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)),ZE(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(()=>K3(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(cAe(t))),this.updateAllowDefault(t),this.allowDefault||!n?ZE(this.view,"pointer"):YTs(this.view,n.pos,n.inside,t,this.selectNode)?t.preventDefault():t.button==0&&(this.flushed||fv&&this.mightDrag&&!this.mightDrag.node.isAtom||fy&&!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)?(aB(this.view,hl.near(this.view.state.doc.resolve(n.pos))),t.preventDefault()):ZE(this.view,"pointer")}move(t){this.updateAllowDefault(t),ZE(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)}}j1.touchstart=s=>{s.input.lastTouch=Date.now(),MGe(s),ZE(s,"pointer")};j1.touchmove=s=>{s.input.lastTouch=Date.now(),ZE(s,"pointer")};j1.contextmenu=s=>MGe(s);function qMt(s,t){return s.composing?!0:fv&&Math.abs(t.timeStamp-s.input.compositionEndedAt)<500?(s.input.compositionEndedAt=-2e8,!0):!1}const e6s=I3?5e3:-1;N1.compositionstart=N1.compositionupdate=s=>{if(!s.composing){s.domObserver.flush();let{state:t}=s,n=t.selection.$to;if(t.selection instanceof Qo&&(t.storedMarks||!n.textOffset&&n.parentOffset&&n.nodeBefore.marks.some(r=>r.type.spec.inclusive===!1)||fy&&bMt&&t6s(s)))s.markCursor=s.state.storedMarks||n.marks(),hSe(s,!0),s.markCursor=null;else if(hSe(s,!t.selection.empty),Jj&&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}VMt(s,e6s)};function t6s(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"}N1.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++,VMt(s,20))};function VMt(s,t){clearTimeout(s.input.composingTimeout),t>-1&&(s.input.composingTimeout=setTimeout(()=>hSe(s),t))}function HMt(s){for(s.composing&&(s.input.composing=!1,s.input.compositionEndedAt=n6s());s.input.compositionNodes.length>0;)s.input.compositionNodes.pop().markParentsDirty()}function s6s(s){let t=s.domSelectionRange();if(!t.focusNode)return null;let n=KEs(t.focusNode,t.focusOffset),r=YEs(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 n6s(){let s=document.createEvent("Event");return s.initEvent("event",!0,!0),s.timeStamp}function hSe(s,t=!1){if(!(I3&&s.domObserver.flushingSoon>=0)){if(s.domObserver.forceFlush(),HMt(s),t||s.docView&&s.docView.dirty){let n=SGe(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 r6s(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 tX=Db&&zT<15||oU&&JEs<604;j1.copy=N1.cut=(s,t)=>{let n=t,r=s.state.selection,a=n.type=="cut";if(r.empty)return;let i=tX?null:n.clipboardData,l=r.content(),{dom:o,text:c}=AGe(s,l);i?(n.preventDefault(),i.clearData(),i.setData("text/html",o.innerHTML),i.setData("text/plain",c)):r6s(s,o),a&&s.dispatch(s.state.tr.deleteSelection().scrollIntoView().setMeta("uiEvent","cut"))};function a6s(s){return s.openStart==0&&s.openEnd==0&&s.content.childCount==1?s.content.firstChild:null}function i6s(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?sX(s,r.value,null,a,t):sX(s,r.textContent,r.innerHTML,a,t)},50)}function sX(s,t,n,r,a){let i=RMt(s,t,n,r,s.state.selection.$from);if(s.someProp("handlePaste",c=>c(s,a,i||xi.empty)))return!0;if(!i)return!1;let l=a6s(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 GMt(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," "):""}N1.paste=(s,t)=>{let n=t;if(s.composing&&!I3)return;let r=tX?null:n.clipboardData,a=s.input.shiftKey&&s.input.lastKeyCode!=45;r&&sX(s,GMt(r),r.getData("text/html"),a,n)?n.preventDefault():i6s(s,n)};class WMt{constructor(t,n,r){this.slice=t,this.move=n,this.node=r}}const o6s=_j?"altKey":"ctrlKey";function KMt(s,t){let n;return s.someProp("dragCopies",r=>{n=n||r(t)}),n!=null?!n:!t[o6s]}j1.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(cAe(n)),l;if(!(i&&i.pos>=a.from&&i.pos<=(a instanceof qo?a.to-1:a.to))){if(r&&r.mightDrag)l=qo.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=qo.create(s.state.doc,h.posBefore))}}let o=(l||s.state.selection).content(),{dom:c,text:d,slice:u}=AGe(s,o);(!n.dataTransfer.files.length||!fy||vMt>120)&&n.dataTransfer.clearData(),n.dataTransfer.setData(tX?"Text":"text/html",c.innerHTML),n.dataTransfer.effectAllowed="copyMove",tX||n.dataTransfer.setData("text/plain",d),s.dragging=new WMt(u,KMt(s,n),l)};j1.dragend=s=>{let t=s.dragging;window.setTimeout(()=>{s.dragging==t&&(s.dragging=null)},50)};N1.dragover=N1.dragenter=(s,t)=>t.preventDefault();N1.drop=(s,t)=>{try{l6s(s,t,s.dragging)}finally{s.dragging=null}};function l6s(s,t,n){if(!t.dataTransfer)return;let r=s.posAtCoords(cAe(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=RMt(s,GMt(t.dataTransfer),tX?null:t.dataTransfer.getData("text/html"),!1,a);let l=!!(n&&KMt(s,t));if(s.someProp("handleDrop",p=>p(s,t,i||xi.empty,l))){t.preventDefault();return}if(!i)return;t.preventDefault();let o=i?dMt(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&&qo.isSelectable(i.content.firstChild)&&m.nodeAfter&&m.nodeAfter.sameMarkup(i.content.firstChild))c.setSelection(new qo(m));else{let p=c.mapping.map(o);c.mapping.maps[c.mapping.maps.length-1].forEach((x,g,y,b)=>p=b),c.setSelection(CGe(s,m,c.doc.resolve(p)))}s.focus(),s.dispatch(c.setMeta("uiEvent","drop"))}j1.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())&&K3(s)},20))};j1.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)};j1.beforeinput=(s,t)=>{if(fy&&I3&&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,v8(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 N1)j1[s]=N1[s];function nX(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 mSe{constructor(t,n){this.toDOM=t,this.spec=n||PR,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 l1(i-r,i-r,this)}valid(){return!0}eq(t){return this==t||t instanceof mSe&&(this.spec.key&&this.spec.key==t.spec.key||this.toDOM==t.toDOM&&nX(this.spec,t.spec))}destroy(t){this.spec.destroy&&this.spec.destroy(t)}}class $T{constructor(t,n){this.attrs=t,this.spec=n||PR}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 l1(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==ev||t.maps.length==0?this:this.mapInner(t,n,0,0,r||PR)}mapInner(t,n,r,a,i){let l;for(let o=0;o{let d=c+r,u;if(u=ZMt(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 $T){let d=Math.max(i,c.from)-i,u=Math.min(l,c.to)-i;da.map(t,n,PR));return JA.from(r)}forChild(t,n){if(n.isLeaf)return xf.empty;let r=[];for(let a=0;an instanceof xf)?t:t.reduce((n,r)=>n.concat(r instanceof xf?r:r.members),[]))}}forEachSet(t){for(let n=0;n{let y=g-x-(p-m);for(let b=0;bv+u-h)continue;let N=o[b]+u-h;p>=N?o[b+1]=m<=N?-2:-1:m>=u&&y&&(o[b]+=y,o[b+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:x,offset:g}=r.content.findIndex(h),y=r.maybeChild(x);if(y&&g==h&&g+y.nodeSize==p){let b=o[d+2].mapInner(n,y,u+1,s[d]+i+1,l);b!=ev?(o[d]=h,o[d+1]=p,o[d+2]=b):(o[d+1]=-2,c=!0)}else c=!0}if(c){let d=d6s(o,s,t,n,a,i,l),u=pSe(d,r,0,l);t=u.local;for(let h=0;hn&&l.to{let d=ZMt(s,o,c+n);if(d){i=!0;let u=pSe(d,o,n+c+1,r);u!=ev&&a.push(c,c+o.nodeSize,u)}});let l=YMt(i?XMt(s):s,-n).sort(IR);for(let o=0;o0;)t++;s.splice(t,0,n)}function IPe(s){let t=[];return s.someProp("decorations",n=>{let r=n(s.state);r&&r!=ev&&t.push(r)}),s.cursorWrapper&&t.push(xf.create(s.state.doc,[s.cursorWrapper.deco])),JA.from(t)}const u6s={childList:!0,characterData:!0,characterDataOldValue:!0,attributes:!0,attributeOldValue:!0,subtree:!0},h6s=Db&&zT<=11;class m6s{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 p6s{constructor(t,n){this.view=t,this.handleDOMChange=n,this.queue=[],this.flushingSoon=-1,this.observer=null,this.currentSelection=new m6s,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():fv&&t.composing&&r.some(a=>a.type=="childList"&&a.target.nodeName=="TR")?(t.input.badSafariComposition=!0,this.flushSoon()):this.flush()}),h6s&&(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,u6s)),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(Rlt(this.view)){if(this.suppressingSelectionUpdates)return K3(this.view);if(Db&&zT<=11&&!this.view.state.selection.empty){let t=this.view.domSelectionRange();if(t.focusNode&&pO(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=iU(i))n.add(i);for(let i=t.anchorNode;i;i=iU(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)&&Rlt(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(Jj&&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||g6s(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),f6s(t)),t.input.badSafariComposition&&(t.input.badSafariComposition=!1,y6s(t,c)),this.handleDOMChange(i,l,o,c),t.docView&&t.docView.dirty?t.updateState(t.state):this.currentSelection.eq(r)||K3(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 b=r.childNodes[y-1],v=b.pmViewDesc;if(b.nodeName=="BR"&&!v){i=y;break}if(!v||v.size)break}let h=s.state.doc,m=s.someProp("domParser")||jY.fromSchema(s.state.schema),p=h.resolve(l),x=null,g=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:b6s,context:p});if(d&&d[0].pos!=null){let y=d[0].pos,b=d[1]&&d[1].pos;b==null&&(b=y),x={anchor:y+l,head:b+l}}return{doc:g,sel:x,from:l,to:o}}function b6s(s){let t=s.pmViewDesc;if(t)return t.parseRule();if(s.nodeName=="BR"&&s.parentNode){if(fv&&/^(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||fv&&/^(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 _6s=/^(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 w6s(s,t,n,r,a){let i=s.input.compositionPendingChanges||(s.composing?s.input.compositionID:0);if(s.input.compositionPendingChanges=0,t<0){let P=s.input.lastSelectionTime>Date.now()-50?s.input.lastSelectionOrigin:null,M=SGe(s,P);if(M&&!s.state.selection.eq(M)){if(fy&&I3&&s.input.lastKeyCode===13&&Date.now()-100D(s,v8(13,"Enter"))))return;let I=s.state.tr.setSelection(M);P=="pointer"?I.setMeta("pointer",!0):P=="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=v6s(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||I3)&&a.some(P=>P.nodeType==1&&!_6s.test(P.nodeName))&&(!x||x.endA>=x.endB)&&s.someProp("handleKeyDown",P=>P(s,v8(13,"Enter")))){s.input.lastIOSEnter=0;return}if(!x)if(r&&c instanceof Qo&&!c.empty&&c.$head.sameParent(c.$anchor)&&!s.composing&&!(d.sel&&d.sel.anchor!=d.sel.head))x={start:c.from,endA:c.to,endB:c.to};else{if(d.sel){let P=Klt(s,s.state.doc,d.sel);if(P&&!P.eq(s.state.selection)){let M=s.state.tr.setSelection(P);i&&M.setMeta("composition",i),s.dispatch(M)}}return}s.state.selection.froms.state.selection.from&&x.start<=s.state.selection.from+2&&s.state.selection.from>=d.from?x.start=s.state.selection.from:x.endA=s.state.selection.to-2&&s.state.selection.to<=d.to&&(x.endB+=s.state.selection.to-x.endA,x.endA=s.state.selection.to)),Db&&zT<=11&&x.endB==x.start+1&&x.endA==x.start&&x.start>d.from&&d.doc.textBetween(x.start-d.from-1,x.start-d.from+1)=="  "&&(x.start--,x.endA--,x.endB--);let g=d.doc.resolveNoCache(x.start-d.from),y=d.doc.resolveNoCache(x.endB-d.from),b=u.resolve(x.start),v=g.sameParent(y)&&g.parent.inlineContent&&b.end()>=x.endA;if((oU&&s.input.lastIOSEnter>Date.now()-225&&(!v||a.some(P=>P.nodeName=="DIV"||P.nodeName=="P"))||!v&&g.posP(s,v8(13,"Enter")))){s.input.lastIOSEnter=0;return}if(s.state.selection.anchor>x.start&&N6s(u,x.start,x.endA,g,y)&&s.someProp("handleKeyDown",P=>P(s,v8(8,"Backspace")))){I3&&fy&&s.domObserver.suppressSelectionUpdates();return}fy&&x.endB==x.start&&(s.input.lastChromeDelete=Date.now()),I3&&!v&&g.start()!=y.start()&&y.parentOffset==0&&g.depth==y.depth&&d.sel&&d.sel.anchor==d.sel.head&&d.sel.head==x.endA&&(x.endB-=2,y=d.doc.resolveNoCache(x.endB-d.from),setTimeout(()=>{s.someProp("handleKeyDown",function(P){return P(s,v8(13,"Enter"))})},20));let N=x.start,C=x.endA,A=P=>{let M=P||s.state.tr.replace(N,C,d.doc.slice(x.start-d.from,x.endB-d.from));if(d.sel){let I=Klt(s,M.doc,d.sel);I&&!(fy&&s.composing&&I.empty&&(x.start!=x.endB||s.input.lastChromeDeleteK3(s),20));let P=A(s.state.tr.delete(N,C)),M=u.resolve(x.start).marksAcross(u.resolve(x.endA));M&&P.ensureMarks(M),s.dispatch(P)}else if(x.endA==x.endB&&(T=j6s(g.parent.content.cut(g.parentOffset,y.parentOffset),b.parent.content.cut(b.parentOffset,x.endA-b.start())))){let P=A(s.state.tr);T.type=="add"?P.addMark(N,C,T.mark):P.removeMark(N,C,T.mark),s.dispatch(P)}else if(g.parent.child(g.index()).isText&&g.index()==y.index()-(y.textOffset?0:1)){let P=g.parent.textBetween(g.parentOffset,y.parentOffset),M=()=>A(s.state.tr.insertText(P,N,C));s.someProp("handleTextInput",I=>I(s,N,C,P,M))||s.dispatch(M())}else s.dispatch(A());else s.dispatch(A())}function Klt(s,t,n){return Math.max(n.anchor,n.head)>t.content.size?null:CGe(s,t.resolve(n.anchor),t.resolve(n.head))}function j6s(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||DPe(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 k6s(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 QMt{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 $Ts,this.prevDirectPlugins=[],this.pluginViews=[],this.requiresGeckoHackNode=!1,this.dragging=null,this._props=n,this.state=n.state,this.directPlugins=n.plugins||[],this.directPlugins.forEach(ect),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=Qlt(this),Xlt(this),this.nodeViews=Jlt(this),this.docView=Tlt(this.state.doc,Zlt(this),IPe(this),this.dom,this),this.domObserver=new p6s(this,(r,a,i,l)=>w6s(this,r,a,i,l)),this.domObserver.start(),UTs(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&&M7e(this);let n=this._props;this._props=t,t.plugins&&(t.plugins.forEach(ect),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&&(HMt(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=Jlt(this);C6s(p,this.nodeViews)&&(this.nodeViews=p,i=!0)}(o||n.handleDOMEvents!=this._props.handleDOMEvents)&&M7e(this),this.editable=Qlt(this),Xlt(this);let c=IPe(this),d=Zlt(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&&sTs(this);if(l){this.domObserver.stop();let p=h&&(Db||fy)&&!this.composing&&!a.selection.empty&&!t.selection.empty&&S6s(a.selection,t.selection);if(h){let x=fy?this.trackWrites=this.domSelectionRange().focusNode:null;this.composing&&(this.input.compositionNode=s6s(this)),(i||!this.docView.update(t.doc,d,c,this))&&(this.docView.updateOuterDeco(d),this.docView.destroy(),this.docView=Tlt(t.doc,d,c,this.dom,this)),x&&(!this.trackWrites||!this.dom.contains(this.trackWrites))&&(p=!0)}p||!(this.input.mouseDown&&this.domObserver.currentSelection.eq(this.domSelectionRange())&&STs(this))?K3(this,p):(PMt(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&&nTs(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 qo){let n=this.docView.domAfterPos(this.state.selection.from);n.nodeType==1&&Nlt(this,n.getBoundingClientRect(),t)}else Nlt(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 cTs(this,t)}coordsAtPos(t,n=1){return kMt(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 pTs(this,n||this.state,t)}pasteHTML(t,n){return sX(this,"",t,!1,n||new ClipboardEvent("paste"))}pasteText(t,n){return sX(this,t,null,!0,n||new ClipboardEvent("paste"))}serializeForClipboard(t){return AGe(this,t)}destroy(){this.docView&&(qTs(this),this.destroyPluginViews(),this.mounted?(this.docView.update(this.state.doc,[],IPe(this),this),this.dom.textContent=""):this.dom.parentNode&&this.dom.parentNode.removeChild(this.dom),this.docView.destroy(),this.docView=null,GEs())}get isDestroyed(){return this.docView==null}dispatchEvent(t){return HTs(this,t)}domSelectionRange(){let t=this.domSelection();return t?fv&&this.root.nodeType===11&&XEs(this.dom.ownerDocument)==this.dom&&x6s(this,t)||t:{focusNode:null,focusOffset:0,anchorNode:null,anchorOffset:0}}domSelection(){return this.root.getSelection()}}QMt.prototype.dispatch=function(s){let t=this._props.dispatchTransaction;t?t.call(this,s):this.updateState(this.state.apply(s))};function Zlt(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"),[l1.node(0,s.state.doc.content.size,t)]}function Xlt(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:l1.widget(s.state.selection.from,t,{raw:!0,marks:s.markCursor})}}else s.cursorWrapper=null}function Qlt(s){return!s.someProp("editable",t=>t(s.state)===!1)}function S6s(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 Jlt(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 C6s(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 ect(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 o6={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:"'"},fSe={48:")",49:"!",50:"@",51:"#",52:"$",53:"%",54:"^",55:"&",56:"*",57:"(",59:":",61:"+",173:"_",186:":",187:"+",188:"<",189:"_",190:">",191:"?",192:"~",219:"{",220:"|",221:"}",222:'"'},A6s=typeof navigator<"u"&&/Mac/.test(navigator.platform),E6s=typeof navigator<"u"&&/MSIE \d|Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(navigator.userAgent);for(var uy=0;uy<10;uy++)o6[48+uy]=o6[96+uy]=String(uy);for(var uy=1;uy<=24;uy++)o6[uy+111]="F"+uy;for(var uy=65;uy<=90;uy++)o6[uy]=String.fromCharCode(uy+32),fSe[uy]=String.fromCharCode(uy);for(var RPe in o6)fSe.hasOwnProperty(RPe)||(fSe[RPe]=o6[RPe]);function T6s(s){var t=A6s&&s.metaKey&&s.shiftKey&&!s.ctrlKey&&!s.altKey||E6s&&s.shiftKey&&s.key&&s.key.length==1||s.key=="Unidentified",n=!t&&s.key||(s.shiftKey?fSe:o6)[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 M6s=typeof navigator<"u"&&/Mac|iP(hone|[oa]d)/.test(navigator.platform),L6s=typeof navigator<"u"&&/Win/.test(navigator.platform);function P6s(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 JMt(s,t){let{$cursor:n}=s.selection;return!n||(t?!t.endOfTextblock("backward",s):n.parentOffset>0)?null:n}const O6s=(s,t,n)=>{let r=JMt(s,n);if(!r)return!1;let a=DGe(r);if(!a){let l=r.blockRange(),o=l&&Oq(l);return o==null?!1:(t&&t(s.tr.lift(l,o).scrollIntoView()),!0)}let i=a.nodeBefore;if(nLt(s,a,t,-1))return!0;if(r.parent.content.size==0&&(lU(i,"end")||qo.isSelectable(i)))for(let l=r.depth;;l--){let o=aAe(s.doc,r.before(l),r.after(l),xi.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},F6s=(s,t,n)=>{let r=JMt(s,n);if(!r)return!1;let a=DGe(r);return a?eLt(s,a,t):!1},z6s=(s,t,n)=>{let r=tLt(s,n);if(!r)return!1;let a=RGe(r);return a?eLt(s,a,t):!1};function eLt(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=aAe(s.doc,i,c,xi.empty);if(!d||d.from!=i||d instanceof Cx&&d.slice.size>=c-i)return!1;if(n){let u=s.tr.step(d);u.setSelection(Qo.create(u.doc,i)),n(u.scrollIntoView())}return!0}function lU(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 B6s=(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=DGe(r)}let l=i&&i.nodeBefore;return!l||!qo.isSelectable(l)?!1:(t&&t(s.tr.setSelection(qo.create(s.doc,i.pos-l.nodeSize)).scrollIntoView()),!0)};function DGe(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 tLt(s,t){let{$cursor:n}=s.selection;return!n||(t?!t.endOfTextblock("forward",s):n.parentOffset{let r=tLt(s,n);if(!r)return!1;let a=RGe(r);if(!a)return!1;let i=a.nodeAfter;if(nLt(s,a,t,1))return!0;if(r.parent.content.size==0&&(lU(i,"start")||qo.isSelectable(i))){let l=aAe(s.doc,r.before(),r.after(),xi.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 qo,a;if(r){if(n.node.isTextblock||!L6(s.doc,n.from))return!1;a=n.from}else if(a=rAe(s.doc,n.from,-1),a==null)return!1;if(t){let i=s.tr.join(a);r&&i.setSelection(qo.create(i.doc,a-s.doc.resolve(a).nodeBefore.nodeSize)),t(i.scrollIntoView())}return!0},V6s=(s,t)=>{let n=s.selection,r;if(n instanceof qo){if(n.node.isTextblock||!L6(s.doc,n.to))return!1;r=n.to}else if(r=rAe(s.doc,n.to,1),r==null)return!1;return t&&t(s.tr.join(r).scrollIntoView()),!0},H6s=(s,t)=>{let{$from:n,$to:r}=s.selection,a=n.blockRange(r),i=a&&Oq(a);return i==null?!1:(t&&t(s.tr.lift(a,i).scrollIntoView()),!0)},G6s=(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 sLt(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=sLt(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(hl.near(c.doc.resolve(o),1)),t(c.scrollIntoView())}return!0},K6s=(s,t)=>{let n=s.selection,{$from:r,$to:a}=n;if(n instanceof Qj||r.parent.inlineContent||a.parent.inlineContent)return!1;let i=sLt(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(nB(s.doc,i))return t&&t(s.tr.split(i).scrollIntoView()),!0}let r=n.blockRange(),a=r&&Oq(r);return a==null?!1:(t&&t(s.tr.lift(r,a).scrollIntoView()),!0)},Z6s=(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(qo.create(s.doc,a))),!0)};function X6s(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||L6(s.doc,t.pos))?!1:(n&&n(s.tr.join(t.pos).scrollIntoView()),!0)}function nLt(s,t,n,r){let a=t.nodeBefore,i=t.nodeAfter,l,o,c=a.type.spec.isolating||i.type.spec.isolating;if(!c&&X6s(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,x=Ia.empty;for(let b=l.length-1;b>=0;b--)x=Ia.from(l[b].create(null,x));x=Ia.from(a.copy(x));let g=s.tr.step(new N0(t.pos-1,p,t.pos,p,new xi(x,1,0),l.length,!0)),y=g.doc.resolve(p+2*l.length);y.nodeAfter&&y.nodeAfter.type==a.type&&L6(g.doc,y.pos)&&g.join(y.pos),n(g.scrollIntoView())}return!0}let u=i.type.spec.isolating||r>0&&c?null:hl.findFrom(t,1),h=u&&u.$from.blockRange(u.$to),m=h&&Oq(h);if(m!=null&&m>=t.depth)return n&&n(s.tr.lift(h,m).scrollIntoView()),!0;if(d&&lU(i,"start",!0)&&lU(a,"end")){let p=a,x=[];for(;x.push(p),!p.isTextblock;)p=p.lastChild;let g=i,y=1;for(;!g.isTextblock;g=g.firstChild)y++;if(p.canReplace(p.childCount,p.childCount,g.content)){if(n){let b=Ia.empty;for(let N=x.length-1;N>=0;N--)b=Ia.from(x[N].copy(b));let v=s.tr.step(new N0(t.pos-x.length,t.pos+i.nodeSize,t.pos+y,t.pos+i.nodeSize-y,new xi(b,x.length,0),0,!0));n(v.scrollIntoView())}return!0}}return!1}function rLt(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(Qo.create(t.doc,s<0?a.start(i):a.end(i)))),!0):!1}}const Q6s=rLt(-1),J6s=rLt(1);function eMs(s,t=null){return function(n,r){let{$from:a,$to:i}=n.selection,l=a.blockRange(i),o=l&&wGe(l,s,t);return o?(r&&r(n.tr.wrap(l,o).scrollIntoView()),!0):!1}}function tct(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 lSe(c,c,t.depth),t.endIndex=0;u--)i=Ia.from(n[u].type.create(n[u].attrs,i));s.step(new N0(t.start-(r?2:0),t.end,t.start,t.end,new xi(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?aMs(t,n,s,i):iMs(t,n,i):!0:!1}}function aMs(s,t,n,r){let a=s.tr,i=r.end,l=r.$to.end(r.depth);ig;x--)p-=a.child(x).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?Ia.empty:Ia.from(a))))return!1;let h=i.pos,m=h+l.nodeSize;return r.step(new N0(h-(o?1:0),m+(c?1:0),h+1,m-1,new xi((o?Ia.empty:Ia.from(a.copy(Ia.empty))).append(c?Ia.empty:Ia.from(a.copy(Ia.empty))),o?0:1,c?0:1),o?0:1)),t(r.scrollIntoView()),!0}function oMs(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=Ia.from(d?s.create():null),h=new xi(Ia.from(s.create(null,Ia.from(o.type.create(null,u)))),d?3:1,0),m=i.start,p=i.end;n(t.tr.step(new N0(m-(d?3:1),p,m,p,h,1,!0)).scrollIntoView())}return!0}}function dAe(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 uAe=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,(...g)=>{const y=this.buildProps(d,n),b=p(...g)(y);return o.push(b),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:dAe({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}},lMs=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 oo(s,t,n){return s.config[t]===void 0&&s.parent?oo(s.parent,t,n):typeof s.config[t]=="function"?s.config[t].bind({...n,parent:s.parent?oo(s.parent,t,n):null}):s.config[t]}function hAe(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 aLt(s){const t=[],{nodeExtensions:n,markExtensions:r}=hAe(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=oo(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=oo(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 C0(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 ap(...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 L7e(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)=>ap(n,r),{})}function iLt(s){return typeof s=="function"}function jc(s,t=void 0,...n){return iLt(s)?t?s.bind(t)(...n):s(...n):s}function cMs(s={}){return Object.keys(s).length===0&&s.constructor===Object}function dMs(s){return typeof s!="string"?s:s.match(/^[+-]?(?:\d*\.)?\d+$/)?Number(s):s==="true"?!0:s==="false"?!1:s}function sct(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):dMs(n.getAttribute(l.name));return o==null?i:{...i,[l.name]:o}},{});return{...r,...a}}}}function nct(s){return Object.fromEntries(Object.entries(s).filter(([t,n])=>t==="attrs"&&cMs(n)?!1:n!=null))}function uMs(s,t){var n;const r=aLt(s),{nodeExtensions:a,markExtensions:i}=hAe(s),l=(n=a.find(d=>oo(d,"topNode")))===null||n===void 0?void 0:n.name,o=Object.fromEntries(a.map(d=>{const u=r.filter(b=>b.type===d.name),h={name:d.name,options:d.options,storage:d.storage,editor:t},m=s.reduce((b,v)=>{const N=oo(v,"extendNodeSchema",h);return{...b,...N?N(d):{}}},{}),p=nct({...m,content:jc(oo(d,"content",h)),marks:jc(oo(d,"marks",h)),group:jc(oo(d,"group",h)),inline:jc(oo(d,"inline",h)),atom:jc(oo(d,"atom",h)),selectable:jc(oo(d,"selectable",h)),draggable:jc(oo(d,"draggable",h)),code:jc(oo(d,"code",h)),whitespace:jc(oo(d,"whitespace",h)),linebreakReplacement:jc(oo(d,"linebreakReplacement",h)),defining:jc(oo(d,"defining",h)),isolating:jc(oo(d,"isolating",h)),attrs:Object.fromEntries(u.map(b=>{var v;return[b.name,{default:(v=b==null?void 0:b.attribute)===null||v===void 0?void 0:v.default}]}))}),x=jc(oo(d,"parseHTML",h));x&&(p.parseDOM=x.map(b=>sct(b,u)));const g=oo(d,"renderHTML",h);g&&(p.toDOM=b=>g({node:b,HTMLAttributes:L7e(b,u)}));const y=oo(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,b)=>{const v=oo(b,"extendMarkSchema",h);return{...y,...v?v(d):{}}},{}),p=nct({...m,inclusive:jc(oo(d,"inclusive",h)),excludes:jc(oo(d,"excludes",h)),group:jc(oo(d,"group",h)),spanning:jc(oo(d,"spanning",h)),code:jc(oo(d,"code",h)),attrs:Object.fromEntries(u.map(y=>{var b;return[y.name,{default:(b=y==null?void 0:y.attribute)===null||b===void 0?void 0:b.default}]}))}),x=jc(oo(d,"parseHTML",h));x&&(p.parseDOM=x.map(y=>sct(y,u)));const g=oo(d,"renderHTML",h);return g&&(p.toDOM=y=>g({mark:y,HTMLAttributes:L7e(y,u)})),[d.name,p]}));return new J6t({topNode:l,nodes:o,marks:c})}function FPe(s,t){return t.nodes[s]||t.marks[s]||null}function rct(s,t){return Array.isArray(t)?t.some(n=>(typeof n=="string"?n:n.name)===s.name):t}function OGe(s,t){const n=QO.fromSchema(t).serializeFragment(s),a=document.implementation.createHTMLDocument().createElement("div");return a.appendChild(n),a.innerHTML}const hMs=(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 FGe(s){return Object.prototype.toString.call(s)==="[object RegExp]"}class mAe{constructor(t){this.find=t.find,this.handler=t.handler}}const mMs=(s,t)=>{if(FGe(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 Bne(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=hMs(d)+i;return l.forEach(m=>{if(u)return;const p=mMs(h,m.find);if(!p)return;const x=c.state.tr,g=dAe({state:c.state,transaction:x}),y={from:r-(p[0].length-i.length),to:a},{commands:b,chain:v,can:N}=new uAe({editor:n,state:g});m.handler({state:g,range:y,match:p,commands:b,chain:v,can:N})===null||!x.steps.length||(x.setMeta(o,{transform:x,from:r,to:a,text:i}),c.dispatch(x),u=!0)}),u}function pMs(s){const{editor:t,rules:n}=s,r=new Lg({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=OGe(Ia.from(u),l.schema);const{from:h}=c,m=h+u.length;Bne({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 Bne({editor:t,from:i,to:l,text:o,rules:n,plugin:r})},handleDOMEvents:{compositionend:a=>(setTimeout(()=>{const{$cursor:i}=a.state.selection;i&&Bne({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?Bne({editor:t,from:l.pos,to:l.pos,text:` `,rules:n,plugin:r}):!1}},isInputRules:!0});return r}function fMs(s){return Object.prototype.toString.call(s).slice(8,-1)}function $ne(s){return fMs(s)!=="Object"?!1:s.constructor===Object&&Object.getPrototypeOf(s)===Object.prototype}function pAe(s,t){const n={...s};return $ne(s)&&$ne(t)&&Object.keys(t).forEach(r=>{$ne(t[r])&&$ne(s[r])?n[r]=pAe(s[r],t[r]):n[r]=t[r]}),n}class GN{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=jc(oo(this,"addOptions",{name:this.name}))),this.storage=jc(oo(this,"addStorage",{name:this.name,options:this.options}))||{}}static create(t={}){return new GN(t)}configure(t={}){const n=this.extend({...this.config,addOptions:()=>pAe(this.options,t)});return n.name=this.name,n.parent=this.parent,n}extend(t={}){const n=new GN(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=jc(oo(n,"addOptions",{name:n.name})),n.storage=jc(oo(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 xMs(s){return typeof s=="number"}class gMs{constructor(t){this.find=t.find,this.handler=t.handler}}const yMs=(s,t,n)=>{if(FGe(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 vMs(s){const{editor:t,state:n,from:r,to:a,rule:i,pasteEvent:l,dropEvent:o}=s,{commands:c,chain:d,can:u}=new uAe({editor:t,state:n}),h=[];return n.doc.nodesBetween(r,a,(p,x)=>{if(!p.isTextblock||p.type.spec.code)return;const g=Math.max(r,x),y=Math.min(a,x+p.content.size),b=p.textBetween(g-x,y-x,void 0,"");yMs(b,i.find,l).forEach(N=>{if(N.index===void 0)return;const C=g+N.index+1,A=C+N[0].length,T={from:n.tr.mapping.map(C),to:n.tr.mapping.map(A)},P=i.handler({state:n,range:T,match:N,commands:c,chain:d,can:u,pasteEvent:l,dropEvent:o});h.push(P)})}),h.every(p=>p!==null)}let Une=null;const bMs=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 _Ms(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:x})=>{const g=u.tr,y=dAe({state:u,transaction:g});if(!(!vMs({editor:t,state:y,from:Math.max(h-1,0),to:m.b-1,rule:p,pasteEvent:x,dropEvent:o})||!g.steps.length)){try{o=typeof DragEvent<"u"?new DragEvent("drop"):null}catch{o=null}return l=typeof ClipboardEvent<"u"?new ClipboardEvent("paste"):null,g}};return n.map(u=>new Lg({view(h){const m=x=>{var g;r=!((g=h.dom.parentElement)===null||g===void 0)&&g.contains(x.target)?h.dom.parentElement:null,r&&(Une=t)},p=()=>{Une&&(Une=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=Une;p!=null&&p.isEditable&&setTimeout(()=>{const x=p.state.selection;x&&p.commands.deleteRange({from:x.from,to:x.to})},10)}return!1},paste:(h,m)=>{var p;const x=(p=m.clipboardData)===null||p===void 0?void 0:p.getData("text/html");return l=m,a=!!(x!=null&&x.includes("data-pm-slice")),!1}}},appendTransaction:(h,m,p)=>{const x=h[0],g=x.getMeta("uiEvent")==="paste"&&!a,y=x.getMeta("uiEvent")==="drop"&&!i,b=x.getMeta("applyPasteRules"),v=!!b;if(!g&&!y&&!v)return;if(v){let{text:A}=b;typeof A=="string"?A=A:A=OGe(Ia.from(A),p.schema);const{from:T}=b,P=T+A.length,M=bMs(A);return c({rule:u,state:p,from:T,to:{b:P},pasteEvt:M})}const N=m.doc.content.findDiffStart(p.doc.content),C=m.doc.content.findDiffEnd(p.doc.content);if(!(!xMs(N)||!C||N===C.b))return c({rule:u,state:p,from:N,to:C,pasteEvt:l})}}))}function wMs(s){const t=s.filter((n,r)=>s.indexOf(n)!==r);return Array.from(new Set(t))}class W9{constructor(t,n){this.splittableMarks=[],this.editor=n,this.extensions=W9.resolve(t),this.schema=uMs(this.extensions,n),this.setupExtensions()}static resolve(t){const n=W9.sort(W9.flatten(t)),r=wMs(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=oo(n,"addExtensions",r);return a?[n,...this.flatten(a())]:n}).flat(10)}static sort(t){return t.sort((r,a)=>{const i=oo(r,"priority")||100,l=oo(a,"priority")||100;return i>l?-1:i{const r={name:n.name,options:n.options,storage:n.storage,editor:this.editor,type:FPe(n.name,this.schema)},a=oo(n,"addCommands",r);return a?{...t,...a()}:t},{})}get plugins(){const{editor:t}=this,n=W9.sort([...this.extensions].reverse()),r=[],a=[],i=n.map(l=>{const o={name:l.name,options:l.options,storage:l.storage,editor:t,type:FPe(l.name,this.schema)},c=[],d=oo(l,"addKeyboardShortcuts",o);let u={};if(l.type==="mark"&&oo(l,"exitable",o)&&(u.ArrowRight=()=>GN.handleExit({editor:t,mark:l})),d){const g=Object.fromEntries(Object.entries(d()).map(([y,b])=>[y,()=>b({editor:t})]));u={...u,...g}}const h=D6s(u);c.push(h);const m=oo(l,"addInputRules",o);rct(l,t.options.enableInputRules)&&m&&r.push(...m());const p=oo(l,"addPasteRules",o);rct(l,t.options.enablePasteRules)&&p&&a.push(...p());const x=oo(l,"addProseMirrorPlugins",o);if(x){const g=x();c.push(...g)}return c}).flat();return[pMs({editor:t,rules:r}),..._Ms({editor:t,rules:a}),...i]}get attributes(){return aLt(this.extensions)}get nodeViews(){const{editor:t}=this,{nodeExtensions:n}=hAe(this.extensions);return Object.fromEntries(n.filter(r=>!!oo(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:C0(r.name,this.schema)},l=oo(r,"addNodeView",i);if(!l)return[];const o=(c,d,u,h,m)=>{const p=L7e(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:FPe(t.name,this.schema)};t.type==="mark"&&(!((n=jc(oo(t,"keepOnSplit",r)))!==null&&n!==void 0)||n)&&this.splittableMarks.push(t.name);const a=oo(t,"onBeforeCreate",r),i=oo(t,"onCreate",r),l=oo(t,"onUpdate",r),o=oo(t,"onSelectionUpdate",r),c=oo(t,"onTransaction",r),d=oo(t,"onFocus",r),u=oo(t,"onBlur",r),h=oo(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 ky{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=jc(oo(this,"addOptions",{name:this.name}))),this.storage=jc(oo(this,"addStorage",{name:this.name,options:this.options}))||{}}static create(t={}){return new ky(t)}configure(t={}){const n=this.extend({...this.config,addOptions:()=>pAe(this.options,t)});return n.name=this.name,n.parent=this.parent,n}extend(t={}){const n=new ky({...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=jc(oo(n,"addOptions",{name:n.name})),n.storage=jc(oo(n,"addStorage",{name:n.name,options:n.options})),n}}function oLt(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 lLt(s){return Object.fromEntries(Object.entries(s.nodes).filter(([,t])=>t.spec.toText).map(([t,n])=>[t,n.spec.toText]))}const jMs=ky.create({name:"clipboardTextSerializer",addOptions(){return{blockSeparator:void 0}},addProseMirrorPlugins(){return[new Lg({key:new vv("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=lLt(n);return oLt(r,{from:l,to:o},{...this.options.blockSeparator!==void 0?{blockSeparator:this.options.blockSeparator}:{},textSerializers:c})}}})]}}),NMs=()=>({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),kMs=(s=!1)=>({commands:t})=>t.setContent("",s),SMs=()=>({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 x=Oq(p);if(o.type.isTextblock){const{defaultType:g}=h.parent.contentMatchAt(h.index());t.setNodeMarkup(p.start,g)}(x||x===0)&&t.lift(p,x)})}),!0},CMs=s=>t=>s(t),AMs=()=>({state:s,dispatch:t})=>K6s(s,t),EMs=(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 Qo(r.doc.resolve(Math.max(l-1,0)))),!0},TMs=()=>({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},MMs=s=>({tr:t,state:n,dispatch:r})=>{const a=C0(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},LMs=s=>({tr:t,dispatch:n})=>{const{from:r,to:a}=s;return n&&t.delete(r,a),!0},PMs=()=>({state:s,dispatch:t})=>R6s(s,t),IMs=()=>({commands:s})=>s.keyboardShortcut("Enter"),DMs=()=>({state:s,dispatch:t})=>W6s(s,t);function xSe(s,t,n={strict:!0}){const r=Object.keys(t);return r.length?r.every(a=>n.strict?t[a]===s[a]:FGe(t[a])?t[a].test(s[a]):t[a]===s[a]):!0}function cLt(s,t,n={}){return s.find(r=>r.type===t&&xSe(Object.fromEntries(Object.keys(n).map(a=>[a,r.attrs[a]])),n))}function act(s,t,n={}){return!!cLt(s,t,n)}function zGe(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),!cLt([...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&&act([...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=I6(s,r.schema),{doc:l,selection:o}=n,{$from:c,from:d,to:u}=o;if(a){const h=zGe(c,i,t);if(h&&h.from<=d&&h.to>=u){const m=Qo.create(l,h.from,h.to);n.setSelection(m)}}return!0},OMs=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=()=>{(gSe()||ict())&&r.dom.focus(),requestAnimationFrame(()=>{n.isDestroyed||(r.focus(),FMs()&&!gSe()&&!ict()&&r.dom.focus({preventScroll:!0}))})};if(r.hasFocus()&&s===null||s===!1)return!0;if(i&&s===null&&!dLt(n.state.selection))return l(),!0;const o=uLt(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},BMs=(s,t)=>n=>s.every((r,a)=>t(r,{...n,index:a})),$Ms=(s,t)=>({tr:n,commands:r})=>r.insertContentAt({from:n.selection.from,to:n.selection.to},s,t),hLt=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&&hLt(r)}return s};function qne(s){const t=`${s}`,n=new window.DOMParser().parseFromString(t,"text/html").body;return hLt(n)}function rX(s,t,n){if(s instanceof FT||s instanceof Ia)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 Ia.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),rX("",t,n)}if(a){if(n.errorOnInvalidContent){let l=!1,o="";const c=new J6t({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?jY.fromSchema(c).parseSlice(qne(s),n.parseOptions):jY.fromSchema(c).parse(qne(s),n.parseOptions),n.errorOnInvalidContent&&l)throw new Error("[tiptap error]: Invalid HTML content",{cause:new Error(`Invalid element found: ${o}`)})}const i=jY.fromSchema(t);return n.slice?i.parseSlice(qne(s),n.parseOptions).content:i.parse(qne(s),n.parseOptions)}return rX("",t,n)}function UMs(s,t,n){const r=s.steps.length-1;if(r{l===0&&(l=u)}),s.setSelection(hl.near(s.doc.resolve(l),n))}const qMs=s=>!("type"in s),VMs=(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{rX(t,i.schema,{parseOptions:d,errorOnInvalidContent:!0})}catch(y){c(y)}try{o=rX(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((qMs(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 g;if(m){if(Array.isArray(t))g=t.map(y=>y.text||"").join("");else if(t instanceof Ia){let y="";t.forEach(b=>{b.text&&(y+=b.text)}),g=y}else typeof t=="object"&&t&&t.text?g=t.text:g=t;r.insertText(g,u,h)}else g=o,r.replaceWith(u,h,g);n.updateSelection&&UMs(r,r.steps.length-1,-1),n.applyInputRules&&r.setMeta("applyInputRules",{from:u,text:g}),n.applyPasteRules&&r.setMeta("applyPasteRules",{from:u,text:g})}return!0},HMs=()=>({state:s,dispatch:t})=>q6s(s,t),GMs=()=>({state:s,dispatch:t})=>V6s(s,t),WMs=()=>({state:s,dispatch:t})=>O6s(s,t),KMs=()=>({state:s,dispatch:t})=>$6s(s,t),YMs=()=>({state:s,dispatch:t,tr:n})=>{try{const r=rAe(s.doc,s.selection.$from.pos,-1);return r==null?!1:(n.join(r,2),t&&t(n),!0)}catch{return!1}},ZMs=()=>({state:s,dispatch:t,tr:n})=>{try{const r=rAe(s.doc,s.selection.$from.pos,1);return r==null?!1:(n.join(r,2),t&&t(n),!0)}catch{return!1}},XMs=()=>({state:s,dispatch:t})=>F6s(s,t),QMs=()=>({state:s,dispatch:t})=>z6s(s,t);function mLt(){return typeof navigator<"u"?/Mac/.test(navigator.platform):!1}function JMs(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=JMs(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 aX(s,t,n={}){const{from:r,to:a,empty:i}=s.selection,l=t?C0(t,s.schema):null,o=[];s.doc.nodesBetween(r,a,(h,m)=>{if(h.isText)return;const p=Math.max(r,m),x=Math.min(a,m+h.nodeSize);o.push({node:h,from:p,to:x})});const c=a-r,d=o.filter(h=>l?l.name===h.node.type.name:!0).filter(h=>xSe(h.node.attrs,n,{strict:!1}));return i?!!d.length:d.reduce((h,m)=>h+m.to-m.from,0)>=c}const tLs=(s,t={})=>({state:n,dispatch:r})=>{const a=C0(s,n.schema);return aX(n,a,t)?H6s(n,r):!1},sLs=()=>({state:s,dispatch:t})=>Y6s(s,t),nLs=s=>({state:t,dispatch:n})=>{const r=C0(s,t.schema);return rMs(r)(t,n)},rLs=()=>({state:s,dispatch:t})=>G6s(s,t);function fAe(s,t){return t.nodes[s]?"node":t.marks[s]?"mark":null}function oct(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 aLs=(s,t)=>({tr:n,state:r,dispatch:a})=>{let i=null,l=null;const o=fAe(typeof s=="string"?s:s.name,r.schema);return o?(o==="node"&&(i=C0(s,r.schema)),o==="mark"&&(l=I6(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,oct(d.attrs,t)),l&&d.marks.length&&d.marks.forEach(h=>{l===h.type&&n.addMark(u,u+d.nodeSize,l.create(oct(h.attrs,t)))})})}),!0):!1},iLs=()=>({tr:s,dispatch:t})=>(t&&s.scrollIntoView(),!0),oLs=()=>({tr:s,dispatch:t})=>{if(t){const n=new Qj(s.doc);s.setSelection(n)}return!0},lLs=()=>({state:s,dispatch:t})=>B6s(s,t),cLs=()=>({state:s,dispatch:t})=>U6s(s,t),dLs=()=>({state:s,dispatch:t})=>Z6s(s,t),uLs=()=>({state:s,dispatch:t})=>J6s(s,t),hLs=()=>({state:s,dispatch:t})=>Q6s(s,t);function P7e(s,t,n={},r={}){return rX(s,t,{slice:!1,parseOptions:n,errorOnInvalidContent:r.errorOnInvalidContent})}const mLs=(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=P7e(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 pLt(s,t){const n=I6(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 pLs(s,t){const n=new jGe(s);return t.forEach(r=>{r.steps.forEach(a=>{n.step(a)})}),n}function fLs(s){for(let t=0;t{n(a)&&r.push({node:a,pos:i})}),r}function fLt(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 BGe(s){return t=>fLt(t.$from,s)}function gLs(s,t){const n={from:0,to:s.content.size};return oLt(s,n,t)}function yLs(s,t){const n=C0(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 xLt(s,t){const n=fAe(typeof t=="string"?t:t.name,s.schema);return n==="node"?yLs(s,t):n==="mark"?pLt(s,t):{}}function vLs(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 bLs(s){const t=vLs(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 _Ls(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}})})}),bLs(r)}function $Ge(s,t,n){const r=[];return s===t?n.resolve(s).marks().forEach(a=>{const i=n.resolve(s),l=zGe(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 P2e(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 I7e(s,t,n={}){const{empty:r,ranges:a}=s.selection,i=t?I6(t,s.schema):null;if(r)return!!(s.storedMarks||s.selection.$from.marks()).filter(h=>i?i.name===h.type.name:!0).find(h=>xSe(h.attrs,n,{strict:!1}));let l=0;const o=[];if(a.forEach(({$from:h,$to:m})=>{const p=h.pos,x=m.pos;s.doc.nodesBetween(p,x,(g,y)=>{if(!g.isText&&!g.marks.length)return;const b=Math.max(p,y),v=Math.min(x,y+g.nodeSize),N=v-b;l+=N,o.push(...g.marks.map(C=>({mark:C,from:b,to:v})))})}),l===0)return!1;const c=o.filter(h=>i?i.name===h.mark.type.name:!0).filter(h=>xSe(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 wLs(s,t,n={}){if(!t)return aX(s,null,n)||I7e(s,null,n);const r=fAe(t,s.schema);return r==="node"?aX(s,t,n):r==="mark"?I7e(s,t,n):!1}function lct(s,t){const{nodeExtensions:n}=hAe(t),r=n.find(l=>l.name===s);if(!r)return!1;const a={name:r.name,options:r.options,storage:r.storage},i=jc(oo(r,"group",a));return typeof i!="string"?!1:i.split(" ").includes("list")}function UGe(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&&(UGe(i,{ignoreWhitespace:n,checkChildren:t})||(a=!1))}),a}return!1}function jLs(s){return s instanceof qo}function NLs(s,t,n){var r;const{selection:a}=t;let i=null;if(dLt(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),x=!!n.isInSet(u.marks)||!u.marks.some(g=>g.type.excludes(n));d=p&&x}return!d}),d})}const kLs=(s,t={})=>({tr:n,state:r,dispatch:a})=>{const{selection:i}=n,{empty:l,ranges:o}=i,c=I6(s,r.schema);if(a)if(l){const d=pLt(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 x=Math.max(p,u),g=Math.min(p+m.nodeSize,h);m.marks.find(b=>b.type===c)?m.marks.forEach(b=>{c===b.type&&n.addMark(x,g,c.create({...b.attrs,...t}))}):n.addMark(x,g,c.create(t))})});return NLs(r,n,c)},SLs=(s,t)=>({tr:n})=>(n.setMeta(s,t),!0),CLs=(s,t={})=>({state:n,dispatch:r,chain:a})=>{const i=C0(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})=>tct(i,{...l,...t})(n)?!0:o.clearNodes()).command(({state:o})=>tct(i,{...l,...t})(o,r)).run():(console.warn('[tiptap warn]: Currently "setNode()" only supports text block nodes.'),!1)},ALs=s=>({tr:t,dispatch:n})=>{if(n){const{doc:r}=t,a=R8(s,0,r.content.size),i=qo.create(r,a);t.setSelection(i)}return!0},ELs=s=>({tr:t,dispatch:n})=>{if(n){const{doc:r}=t,{from:a,to:i}=typeof s=="number"?{from:s,to:s}:s,l=Qo.atStart(r).from,o=Qo.atEnd(r).to,c=R8(a,l,o),d=R8(i,l,o),u=Qo.create(r,c,d);t.setSelection(u)}return!0},TLs=s=>({state:t,dispatch:n})=>{const r=C0(s,t.schema);return oMs(r)(t,n)};function cct(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 MLs=({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=P2e(d,o.node().type.name,o.node().attrs);if(i instanceof qo&&i.node.isBlock)return!o.parentOffset||!nB(l,o.pos)?!1:(r&&(s&&cct(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:fLs(o.node(-1).contentMatchAt(o.indexAfter(-1)));let p=h&&m?[{type:m,attrs:u}]:void 0,x=nB(t.doc,t.mapping.map(o.pos),1,p);if(!p&&!x&&nB(t.doc,t.mapping.map(o.pos),1,m?[{type:m}]:void 0)&&(x=!0,p=m?[{type:m,attrs:u}]:void 0),r){if(x&&(i instanceof Qo&&t.deleteSelection(),t.split(t.mapping.map(o.pos),1,p),m&&!h&&!o.parentOffset&&o.parent.type!==m)){const g=t.mapping.map(o.before()),y=t.doc.resolve(g);o.node(-1).canReplaceWith(y.index(),y.index()+1,m)&&t.setNodeMarkup(t.mapping.map(o.before()),m)}s&&cct(n,a.extensionManager.splittableMarks),t.scrollIntoView()}return x},LLs=(s,t={})=>({tr:n,state:r,dispatch:a,editor:i})=>{var l;const o=C0(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 b=Ia.empty;const v=c.index(-1)?1:c.index(-2)?2:3;for(let M=c.depth-v;M>=c.depth-3;M-=1)b=Ia.from(c.node(M).copy(b));const N=c.indexAfter(-1){if(P>-1)return!1;M.isTextblock&&M.content.size===0&&(P=I+1)}),P>-1&&n.setSelection(Qo.near(n.doc.resolve(P))),n.scrollIntoView()}return!0}const p=d.pos===c.end()?h.contentMatchAt(0).defaultType:null,x={...P2e(m,h.type.name,h.attrs),...t},g={...P2e(m,c.node().type.name,c.node().attrs),...t};n.delete(c.pos,d.pos);const y=p?[{type:o,attrs:x},{type:p,attrs:g}]:[{type:o,attrs:x}];if(!nB(n.doc,c.pos,2))return!1;if(a){const{selection:b,storedMarks:v}=r,{splittableMarks:N}=i.extensionManager,C=v||b.$to.parentOffset&&b.$from.marks();if(n.split(c.pos,2,y).scrollIntoView(),!C||!a)return!0;const A=C.filter(T=>N.includes(T.type.name));n.ensureMarks(A)}return!0},zPe=(s,t)=>{const n=BGe(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)&&L6(s.doc,n.pos)&&s.join(n.pos),!0},BPe=(s,t)=>{const n=BGe(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)&&L6(s.doc,r)&&s.join(r),!0},PLs=(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=C0(s,l.schema),x=C0(t,l.schema),{selection:g,storedMarks:y}=l,{$from:b,$to:v}=g,N=b.blockRange(v),C=y||g.$to.parentOffset&&g.$from.marks();if(!N)return!1;const A=BGe(T=>lct(T.type.name,h))(g);if(N.depth>=1&&A&&N.depth-A.depth<=1){if(A.node.type===p)return d.liftListItem(x);if(lct(A.node.type.name,h)&&p.validContent(A.node.content)&&o)return c().command(()=>(i.setNodeMarkup(A.pos,p),!0)).command(()=>zPe(i,p)).command(()=>BPe(i,p)).run()}return!n||!C||!o?c().command(()=>u().wrapInList(p,r)?!0:d.clearNodes()).wrapInList(p,r).command(()=>zPe(i,p)).command(()=>BPe(i,p)).run():c().command(()=>{const T=u().wrapInList(p,r),P=C.filter(M=>m.includes(M.type.name));return i.ensureMarks(P),T?!0:d.clearNodes()}).wrapInList(p,r).command(()=>zPe(i,p)).command(()=>BPe(i,p)).run()},ILs=(s,t={},n={})=>({state:r,commands:a})=>{const{extendEmptyMarkRange:i=!1}=n,l=I6(s,r.schema);return I7e(r,l,t)?a.unsetMark(l,{extendEmptyMarkRange:i}):a.setMark(l,t)},DLs=(s,t,n={})=>({state:r,commands:a})=>{const i=C0(s,r.schema),l=C0(t,r.schema),o=aX(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})},RLs=(s,t={})=>({state:n,commands:r})=>{const a=C0(s,n.schema);return aX(n,a,t)?r.lift(a):r.wrapIn(a,t)},OLs=()=>({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},FLs=()=>({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},zLs=(s,t={})=>({tr:n,state:r,dispatch:a})=>{var i;const{extendEmptyMarkRange:l=!1}=t,{selection:o}=n,c=I6(s,r.schema),{$from:d,empty:u,ranges:h}=o;if(!a)return!0;if(u&&l){let{from:m,to:p}=o;const x=(i=d.marks().find(y=>y.type===c))===null||i===void 0?void 0:i.attrs,g=zGe(d,c,x);g&&(m=g.from,p=g.to),n.removeMark(m,p,c)}else h.forEach(m=>{n.removeMark(m.$from.pos,m.$to.pos,c)});return n.removeStoredMark(c),!0},BLs=(s,t={})=>({tr:n,state:r,dispatch:a})=>{let i=null,l=null;const o=fAe(typeof s=="string"?s:s.name,r.schema);return o?(o==="node"&&(i=C0(s,r.schema)),o==="mark"&&(l=I6(s,r.schema)),a&&n.selection.ranges.forEach(c=>{const d=c.$from.pos,u=c.$to.pos;let h,m,p,x;n.selection.empty?r.doc.nodesBetween(d,u,(g,y)=>{i&&i===g.type&&(p=Math.max(y,d),x=Math.min(y+g.nodeSize,u),h=y,m=g)}):r.doc.nodesBetween(d,u,(g,y)=>{y=d&&y<=u&&(i&&i===g.type&&n.setNodeMarkup(y,void 0,{...g.attrs,...t}),l&&g.marks.length&&g.marks.forEach(b=>{if(l===b.type){const v=Math.max(y,d),N=Math.min(y+g.nodeSize,u);n.addMark(v,N,l.create({...b.attrs,...t}))}}))}),m&&(h!==void 0&&n.setNodeMarkup(h,void 0,{...m.attrs,...t}),l&&m.marks.length&&m.marks.forEach(g=>{l===g.type&&n.addMark(p,x,l.create({...g.attrs,...t}))}))}),!0):!1},$Ls=(s,t={})=>({state:n,dispatch:r})=>{const a=C0(s,n.schema);return eMs(a,t)(n,r)},ULs=(s,t={})=>({state:n,dispatch:r})=>{const a=C0(s,n.schema);return tMs(a,t)(n,r)};var qLs=Object.freeze({__proto__:null,blur:NMs,clearContent:kMs,clearNodes:SMs,command:CMs,createParagraphNear:AMs,cut:EMs,deleteCurrentNode:TMs,deleteNode:MMs,deleteRange:LMs,deleteSelection:PMs,enter:IMs,exitCode:DMs,extendMarkRange:RMs,first:OMs,focus:zMs,forEach:BMs,insertContent:$Ms,insertContentAt:VMs,joinBackward:WMs,joinDown:GMs,joinForward:KMs,joinItemBackward:YMs,joinItemForward:ZMs,joinTextblockBackward:XMs,joinTextblockForward:QMs,joinUp:HMs,keyboardShortcut:eLs,lift:tLs,liftEmptyBlock:sLs,liftListItem:nLs,newlineInCode:rLs,resetAttributes:aLs,scrollIntoView:iLs,selectAll:oLs,selectNodeBackward:lLs,selectNodeForward:cLs,selectParentNode:dLs,selectTextblockEnd:uLs,selectTextblockStart:hLs,setContent:mLs,setMark:kLs,setMeta:SLs,setNode:CLs,setNodeSelection:ALs,setTextSelection:ELs,sinkListItem:TLs,splitBlock:MLs,splitListItem:LLs,toggleList:PLs,toggleMark:ILs,toggleNode:DLs,toggleWrap:RLs,undoInputRule:OLs,unsetAllMarks:FLs,unsetMark:zLs,updateAttributes:BLs,wrapIn:$Ls,wrapInList:ULs});const VLs=ky.create({name:"commands",addCommands(){return{...qLs}}}),HLs=ky.create({name:"drop",addProseMirrorPlugins(){return[new Lg({key:new vv("tiptapDrop"),props:{handleDrop:(s,t,n,r)=>{this.editor.emit("drop",{editor:this.editor,event:t,slice:n,moved:r})}}})]}}),GLs=ky.create({name:"editable",addProseMirrorPlugins(){return[new Lg({key:new vv("editable"),props:{editable:()=>this.editor.options.editable}})]}}),WLs=new vv("focusEvents"),KLs=ky.create({name:"focusEvents",addProseMirrorPlugins(){const{editor:s}=this;return[new Lg({key:WLs,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}}}})]}}),YLs=ky.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,x=h.parent.isTextblock&&m>0?o.doc.resolve(m-1):h,g=x.parent.type.spec.isolating,y=h.pos-h.parentOffset,b=g&&x.parent.childCount===1?y===h.pos:hl.atStart(d).from===m;return!u||!p.type.isTextblock||p.textContent.length||!b||b&&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 gSe()||mLt()?i:a},addProseMirrorPlugins(){return[new Lg({key:new vv("clearDocument"),appendTransaction:(s,t,n)=>{if(s.some(g=>g.getMeta("composition")))return;const r=s.some(g=>g.docChanged)&&!t.doc.eq(n.doc),a=s.some(g=>g.getMeta("preventClearDocument"));if(!r||a)return;const{empty:i,from:l,to:o}=t.selection,c=hl.atStart(t.doc).from,d=hl.atEnd(t.doc).to;if(i||!(l===c&&o===d)||!UGe(n.doc))return;const m=n.tr,p=dAe({state:n,transaction:m}),{commands:x}=new uAe({editor:this.editor,state:p});if(x.clearNodes(),!!m.steps.length)return m}})]}}),ZLs=ky.create({name:"paste",addProseMirrorPlugins(){return[new Lg({key:new vv("tiptapPaste"),props:{handlePaste:(s,t,n)=>{this.editor.emit("paste",{editor:this.editor,event:t,slice:n})}}})]}}),XLs=ky.create({name:"tabindex",addProseMirrorPlugins(){return[new Lg({key:new vv("tabindex"),props:{attributes:()=>this.editor.isEditable?{tabindex:"0"}:{}}})]}});class b8{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 b8(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 b8(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 b8(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 b8(o,this.editor,a,a?n:null);a&&(c.actualDepth=this.depth+1),t.push(new b8(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 QLs=`.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 JLs(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 ePs extends lMs{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=JLs(QLs,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=iLt(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?[GLs,jMs.configure({blockSeparator:(n=(t=this.options.coreExtensionOptions)===null||t===void 0?void 0:t.clipboardTextSerializer)===null||n===void 0?void 0:n.blockSeparator}),VLs,KLs,YLs,XLs,HLs,ZLs].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 W9(a,this)}createCommandManager(){this.commandManager=new uAe({editor:this})}createSchema(){this.schema=this.extensionManager.schema}createView(){var t;let n;try{n=P7e(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=P7e(this.options.content,this.schema,this.options.parseOptions,{errorOnInvalidContent:!1})}const r=uLt(n,this.options.autofocus);this.view=new QMt(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:G9.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 xLt(this.state,t)}isActive(t,n){const r=typeof t=="string"?t:null,a=typeof t=="string"?n:t;return wLs(this.state,r,a)}getJSON(){return this.state.doc.toJSON()}getHTML(){return OGe(this.state.doc.content,this.schema)}getText(t){const{blockSeparator:n=` `,textSerializers:r={}}=t||{};return gLs(this.state.doc,{blockSeparator:n,textSerializers:{...lLt(this.schema),...r}})}get isEmpty(){return UGe(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 b8(n,this)}get $doc(){return this.$pos(0)}}function cU(s){return new mAe({find:s.find,handler:({state:t,range:n,match:r})=>{const a=jc(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($Ge(n.from,n.to,t.doc).filter(p=>p.mark.type.excluded.find(g=>g===s.type&&g!==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 gLt(s){return new mAe({find:s.find,handler:({state:t,range:n,match:r})=>{const a=jc(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 D7e(s){return new mAe({find:s.find,handler:({state:t,range:n,match:r})=>{const a=t.doc.resolve(n.from),i=jc(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 iX(s){return new mAe({find:s.find,handler:({state:t,range:n,match:r,chain:a})=>{const i=jc(s.getAttributes,void 0,r)||{},l=t.tr.delete(n.from,n.to),c=l.doc.resolve(n.from).blockRange(),d=c&&wGe(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,x=m||h.$to.parentOffset&&h.$from.marks();if(x){const g=x.filter(y=>p.includes(y.type.name));l.ensureMarks(g)}}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&&L6(l.doc,n.from-1)&&(!s.joinPredicate||s.joinPredicate(r,u))&&l.join(n.from-1)}})}let bv=class R7e{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=jc(oo(this,"addOptions",{name:this.name}))),this.storage=jc(oo(this,"addStorage",{name:this.name,options:this.options}))||{}}static create(t={}){return new R7e(t)}configure(t={}){const n=this.extend({...this.config,addOptions:()=>pAe(this.options,t)});return n.name=this.name,n.parent=this.parent,n}extend(t={}){const n=new R7e(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=jc(oo(n,"addOptions",{name:n.name})),n.storage=jc(oo(n,"addStorage",{name:n.name,options:n.options})),n}};function xO(s){return new gMs({find:s.find,handler:({state:t,range:n,match:r,pasteEvent:a})=>{const i=jc(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($Ge(n.from,n.to,t.doc).filter(x=>x.mark.type.excluded.find(y=>y===s.type&&y!==x.mark.type)).filter(x=>x.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 tPs(s,t){const{selection:n}=s,{$from:r}=n;if(n instanceof qo){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 sPs(s){return s&&s.__esModule&&Object.prototype.hasOwnProperty.call(s,"default")?s.default:s}var yLt={exports:{}},$Pe={};/** * @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 dct;function nPs(){if(dct)return $Pe;dct=1;var s=It;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(),x=r({inst:{value:p,getSnapshot:m}}),g=x[0].inst,y=x[1];return i(function(){g.value=p,g.getSnapshot=m,c(g)&&y({inst:g})},[h,p,m]),a(function(){return c(g)&&y({inst:g}),h(function(){c(g)&&y({inst:g})})},[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 $Pe.useSyncExternalStore=s.useSyncExternalStore!==void 0?s.useSyncExternalStore:u,$Pe}yLt.exports=nPs();var qGe=yLt.exports;const rPs=(...s)=>t=>{s.forEach(n=>{typeof n=="function"?n(t):n&&(n.current=t)})},aPs=({contentComponent:s})=>{const t=qGe.useSyncExternalStore(s.subscribe,s.getSnapshot,s.getServerSnapshot);return It.createElement(It.Fragment,null,Object.values(t))};function iPs(){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]:Qqe.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 oPs extends It.Component{constructor(t){var n;super(t),this.editorContentRef=It.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=iPs(),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 It.createElement(It.Fragment,null,It.createElement("div",{ref:rPs(n,this.editorContentRef),...r}),(t==null?void 0:t.contentComponent)&&It.createElement(aPs,{contentComponent:t.contentComponent}))}}const lPs=j.forwardRef((s,t)=>{const n=It.useMemo(()=>Math.floor(Math.random()*4294967295).toString(),[s.editor]);return It.createElement(oPs,{key:n,innerRef:t,...s})}),VGe=It.memo(lPs);var cPs=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},dPs=sPs(cPs),vLt={exports:{}},UPe={};/** * @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 uct;function uPs(){if(uct)return UPe;uct=1;var s=It,t=qGe;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 UPe.useSyncExternalStoreWithSelector=function(d,u,h,m,p){var x=i(null);if(x.current===null){var g={hasValue:!1,value:null};x.current=g}else g=x.current;x=o(function(){function b(T){if(!v){if(v=!0,N=T,T=m(T),p!==void 0&&g.hasValue){var P=g.value;if(p(P,T))return C=P}return C=T}if(P=C,r(N,T))return P;var M=m(T);return p!==void 0&&p(P,M)?P:(N=T,C=M)}var v=!1,N,C,A=h===void 0?null:h;return[function(){return b(u())},A===null?void 0:function(){return b(A())}]},[u,h,m,p]);var y=a(d,x[0],x[1]);return l(function(){g.hasValue=!0,g.value=y},[y]),c(y),y},UPe}vLt.exports=uPs();var hPs=vLt.exports;const mPs=typeof window<"u"?j.useLayoutEffect:j.useEffect;class pPs{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 fPs(s){var t;const[n]=j.useState(()=>new pPs(s.editor)),r=hPs.useSyncExternalStoreWithSelector(n.subscribe,n.getSnapshot,n.getServerSnapshot,s.selector,(t=s.equalityFn)!==null&&t!==void 0?t:dPs);return mPs(()=>n.watch(s.editor),[s.editor,n]),j.useDebugValue(r),r}const xPs=!1,O7e=typeof window>"u",gPs=O7e||!!(typeof window<"u"&&window.next);class HGe{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 O7e||gPs?null:this.createEditor();if(this.options.current.immediatelyRender&&O7e&&xPs)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 ePs(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?HGe.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 GGe(s={},t=[]){const n=j.useRef(s);n.current=s;const[r]=j.useState(()=>new HGe(n)),a=qGe.useSyncExternalStore(r.subscribe,r.getEditor,r.getServerSnapshot);return j.useDebugValue(a),j.useEffect(r.onRender(t)),fPs({editor:a,selector:({transactionNumber:i})=>s.shouldRerenderOnTransaction===!1?null:s.immediatelyRender&&i===0?0:i+1}),a}const yPs=j.createContext({editor:null});yPs.Consumer;const vPs=j.createContext({onDragStart:void 0}),bPs=()=>j.useContext(vPs);It.forwardRef((s,t)=>{const{onDragStart:n}=bPs(),r=s.as||"div";return It.createElement(r,{...s,ref:t,"data-node-view-wrapper":"",onDragStart:n,style:{whiteSpace:"normal",...s.style}})});const _Ps=/^\s*>\s$/,wPs=bv.create({name:"blockquote",addOptions(){return{HTMLAttributes:{}}},content:"block+",group:"block",defining:!0,parseHTML(){return[{tag:"blockquote"}]},renderHTML({HTMLAttributes:s}){return["blockquote",ap(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[iX({find:_Ps,type:this.type})]}}),jPs=/(?:^|\s)(\*\*(?!\s+\*\*)((?:[^*]+))\*\*(?!\s+\*\*))$/,NPs=/(?:^|\s)(\*\*(?!\s+\*\*)((?:[^*]+))\*\*(?!\s+\*\*))/g,kPs=/(?:^|\s)(__(?!\s+__)((?:[^_]+))__(?!\s+__))$/,SPs=/(?:^|\s)(__(?!\s+__)((?:[^_]+))__(?!\s+__))/g,CPs=GN.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",ap(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[cU({find:jPs,type:this.type}),cU({find:kPs,type:this.type})]},addPasteRules(){return[xO({find:NPs,type:this.type}),xO({find:SPs,type:this.type})]}}),APs="listItem",hct="textStyle",mct=/^\s*([-+*])\s$/,EPs=bv.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",ap(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(APs,this.editor.getAttributes(hct)).run():s.toggleList(this.name,this.options.itemTypeName,this.options.keepMarks)}},addKeyboardShortcuts(){return{"Mod-Shift-8":()=>this.editor.commands.toggleBulletList()}},addInputRules(){let s=iX({find:mct,type:this.type});return(this.options.keepMarks||this.options.keepAttributes)&&(s=iX({find:mct,type:this.type,keepMarks:this.options.keepMarks,keepAttributes:this.options.keepAttributes,getAttributes:()=>this.editor.getAttributes(hct),editor:this.editor})),[s]}}),TPs=/(^|[^`])`([^`]+)`(?!`)/,MPs=/(^|[^`])`([^`]+)`(?!`)/g,LPs=GN.create({name:"code",addOptions(){return{HTMLAttributes:{}}},excludes:"_",code:!0,exitable:!0,parseHTML(){return[{tag:"code"}]},renderHTML({HTMLAttributes:s}){return["code",ap(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[cU({find:TPs,type:this.type})]},addPasteRules(){return[xO({find:MPs,type:this.type})]}}),PPs=/^```([a-z]+)?[\s\n]$/,IPs=/^~~~([a-z]+)?[\s\n]$/,DPs=bv.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",ap(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(hl.near(r.resolve(o))),!0)):s.commands.exitCode()}}},addInputRules(){return[D7e({find:PPs,type:this.type,getAttributes:s=>({language:s[1]})}),D7e({find:IPs,type:this.type,getAttributes:s=>({language:s[1]})})]},addProseMirrorPlugins(){return[new Lg({key:new vv("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(Qo.near(l.doc.resolve(Math.max(0,l.selection.from-2)))),l.setMeta("paste",!0),s.dispatch(l),!0}}})]}}),RPs=bv.create({name:"doc",topNode:!0,content:"block+"});function OPs(s={}){return new Lg({view(t){return new FPs(t,s)}})}class FPs{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 x=p.getBoundingClientRect(),g=h?x.bottom:x.top;h&&m&&(g=(g+this.editorView.nodeDOM(this.cursorPos).getBoundingClientRect().top)/2);let y=this.width/2*o;r={left:x.left,right:x.right,top:g-y,bottom:g+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=dMt(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 zPs=ky.create({name:"dropCursor",addOptions(){return{color:"currentColor",width:1,class:void 0}},addProseMirrorPlugins(){return[OPs(this.options)]}});class gf extends hl{constructor(t){super(t,t)}map(t,n){let r=t.resolve(n.map(this.head));return gf.valid(r)?new gf(r):hl.near(r)}content(){return xi.empty}eq(t){return t instanceof gf&&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 gf(t.resolve(n.pos))}getBookmark(){return new WGe(this.anchor)}static valid(t){let n=t.parent;if(n.inlineContent||!BPs(t)||!$Ps(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&&gf.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(gf.valid(c))return c}for(;;){let l=n>0?i.firstChild:i.lastChild;if(!l){if(i.isAtom&&!i.isText&&!qo.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(gf.valid(o))return o}return null}}}gf.prototype.visible=!1;gf.findFrom=gf.findGapCursorFrom;hl.jsonID("gapcursor",gf);class WGe{constructor(t){this.pos=t}map(t){return new WGe(t.map(this.pos))}resolve(t){let n=t.resolve(this.pos);return gf.valid(n)?new gf(n):hl.near(n)}}function bLt(s){return s.isAtom||s.spec.isolating||s.spec.createGapCursor}function BPs(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||bLt(a.type))return!0;if(a.inlineContent)return!1}}return!0}function $Ps(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||bLt(a.type))return!0;if(a.inlineContent)return!1}}return!0}function UPs(){return new Lg({props:{decorations:GPs,createSelectionBetween(s,t,n){return t.pos==n.pos&&gf.valid(n)?new gf(n):null},handleClick:VPs,handleKeyDown:qPs,handleDOMEvents:{beforeinput:HPs}}})}const qPs=IGe({ArrowLeft:Vne("horiz",-1),ArrowRight:Vne("horiz",1),ArrowUp:Vne("vert",-1),ArrowDown:Vne("vert",1)});function Vne(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 Qo){if(!i.endOfTextblock(n)||o.depth==0)return!1;c=!1,o=r.doc.resolve(t>0?o.after():o.before())}let d=gf.findGapCursorFrom(o,t,c);return d?(a&&a(r.tr.setSelection(new gf(d))),!0):!1}}function VPs(s,t,n){if(!s||!s.editable)return!1;let r=s.state.doc.resolve(t);if(!gf.valid(r))return!1;let a=s.posAtCoords({left:n.clientX,top:n.clientY});return a&&a.inside>-1&&qo.isSelectable(s.state.doc.nodeAt(a.inside))?!1:(s.dispatch(s.state.tr.setSelection(new gf(r))),!0)}function HPs(s,t){if(t.inputType!="insertCompositionText"||!(s.state.selection instanceof gf))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=Ia.empty;for(let l=r.length-1;l>=0;l--)a=Ia.from(r[l].createAndFill(null,a));let i=s.state.tr.replace(n.pos,n.pos,new xi(a,0,0));return i.setSelection(Qo.near(i.doc.resolve(n.pos+1))),s.dispatch(i),!1}function GPs(s){if(!(s.selection instanceof gf))return null;let t=document.createElement("div");return t.className="ProseMirror-gapcursor",xf.create(s.doc,[l1.widget(s.selection.head,t,{key:"gapcursor"})])}const WPs=ky.create({name:"gapCursor",addProseMirrorPlugins(){return[UPs()]},extendNodeSchema(s){var t;const n={name:s.name,options:s.options,storage:s.storage};return{allowGapCursor:(t=jc(oo(s,"allowGapCursor",n)))!==null&&t!==void 0?t:null}}}),KPs=bv.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",ap(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()}}}),YPs=bv.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]}`,ap(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=>D7e({find:new RegExp(`^(#{${Math.min(...this.options.levels)},${s}})\\s$`),type:this.type,getAttributes:{level:s}}))}});var ySe=200,k0=function(){};k0.prototype.append=function(t){return t.length?(t=k0.from(t),!this.length&&t||t.length=n?k0.empty:this.sliceInner(Math.max(0,t),Math.min(this.length,n))};k0.prototype.get=function(t){if(!(t<0||t>=this.length))return this.getInner(t)};k0.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)};k0.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};k0.from=function(t){return t instanceof k0?t:t&&t.length?new _Lt(t):k0.empty};var _Lt=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<=ySe)return new t(this.values.concat(a.flatten()))},t.prototype.leafPrepend=function(a){if(this.length+a.length<=ySe)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}(k0);k0.empty=new _Lt([]);var ZPs=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}(k0);const XPs=500;class kN{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 aA(h.map));let p=h.step.map(a.slice(i)),x;p&&l.maybeStep(p).doc&&(x=l.mapping.maps[l.mapping.maps.length-1],d.push(new aA(x,void 0,void 0,d.length+u.length))),i--,x&&a.appendMap(x,i)}else l.maybeStep(h.step);if(h.selection)return o=a?h.selection.map(a.slice(i)):h.selection,c=new kN(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;uJPs&&(o=QPs(o,d),l-=d),new kN(o.append(i),l)}remapping(t,n){let r=new JZ;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 kN(this.items.append(t.map(n=>new aA(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 x=i.maps[p];if(m.step){let g=t.steps[p].invert(t.docs[p]),y=m.selection&&m.selection.map(i.slice(c+1,p));y&&o++,r.push(new aA(x,g,y))}else r.push(new aA(x))},a);let d=[];for(let m=n;mXPs&&(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 aA(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 kN(k0.from(a.reverse()),i)}}kN.empty=new kN(k0.empty,0);function QPs(s,t){let n;return s.forEach((r,a)=>{if(r.selection&&t--==0)return n=a,!1}),s.slice(n)}let aA=class wLt{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 wLt(n.getMap().invert(),n,this.selection)}}};class BA{constructor(t,n,r,a,i){this.done=t,this.undone=n,this.prevRanges=r,this.prevTime=a,this.prevComposition=i}}const JPs=20;function eIs(s,t,n,r){let a=n.getMeta(DR),i;if(a)return a.historyState;n.getMeta(nIs)&&(s=new BA(s.done,s.undone,null,0,-1));let l=n.getMeta("appendedTransaction");if(n.steps.length==0)return s;if(l&&l.getMeta(DR))return l.getMeta(DR).redo?new BA(s.done.addTransform(n,void 0,r,I2e(t)),s.undone,pct(n.mapping.maps),s.prevTime,s.prevComposition):new BA(s.done,s.undone.addTransform(n,void 0,r,I2e(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||!tIs(n,s.prevRanges)),d=l?qPe(s.prevRanges,n.mapping):pct(n.mapping.maps);return new BA(s.done.addTransform(n,c?t.selection.getBookmark():void 0,r,I2e(t)),kN.empty,d,n.time,o??s.prevComposition)}else return(i=n.getMeta("rebased"))?new BA(s.done.rebased(n,i),s.undone.rebased(n,i),qPe(s.prevRanges,n.mapping),s.prevTime,s.prevComposition):new BA(s.done.addMaps(n.mapping.maps),s.undone.addMaps(n.mapping.maps),qPe(s.prevRanges,n.mapping),s.prevTime,s.prevComposition)}function tIs(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 pct(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 qPe(s,t){if(!s)return null;let n=[];for(let r=0;r{let a=DR.getState(n);if(!a||(s?a.undone:a.done).eventCount==0)return!1;if(r){let i=sIs(a,n,s);i&&r(t?i.scrollIntoView():i)}return!0}}const NLt=jLt(!1,!0),kLt=jLt(!0,!0),aIs=ky.create({name:"history",addOptions(){return{depth:100,newGroupDelay:500}},addCommands(){return{undo:()=>({state:s,dispatch:t})=>NLt(s,t),redo:()=>({state:s,dispatch:t})=>kLt(s,t)}},addProseMirrorPlugins(){return[rIs(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()}}}),iIs=bv.create({name:"horizontalRule",addOptions(){return{HTMLAttributes:{}}},group:"block",parseHTML(){return[{tag:"hr"}]},renderHTML({HTMLAttributes:s}){return["hr",ap(this.options.HTMLAttributes,s)]},addCommands(){return{setHorizontalRule:()=>({chain:s,state:t})=>{if(!tPs(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}):jLs(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(Qo.create(l.doc,d.pos+1)):d.nodeAfter.isBlock?l.setSelection(qo.create(l.doc,d.pos)):l.setSelection(Qo.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(Qo.create(l.doc,u+1)))}l.scrollIntoView()}return!0}).run()}}},addInputRules(){return[gLt({find:/^(?:---|—-|___\s|\*\*\*\s)$/,type:this.type})]}}),oIs=/(?:^|\s)(\*(?!\s+\*)((?:[^*]+))\*(?!\s+\*))$/,lIs=/(?:^|\s)(\*(?!\s+\*)((?:[^*]+))\*(?!\s+\*))/g,cIs=/(?:^|\s)(_(?!\s+_)((?:[^_]+))_(?!\s+_))$/,dIs=/(?:^|\s)(_(?!\s+_)((?:[^_]+))_(?!\s+_))/g,uIs=GN.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",ap(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[cU({find:oIs,type:this.type}),cU({find:cIs,type:this.type})]},addPasteRules(){return[xO({find:lIs,type:this.type}),xO({find:dIs,type:this.type})]}}),hIs=bv.create({name:"listItem",addOptions(){return{HTMLAttributes:{},bulletListTypeName:"bulletList",orderedListTypeName:"orderedList"}},content:"paragraph block*",defining:!0,parseHTML(){return[{tag:"li"}]},renderHTML({HTMLAttributes:s}){return["li",ap(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)}}}),mIs="listItem",xct="textStyle",gct=/^(\d+)\.\s$/,pIs=bv.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",ap(this.options.HTMLAttributes,n),0]:["ol",ap(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(mIs,this.editor.getAttributes(xct)).run():s.toggleList(this.name,this.options.itemTypeName,this.options.keepMarks)}},addKeyboardShortcuts(){return{"Mod-Shift-7":()=>this.editor.commands.toggleOrderedList()}},addInputRules(){let s=iX({find:gct,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=iX({find:gct,type:this.type,keepMarks:this.options.keepMarks,keepAttributes:this.options.keepAttributes,getAttributes:t=>({start:+t[1],...this.editor.getAttributes(xct)}),joinPredicate:(t,n)=>n.childCount+n.attrs.start===+t[1],editor:this.editor})),[s]}}),fIs=bv.create({name:"paragraph",priority:1e3,addOptions(){return{HTMLAttributes:{}}},group:"block",content:"inline*",parseHTML(){return[{tag:"p"}]},renderHTML({HTMLAttributes:s}){return["p",ap(this.options.HTMLAttributes,s),0]},addCommands(){return{setParagraph:()=>({commands:s})=>s.setNode(this.name)}},addKeyboardShortcuts(){return{"Mod-Alt-0":()=>this.editor.commands.setParagraph()}}}),xIs=/(?:^|\s)(~~(?!\s+~~)((?:[^~]+))~~(?!\s+~~))$/,gIs=/(?:^|\s)(~~(?!\s+~~)((?:[^~]+))~~(?!\s+~~))/g,yIs=GN.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",ap(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[cU({find:xIs,type:this.type})]},addPasteRules(){return[xO({find:gIs,type:this.type})]}}),vIs=bv.create({name:"text",group:"inline"}),KGe=ky.create({name:"starterKit",addExtensions(){const s=[];return this.options.bold!==!1&&s.push(CPs.configure(this.options.bold)),this.options.blockquote!==!1&&s.push(wPs.configure(this.options.blockquote)),this.options.bulletList!==!1&&s.push(EPs.configure(this.options.bulletList)),this.options.code!==!1&&s.push(LPs.configure(this.options.code)),this.options.codeBlock!==!1&&s.push(DPs.configure(this.options.codeBlock)),this.options.document!==!1&&s.push(RPs.configure(this.options.document)),this.options.dropcursor!==!1&&s.push(zPs.configure(this.options.dropcursor)),this.options.gapcursor!==!1&&s.push(WPs.configure(this.options.gapcursor)),this.options.hardBreak!==!1&&s.push(KPs.configure(this.options.hardBreak)),this.options.heading!==!1&&s.push(YPs.configure(this.options.heading)),this.options.history!==!1&&s.push(aIs.configure(this.options.history)),this.options.horizontalRule!==!1&&s.push(iIs.configure(this.options.horizontalRule)),this.options.italic!==!1&&s.push(uIs.configure(this.options.italic)),this.options.listItem!==!1&&s.push(hIs.configure(this.options.listItem)),this.options.orderedList!==!1&&s.push(pIs.configure(this.options.orderedList)),this.options.paragraph!==!1&&s.push(fIs.configure(this.options.paragraph)),this.options.strike!==!1&&s.push(yIs.configure(this.options.strike)),this.options.text!==!1&&s.push(vIs.configure(this.options.text)),s}}),bIs="aaa1rp3bb0ott3vie4c1le2ogado5udhabi7c0ademy5centure6ountant0s9o1tor4d0s1ult4e0g1ro2tna4f0l1rica5g0akhan5ency5i0g1rbus3force5tel5kdn3l0ibaba4pay4lfinanz6state5y2sace3tom5m0azon4ericanexpress7family11x2fam3ica3sterdam8nalytics7droid5quan4z2o0l2partments8p0le4q0uarelle8r0ab1mco4chi3my2pa2t0e3s0da2ia2sociates9t0hleta5torney7u0ction5di0ble3o3spost5thor3o0s4w0s2x0a2z0ure5ba0by2idu3namex4d1k2r0celona5laycard4s5efoot5gains6seball5ketball8uhaus5yern5b0c1t1va3cg1n2d1e0ats2uty4er2rlin4st0buy5t2f1g1h0arti5i0ble3d1ke2ng0o3o1z2j1lack0friday9ockbuster8g1omberg7ue3m0s1w2n0pparibas9o0ats3ehringer8fa2m1nd2o0k0ing5sch2tik2on4t1utique6x2r0adesco6idgestone9oadway5ker3ther5ussels7s1t1uild0ers6siness6y1zz3v1w1y1z0h3ca0b1fe2l0l1vinklein9m0era3p2non3petown5ital0one8r0avan4ds2e0er0s4s2sa1e1h1ino4t0ering5holic7ba1n1re3c1d1enter4o1rn3f0a1d2g1h0anel2nel4rity4se2t2eap3intai5ristmas6ome4urch5i0priani6rcle4sco3tadel4i0c2y3k1l0aims4eaning6ick2nic1que6othing5ud3ub0med6m1n1o0ach3des3ffee4llege4ogne5m0mbank4unity6pany2re3uter5sec4ndos3struction8ulting7tact3ractors9oking4l1p2rsica5untry4pon0s4rses6pa2r0edit0card4union9icket5own3s1uise0s6u0isinella9v1w1x1y0mru3ou3z2dad1nce3ta1e1ing3sun4y2clk3ds2e0al0er2s3gree4livery5l1oitte5ta3mocrat6ntal2ist5si0gn4v2hl2iamonds6et2gital5rect0ory7scount3ver5h2y2j1k1m1np2o0cs1tor4g1mains5t1wnload7rive4tv2ubai3nlop4pont4rban5vag2r2z2earth3t2c0o2deka3u0cation8e1g1mail3erck5nergy4gineer0ing9terprises10pson4quipment8r0icsson6ni3s0q1tate5t1u0rovision8s2vents5xchange6pert3osed4ress5traspace10fage2il1rwinds6th3mily4n0s2rm0ers5shion4t3edex3edback6rrari3ero6i0delity5o2lm2nal1nce1ial7re0stone6mdale6sh0ing5t0ness6j1k1lickr3ghts4r2orist4wers5y2m1o0o0d1tball6rd1ex2sale4um3undation8x2r0ee1senius7l1ogans4ntier7tr2ujitsu5n0d2rniture7tbol5yi3ga0l0lery3o1up4me0s3p1rden4y2b0iz3d0n2e0a1nt0ing5orge5f1g0ee3h1i0ft0s3ves2ing5l0ass3e1obal2o4m0ail3bh2o1x2n1odaddy5ld0point6f2o0dyear5g0le4p1t1v2p1q1r0ainger5phics5tis4een3ipe3ocery4up4s1t1u0cci3ge2ide2tars5ru3w1y2hair2mburg5ngout5us3bo2dfc0bank7ealth0care8lp1sinki6re1mes5iphop4samitsu7tachi5v2k0t2m1n1ockey4ldings5iday5medepot5goods5s0ense7nda3rse3spital5t0ing5t0els3mail5use3w2r1sbc3t1u0ghes5yatt3undai7ibm2cbc2e1u2d1e0ee3fm2kano4l1m0amat4db2mo0bilien9n0c1dustries8finiti5o2g1k1stitute6urance4e4t0ernational10uit4vestments10o1piranga7q1r0ish4s0maili5t0anbul7t0au2v3jaguar4va3cb2e0ep2tzt3welry6io2ll2m0p2nj2o0bs1urg4t1y2p0morgan6rs3uegos4niper7kaufen5ddi3e0rryhotels6properties14fh2g1h1i0a1ds2m1ndle4tchen5wi3m1n1oeln3matsu5sher5p0mg2n2r0d1ed3uokgroup8w1y0oto4z2la0caixa5mborghini8er3nd0rover6xess5salle5t0ino3robe5w0yer5b1c1ds2ease3clerc5frak4gal2o2xus4gbt3i0dl2fe0insurance9style7ghting6ke2lly3mited4o2ncoln4k2ve1ing5k1lc1p2oan0s3cker3us3l1ndon4tte1o3ve3pl0financial11r1s1t0d0a3u0ndbeck6xe1ury5v1y2ma0drid4if1son4keup4n0agement7go3p1rket0ing3s4riott5shalls7ttel5ba2c0kinsey7d1e0d0ia3et2lbourne7me1orial6n0u2rckmsd7g1h1iami3crosoft7l1ni1t2t0subishi9k1l0b1s2m0a2n1o0bi0le4da2e1i1m1nash3ey2ster5rmon3tgage6scow4to0rcycles9v0ie4p1q1r1s0d2t0n1r2u0seum3ic4v1w1x1y1z2na0b1goya4me2vy3ba2c1e0c1t0bank4flix4work5ustar5w0s2xt0direct7us4f0l2g0o2hk2i0co2ke1on3nja3ssan1y5l1o0kia3rton4w0ruz3tv4p1r0a1w2tt2u1yc2z2obi1server7ffice5kinawa6layan0group9lo3m0ega4ne1g1l0ine5oo2pen3racle3nge4g0anic5igins6saka4tsuka4t2vh3pa0ge2nasonic7ris2s1tners4s1y3y2ccw3e0t2f0izer5g1h0armacy6d1ilips5one2to0graphy6s4ysio5ics1tet2ures6d1n0g1k2oneer5zza4k1l0ace2y0station9umbing5s3m1n0c2ohl2ker3litie5rn2st3r0axi3ess3ime3o0d0uctions8f1gressive8mo2perties3y5tection8u0dential9s1t1ub2w0c2y2qa1pon3uebec3st5racing4dio4e0ad1lestate6tor2y4cipes5d0stone5umbrella9hab3ise0n3t2liance6n0t0als5pair3ort3ublican8st0aurant8view0s5xroth6ich0ardli6oh3l1o1p2o0cks3deo3gers4om3s0vp3u0gby3hr2n2w0e2yukyu6sa0arland6fe0ty4kura4le1on3msclub4ung5ndvik0coromant12ofi4p1rl2s1ve2xo3b0i1s2c0b1haeffler7midt4olarships8ol3ule3warz5ience5ot3d1e0arch3t2cure1ity6ek2lect4ner3rvices6ven3w1x0y3fr2g1h0angrila6rp3ell3ia1ksha5oes2p0ping5uji3w3i0lk2na1gles5te3j1k0i0n2y0pe4l0ing4m0art3ile4n0cf3o0ccer3ial4ftbank4ware6hu2lar2utions7ng1y2y2pa0ce3ort2t3r0l2s1t0ada2ples4r1tebank4farm7c0group6ockholm6rage3e3ream4udio2y3yle4u0cks3pplies3y2ort5rf1gery5zuki5v1watch4iss4x1y0dney4stems6z2tab1ipei4lk2obao4rget4tamotors6r2too4x0i3c0i2d0k2eam2ch0nology8l1masek5nnis4va3f1g1h0d1eater2re6iaa2ckets5enda4ps2res2ol4j0maxx4x2k0maxx5l1m0all4n1o0day3kyo3ols3p1ray3shiba5tal3urs3wn2yota3s3r0ade1ing4ining5vel0ers0insurance16ust3v2t1ube2i1nes3shu4v0s2w1z2ua1bank3s2g1k1nicom3versity8o2ol2ps2s1y1z2va0cations7na1guard7c1e0gas3ntures6risign5mögensberater2ung14sicherung10t2g1i0ajes4deo3g1king4llas4n1p1rgin4sa1ion4va1o3laanderen9n1odka3lvo3te1ing3o2yage5u2wales2mart4ter4ng0gou5tch0es6eather0channel12bcam3er2site5d0ding5ibo2r3f1hoswho6ien2ki2lliamhill9n0dows4e1ners6me2olterskluwer11odside6rk0s2ld3w2s1tc1f3xbox3erox4ihuan4n2xx2yz3yachts4hoo3maxun5ndex5e1odobashi7ga2kohama6u0tube6t1un3za0ppos4ra3ero3ip2m1one3uerich6w2",_Is="ελ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",F7e="numeric",z7e="ascii",B7e="alpha",CY="asciinumeric",_W="alphanumeric",$7e="domain",SLt="emoji",wIs="scheme",jIs="slashscheme",HPe="whitespace";function NIs(s,t){return s in t||(t[s]=[]),t[s]}function O8(s,t,n){t[F7e]&&(t[CY]=!0,t[_W]=!0),t[z7e]&&(t[CY]=!0,t[B7e]=!0),t[CY]&&(t[_W]=!0),t[B7e]&&(t[_W]=!0),t[_W]&&(t[$7e]=!0),t[SLt]&&(t[$7e]=!0);for(const r in t){const a=NIs(r,n);a.indexOf(s)<0&&a.push(s)}}function kIs(s,t){const n={};for(const r in t)t[r].indexOf(s)>=0&&(n[r]=!0);return n}function vb(s=null){this.j={},this.jr=[],this.jd=null,this.t=s}vb.groups={};vb.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),af=(s,t,n,r,a)=>s.tr(t,n,r,a),yct=(s,t,n,r,a)=>s.ts(t,n,r,a),Fa=(s,t,n,r,a)=>s.tt(t,n,r,a),D4="WORD",U7e="UWORD",CLt="ASCIINUMERICAL",ALt="ALPHANUMERICAL",oX="LOCALHOST",q7e="TLD",V7e="UTLD",D2e="SCHEME",m9="SLASH_SCHEME",YGe="NUM",H7e="WS",ZGe="NL",AY="OPENBRACE",EY="CLOSEBRACE",vSe="OPENBRACKET",bSe="CLOSEBRACKET",_Se="OPENPAREN",wSe="CLOSEPAREN",jSe="OPENANGLEBRACKET",NSe="CLOSEANGLEBRACKET",kSe="FULLWIDTHLEFTPAREN",SSe="FULLWIDTHRIGHTPAREN",CSe="LEFTCORNERBRACKET",ASe="RIGHTCORNERBRACKET",ESe="LEFTWHITECORNERBRACKET",TSe="RIGHTWHITECORNERBRACKET",MSe="FULLWIDTHLESSTHAN",LSe="FULLWIDTHGREATERTHAN",PSe="AMPERSAND",ISe="APOSTROPHE",DSe="ASTERISK",$A="AT",RSe="BACKSLASH",OSe="BACKTICK",FSe="CARET",eE="COLON",XGe="COMMA",zSe="DOLLAR",tS="DOT",BSe="EQUALS",QGe="EXCLAMATION",hj="HYPHEN",TY="PERCENT",$Se="PIPE",USe="PLUS",qSe="POUND",MY="QUERY",JGe="QUOTE",ELt="FULLWIDTHMIDDLEDOT",eWe="SEMI",sS="SLASH",LY="TILDE",VSe="UNDERSCORE",TLt="EMOJI",HSe="SYM";var MLt=Object.freeze({__proto__:null,ALPHANUMERICAL:ALt,AMPERSAND:PSe,APOSTROPHE:ISe,ASCIINUMERICAL:CLt,ASTERISK:DSe,AT:$A,BACKSLASH:RSe,BACKTICK:OSe,CARET:FSe,CLOSEANGLEBRACKET:NSe,CLOSEBRACE:EY,CLOSEBRACKET:bSe,CLOSEPAREN:wSe,COLON:eE,COMMA:XGe,DOLLAR:zSe,DOT:tS,EMOJI:TLt,EQUALS:BSe,EXCLAMATION:QGe,FULLWIDTHGREATERTHAN:LSe,FULLWIDTHLEFTPAREN:kSe,FULLWIDTHLESSTHAN:MSe,FULLWIDTHMIDDLEDOT:ELt,FULLWIDTHRIGHTPAREN:SSe,HYPHEN:hj,LEFTCORNERBRACKET:CSe,LEFTWHITECORNERBRACKET:ESe,LOCALHOST:oX,NL:ZGe,NUM:YGe,OPENANGLEBRACKET:jSe,OPENBRACE:AY,OPENBRACKET:vSe,OPENPAREN:_Se,PERCENT:TY,PIPE:$Se,PLUS:USe,POUND:qSe,QUERY:MY,QUOTE:JGe,RIGHTCORNERBRACKET:ASe,RIGHTWHITECORNERBRACKET:TSe,SCHEME:D2e,SEMI:eWe,SLASH:sS,SLASH_SCHEME:m9,SYM:HSe,TILDE:LY,TLD:q7e,UNDERSCORE:VSe,UTLD:V7e,UWORD:U7e,WORD:D4,WS:H7e});const _4=/[a-z]/,oG=new RegExp("\\p{L}","u"),GPe=new RegExp("\\p{Emoji}","u"),w4=/\d/,WPe=/\s/,vct="\r",KPe=` `,SIs="️",CIs="‍",YPe="";let Hne=null,Gne=null;function AIs(s=[]){const t={};vb.groups=t;const n=new vb;Hne==null&&(Hne=bct(bIs)),Gne==null&&(Gne=bct(_Is)),Fa(n,"'",ISe),Fa(n,"{",AY),Fa(n,"}",EY),Fa(n,"[",vSe),Fa(n,"]",bSe),Fa(n,"(",_Se),Fa(n,")",wSe),Fa(n,"<",jSe),Fa(n,">",NSe),Fa(n,"(",kSe),Fa(n,")",SSe),Fa(n,"「",CSe),Fa(n,"」",ASe),Fa(n,"『",ESe),Fa(n,"』",TSe),Fa(n,"<",MSe),Fa(n,">",LSe),Fa(n,"&",PSe),Fa(n,"*",DSe),Fa(n,"@",$A),Fa(n,"`",OSe),Fa(n,"^",FSe),Fa(n,":",eE),Fa(n,",",XGe),Fa(n,"$",zSe),Fa(n,".",tS),Fa(n,"=",BSe),Fa(n,"!",QGe),Fa(n,"-",hj),Fa(n,"%",TY),Fa(n,"|",$Se),Fa(n,"+",USe),Fa(n,"#",qSe),Fa(n,"?",MY),Fa(n,'"',JGe),Fa(n,"/",sS),Fa(n,";",eWe),Fa(n,"~",LY),Fa(n,"_",VSe),Fa(n,"\\",RSe),Fa(n,"・",ELt);const r=af(n,w4,YGe,{[F7e]:!0});af(r,w4,r);const a=af(r,_4,CLt,{[CY]:!0}),i=af(r,oG,ALt,{[_W]:!0}),l=af(n,_4,D4,{[z7e]:!0});af(l,w4,a),af(l,_4,l),af(a,w4,a),af(a,_4,a);const o=af(n,oG,U7e,{[B7e]:!0});af(o,_4),af(o,w4,i),af(o,oG,o),af(i,w4,i),af(i,_4),af(i,oG,i);const c=Fa(n,KPe,ZGe,{[HPe]:!0}),d=Fa(n,vct,H7e,{[HPe]:!0}),u=af(n,WPe,H7e,{[HPe]:!0});Fa(n,YPe,u),Fa(d,KPe,c),Fa(d,YPe,u),af(d,WPe,u),Fa(u,vct),Fa(u,KPe),af(u,WPe,u),Fa(u,YPe,u);const h=af(n,GPe,TLt,{[SLt]:!0});Fa(h,"#"),af(h,GPe,h),Fa(h,SIs,h);const m=Fa(h,CIs);Fa(m,"#"),af(m,GPe,h);const p=[[_4,l],[w4,a]],x=[[_4,null],[oG,o],[w4,i]];for(let g=0;gg[0]>y[0]?1:-1);for(let g=0;g=0?v[$7e]=!0:_4.test(y)?w4.test(y)?v[CY]=!0:v[z7e]=!0:v[F7e]=!0,yct(n,y,y,v)}return yct(n,"localhost",oX,{ascii:!0}),n.jd=new vb(HSe),{start:n,tokens:Object.assign({groups:t},MLt)}}function LLt(s,t){const n=EIs(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 EIs(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 iA(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 lX={defaultProtocol:"http",events:null,format:_ct,formatHref:_ct,nl2br:!1,tagName:"a",target:null,rel:null,validate:!0,truncate:1/0,className:null,attributes:null,ignoreTags:[],render:null};function tWe(s,t=null){let n=Object.assign({},lX);s&&(n=Object.assign(n,s instanceof tWe?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=lX.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 xAe(s,t){class n extends PLt{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 wct=xAe("email",{isLink:!0,toHref(){return"mailto:"+this.toString()}}),jct=xAe("text"),TIs=xAe("nl"),Wne=xAe("url",{isLink:!0,toHref(s=lX.defaultProtocol){return this.hasProtocol()?this.v:`${s}://${this.v}`},hasProtocol(){const s=this.tk;return s.length>=2&&s[0].t!==oX&&s[1].t===eE}}),Jw=s=>new vb(s);function MIs({groups:s}){const t=s.domain.concat([PSe,DSe,$A,RSe,OSe,FSe,zSe,BSe,hj,YGe,TY,$Se,USe,qSe,sS,HSe,LY,VSe]),n=[ISe,eE,XGe,tS,QGe,TY,MY,JGe,eWe,jSe,NSe,AY,EY,bSe,vSe,_Se,wSe,kSe,SSe,CSe,ASe,ESe,TSe,MSe,LSe],r=[PSe,ISe,DSe,RSe,OSe,FSe,zSe,BSe,hj,AY,EY,TY,$Se,USe,qSe,MY,sS,HSe,LY,VSe],a=Jw(),i=Fa(a,LY);wc(i,r,i),wc(i,s.domain,i);const l=Jw(),o=Jw(),c=Jw();wc(a,s.domain,l),wc(a,s.scheme,o),wc(a,s.slashscheme,c),wc(l,r,i),wc(l,s.domain,l);const d=Fa(l,$A);Fa(i,$A,d),Fa(o,$A,d),Fa(c,$A,d);const u=Fa(i,tS);wc(u,r,i),wc(u,s.domain,i);const h=Jw();wc(d,s.domain,h),wc(h,s.domain,h);const m=Fa(h,tS);wc(m,s.domain,h);const p=Jw(wct);wc(m,s.tld,p),wc(m,s.utld,p),Fa(d,oX,p);const x=Fa(h,hj);Fa(x,hj,x),wc(x,s.domain,h),wc(p,s.domain,h),Fa(p,tS,m),Fa(p,hj,x);const g=Fa(p,eE);wc(g,s.numeric,wct);const y=Fa(l,hj),b=Fa(l,tS);Fa(y,hj,y),wc(y,s.domain,l),wc(b,r,i),wc(b,s.domain,l);const v=Jw(Wne);wc(b,s.tld,v),wc(b,s.utld,v),wc(v,s.domain,l),wc(v,r,i),Fa(v,tS,b),Fa(v,hj,y),Fa(v,$A,d);const N=Fa(v,eE),C=Jw(Wne);wc(N,s.numeric,C);const A=Jw(Wne),T=Jw();wc(A,t,A),wc(A,n,T),wc(T,t,A),wc(T,n,T),Fa(v,sS,A),Fa(C,sS,A);const P=Fa(o,eE),M=Fa(c,eE),I=Fa(M,sS),D=Fa(I,sS);wc(o,s.domain,l),Fa(o,tS,b),Fa(o,hj,y),wc(c,s.domain,l),Fa(c,tS,b),Fa(c,hj,y),wc(P,s.domain,A),Fa(P,sS,A),Fa(P,MY,A),wc(D,s.domain,A),wc(D,t,A),Fa(D,sS,A);const B=[[AY,EY],[vSe,bSe],[_Se,wSe],[jSe,NSe],[kSe,SSe],[CSe,ASe],[ESe,TSe],[MSe,LSe]];for(let q=0;q=0&&m++,a++,u++;if(m<0)a-=u,a0&&(i.push(ZPe(jct,t,l)),l=[]),a-=m,u-=m;const p=h.t,x=n.slice(a-u,a);i.push(ZPe(p,t,x))}}return l.length>0&&i.push(ZPe(jct,t,l)),i}function ZPe(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 PIs=typeof console<"u"&&console&&console.warn||(()=>{}),IIs="until manual call of linkify.init(). Register all schemes and plugins before invoking linkify the first time.",vm={scanner:null,parser:null,tokenQueue:[],pluginQueue:[],customSchemes:[],initialized:!1};function DIs(){return vb.groups={},vm.scanner=null,vm.parser=null,vm.tokenQueue=[],vm.pluginQueue=[],vm.customSchemes=[],vm.initialized=!1,vm}function Nct(s,t=!1){if(vm.initialized&&PIs(`linkifyjs: already initialized - will not register custom scheme "${s}" ${IIs}`),!/^[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`);vm.customSchemes.push([s,t])}function RIs(){vm.scanner=AIs(vm.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=pLs(n.doc,[...t]);if(_Ls(o).forEach(({newRange:d})=>{const u=xLs(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(!FIs.test(p))return;h=u[0],m=r.doc.textBetween(h.pos,d.to,void 0," ")}if(h&&m){const p=m.split(OIs).filter(Boolean);if(p.length<=0)return!1;const x=p[p.length-1],g=h.pos+m.lastIndexOf(x);if(!x)return!1;const y=sWe(x).map(b=>b.toObject(s.defaultProtocol));if(!BIs(y))return!1;y.filter(b=>b.isLink).map(b=>({...b,from:g+b.start+1,to:g+b.end+1})).filter(b=>r.schema.marks.code?!r.doc.rangeHasMark(b.from,b.to,r.schema.marks.code):!0).filter(b=>s.validate(b.value)).filter(b=>s.shouldAutoLink(b.value)).forEach(b=>{$Ge(b.from,b.to,r.doc).some(v=>v.mark.type===s.type)||l.addMark(b.from,b.to,s.type.create({href:b.href}))})}}),!!l.steps.length)return l}})}function UIs(s){return new Lg({key:new vv("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=xLt(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 qIs(s){return new Lg({key:new vv("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=ILt(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 OM(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(zIs,"").match(new RegExp(`^(?:(?:${n.join("|")}):|[^a-z]|[a-z0-9+.-]+(?:[^a-z+.-:]|$))`,"i"))}const rWe=GN.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"){Nct(s);return}Nct(s.scheme,s.optionalSlashes)})},onDestroy(){DIs()},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)=>!!OM(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=>!!OM(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=>!!OM(t,this.options.protocols),protocols:this.options.protocols,defaultProtocol:this.options.defaultProtocol})?["a",ap(this.options.HTMLAttributes,s),0]:["a",ap(this.options.HTMLAttributes,{...s,href:""}),0]},addCommands(){return{setLink:s=>({chain:t})=>{const{href:n}=s;return this.options.isAllowedUri(n,{defaultValidate:r=>!!OM(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=>!!OM(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[xO({find:s=>{const t=[];if(s){const{protocols:n,defaultProtocol:r}=this.options,a=ILt(s).filter(i=>i.isLink&&this.options.isAllowedUri(i.value,{defaultValidate:l=>!!OM(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($Is({type:this.type,defaultProtocol:this.options.defaultProtocol,validate:r=>this.options.isAllowedUri(r,{defaultValidate:a=>!!OM(a,t),protocols:t,defaultProtocol:n}),shouldAutoLink:this.options.shouldAutoLink})),this.options.openOnClick===!0&&s.push(UIs({type:this.type})),this.options.linkOnPaste&&s.push(qIs({editor:this.editor,defaultProtocol:this.options.defaultProtocol,type:this.type})),s}}),aWe=ky.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")}}}),VIs=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}`)})},iWe=GN.create({name:"textStyle",priority:101,addOptions(){return{HTMLAttributes:{},mergeNestedSpanStyles:!1}},parseHTML(){return[{tag:"span",getAttrs:s=>s.hasAttribute("style")?(this.options.mergeNestedSpanStyles&&VIs(s),{}):!1}]},renderHTML({HTMLAttributes:s}){return["span",ap(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}}}}),HIs=/(?:^|\s)(!\[(.+|:?)]\((\S+)(?:(?:\s+)["'](\S+)["'])?\))$/,GIs=bv.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",ap(this.options.HTMLAttributes,s)]},addCommands(){return{setImage:s=>({commands:t})=>t.insertContent({type:this.name,attrs:s})}},addInputRules(){return[gLt({find:HIs,type:this.type,getAttributes:s=>{const[,,t,n,r]=s;return{src:n,alt:t,title:r}}})]}});let G7e,W7e;if(typeof WeakMap<"u"){let s=new WeakMap;G7e=t=>s.get(t),W7e=(t,n)=>(s.set(t,n),n)}else{const s=[];let n=0;G7e=r=>{for(let a=0;a(n==10&&(n=0),s[n++]=r,s[n++]=a)}var vf=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:b-N});break}const C=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 YIs(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 XIs(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 sk(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 gAe(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=gO(t.$head)||QIs(t.$head);if(n)return n;throw new RangeError(`No cell found around position ${t.head}`)}function QIs(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 K7e(s){return s.parent.type.spec.tableRole=="row"&&!!s.nodeAfter}function JIs(s){return s.node(0).resolve(s.pos+s.nodeAfter.nodeSize)}function oWe(s,t){return s.depth==t.depth&&s.pos>=t.start(-1)&&s.pos<=t.end(-1)}function DLt(s,t,n){const r=s.node(-1),a=vf.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 yO(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 RLt(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 fMt(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(K7e(r)&&K7e(a)&&oWe(r,a)){const i=this.$anchorCell.node(-1)!=r.node(-1);return i&&this.isRowSelection()?R4.rowSelection(r,a):i&&this.isColSelection()?R4.colSelection(r,a):new R4(r,a)}return Qo.between(r,a)}content(){const t=this.$anchorCell.node(-1),n=vf.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 b=x.attrs;if(g>0&&(b=yO(b,0,g)),y>0&&(b=yO(b,b.colspan-y,y)),p.lefta.bottom){const b={...x.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=vf.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 R4&&t.$anchorCell.pos==this.$anchorCell.pos&&t.$headCell.pos==this.$headCell.pos}static rowSelection(t,n=t){const r=t.node(-1),a=vf.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(l1.node(r,r+n.nodeSize,{class:"selectedCell"}))}),xf.create(s.doc,t)}function n8s({$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 r8s({$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 a8s(s,t,n){const r=(t||s).selection,a=(t||s).doc;let i,l;if(r instanceof qo&&(l=r.node.type.spec.tableRole)){if(l=="cell"||l=="header_cell")i=em.create(a,r.from);else if(l=="row"){const o=a.resolve(r.from+1);i=em.rowSelection(o,o)}else if(!n){const o=vf.get(r.node),c=r.from+1,d=c+o.map[o.width*o.height-1];i=em.create(a,c+1,d)}}else r instanceof Qo&&n8s(r)?i=Qo.create(a,r.from):r instanceof Qo&&r8s(r)&&(i=Qo.create(a,r.$from.start(),r.$from.end()));return i&&(t||(t=s.tr)).setSelection(i),t}const i8s=new vv("fix-tables");function FLt(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=o8s(s,a,i,n))};return t?t.doc!=s.doc&&FLt(t.doc,s.doc,0,r):s.doc.descendants(r),n}function o8s(s,t,n,r){const a=vf.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 x=[];for(let y=0;y0?-1:0;e8s(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;h8s(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=kct(d)?c+1:u;i.replaceWith(h+r.tableStart,u+r.tableStart,o)}i.setSelection(new em(i.doc.resolve(c+r.tableStart))),t(i)}return!0}function Cct(s,t){const n=xv(s.schema);return y8s(({node:r})=>n[r.type.spec.tableRole])(s,t)}function y8s(s){return(t,n)=>{const r=t.selection;let a,i;if(r instanceof em){if(r.$anchorCell.pos!=r.$headCell.pos)return!1;a=r.$anchorCell.nodeAfter,i=r.$anchorCell.pos}else{var l;if(a=XIs(r.$from),!a)return!1;i=(l=gO(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=I5(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 b8s(s){return function(t,n){if(!sk(t))return!1;if(n){const r=xv(t.schema),a=I5(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,x=l.doc.nodeAt(p);x&&l.setNodeMarkup(p,h,x.attrs)}),r(l)}return!0}}cX("row",{useDeprecatedLogic:!0});cX("column",{useDeprecatedLogic:!0});const _8s=cX("cell",{useDeprecatedLogic:!0});function w8s(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 Kne(s,t){const n=s.selection;if(!(n instanceof em))return!1;if(t){const r=s.tr,a=xv(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 xi(a,0,0))}),r.docChanged&&t(r)}return!0}function N8s(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(Ia.empty),n[a]r&&(m=m.type.createChecked(yO(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(Ia.from(c))}n=i,t=a}return{width:s,height:t,rows:n}}function C8s(s,t,n,r,a,i,l){const o=s.doc.type.schema,c=xv(o);let d,u;if(a>t.width)for(let h=0,m=0;ht.height){const h=[];for(let x=0,g=(t.height-1)*t.width;x=t.width?!1:n.nodeAt(t.map[g+x]).type==c.header_cell;h.push(y?u||(u=c.header_cell.createAndFill()):d||(d=c.cell.createAndFill()))}const m=c.row.create(null,Ia.from(h)),p=[];for(let x=t.height;x{if(!a)return!1;const i=n.selection;if(i instanceof em)return R2e(n,r,hl.near(i.$headCell,t));if(s!="horiz"&&!i.empty)return!1;const l=ULt(a,s,t);if(l==null)return!1;if(s=="horiz")return R2e(n,r,hl.near(n.doc.resolve(i.head+t),t));{const o=n.doc.resolve(l),c=DLt(o,s,t);let d;return c?d=hl.near(c,1):t<0?d=hl.near(n.doc.resolve(o.before(-1)),-1):d=hl.near(n.doc.resolve(o.after(-1)),1),R2e(n,r,d)}}}function Zne(s,t){return(n,r,a)=>{if(!a)return!1;const i=n.selection;let l;if(i instanceof em)l=i;else{const c=ULt(a,s,t);if(c==null)return!1;l=new em(n.doc.resolve(c))}const o=DLt(l.$headCell,s,t);return o?R2e(n,r,new em(l.$anchorCell,o)):!1}}function E8s(s,t){const n=s.state.doc,r=gO(n.resolve(t));return r?(s.dispatch(s.state.tr.setSelection(new em(r))),!0):!1}function T8s(s,t,n){if(!sk(s.state))return!1;let r=N8s(n);const a=s.state.selection;if(a instanceof em){r||(r={width:1,height:1,rows:[Ia.from(Y7e(xv(s.state.schema).cell,n))]});const i=a.$anchorCell.node(-1),l=a.$anchorCell.start(-1),o=vf.get(i).rectBetween(a.$anchorCell.pos-l,a.$headCell.pos-l);return r=S8s(r,o.right-o.left,o.bottom-o.top),Lct(s.state,s.dispatch,l,o,r),!0}else if(r){const i=gAe(s.state),l=i.start(-1);return Lct(s.state,s.dispatch,l,vf.get(i.node(-1)).findCell(i.pos-l),r),!0}else return!1}function M8s(s,t){var n;if(t.button!=0||t.ctrlKey||t.metaKey)return;const r=Pct(s,t.target);let a;if(t.shiftKey&&s.state.selection instanceof em)i(s.state.selection.$anchorCell,t),t.preventDefault();else if(t.shiftKey&&r&&(a=gO(s.state.selection.$anchor))!=null&&((n=XPe(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=XPe(s,d);const h=tE.getState(s.state)==null;if(!u||!oWe(c,u))if(h)u=c;else return;const m=new em(c,u);if(h||!s.state.selection.eq(m)){const p=s.state.tr.setSelection(m);h&&p.setMeta(tE,c.pos),s.dispatch(p)}}function l(){s.root.removeEventListener("mouseup",l),s.root.removeEventListener("dragstart",l),s.root.removeEventListener("mousemove",o),tE.getState(s.state)!=null&&s.dispatch(s.state.tr.setMeta(tE,-1))}function o(c){const d=c,u=tE.getState(s.state);let h;if(u!=null)h=s.state.doc.resolve(u);else if(Pct(s,d.target)!=r&&(h=XPe(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 ULt(s,t,n){if(!(s.state.selection instanceof Qo))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 Pct(s,t){for(;t&&t!=s.dom;t=t.parentNode)if(t.nodeName=="TD"||t.nodeName=="TH")return t;return null}function XPe(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&&gO(s.state.doc.resolve(r))||gO(s.state.doc.resolve(a))}var L8s=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")),Z7e(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,Z7e(t,this.colgroup,this.table,this.defaultCellMinWidth),!0)}ignoreMutation(t){return t.type=="attributes"&&(t.target==this.table||this.colgroup.contains(t.target))}};function Z7e(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 I8s(-1,!1)},apply(l,o){return o.apply(l)}},props:{attributes:l=>{const o=G_.getState(l);return o&&o.activeHandle>-1?{class:"resize-cursor"}:{}},handleDOMEvents:{mousemove:(l,o)=>{D8s(l,o,s,a)},mouseleave:l=>{R8s(l)},mousedown:(l,o)=>{O8s(l,o,t,n)}},decorations:l=>{const o=G_.getState(l);if(o&&o.activeHandle>-1)return U8s(l,o.activeHandle)},nodeViews:{}}});return i}var I8s=class O2e{constructor(t,n){this.activeHandle=t,this.dragging=n}apply(t){const n=this,r=t.getMeta(G_);if(r&&r.setHandle!=null)return new O2e(r.setHandle,!1);if(r&&r.setDragging!==void 0)return new O2e(n.activeHandle,r.setDragging);if(n.activeHandle>-1&&t.docChanged){let a=t.mapping.map(n.activeHandle,-1);return K7e(t.doc.resolve(a))||(a=-1),new O2e(a,n.dragging)}return n}};function D8s(s,t,n,r){if(!s.editable)return;const a=G_.getState(s.state);if(a&&!a.dragging){const i=z8s(t.target);let l=-1;if(i){const{left:o,right:c}=i.getBoundingClientRect();t.clientX-o<=n?l=Ict(s,t,"left",n):c-t.clientX<=n&&(l=Ict(s,t,"right",n))}if(l!=a.activeHandle){if(!r&&l!==-1){const o=s.state.doc.resolve(l),c=o.node(-1),d=vf.get(c),u=o.start(-1);if(d.colCount(o.pos-u)+o.nodeAfter.attrs.colspan-1==d.width-1)return}qLt(s,l)}}}function R8s(s){if(!s.editable)return;const t=G_.getState(s.state);t&&t.activeHandle>-1&&!t.dragging&&qLt(s,-1)}function O8s(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=G_.getState(s.state);if(!l||l.activeHandle==-1||l.dragging)return!1;const o=s.state.doc.nodeAt(l.activeHandle),c=F8s(s,l.activeHandle,o.attrs);s.dispatch(s.state.tr.setMeta(G_,{setDragging:{startX:t.clientX,startWidth:c}}));function d(h){i.removeEventListener("mouseup",d),i.removeEventListener("mousemove",u);const m=G_.getState(s.state);m!=null&&m.dragging&&(B8s(s,m.activeHandle,Dct(m.dragging,h,n)),s.dispatch(s.state.tr.setMeta(G_,{setDragging:null})))}function u(h){if(!h.which)return d(h);const m=G_.getState(s.state);if(m&&m.dragging){const p=Dct(m.dragging,h,n);Rct(s,m.activeHandle,p,r)}}return Rct(s,l.activeHandle,c,r),i.addEventListener("mouseup",d),i.addEventListener("mousemove",u),t.preventDefault(),!0}function F8s(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 W8s(s,t,n,r,a){const i=G8s(s),l=[],o=[];for(let d=0;d{const{selection:t}=s.state;if(!K8s(t))return!1;let n=0;const r=fLt(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},Y8s=bv.create({name:"table",addOptions(){return{HTMLAttributes:{},resizable:!1,renderWrapper:!1,handleWidth:5,cellMinWidth:25,View:V8s,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}=H8s(s,this.options.cellMinWidth),i=["table",ap(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=W8s(i.schema,s,t,n);if(a){const o=r.selection.from+1;r.replaceSelectionWith(l).scrollIntoView().setSelection(Qo.near(r.doc.resolve(o)))}return!0},addColumnBefore:()=>({state:s,dispatch:t})=>l8s(s,t),addColumnAfter:()=>({state:s,dispatch:t})=>c8s(s,t),deleteColumn:()=>({state:s,dispatch:t})=>u8s(s,t),addRowBefore:()=>({state:s,dispatch:t})=>m8s(s,t),addRowAfter:()=>({state:s,dispatch:t})=>p8s(s,t),deleteRow:()=>({state:s,dispatch:t})=>x8s(s,t),deleteTable:()=>({state:s,dispatch:t})=>j8s(s,t),mergeCells:()=>({state:s,dispatch:t})=>Sct(s,t),splitCell:()=>({state:s,dispatch:t})=>Cct(s,t),toggleHeaderColumn:()=>({state:s,dispatch:t})=>cX("column")(s,t),toggleHeaderRow:()=>({state:s,dispatch:t})=>cX("row")(s,t),toggleHeaderCell:()=>({state:s,dispatch:t})=>_8s(s,t),mergeOrSplit:()=>({state:s,dispatch:t})=>Sct(s,t)?!0:Cct(s,t),setCellAttribute:(s,t)=>({state:n,dispatch:r})=>v8s(s,t)(n,r),goToNextCell:()=>({state:s,dispatch:t})=>Ect(1)(s,t),goToPreviousCell:()=>({state:s,dispatch:t})=>Ect(-1)(s,t),fixTables:()=>({state:s,dispatch:t})=>(t&&zLt(s),!0),setCellSelection:s=>({tr:t,dispatch:n})=>{if(n){const r=em.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:Xne,"Mod-Backspace":Xne,Delete:Xne,"Mod-Delete":Xne}},addProseMirrorPlugins(){return[...this.options.resizable&&this.editor.isEditable?[P8s({handleWidth:this.options.handleWidth,cellMinWidth:this.options.cellMinWidth,defaultCellMinWidth:this.options.cellMinWidth,View:this.options.View,lastColumnResizable:this.options.lastColumnResizable})]:[],q8s({allowTableNodeSelection:this.options.allowTableNodeSelection})]},extendNodeSchema(s){const t={name:s.name,options:s.options,storage:s.storage};return{tableRole:jc(oo(s,"tableRole",t))}}}),Z8s=bv.create({name:"tableRow",addOptions(){return{HTMLAttributes:{}}},content:"(tableCell | tableHeader)*",tableRole:"row",parseHTML(){return[{tag:"tr"}]},renderHTML({HTMLAttributes:s}){return["tr",ap(this.options.HTMLAttributes,s),0]}}),X8s=bv.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",ap(this.options.HTMLAttributes,s),0]}}),Q8s=bv.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",ap(this.options.HTMLAttributes,s),0]}});function m2({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=GGe({extensions:[KGe,rWe.configure({openOnClick:!1,HTMLAttributes:{class:"text-primary underline"}}),aWe.configure({types:["heading","paragraph"]}),iWe,GIs.extend({addAttributes(){var g;return{...(g=this.parent)==null?void 0:g.call(this),width:{default:null},height:{default:null},style:{default:null}}}}).configure({inline:!0,allowBase64:!0}),Y8s.extend({addAttributes(){var g;return{...(g=this.parent)==null?void 0:g.call(this),style:{default:null},width:{default:null},cellpadding:{default:null},cellspacing:{default:null},border:{default:null}}}}).configure({resizable:!1}),Z8s.extend({addAttributes(){var g;return{...(g=this.parent)==null?void 0:g.call(this),style:{default:null}}}}),X8s.extend({addAttributes(){var g;return{...(g=this.parent)==null?void 0:g.call(this),style:{default:null},width:{default:null},colspan:{default:1},rowspan:{default:1},valign:{default:null}}}}),Q8s.extend({addAttributes(){var g;return{...(g=this.parent)==null?void 0:g.call(this),style:{default:null},width:{default:null},colspan:{default:1},rowspan:{default:1}}}})],content:s,onUpdate:({editor:g})=>{t(g.getHTML())},editorProps:{attributes:{class:"outline-none","data-placeholder":n},handlePaste:(g,y)=>{var v;const b=(v=y.clipboardData)==null?void 0:v.items;if(!b)return!1;for(const N of Array.from(b))if(N.type.startsWith("image/")){y.preventDefault();const C=N.getAsFile();if(!C)continue;const A=new FileReader;return A.onload=T=>{var M;const P=(M=T.target)==null?void 0:M.result;g.dispatch(g.state.tr.replaceSelectionWith(g.state.schema.nodes.image.create({src:P})))},A.readAsDataURL(C),!0}return!1}}});j.useEffect(()=>{h&&s!==h.getHTML()&&h.commands.setContent(s)},[s,h]);const m=()=>{if(!h)return;const g=h.getAttributes("link").href||"",y=h.getAttributes("link").target;c(g),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(""))},x=()=>{h&&h.chain().focus().extendMarkRange("link").unsetLink().run()};return h?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"border rounded-lg overflow-hidden",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-0.5 p-2 border-b bg-muted/30",children:[e.jsx($,{type:"button",variant:"ghost",size:"sm",onClick:()=>h.chain().focus().toggleHeading({level:1}).run(),className:h.isActive("heading",{level:1})?"bg-muted":"",title:"Heading 1",children:e.jsx(_z,{className:"h-4 w-4"})}),e.jsx($,{type:"button",variant:"ghost",size:"sm",onClick:()=>h.chain().focus().toggleHeading({level:2}).run(),className:h.isActive("heading",{level:2})?"bg-muted":"",title:"Heading 2",children:e.jsx(wz,{className:"h-4 w-4"})}),e.jsx("div",{className:"w-px h-6 bg-border mx-1"}),e.jsx($,{type:"button",variant:"ghost",size:"sm",onClick:()=>h.chain().focus().toggleBold().run(),className:h.isActive("bold")?"bg-muted":"",title:"Bold",children:e.jsx(pT,{className:"h-4 w-4"})}),e.jsx($,{type:"button",variant:"ghost",size:"sm",onClick:()=>h.chain().focus().toggleItalic().run(),className:h.isActive("italic")?"bg-muted":"",title:"Italic",children:e.jsx(_T,{className:"h-4 w-4"})}),e.jsx("div",{className:"w-px h-6 bg-border mx-1"}),e.jsx($,{type:"button",variant:"ghost",size:"sm",onClick:()=>h.chain().focus().toggleBulletList().run(),className:h.isActive("bulletList")?"bg-muted":"",title:"Bullet List",children:e.jsx(Sg,{className:"h-4 w-4"})}),e.jsx($,{type:"button",variant:"ghost",size:"sm",onClick:()=>h.chain().focus().toggleOrderedList().run(),className:h.isActive("orderedList")?"bg-muted":"",title:"Numbered List",children:e.jsx(qj,{className:"h-4 w-4"})}),e.jsx("div",{className:"w-px h-6 bg-border mx-1"}),e.jsx($,{type:"button",variant:"ghost",size:"sm",onClick:()=>h.chain().focus().setTextAlign("left").run(),className:h.isActive({textAlign:"left"})?"bg-muted":"",title:"Align Left",children:e.jsx(iR,{className:"h-4 w-4"})}),e.jsx($,{type:"button",variant:"ghost",size:"sm",onClick:()=>h.chain().focus().setTextAlign("center").run(),className:h.isActive({textAlign:"center"})?"bg-muted":"",title:"Align Center",children:e.jsx(aR,{className:"h-4 w-4"})}),e.jsx($,{type:"button",variant:"ghost",size:"sm",onClick:()=>h.chain().focus().setTextAlign("right").run(),className:h.isActive({textAlign:"right"})?"bg-muted":"",title:"Align Right",children:e.jsx(oR,{className:"h-4 w-4"})}),e.jsx("div",{className:"w-px h-6 bg-border mx-1"}),e.jsx($,{type:"button",variant:"ghost",size:"sm",onClick:m,className:h.isActive("link")?"bg-muted":"",title:"Add Link",children:e.jsx(kc,{className:"h-4 w-4"})}),h.isActive("link")&&e.jsx($,{type:"button",variant:"ghost",size:"sm",onClick:x,title:"Remove Link",children:e.jsx(kc,{className:"h-4 w-4"})}),e.jsx("div",{className:"w-px h-6 bg-border mx-1"}),e.jsx($,{type:"button",variant:"ghost",size:"sm",onClick:()=>h.chain().focus().undo().run(),disabled:!h.can().undo(),title:"Undo",children:e.jsx(PT,{className:"h-4 w-4"})}),e.jsx($,{type:"button",variant:"ghost",size:"sm",onClick:()=>h.chain().focus().redo().run(),disabled:!h.can().redo(),title:"Redo",children:e.jsx(ET,{className:"h-4 w-4"})})]}),e.jsx(VGe,{editor:h,className:"prose prose-sm max-w-none p-3 focus:outline-none [&_.ProseMirror]:outline-none [&_.ProseMirror_img]:max-w-none [&_.ProseMirror_table]:border-none [&_.ProseMirror_table]:border-collapse [&_.ProseMirror_td]:border-none [&_.ProseMirror_td]:p-0 [&_.ProseMirror_td]:align-top [&_.ProseMirror_th]:border-none [&_.ProseMirror_th]:p-0 [&_.ProseMirror_tr]:border-none",style:{minHeight:r}})]}),e.jsx(Os,{open:i,onOpenChange:l,children:e.jsxs(Rs,{className:"sm:max-w-md",children:[e.jsx(Us,{children:e.jsx(zs,{children:"Insert Link"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"link-url",children:"URL"}),e.jsx(be,{id:"link-url",value:o,onChange:g=>c(g.target.value),placeholder:"https://example.com"})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(Tn,{id:"link-new-tab",checked:d,onCheckedChange:u}),e.jsx(se,{htmlFor:"link-new-tab",children:"Open in new tab"})]})]}),e.jsxs(kr,{children:[e.jsx($,{type:"button",variant:"outline",onClick:()=>l(!1),children:"Cancel"}),e.jsx($,{type:"button",onClick:p,children:o?"Apply Link":"Remove Link"})]})]})})]}):null}var J8s=Object.defineProperty,eDs=(s,t,n)=>t in s?J8s(s,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):s[t]=n,Km=(s,t,n)=>eDs(s,typeof t!="symbol"?t+"":t,n);const GSe={x:0,y:0,width:0,height:0,unit:"px"},j7=(s,t,n)=>Math.min(Math.max(s,t),n),tDs=(...s)=>s.filter(t=>t&&typeof t=="string").join(" "),zct=(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 sDs(s,t,n,r){const a=nS(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==="%"?UA(a,n,r):a}function nDs(s,t,n){const r=nS(s,t,n);return r.x=(t-r.width)/2,r.y=(n-r.height)/2,s.unit==="%"?UA(r,t,n):r}function UA(s,t,n){return s.unit==="%"?{...GSe,...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 nS(s,t,n){return s.unit?s.unit==="px"?{...GSe,...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}:{...GSe,...s,unit:"px"}}function Bct(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 x=r-(d.x+d.width);x<0&&(d.x=Math.min(d.x,r-u),d.width+=x);const g=a-(d.y+d.height);if(g<0&&(d.y=Math.min(d.y,a-h),d.height+=g),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 b=Math.max(d.height*t,u);(n==="sw"||n=="nw")&&(d.x-=b-d.width),d.width=b}}return d}function rDs(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 N7={capture:!0,passive:!1};let aDs=0;const CA=class G2 extends j.PureComponent{constructor(){super(...arguments),Km(this,"docMoveBound",!1),Km(this,"mouseDownOnCrop",!1),Km(this,"dragStarted",!1),Km(this,"evData",{startClientX:0,startClientY:0,startCropX:0,startCropY:0,clientX:0,clientY:0,isResize:!0}),Km(this,"componentRef",j.createRef()),Km(this,"mediaRef",j.createRef()),Km(this,"resizeObserver"),Km(this,"initChangeCalled",!1),Km(this,"instanceId",`rc-${aDs++}`),Km(this,"state",{cropIsActive:!1,newCropIsBeingDrawn:!1}),Km(this,"onCropPointerDown",t=>{const{crop:n,disabled:r}=this.props,a=this.getBox();if(!n)return;const i=nS(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 x=0,g=0;l==="ne"||l=="e"?(x=m-(i.x+i.width),g=p-i.y,u=i.x,h=i.y+i.height):l==="se"||l==="s"?(x=m-(i.x+i.width),g=p-(i.y+i.height),u=i.x,h=i.y):l==="sw"||l=="w"?(x=m-i.x,g=p-(i.y+i.height),u=i.x+i.width,h=i.y):(l==="nw"||l=="n")&&(x=m-i.x,g=p-i.y,u=i.x+i.width,h=i.y+i.height),c=u+a.x+x,d=h+a.y+g}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})}),Km(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(nS(u,o.width,o.height),UA(u,o.width,o.height)),this.setState({cropIsActive:!0,newCropIsBeingDrawn:!0})}),Km(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(),zct(n,c)||a(nS(c,l.width,l.height),UA(c,l.width,l.height))}),Km(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)?G2.nudgeStepLarge:t.shiftKey?G2.nudgeStepMedium:G2.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=j7(d.x,0,c.width-d.width),d.y=j7(d.y,0,c.height-d.height);const h=nS(d,c.width,c.height),m=UA(d,c.width,c.height);a(h,m),i&&i(h,m)}}),Km(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)?G2.nudgeStepLarge:t.shiftKey?G2.nudgeStepMedium:G2.nudgeStep,x=nS(a,m.width,m.height),g=rDs(x,t.key,p,n),y=Bct(g,r,n,m.width,m.height,l,o,c,d);if(!zct(a,y)){const b=UA(y,m.width,m.height);u(y,b),h&&h(y,b)}}),Km(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(nS(n,l.width,l.height),UA(n,l.width,l.height)),this.setState({cropIsActive:!1,newCropIsBeingDrawn:!1}))}),Km(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(nS(n,a,i),UA(n,a,i))}}componentWillUnmount(){this.resizeObserver&&this.resizeObserver.disconnect(),this.unbindDocMove()}bindDocMove(){this.docMoveBound||(this.document.addEventListener("pointermove",this.onDocPointerMove,N7),this.document.addEventListener("pointerup",this.onDocPointerDone,N7),this.document.addEventListener("pointercancel",this.onDocPointerDone,N7),this.docMoveBound=!0)}unbindDocMove(){this.docMoveBound&&(this.document.removeEventListener("pointermove",this.onDocPointerMove,N7),this.document.removeEventListener("pointerup",this.onDocPointerDone,N7),this.document.removeEventListener("pointercancel",this.onDocPointerDone,N7),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=j7(t.startCropX+a,0,n.width-r.width),r.y=j7(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 x=Bct(p,n,d,i.width,i.height,l,o,r,a);return n||G2.xyOrds.indexOf(u)>-1?c=x:G2.xOrds.indexOf(u)>-1?(c.x=x.x,c.width=x.width):G2.yOrds.indexOf(u)>-1&&(c.y=x.y,c.height=x.height),c.x=j7(c.x,0,i.width-c.width),c.y=j7(c.y,0,i.height-c.height),c}renderCropSelection(){const{ariaLabels:t=G2.defaultProps.ariaLabels,disabled:n,locked:r,renderSelectionAddon:a,ruleOfThirds:i,crop:l}=this.props,o=this.getCropStyle();if(l)return It.createElement("div",{style:o,className:"ReactCrop__crop-selection",onPointerDown:this.onCropPointerDown,"aria-label":t.cropArea,tabIndex:0,onKeyDown:this.onComponentKeyDown,role:"group"},!n&&!r&&It.createElement("div",{className:"ReactCrop__drag-elements",onFocus:this.onDragFocus},It.createElement("div",{className:"ReactCrop__drag-bar ord-n","data-ord":"n"}),It.createElement("div",{className:"ReactCrop__drag-bar ord-e","data-ord":"e"}),It.createElement("div",{className:"ReactCrop__drag-bar ord-s","data-ord":"s"}),It.createElement("div",{className:"ReactCrop__drag-bar ord-w","data-ord":"w"}),It.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"}),It.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"}),It.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"}),It.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"}),It.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"}),It.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"}),It.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"}),It.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&&It.createElement("div",{className:"ReactCrop__selection-addon",onPointerDown:c=>c.stopPropagation()},a(this.state)),i&&It.createElement(It.Fragment,null,It.createElement("div",{className:"ReactCrop__rule-of-thirds-hz"}),It.createElement("div",{className:"ReactCrop__rule-of-thirds-vt"})))}makePixelCrop(t){const n={...GSe,...this.props.crop||{}};return nS(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=tDs("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 It.createElement("div",{ref:this.componentRef,className:p,style:c},It.createElement("div",{ref:this.mediaRef,className:"ReactCrop__child-wrapper",onPointerDown:this.onComponentPointerDown},n),i?It.createElement("svg",{className:"ReactCrop__crop-mask",width:"100%",height:"100%"},It.createElement("defs",null,It.createElement("mask",{id:`hole-${this.instanceId}`},It.createElement("rect",{width:"100%",height:"100%",fill:"white"}),r?It.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"}):It.createElement("rect",{x:`${i.x}${i.unit}`,y:`${i.y}${i.unit}`,width:`${i.width}${i.unit}`,height:`${i.height}${i.unit}`,fill:"black"}))),It.createElement("rect",{fill:"black",fillOpacity:.5,width:"100%",height:"100%",mask:`url(#hole-${this.instanceId})`})):void 0,m)}};Km(CA,"xOrds",["e","w"]),Km(CA,"yOrds",["n","s"]),Km(CA,"xyOrds",["nw","ne","se","sw"]),Km(CA,"nudgeStep",1),Km(CA,"nudgeStepMedium",10),Km(CA,"nudgeStepLarge",100),Km(CA,"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 iDs=CA;function oDs(s,t,n){return nDs(sDs({unit:"%",width:90},n,s,t),s,t)}const lWe=({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),x=j.useCallback(b=>{const{width:v,height:N}=b.currentTarget;o(oDs(v,N,a))},[a]),g=j.useCallback(async()=>{const b=i.current;if(!b||!c)return;const v=document.createElement("canvas"),N=v.getContext("2d");if(!N)return;const C=b.naturalWidth/b.width,A=b.naturalHeight/b.height,T=400;v.width=T,v.height=T,N.imageSmoothingQuality="high";const P=c.x*C,M=c.y*A,I=c.width*C,D=c.height*A,B=m*Math.PI/180,q=v.width/2,W=v.height/2;return N.save(),N.translate(q,W),N.rotate(B),N.scale(u,u),N.translate(-q,-W),N.drawImage(b,P,M,I,D,0,0,T,T),N.restore(),new Promise((V,K)=>{v.toBlob(Q=>{Q?V(Q):K(new Error("Canvas is empty"))},"image/jpeg",.95)})},[c,u,m]),y=async()=>{try{const b=await g();b&&(r(b),t())}catch(b){console.error("Error cropping image:",b)}};return e.jsx(Os,{open:s,onOpenChange:t,children:e.jsxs(Rs,{className:"max-w-lg",children:[e.jsx(Us,{children:e.jsx(zs,{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(iDs,{crop:l,onChange:(b,v)=>o(v),onComplete:b=>d(b),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:x})})}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(Wz,{className:"h-4 w-4 text-muted-foreground"}),e.jsx(rx,{value:[u],min:.5,max:3,step:.1,onValueChange:([b])=>h(b),className:"flex-1"}),e.jsx(IT,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(jR,{className:"h-4 w-4 text-muted-foreground"}),e.jsx(rx,{value:[m],min:-180,max:180,step:1,onValueChange:([b])=>p(b),className:"flex-1"}),e.jsxs("span",{className:"text-sm text-muted-foreground w-12",children:[m,"°"]})]})]})]}),e.jsxs(kr,{children:[e.jsx($,{variant:"outline",onClick:t,children:"Cancel"}),e.jsx($,{onClick:y,children:"Save Photo"})]})]})})},$ct="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 lDs(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 cDs(){const{user:s}=_s(),{toast:t}=gi(),[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),[x,g]=j.useState(!1);j.useEffect(()=>{s!=null&&s.id&&(async()=>{const{data:v}=await U.from("profiles").select("phone, phone_e164, sms_consent, sms_consent_at").eq("id",s.id).maybeSingle(),N=v;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 v=lDs(l);if(!v){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 U.from("profiles").update({phone_e164:v,sms_consent:!0,sms_consent_at:new Date().toISOString(),sms_consent_text:$ct,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."})},b=async()=>{i(!0);const{error:v}=await U.from("profiles").update({sms_consent:!1,sms_opted_out_at:new Date().toISOString()}).eq("id",s.id);if(i(!1),v){t({title:"Error",description:v.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(_e,{children:[e.jsxs(Bt,{children:[e.jsxs(Ut,{className:"flex items-center gap-2",children:[e.jsx(Ji,{className:"h-5 w-5"}),"Text Message (SMS) Alerts",u&&e.jsx($e,{variant:"secondary",children:"Opted in"})]}),e.jsx(vr,{children:"Get a text the moment a new lead comes in, plus important account notifications."})]}),e.jsx(Oe,{className:"space-y-4",children:n?e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(Ht,{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(se,{htmlFor:"sms-mobile",children:"Mobile Number (optional)"}),e.jsx(be,{id:"sms-mobile",type:"tel",value:l,onChange:v=>o(v.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(ui,{id:"sms-consent",checked:c,onCheckedChange:v=>d(v===!0),disabled:u,className:"mt-0.5"}),e.jsx(se,{htmlFor:"sms-consent",className:"text-sm font-normal leading-relaxed cursor-pointer",children:$ct})]})}),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"}),"."]}),x&&!u&&e.jsx("p",{className:"text-xs text-muted-foreground",children:"You chose not to enroll in text alerts. Nothing was saved and your account is unaffected."}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs($,{onClick:y,disabled:a||u&&!l,children:[a&&e.jsx(Ht,{className:"mr-2 h-4 w-4 animate-spin"}),u?"Update Number":"Opt in to SMS"]}),u?e.jsx($,{variant:"outline",onClick:b,disabled:a,children:"Opt out"}):e.jsx($,{variant:"outline",type:"button",disabled:a,onClick:()=>{o(""),d(!1),g(!0),t({title:"SMS skipped",description:"No consent was recorded. You can keep using LevelUp normally."})},children:"Skip SMS / Continue without text alerts"})]})]})})]})}const Uct="#2a4c64",qct="#B8965A",Vct="Inter",Hct="Inter";function p9(s){if(typeof s!="string")return null;const t=s.trim();return t.length?t:null}function J1(s,t=null){for(const[n,r]of s){const a=p9(r);if(a)return{value:a,source:n}}return{value:t,source:"default"}}function dDs(s){const t=s.agent??{},n=s.brokerage??{},r=s.legacy??{},a=!!n.lock_colors,i=!!n.lock_logo,l=(T,P,M)=>a?[["brokerage",P],["agent",T],["legacy",M]]:[["agent",T],["brokerage",P],["legacy",M]],o=J1(l(t.brand_color,n.primary_color,r.brand_color),Uct),c=J1(l(t.accent_color,n.accent_color,r.accent_color),qct),d=J1([["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=J1(u),m=J1([["brokerage",n.logo_url],["legacy",r.brokerage_logo_url]]),p=J1([["agent",t.headshot_url],["legacy",r.avatar_url]]),x=J1([["agent",t.tagline],["legacy",r.tagline||r.title]]),g=J1([["agent",t.preferred_font],["brokerage",n.heading_font]],Vct),y=J1([["brokerage",n.body_font]],Hct),b=J1([["agent",t.license_number],["legacy",r.license_number]]),v=J1([["agent",t.license_state],["legacy",r.license_state],["brokerage",n.license_state]]),N=J1([["agent",t.website_url],["legacy",r.website_url]]),C=J1([["brokerage",n.legal_name],["legacy",r.brokerage_name]]),A=J1([["brokerage",n.compliance_line]]);return{agent_name:p9(r.name),brokerage_name:C.value,brand_color:o.value??Uct,secondary_color:d.value,accent_color:c.value??qct,heading_font:g.value??Vct,body_font:y.value??Hct,logo_url:h.value,logo_dark_url:p9(n.logo_dark_url),brokerage_logo_url:m.value,icon_mark_url:p9(n.icon_mark_url),headshot_url:p.value,tagline:x.value,license_number:b.value,license_state:v.value,website_url:N.value,email:p9(r.email),phone:p9(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:x.source,heading_font:g.source,body_font:y.source,license_number:b.source,license_state:v.source,website_url:N.source,brokerage_name:C.source,compliance_line:A.source}}}function uDs(){const{user:s}=_s();return ht({queryKey:["agent-brand-profile",s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await U.from("agent_brand_profiles").select("*").eq("user_id",s.id).maybeSingle();if(n)throw n;return t??null}})}function hDs(){const{user:s}=_s(),t=ts();return yt({mutationFn:async n=>{if(!s)throw new Error("Not signed in");const{data:r,error:a}=await U.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 mDs(s){return ht({queryKey:["brokerage-brand-profile",s],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await U.from("brokerage_brand_profiles").select("*").eq("brokerage_id",s).maybeSingle();if(n)throw n;return t??null}})}function pDs(s){const{user:t}=_s(),n=ts();return yt({mutationFn:async r=>{if(!s)throw new Error("No brokerage selected");const{data:a,error:i}=await U.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 fDs(){const{user:s}=_s();return ht({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([U.from("profiles").select("name, email, phone, avatar_url, website_url, title, brokerage_name, brokerage_id").eq("id",t).maybeSingle(),U.from("agent_brand_profiles").select("*").eq("user_id",t).maybeSingle(),U.from("agent_cards").select("brokerage_display_name, brokerage_logo_url, team_logo_url, display_email, title, positioning_statement").eq("user_id",t).maybeSingle(),U.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,x]=await Promise.all([U.from("brokerage_brand_profiles").select("*").eq("brokerage_id",l.brokerage_id).maybeSingle(),U.from("brokerages").select("name").eq("id",l.brokerage_id).maybeSingle()]);u=p.data??null,h=((m=x.data)==null?void 0:m.name)??null}return dDs({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 VLt(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 U.storage.from("card-logos").upload(a,t,{upsert:!0,cacheControl:"3600"});if(i)throw i;return U.storage.from("card-logos").getPublicUrl(a).data.publicUrl}const xDs=["Inter","Playfair Display","Montserrat","Poppins","Lora","Work Sans"];function gDs(){const{user:s}=_s(),{toast:t}=gi(),{data:n,isLoading:r}=uDs(),{data:a}=fDs(),i=hDs(),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,b)=>u(v=>({...v,[y]:b})),x=async y=>{if(s){c(!0);try{const b=await VLt(s.id,y,"logo");p("logo_url",b),t({title:"Logo uploaded"})}catch(b){t({title:"Upload failed",description:b.message,variant:"destructive"})}finally{c(!1)}}},g=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(_e,{children:[e.jsxs(Bt,{children:[e.jsxs(Ut,{className:"flex items-center gap-2",children:[e.jsx(Rc,{className:"h-5 w-5"}),"Brand Kit"]}),e.jsx(vr,{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(Oe,{className:"space-y-6",children:r?e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground text-sm",children:[e.jsx(Ht,{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(se,{className:"flex items-center gap-2",children:["Brand color",h&&e.jsxs($e,{variant:"secondary",className:"gap-1",children:[e.jsx(Ad,{className:"h-3 w-3"})," Set by brokerage"]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(be,{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(be,{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(se,{children:"Accent color"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(be,{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(be,{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(se,{className:"flex items-center gap-2",children:["Personal / team logo",m&&e.jsxs($e,{variant:"secondary",className:"gap-1",children:[e.jsx(Ad,{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 b;return((b=y.target.files)==null?void 0:b[0])&&x(y.target.files[0])}}),e.jsxs($,{type:"button",variant:"outline",disabled:o||m,onClick:()=>{var y;return(y=l.current)==null?void 0:y.click()},children:[o?e.jsx(Ht,{className:"h-4 w-4 animate-spin"}):e.jsx(si,{className:"h-4 w-4"}),e.jsx("span",{className:"ml-2",children:"Upload logo"})]}),d.logo_url&&e.jsx($,{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(se,{htmlFor:"brand-tagline",children:"Tagline"}),e.jsx(be,{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(se,{htmlFor:"brand-font",children:"Preferred font"}),e.jsx(be,{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:xDs.map(y=>e.jsx("option",{value:y},y))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"brand-license",children:"License number"}),e.jsx(be,{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(se,{htmlFor:"brand-license-state",children:"License state"}),e.jsx(be,{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(se,{htmlFor:"brand-website",children:"Website"}),e.jsx(be,{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($,{onClick:g,disabled:i.isPending,children:[i.isPending?e.jsx(Ht,{className:"mr-2 h-4 w-4 animate-spin"}):e.jsx(Jo,{className:"mr-2 h-4 w-4"}),"Save brand kit"]})]})})]})}const yDs=()=>{const{user:s}=_s(),{toast:t}=gi(),[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 U.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 U.auth.getSession();if(!h)throw new Error("Not authenticated");const{data:m,error:p}=await U.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($e,{className:"bg-amber-500",children:"Grandfathered"});switch(l==null?void 0:l.status){case"active":return e.jsx($e,{className:"bg-green-500",children:"Active"});case"trialing":return e.jsx($e,{className:"bg-blue-500",children:"Trial"});case"past_due":return e.jsx($e,{variant:"destructive",children:"Past Due"});case"canceled":return e.jsx($e,{variant:"secondary",children:"Canceled"});default:return e.jsx($e,{variant:"outline",children:"No Subscription"})}};return n?e.jsxs(_e,{children:[e.jsx(Bt,{children:e.jsxs(Ut,{className:"flex items-center gap-2",children:[e.jsx(yy,{className:"h-5 w-5"}),"Subscription"]})}),e.jsx(Oe,{children:e.jsx("div",{className:"flex items-center justify-center py-4",children:e.jsx(Ht,{className:"h-6 w-6 animate-spin text-muted-foreground"})})})]}):e.jsxs(_e,{children:[e.jsxs(Bt,{children:[e.jsxs(Ut,{className:"flex items-center gap-2",children:[e.jsx(yy,{className:"h-5 w-5"}),"Subscription"]}),e.jsx(vr,{children:"Manage your subscription and billing"})]}),e.jsxs(Oe,{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:"Status"}),e.jsx("div",{className:"mt-1",children: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($,{onClick:d,variant:"outline",disabled:a,children:[a?e.jsx(Ht,{className:"mr-2 h-4 w-4 animate-spin"}):e.jsx(Tr,{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."})]})]})},vDs=()=>{const{user:s}=_s(),t=Vn(),{toast:n}=gi(),[r]=oc(),a=r.get("setup")==="true",i=r.get("reset")==="true",{isSupported:l,isSubscribed:o,isLoading:c,subscribe:d,unsubscribe:u}=YCt(),[h,m]=j.useState(!1),[p,x]=j.useState(""),[g,y]=j.useState(!1),[b,v]=j.useState(!1),[N,C]=j.useState(""),[A,T]=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}),[P,M]=j.useState(!1),[I,D]=j.useState(!1),[B,q]=j.useState(!1),[W,V]=j.useState(!1),[K,Q]=j.useState(!1),[J,ce]=j.useState({newPassword:"",confirmPassword:""});j.useEffect(()=>{s&&ue()},[s]),j.useEffect(()=>{i&&s&&setTimeout(()=>{var ve;(ve=document.getElementById("change-password-section"))==null||ve.scrollIntoView({behavior:"smooth",block:"center"})},500)},[i,s]);const ue=async()=>{var ve,ge,fe,je;if(!(s!=null&&s.id)){console.log("No user ID available yet");return}try{console.log("Loading profile for user:",s.id);const{data:Ee,error:Me}=await U.from("profiles").select("name, email, phone, digest_opt_out, event_invite_opt_out, title, bio, areas_served, years_experience, brokerage_id, brokerage_name, instagram_url, facebook_url, linkedin_url, email_signature, use_email_signature, brokerages(name)").eq("id",s.id).maybeSingle();if(Me)throw console.error("Profile query error:",Me),Me;if(Ee){console.log("Profile loaded successfully:",Ee);const ze=((ve=Ee.brokerages)==null?void 0:ve.name)||"";M(!!Ee.brokerage_id),T({name:Ee.name||"",email:Ee.email||"",phone:Ee.phone||"",title:Ee.title||"",bio:Ee.bio||"",areas_served:Ee.areas_served||"",years_experience:((ge=Ee.years_experience)==null?void 0:ge.toString())||"",brokerage_name:Ee.brokerage_id?ze:Ee.brokerage_name||"",instagram_url:Ee.instagram_url||"",facebook_url:Ee.facebook_url||"",linkedin_url:Ee.linkedin_url||"",email_signature:Ee.email_signature||"",use_email_signature:Ee.use_email_signature||!1}),D(Ee.digest_opt_out||!1),V(Ee.event_invite_opt_out||!1)}else console.warn("No profile found for user"),T({name:((fe=s.user_metadata)==null?void 0:fe.name)||((je=s.email)==null?void 0:je.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:De}=await U.storage.from("avatars").list(`${s.id}`);if(De&&De.length>0){const{data:ze}=U.storage.from("avatars").getPublicUrl(`${s.id}/${De[0].name}`);x(ze.publicUrl)}}catch(Ee){console.error("Error loading profile:",Ee),n({title:"Error",description:Ee.message||"Failed to load profile",variant:"destructive"})}},ne=ve=>{var je;const ge=(je=ve.target.files)==null?void 0:je[0];if(!ge)return;const fe=new FileReader;fe.onloadend=()=>{C(fe.result),v(!0)},fe.readAsDataURL(ge),ve.target.value=""},ee=async ve=>{if(s){y(!0);try{const{data:ge}=await U.storage.from("avatars").list(`${s.id}`);ge&&ge.length>0&&await U.storage.from("avatars").remove(ge.map(ze=>`${s.id}/${ze.name}`));const je=`${s.id}/avatar.jpg`,{error:Ee}=await U.storage.from("avatars").upload(je,ve,{upsert:!0,contentType:"image/jpeg"});if(Ee)throw Ee;const{data:Me}=U.storage.from("avatars").getPublicUrl(je),De=Me.publicUrl;x(`${De}?t=${Date.now()}`),await U.from("profiles").update({avatar_url:De}).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{y(!1)}}},le=async()=>{if(!A.name.trim()||!A.email.trim()){n({title:"Error",description:"Name and email are required",variant:"destructive"});return}m(!0);try{const{error:ve}=await U.from("profiles").update({name:A.name.trim(),email:A.email.trim(),phone:A.phone.trim()||null,title:A.title.trim()||null,bio:A.bio.trim()||null,areas_served:A.areas_served.trim()||null,years_experience:A.years_experience?parseInt(A.years_experience):null,...P?{}:{brokerage_name:A.brokerage_name.trim()||null},instagram_url:A.instagram_url.trim()||null,facebook_url:A.facebook_url.trim()||null,linkedin_url:A.linkedin_url.trim()||null,email_signature:A.email_signature||"",use_email_signature:A.use_email_signature}).eq("id",s==null?void 0:s.id);if(ve)throw ve;n({title:"Success",description:"Profile updated successfully"})}catch(ve){console.error("Error updating profile:",ve),n({title:"Error",description:ve.message||"Failed to update profile",variant:"destructive"})}finally{m(!1)}},he=async()=>{if(!J.newPassword){n({title:"Error",description:"Please enter a new password",variant:"destructive"});return}if(J.newPassword.length<6){n({title:"Error",description:"Password must be at least 6 characters",variant:"destructive"});return}if(J.newPassword!==J.confirmPassword){n({title:"Error",description:"Passwords do not match",variant:"destructive"});return}m(!0);try{const{error:ve}=await U.auth.updateUser({password:J.newPassword});if(ve)throw ve;n({title:"Success",description:"Password updated successfully"}),ce({newPassword:"",confirmPassword:""}),a&&setTimeout(()=>t("/dashboard"),1e3)}catch(ve){console.error("Error updating password:",ve),n({title:"Error",description:ve.message||"Failed to update password",variant:"destructive"})}finally{m(!1)}};return e.jsx(Ks,{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($,{variant:"outline",onClick:()=>{var ve;(ve=document.getElementById("change-password-section"))==null||ve.scrollIntoView({behavior:"smooth",block:"center"})},className:"gap-2",children:[e.jsx(q3,{className:"h-4 w-4"}),"Change Password"]})}),e.jsxs("div",{className:"space-y-6",children:[e.jsxs(_e,{children:[e.jsxs(Bt,{children:[e.jsx(Ut,{children:"Profile Photo"}),e.jsx(vr,{children:"Upload a professional photo for your profile"})]}),e.jsxs(Oe,{className:"flex items-center gap-6",children:[e.jsxs(Ea,{className:"h-24 w-24",children:[e.jsx(ki,{src:p}),e.jsx(Ta,{className:"text-2xl",children:A.name.split(" ").map(ve=>ve[0]).join("").toUpperCase()||"U"})]}),e.jsxs("div",{className:"flex-1",children:[e.jsx("input",{type:"file",id:"avatar-upload",accept:"image/*",className:"hidden",onChange:ne,disabled:g}),e.jsxs($,{variant:"outline",onClick:()=>{var ve;return(ve=document.getElementById("avatar-upload"))==null?void 0:ve.click()},disabled:g,children:[e.jsx(si,{className:"mr-2 h-4 w-4"}),g?"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(_e,{children:[e.jsxs(Bt,{children:[e.jsx(Ut,{children:"Personal Information"}),e.jsx(vr,{children:"Update your profile details"})]}),e.jsxs(Oe,{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"name",children:"Name"}),e.jsx(be,{id:"name",value:A.name,onChange:ve=>T({...A,name:ve.target.value}),maxLength:100})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"email",children:"Email"}),e.jsx(be,{id:"email",type:"email",value:A.email,onChange:ve=>T({...A,email:ve.target.value}),maxLength:255})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"phone",children:"Phone Number"}),e.jsx(be,{id:"phone",type:"tel",value:A.phone,onChange:ve=>T({...A,phone:ve.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(se,{htmlFor:"title",children:"Job Title"}),e.jsx(be,{id:"title",value:A.title,onChange:ve=>T({...A,title:ve.target.value}),placeholder:"e.g., Broker Associate, Team Lead",maxLength:100})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"bio",children:"Bio"}),e.jsx(Is,{id:"bio",value:A.bio,onChange:ve=>T({...A,bio:ve.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(se,{htmlFor:"areas_served",children:"Areas Served"}),e.jsx(be,{id:"areas_served",value:A.areas_served,onChange:ve=>T({...A,areas_served:ve.target.value}),placeholder:"e.g., Downtown, Suburbs"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"years_experience",children:"Years Experience"}),e.jsx(be,{id:"years_experience",type:"number",min:"0",value:A.years_experience,onChange:ve=>T({...A,years_experience:ve.target.value}),placeholder:"e.g., 5"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(se,{htmlFor:"brokerage_name",children:["Brokerage ",P&&e.jsx("span",{className:"text-xs text-muted-foreground",children:"(managed)"})]}),e.jsx(be,{id:"brokerage_name",value:A.brokerage_name,onChange:ve=>T({...A,brokerage_name:ve.target.value}),placeholder:"e.g., Keller Williams Realty",disabled:P,maxLength:150}),e.jsx("p",{className:"text-xs text-muted-foreground",children:P?"Your brokerage is managed by your office and can't be changed here.":"Used as your brokerage name across ReelFlow, branding, and email signatures."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Social Links"}),e.jsxs("div",{className:"grid grid-cols-1 gap-3",children:[e.jsx(be,{value:A.linkedin_url,onChange:ve=>T({...A,linkedin_url:ve.target.value}),placeholder:"LinkedIn URL"}),e.jsx(be,{value:A.instagram_url,onChange:ve=>T({...A,instagram_url:ve.target.value}),placeholder:"Instagram URL"}),e.jsx(be,{value:A.facebook_url,onChange:ve=>T({...A,facebook_url:ve.target.value}),placeholder:"Facebook URL"})]})]}),e.jsxs($,{onClick:le,disabled:h,children:[e.jsx(Jo,{className:"mr-2 h-4 w-4"}),"Save Changes"]})]})]}),e.jsxs(_e,{children:[e.jsxs(Bt,{children:[e.jsxs(Ut,{className:"flex items-center gap-2",children:[e.jsx(wN,{className:"h-5 w-5"}),"Email Signature"]}),e.jsx(vr,{children:"Add a signature that will be appended to emails sent via Gmail"})]}),e.jsxs(Oe,{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:"Use email signature in all emails"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:A.use_email_signature?"Your signature will be added to every email sent via Gmail":"Signature is currently disabled"})]}),e.jsx(Tn,{checked:A.use_email_signature,onCheckedChange:ve=>T({...A,use_email_signature:ve})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Signature"}),e.jsx(m2,{content:A.email_signature,onChange:ve=>T({...A,email_signature:ve}),placeholder:"Paste your Gmail signature here or create one...",minHeight:"120px",compact:!0}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Tip: Copy your signature from Gmail Settings and paste it here — images and formatting will be preserved."})]}),e.jsxs($,{onClick:le,disabled:h,children:[e.jsx(Jo,{className:"mr-2 h-4 w-4"}),"Save Signature"]})]})]}),e.jsx(gDs,{}),e.jsxs(_e,{id:"change-password-section",children:[e.jsxs(Bt,{children:[e.jsx(Ut,{children:a?"Set Your Password":"Change Password"}),e.jsx(vr,{children:a?"Create a secure password for your account":"Update your password to keep your account secure"})]}),e.jsxs(Oe,{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"newPassword",children:"New Password"}),e.jsx(be,{id:"newPassword",type:"password",value:J.newPassword,onChange:ve=>ce({...J,newPassword:ve.target.value}),placeholder:"Min 6 characters"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"confirmPassword",children:"Confirm Password"}),e.jsx(be,{id:"confirmPassword",type:"password",value:J.confirmPassword,onChange:ve=>ce({...J,confirmPassword:ve.target.value}),placeholder:"Re-enter your new password"})]}),e.jsxs($,{onClick:he,disabled:h,children:[e.jsx(Jo,{className:"mr-2 h-4 w-4"}),a?"Complete Setup":"Update Password"]}),a&&e.jsx($,{variant:"outline",onClick:()=>t("/dashboard"),className:"ml-2",children:"Skip for Now"})]})]}),e.jsxs(_e,{children:[e.jsxs(Bt,{children:[e.jsxs(Ut,{className:"flex items-center gap-2",children:[o?e.jsx(Dx,{className:"h-5 w-5"}):e.jsx(e5,{className:"h-5 w-5"}),"Push Notifications"]}),e.jsx(vr,{children:"Receive browser notifications when new content is added"})]}),e.jsx(Oe,{children:l?e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:o?"Notifications enabled":"Notifications disabled"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:o?"You'll receive notifications about new templates, videos, and events":"Enable to get notified about new content"})]}),e.jsx(Tn,{checked:o,onCheckedChange:ve=>{ve?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(cDs,{}),e.jsxs(_e,{children:[e.jsxs(Bt,{children:[e.jsxs(Ut,{className:"flex items-center gap-2",children:[I?e.jsx(wT,{className:"h-5 w-5"}):e.jsx(nn,{className:"h-5 w-5"}),"Email Preferences"]}),e.jsx(vr,{children:"Manage your email subscription settings"})]}),e.jsxs(Oe,{children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:"Weekly Digest"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:I?"You won't receive weekly digest emails":"Receive a weekly summary of new content, events, and your progress"})]}),e.jsx(Tn,{checked:!I,onCheckedChange:async ve=>{q(!0);try{const{error:ge}=await U.from("profiles").update({digest_opt_out:!ve}).eq("id",s==null?void 0:s.id);if(ge)throw ge;D(!ve),n({title:ve?"Subscribed":"Unsubscribed",description:ve?"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{q(!1)}},disabled:B})]}),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:W?"You won't receive event invite emails (weekly digest is unaffected)":"Get invited to LevelUp live trainings and special events"})]}),e.jsx(Tn,{checked:!W,onCheckedChange:async ve=>{Q(!0);try{const{error:ge}=await U.from("profiles").update({event_invite_opt_out:!ve}).eq("id",s==null?void 0:s.id);if(ge)throw ge;V(!ve),n({title:ve?"Subscribed":"Unsubscribed",description:ve?"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{Q(!1)}},disabled:K})]})]})]}),e.jsx(XAs,{}),e.jsx(yDs,{})]}),e.jsx(lWe,{open:b,onClose:()=>v(!1),imageSrc:N,onCropComplete:ee,aspectRatio:1})]})})};var bDs="AspectRatio",HLt=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(Ka.div,{...a,ref:t,style:{...r,position:"absolute",top:0,right:0,bottom:0,left:0}})})});HLt.displayName=bDs;var _Ds=HLt;const wDs=_Ds;function jDs(){const{user:s}=_s(),t=ts(),[n,r]=j.useState(!1),[a,i]=j.useState(!1),{data:l,isLoading:o}=ht({queryKey:["calendar-token",s==null?void 0:s.id],queryFn:async()=>{const{data:x,error:g}=await U.from("profiles").select("calendar_token").eq("id",s==null?void 0:s.id).single();if(g)throw g;return x},enabled:!!s&&a}),c=yt({mutationFn:async()=>{const x=new Uint8Array(12);crypto.getRandomValues(x);const g=btoa(String.fromCharCode(...x)).replace(/\+/g,"x").replace(/\//g,"y").replace(/=/g,"").substring(0,16),{error:y}=await U.from("profiles").update({calendar_token:g}).eq("id",s==null?void 0:s.id);if(y)throw y;return g},onSuccess:()=>{t.invalidateQueries({queryKey:["calendar-token",s==null?void 0:s.id]}),ae.success("Calendar subscription URL generated!")},onError:x=>{ae.error("Failed to generate calendar URL: "+x.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),ae.success("Calendar URL copied to clipboard!"),setTimeout(()=>r(!1),2e3))},h=()=>{d&&(window.location.href=d.replace("https://","webcal://"))},m=()=>{if(d){const x=d.replace("https://","webcal://"),g=`https://calendar.google.com/calendar/r?cid=${encodeURIComponent(x)}`;window.open(g,"_blank")}},p=()=>{if(d){const x=`https://outlook.live.com/calendar/0/addfromweb?url=${encodeURIComponent(d)}&name=Level%20Up%20Events`;window.open(x,"_blank")}};return e.jsxs(Os,{open:a,onOpenChange:i,children:[e.jsx(Ko,{asChild:!0,children:e.jsxs($,{variant:"outline",className:"gap-2",children:[e.jsx(ia,{className:"h-4 w-4"}),"Subscribe to Calendar"]})}),e.jsxs(Rs,{className:"sm:max-w-md",children:[e.jsxs(Us,{children:[e.jsxs(zs,{className:"flex items-center gap-2",children:[e.jsx(ia,{className:"h-5 w-5 text-primary"}),"Subscribe to Events Calendar"]}),e.jsx(Sr,{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(Ht,{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(be,{value:d,readOnly:!0,className:"text-xs font-mono"}),e.jsx($,{variant:"outline",size:"icon",onClick:u,children:n?e.jsx(oa,{className:"h-4 w-4 text-green-500"}):e.jsx(Ca,{className:"h-4 w-4"})})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"text-sm font-medium",children:"Quick Add"}),e.jsxs("div",{className:"grid gap-2",children:[e.jsxs($,{variant:"outline",className:"w-full justify-start gap-2",onClick:h,children:[e.jsx("svg",{className:"h-4 w-4",viewBox:"0 0 24 24",fill:"currentColor",children:e.jsx("path",{d:"M18.71 19.5c-.83 1.24-1.71 2.45-3.05 2.47-1.34.03-1.77-.79-3.29-.79-1.53 0-2 .77-3.27.82-1.31.05-2.3-1.32-3.14-2.53C4.25 17 2.94 12.45 4.7 9.39c.87-1.52 2.43-2.48 4.12-2.51 1.28-.02 2.5.87 3.29.87.78 0 2.26-1.07 3.81-.91.65.03 2.47.26 3.64 1.98-.09.06-2.17 1.28-2.15 3.81.03 3.02 2.65 4.03 2.68 4.04-.03.07-.42 1.44-1.38 2.83M13 3.5c.73-.83 1.94-1.46 2.94-1.5.13 1.17-.34 2.35-1.04 3.19-.69.85-1.83 1.51-2.95 1.42-.15-1.15.41-2.35 1.05-3.11z"})}),"Add to Apple Calendar",e.jsx(Tr,{className:"h-3 w-3 ml-auto opacity-50"})]}),e.jsxs($,{variant:"outline",className:"w-full justify-start gap-2",onClick:m,children:[e.jsxs("svg",{className:"h-4 w-4",viewBox:"0 0 24 24",fill:"currentColor",children:[e.jsx("path",{d:"M19.5 22h-15A2.5 2.5 0 0 1 2 19.5v-15A2.5 2.5 0 0 1 4.5 2H9v2H4.5a.5.5 0 0 0-.5.5v15a.5.5 0 0 0 .5.5h15a.5.5 0 0 0 .5-.5V15h2v4.5a2.5 2.5 0 0 1-2.5 2.5z"}),e.jsx("path",{d:"M12 2v8.5a1.5 1.5 0 0 0 1.5 1.5H22V2h-10z",fill:"#4285F4"}),e.jsx("path",{d:"M12 12V2H4.5A2.5 2.5 0 0 0 2 4.5V12h10z",fill:"#34A853"}),e.jsx("path",{d:"M2 12v7.5A2.5 2.5 0 0 0 4.5 22H12v-10H2z",fill:"#FBBC05"}),e.jsx("path",{d:"M12 22h7.5a2.5 2.5 0 0 0 2.5-2.5V12h-10v10z",fill:"#EA4335"})]}),"Add to Google Calendar",e.jsx(Tr,{className:"h-3 w-3 ml-auto opacity-50"})]}),e.jsxs($,{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(Tr,{className:"h-3 w-3 ml-auto opacity-50"})]})]})]}),e.jsx("p",{className:"text-xs text-muted-foreground text-center pt-2",children:"Events sync automatically. If your membership expires, the calendar will show as empty."})]}):e.jsxs("div",{className:"text-center space-y-4",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Generate your personal calendar subscription URL to get started."}),e.jsx($,{onClick:()=>c.mutate(),disabled:c.isPending,className:"w-full",children:c.isPending?e.jsxs(e.Fragment,{children:[e.jsx(Ht,{className:"h-4 w-4 mr-2 animate-spin"}),"Generating..."]}):e.jsxs(e.Fragment,{children:[e.jsx(ia,{className:"h-4 w-4 mr-2"}),"Generate Calendar URL"]})})]})})]})]})}const NDs={first_timer:Qa,regular:V3,dedicated:pu,veteran:pl,streak_master:yd,century:pl},kDs={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 Gct(s){return s===1?e.jsx(pl,{className:"h-5 w-5 text-yellow-500"}):s===2?e.jsx(V3,{className:"h-5 w-5 text-gray-400"}):s===3?e.jsx(pu,{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 GLt({showUserStats:s=!0,compact:t=!1,brokerageId:n,title:r="Event Leaderboard"}){const{user:a}=_s(),{data:i,isLoading:l}=k6t(t?5:10,n),{data:o}=S6t(a==null?void 0:a.id),{data:c}=A6t(a==null?void 0:a.id),{data:d}=C6t(a==null?void 0:a.id);return l?e.jsxs(_e,{children:[e.jsx(Bt,{children:e.jsxs(Ut,{className:"flex items-center gap-2",children:[e.jsx(pl,{className:"h-5 w-5 text-yellow-500"}),r]})}),e.jsx(Oe,{children:e.jsx("div",{className:"space-y-3",children:[...Array(5)].map((u,h)=>e.jsx(on,{className:"h-12 w-full"},h))})})]}):e.jsxs(_e,{children:[e.jsx(Bt,{className:"pb-3",children:e.jsxs(Ut,{className:"flex items-center gap-2",children:[e.jsx(pl,{className:"h-5 w-5 text-yellow-500"}),r]})}),e.jsxs(Oe,{children:[s&&o&&e.jsxs("div",{className:"mb-4 p-3 rounded-lg bg-primary/5 border border-primary/10",children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx("span",{className:"text-sm font-medium",children:"Your Stats"}),c&&e.jsxs($e,{variant:"secondary",className:"text-xs",children:["Rank #",c]})]}),e.jsxs("div",{className:"grid grid-cols-3 gap-2 text-center",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-lg font-bold text-primary",children:o.total_points}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Points"})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-lg font-bold",children:o.total_events_attended}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Events"})]}),e.jsxs("div",{className:"flex items-center justify-center gap-1",children:[e.jsx(yd,{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=NDs[u.badge_type]||Qa;return e.jsxs($e,{variant:"outline",className:`text-xs ${kDs[u.badge_type]||""}`,title:u.badge_description||"",children:[e.jsx(h,{className:"h-3 w-3 mr-1"}),u.badge_name]},u.id)}),d.length>4&&e.jsxs($e,{variant:"outline",className:"text-xs",children:["+",d.length-4," more"]})]})]}),e.jsxs(ua,{defaultValue:"points",className:"w-full",children:[e.jsxs(ha,{className:"w-full mb-3",children:[e.jsx(Qt,{value:"points",className:"flex-1",children:"By Points"}),e.jsx(Qt,{value:"events",className:"flex-1",children:"By Events"})]}),e.jsx(Jt,{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,x;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:Gct(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:[((x=u.profile)==null?void 0:x.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(Jt,{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,x;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:Gct(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:[((x=u.profile)==null?void 0:x.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 SDs(){const s=Vn(),{user:t,isAdmin:n}=_s(),r=ts(),[a,i]=j.useState(!1),[l,o]=j.useState(!1),{data:c,isLoading:d}=ht({queryKey:["public-events"],queryFn:async()=>{const{data:T,error:P}=await U.from("events").select("*").order("event_date",{ascending:!0});if(P)throw P;return T}}),{data:u}=ht({queryKey:["my-registrations"],queryFn:async()=>{if(!t)return[];const{data:T,error:P}=await U.from("event_registrations").select("event_id, zoom_join_url").eq("user_id",t.id);if(P)throw P;return T},enabled:!!t}),{data:h}=ht({queryKey:["event-registration-counts"],queryFn:async()=>{let T=[],P=0;const M=1e3;for(;;){const{data:D,error:B}=await U.from("event_registrations").select("event_id").range(P,P+M-1);if(B)throw B;if(!D||D.length===0||(T=T.concat(D),D.length{I[D.event_id]=(I[D.event_id]||0)+1}),I}}),m=yt({mutationFn:async T=>{await U.auth.refreshSession();const{data:P,error:M}=await U.functions.invoke("zoom-register",{body:{event_id:T}});if(M)throw M;if(P!=null&&P.error)throw new Error(P.error);return P},onSuccess:T=>{r.invalidateQueries({queryKey:["my-registrations"]}),r.invalidateQueries({queryKey:["event-registration-counts"]}),T!=null&&T.join_url?ae.success("Successfully registered! You'll receive a Zoom confirmation email."):ae.success("Successfully registered for the event!")},onError:T=>{ae.error("Failed to register: "+T.message)}}),p=yt({mutationFn:async T=>{const{data:P,error:M}=await U.functions.invoke("zoom-unregister",{body:{event_id:T}});if(M)throw M;if(P!=null&&P.error)throw new Error(P.error);return P},onSuccess:()=>{r.invalidateQueries({queryKey:["my-registrations"]}),r.invalidateQueries({queryKey:["event-registration-counts"]}),ae.success("Registration cancelled and removed from Zoom")},onError:T=>{ae.error("Failed to cancel: "+T.message)}}),x=T=>u==null?void 0:u.some(P=>P.event_id===T),g=T=>{const P=u==null?void 0:u.find(M=>M.event_id===T);return P==null?void 0:P.zoom_join_url},y=T=>T.capacity?((h==null?void 0:h[T.id])||0)>=T.capacity:!1,b=(c==null?void 0:c.filter(T=>P8(T.event_date)!=="ended"))||[],v=(c==null?void 0:c.filter(T=>P8(T.event_date)==="ended"))||[],N=b.filter(T=>P8(T.event_date)==="live").length,C=b.filter(T=>x(T.id)).length,A=l?v:v.slice(0,6);return e.jsx(Ks,{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.":b.length>0?`Next up: ${b[0].title}`:"No upcoming events scheduled — replays are below."})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(jDs,{}),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(pc,{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:b.length,icon:ia},{label:"You're registered",value:C,icon:oa},{label:"Live now",value:N,icon:Cg},{label:"Past events",value:v.length,icon:Uj}].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))}):b.length===0?e.jsx(_e,{className:"rounded-2xl border-dashed py-12 text-center",children:e.jsxs(Oe,{className:"space-y-2",children:[e.jsx(ia,{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:b.map(T=>{const P=P8(T.event_date),M=hGe(T.event_date),I=P==="live",D=P==="starting_soon";return e.jsxs(_e,{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":D?"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(Cg,{className:"h-3.5 w-3.5"}),"LIVE NOW"]}):e.jsxs(e.Fragment,{children:[e.jsx(Hr,{className:"h-3.5 w-3.5"}),"STARTING SOON"]})]}),T.image_url&&e.jsxs(wDs,{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(Bt,{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(ia,{className:"h-3 w-3"}),new Intl.DateTimeFormat("en-US",{month:"short",day:"numeric",timeZone:"America/New_York"}).format(new Date(T.event_date))]}),x(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(oa,{className:"h-3 w-3"}),"Registered"]})]}),e.jsx(Ut,{className:"line-clamp-2 pt-1",children:T.title}),T.description&&e.jsx(vr,{className:"line-clamp-2",children:T.description.replace(/<[^>]*>/g,"")})]}),e.jsxs(Oe,{className:"flex-1 space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(ia,{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(Hr,{className:"h-4 w-4"}),ZZ(new Date(T.event_date))]}),e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(qn,{className:"h-4 w-4"}),(h==null?void 0:h[T.id])||0," registered",T.capacity&&` / ${T.capacity} spots`]})]}),e.jsx(uY,{className:"flex gap-2",onClick:B=>B.stopPropagation(),children:x(T.id)?e.jsxs(e.Fragment,{children:[e.jsxs($,{variant:"outline",className:"flex-1",onClick:()=>p.mutate(T.id),disabled:p.isPending,children:[e.jsx(pr,{className:"h-4 w-4 mr-2"}),"Cancel"]}),e.jsxs($,{className:"flex-1",onClick:()=>window.open(g(T.id)||T.zoom_link,"_blank"),children:[e.jsx(Tr,{className:"h-4 w-4 mr-2"}),"Join Zoom"]})]}):e.jsx($,{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(oa,{className:"h-4 w-4 mr-2"}),"Register"]})})})]},T.id)})}),v.length>0&&e.jsxs(_e,{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(Uj,{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:[v.length," previous ",v.length===1?"session":"sessions"," — open one to watch the replay"]})]})]}),e.jsx(_o,{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(Sh,{className:"h-4 w-4 shrink-0 text-muted-foreground"})]})},T.id))}),v.length>6&&e.jsx("div",{className:"border-t px-5 py-3",children:e.jsx($,{variant:"ghost",size:"sm",className:"w-full",onClick:()=>o(T=>!T),children:l?"Show less":`Show all ${v.length}`})})]})]})]}),n&&e.jsx("div",{className:"lg:col-span-1",children:e.jsx(GLt,{showUserStats:!0})})]})]})})}const QPe=[{value:"all",label:"All Roles",icon:qn},{value:"newest",label:"Newest Members",icon:Hr},{value:"brokerage_manager",label:"Brokerage Managers",icon:sY},{value:"admin",label:"Admins",icon:kf}];function CDs({open:s,onOpenChange:t,resourceType:n,resourceId:r,resourceTitle:a}){var De,ze;const{user:i,isAdmin:l,isBrokerageManager:o}=_s(),[c,d]=j.useState([]),[u,h]=j.useState([]),[m,p]=j.useState([]),[x,g]=j.useState([]),[y,b]=j.useState(""),[v,N]=j.useState(""),[C,A]=j.useState(""),[T,P]=j.useState(!1),[M,I]=j.useState(!1),[D,B]=j.useState("agents"),[q,W]=j.useState("all"),[V,K]=j.useState({}),Q=l||o;j.useEffect(()=>{s&&i&&(l?J():ce())},[s,i,l]),j.useEffect(()=>{s||(p([]),g([]),b(""),N(""),A(""),B("agents"),W("all"))},[s]);const J=async()=>{if(i){P(!0);try{const{data:ke,error:Xe}=await U.from("brokerages").select("id, name").order("name");if(Xe)throw Xe;const Se=1e3,Re={};let Ae=0,Be=!0;for(;Be;){const{data:Ze,error:Ue}=await U.from("profiles").select("brokerage_id").range(Ae*Se,(Ae+1)*Se-1);if(Ue)throw Ue;Ze==null||Ze.forEach(et=>{et.brokerage_id&&(Re[et.brokerage_id]=(Re[et.brokerage_id]||0)+1)}),Be=(Ze==null?void 0:Ze.length)===Se,Ae++}h((ke==null?void 0:ke.map(Ze=>({...Ze,agent_count:Re[Ze.id]||0})))||[]);const qe=[];for(Ae=0,Be=!0;Be;){const{data:Ze,error:Ue}=await U.from("profiles").select("id, name, email, brokerage_id, created_at, brokerages(name)").neq("id",i.id).order("name").range(Ae*Se,(Ae+1)*Se-1);if(Ue)throw Ue;Ze&&qe.push(...Ze),Be=(Ze==null?void 0:Ze.length)===Se,Ae++}const Ke={};for(Ae=0,Be=!0;Be;){const{data:Ze,error:Ue}=await U.from("user_roles").select("user_id, role").range(Ae*Se,(Ae+1)*Se-1);if(Ue)throw Ue;Ze==null||Ze.forEach(et=>{Ke[et.user_id]||(Ke[et.user_id]=[]),Ke[et.user_id].push(et.role)}),Be=(Ze==null?void 0:Ze.length)===Se,Ae++}K(Ke),d(qe.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:Ke[Ze.id]||[],created_at:Ze.created_at}}))}catch(ke){console.error("Error loading data:",ke),ae.error("Failed to load agents and brokerages")}finally{P(!1)}}},ce=async()=>{if(i){P(!0);try{const{data:ke}=await U.from("profiles").select("brokerage_id").eq("id",i.id).single();if(!(ke!=null&&ke.brokerage_id)){ae.error("You must be part of a brokerage to share resources"),t(!1);return}const{data:Xe,error:Se}=await U.from("profiles").select("id, name, email").eq("brokerage_id",ke.brokerage_id).neq("id",i.id).order("name");if(Se)throw Se;d(Xe||[])}catch(ke){console.error("Error loading agents:",ke),ae.error("Failed to load agents")}finally{P(!1)}}},ue=c.filter(ke=>{var Se;const Xe=ke.name.toLowerCase().includes(y.toLowerCase())||ke.email.toLowerCase().includes(y.toLowerCase())||((Se=ke.brokerage_name)==null?void 0:Se.toLowerCase().includes(y.toLowerCase()));if(l&&q!=="all"&&q!=="newest"){const Re=V[ke.id]||[];return Xe&&Re.includes(q)}return Xe}).sort((ke,Xe)=>q==="newest"?(Xe.created_at||"").localeCompare(ke.created_at||""):0),ne=u.filter(ke=>ke.name.toLowerCase().includes(v.toLowerCase())),ee=()=>{m.length===ue.length?p([]):p(ue.map(ke=>ke.id))},le=()=>{x.length===ne.length?g([]):g(ne.map(ke=>ke.id))},he=ke=>{if(!Q){p([ke]);return}p(Xe=>Xe.includes(ke)?Xe.filter(Se=>Se!==ke):[...Xe,ke])},ve=ke=>{g(Xe=>Xe.includes(ke)?Xe.filter(Se=>Se!==ke):[...Xe,ke])},ge=async()=>{if(!(m.length>0||x.length>0)){ae.error("Please select at least one agent or brokerage to share with");return}I(!0);try{const{data:Xe,error:Se}=await U.functions.invoke("send-share-notification",{body:{recipientIds:m,brokerageIds:x,resourceType:n,resourceId:r,resourceTitle:a,message:C.trim()||void 0}});if(Se)throw Se;const Re=(Xe==null?void 0:Xe.sharesCreated)||m.length;ae.success(`Shared with ${Re} agent${Re!==1?"s":""}`),t(!1)}catch(Xe){console.error("Error sharing resource:",Xe),ae.error("Failed to share resource")}finally{I(!1)}},fe=ke=>ke.split(" ").map(Xe=>Xe[0]).join("").toUpperCase().slice(0,2),je=ke=>{const Xe=V[ke]||[];return Xe.includes("admin")?e.jsx($e,{variant:"secondary",className:"text-[10px] px-1.5 py-0",children:"Admin"}):Xe.includes("brokerage_manager")?e.jsx($e,{variant:"outline",className:"text-[10px] px-1.5 py-0",children:"Manager"}):null},Ee=m.length+x.length,Me=q!=="all"&&q!=="newest"?ue.length:null;return e.jsx(Os,{open:s,onOpenChange:t,children:e.jsxs(Rs,{className:"sm:max-w-lg max-h-[90vh] overflow-hidden flex flex-col",children:[e.jsxs(Us,{className:"flex-shrink-0",children:[e.jsxs(zs,{className:"flex items-center gap-2",children:[e.jsx(Br,{className:"h-5 w-5 text-primary"}),"Share Resource"]}),e.jsxs(Sr,{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(ua,{value:D,onValueChange:B,className:"flex-1 flex flex-col overflow-hidden",children:[e.jsxs(ha,{className:"grid w-full grid-cols-2 flex-shrink-0",children:[e.jsxs(Qt,{value:"agents",className:"flex items-center gap-2",children:[e.jsx(qn,{className:"h-4 w-4"}),e.jsx("span",{children:"Agents"}),m.length>0&&e.jsx($e,{variant:"default",className:"h-5 min-w-5 px-1.5 text-xs",children:m.length})]}),e.jsxs(Qt,{value:"brokerages",className:"flex items-center gap-2",children:[e.jsx(Ai,{className:"h-4 w-4"}),e.jsx("span",{children:"Brokerages"}),x.length>0&&e.jsx($e,{variant:"default",className:"h-5 min-w-5 px-1.5 text-xs",children:x.length})]})]}),e.jsxs(Jt,{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(Vr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(be,{placeholder:"Search by name, email, or brokerage...",value:y,onChange:ke=>b(ke.target.value),className:"pl-9"})]}),e.jsxs(vs,{value:q,onValueChange:W,children:[e.jsxs(gs,{className:"w-[180px]",children:[e.jsx($j,{className:"h-4 w-4 mr-2 text-muted-foreground"}),e.jsx(bs,{placeholder:"Filter by role"})]}),e.jsx(ys,{children:QPe.map(ke=>e.jsx(Ye,{value:ke.value,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ke.icon,{className:"h-4 w-4"}),e.jsx("span",{children:ke.label})]})},ke.value))})]})]}),e.jsxs("div",{className:"flex items-center justify-between px-1 flex-shrink-0",children:[e.jsxs($,{variant:"ghost",size:"sm",onClick:ee,className:"text-xs h-8",disabled:ue.length===0,children:[e.jsx(qn,{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:[Me!==null&&e.jsxs("span",{className:"text-primary font-medium",children:[Me," ",(De=QPe.find(ke=>ke.value===q))==null?void 0:De.label]}),e.jsxs("span",{className:"font-medium",children:[m.length," selected"]})]})]}),e.jsx(Oi,{className:"h-[300px] border rounded-lg",children:T?e.jsx("div",{className:"flex items-center justify-center h-[200px]",children:e.jsx(Ht,{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(qn,{className:"h-8 w-8 mb-2 opacity-50"}),e.jsx("p",{className:"text-sm",children:q!=="all"?`No ${(ze=QPe.find(ke=>ke.value===q))==null?void 0:ze.label.toLowerCase()} found`:"No agents found"})]}):e.jsx("div",{className:"p-2 space-y-1",children:ue.map(ke=>e.jsxs("div",{className:`flex items-center gap-3 p-2.5 rounded-lg cursor-pointer hover:bg-accent/50 transition-colors ${m.includes(ke.id)?"bg-accent":""}`,onClick:()=>he(ke.id),children:[e.jsx(ui,{checked:m.includes(ke.id),onCheckedChange:()=>he(ke.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:fe(ke.name)})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("p",{className:"text-sm font-medium truncate",children:ke.name}),je(ke.id)]}),e.jsxs("p",{className:"text-xs text-muted-foreground truncate",children:[ke.email,ke.brokerage_name&&e.jsxs("span",{className:"ml-1 opacity-75",children:["• ",ke.brokerage_name]})]})]})]},ke.id))})})]}),e.jsxs(Jt,{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(Vr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(be,{placeholder:"Search brokerages...",value:v,onChange:ke=>N(ke.target.value),className:"pl-9"})]}),e.jsxs("div",{className:"flex items-center justify-between px-1 flex-shrink-0",children:[e.jsxs($,{variant:"ghost",size:"sm",onClick:le,className:"text-xs h-8",disabled:ne.length===0,children:[e.jsx(Ai,{className:"h-3.5 w-3.5 mr-1.5"}),x.length===ne.length&&ne.length>0?"Deselect All":"Select All"]}),e.jsxs("span",{className:"text-xs text-muted-foreground font-medium",children:[x.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(Oi,{className:"h-[250px] border rounded-lg",children:T?e.jsx("div",{className:"flex items-center justify-center h-[180px]",children:e.jsx(Ht,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):ne.length===0?e.jsxs("div",{className:"flex flex-col items-center justify-center h-[180px] text-muted-foreground",children:[e.jsx(Ai,{className:"h-8 w-8 mb-2 opacity-50"}),e.jsx("p",{className:"text-sm",children:"No brokerages found"})]}):e.jsx("div",{className:"p-2 space-y-1",children:ne.map(ke=>e.jsxs("div",{className:`flex items-center gap-3 p-2.5 rounded-lg cursor-pointer hover:bg-accent/50 transition-colors ${x.includes(ke.id)?"bg-accent":""}`,onClick:()=>ve(ke.id),children:[e.jsx(ui,{checked:x.includes(ke.id),onCheckedChange:()=>ve(ke.id),className:"flex-shrink-0"}),e.jsx("div",{className:"h-9 w-9 rounded-lg bg-primary/10 flex items-center justify-center flex-shrink-0",children:e.jsx(Ai,{className:"h-4 w-4 text-primary"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium truncate",children:ke.name}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[ke.agent_count," agent",ke.agent_count!==1?"s":""]})]})]},ke.id))})})]})]}):e.jsxs("div",{className:"flex-1 flex flex-col space-y-3 overflow-hidden",children:[e.jsxs("div",{className:"relative flex-shrink-0",children:[e.jsx(Vr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(be,{placeholder:"Search agents...",value:y,onChange:ke=>b(ke.target.value),className:"pl-9"})]}),Q&&e.jsxs("div",{className:"flex items-center justify-between px-1 flex-shrink-0",children:[e.jsxs($,{variant:"ghost",size:"sm",onClick:ee,className:"text-xs h-8",disabled:ue.length===0,children:[e.jsx(qn,{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(Oi,{className:"h-[300px] border rounded-lg",children:T?e.jsx("div",{className:"flex items-center justify-center h-[200px]",children:e.jsx(Ht,{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(qn,{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(ke=>e.jsxs("div",{className:`flex items-center gap-3 p-2.5 rounded-lg cursor-pointer hover:bg-accent/50 transition-colors ${m.includes(ke.id)?"bg-accent":""}`,onClick:()=>he(ke.id),children:[e.jsx(ui,{checked:m.includes(ke.id),onCheckedChange:()=>he(ke.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:fe(ke.name)})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium truncate",children:ke.name}),e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:ke.email})]})]},ke.id))})})]}),e.jsxs("div",{className:"space-y-2 flex-shrink-0",children:[e.jsx(se,{htmlFor:"message",className:"text-sm font-medium",children:"Add a message (optional)"}),e.jsx(Is,{id:"message",placeholder:"I thought you might find this useful...",value:C,onChange:ke=>A(ke.target.value),rows:2,className:"resize-none"})]}),e.jsxs("div",{className:"flex justify-end gap-2 pt-2 flex-shrink-0",children:[e.jsx($,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsx($,{onClick:ge,disabled:Ee===0||M,children:M?e.jsxs(e.Fragment,{children:[e.jsx(Ht,{className:"h-4 w-4 mr-2 animate-spin"}),"Sharing..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Br,{className:"h-4 w-4 mr-2"}),"Share"]})})]})]})]})})}function Fq({resourceType:s,resourceId:t,resourceTitle:n,variant:r="outline",size:a="sm",className:i=""}){const[l,o]=j.useState(!1),{user:c}=_s();return c?e.jsxs(e.Fragment,{children:[e.jsxs($,{variant:r,size:a,onClick:()=>o(!0),className:i,children:[e.jsx(vd,{className:"h-4 w-4 mr-2"}),"Share"]}),e.jsx(CDs,{open:l,onOpenChange:o,resourceType:s,resourceId:t,resourceTitle:n})]}):null}function ADs(){const{eventId:s}=Vi(),t=Vn(),{user:n}=_s(),[r,a]=j.useState(null),[i,l]=j.useState(null),[o,c]=j.useState(0),[d,u]=j.useState(!0),[h,m]=j.useState(!1);j.useEffect(()=>{s&&p()},[s,n]);const p=async()=>{try{const{data:N,error:C}=await U.from("events").select("*").eq("id",s).single();if(C)throw C;a(N);const{count:A}=await U.from("event_registrations").select("*",{count:"exact",head:!0}).eq("event_id",s);if(c(A||0),n){const{data:T}=await U.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),ae.error("Failed to load event"),t("/events")}finally{u(!1)}},x=async()=>{if(!(!n||!r)){m(!0);try{const{error:N}=await U.auth.refreshSession();if(N){console.error("Session refresh failed:",N),ae.error("Your session has expired. Please log in again.");return}if(i){const{error:C}=await U.functions.invoke("zoom-unregister",{body:{event_id:r.id}});if(C)throw C;ae.success("Successfully cancelled registration"),l(null),c(A=>A-1)}else{const{data:C,error:A}=await U.functions.invoke("zoom-register",{body:{event_id:r.id}});if(A)throw A;ae.success("Successfully registered for event!"),l({id:C.registration_id,zoom_join_url:C.zoom_join_url}),c(T=>T+1)}}catch(N){console.error("Registration error:",N),ae.error(i?"Failed to cancel registration":"Failed to register for event")}finally{m(!1)}}},g=N=>{var C,A,T;if(N.includes("iframe.mediadelivery.net")||N.includes("video.bunnycdn.com")){const P=N.match(/embed\/(\d+)\/([a-f0-9-]+)/);if(P)return`https://iframe.mediadelivery.net/embed/${P[1]}/${P[2]}?autoplay=false&preload=true`}if(N.includes("youtube.com")||N.includes("youtu.be")){const P=N.includes("youtu.be")?(C=N.split("youtu.be/")[1])==null?void 0:C.split("?")[0]:(A=N.split("v=")[1])==null?void 0:A.split("&")[0];if(P)return`https://www.youtube.com/embed/${P}`}if(N.includes("vimeo.com")){const P=(T=N.split("vimeo.com/")[1])==null?void 0:T.split("?")[0];if(P)return`https://player.vimeo.com/video/${P}`}return N};if(d)return e.jsx(Ks,{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(Ks,{title:"Event Not Found",children:e.jsxs("div",{className:"text-center py-16",children:[e.jsx("p",{className:"text-muted-foreground",children:"Event not found"}),e.jsx($,{onClick:()=>t("/events"),className:"mt-4",children:"Back to Events"})]})});const y=d5(new Date(r.event_date)),b=r.capacity&&o>=r.capacity,v=(i==null?void 0:i.zoom_join_url)||r.zoom_link;return e.jsx(Ks,{title:r.title,children:e.jsxs("div",{className:"max-w-4xl mx-auto",children:[e.jsxs($,{variant:"ghost",className:"mb-6 gap-2",onClick:()=>t("/events"),children:[e.jsx(ka,{className:"h-4 w-4"}),"Back to Events"]}),r.image_url&&e.jsxs("div",{className:"relative aspect-video rounded-xl overflow-hidden mb-6",children:[e.jsx("img",{src:r.image_url,alt:r.title,className:"w-full h-full object-cover"}),y&&e.jsx("div",{className:"absolute inset-0 bg-black/50 flex items-center justify-center",children:e.jsx($e,{variant:"secondary",className:"text-lg px-4 py-2",children:"Event Ended"})})]}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-3 gap-6",children:[e.jsxs("div",{className:"lg:col-span-2 space-y-6",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-start justify-between gap-4 mb-4",children:[e.jsx("h1",{className:"text-3xl font-bold text-foreground",children:r.title}),e.jsx(Fq,{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(Sh,{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:g(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(_e,{children:e.jsxs(Oe,{className:"p-6 space-y-4",children:[e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(ia,{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:ZZ(new Date(r.event_date))})]})]}),r.capacity&&e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(qn,{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(Ro,{className:"h-5 w-5 text-green-600"}),e.jsx("span",{className:"text-sm font-medium text-green-700",children:"You're registered!"})]}),e.jsxs("div",{className:"space-y-2 pt-2",children:[!y&&e.jsx(e.Fragment,{children:i?e.jsxs(e.Fragment,{children:[e.jsxs($,{className:"w-full gap-2",onClick:()=>window.open(v,"_blank"),children:[e.jsx(Tr,{className:"h-4 w-4"}),"Join Event"]}),e.jsxs($,{variant:"outline",className:"w-full",onClick:x,disabled:h,children:[h?e.jsx(Ht,{className:"h-4 w-4 animate-spin mr-2"}):null,"Cancel Registration"]})]}):e.jsx($,{className:"w-full gap-2",onClick:x,disabled:h||(b??!1),children:h?e.jsx(Ht,{className:"h-4 w-4 animate-spin"}):b?"Event Full":"Register Now"})}),y&&i&&e.jsxs($,{variant:"outline",className:"w-full gap-2",onClick:()=>window.open(r.zoom_link,"_blank"),children:[e.jsx(Tr,{className:"h-4 w-4"}),"View Recording"]})]})]})})})]})]})})}const EDs=[{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 TDs(){const{isAdmin:s}=_s(),t=EDs.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(_A,{to:n.to,end:n.end,className:({isActive:r})=>Tt("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 WSe=[{id:"market-listing",title:"Market a Listing",blurb:"Presentations, copy, pages and video",icon:sa,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:nn,color:"bg-emerald-500/15 text-emerald-600"},{id:"social-content",title:"Create Social Content",blurb:"Reels, posts and captions",icon:Eh,color:"bg-rose-500/15 text-rose-600"},{id:"open-house",title:"Host an Open House",blurb:"Promote, sign in and follow up",icon:zj,color:"bg-sky-500/15 text-sky-600"},{id:"new-business",title:"Generate New Business",blurb:"Leads, expireds and by-owner sellers",icon:Il,color:"bg-amber-500/15 text-amber-600"},{id:"brand",title:"Build My Brand",blurb:"Your card, site, reviews and presence",icon:Rc,color:"bg-teal-500/15 text-teal-600"}];WSe.reduce((s,t)=>({...s,[t.id]:t}),{});const MDs=[{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"}],WLt=[{id:"scheduler",name:"LevelUp Scheduler",description:"Share your booking link, sync Google Calendar and let clients book you",icon:Xu,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:Xr,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:yy,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:by,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:Wr,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:wf,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:dn,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:nn,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:lh,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:Br,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:wN,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:Lz,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:Gj,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:lh,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:ml,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:by,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:dn,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:sa,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"]}],Wct=WLt.reduce((s,t)=>({...s,[t.id]:t}),{}),LDs={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 PDs(s){return LDs[s]??{goals:[],categories:[],keywords:[]}}const cWe=[{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:sa,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:zj,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:qn,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"}]}],vO=cWe.reduce((s,t)=>({...s,[t.id]:t}),{});function IDs({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:Tt("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 DDs({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:Tt("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:Tt("flex-shrink-0 w-12 h-12 rounded-xl flex items-center justify-center text-2xl",s.color),children:i?e.jsx(Ad,{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:Tt("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:Tt("flex-shrink-0 p-2 -m-1 rounded-lg transition-colors",t?"text-primary":"text-muted-foreground/40 hover:text-primary"),children:e.jsx(wg,{className:Tt("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 RR({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(DDs,{item:a,isFavorite:t(a),onOpen:n,onToggleFavorite:r},a.key))})}const RDs="bg-primary/10 text-primary";function Cee(){const{user:s,isAdmin:t}=_s(),n=ek(),r=Vn(),{hasAccess:a}=uCe(),[i,l]=j.useState([]),[o,c]=j.useState(!0),[d,u]=j.useState(new Set),[h,m]=j.useState(new Set),[p,x]=j.useState(!1),[g,y]=j.useState([]),[b,v]=j.useState(""),N=j.useCallback(async()=>{if(s!=null&&s.id)try{const[{data:V},{data:K},{data:Q},{data:J},{data:ce},{data:ue},{data:ne}]=await Promise.all([U.from("user_tags").select("tag").eq("user_id",s.id),U.from("app_tiles").select("*").order("name"),U.from("user_favorites").select("app_id").eq("user_id",s.id),U.from("user_tool_favorites").select("tool_id").eq("user_id",s.id),U.from("lead_sites").select("id, mls_provider_id, no_mls_mode, is_active").eq("agent_id",s.id),U.from("activity_logs").select("app_id, app_name, launched_at").eq("user_id",s.id).order("launched_at",{ascending:!1}).limit(40),U.from("profiles").select("name").eq("id",s.id).maybeSingle()]),ee=(V||[]).map(fe=>fe.tag);x((ce||[]).some(fe=>fe.is_active&&fe.mls_provider_id&&!fe.no_mls_mode)),u(new Set((Q||[]).map(fe=>fe.app_id))),m(new Set((J||[]).map(fe=>fe.tool_id)));const le=(K||[]).filter(fe=>fe.app_id==="newsletter_studio"?!1:!fe.required_tags||fe.required_tags.length===0?!0:fe.required_tags.some(je=>ee.includes(je)));l(le.sort((fe,je)=>fe.name==="LevelUp Members Portal"?-1:je.name==="LevelUp Members Portal"?1:0));const he=new Set,ve=[];for(const fe of ue||[])if(!(!fe.app_id||he.has(fe.app_id))&&(he.add(fe.app_id),ve.push({appId:fe.app_id,name:fe.app_name,at:fe.launched_at}),ve.length>=8))break;y(ve);const ge=ne==null?void 0:ne.name;v(ge?ge.trim().split(" ")[0]:"")}catch(V){console.error("Error loading app catalog:",V),ae.error("Failed to load apps")}finally{c(!1)}},[s==null?void 0:s.id]);j.useEffect(()=>{N()},[N]);const C=j.useMemo(()=>{const V=ce=>{if(!n.isRestricted)return null;const ue=Nhs(ce);return ue&&!n.hasFeature(ue)?ue:null},K=WLt.filter(ce=>!(ce.adminOnly&&!t||ce.requiresLeadSiteMLS&&!p&&!t||ce.requiresWeeklyReels&&!a)).map(ce=>({key:`tool:${ce.id}`,kind:"tool",id:ce.id,name:ce.name,description:ce.description,icon:ce.icon,color:ce.color,isNew:ce.isNew,beta:ce.beta,popular:ce.popular,goals:ce.goals,categories:ce.categories,keywords:ce.keywords,lockedFeature:V(ce.id),tool:ce})),Q={AgentReview:"marketing_studio",SigFlow:"marketing_studio",Staging_Studio:"marketing_studio",social_autopilot:"social",newsletter_studio:"newsletter"},J=i.map(ce=>{const ue=PDs(ce.app_id),ne=Q[ce.app_id];return{key:`app:${ce.app_id}`,kind:"app",id:ce.app_id,name:ce.name,description:ce.description,icon:ce.icon,color:RDs,goals:ue.goals,categories:ue.categories,keywords:ue.keywords,lockedFeature:n.isRestricted&&ne&&!n.hasFeature(ne)?ne:null,tile:ce}});return[...K,...J]},[i,t,p,a,n.isRestricted,n.features]),A=j.useCallback(V=>{var K;return V.kind==="tool"?h.has(V.id):d.has(((K=V.tile)==null?void 0:K.id)??"")},[h,d]),T=j.useMemo(()=>C.filter(A),[C,A]),P=j.useMemo(()=>{const V=new Map(C.map(K=>[K.id,K]));return g.map(K=>V.get(K.appId)).filter(Boolean)},[C,g]),M=j.useMemo(()=>C.filter(V=>V.kind==="app"),[C]),I=j.useCallback(async(V,K)=>{try{await U.from("activity_logs").insert({user_id:s==null?void 0:s.id,app_id:V,app_name:K,user_agent:navigator.userAgent})}catch{}},[s==null?void 0:s.id]),D=j.useCallback(async V=>{var Q;try{const J=new URL(V.target_url);if(new Set([window.location.hostname,"dashboard.relevelup.com"]).has(J.hostname)){await I(V.app_id,V.name),r(J.pathname+J.search+J.hash);return}}catch{}const K=window.open("about:blank","_blank");try{const{data:J,error:ce}=await U.auth.getSession();if(ce||!J.session){K==null||K.close(),ae.error("Session expired. Please refresh the page and try again.");return}await I(V.app_id,V.name);const{data:ue,error:ne}=await U.functions.invoke("sso-launch",{body:{app_id:V.app_id},headers:{Authorization:`Bearer ${J.session.access_token}`}});if(ne)throw ne;ue!=null&&ue.redirect_url?K&&!K.closed?(K.location.href=ue.redirect_url,(Q=K.focus)==null||Q.call(K)):window.location.assign(ue.redirect_url):(K==null||K.close(),ae.error("Launch link unavailable"))}catch(J){K==null||K.close(),console.error("Error launching app:",J),ae.error("Failed to launch app. Please try again.")}},[I,r]),B=j.useCallback(V=>{if(V.lockedFeature){r(`/upgrade/${V.lockedFeature}`);return}if(V.kind==="app"&&V.tile){D(V.tile);return}V.tool&&(I(V.tool.id,V.tool.name),r(V.tool.path))},[D,I,r]),q=j.useCallback(async V=>{var ne;if(!(s!=null&&s.id))return;const K=A(V),Q=V.kind==="tool"?"user_tool_favorites":"user_favorites",J=V.kind==="tool"?"tool_id":"app_id",ce=V.kind==="tool"?V.id:(ne=V.tile)==null?void 0:ne.id;if(!ce)return;const ue=V.kind==="tool"?m:u;ue(ee=>{const le=new Set(ee);return K?le.delete(ce):le.add(ce),le});try{if(K){const{error:ee}=await U.from(Q).delete().eq("user_id",s.id).eq(J,ce);if(ee)throw ee}else{const{error:ee}=await U.from(Q).insert({user_id:s.id,[J]:ce});if(ee)throw ee}}catch(ee){console.error("Error toggling favorite:",ee),ae.error("Failed to update favorites"),ue(le=>{const he=new Set(le);return K?he.add(ce):he.delete(ce),he})}},[A,s==null?void 0:s.id]),W=j.useCallback((V,K=C)=>{const Q=V.trim().toLowerCase();if(!Q)return K;const J=Q.split(/\s+/);return K.filter(ce=>{const ue=[ce.name,ce.description,...ce.keywords,...ce.categories,...ce.goals].join(" ").toLowerCase();return J.every(ne=>ue.includes(ne))||ue.includes(Q)})},[C]);return{loading:o,items:C,favoriteItems:T,recentItems:P,connectedItems:M,recent:g,firstName:b,isFavorite:A,toggleFavorite:q,openItem:B,search:W,reload:N}}function JPe(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 yAe(s){const t=vO[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 vAe(){const{user:s}=_s(),[t,n]=j.useState([]),[r,a]=j.useState(!0),i=j.useCallback(async()=>{if(s!=null&&s.id)try{const{data:m,error:p}=await U.from("workflow_runs").select("*").eq("user_id",s.id).order("last_activity_at",{ascending:!1});if(p)throw p;n((m||[]).map(JPe))}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 x;if(!(s!=null&&s.id))return null;try{const{data:g,error:y}=await U.from("workflow_runs").insert({user_id:s.id,workflow_id:m,run_name:p.trim()||((x=vO[m])==null?void 0:x.title)||"Untitled"}).select("*").single();if(y)throw y;const b=JPe(g);return n(v=>[b,...v]),b}catch(g){return console.error("Error starting workflow:",g),ae.error("Could not start this workflow"),null}},[s==null?void 0:s.id]),o=j.useCallback(async(m,p)=>{const x={...p,last_activity_at:new Date().toISOString()};n(y=>y.map(b=>b.id===m?JPe({...b,...x}):b));const{error:g}=await U.from("workflow_runs").update(x).eq("id",m);g&&(console.error("Error updating workflow run:",g),ae.error("Could not save your progress"))},[]),c=j.useCallback(async(m,p,x)=>{const g={...m.step_state};x?g[p]=x:delete g[p];const y=vO[m.workflow_id],b=y?y.steps.every(v=>g[v.key]):!1;await o(m.id,{step_state:g,status:b?"completed":"in_progress",completed_at:b?new Date().toISOString():null}),b&&m.status!=="completed"&&ae.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(x=>x.filter(g=>g.id!==m));const{error:p}=await U.from("workflow_runs").delete().eq("id",m);p&&(console.error("Error deleting workflow run:",p),ae.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 ODs(){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 FDs(){const s=Vn(),{items:t,firstName:n,recentItems:r,favoriteItems:a,isFavorite:i,toggleFavorite:l,openItem:o,search:c}=Cee(),{isAdmin:d}=_s(),{activeRuns:u}=vAe(),h=d?u:[],[m,p]=j.useState(""),x=j.useMemo(()=>m.trim()?c(m).slice(0,8):[],[m,c]),g=j.useMemo(()=>{const b=new Set(r.map(C=>C.id)),v=[],N=C=>{for(const A of C){if(v.length>=4)break;v.some(T=>T.key===A.key)||v.push(A)}};return N(a.filter(C=>!b.has(C.id))),N(t.filter(C=>C.isNew&&!b.has(C.id))),N(t.filter(C=>C.popular&&!b.has(C.id))),v},[t,a,r]),y=b=>s(`/apps/browse?goal=${b.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:[ODs(),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(Vr,{className:"absolute left-4 top-1/2 -translate-y-1/2 h-5 w-5 text-muted-foreground"}),e.jsx(be,{value:m,onChange:b=>p(b.target.value),onKeyDown:b=>{b.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:x.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”."]}):x.map(b=>{const v=typeof b.icon=="string"?null:b.icon;return e.jsxs("button",{type:"button",onClick:()=>o(b),className:"w-full flex items-center gap-3 p-4 text-left hover:bg-muted/50 transition-colors",children:[e.jsx("span",{className:Tt("w-10 h-10 rounded-lg flex items-center justify-center text-xl flex-shrink-0",b.color),children:v?e.jsx(v,{className:"h-5 w-5"}):b.icon}),e.jsxs("span",{className:"min-w-0",children:[e.jsx("span",{className:"block font-medium text-foreground",children:b.name}),e.jsx("span",{className:"block text-sm text-muted-foreground truncate",children:b.description})]})]},b.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:WSe.map(b=>e.jsx(IDs,{goal:b,onSelect:y},b.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(Hr,{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(b=>{const v=vO[b.workflow_id],N=yAe(b);return e.jsxs("button",{type:"button",onClick:()=>s(`/apps/workflows/${b.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:b.run_name}),e.jsxs("p",{className:"text-sm text-muted-foreground truncate",children:[v==null?void 0:v.title," · Step ",Math.min(N.touched+1,N.total)," of ",N.total]})]}),e.jsx(ni,{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}%`}})})]},b.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(b=>{const v=typeof b.icon=="string"?null:b.icon;return e.jsxs("button",{type:"button",onClick:()=>o(b),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:Tt("w-10 h-10 rounded-lg flex items-center justify-center text-xl mb-3",b.color),children:v?e.jsx(v,{className:"h-5 w-5"}):b.icon}),e.jsx("span",{className:"block font-medium text-sm text-foreground truncate",children:b.name}),e.jsx("span",{className:"block text-xs text-muted-foreground",children:"Open again"})]},b.key)})})]})]}),g.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(dn,{className:"h-4 w-4 text-primary"})," Recommended for you"]}),e.jsx("div",{className:"space-y-3",children:g.map(b=>{const v=typeof b.icon=="string"?null:b.icon;return e.jsxs("button",{type:"button",onClick:()=>o(b),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:Tt("w-10 h-10 rounded-lg flex items-center justify-center text-xl flex-shrink-0",b.color),children:v?e.jsx(v,{className:"h-5 w-5"}):b.icon}),e.jsxs("span",{className:"min-w-0",children:[e.jsx("span",{className:"block font-medium text-foreground",children:b.name}),e.jsx("span",{className:"block text-sm text-muted-foreground line-clamp-2",children:b.description})]})]},b.key)})}),e.jsx($,{variant:"outline",className:"w-full",onClick:()=>s("/apps/browse"),children:"Browse all apps"})]})]}),a.length>0&&e.jsxs("section",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-4",children:[e.jsx("h2",{className:"text-lg font-semibold text-foreground",children:"Your favorites"}),e.jsx($,{variant:"ghost",size:"sm",onClick:()=>s("/apps/my-apps"),children:"View all"})]}),e.jsx(RR,{items:a.slice(0,6),isFavorite:i,onOpen:o,onToggleFavorite:l})]})]})}function KLt({workflow:s,activeRun:t,onStart:n,onResume:r}){const a=s.icon,i=t?yAe(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:Tt("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(Fr,{className:"h-3.5 w-3.5"}),e.jsxs("span",{children:[s.steps.length," steps · ",s.outcome]})]}),t&&i?e.jsxs("div",{className:"mt-auto space-y-3",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between text-xs text-muted-foreground mb-1",children:[e.jsx("span",{className:"truncate pr-2",children:t.run_name}),e.jsxs("span",{className:"flex-shrink-0",children:["Step ",Math.min(i.touched+1,i.total)," of ",i.total]})]}),e.jsx("div",{className:"h-2 rounded-full bg-muted overflow-hidden",children:e.jsx("div",{className:"h-full bg-primary transition-all",style:{width:`${i.pct}%`}})})]}),e.jsxs($,{className:"w-full",onClick:()=>r(t),children:["Continue ",e.jsx(ni,{className:"h-4 w-4 ml-1"})]})]}):e.jsx("div",{className:"mt-auto",children:e.jsxs($,{className:"w-full",onClick:()=>n(s),children:["Start Workflow ",e.jsx(ni,{className:"h-4 w-4 ml-1"})]})})]})}function YLt({workflow:s,onClose:t,onStart:n}){const[r,a]=j.useState(""),[i,l]=j.useState(!1);j.useEffect(()=>{a(""),l(!1)},[s==null?void 0:s.id]);const o=async()=>{s&&(l(!0),await n(s,r.trim()||s.title),l(!1))};return e.jsx(Os,{open:!!s,onOpenChange:c=>!c&&t(),children:e.jsxs(Rs,{className:"sm:max-w-md",children:[e.jsxs(Us,{children:[e.jsx(zs,{children:s==null?void 0:s.title}),e.jsxs(Sr,{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(se,{htmlFor:"workflow-run-name",children:s==null?void 0:s.namePrompt}),e.jsx(be,{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(kr,{children:[e.jsx($,{variant:"outline",onClick:t,disabled:i,children:"Cancel"}),e.jsx($,{onClick:o,disabled:i,children:i?"Starting…":"Start workflow"})]})]})})}function zDs(){const s=Vn(),[t,n]=oc(),{items:r,isFavorite:a,toggleFavorite:i,openItem:l,search:o}=Cee(),{isAdmin:c}=_s(),{activeRuns:d,startRun:u}=vAe(),h=t.get("goal"),m=t.get("category")??null,[p,x]=j.useState(t.get("q")??""),[g,y]=j.useState(null);j.useEffect(()=>{x(t.get("q")??"")},[t]);const b=(T,P)=>{const M=new URLSearchParams(t);P?M.set(T,P):M.delete(T),n(M,{replace:!0})},v=()=>{const T=new URLSearchParams(t);T.delete("category"),T.delete("goal"),T.delete("q"),n(T,{replace:!0}),x("")},N=j.useMemo(()=>{let T=r;return h&&(T=T.filter(P=>P.goals.includes(h))),m&&(T=T.filter(P=>P.categories.includes(m))),p.trim()&&(T=o(p,T)),T},[r,h,m,p,o]),C=j.useMemo(()=>h||m||p.trim()?null:WSe.map(T=>({goal:T,apps:r.filter(P=>P.goals.includes(T.id))})).filter(T=>T.apps.length>0),[r,h,m,p]),A=h?WSe.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(Vr,{className:"absolute left-4 top-1/2 -translate-y-1/2 h-5 w-5 text-muted-foreground"}),e.jsx(be,{value:p,onChange:T=>{x(T.target.value),b("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:v,className:Tt("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"}),MDs.map(T=>e.jsx("button",{type:"button",onClick:()=>b("category",m===T.id?null:T.id),className:Tt("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:()=>b("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:cWe.map(T=>e.jsx(KLt,{workflow:T,activeRun:d.find(P=>P.workflow_id===T.id),onStart:y,onResume:P=>s(`/apps/workflows/${P.id}`)},T.id))})]}),C?C.map(({goal:T,apps:P})=>e.jsxs("section",{children:[e.jsx("h2",{className:"text-lg font-semibold text-foreground mb-4",children:T.title}),e.jsx(RR,{items:P,isFavorite:a,onOpen:l,onToggleFavorite:i})]},T.id)):N.length>0?e.jsx(RR,{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(Vr,{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(YLt,{workflow:g,onClose:()=>y(null),onStart:async(T,P)=>{const M=await u(T.id,P);y(null),M&&s(`/apps/workflows/${M.id}`)}})]})}function BDs(){const s=Vn(),{favoriteItems:t,recentItems:n,connectedItems:r,isFavorite:a,toggleFavorite:i,openItem:l}=Cee(),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(wg,{className:"h-10 w-10 text-muted-foreground mx-auto mb-3"}),e.jsx("p",{className:"font-medium text-foreground",children:"Nothing saved yet"}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1 max-w-sm mx-auto",children:"Tap the bookmark on any app to pin it here for quick access."}),e.jsx($,{className:"mt-4",onClick:()=>s("/apps/browse"),children:"Browse apps"})]}),t.length>0&&e.jsxs("section",{children:[e.jsxs("h2",{className:"text-lg font-semibold text-foreground mb-4 flex items-center gap-2",children:[e.jsx(wg,{className:"h-4 w-4 text-primary"})," Favorites"]}),e.jsx(RR,{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(Hr,{className:"h-4 w-4 text-muted-foreground"})," Recently used"]}),e.jsx(RR,{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(R_,{className:"h-4 w-4 text-muted-foreground"})," Activated for your account"]}),e.jsx(RR,{items:r,isFavorite:a,onOpen:l,onToggleFavorite:i})]})]})}function $Ds(){const{connectedItems:s,isFavorite:t,toggleFavorite:n,openItem:r}=Cee();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(Dc,{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(RR,{items:s,isFavorite:t,onOpen:r,onToggleFavorite:n})]})}function UDs(){const s=Vn(),{activeRuns:t,completedRuns:n,startRun:r,reopenRun:a,deleteRun:i}=vAe(),[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=vO[c.workflow_id],u=yAe(c);return e.jsxs("div",{className:"bg-card border border-border rounded-2xl p-4 flex items-center gap-4",children:[e.jsxs("button",{type:"button",onClick:()=>s(`/apps/workflows/${c.id}`),className:"flex-1 min-w-0 text-left",children:[e.jsx("p",{className:"font-medium text-foreground truncate",children:c.run_name}),e.jsxs("p",{className:"text-sm text-muted-foreground truncate",children:[d==null?void 0:d.title," · Step ",Math.min(u.touched+1,u.total)," of ",u.total]}),e.jsx("div",{className:"h-1.5 rounded-full bg-muted overflow-hidden mt-3",children:e.jsx("div",{className:"h-full bg-primary",style:{width:`${u.pct}%`}})})]}),e.jsx($,{onClick:()=>s(`/apps/workflows/${c.id}`),children:"Continue"})]},c.id)})})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-lg font-semibold text-foreground mb-4",children:"Start a workflow"}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4",children:cWe.map(c=>e.jsx(KLt,{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(Fr,{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=vO[c.workflow_id])==null?void 0:d.title})]}),e.jsxs($,{variant:"ghost",size:"sm",onClick:()=>a(c),children:[e.jsx(Ih,{className:"h-4 w-4 mr-1"})," Reopen"]}),e.jsx($,{variant:"ghost",size:"icon","aria-label":"Delete workflow",onClick:()=>i(c.id),children:e.jsx(Pn,{className:"h-4 w-4 text-muted-foreground"})})]},c.id)})})]}),e.jsx(YLt,{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 qDs(){const{runId:s}=Vi(),t=Vn(),{runs:n,loading:r,setStep:a,renameRun:i,reopenRun:l,deleteRun:o}=vAe(),{items:c,openItem:d}=Cee(),[u,h]=j.useState(!1),[m,p]=j.useState(""),x=j.useMemo(()=>n.find(N=>N.id===s),[n,s]),g=x?vO[x.workflow_id]:void 0;if(r)return e.jsx("p",{className:"text-muted-foreground",children:"Loading…"});if(!x||!g)return e.jsxs("div",{className:"text-center py-16 bg-card border border-border rounded-2xl",children:[e.jsx("p",{className:"font-medium text-foreground",children:"This workflow isn't available"}),e.jsx($,{className:"mt-4",onClick:()=>t("/apps/workflows"),children:"Back to workflows"})]});const y=yAe(x),b=g.icon,v=N=>{if(!N)return;const C=c.find(T=>T.kind==="tool"&&T.id===N);if(C){d(C);return}const A=Wct[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(ka,{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:Tt("w-12 h-12 rounded-xl flex items-center justify-center flex-shrink-0",g.color),children:e.jsx(b,{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(be,{value:m,onChange:N=>p(N.target.value),autoFocus:!0,onKeyDown:N=>{N.key==="Enter"&&(i(x,m),h(!1))}}),e.jsx($,{size:"sm",onClick:()=>{i(x,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:x.run_name}),e.jsx("button",{type:"button","aria-label":"Rename workflow",onClick:()=>{p(x.run_name),h(!0)},className:"text-muted-foreground hover:text-foreground",children:e.jsx(Ya,{className:"h-4 w-4"})})]}),e.jsxs("p",{className:"text-sm text-muted-foreground mt-1",children:[g.title," · ",g.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}%`}})})]}),x.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(Fr,{className:"h-4 w-4"})," Workflow complete"]}),e.jsx($,{variant:"outline",size:"sm",onClick:()=>l(x),children:"Reopen"})]})]}),e.jsx("ol",{className:"space-y-3",children:g.steps.map((N,C)=>{const A=x.step_state[N.key],T=N.toolId?Wct[N.toolId]:void 0,P=A==="done",M=A==="skipped";return e.jsx("li",{className:Tt("bg-card border rounded-2xl p-4 sm:p-5 transition-colors",P?"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:Tt("w-9 h-9 rounded-full flex items-center justify-center flex-shrink-0 text-sm font-semibold",P?"bg-emerald-500 text-white":M?"bg-muted text-muted-foreground":"bg-primary/10 text-primary"),children:P?e.jsx(oa,{className:"h-4 w-4"}):C+1}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:Tt("font-medium text-foreground",(P||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($,{size:"sm",onClick:()=>v(N.toolId),children:["Open ",T.name," ",e.jsx(Tr,{className:"h-3.5 w-3.5 ml-1"})]}),e.jsxs($,{size:"sm",variant:P?"secondary":"outline",onClick:()=>a(x,N.key,P?null:"done"),children:[e.jsx(oa,{className:"h-3.5 w-3.5 mr-1"}),P?"Done":"Mark done"]}),e.jsxs($,{size:"sm",variant:"ghost",onClick:()=>a(x,N.key,M?null:"skipped"),children:[e.jsx(KK,{className:"h-3.5 w-3.5 mr-1"}),M?"Un-skip":"Skip"]})]})]})]})},N.key)})}),e.jsx("div",{className:"pt-2",children:e.jsxs($,{variant:"ghost",size:"sm",className:"text-muted-foreground",onClick:()=>{o(x.id),t("/apps/workflows")},children:[e.jsx(Pn,{className:"h-4 w-4 mr-1"})," Delete this workflow"]})})]})}const VDs=()=>{const{isAdmin:s}=_s();return e.jsx(Ks,{children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(TDs,{}),e.jsxs(RZ,{children:[e.jsx(ds,{index:!0,element:e.jsx(FDs,{})}),e.jsx(ds,{path:"browse",element:e.jsx(zDs,{})}),e.jsx(ds,{path:"my-apps",element:e.jsx(BDs,{})}),e.jsx(ds,{path:"connected",element:e.jsx($Ds,{})}),s&&e.jsx(ds,{path:"workflows",element:e.jsx(UDs,{})}),s&&e.jsx(ds,{path:"workflows/:runId",element:e.jsx(qDs,{})}),e.jsx(ds,{path:"*",element:e.jsx(r1,{to:"/apps",replace:!0})})]})]})})},HDs=()=>{var N;const s=Vn(),{isAdmin:t}=_s(),[n,r]=j.useState(""),[a,i]=j.useState("all"),[l,o]=j.useState("all"),[c,d]=j.useState("grid"),{data:u=[]}=ht({queryKey:["template-categories"],queryFn:async()=>{const{data:C,error:A}=await U.from("template_categories").select("*").order("name");if(A)throw A;return C}}),{data:h=[]}=ht({queryKey:["template-types"],queryFn:async()=>{const{data:C,error:A}=await U.from("template_types").select("*").order("name");if(A)throw A;return C}}),{data:m=[],isLoading:p}=ht({queryKey:["canva-templates",t],queryFn:async()=>{const{data:C,error:A}=await U.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:P}=await U.from("template_links").select("*").order("sort_order");if(P)throw P;const M=async K=>{let J=0;const ce=[];for(;;){const{data:ue,error:ne}=await K().range(J,J+1e3-1);if(ne)throw ne;if(!ue||ue.length===0||(ce.push(...ue),ue.length<1e3))break;J+=1e3}return ce},I=await M(()=>U.from("template_likes").select("template_id")),D=await M(()=>U.from("template_comments").select("template_id")),B=new Map;I.forEach(K=>{B.set(K.template_id,(B.get(K.template_id)||0)+1)});const q=new Map;D.forEach(K=>{q.set(K.template_id,(q.get(K.template_id)||0)+1)});const W=new Map;return t&&(await M(()=>U.from("content_engagement_logs").select("resource_id").eq("resource_type","template").eq("action_type","view"))).forEach(Q=>{W.set(Q.resource_id,(W.get(Q.resource_id)||0)+1)}),(C||[]).map(K=>({...K,links:(T||[]).filter(Q=>Q.template_id===K.id)||[],likesCount:B.get(K.id)||0,commentsCount:q.get(K.id)||0,viewsCount:W.get(K.id)||0}))}}),x=m.filter(C=>{var M;const A=C.name.toLowerCase().includes(n.toLowerCase())||((M=C.description)==null?void 0:M.toLowerCase().includes(n.toLowerCase())),T=a==="all"||C.category_id===a,P=l==="all"||C.type_id===l;return A&&T&&P}),g=()=>{r(""),i("all"),o("all")},y=n||a!=="all"||l!=="all",b=(N=[...m].sort((C,A)=>new Date(A.publish_date||A.created_at).getTime()-new Date(C.publish_date||C.created_at).getTime())[0])==null?void 0:N.id,v=C=>{s(`/templates/${C}`)};return e.jsx(Ks,{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(C=>C.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(Qa,{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(C=>C.is_featured).slice(0,4).map(C=>e.jsxs(_e,{className:"group overflow-hidden hover:shadow-lg transition-all duration-200 cursor-pointer relative",onClick:()=>v(C.id),children:[e.jsxs("div",{className:"aspect-[3/2] relative overflow-hidden bg-muted",children:[C.id===b&&e.jsx($e,{className:"absolute top-2 left-2 z-10 font-bold border-0 hover:opacity-90",style:{backgroundColor:"#e8c369",color:"#3d2f0a"},children:"NEW!"}),C.preview_image_url?e.jsx("img",{src:C.preview_image_url,alt:C.name,className:"w-full h-full object-cover group-hover:scale-105 transition-transform duration-300"}):e.jsx("div",{className:"w-full h-full flex items-center justify-center text-muted-foreground",children:"No Preview"})]}),e.jsxs(Oe,{className:"p-3",children:[e.jsx("h3",{className:"font-semibold text-foreground line-clamp-1 text-sm",children:C.name}),C.description&&e.jsx("p",{className:"text-xs text-muted-foreground line-clamp-2 mt-1",children:EZ(C.description)})]})]},C.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(Vr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(be,{placeholder:"Search templates...",value:n,onChange:C=>r(C.target.value),className:"pl-9"})]}),e.jsxs(vs,{value:a,onValueChange:i,children:[e.jsx(gs,{className:"w-full sm:w-48",children:e.jsx(bs,{placeholder:"All Categories"})}),e.jsxs(ys,{children:[e.jsx(Ye,{value:"all",children:"All Categories"}),u.map(C=>e.jsx(Ye,{value:C.id,children:C.name},C.id))]})]}),e.jsxs(vs,{value:l,onValueChange:o,children:[e.jsx(gs,{className:"w-full sm:w-48",children:e.jsx(bs,{placeholder:"All Types"})}),e.jsxs(ys,{children:[e.jsx(Ye,{value:"all",children:"All Types"}),h.map(C=>e.jsx(Ye,{value:C.id,children:C.name},C.id))]})]}),e.jsxs("div",{className:"flex gap-2",children:[y&&e.jsx($,{variant:"outline",size:"sm",onClick:g,children:"Clear Filters"}),e.jsxs("div",{className:"flex gap-1",children:[e.jsx($,{variant:c==="grid"?"secondary":"outline",size:"icon",onClick:()=>d("grid"),className:"rounded-full",children:e.jsx(_0,{className:"h-4 w-4"})}),e.jsx($,{variant:c==="list"?"secondary":"outline",size:"icon",onClick:()=>d("list"),className:"rounded-full",children:e.jsx(Sg,{className:"h-4 w-4"})})]})]})]}),e.jsxs("div",{className:"text-sm text-muted-foreground",children:[x.length," template",x.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((C,A)=>e.jsx(_e,{children:e.jsxs(Oe,{className:"p-4",children:[e.jsx(on,{className:"aspect-[4/3] w-full rounded-lg mb-4"}),e.jsx(on,{className:"h-5 w-3/4 mb-2"}),e.jsx(on,{className:"h-4 w-full mb-4"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(on,{className:"h-5 w-16"}),e.jsx(on,{className:"h-5 w-20"})]})]})},A))}),!p&&x.length===0&&e.jsxs("div",{className:"text-center py-12",children:[e.jsx("div",{className:"text-muted-foreground mb-4",children:y?"No templates match your filters":"No templates available yet"}),y&&e.jsx($,{variant:"outline",onClick:g,children:"Clear Filters"})]}),!p&&x.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:x.map(C=>e.jsxs(_e,{className:`group overflow-hidden hover:shadow-lg transition-all duration-200 cursor-pointer ${c==="list"?"flex flex-row":""}`,onClick:()=>v(C.id),children:[e.jsxs("div",{className:`relative overflow-hidden bg-muted ${c==="list"?"w-48 shrink-0":"aspect-[3/2]"}`,children:[C.id===b&&e.jsx($e,{className:"absolute top-2 left-2 z-10 font-bold border-0 hover:opacity-90",style:{backgroundColor:"#e8c369",color:"#3d2f0a"},children:"NEW!"}),C.preview_image_url?e.jsx("img",{src:C.preview_image_url,alt:C.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"}),C.links.length>1&&e.jsx("div",{className:"absolute top-2 right-2",children:e.jsxs($e,{variant:"secondary",className:"gap-1 bg-background/90 backdrop-blur-sm !text-secondary",children:[e.jsx(kc,{className:"h-3 w-3"}),C.links.length]})})]}),e.jsxs(Oe,{className:`p-4 flex flex-col ${c==="list"?"flex-1":""}`,children:[e.jsx("h3",{className:"font-semibold text-foreground line-clamp-1 mb-1",children:C.name}),C.description&&e.jsx("p",{className:"text-sm text-muted-foreground line-clamp-2 mb-3 flex-1",children:EZ(C.description)}),e.jsxs("div",{className:"flex flex-wrap gap-2 mb-3",children:[C.category&&e.jsx($e,{variant:"secondary",className:"text-xs",children:C.category.name}),C.type&&e.jsx($e,{variant:"outline",className:"text-xs",children:C.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(Ox,{className:"h-3.5 w-3.5"}),C.likesCount]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Ed,{className:"h-3.5 w-3.5"}),C.commentsCount]}),t&&e.jsxs("span",{className:"flex items-center gap-1",title:"Total views (admin only)",children:[e.jsx(ga,{className:"h-3.5 w-3.5"}),C.viewsCount]})]}),e.jsxs($,{size:"sm",className:"w-full gap-2",onClick:A=>{A.stopPropagation(),v(C.id)},children:[e.jsx(Tr,{className:"h-4 w-4"}),"View Template"]})]})]},C.id))})]})})};var GDs="Separator",Kct="horizontal",WDs=["horizontal","vertical"],ZLt=j.forwardRef((s,t)=>{const{decorative:n,orientation:r=Kct,...a}=s,i=KDs(r)?r:Kct,o=n?{role:"none"}:{"aria-orientation":i==="vertical"?i:void 0,role:"separator"};return e.jsx(Ka.div,{"data-orientation":i,...o,...a,ref:t})});ZLt.displayName=GDs;function KDs(s){return WDs.includes(s)}var XLt=ZLt;const Hl=j.forwardRef(({className:s,orientation:t="horizontal",decorative:n=!0,...r},a)=>e.jsx(XLt,{ref:a,decorative:n,orientation:t,className:Tt("shrink-0 bg-border",t==="horizontal"?"h-[1px] w-full":"h-full w-[1px]",s),...r}));Hl.displayName=XLt.displayName;const YDs=()=>{const{templateId:s}=Vi(),t=Vn(),{user:n,isAdmin:r}=_s(),{toast:a}=gi(),i=ts(),{trackEngagement:l}=Iq(),[o,c]=j.useState(""),{data:d,isLoading:u}=ht({queryKey:["template-detail",s],queryFn:async()=>{const{data:C,error:A}=await U.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 U.from("template_links").select("*").eq("template_id",s).order("sort_order"),{data:P}=await U.from("template_guides").select("*").eq("template_id",s).order("sort_order");return{...C,links:T||[],guides:P||[]}},enabled:!!s}),{data:h=[]}=ht({queryKey:["template-linked-toolkits",s],queryFn:async()=>{const{data:C,error:A}=await U.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(C||[]).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=[]}=ht({queryKey:["template-likes",s],queryFn:async()=>{const{data:C,error:A}=await U.from("template_likes").select("*").eq("template_id",s);if(A)throw A;return C},enabled:!!s}),{data:p=[]}=ht({queryKey:["template-comments",s],queryFn:async()=>{const{data:C,error:A}=await U.from("template_comments").select("*").eq("template_id",s).order("created_at",{ascending:!1});if(A)throw A;const T=[...new Set(C.map(I=>I.user_id))],{data:P}=await U.from("profiles").select("id, name").in("id",T),M=new Map((P==null?void 0:P.map(I=>[I.id,I.name]))||[]);return C.map(I=>({...I,user_name:M.get(I.user_id)||"Unknown User"}))},enabled:!!s}),x=yt({mutationFn:async C=>{const{error:A}=await U.from("template_comments").insert({template_id:s,user_id:n.id,content:C});if(A)throw A},onSuccess:()=>{i.invalidateQueries({queryKey:["template-comments",s]}),c(""),a({title:"Comment added!"})},onError:C=>{a({title:"Error adding comment",description:C.message,variant:"destructive"})}}),g=yt({mutationFn:async C=>{const{error:A}=await U.from("template_comments").delete().eq("id",C);if(A)throw A},onSuccess:()=>{i.invalidateQueries({queryKey:["template-comments",s]}),a({title:"Comment deleted"})}}),y=yt({mutationFn:async()=>{const C=m.find(A=>A.user_id===(n==null?void 0:n.id));if(C){const{error:A}=await U.from("template_likes").delete().eq("id",C.id);if(A)throw A}else{const{error:A}=await U.from("template_likes").insert({template_id:s,user_id:n.id});if(A)throw A}},onSuccess:()=>{i.invalidateQueries({queryKey:["template-likes",s]})}}),b=m.some(C=>C.user_id===(n==null?void 0:n.id)),v=C=>C.split(" ").map(A=>A[0]).join("").toUpperCase().slice(0,2),N=C=>{C.preventDefault(),!(!o.trim()||!n)&&x.mutate(o.trim())};return u?e.jsx(Ks,{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(Ks,{title:d.name,children:e.jsxs("div",{className:"space-y-6 max-w-5xl mx-auto",children:[e.jsx($,{variant:"ghost",size:"sm",asChild:!0,className:"gap-2",children:e.jsxs(Wn,{to:"/templates",children:[e.jsx(ka,{className:"h-4 w-4"}),"Back to Templates"]})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-start sm:justify-between gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("h1",{className:"text-2xl font-bold text-foreground",children:d.name}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[d.category&&e.jsx($e,{variant:"secondary",children:d.category.name}),d.type&&e.jsx($e,{variant:"outline",children:d.type.name})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[r&&e.jsx($,{variant:"outline",className:"gap-2 rounded-full",asChild:!0,children:e.jsxs(Wn,{to:`/admin/templates?edit=${d.id}`,children:[e.jsx(Ya,{className:"h-4 w-4"}),e.jsx("span",{children:"Edit"})]})}),e.jsx(Fq,{resourceType:"template",resourceId:d.id,resourceTitle:d.name,size:"default",className:"rounded-full"}),e.jsxs($,{variant:b?"default":"outline",className:"gap-2 rounded-full",onClick:()=>y.mutate(),disabled:!n||y.isPending,children:[e.jsx(Ox,{className:`h-4 w-4 ${b?"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(_e,{children:e.jsxs(Oe,{className:"pt-6",children:[e.jsxs("h3",{className:"font-semibold flex items-center gap-2 mb-4",children:[e.jsx(kc,{className:"h-4 w-4"}),d.links.length===1?"Template Link":"Template Links"]}),e.jsx("div",{className:"grid gap-2",children:d.links.map(C=>e.jsxs($,{variant:"outline",className:"w-full justify-between gap-2 h-auto py-3",onClick:()=>{l("template",d.id,d.name,"click_canva"),window.open(C.canva_share_link,"_blank")},children:[e.jsx("span",{className:"font-medium",children:C.title}),e.jsx(Tr,{className:"h-4 w-4 text-muted-foreground"})]},C.id))})]})}),d.video_url&&e.jsx(_e,{children:e.jsx(Oe,{className:"pt-6",children:e.jsx("div",{className:"aspect-video w-full rounded-lg overflow-hidden",children:e.jsx("iframe",{src:d.video_url,className:"w-full h-full",allow:"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture",allowFullScreen:!0})})})}),d.guides&&d.guides.length>0&&e.jsx(_e,{children:e.jsxs(Oe,{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"}),"Guide Files"]}),e.jsx("div",{className:"grid gap-2",children:d.guides.map(C=>e.jsxs($,{variant:"outline",className:"w-full justify-between gap-2 h-auto py-3",onClick:()=>{l("template",d.id,d.name,"click_pdf"),window.open(C.file_url,"_blank")},children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Wr,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"font-medium",children:C.name}),C.file_size&&e.jsxs("span",{className:"text-xs text-muted-foreground",children:["(",(C.file_size/1024).toFixed(0)," KB)"]})]}),e.jsx(di,{className:"h-4 w-4 text-muted-foreground"})]},C.id))})]})}),h.length>0&&e.jsx(_e,{children:e.jsxs(Oe,{className:"pt-6",children:[e.jsxs("h3",{className:"font-semibold flex items-center gap-2 mb-4",children:[e.jsx(Tu,{className:"h-4 w-4"}),"Related Toolkits"]}),e.jsx("div",{className:"grid gap-2",children:h.map(C=>e.jsxs($,{variant:"outline",className:"w-full justify-start gap-3 h-auto py-3",onClick:()=>t(`/toolbox/${C.id}`),children:[C.featured_image_url?e.jsx("img",{src:C.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(Tu,{className:"h-4 w-4 text-muted-foreground"})}),e.jsx("span",{className:"font-medium",children:C.name})]},C.id))})]})}),e.jsx(Hl,{}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("h3",{className:"font-semibold flex items-center gap-2 text-lg",children:[e.jsx(Ed,{className:"h-5 w-5"}),"Comments (",p.length,")"]}),n?e.jsxs("form",{onSubmit:N,className:"flex gap-2",children:[e.jsx(Is,{placeholder:"Add a comment...",value:o,onChange:C=>c(C.target.value),className:"min-h-[80px] resize-none flex-1"}),e.jsx($,{type:"submit",size:"icon",className:"h-10 w-10",disabled:!o.trim()||x.isPending,children:e.jsx(Br,{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(_e,{children:e.jsx(Oe,{className:"py-8 text-center",children:e.jsx("p",{className:"text-muted-foreground",children:"No comments yet. Be the first to share your thoughts!"})})}):p.map(C=>e.jsx(_e,{children:e.jsx(Oe,{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(C.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:C.user_name}),e.jsx("span",{className:"text-sm text-muted-foreground",children:fc(new Date(C.created_at),{addSuffix:!0})}),C.user_id===(n==null?void 0:n.id)&&e.jsx($,{variant:"ghost",size:"icon",className:"h-6 w-6 ml-auto",onClick:()=>g.mutate(C.id),children:e.jsx(Pn,{className:"h-3 w-3 text-muted-foreground"})})]}),e.jsx("p",{className:"text-sm whitespace-pre-wrap",children:C.content})]})]})})},C.id))})]})]})}):e.jsx(Ks,{title:"Templates",children:e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(kc,{className:"h-12 w-12 text-muted-foreground mb-4"}),e.jsx("h3",{className:"text-lg font-semibold",children:"Template not found"}),e.jsx("p",{className:"text-muted-foreground mt-1",children:"This template may have been removed or is not available."}),e.jsx($,{asChild:!0,className:"mt-4",children:e.jsx(Wn,{to:"/templates",children:"Back to Templates"})})]})})},Yct=({program:s,enrolled:t})=>{const{notOpenYet:n,closed:r,opensLabel:a}=XCe(s);return e.jsxs(_e,{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(dn,{className:"h-10 w-10 text-primary/60"})}),e.jsxs("div",{className:"absolute left-3 top-3 flex gap-2",children:[s.is_featured&&e.jsx($e,{className:"shadow-sm",children:"Featured"}),t&&e.jsxs($e,{variant:"secondary",className:"shadow-sm",children:[e.jsx(Fr,{className:"mr-1 h-3 w-3"})," Enrolled"]})]})]}),e.jsxs(Oe,{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(Hr,{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(Nl,{className:"h-3.5 w-3.5"}),"Starts ",gd(s.kickoff_at)]}),e.jsxs("span",{className:"inline-flex items-center gap-1.5",children:[e.jsx(qn,{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":Mp(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 ",KZ(s.duration_weeks)," — no subscription",s.charge_at?` · charged ${gd(s.charge_at)}`:""]}):null]}),e.jsx($,{asChild:!0,size:"sm",children:e.jsxs(Wn,{to:t?`/programs/${s.slug}/workspace`:`/programs/${s.slug}`,children:[t?"Open program":n?"Preview details":"View details",e.jsx(ni,{className:"ml-1.5 h-4 w-4"})]})})]})]})]})},ZDs=()=>{const{data:s=[],isLoading:t}=h6t(),{data:n=[]}=dGe(),r=new Set(n.filter(l=>rU(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(Ks,{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(on,{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(Yct,{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(_e,{className:"border-dashed",children:e.jsxs(Oe,{className:"flex flex-col items-center gap-3 p-12 text-center",children:[e.jsx(dn,{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(Yct,{program:l,enrolled:!1},l.id))})]})]})]})})},XDs=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},QDs=({url:s,headline:t,posterUrl:n})=>{const[r,a]=j.useState(!1),i=(s||"").trim();if(!i)return null;const l=XDs(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(Sh,{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 bAe="Collapsible",[JDs,QLt]=ip(bAe),[eRs,dWe]=JDs(bAe),JLt=j.forwardRef((s,t)=>{const{__scopeCollapsible:n,open:r,defaultOpen:a,disabled:i,onOpenChange:l,...o}=s,[c,d]=Ux({prop:r,defaultProp:a??!1,onChange:l,caller:bAe});return e.jsx(eRs,{scope:n,disabled:i,contentId:Fx(),open:c,onOpenToggle:j.useCallback(()=>d(u=>!u),[d]),children:e.jsx(Ka.div,{"data-state":pWe(c),"data-disabled":i?"":void 0,...o,ref:t})})});JLt.displayName=bAe;var ePt="CollapsibleTrigger",uWe=j.forwardRef((s,t)=>{const{__scopeCollapsible:n,...r}=s,a=dWe(ePt,n);return e.jsx(Ka.button,{type:"button","aria-controls":a.contentId,"aria-expanded":a.open||!1,"data-state":pWe(a.open),"data-disabled":a.disabled?"":void 0,disabled:a.disabled,...r,ref:t,onClick:xa(s.onClick,a.onOpenToggle)})});uWe.displayName=ePt;var hWe="CollapsibleContent",mWe=j.forwardRef((s,t)=>{const{forceMount:n,...r}=s,a=dWe(hWe,s.__scopeCollapsible);return e.jsx(dx,{present:n||a.open,children:({present:i})=>e.jsx(tRs,{...r,ref:t,present:i})})});mWe.displayName=hWe;var tRs=j.forwardRef((s,t)=>{const{__scopeCollapsible:n,present:r,children:a,...i}=s,l=dWe(hWe,n),[o,c]=j.useState(r),d=j.useRef(null),u=Po(t,d),h=j.useRef(0),m=h.current,p=j.useRef(0),x=p.current,g=l.open||o,y=j.useRef(g),b=j.useRef(void 0);return j.useEffect(()=>{const v=requestAnimationFrame(()=>y.current=!1);return()=>cancelAnimationFrame(v)},[]),Sf(()=>{const v=d.current;if(v){b.current=b.current||{transitionDuration:v.style.transitionDuration,animationName:v.style.animationName},v.style.transitionDuration="0s",v.style.animationName="none";const N=v.getBoundingClientRect();h.current=N.height,p.current=N.width,y.current||(v.style.transitionDuration=b.current.transitionDuration,v.style.animationName=b.current.animationName),c(r)}},[l.open,r]),e.jsx(Ka.div,{"data-state":pWe(l.open),"data-disabled":l.disabled?"":void 0,id:l.contentId,hidden:!g,...i,ref:u,style:{"--radix-collapsible-content-height":m?`${m}px`:void 0,"--radix-collapsible-content-width":x?`${x}px`:void 0,...s.style},children:g&&a})});function pWe(s){return s?"open":"closed"}var tPt=JLt,sRs=uWe,nRs=mWe,nk="Accordion",rRs=["Home","End","ArrowDown","ArrowUp","ArrowLeft","ArrowRight"],[fWe,aRs,iRs]=uq(nk),[_Ae,QXn]=ip(nk,[iRs,QLt]),xWe=QLt(),sPt=It.forwardRef((s,t)=>{const{type:n,...r}=s,a=r,i=r;return e.jsx(fWe.Provider,{scope:s.__scopeAccordion,children:n==="multiple"?e.jsx(dRs,{...i,ref:t}):e.jsx(cRs,{...a,ref:t})})});sPt.displayName=nk;var[nPt,oRs]=_Ae(nk),[rPt,lRs]=_Ae(nk,{collapsible:!1}),cRs=It.forwardRef((s,t)=>{const{value:n,defaultValue:r,onValueChange:a=()=>{},collapsible:i=!1,...l}=s,[o,c]=Ux({prop:n,defaultProp:r??"",onChange:a,caller:nk});return e.jsx(nPt,{scope:s.__scopeAccordion,value:It.useMemo(()=>o?[o]:[],[o]),onItemOpen:c,onItemClose:It.useCallback(()=>i&&c(""),[i,c]),children:e.jsx(rPt,{scope:s.__scopeAccordion,collapsible:i,children:e.jsx(aPt,{...l,ref:t})})})}),dRs=It.forwardRef((s,t)=>{const{value:n,defaultValue:r,onValueChange:a=()=>{},...i}=s,[l,o]=Ux({prop:n,defaultProp:r??[],onChange:a,caller:nk}),c=It.useCallback(u=>o((h=[])=>[...h,u]),[o]),d=It.useCallback(u=>o((h=[])=>h.filter(m=>m!==u)),[o]);return e.jsx(nPt,{scope:s.__scopeAccordion,value:l,onItemOpen:c,onItemClose:d,children:e.jsx(rPt,{scope:s.__scopeAccordion,collapsible:!0,children:e.jsx(aPt,{...i,ref:t})})})}),[uRs,wAe]=_Ae(nk),aPt=It.forwardRef((s,t)=>{const{__scopeAccordion:n,disabled:r,dir:a,orientation:i="vertical",...l}=s,o=It.useRef(null),c=Po(o,t),d=aRs(n),h=jC(a)==="ltr",m=xa(s.onKeyDown,p=>{var M;if(!rRs.includes(p.key))return;const x=p.target,g=d().filter(I=>{var D;return!((D=I.ref.current)!=null&&D.disabled)}),y=g.findIndex(I=>I.ref.current===x),b=g.length;if(y===-1)return;p.preventDefault();let v=y;const N=0,C=b-1,A=()=>{v=y+1,v>C&&(v=N)},T=()=>{v=y-1,v{const{__scopeAccordion:n,value:r,...a}=s,i=wAe(KSe,n),l=oRs(KSe,n),o=xWe(n),c=Fx(),d=r&&l.value.includes(r)||!1,u=i.disabled||s.disabled;return e.jsx(hRs,{scope:n,open:d,disabled:u,triggerId:c,children:e.jsx(tPt,{"data-orientation":i.orientation,"data-state":hPt(d),...o,...a,ref:t,disabled:u,open:d,onOpenChange:h=>{h?l.onItemOpen(r):l.onItemClose(r)}})})});iPt.displayName=KSe;var oPt="AccordionHeader",lPt=It.forwardRef((s,t)=>{const{__scopeAccordion:n,...r}=s,a=wAe(nk,n),i=gWe(oPt,n);return e.jsx(Ka.h3,{"data-orientation":a.orientation,"data-state":hPt(i.open),"data-disabled":i.disabled?"":void 0,...r,ref:t})});lPt.displayName=oPt;var Q7e="AccordionTrigger",cPt=It.forwardRef((s,t)=>{const{__scopeAccordion:n,...r}=s,a=wAe(nk,n),i=gWe(Q7e,n),l=lRs(Q7e,n),o=xWe(n);return e.jsx(fWe.ItemSlot,{scope:n,children:e.jsx(sRs,{"aria-disabled":i.open&&!l.collapsible||void 0,"data-orientation":a.orientation,id:i.triggerId,...o,...r,ref:t})})});cPt.displayName=Q7e;var dPt="AccordionContent",uPt=It.forwardRef((s,t)=>{const{__scopeAccordion:n,...r}=s,a=wAe(nk,n),i=gWe(dPt,n),l=xWe(n);return e.jsx(nRs,{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}})});uPt.displayName=dPt;function hPt(s){return s?"open":"closed"}var mRs=sPt,pRs=iPt,fRs=lPt,mPt=cPt,pPt=uPt;const JO=mRs,D6=j.forwardRef(({className:s,...t},n)=>e.jsx(pRs,{ref:n,className:Tt("border-b",s),...t}));D6.displayName="AccordionItem";const R6=j.forwardRef(({className:s,children:t,...n},r)=>e.jsx(fRs,{className:"flex",children:e.jsxs(mPt,{ref:r,className:Tt("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(_o,{className:"h-4 w-4 shrink-0 transition-transform duration-200"})]})}));R6.displayName=mPt.displayName;const O6=j.forwardRef(({className:s,children:t,...n},r)=>e.jsx(pPt,{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:Tt("pb-4 pt-0",s),children:t})}));O6.displayName=pPt.displayName;const xRs=({programId:s,opensLabel:t})=>{const{data:n,isLoading:r}=lCs(s),a=cCs(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($3,{className:"mt-0.5 h-4 w-4 shrink-0 text-primary"}),e.jsxs("div",{className:"space-y-0.5 text-sm",children:[e.jsx("p",{className:"font-semibold",children:i?"You're on the notify list":"Want a heads-up when enrollment opens?"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:i?`We'll email you the moment seats go live${t?` (${t})`:""}.`:`Seats are limited — we'll email you the moment enrollment opens${t?` ${t}`:""}.`})]})]}),e.jsxs($,{variant:i?"outline":"default",size:"sm",disabled:r||a.isPending,onClick:()=>a.mutate(!i),className:"shrink-0",children:[a.isPending?e.jsx(Ht,{className:"mr-2 h-4 w-4 animate-spin"}):i?e.jsx(oa,{className:"mr-2 h-4 w-4"}):e.jsx($3,{className:"mr-2 h-4 w-4"}),i?"You're on the list":"Notify me"]})]})},gRs=()=>{const{slug:s}=Vi(),{data:t,isLoading:n}=cGe(s),{data:r}=m6t(t==null?void 0:t.id),{data:a}=uGe(t==null?void 0:t.id),i=rU(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(Ks,{children:e.jsxs("div",{className:"mx-auto max-w-5xl space-y-6 p-8",children:[e.jsx(on,{className:"h-64 w-full rounded-xl"}),e.jsx(on,{className:"h-40 w-full rounded-xl"})]})});if(!t)return e.jsx(Ks,{children:e.jsxs("div",{className:"mx-auto max-w-2xl p-12 text-center",children:[e.jsx("h1",{className:"text-2xl font-bold",children:"Program not found"}),e.jsx("p",{className:"mt-2 text-muted-foreground",children:"This program may have been closed or unpublished."}),e.jsx($,{asChild:!0,className:"mt-6",children:e.jsx(Wn,{to:"/programs",children:"Back to Programs"})})]})});const p=typeof r=="number"&&r<=0&&!i,{notOpenYet:x,closed:g,opensLabel:y}=XCe(t),b=!i&&(p||g||x),v=i?"Open your program":x?`Enrollment opens ${gd(t.enrollment_open_at)}`:p?"Cohort is full":g?"Enrollment closed":t.payment_mode==="delayed"?"Reserve my seat":"Enroll now",N=i?`/programs/${t.slug}/workspace`:`/programs/${t.slug}/enroll`;return e.jsxs(Ks,{children:[e.jsxs(Ul,{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(QDs,{url:t.promo_video_url,headline:t.promo_video_headline,posterUrl:t.hero_image_url||t.cover_image_url}):t.hero_image_url||t.cover_image_url?e.jsx("img",{src:t.hero_image_url||t.cover_image_url,alt:`${t.name} hero`,className:"h-56 w-full object-cover md:h-72"}):e.jsx("div",{className:"h-40 w-full bg-gradient-to-br from-primary/20 via-background to-accent/20 md:h-56"})}),e.jsxs("div",{className:"space-y-6 p-6 md:p-8",children:[e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs($e,{variant:"secondary",children:[t.duration_weeks,"-week program"]}),typeof r=="number"&&!i&&e.jsx($e,{variant:r<=10?"destructive":"outline",children:r>0?`${r} of ${t.capacity} seats left`:"Full"}),i&&e.jsxs($e,{children:[e.jsx(Fr,{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":Mp(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 ",KZ(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:gd(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(yy,{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:[p7e(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:gd(t.charge_at)}),". Cancel any time before then and you won't be billed."]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"No recurring billing, no monthly installments, and no automatic renewal."})]})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[e.jsx($,{asChild:!b,size:"lg",disabled:b,children:b?e.jsx("span",{children:v}):e.jsxs(Wn,{to:N,children:[v,e.jsx(ni,{className:"ml-2 h-4 w-4"})]})}),e.jsx($,{asChild:!0,variant:"ghost",size:"lg",children:e.jsx(Wn,{to:"/programs",children:"All programs"})})]}),x&&!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(Nl,{className:"h-3.5 w-3.5"}),"Enrollment opens ",y]}),e.jsx(xRs,{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((C,A)=>e.jsxs("div",{className:"flex items-start gap-3 rounded-lg border border-border/60 p-4",children:[e.jsx(Fr,{className:"mt-0.5 h-4 w-4 shrink-0 text-primary"}),e.jsx("p",{className:"text-sm",children:C})]},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((C,A)=>e.jsx(_e,{className:"border-border/60",children:e.jsxs(Oe,{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:C.title}),e.jsx("p",{className:"text-sm text-muted-foreground",children:C.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((C,A)=>e.jsxs("li",{className:"flex items-start gap-2.5 text-sm",children:[e.jsx(dn,{className:"mt-0.5 h-4 w-4 shrink-0 text-primary"}),C]},A))})]}),(d.length>0||u.length>0)&&e.jsxs("section",{className:"grid gap-6 md:grid-cols-2",children:[d.length>0&&e.jsx(_e,{className:"border-border/60",children:e.jsxs(Oe,{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((C,A)=>e.jsxs("li",{className:"flex gap-2",children:[e.jsx(Fr,{className:"mt-0.5 h-4 w-4 shrink-0 text-primary"}),C]},A))})]})}),u.length>0&&e.jsx(_e,{className:"border-border/60",children:e.jsxs(Oe,{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((C,A)=>e.jsxs("li",{className:"flex gap-2",children:[e.jsx(Hr,{className:"mt-0.5 h-4 w-4 shrink-0"}),C]},A))})]})})]}),h.length>0&&e.jsxs("section",{className:"space-y-4",children:[e.jsx("h2",{className:"text-xl font-semibold",children:"Questions"}),e.jsx(JO,{type:"single",collapsible:!0,className:"rounded-xl border border-border/60 px-4",children:h.map((C,A)=>e.jsxs(D6,{value:`faq-${A}`,children:[e.jsx(R6,{className:"text-left text-sm font-medium",children:C.q}),e.jsx(O6,{className:"text-sm text-muted-foreground",children:C.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(Xr,{className:"mx-auto h-8 w-8 text-primary"}),e.jsx("h2",{className:"mt-4 text-2xl font-bold",children:l.closing_headline||"Ready to commit?"}),e.jsx("p",{className:"mx-auto mt-2 max-w-xl text-muted-foreground",children:l.closing_body||`Seats are capped at ${t.capacity} so every member gets attention. Reserve yours and we'll take it from there.`}),e.jsxs("div",{className:"mt-6 flex flex-wrap items-center justify-center gap-3",children:[e.jsx($,{asChild:!b,size:"lg",disabled:b,children:b?e.jsx("span",{children:v}):e.jsxs(Wn,{to:N,children:[v,e.jsx(ni,{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(qn,{className:"h-4 w-4"}),r," seats remaining"]})]}),!i&&(x?e.jsxs("p",{className:"mt-3 inline-flex items-center gap-1.5 text-xs text-muted-foreground",children:[e.jsx(Nl,{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(Nl,{className:"h-3.5 w-3.5"}),"Enrollment closes ",gd(t.enrollment_close_at)]}):null)]})]})]})},Qne=["Your business","Your content","Your goals","Reserve your seat"],yRs=()=>{const{slug:s}=Vi(),t=Vn(),[n,r]=oc(),{user:a}=_s(),{data:i,isLoading:l}=cGe(s),{data:o}=m6t(i==null?void 0:i.id),{data:c,refetch:d}=uGe(i==null?void 0:i.id),{data:u}=p6t(i==null?void 0:i.id),h=z3s(),m=B3s(),p=Y3s(),x=Z3s(),[g,y]=j.useState(0),[b,v]=j.useState(!1),[N,C]=j.useState(!1),[A,T]=j.useState(!1),[P,M]=j.useState(!1),[I,D]=j.useState(""),[B,q]=j.useState(null),W=j.useRef({}),[V,K]=j.useState({}),Q=j.useRef(!1),J=(qe,Ke)=>{W.current={...W.current,[qe]:Ke},K(W.current)};j.useEffect(()=>{Q.current||(u?(W.current={...u},K(W.current),Q.current=!0):a&&(W.current={email:a.email,...W.current},K(W.current)))},[u,a]),j.useEffect(()=>{const qe=c;!i||!(qe!=null&&qe.discount_code)||B||q({code:qe.discount_code,discount_cents:qe.discount_cents||0,amount_cents:qe.amount_cents??i.price_cents,original_cents:i.price_cents})},[c,i,B]);const ce=B?B.amount_cents:(i==null?void 0:i.price_cents)??0,ue=j.useMemo(()=>YZ(i),[i]),ne=qe=>F3s(ue,qe),ee=qe=>Jot(ue,qe)?e.jsx("span",{className:"text-destructive",children:" *"}):null,le=(qe,Ke)=>{const Ze={...W.current.extra||{},[qe]:Ke};J("extra",Ze)},he=qe=>ue.custom.filter((Ke,Ze)=>Ze%3===qe),ve=qe=>{const Ke=he(qe);if(!Ke.length)return null;const Ze=V.extra||{};return e.jsx("div",{className:"space-y-4",children:Ke.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(ui,{id:Ue.id,checked:!!Ze[Ue.id],onCheckedChange:et=>le(Ue.id,!!et)}),e.jsxs(se,{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(se,{htmlFor:Ue.id,children:[Ue.label,Ue.required&&e.jsx("span",{className:"text-destructive",children:" *"})]}),Ue.type==="long_text"?e.jsx(Is,{id:Ue.id,rows:3,value:Ze[Ue.id]||"",onChange:et=>le(Ue.id,et.target.value)}):Ue.type==="select"?e.jsxs(vs,{value:Ze[Ue.id]||"",onValueChange:et=>le(Ue.id,et),children:[e.jsx(gs,{children:e.jsx(bs,{placeholder:"Select"})}),e.jsx(ys,{children:(Ue.options||[]).map(et=>e.jsx(Ye,{value:et,children:et},et))})]}):e.jsx(be,{id:Ue.id,value:Ze[Ue.id]||"",onChange:et=>le(Ue.id,et.target.value)})]}),Ue.help&&e.jsx("p",{className:"text-xs text-muted-foreground",children:Ue.help})]},Ue.id))})},ge=qe=>{const Ke=W.current,Ze=Ge=>Ge==null||Ge===""||Ge===!1,Ue=lGe.find(Ge=>Ge.step===qe&&Jot(ue,Ge.key)&&Ze(Ge.key==="timezone"?Ke.timezone||(i==null?void 0:i.timezone):Ke[Ge.key]));if(Ue)return Ue.label;const et=Ke.extra||{},Qe=he(qe).find(Ge=>Ge.required&&Ze(et[Ge.id]));return Qe?Qe.label:null},fe=()=>{if(g<=2){const qe=ge(g);if(qe)return ae.error(`Please answer: ${qe}`)}y(qe=>qe+1)},je=async()=>{if(!(!i||!I.trim()))try{let qe=c==null?void 0:c.id;(!qe||(c==null?void 0:c.status)==="canceled")&&(qe=await m.mutateAsync(i.id));const Ke=await p.mutateAsync({enrollmentId:qe,code:I});q(Ke),D(""),await d(),ae.success(`Code applied — you save ${Mp(Ke.discount_cents,i.currency)}`)}catch(qe){ae.error(qe.message||"That code could not be applied")}},Ee=async()=>{if(!(c!=null&&c.id))return q(null);try{await x.mutateAsync(c.id),q(null),await d()}catch(qe){ae.error(qe.message||"Could not remove the code")}},Me=n.get("setup"),De=n.get("session_id"),ze=j.useRef(!1);j.useEffect(()=>{Me!=="success"||!De||!(c!=null&&c.id)||ze.current||(ze.current=!0,C(!0),(async()=>{const{data:qe,error:Ke}=await U.functions.invoke("program-enroll",{body:{action:"verify",enrollment_id:c.id,session_id:De}});if(C(!1),Ke||qe!=null&&qe.error||(qe==null?void 0:qe.success)===!1){ae.error((qe==null?void 0:qe.error)||(Ke==null?void 0:Ke.message)||"We could not confirm your card");return}await d(),n.delete("setup"),n.delete("session_id"),r(n,{replace:!0}),ae.success("Your seat is confirmed")})())},[Me,De,c==null?void 0:c.id]),j.useEffect(()=>{Me==="cancelled"&&ae.info("Checkout cancelled — your seat is held for a short while.")},[Me]);const ke=j.useMemo(()=>c&&["reserved","scheduled_for_charge","paid","completed"].includes(c.status),[c]),Xe=async()=>{if(i){if(!A||i.payment_mode!=="free"&&!P){ae.error("Please confirm the checkboxes to continue");return}v(!0);try{let qe=c==null?void 0:c.id;(!qe||(c==null?void 0:c.status)==="canceled")&&(qe=await m.mutateAsync(i.id)),await h.mutateAsync({...W.current,id:void 0,program_id:i.id,enrollment_id:qe,created_at:void 0,updated_at:void 0,user_id:void 0});const{data:Ke,error:Ze}=await U.functions.invoke("program-enroll",{body:{action:"setup",enrollment_id:qe}});if(Ze||Ke!=null&&Ke.error)throw new Error((Ke==null?void 0:Ke.error)||(Ze==null?void 0:Ze.message));if(Ke!=null&&Ke.free){await d(),ae.success("You're in"),t(`/programs/${i.slug}/workspace`);return}Ke!=null&&Ke.url&&(window.location.href=Ke.url)}catch(qe){ae.error(qe.message||"Could not start enrollment")}finally{v(!1)}}};if(l)return e.jsx(Ks,{children:e.jsxs("div",{className:"mx-auto max-w-2xl space-y-4 p-8",children:[e.jsx(on,{className:"h-10 w-1/2"}),e.jsx(on,{className:"h-64 w-full rounded-xl"})]})});if(!i)return e.jsx(Ks,{children:e.jsxs("div",{className:"mx-auto max-w-xl p-12 text-center",children:[e.jsx("h1",{className:"text-2xl font-bold",children:"Program not found"}),e.jsx($,{asChild:!0,className:"mt-6",children:e.jsx(Wn,{to:"/programs",children:"Back to Programs"})})]})});if(rU(c)&&ke&&Me!=="success")return e.jsx(Ks,{children:e.jsxs("div",{className:"mx-auto max-w-xl space-y-4 p-12 text-center",children:[e.jsx(Fr,{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 ${gd(c==null?void 0:c.charge_scheduled_at)||"the program start date"}.`}),e.jsx($,{asChild:!0,size:"lg",children:e.jsx(Wn,{to:`/programs/${i.slug}/workspace`,children:"Open your program workspace"})})]})});const Se=typeof o=="number"&&o<=0,{notOpenYet:Re,closed:Ae,opensLabel:Be}=XCe(i);return Re||Ae?e.jsx(Ks,{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:Re?"Enrollment is not open yet":"Enrollment is closed"}),e.jsx("p",{className:"text-muted-foreground",children:Re?`Enrollment for ${i.name} opens ${Be}. Come back then to reserve your seat.`:`Enrollment for ${i.name} has closed. Watch the Hub for the next cohort.`}),e.jsx($,{asChild:!0,children:e.jsx(Wn,{to:`/programs/${i.slug}`,children:"Back to program details"})})]})}):e.jsx(Ks,{children:e.jsxs("div",{className:"mx-auto w-full max-w-3xl space-y-6 p-4 md:p-8",children:[e.jsx($,{asChild:!0,variant:"ghost",size:"sm",className:"-ml-2",children:e.jsxs(Wn,{to:`/programs/${i.slug}`,children:[e.jsx(ka,{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?`${p7e(i.price_cents,i.currency,i.duration_weeks)}. Your card is saved today and charged once on ${gd(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:Qne[g]}),e.jsxs("span",{children:["Step ",g+1," of ",Qne.length]})]}),e.jsx(Ki,{value:(g+1)/Qne.length*100})]}),N&&e.jsx(_e,{className:"border-primary/40 bg-primary/5",children:e.jsxs(Oe,{className:"flex items-center gap-3 p-4 text-sm",children:[e.jsx(Ht,{className:"h-4 w-4 animate-spin text-primary"}),"Confirming your card with Stripe…"]})}),e.jsx(_e,{children:e.jsxs(Oe,{className:"space-y-5 p-6",children:[g===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}),g===0&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[ne("full_name")&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs(se,{htmlFor:"full_name",children:["Full name",ee("full_name")]}),e.jsx(be,{id:"full_name",value:V.full_name||"",onChange:qe=>J("full_name",qe.target.value)})]}),ne("phone")&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs(se,{htmlFor:"phone",children:["Mobile number",ee("phone")]}),e.jsx(be,{id:"phone",value:V.phone||"",onChange:qe=>J("phone",qe.target.value)})]}),ne("instagram_handle")&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs(se,{htmlFor:"instagram_handle",children:["Instagram handle",ee("instagram_handle")]}),e.jsx(be,{id:"instagram_handle",placeholder:"@yourhandle",value:V.instagram_handle||"",onChange:qe=>J("instagram_handle",qe.target.value)})]}),ne("city")&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs(se,{htmlFor:"city",children:["Primary city / market",ee("city")]}),e.jsx(be,{id:"city",value:V.city||"",onChange:qe=>J("city",qe.target.value)})]})]}),ne("service_areas")&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs(se,{htmlFor:"service_areas",children:["Neighborhoods or areas you serve",ee("service_areas")]}),e.jsx(Is,{id:"service_areas",rows:2,value:V.service_areas||"",onChange:qe=>J("service_areas",qe.target.value)})]}),e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[ne("years_experience")&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs(se,{children:["Years in real estate",ee("years_experience")]}),e.jsxs(vs,{value:V.years_experience||"",onValueChange:qe=>J("years_experience",qe),children:[e.jsx(gs,{children:e.jsx(bs,{placeholder:"Select"})}),e.jsx(ys,{children:["Less than 1","1-3","4-7","8-15","15+"].map(qe=>e.jsx(Ye,{value:qe,children:qe},qe))})]})]}),ne("specialty")&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs(se,{htmlFor:"specialty",children:["Specialty or niche",ee("specialty")]}),e.jsx(be,{id:"specialty",value:V.specialty||"",onChange:qe=>J("specialty",qe.target.value)})]})]}),ve(0)]}),g===1&&e.jsxs(e.Fragment,{children:[ne("target_audience")&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs(se,{htmlFor:"target_audience",children:["Who are you trying to reach?",ee("target_audience")]}),e.jsx(Is,{id:"target_audience",rows:2,placeholder:"First-time buyers, move-up sellers, investors…",value:V.target_audience||"",onChange:qe=>J("target_audience",qe.target.value)})]}),e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[ne("video_comfort")&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs(se,{children:["How comfortable are you on camera?",ee("video_comfort")]}),e.jsxs(vs,{value:V.video_comfort||"",onValueChange:qe=>J("video_comfort",qe),children:[e.jsx(gs,{children:e.jsx(bs,{placeholder:"Select"})}),e.jsx(ys,{children:["Terrified","Nervous but willing","Getting comfortable","Very comfortable"].map(qe=>e.jsx(Ye,{value:qe,children:qe},qe))})]})]}),ne("posting_frequency")&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs(se,{children:["How often do you post today?",ee("posting_frequency")]}),e.jsxs(vs,{value:V.posting_frequency||"",onValueChange:qe=>J("posting_frequency",qe),children:[e.jsx(gs,{children:e.jsx(bs,{placeholder:"Select"})}),e.jsx(ys,{children:["Never","Rarely","Weekly","A few times a week","Daily"].map(qe=>e.jsx(Ye,{value:qe,children:qe},qe))})]})]})]}),ne("content_style")&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs(se,{htmlFor:"content_style",children:["What content style feels like you?",ee("content_style")]}),e.jsx(Is,{id:"content_style",rows:2,placeholder:"Educational, funny, behind-the-scenes, luxury-polished…",value:V.content_style||"",onChange:qe=>J("content_style",qe.target.value)})]}),ne("personal_interests")&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs(se,{htmlFor:"personal_interests",children:["Interests or hobbies we can weave in",ee("personal_interests")]}),e.jsx(Is,{id:"personal_interests",rows:2,value:V.personal_interests||"",onChange:qe=>J("personal_interests",qe.target.value)})]}),ve(1)]}),g===2&&e.jsxs(e.Fragment,{children:[ne("primary_goal")&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs(se,{htmlFor:"primary_goal",children:["Your #1 goal for this program",ee("primary_goal")]}),e.jsx(Is,{id:"primary_goal",rows:3,value:V.primary_goal||"",onChange:qe=>J("primary_goal",qe.target.value)})]}),ne("topics_to_avoid")&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs(se,{htmlFor:"topics_to_avoid",children:["Anything you don't want to talk about",ee("topics_to_avoid")]}),e.jsx(Is,{id:"topics_to_avoid",rows:2,value:V.topics_to_avoid||"",onChange:qe=>J("topics_to_avoid",qe.target.value)})]}),ne("timezone")&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs(se,{children:["Your time zone",ee("timezone")]}),e.jsxs(vs,{value:V.timezone||i.timezone,onValueChange:qe=>J("timezone",qe),children:[e.jsx(gs,{children:e.jsx(bs,{placeholder:"Select"})}),e.jsx(ys,{children:["America/New_York","America/Chicago","America/Denver","America/Phoenix","America/Los_Angeles","Pacific/Honolulu"].map(qe=>e.jsx(Ye,{value:qe,children:qe.replace("America/","").replace("_"," ")},qe))})]})]}),ve(2),ne("consent_public_profile")&&e.jsxs("div",{className:"flex items-start gap-3 rounded-lg border border-border/60 p-4",children:[e.jsx(ui,{id:"consent_public_profile",checked:!!V.consent_public_profile,onCheckedChange:qe=>J("consent_public_profile",!!qe)}),e.jsx(se,{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."})]})]}),g===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":B?e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-sm font-normal text-muted-foreground line-through",children:Mp(B.original_cents,i.currency)}),Mp(ce,i.currency)]}):Mp(i.price_cents,i.currency)})]}),i.payment_mode!=="free"&&e.jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:p7e(ce,i.currency,i.duration_weeks)}),i.payment_mode!=="free"&&e.jsx("div",{className:"mt-3 border-t border-border/60 pt-3",children:B?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(Up,{className:"h-3.5 w-3.5 text-primary"}),"Code ",e.jsx("span",{className:"font-mono font-semibold",children:B.code})," applied — you save ",Mp(B.discount_cents,i.currency)]}),e.jsxs($,{variant:"ghost",size:"sm",onClick:Ee,disabled:x.isPending,children:[e.jsx(pr,{className:"mr-1 h-3.5 w-3.5"})," Remove"]})]}):e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"discount_code",className:"text-xs text-muted-foreground",children:"Have a discount code?"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(be,{id:"discount_code",placeholder:"Enter code",className:"font-mono uppercase",value:I,onChange:qe=>D(qe.target.value.toUpperCase()),onKeyDown:qe=>{qe.key==="Enter"&&(qe.preventDefault(),je())}}),e.jsx($,{variant:"outline",onClick:je,disabled:!I.trim()||p.isPending||m.isPending,children:p.isPending||m.isPending?e.jsx(Ht,{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(yy,{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:gd(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(ui,{id:"terms",checked:A,onCheckedChange:qe=>T(!!qe)}),e.jsx(se,{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(ui,{id:"charge",checked:P,onCheckedChange:qe=>M(!!qe)}),e.jsx(se,{htmlFor:"charge",className:"text-sm font-normal leading-relaxed",children:i.payment_mode==="delayed"?`I authorize LevelUp to charge my saved card one time — ${Mp(ce,i.currency)} for the ${KZ(i.duration_weeks)} — on ${gd(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 — ${Mp(ce,i.currency)} for the ${KZ(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(j0,{className:"h-3.5 w-3.5"}),"Card details are handled by Stripe — LevelUp never sees or stores them."]})]}),e.jsxs("div",{className:"flex items-center justify-between border-t border-border/60 pt-5",children:[e.jsxs($,{variant:"ghost",onClick:()=>y(qe=>Math.max(0,qe-1)),disabled:g===0||b,children:[e.jsx(ka,{className:"mr-1.5 h-4 w-4"})," Back"]}),gString(s).padStart(2,"0"),tIe=s=>s.toISOString().replace(/[-:]/g,"").split(".")[0]+"Z",vRs=({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:${tIe(new Date)}`,`DTSTART:${tIe(d)}`,`DTEND:${tIe(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:eIe(i.hours)},{label:"Minutes",value:eIe(i.minutes)},{label:"Seconds",value:eIe(i.seconds)}];return e.jsxs(_e,{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(Oe,{className:"relative space-y-6 p-6 md:p-9",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs($e,{className:"gap-1.5",children:[e.jsx(dn,{className:"h-3.5 w-3.5"})," Your seat is confirmed"]}),e.jsxs($e,{variant:"outline",className:"gap-1.5",children:[e.jsx(Hr,{className:"h-3.5 w-3.5"})," ",l]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("h2",{className:"text-2xl font-bold tracking-tight md:text-3xl",children:i.done?"We're live — let's go":`${s.name} kicks off soon`}),e.jsx("p",{className:"max-w-2xl text-sm text-muted-foreground md:text-base",children:i.done?"The kickoff call is starting. Head to your sessions below to join.":"Everything unlocks on kickoff day. Until then, get your setup dialed in so week one is pure momentum."})]}),e.jsx("div",{className:"grid max-w-xl grid-cols-4 gap-2 md:gap-3",children:c.map(d=>e.jsxs("div",{className:"rounded-xl border bg-background/80 px-2 py-4 text-center backdrop-blur-sm",children:[e.jsx("div",{className:"text-2xl font-bold tabular-nums tracking-tight md:text-4xl",children:d.value}),e.jsx("div",{className:"mt-1 text-[10px] uppercase tracking-widest text-muted-foreground md:text-xs",children:d.label})]},d.label))}),e.jsx("div",{className:"flex flex-wrap gap-3",children:e.jsxs($,{onClick:o,size:"lg",children:[e.jsx(gg,{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(Fr,{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))})]})]})},sIe=s=>s.toISOString().replace(/[-:]/g,"").split(".")[0]+"Z",bRs=(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:${sIe(new Date)}`,`DTSTART:${sIe(n)}`,`DTEND:${sIe(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)},_Rs={pdf:Wr,document:PN,checklist:Jh,template_link:nw,video:lh,external:Dc},wRs=()=>{var he;const{slug:s}=Vi(),[t]=oc(),{isAdmin:n}=_s(),r=n?t.get("as"):null,a=t.get("name")||"this member",i=n&&(t.get("preview")==="1"||!!r),{data:l,isLoading:o}=cGe(s),{data:c}=uGe(l==null?void 0:l.id),{data:d,isLoading:u}=$3s(l==null?void 0:l.id,r),h=U3s(l==null?void 0:l.id),m=q3s(l==null?void 0:l.id),p=V3s(l==null?void 0:l.id),x=H3s(l==null?void 0:l.id),{data:g}=p6t(l==null?void 0:l.id),y=!!(l!=null&&l.kickoff_at)&&new Date(l.kickoff_at).getTime()>Date.now(),[b,v]=j.useState(!1),[N,C]=j.useState({title:"",instagram_url:""}),[A,T]=j.useState({}),[P,M]=j.useState(null),I=j.useMemo(()=>{if(!(l!=null&&l.kickoff_at))return 1;const ve=Math.floor((Date.now()-new Date(l.kickoff_at).getTime())/864e5);return Math.min(Math.max(Math.floor(ve/7)+1,1),l.duration_weeks)},[l]),D=new Set(((d==null?void 0:d.completions)||[]).map(ve=>ve.lesson_id)),B=(d==null?void 0:d.lessons)||[],q=B.length?Math.round(D.size/B.length*100):0,W=((d==null?void 0:d.videoLogs)||[]).filter(ve=>ve.week_number===I).length,V=((d==null?void 0:d.videoLogs)||[]).length,K=(l==null?void 0:l.weekly_video_goal)||3,Q=j.useMemo(()=>{const ve=new Map;((d==null?void 0:d.videoLogs)||[]).forEach(fe=>ve.set(fe.week_number,(ve.get(fe.week_number)||0)+1));let ge=0;for(let fe=I;fe>=1;fe--)if((ve.get(fe)||0)>=K)ge++;else if(fe!==I)break;return ge},[d==null?void 0:d.videoLogs,I,K]);if(o||u)return e.jsx(Ks,{children:e.jsxs("div",{className:"mx-auto max-w-6xl space-y-6 p-8",children:[e.jsx(on,{className:"h-28 w-full rounded-xl"}),e.jsx(on,{className:"h-64 w-full rounded-xl"})]})});if(!l)return e.jsx(Ks,{children:e.jsxs("div",{className:"mx-auto max-w-xl p-12 text-center",children:[e.jsx("h1",{className:"text-2xl font-bold",children:"Program not found"}),e.jsx($,{asChild:!0,className:"mt-6",children:e.jsx(Wn,{to:"/programs",children:"Back to Programs"})})]})});if(!rU(c)&&!i)return e.jsx(Ks,{children:e.jsxs("div",{className:"mx-auto max-w-xl space-y-4 p-12 text-center",children:[e.jsx("h1",{className:"text-2xl font-bold",children:"You're not enrolled yet"}),e.jsxs("p",{className:"text-muted-foreground",children:["Reserve your seat in ",l.name," to unlock the roadmap, lessons and mastermind sessions."]}),e.jsx($,{asChild:!0,size:"lg",children:e.jsx(Wn,{to:`/programs/${l.slug}`,children:"View the program"})})]})});const J=((d==null?void 0:d.events)||[]).filter(ve=>new Date(ve.starts_at)>=new Date),ce=((d==null?void 0:d.events)||[]).filter(ve=>new Date(ve.starts_at)ve.is_pinned),ee=[...(d==null?void 0:d.myResources)||[],...(d==null?void 0:d.resources)||[]].reduce((ve,ge)=>{const fe=ge.user_id?`Just for you · ${ge.category}`:ge.category;return(ve[fe]||(ve[fe]=[])).push(ge),ve},{}),le=((d==null?void 0:d.progress)||[]).find(ve=>ve.week_number===I)||{};return e.jsx(Ks,{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||!rU(c))&&e.jsx(_e,{className:"border-primary/40 bg-primary/5",children:e.jsxs(Oe,{className:"flex flex-wrap items-center justify-between gap-3 p-4 text-sm",children:[e.jsx("span",{children:r?e.jsxs(e.Fragment,{children:[e.jsx("strong",{children:"Admin view"})," — you're seeing ",a,"'s dashboard exactly as they see it (progress, check-ins, videos and personal resources). It's read-only: avoid logging videos or check-ins here."]}):e.jsxs(e.Fragment,{children:[e.jsx("strong",{children:"Admin preview"})," — this is exactly what an enrollee sees. Your own progress, check-ins and video logs are empty because you're not enrolled."]})}),e.jsx($,{variant:"outline",size:"sm",asChild:!0,children:e.jsx(Wn,{to:"/admin/programs",children:"Back to Programs admin"})})]})}),e.jsxs("header",{className:"space-y-3",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs($e,{variant:"secondary",children:["Week ",I," of ",l.duration_weeks]}),(c==null?void 0:c.status)==="scheduled_for_charge"&&c.charge_scheduled_at&&e.jsxs($e,{variant:"outline",children:["Billing ",gd(c.charge_scheduled_at)]}),(c==null?void 0:c.status)==="payment_failed"&&e.jsx($e,{variant:"destructive",children:"Payment issue"})]}),e.jsx("p",{className:"neon-eyebrow font-semibold",children:"LevelUp Program"}),e.jsx("h1",{className:"neon-title w-fit text-4xl font-black uppercase tracking-tight md:text-5xl",children:l.name}),l.subtitle&&e.jsx("p",{className:"text-muted-foreground",children:l.subtitle})]}),y&&e.jsx(vRs,{program:l,intakeComplete:!!g}),e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2 lg:grid-cols-4",children:[e.jsx(_e,{className:"neon-topline",children:e.jsxs(Oe,{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(Mu,{className:"h-3.5 w-3.5 text-primary"})," This week"]}),e.jsxs("p",{className:"neon-stat text-3xl font-black",children:[W,e.jsxs("span",{className:"text-base font-normal text-muted-foreground",children:[" / ",K]})]}),e.jsx(Ki,{value:Math.min(W/K*100,100),className:"h-1.5"})]})}),e.jsx(_e,{className:"neon-topline",children:e.jsxs(Oe,{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(lh,{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(_e,{className:"neon-topline",children:e.jsxs(Oe,{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(yd,{className:"h-3.5 w-3.5 text-primary"})," Streak"]}),e.jsxs("p",{className:"neon-stat text-3xl font-black",children:[Q," wk"]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"hitting your goal"})]})}),e.jsx(_e,{className:"neon-topline",children:e.jsxs(Oe,{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(Il,{className:"h-3.5 w-3.5 text-primary"})," Curriculum"]}),e.jsxs("p",{className:"neon-stat text-3xl font-black",children:[q,"%"]}),e.jsx(Ki,{value:q,className:"h-1.5"})]})})]}),e.jsxs("div",{className:"flex flex-wrap gap-3",children:[e.jsxs(Os,{open:b,onOpenChange:v,children:[e.jsx(Ko,{asChild:!0,children:e.jsxs($,{children:[e.jsx(sn,{className:"mr-1.5 h-4 w-4"})," Log a video"]})}),e.jsxs(Rs,{children:[e.jsx(Us,{children:e.jsx(zs,{children:"Log a posted video"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"v-title",children:"What was it about?"}),e.jsx(be,{id:"v-title",value:N.title,onChange:ve=>C(ge=>({...ge,title:ve.target.value}))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"v-url",children:"Instagram link (optional)"}),e.jsx(be,{id:"v-url",placeholder:"https://instagram.com/reel/…",value:N.instagram_url,onChange:ve=>C(ge=>({...ge,instagram_url:ve.target.value}))})]})]}),e.jsx(kr,{children:e.jsx($,{onClick:async()=>{await m.mutateAsync({week_number:I,...N}),C({title:"",instagram_url:""}),v(!1)},children:"Log video"})})]})]}),((he=J[0])==null?void 0:he.meeting_link)&&e.jsx($,{variant:"outline",asChild:!0,children:e.jsxs("a",{href:J[0].meeting_link,target:"_blank",rel:"noreferrer",children:[e.jsx(Sh,{className:"mr-1.5 h-4 w-4"})," Join next session"]})})]}),ue.length>0&&e.jsx(_e,{className:"border-primary/30 bg-primary/5",children:e.jsx(Oe,{className:"space-y-3 p-5",children:ue.map(ve=>e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(Eh,{className:"mt-0.5 h-4 w-4 shrink-0 text-primary"}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:ve.title}),ve.body&&e.jsx("p",{className:"text-sm text-muted-foreground",children:ve.body})]})]},ve.id))})}),e.jsxs(ua,{defaultValue:"roadmap",children:[e.jsxs(ha,{className:"flex w-full flex-wrap justify-start",children:[e.jsx(Qt,{value:"roadmap",children:"Roadmap"}),e.jsx(Qt,{value:"lessons",children:"Lessons"}),e.jsx(Qt,{value:"checkin",children:"Weekly check-in"}),e.jsx(Qt,{value:"events",children:"Sessions"}),e.jsx(Qt,{value:"resources",children:"Resources"}),e.jsx(Qt,{value:"profile",children:"Profile review"})]}),e.jsxs(Jt,{value:"roadmap",className:"mt-6 space-y-4",children:[((d==null?void 0:d.weeks)||[]).length===0&&e.jsx("p",{className:"text-sm text-muted-foreground",children:"The roadmap will appear here before kickoff."}),((d==null?void 0:d.weeks)||[]).map(ve=>{const ge=ve.release_at&&new Date(ve.release_at)>new Date;return e.jsx(_e,{className:ge?"opacity-60":ve.week_number===I?"border-primary/50":"",children:e.jsxs(Oe,{className:"space-y-2 p-5",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs($e,{variant:"outline",children:["Week ",ve.week_number]}),e.jsx("span",{className:"text-xs uppercase tracking-wide text-muted-foreground",children:ve.phase}),ve.week_number===I&&e.jsx($e,{children:"Current"}),ge&&e.jsxs("span",{className:"inline-flex items-center gap-1 text-xs text-muted-foreground",children:[e.jsx(Hr,{className:"h-3 w-3"})," Unlocks ",gd(ve.release_at)]})]}),e.jsx("h3",{className:"font-semibold",children:ve.title}),ve.learning_goal&&e.jsx("p",{className:"text-sm text-muted-foreground",children:ve.learning_goal}),!ge&&Array.isArray(ve.tasks)&&ve.tasks.length>0&&e.jsx("ul",{className:"mt-2 space-y-1.5",children:ve.tasks.map((fe,je)=>e.jsxs("li",{className:"flex items-start gap-2 text-sm",children:[e.jsx(Fr,{className:"mt-0.5 h-3.5 w-3.5 shrink-0 text-primary"}),typeof fe=="string"?fe:fe.label]},je))})]})},ve.id)})]}),e.jsxs(Jt,{value:"lessons",className:"mt-6 space-y-3",children:[B.length===0&&e.jsx("p",{className:"text-sm text-muted-foreground",children:"Lessons unlock as the program progresses."}),B.map(ve=>{const ge=f6t(ve.video_url),fe=P===ve.id;return e.jsx(_e,{children:e.jsxs(Oe,{className:"space-y-4 p-5",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-4",children:[e.jsx(ui,{checked:D.has(ve.id),onCheckedChange:je=>h.mutate({lessonId:ve.id,done:!!je}),"aria-label":`Mark ${ve.title} complete`}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:"font-medium",children:ve.title}),ve.summary&&e.jsx("p",{className:"text-sm text-muted-foreground",children:ve.summary}),ve.action_assignment&&e.jsxs("p",{className:"mt-1 text-xs text-primary",children:["Action: ",ve.action_assignment]})]}),ve.duration_minutes&&e.jsxs("span",{className:"inline-flex items-center gap-1 text-xs text-muted-foreground",children:[e.jsx(Hr,{className:"h-3 w-3"})," ",ve.duration_minutes," min"]}),e.jsxs("div",{className:"flex gap-2",children:[ve.video_url&&(ge||bY(ve.video_url))&&e.jsxs($,{size:"sm",variant:"outline",onClick:()=>M(fe?null:ve.id),children:[e.jsx(Sh,{className:"mr-1.5 h-3.5 w-3.5"})," ",fe?"Close":"Watch"]}),ve.video_url&&!ge&&!bY(ve.video_url)&&e.jsx($,{size:"sm",variant:"outline",asChild:!0,children:e.jsxs("a",{href:ve.video_url,target:"_blank",rel:"noreferrer",children:[e.jsx(Sh,{className:"mr-1.5 h-3.5 w-3.5"})," Watch"]})}),ve.worksheet_url&&e.jsx($,{size:"sm",variant:"ghost",asChild:!0,children:e.jsxs("a",{href:ve.worksheet_url,target:"_blank",rel:"noreferrer",children:[e.jsx(di,{className:"mr-1.5 h-3.5 w-3.5"})," Worksheet"]})})]})]}),fe&&ge&&e.jsx("div",{className:"overflow-hidden rounded-lg border border-border/60",children:e.jsx("iframe",{src:ge,title:ve.title,className:"aspect-video w-full",allow:"accelerometer; autoplay; clipboard-write; encrypted-media; picture-in-picture",allowFullScreen:!0})}),fe&&!ge&&bY(ve.video_url)&&e.jsx("div",{className:"overflow-hidden rounded-lg border border-border/60 bg-black",children:e.jsx("video",{src:ve.video_url,controls:!0,autoPlay:!0,className:"aspect-video w-full"})})]})},ve.id)})]}),e.jsx(Jt,{value:"checkin",className:"mt-6",children:e.jsx(_e,{children:e.jsxs(Oe,{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(([ve,ge])=>e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:ve,children:ge}),e.jsx(be,{id:ve,type:"number",min:0,defaultValue:le[ve]??"",onChange:fe=>T(je=>({...je,[ve]:Number(fe.target.value)}))})]},ve))}),[["biggest_win","Biggest win"],["biggest_challenge","Biggest challenge"],["what_to_improve","What you’ll change next week"]].map(([ve,ge])=>e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:ve,children:ge}),e.jsx(Is,{id:ve,rows:2,defaultValue:le[ve]??"",onChange:fe=>T(je=>({...je,[ve]:fe.target.value}))})]},ve)),e.jsx($,{onClick:()=>p.mutate({week_number:I,goal_videos:K,...A}),children:"Save check-in"})]})})}),e.jsxs(Jt,{value:"events",className:"mt-6 space-y-4",children:[J.length===0&&ce.length===0&&e.jsx("p",{className:"text-sm text-muted-foreground",children:"Sessions will be scheduled before kickoff."}),J.map(ve=>e.jsx(_e,{className:"border-primary/30",children:e.jsxs(Oe,{className:"flex flex-wrap items-center gap-4 p-5",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx($e,{variant:"secondary",className:"capitalize",children:String(ve.event_kind).replace("_"," ")}),e.jsxs("span",{className:"inline-flex items-center gap-1 text-xs text-muted-foreground",children:[e.jsx(Nl,{className:"h-3 w-3"})," ",gd(ve.starts_at,!0)]})]}),e.jsx("p",{className:"mt-1.5 font-medium",children:ve.title}),ve.speaker&&e.jsxs("p",{className:"text-sm text-muted-foreground",children:["with ",ve.speaker]}),ve.description&&e.jsx("p",{className:"mt-1 text-sm text-muted-foreground",children:ve.description})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx($,{size:"sm",variant:"outline",onClick:()=>x.mutate({eventId:ve.id,optIn:!0}),children:"Remind me"}),e.jsxs($,{size:"sm",variant:"ghost",onClick:()=>bRs(ve,l.name),children:[e.jsx(Nl,{className:"mr-1.5 h-3.5 w-3.5"})," Add to calendar"]}),ve.meeting_link&&e.jsx($,{size:"sm",asChild:!0,children:e.jsxs("a",{href:ve.meeting_link,target:"_blank",rel:"noreferrer",children:["Join ",e.jsx(Tr,{className:"ml-1.5 h-3.5 w-3.5"})]})})]})]})},ve.id)),ce.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"}),ce.map(ve=>e.jsx(_e,{children:e.jsxs(Oe,{className:"flex flex-wrap items-center gap-4 p-5",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:"font-medium",children:ve.title}),e.jsx("p",{className:"text-xs text-muted-foreground",children:gd(ve.starts_at,!0)})]}),ve.replay_url?e.jsx($,{size:"sm",variant:"outline",asChild:!0,children:e.jsxs("a",{href:ve.replay_url,target:"_blank",rel:"noreferrer",children:[e.jsx(Sh,{className:"mr-1.5 h-3.5 w-3.5"})," Watch replay"]})}):e.jsx("span",{className:"text-xs text-muted-foreground",children:"Replay coming soon"})]})},ve.id))]})]}),e.jsxs(Jt,{value:"resources",className:"mt-6 space-y-8",children:[Object.keys(ee).length===0&&e.jsx(_e,{className:"border-dashed",children:e.jsxs(Oe,{className:"flex flex-col items-center gap-2 p-12 text-center",children:[e.jsx(Wr,{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(ee).map(([ve,ge])=>e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("h3",{className:"text-sm font-semibold uppercase tracking-[0.18em] text-muted-foreground",children:ve}),e.jsx("span",{className:"h-px flex-1 bg-border"}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:[ge.length," item",ge.length===1?"":"s"]})]}),e.jsx("div",{className:"grid gap-4 md:grid-cols-2 xl:grid-cols-3",children:ge.map(fe=>{const je=_ee(fe),Ee=_Rs[fe.resource_kind]||Wr;return e.jsxs("div",{role:"button",tabIndex:0,onClick:()=>je&&_Y(fe),onKeyDown:Me=>{je&&(Me.key==="Enter"||Me.key===" ")&&(Me.preventDefault(),_Y(fe))},className:"group relative flex cursor-pointer flex-col gap-3 overflow-hidden rounded-2xl border border-border/60 bg-card p-5 transition-all hover:-translate-y-0.5 hover:border-primary/50 hover:shadow-lg",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsx("div",{className:"flex h-11 w-11 items-center justify-center rounded-xl bg-primary/10 text-primary",children:e.jsx(Ee,{className:"h-5 w-5"})}),e.jsx($e,{variant:"secondary",className:"capitalize",children:String(fe.resource_kind).replace("_"," ")})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx("p",{className:"font-semibold leading-snug",children:fe.title}),fe.description&&e.jsx("p",{className:"line-clamp-3 text-sm text-muted-foreground",children:fe.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(Tr,{className:"h-3.5 w-3.5"})," Open"]}),fe.file_path&&e.jsxs("button",{type:"button",onClick:Me=>{Me.stopPropagation(),_Y(fe,"download")},className:"inline-flex items-center gap-1.5 text-sm font-medium text-muted-foreground hover:text-primary",children:[e.jsx(di,{className:"h-3.5 w-3.5"})," Download"]})]})]},fe.id)})})]},ve))]}),e.jsx(Jt,{value:"profile",className:"mt-6",children:e.jsx(_e,{children:e.jsxs(Oe,{className:"space-y-4 p-6",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Qh,{className:"h-5 w-5 text-primary"}),e.jsx("h3",{className:"font-semibold",children:"Your profile review"})]}),!(d!=null&&d.analysis)||d.analysis.status==="not_submitted"?e.jsx("p",{className:"text-sm text-muted-foreground",children:"Your Instagram review hasn't been submitted yet. Your coach will request screenshots during onboarding week."}):d.analysis.status==="in_review"?e.jsx("p",{className:"text-sm text-muted-foreground",children:"Your profile is in review — you'll get a notification when the report is ready."}):e.jsxs("div",{className:"space-y-4",children:[d.analysis.scores&&Object.keys(d.analysis.scores).length>0&&e.jsx("div",{className:"grid gap-3 sm:grid-cols-2",children:Object.entries(d.analysis.scores).map(([ve,ge])=>e.jsxs("div",{className:"space-y-1 rounded-lg border border-border/60 p-3",children:[e.jsxs("div",{className:"flex justify-between text-sm",children:[e.jsx("span",{className:"capitalize",children:ve.replace(/_/g," ")}),e.jsxs("span",{className:"font-semibold",children:[ge,"/10"]})]}),e.jsx(Ki,{value:Number(ge)*10,className:"h-1.5"})]},ve))}),Array.isArray(d.analysis.top_priorities)&&d.analysis.top_priorities.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{className:"text-sm font-semibold",children:"Top priorities"}),e.jsx("ul",{className:"space-y-1.5",children:d.analysis.top_priorities.map((ve,ge)=>e.jsxs("li",{className:"flex items-start gap-2 text-sm",children:[e.jsx(pu,{className:"mt-0.5 h-3.5 w-3.5 shrink-0 text-primary"}),typeof ve=="string"?ve:ve.label]},ge))})]}),d.analysis.member_notes&&e.jsx("div",{className:"rounded-lg border border-border/60 bg-muted/30 p-4 text-sm leading-relaxed whitespace-pre-line",children:d.analysis.member_notes}),d.analysis.report_url&&e.jsx($,{variant:"outline",asChild:!0,children:e.jsxs("a",{href:d.analysis.report_url,target:"_blank",rel:"noreferrer",children:[e.jsx(di,{className:"mr-1.5 h-4 w-4"})," Download full report"]})})]})]})})})]})]})})})},Va=j.forwardRef(({className:s,...t},n)=>e.jsx("div",{className:"relative w-full overflow-auto",children:e.jsx("table",{ref:n,className:Tt("w-full caption-bottom text-sm",s),...t})}));Va.displayName="Table";const Ha=j.forwardRef(({className:s,...t},n)=>e.jsx("thead",{ref:n,className:Tt("[&_tr]:border-b",s),...t}));Ha.displayName="TableHeader";const Ga=j.forwardRef(({className:s,...t},n)=>e.jsx("tbody",{ref:n,className:Tt("[&_tr:last-child]:border-0",s),...t}));Ga.displayName="TableBody";const jRs=j.forwardRef(({className:s,...t},n)=>e.jsx("tfoot",{ref:n,className:Tt("border-t bg-muted/50 font-medium [&>tr]:last:border-b-0",s),...t}));jRs.displayName="TableFooter";const hn=j.forwardRef(({className:s,...t},n)=>e.jsx("tr",{ref:n,className:Tt("border-b transition-colors data-[state=selected]:bg-muted hover:bg-muted/50",s),...t}));hn.displayName="TableRow";const Lt=j.forwardRef(({className:s,...t},n)=>e.jsx("th",{ref:n,className:Tt("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:Tt("p-4 align-middle [&:has([role=checkbox])]:pr-0",s),...t}));gt.displayName="TableCell";const NRs=j.forwardRef(({className:s,...t},n)=>e.jsx("caption",{ref:n,className:Tt("mt-4 text-sm text-muted-foreground",s),...t}));NRs.displayName="TableCaption";const Jne=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())}`},ere=s=>s?new Date(s).toISOString():null,nIe=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:Jne(s.enrollment_open_at),enrollment_close_at:Jne(s.enrollment_close_at),kickoff_at:Jne(s.kickoff_at),charge_at:Jne(s.charge_at),status:s.status||"draft",is_public:!!s.is_public,is_featured:!!s.is_featured,sort_order:s.sort_order??0}),kRs=({program:s,onSaved:t})=>{const[n,r]=j.useState(()=>nIe(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(nIe(s)),i(!1)},[s.id,s.updated_at]);const m=(y,b)=>{r(v=>({...v,[y]:b})),i(!0)},p=async(y,b)=>{if(!y.type.startsWith("image/")){ae.error("Please choose an image file");return}if(y.size>8*1024*1024){ae.error("Image must be under 8MB");return}d(b);try{const v=y.name.split(".").pop()||"jpg",N=`programs/${s.id}/${b}-${Date.now()}.${v}`,{error:C}=await U.storage.from("event-images").upload(N,y,{cacheControl:"31536000",upsert:!0});if(C)throw C;const{data:A}=U.storage.from("event-images").getPublicUrl(N);m(b==="cover"?"cover_image_url":"hero_image_url",A.publicUrl),ae.success(`${b==="cover"?"Cover":"Hero"} image uploaded — remember to save`)}catch(v){ae.error(v.message||"Upload failed")}finally{d(null)}},x=async()=>{if(!n.name.trim())return ae.error("Program name is required");if(!n.slug.trim())return ae.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:ere(n.enrollment_open_at),enrollment_close_at:ere(n.enrollment_close_at),kickoff_at:ere(n.kickoff_at),charge_at:ere(n.charge_at),status:n.status,is_public:n.is_public,is_featured:n.is_featured,sort_order:Math.round(n.sort_order)},{error:b}=await U.from("programs").update(y).eq("id",s.id);if(b)throw b;ae.success("Program saved"),i(!1),t()}catch(y){ae.error(y.message||"Could not save the program")}finally{o(!1)}},g=({kind:y,label:b,hint:v})=>{const N=y==="cover"?n.cover_image_url:n.hero_image_url,C=y==="cover"?u:h;return e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:b}),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:`${b} 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 ${b}`,children:e.jsx(pr,{className:"h-3.5 w-3.5"})})]}):e.jsxs("div",{className:"flex h-full w-full flex-col items-center justify-center gap-1 text-muted-foreground",children:[e.jsx(x1,{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:C,type:"file",accept:"image/*",className:"hidden",onChange:A=>{var P;const T=(P=A.target.files)==null?void 0:P[0];T&&p(T,y),A.target.value=""}}),e.jsxs($,{type:"button",variant:"outline",size:"sm",onClick:()=>{var A;return(A=C.current)==null?void 0:A.click()},disabled:c===y,children:[c===y?e.jsx(Ht,{className:"mr-1.5 h-4 w-4 animate-spin"}):e.jsx(si,{className:"mr-1.5 h-4 w-4"}),"Upload image"]}),e.jsx(be,{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:v})]})]})]})};return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"sticky top-0 z-10 -mx-1 flex flex-wrap items-center justify-between gap-3 rounded-lg border border-border bg-background/95 px-4 py-3 backdrop-blur",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:a?"You have unsaved changes.":"All changes saved."}),e.jsxs("div",{className:"flex gap-2",children:[a&&e.jsx($,{variant:"ghost",onClick:()=>{r(nIe(s)),i(!1)},children:"Discard"}),e.jsxs($,{onClick:x,disabled:l||!a,children:[l?e.jsx(Ht,{className:"mr-1.5 h-4 w-4 animate-spin"}):e.jsx(Jo,{className:"mr-1.5 h-4 w-4"}),"Save changes"]})]})]}),e.jsx(_e,{children:e.jsxs(Oe,{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(se,{children:"Program name"}),e.jsx(be,{value:n.name,onChange:y=>m("name",y.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Slug (public URL)"}),e.jsx(be,{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(se,{children:"Subtitle"}),e.jsx(be,{value:n.subtitle,onChange:y=>m("subtitle",y.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Tagline"}),e.jsx(be,{value:n.tagline,onChange:y=>m("tagline",y.target.value)})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Short description (cards & previews)"}),e.jsx(Is,{rows:2,value:n.short_description,onChange:y=>m("short_description",y.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Full program description (sales page)"}),e.jsx(Is,{rows:8,value:n.description,onChange:y=>m("description",y.target.value)})]})]})}),e.jsx(_e,{children:e.jsxs(Oe,{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(g,{kind:"cover",label:"Program cover image",hint:"Shown on the Programs list and enrollment cards. 1200×630 works great."}),e.jsx(g,{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(se,{children:"Promo video URL (optional)"}),e.jsx(be,{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(be,{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(se,{children:"Accent color"}),e.jsx(be,{placeholder:"#406E71",value:n.accent_color,onChange:y=>m("accent_color",y.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Sort order"}),e.jsx(be,{type:"number",value:n.sort_order,onChange:y=>m("sort_order",Number(y.target.value))})]})]})]})}),e.jsx(_e,{children:e.jsxs(Oe,{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(se,{children:"One-time price (USD)"}),e.jsx(be,{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(se,{children:"Seats (capacity)"}),e.jsx(be,{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(se,{children:"Billing mode"}),e.jsxs(vs,{value:n.payment_mode,onValueChange:y=>m("payment_mode",y),children:[e.jsx(gs,{children:e.jsx(bs,{})}),e.jsxs(ys,{children:[e.jsx(Ye,{value:"delayed",children:"Save card, charge once later"}),e.jsx(Ye,{value:"immediate",children:"Charge once at checkout"}),e.jsx(Ye,{value:"free",children:"Free / included"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Charge date (one-time)"}),e.jsx(be,{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(se,{children:"Payment grace days"}),e.jsx(be,{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(se,{children:"Currency"}),e.jsx(be,{value:n.currency,onChange:y=>m("currency",y.target.value)})]})]})]})}),e.jsx(_e,{children:e.jsxs(Oe,{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(se,{children:"Enrollment opens"}),e.jsx(be,{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(se,{children:"Enrollment closes"}),e.jsx(be,{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(se,{children:"Kickoff"}),e.jsx(be,{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(se,{children:"Length (weeks)"}),e.jsx(be,{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(se,{children:"Videos per week goal"}),e.jsx(be,{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(se,{children:"Timezone"}),e.jsx(be,{value:n.timezone,onChange:y=>m("timezone",y.target.value)})]})]})]})}),e.jsx(_e,{children:e.jsxs(Oe,{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(se,{children:"Status"}),e.jsxs(vs,{value:n.status,onValueChange:y=>m("status",y),children:[e.jsx(gs,{className:"sm:max-w-xs",children:e.jsx(bs,{})}),e.jsxs(ys,{children:[e.jsx(Ye,{value:"draft",children:"Draft (hidden)"}),e.jsx(Ye,{value:"published",children:"Published (members can enroll)"}),e.jsx(Ye,{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(Tn,{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(Tn,{checked:n.is_public,onCheckedChange:y=>m("is_public",y)})]})]})}),e.jsx("div",{className:"flex justify-end pb-4",children:e.jsxs($,{onClick:x,disabled:l||!a,size:"lg",children:[l?e.jsx(Ht,{className:"mr-1.5 h-4 w-4 animate-spin"}):e.jsx(Jo,{className:"mr-1.5 h-4 w-4"}),"Save changes"]})})]})},Zct={title:"",description:"",category:"Personal",resource_kind:"pdf",url:"",file_path:"",status:"published",sort_order:0},SRs=({programId:s,userId:t,memberName:n})=>{const{data:r=[],isLoading:a}=aCs(s,t),i=iCs(s,t),l=oCs(),[o,c]=j.useState(!1),[d,u]=j.useState({...Zct}),[h,m]=j.useState(!1),p=j.useRef(null),x=()=>{u({...Zct,sort_order:r.length}),c(!0)},g=v=>{u({id:v.id,title:v.title,description:v.description||"",category:v.category||"Personal",resource_kind:v.resource_kind,url:v.url||"",file_path:v.file_path||"",status:v.status,sort_order:v.sort_order}),c(!0)},y=async v=>{if(!(!v||!s||!t)){if(v.size>50*1024*1024)return ae.error("File must be under 50MB");m(!0);try{const N=v.name.split(".").pop()||"pdf",C=`programs/${s}/members/${t}/${Date.now()}-${Math.random().toString(36).slice(2,8)}.${N}`,{error:A}=await U.storage.from(Dq).upload(C,v,{contentType:v.type||"application/pdf",upsert:!1});if(A)throw A;u(T=>({...T,file_path:C,url:"",title:T.title||v.name.replace(/\.[^.]+$/,""),resource_kind:v.type==="application/pdf"?"pdf":T.resource_kind})),ae.success("File uploaded")}catch(N){ae.error(N.message||"Upload failed")}finally{m(!1),p.current&&(p.current.value="")}}},b=async()=>{if(!d.title.trim())return ae.error("Give the resource a title");if(!d.file_path&&!d.url.trim())return ae.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(Ad,{className:"h-4 w-4 text-primary"})," Personal resources"]}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:["Only ",n||"this member"," can see these — they appear in a “Just for you” section on their program dashboard."]})]}),e.jsxs($,{size:"sm",onClick:x,disabled:!t,children:[e.jsx(sn,{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(_e,{className:"border-dashed",children:e.jsx(Oe,{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(v=>e.jsx(_e,{className:"border-border/60",children:e.jsxs(Oe,{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:v.title}),e.jsx($e,{variant:"secondary",children:v.category}),e.jsx($e,{variant:"outline",className:"capitalize",children:v.resource_kind.replace("_"," ")}),v.status!=="published"&&e.jsx($e,{variant:"outline",className:"capitalize",children:v.status})]}),v.description&&e.jsx("p",{className:"max-w-xl text-sm text-muted-foreground",children:v.description}),_ee(v)&&e.jsxs("button",{type:"button",onClick:()=>_Y(v),className:"inline-flex items-center gap-1 text-xs text-primary hover:underline",children:[e.jsx(Tr,{className:"h-3 w-3"})," Open"]})]}),e.jsxs("div",{className:"flex gap-1",children:[e.jsx($,{variant:"ghost",size:"icon",onClick:()=>g(v),children:e.jsx(Ya,{className:"h-4 w-4"})}),e.jsx($,{variant:"ghost",size:"icon",onClick:async()=>{await Yi(`Remove "${v.title}"?`)&&l.mutate(v)},children:e.jsx(Pn,{className:"h-4 w-4 text-destructive"})})]})]})},v.id))}),e.jsx(Os,{open:o,onOpenChange:c,children:e.jsxs(Rs,{className:"max-w-lg",children:[e.jsx(Us,{children:e.jsx(zs,{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(se,{children:"Title"}),e.jsx(be,{value:d.title,onChange:v=>u({...d,title:v.target.value}),placeholder:"Your 90-day content plan"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:"Description"}),e.jsx(Is,{rows:2,value:d.description,onChange:v=>u({...d,description:v.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(se,{children:"Category"}),e.jsx(be,{value:d.category,onChange:v=>u({...d,category:v.target.value}),placeholder:"Personal"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:"Type"}),e.jsxs(vs,{value:d.resource_kind,onValueChange:v=>u({...d,resource_kind:v}),children:[e.jsx(gs,{children:e.jsx(bs,{})}),e.jsx(ys,{children:x6t.map(v=>e.jsx(Ye,{value:v.value,children:v.label},v.value))})]})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:"File"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs($,{type:"button",variant:"outline",size:"sm",disabled:h,onClick:()=>{var v;return(v=p.current)==null?void 0:v.click()},children:[h?e.jsx(Ht,{className:"mr-1.5 h-4 w-4 animate-spin"}):e.jsx(si,{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:v=>{var N;return y((N=v.target.files)==null?void 0:N[0])}})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:"…or link"}),e.jsx(be,{value:d.url,onChange:v=>u({...d,url:v.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(se,{children:"Status"}),e.jsxs(vs,{value:d.status,onValueChange:v=>u({...d,status:v}),children:[e.jsx(gs,{children:e.jsx(bs,{})}),e.jsxs(ys,{children:[e.jsx(Ye,{value:"published",children:"Published"}),e.jsx(Ye,{value:"draft",children:"Draft"}),e.jsx(Ye,{value:"archived",children:"Archived"})]})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:"Sort order"}),e.jsx(be,{type:"number",value:d.sort_order,onChange:v=>u({...d,sort_order:v.target.value})})]})]})]}),e.jsxs(kr,{children:[e.jsx($,{variant:"ghost",onClick:()=>c(!1),children:"Cancel"}),e.jsxs($,{onClick:b,disabled:i.isPending||h,children:[i.isPending&&e.jsx(Ht,{className:"mr-1.5 h-4 w-4 animate-spin"})," Save"]})]})]})})]})},CRs=({program:s,enrollment:t,open:n,onOpenChange:r,onUpdated:a})=>{var K,Q,J,ce,ue,ne,ee,le,he,ve;const i=t==null?void 0:t.user_id,[l,o]=j.useState((t==null?void 0:t.admin_notes)||""),[c,d]=j.useState(!1),[u,h]=j.useState(""),[m,p]=j.useState(!1),[x,g]=j.useState(!1),y=j.useRef(null),{data:b,isLoading:v,refetch:N}=ht({queryKey:["admin-program-agent",s.id,i],enabled:n&&!!i,queryFn:async()=>{const[ge,fe,je,Ee,Me,De,ze,ke]=await Promise.all([U.from("program_weekly_progress").select("*").eq("program_id",s.id).eq("user_id",i).order("week_number"),U.from("program_video_logs").select("*").eq("program_id",s.id).eq("user_id",i).order("posted_at",{ascending:!1}),U.from("program_lesson_completions").select("*").eq("program_id",s.id).eq("user_id",i),U.from("program_badge_awards").select("*").eq("program_id",s.id).eq("user_id",i),U.from("program_intake_responses").select("*").eq("program_id",s.id).eq("user_id",i).maybeSingle(),U.from("program_event_attendance").select("*").eq("program_id",s.id).eq("user_id",i),U.from("program_lessons").select("id").eq("program_id",s.id),U.from("program_profile_analyses").select("*").eq("program_id",s.id).eq("user_id",i).maybeSingle()]);return{weekly:ge.data||[],videos:fe.data||[],completions:je.data||[],badges:Ee.data||[],intake:Me.data,attendance:De.data||[],lessonCount:(ze.data||[]).length,analysis:ke.data}}});j.useEffect(()=>{var ge;h(((ge=b==null?void 0:b.analysis)==null?void 0:ge.member_notes)||"")},[(K=b==null?void 0:b.analysis)==null?void 0:K.id]);const C=j.useMemo(()=>{var je;const ge=YZ(s),fe=((je=b==null?void 0:b.intake)==null?void 0:je.extra)||{};return ge.custom.map(Ee=>({label:Ee.label,value:typeof fe[Ee.id]=="boolean"?fe[Ee.id]?"Yes":"No":fe[Ee.id]||""})).filter(Ee=>!!Ee.value)},[s,b==null?void 0:b.intake]),A=async ge=>i?U.from("program_profile_analyses").upsert({program_id:s.id,user_id:i,enrollment_id:(t==null?void 0:t.id)||null,...ge},{onConflict:"program_id,user_id"}):{error:{message:"Missing agent"}},T=async ge=>{if(ge.type!=="application/pdf")return ae.error("Please choose a PDF file");if(ge.size>25*1024*1024)return ae.error("PDF must be under 25MB");g(!0);try{const fe=`programs/${s.id}/reviews/${i}-${Date.now()}.pdf`,{error:je}=await U.storage.from("event-images").upload(fe,ge,{contentType:"application/pdf",upsert:!0});if(je)throw je;const{data:Ee}=U.storage.from("event-images").getPublicUrl(fe),{error:Me}=await A({report_url:Ee.publicUrl,status:"ready",reviewed_at:new Date().toISOString()});if(Me)throw Me;ae.success("Profile review uploaded"),await N()}catch(fe){ae.error(fe.message||"Upload failed")}finally{g(!1)}},P=async()=>{const{error:ge}=await A({report_url:null,status:"in_review"});if(ge)return ae.error(ge.message);ae.success("Review removed"),await N()},M=async()=>{p(!0);const{error:ge}=await A({member_notes:u});if(p(!1),ge)return ae.error(ge.message);ae.success("Review notes saved"),await N()},I=async()=>{if(!t)return;d(!0);const{error:ge}=await U.from("program_enrollments").update({admin_notes:l}).eq("id",t.id);if(d(!1),ge)return ae.error(ge.message);ae.success("Notes saved"),a()},D=((b==null?void 0:b.videos)||[]).filter(ge=>ge.posted).length,B=(s.weekly_video_goal||0)*(s.duration_weeks||0),q=b!=null&&b.lessonCount?Math.round(((b==null?void 0:b.completions.length)||0)/b.lessonCount*100):0,W=B?Math.min(100,Math.round(D/B*100)):0,V=((b==null?void 0:b.attendance)||[]).filter(ge=>ge.attended).length;return e.jsx(Ub,{open:n,onOpenChange:r,children:e.jsxs(T1,{className:"w-full overflow-y-auto sm:max-w-2xl",children:[e.jsxs(kw,{className:"mb-4",children:[e.jsxs(Sw,{children:[((Q=t==null?void 0:t.profile)==null?void 0:Q.name)||"Agent"," · ",s.name]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:(J=t==null?void 0:t.profile)==null?void 0:J.email}),i&&e.jsx($,{variant:"outline",size:"sm",className:"mt-3 w-fit",asChild:!0,children:e.jsxs("a",{href:`/programs/${s.slug}/workspace?preview=1&as=${i}&name=${encodeURIComponent(((ce=t==null?void 0:t.profile)==null?void 0:ce.name)||((ue=t==null?void 0:t.profile)==null?void 0:ue.email)||"this member")}`,target:"_blank",rel:"noreferrer",children:[e.jsx(Tr,{className:"mr-2 h-4 w-4"}),"Open their dashboard"]})})]}),t?v?e.jsx(on,{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(_e,{children:e.jsxs(Oe,{className:"p-4",children:[e.jsx("p",{className:"text-xs uppercase tracking-wide text-muted-foreground",children:"Status"}),e.jsx($e,{className:"mt-1 capitalize",children:String(t.status).replace(/_/g," ")}),e.jsxs("p",{className:"mt-2 text-xs text-muted-foreground",children:[Mp(t.amount_cents,t.currency)," ·"," ",t.charged_at?`Charged ${gd(t.charged_at)}`:`Charge ${gd(t.charge_scheduled_at)||"not set"}`]})]})}),e.jsx(_e,{children:e.jsxs(Oe,{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:gd(t.last_activity_at,!0)||"No activity yet"}),e.jsxs("p",{className:"mt-2 text-xs text-muted-foreground",children:["Enrolled ",gd(t.created_at)]})]})})]}),e.jsx(_e,{children:e.jsxs(Oe,{className:"space-y-4 p-5",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"mb-1 flex items-center justify-between text-sm",children:[e.jsx("span",{className:"font-medium",children:"Videos posted"}),e.jsxs("span",{className:"text-muted-foreground",children:[D," / ",B||"—"]})]}),e.jsx(Ki,{value:W})]}),e.jsxs("div",{children:[e.jsxs("div",{className:"mb-1 flex items-center justify-between text-sm",children:[e.jsx("span",{className:"font-medium",children:"Curriculum completed"}),e.jsxs("span",{className:"text-muted-foreground",children:[(b==null?void 0:b.completions.length)||0," / ",(b==null?void 0:b.lessonCount)||0]})]}),e.jsx(Ki,{value:q})]}),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: "}),(b==null?void 0:b.badges.length)||0]}),e.jsxs("span",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Weeks reported: "}),(b==null?void 0:b.weekly.length)||0]})]})]})}),e.jsx(_e,{children:e.jsxs(Oe,{className:"p-5",children:[e.jsx("p",{className:"mb-3 text-sm font-semibold",children:"Weekly progress"}),((b==null?void 0:b.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:b.weekly.map(ge=>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 ",ge.week_number]}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:[ge.videos_posted,"/",ge.goal_videos||s.weekly_video_goal," posted ·"," ",ge.stories_posted," stories"]})]}),ge.biggest_win&&e.jsxs("p",{className:"mt-1 text-muted-foreground",children:["Win: ",ge.biggest_win]}),ge.biggest_challenge&&e.jsxs("p",{className:"text-muted-foreground",children:["Challenge: ",ge.biggest_challenge]})]},ge.id))})]})}),e.jsx(_e,{children:e.jsxs(Oe,{className:"p-5",children:[e.jsx("p",{className:"mb-3 text-sm font-semibold",children:"Video log"}),((b==null?void 0:b.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:b.videos.slice(0,25).map(ge=>e.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[e.jsx(Xr,{className:"h-3.5 w-3.5 shrink-0 text-muted-foreground"}),e.jsx("span",{className:"truncate",children:ge.title||"Untitled video"}),e.jsxs("span",{className:"ml-auto shrink-0 text-xs text-muted-foreground",children:["Wk ",ge.week_number," · ",gd(ge.posted_at)]}),ge.instagram_url&&e.jsx("a",{href:ge.instagram_url,target:"_blank",rel:"noreferrer",className:"shrink-0 text-muted-foreground hover:text-foreground","aria-label":"Open post",children:e.jsx(Tr,{className:"h-3.5 w-3.5"})})]},ge.id))})]})}),(b==null?void 0:b.intake)&&e.jsx(_e,{children:e.jsxs(Oe,{className:"space-y-1 p-5 text-sm",children:[e.jsx("p",{className:"mb-2 text-sm font-semibold",children:"Intake answers"}),[["Full name",b.intake.full_name],["Email",b.intake.email],["Phone",b.intake.phone],["Instagram",b.intake.instagram_handle],["City / market",b.intake.city],["Areas served",b.intake.service_areas],["Years in real estate",b.intake.years_experience],["Specialty",b.intake.specialty],["Target audience",b.intake.target_audience],["On camera",b.intake.video_comfort],["Posts today",b.intake.posting_frequency],["Content style",b.intake.content_style],["Interests",b.intake.personal_interests],["#1 goal",b.intake.primary_goal],["Topics to avoid",b.intake.topics_to_avoid],["Time zone",b.intake.timezone]].filter(([,ge])=>!!ge).map(([ge,fe])=>e.jsxs("p",{children:[e.jsxs("span",{className:"text-muted-foreground",children:[ge,": "]}),fe]},ge)),C.map(({label:ge,value:fe})=>e.jsxs("p",{children:[e.jsxs("span",{className:"text-muted-foreground",children:[ge,": "]}),fe]},ge)),e.jsxs("p",{className:"pt-1 text-xs text-muted-foreground",children:["Content-sharing consent: ",b.intake.consent_public_profile?"Yes":"No"]})]})}),e.jsx(_e,{children:e.jsx(Oe,{className:"p-5",children:e.jsx(SRs,{programId:s.id,userId:i,memberName:(ne=t==null?void 0:t.profile)==null?void 0:ne.name})})}),e.jsx(_e,{children:e.jsxs(Oe,{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."})]}),((ee=b==null?void 0:b.analysis)==null?void 0:ee.status)&&e.jsx($e,{variant:"secondary",className:"capitalize",children:String(b.analysis.status).replace(/_/g," ")})]}),(le=b==null?void 0:b.analysis)!=null&&le.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(Wr,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"truncate",children:"Review uploaded"}),e.jsxs("a",{href:b.analysis.report_url,target:"_blank",rel:"noreferrer",className:"ml-auto inline-flex items-center gap-1 text-primary hover:underline",children:["View ",e.jsx(Tr,{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:ge=>{var je;const fe=(je=ge.target.files)==null?void 0:je[0];fe&&T(fe),ge.target.value=""}}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs($,{size:"sm",variant:"outline",onClick:()=>{var ge;return(ge=y.current)==null?void 0:ge.click()},disabled:x,children:[e.jsx(si,{className:"mr-1.5 h-3.5 w-3.5"}),x?"Uploading…":(he=b==null?void 0:b.analysis)!=null&&he.report_url?"Replace PDF":"Upload PDF"]}),((ve=b==null?void 0:b.analysis)==null?void 0:ve.report_url)&&e.jsx($,{size:"sm",variant:"ghost",onClick:P,children:"Remove"})]}),e.jsxs("div",{className:"space-y-2 pt-1",children:[e.jsx(se,{children:"Review summary shown to the agent (optional)"}),e.jsx(Is,{rows:3,value:u,onChange:ge=>h(ge.target.value),placeholder:"Top 3 priorities, quick wins, what to fix first…"}),e.jsx("div",{className:"flex justify-end",children:e.jsx($,{size:"sm",variant:"outline",onClick:M,disabled:m,children:"Save review notes"})})]})]})}),e.jsx(_e,{children:e.jsxs(Oe,{className:"space-y-3 p-5",children:[e.jsx(se,{children:"Coach notes (internal)"}),e.jsx(Is,{rows:4,value:l,onChange:ge=>o(ge.target.value)}),e.jsx("div",{className:"flex justify-end",children:e.jsx($,{size:"sm",onClick:I,disabled:c,children:"Save notes"})})]})})]}):null]})})},Xct={code:"",label:"",kind:"percent",percent_off:"20",amount_off:"",max_redemptions:"",starts_at:"",expires_at:"",is_active:!0},Qct=s=>{if(!s)return"";const t=new Date(s),n=t.getTimezoneOffset();return new Date(t.getTime()-n*6e4).toISOString().slice(0,16)},ARs=({program:s})=>{const{data:t=[],isLoading:n}=G3s(s.id),r=W3s(s.id),a=K3s(),[i,l]=j.useState(!1),[o,c]=j.useState({...Xct}),d=()=>{c({...Xct}),l(!0)},u=x=>{c({id:x.id,code:x.code,label:x.label||"",kind:x.percent_off!=null?"percent":"amount",percent_off:x.percent_off!=null?String(x.percent_off):"",amount_off:x.amount_off_cents!=null?String(x.amount_off_cents/100):"",max_redemptions:x.max_redemptions!=null?String(x.max_redemptions):"",starts_at:Qct(x.starts_at),expires_at:Qct(x.expires_at),is_active:x.is_active}),l(!0)},h=j.useMemo(()=>{const x=o.kind==="percent"?Math.floor(s.price_cents*Number(o.percent_off||0)/100):Math.round(Number(o.amount_off||0)*100),g=Math.min(Math.max(x,0),s.price_cents);return{discount:g,final:s.price_cents-g}},[o,s.price_cents]),m=async()=>{if(!o.code.trim())return ae.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=x=>{const g=x.percent_off!=null?Math.floor(s.price_cents*Number(x.percent_off)/100):x.amount_off_cents||0,y=Math.max(s.price_cents-Math.min(g,s.price_cents),0);return{off:x.percent_off!=null?`${Number(x.percent_off)}% off`:`${Mp(x.amount_off_cents||0,s.currency)} off`,final:Mp(y,s.currency)}};return e.jsxs("div",{className:"space-y-4",children:[e.jsx(_e,{children:e.jsxs(Oe,{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 ",Mp(s.price_cents,s.currency)," charge."]})]}),e.jsxs(Os,{open:i,onOpenChange:l,children:[e.jsx(Ko,{asChild:!0,children:e.jsxs($,{onClick:d,children:[e.jsx(sn,{className:"mr-1.5 h-4 w-4"})," New code"]})}),e.jsxs(Rs,{className:"max-h-[85vh] overflow-y-auto",children:[e.jsx(Us,{children:e.jsx(zs,{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(se,{children:"Code"}),e.jsx(be,{placeholder:"FOUNDER50",value:o.code,onChange:x=>c({...o,code:x.target.value.toUpperCase()})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Internal label (optional)"}),e.jsx(be,{placeholder:"Founding cohort",value:o.label,onChange:x=>c({...o,label:x.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Discount type"}),e.jsxs(vs,{value:o.kind,onValueChange:x=>c({...o,kind:x}),children:[e.jsx(gs,{children:e.jsx(bs,{})}),e.jsxs(ys,{children:[e.jsx(Ye,{value:"percent",children:"Percent off"}),e.jsx(Ye,{value:"amount",children:"Dollar amount off"})]})]})]}),o.kind==="percent"?e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Percent off"}),e.jsx(be,{type:"number",min:1,max:100,value:o.percent_off,onChange:x=>c({...o,percent_off:x.target.value})})]}):e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Amount off (USD)"}),e.jsx(be,{type:"number",min:0,value:o.amount_off,onChange:x=>c({...o,amount_off:x.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Max redemptions (blank = unlimited)"}),e.jsx(be,{type:"number",min:1,value:o.max_redemptions,onChange:x=>c({...o,max_redemptions:x.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Active from (optional)"}),e.jsx(be,{type:"datetime-local",value:o.starts_at,onChange:x=>c({...o,starts_at:x.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Expires (optional)"}),e.jsx(be,{type:"datetime-local",value:o.expires_at,onChange:x=>c({...o,expires_at:x.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(Tn,{checked:o.is_active,onCheckedChange:x=>c({...o,is_active:x})})]}),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:[Mp(s.price_cents,s.currency)," →"," ",e.jsx("span",{className:"font-semibold text-foreground",children:Mp(h.final,s.currency)})," ","(",Mp(h.discount,s.currency)," off) — charged one time."]})]})]}),e.jsx(kr,{children:e.jsxs($,{onClick:m,disabled:r.isPending,children:[r.isPending&&e.jsx(Ht,{className:"mr-1.5 h-4 w-4 animate-spin"}),o.id?"Save changes":"Create code"]})})]})]})]})}),n?e.jsx(on,{className:"h-40 w-full rounded-xl"}):t.length===0?e.jsx(_e,{className:"border-dashed",children:e.jsxs(Oe,{className:"flex flex-col items-center gap-3 p-12 text-center",children:[e.jsx(Up,{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(_e,{children:e.jsx(Oe,{className:"overflow-x-auto p-0",children:e.jsxs(Va,{children:[e.jsx(Ha,{children:e.jsxs(hn,{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(Ga,{children:t.map(x=>{const g=p(x);return e.jsxs(hn,{children:[e.jsxs(gt,{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"font-mono font-semibold",children:x.code}),e.jsx($,{variant:"ghost",size:"icon",className:"h-6 w-6",onClick:()=>{navigator.clipboard.writeText(x.code),ae.success("Code copied")},children:e.jsx(Ca,{className:"h-3.5 w-3.5"})})]}),x.label&&e.jsx("p",{className:"text-xs text-muted-foreground",children:x.label})]}),e.jsx(gt,{className:"whitespace-nowrap",children:e.jsxs("span",{className:"inline-flex items-center gap-1.5",children:[e.jsx(ST,{className:"h-3.5 w-3.5 text-muted-foreground"}),g.off]})}),e.jsx(gt,{className:"font-medium",children:g.final}),e.jsxs(gt,{children:[x.times_redeemed,x.max_redemptions?` / ${x.max_redemptions}`:""]}),e.jsxs(gt,{className:"text-xs text-muted-foreground",children:[x.starts_at?`From ${gd(x.starts_at)}`:"Anytime",x.expires_at?` · until ${gd(x.expires_at)}`:""]}),e.jsx(gt,{children:e.jsx($e,{variant:x.is_active?"default":"secondary",children:x.is_active?"Active":"Paused"})}),e.jsx(gt,{className:"text-right",children:e.jsxs("div",{className:"flex justify-end gap-1",children:[e.jsx($,{variant:"outline",size:"sm",onClick:()=>u(x),children:"Edit"}),e.jsx($,{variant:"ghost",size:"icon",onClick:async()=>{await Yi(`Delete ${x.code}?`)&&a.mutate(x.id)},children:e.jsx(Pn,{className:"h-4 w-4 text-destructive"})})]})})]},x.id)})})]})})})]})},zk=({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(Fr,{className:"mt-0.5 h-4 w-4 shrink-0 text-primary"}):e.jsx(mc,{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})]})]}),ERs=({program:s})=>{var c,d;const{data:t,isLoading:n}=ht({queryKey:["admin-program-content-counts",s.id],queryFn:async()=>{const[u,h,m,p,x]=await Promise.all([U.from("program_weeks").select("id, week_number, title").eq("program_id",s.id),U.from("program_lessons").select("id, title").eq("program_id",s.id),U.from("program_resources").select("id, title").eq("program_id",s.id),U.from("program_events").select("id, title, starts_at").eq("program_id",s.id),U.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:x.data||[]}}}),{notOpenYet:r,closed:a,opensLabel:i}=XCe(s),l=`/programs/${s.slug}`,o=[{icon:dn,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:Fz,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:yy,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 ${Mp(s.price_cents,s.currency)} charge runs on ${gd(s.charge_at||s.kickoff_at)||"the charge date (not set)"}.`:`Stripe charges ${Mp(s.price_cents,s.currency)} once at checkout.`},{icon:nn,title:"4 · Emails",body:"Confirmation right after enrollment, then payment receipt (or a payment-failed action email) when the one-time charge runs."},{icon:Lz,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(_e,{children:e.jsxs(Oe,{className:"flex flex-wrap items-center justify-between gap-4 p-5",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:"What enrollees see"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Walk the exact member journey end to end. Workspace preview opens in read-only admin mode — it does not create an enrollment."})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx($,{variant:"outline",asChild:!0,children:e.jsxs("a",{href:l,target:"_blank",rel:"noreferrer",children:["Sales page ",e.jsx(Tr,{className:"ml-1.5 h-3.5 w-3.5"})]})}),e.jsx($,{asChild:!0,children:e.jsxs("a",{href:`${l}/workspace?preview=1`,target:"_blank",rel:"noreferrer",children:["Workspace preview ",e.jsx(Tr,{className:"ml-1.5 h-3.5 w-3.5"})]})})]})]})}),(s.status!=="published"||r||a)&&e.jsx(_e,{className:"border-amber-500/40 bg-amber-500/5",children:e.jsxs(Oe,{className:"flex items-start gap-3 p-5 text-sm",children:[e.jsx(mc,{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(_e,{children:e.jsxs(Oe,{className:"space-y-3 p-5",children:[e.jsx("p",{className:"text-xs font-semibold uppercase tracking-wider text-muted-foreground",children:"The enrollee journey"}),e.jsx("div",{className:"space-y-4",children:o.map(u=>e.jsxs("div",{className:"flex gap-3",children:[e.jsx("div",{className:"mt-0.5 flex h-8 w-8 shrink-0 items-center justify-center rounded-lg bg-primary/10",children:e.jsx(u.icon,{className:"h-4 w-4 text-primary"})}),e.jsxs("div",{className:"min-w-0 space-y-1",children:[e.jsx("p",{className:"text-sm font-medium",children:u.title}),e.jsx("p",{className:"text-sm text-muted-foreground",children:u.body}),u.href&&e.jsx($,{variant:"link",size:"sm",className:"h-auto p-0",asChild:!0,children:e.jsxs("a",{href:u.href,target:"_blank",rel:"noreferrer",children:[u.cta," ",e.jsx(Tr,{className:"ml-1 h-3 w-3"})]})})]})]},u.title))})]})}),e.jsx(_e,{children:e.jsxs(Oe,{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(on,{className:"mt-4 h-64 w-full rounded-lg"}):e.jsxs("div",{className:"mt-2",children:[e.jsx(zk,{ok:!!s.cover_image_url,label:"Cover image",detail:s.cover_image_url?"Set":"Missing — cards look empty on the Programs page"}),e.jsx(zk,{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(zk,{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(zk,{ok:s.payment_mode==="free"||s.price_cents>0,label:"One-time price",detail:s.payment_mode==="free"?"Free / included":Mp(s.price_cents,s.currency)}),e.jsx(zk,{ok:!!s.kickoff_at&&(s.payment_mode==="free"||!!s.charge_at),label:"Kickoff and charge dates",detail:`Kickoff ${gd(s.kickoff_at)||"not set"} · charge ${gd(s.charge_at)||"not set"}`}),e.jsx(zk,{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(zk,{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(zk,{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(zk,{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 ${gd(t.events[0].starts_at)}`:""}`}),e.jsx(zk,{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(_e,{children:e.jsx(Oe,{className:"grid gap-4 p-5 sm:grid-cols-2 lg:grid-cols-5",children:[{icon:Nl,label:"Weeks",value:t.weeks.length},{icon:Wr,label:"Lessons",value:t.lessons.length},{icon:Wr,label:"Resources",value:t.resources.length},{icon:Nl,label:"Events",value:t.events.length},{icon:Eh,label:"Announcements",value:t.announcements.length}].map((u,h)=>e.jsxs("div",{className:"rounded-lg border border-border/60 p-4",children:[e.jsx(u.icon,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("p",{className:"mt-2 text-2xl font-bold",children:u.value}),e.jsx("p",{className:"text-xs text-muted-foreground",children:u.label})]},h))})}),e.jsx($e,{variant:"outline",className:"text-xs",children:"Tip: preview in an incognito window as a test member to see the real enrollment flow end to end."})]})},TRs=["Step 1 · Your business","Step 2 · Your content","Step 3 · Your goals"],MRs={short_text:"Short answer",long_text:"Paragraph",select:"Dropdown",checkbox:"Yes / no checkbox"},LRs=({program:s,onSaved:t})=>{const[n,r]=j.useState(()=>YZ(s)),[a,i]=j.useState(!1),[l,o]=j.useState(!1);j.useEffect(()=>{r(YZ(s)),i(!1)},[s.id,s.updated_at]);const c=y=>{r(b=>({...b,...y})),i(!0)},d=(y,b)=>{const v=b?n.hidden.filter(C=>C!==y):[...new Set([...n.hidden,y])],N=b?n.required:n.required.filter(C=>C!==y);c({hidden:v,required:N})},u=(y,b)=>{c({required:b?[...new Set([...n.required,y])]:n.required.filter(v=>v!==y)})},h=()=>{const y={id:`q_${Date.now().toString(36)}`,label:"",type:"short_text",required:!1,options:[]};c({custom:[...n.custom,y]})},m=(y,b)=>c({custom:n.custom.map(v=>v.id===y?{...v,...b}:v)}),p=y=>c({custom:n.custom.filter(b=>b.id!==y)}),x=(y,b)=>{const v=[...n.custom],N=y+b;N<0||N>=v.length||([v[y],v[N]]=[v[N],v[y]],c({custom:v}))},g=async()=>{if(n.custom.find(N=>!N.label.trim()))return ae.error("Every custom question needs a label");o(!0);const b={...s.sales_copy||{},intake:n},{error:v}=await U.from("programs").update({sales_copy:b}).eq("id",s.id);if(o(!1),v)return ae.error(v.message);i(!1),ae.success("Intake form saved"),t==null||t()};return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-semibold",children:"Intake form"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Controls the questions each agent answers during enrollment."})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx($,{variant:"outline",size:"sm",asChild:!0,children:e.jsxs("a",{href:`/programs/${s.slug}/enroll`,target:"_blank",rel:"noreferrer",children:[e.jsx(Tr,{className:"mr-1.5 h-3.5 w-3.5"})," Preview form"]})}),e.jsxs($,{size:"sm",onClick:g,disabled:!a||l,children:[e.jsx(Jo,{className:"mr-1.5 h-3.5 w-3.5"}),l?"Saving…":"Save intake form"]})]})]}),e.jsxs(_e,{children:[e.jsx(Bt,{className:"pb-3",children:e.jsx(Ut,{className:"text-sm",children:"Intro message"})}),e.jsx(Oe,{children:e.jsx(Is,{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(_e,{children:[e.jsx(Bt,{className:"pb-3",children:e.jsx(Ut,{className:"text-sm",children:TRs[y]})}),e.jsxs(Oe,{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"})]}),lGe.filter(b=>b.step===y).map(b=>{const v=!n.hidden.includes(b.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:b.label}),e.jsx("div",{className:"flex w-16 justify-center",children:e.jsx(Tn,{checked:v,onCheckedChange:N=>d(b.key,N),"aria-label":`Show ${b.label}`})}),e.jsx("div",{className:"flex w-16 justify-center",children:e.jsx(Tn,{checked:n.required.includes(b.key),disabled:!v,onCheckedChange:N=>u(b.key,N),"aria-label":`Require ${b.label}`})})]},b.key)})]})]},y)),e.jsxs(_e,{children:[e.jsxs(Bt,{className:"flex-row items-center justify-between space-y-0 pb-3",children:[e.jsxs(Ut,{className:"text-sm",children:["Custom questions"," ",e.jsx($e,{variant:"secondary",className:"ml-1",children:n.custom.length})]}),e.jsxs($,{size:"sm",variant:"outline",onClick:h,children:[e.jsx(sn,{className:"mr-1.5 h-3.5 w-3.5"})," Add question"]})]}),e.jsxs(Oe,{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,b)=>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:()=>x(b,-1),"aria-label":"Move up",children:e.jsx($p,{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(se,{className:"text-xs",children:"Question"}),e.jsx(be,{value:y.label,placeholder:"What is your biggest content roadblock?",onChange:v=>m(y.id,{label:v.target.value})})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{className:"text-xs",children:"Answer type"}),e.jsxs(vs,{value:y.type,onValueChange:v=>m(y.id,{type:v}),children:[e.jsx(gs,{children:e.jsx(bs,{})}),e.jsx(ys,{children:Object.entries(MRs).map(([v,N])=>e.jsx(Ye,{value:v,children:N},v))})]})]})]}),e.jsx($,{size:"icon",variant:"ghost",onClick:()=>p(y.id),"aria-label":"Delete question",children:e.jsx(Pn,{className:"h-4 w-4 text-destructive"})})]}),y.type==="select"&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{className:"text-xs",children:"Options (one per line)"}),e.jsx(Is,{rows:3,value:(y.options||[]).join(` `),onChange:v=>m(y.id,{options:v.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(se,{className:"text-xs",children:"Helper text (optional)"}),e.jsx(be,{value:y.help||"",onChange:v=>m(y.id,{help:v.target.value})})]}),e.jsxs("div",{className:"flex items-center gap-2 pt-6",children:[e.jsx(Tn,{checked:!!y.required,onCheckedChange:v=>m(y.id,{required:v}),"aria-label":"Required"}),e.jsx("span",{className:"text-sm",children:"Required"})]})]})]},y.id))]})]})]})},uv=tPt,hv=uWe,mv=mWe,PRs=[ix,Wr,Mu],IRs=["Business profile","Content style","Goals & consent"],DRs=({fieldKey:s})=>s.includes("phone")?e.jsx(ya,{className:"h-3.5 w-3.5"}):s.includes("email")?e.jsx(nn,{className:"h-3.5 w-3.5"}):s.includes("instagram")?e.jsx(Qh,{className:"h-3.5 w-3.5"}):s.includes("city")||s.includes("area")?e.jsx(ai,{className:"h-3.5 w-3.5"}):s.includes("timezone")?e.jsx(Hr,{className:"h-3.5 w-3.5"}):s.includes("consent")?s.includes("true")?e.jsx(Fr,{className:"h-3.5 w-3.5"}):e.jsx($d,{className:"h-3.5 w-3.5"}):e.jsx(Lo,{className:"h-3.5 w-3.5"}),Jct=(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(Fr,{className:"h-3.5 w-3.5"})," Yes"]}):e.jsxs("span",{className:"inline-flex items-center gap-1 text-muted-foreground",children:[e.jsx($d,{className:"h-3.5 w-3.5"})," No"]}):String(s),RRs=({program:s})=>{const[t,n]=j.useState(""),[r,a]=j.useState(new Set),{data:i=[],isLoading:l}=ht({queryKey:["admin-program-intakes",s.id],queryFn:async()=>{const{data:h,error:m}=await U.from("program_intake_responses").select("*").eq("program_id",s.id).order("created_at",{ascending:!1});if(m)throw m;return h||[]}}),o=YZ(s),c=lGe.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(on,{className:"h-96 w-full rounded-xl"}):i.length===0?e.jsx(_e,{className:"border-dashed",children:e.jsxs(Oe,{className:"p-12 text-center text-sm text-muted-foreground",children:[e.jsx(Wr,{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(Vr,{className:"absolute left-2.5 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),e.jsx(be,{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=gd(h.created_at,!0);return e.jsx(_e,{className:"overflow-hidden",children:e.jsxs(uv,{open:m,onOpenChange:()=>u(h.id),children:[e.jsx(hv,{asChild:!0,children:e.jsxs(Bt,{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(Lo,{className:"h-4 w-4 text-primary"})}),e.jsxs("div",{children:[e.jsxs(Ut,{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($,{variant:"ghost",size:"icon",className:"h-8 w-8 shrink-0",children:e.jsx(_o,{className:`h-4 w-4 transition-transform ${m?"rotate-180":""}`})})]})]})}),e.jsx(mv,{children:e.jsxs(Oe,{className:"space-y-5 p-5",children:[[0,1,2].map(x=>{const g=c.filter(b=>b.step===x),y=PRs[x];return g.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:IRs[x]})]}),e.jsx("div",{className:"grid gap-3 sm:grid-cols-2 lg:grid-cols-3",children:g.map(b=>{const v=h[b.key];return v==null||v===""?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(DRs,{fieldKey:b.key}),b.label]}),e.jsx("p",{className:"text-sm font-medium",children:Jct(v,b.key)})]},b.key)})})]},x)}),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(Wr,{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(x=>{var y;const g=(y=h.extra)==null?void 0:y[x.id];return g==null||g===""?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:x.label}),e.jsx("p",{className:"text-sm font-medium",children:Jct(g,x.id)})]},x.id)})})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2 pt-2 text-xs text-muted-foreground",children:[e.jsx(ia,{className:"h-3.5 w-3.5"}),"Submitted ",p,h.timezone&&e.jsxs("span",{className:"ml-2",children:["· Timezone: ",h.timezone]})]})]})})]})},h.id)})})]})},ORs=[{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"}],FRs=s=>{if(!s)return"";const t=new Date(s),n=t.getTimezoneOffset();return new Date(t.getTime()-n*6e4).toISOString().slice(0,16)},edt={title:"",description:"",event_kind:"mastermind",starts_at:"",duration_minutes:60,speaker:"",meeting_link:"",replay_url:"",is_published:!0},zRs=({programId:s})=>{const{data:t=[],isLoading:n}=X3s(s),r=Q3s(s),a=J3s(),[i,l]=j.useState(!1),[o,c]=j.useState({...edt}),d=()=>{c({...edt}),l(!0)},u=y=>{c({id:y.id,title:y.title,description:y.description||"",event_kind:y.event_kind,starts_at:FRs(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 ae.error("Give the session a title");if(!o.starts_at)return ae.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),x=t.filter(y=>new Date(y.starts_at).getTime()e.jsx(_e,{className:"border-border/60",children:e.jsxs(Oe,{className:"flex flex-wrap items-start justify-between gap-4 p-5",children:[e.jsxs("div",{className:"min-w-0 space-y-1.5",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx("p",{className:"font-medium",children:y.title}),e.jsx($e,{variant:"secondary",className:"capitalize",children:y.event_kind.replace("_"," ")}),!y.is_published&&e.jsx($e,{variant:"outline",children:"Hidden"})]}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[gd(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(Tr,{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),ae.success("Join link copied")},children:[e.jsx(Ca,{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(Xr,{className:"h-3 w-3"})," Replay"]})]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx($,{variant:"outline",size:"sm",onClick:()=>u(y),children:e.jsx(Ya,{className:"h-3.5 w-3.5"})}),e.jsx($,{variant:"outline",size:"sm",onClick:async()=>{await Yi(`Remove "${y.title}"?`)&&a.mutate(y.id)},children:e.jsx(Pn,{className:"h-3.5 w-3.5"})})]})]})});return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex flex-wrap items-end justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:"Live sessions"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Add your Zoom (or Meet / Teams) sessions here. Enrolled members see them in the Sessions tab with the join button, RSVP reminders and an add-to-calendar link."})]}),e.jsxs($,{onClick:d,children:[e.jsx(sn,{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(_e,{className:"border-dashed",children:e.jsxs(Oe,{className:"flex flex-col items-center gap-3 p-12 text-center",children:[e.jsx(Xu,{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(g,{e:y},y.id))]}),x.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 (",x.length,") — add replay links so members can catch up"]}),x.map(y=>e.jsx(g,{e:y},y.id))]})]}),e.jsx(Os,{open:i,onOpenChange:l,children:e.jsxs(Rs,{className:"max-h-[85vh] max-w-2xl overflow-y-auto",children:[e.jsx(Us,{children:e.jsx(zs,{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(se,{children:"Title"}),e.jsx(be,{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(se,{children:"Type"}),e.jsxs(vs,{value:o.event_kind,onValueChange:y=>c({...o,event_kind:y}),children:[e.jsx(gs,{children:e.jsx(bs,{})}),e.jsx(ys,{children:ORs.map(y=>e.jsx(Ye,{value:y.value,children:y.label},y.value))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Host / speaker"}),e.jsx(be,{value:o.speaker,onChange:y=>c({...o,speaker:y.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Starts (your local time)"}),e.jsx(be,{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(se,{children:"Length (minutes)"}),e.jsx(be,{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(se,{children:"Zoom / meeting link"}),e.jsx(be,{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(se,{children:"Replay link (after the call)"}),e.jsx(be,{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(se,{children:"What we'll cover"}),e.jsx(Is,{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(Tn,{checked:o.is_published,onCheckedChange:y=>c({...o,is_published:y})})]})]}),e.jsx(kr,{children:e.jsxs($,{onClick:h,disabled:r.isPending,children:[r.isPending&&e.jsx(Ht,{className:"mr-1.5 h-4 w-4 animate-spin"}),o.id?"Save session":"Add session"]})})]})})]})},tdt={title:"",summary:"",week_id:"none",duration_minutes:"",video_url:"",worksheet_url:"",action_assignment:"",status:"published",sort_order:0},BRs=({programId:s})=>{const{data:t,isLoading:n}=eCs(s),r=(t==null?void 0:t.lessons)||[],a=(t==null?void 0:t.weeks)||[],{data:i=[]}=g6t(s),l=tCs(s),o=sCs(),[c,d]=j.useState(!1),[u,h]=j.useState({...tdt}),[m,p]=j.useState(!1),x=j.useRef(null),g=async A=>{if(x.current&&(x.current.value=""),!!A){if(!A.type.startsWith("video/"))return ae.error("Please choose a video file");if(A.size>500*1024*1024)return ae.error("Video must be under 500MB");p(!0);try{const T=A.name.split(".").pop()||"mp4",P=`lessons/${crypto.randomUUID()}.${T}`,{error:M}=await U.storage.from("program-assets").upload(P,A,{contentType:A.type,upsert:!1});if(M)throw M;const{data:I,error:D}=await U.storage.from("program-assets").createSignedUrl(P,60*60*24*365*5);if(D||!(I!=null&&I.signedUrl))throw D||new Error("Could not sign video URL");h(B=>({...B,video_url:I.signedUrl})),ae.success("Video uploaded")}catch(T){ae.error((T==null?void 0:T.message)||"Upload failed")}finally{p(!1)}}},y=()=>{h({...tdt,sort_order:r.length}),d(!0)},b=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)},v=async()=>{if(!u.title.trim())return ae.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(P=>P.id===A);return T?`Week ${T.week_number}`:"Unassigned"},C=f6t(u.video_url);return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex flex-wrap items-end justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:"On-demand videos"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Your program's video library. Paste a YouTube, Vimeo or Loom link and it plays inline in the member workspace, grouped by week, with completion tracking."})]}),e.jsxs($,{onClick:y,children:[e.jsx(sn,{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(_e,{className:"border-dashed",children:e.jsxs(Oe,{className:"flex flex-col items-center gap-3 p-12 text-center",children:[e.jsx(lh,{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(_e,{className:"border-border/60",children:e.jsxs(Oe,{className:"flex flex-wrap items-start justify-between gap-4 p-5",children:[e.jsxs("div",{className:"min-w-0 space-y-1.5",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx("p",{className:"font-medium",children:A.title}),e.jsx($e,{variant:"secondary",children:N(A.week_id)}),A.status!=="published"&&e.jsx($e,{variant:"outline",className:"capitalize",children:A.status}),A.duration_minutes?e.jsxs("span",{className:"text-xs text-muted-foreground",children:[A.duration_minutes," min"]}):null]}),A.summary&&e.jsx("p",{className:"max-w-2xl text-sm text-muted-foreground",children:A.summary}),e.jsxs("div",{className:"flex flex-wrap gap-3 pt-1 text-xs",children:[A.video_url?e.jsxs("a",{className:"inline-flex items-center gap-1 text-primary hover:underline",href:A.video_url,target:"_blank",rel:"noreferrer",children:[e.jsx(Tr,{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(Tr,{className:"h-3 w-3"})," Worksheet"]})]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx($,{variant:"outline",size:"sm",onClick:()=>b(A),children:e.jsx(Ya,{className:"h-3.5 w-3.5"})}),e.jsx($,{variant:"outline",size:"sm",onClick:async()=>{await Yi(`Remove "${A.title}"?`)&&o.mutate(A.id)},children:e.jsx(Pn,{className:"h-3.5 w-3.5"})})]})]})},A.id))}),e.jsx(Os,{open:c,onOpenChange:d,children:e.jsxs(Rs,{className:"max-h-[85vh] max-w-2xl overflow-y-auto",children:[e.jsx(Us,{children:e.jsx(zs,{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(se,{children:"Title"}),e.jsx(be,{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(se,{children:"Video link"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(be,{placeholder:"https://youtu.be/… , Vimeo or Loom URL",value:u.video_url,onChange:A=>h({...u,video_url:A.target.value})}),e.jsxs($,{type:"button",variant:"outline",className:"shrink-0",disabled:m,onClick:()=>{var A;return(A=x.current)==null?void 0:A.click()},children:[m?e.jsx(Ht,{className:"mr-1.5 h-4 w-4 animate-spin"}):e.jsx(si,{className:"mr-1.5 h-4 w-4"}),m?"Uploading…":"Upload"]}),e.jsx("input",{ref:x,type:"file",accept:"video/*",className:"hidden",onChange:A=>{var T;return g((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&&!C&&!bY(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.`})]}),C&&e.jsx("div",{className:"overflow-hidden rounded-lg border border-border/60",children:e.jsx("iframe",{src:C,title:"Video preview",className:"aspect-video w-full",allow:"accelerometer; autoplay; clipboard-write; encrypted-media; picture-in-picture",allowFullScreen:!0})}),!C&&bY(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(se,{children:"Week"}),e.jsxs(vs,{value:u.week_id,onValueChange:A=>h({...u,week_id:A}),children:[e.jsx(gs,{children:e.jsx(bs,{})}),e.jsxs(ys,{children:[e.jsx(Ye,{value:"none",children:"Unassigned (library)"}),a.map(A=>e.jsxs(Ye,{value:A.id,children:["Week ",A.week_number," — ",A.title]},A.id))]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Length (minutes)"}),e.jsx(be,{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(se,{children:"Status"}),e.jsxs(vs,{value:u.status,onValueChange:A=>h({...u,status:A}),children:[e.jsx(gs,{children:e.jsx(bs,{})}),e.jsxs(ys,{children:[e.jsx(Ye,{value:"published",children:"Published (visible)"}),e.jsx(Ye,{value:"draft",children:"Draft (hidden)"}),e.jsx(Ye,{value:"archived",children:"Archived"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Order"}),e.jsx(be,{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(se,{children:"Summary"}),e.jsx(Is,{rows:3,value:u.summary,onChange:A=>h({...u,summary:A.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Worksheet / download link"}),i.length>0&&e.jsxs(vs,{value:"",onValueChange:A=>{const T=i.find(M=>M.id===A),P=T?_ee(T):null;P?h({...u,worksheet_url:P}):ae.error("That resource has no file or link yet")},children:[e.jsx(gs,{children:e.jsx(bs,{placeholder:"Choose an uploaded program resource…"})}),e.jsx(ys,{children:i.map(A=>e.jsx(Ye,{value:A.id,children:A.title},A.id))})]}),e.jsx(be,{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(Tr,{className:"h-3 w-3"})," Preview worksheet"]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Action assignment"}),e.jsx(Is,{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(kr,{children:e.jsxs($,{onClick:v,disabled:l.isPending,children:[l.isPending&&e.jsx(Ht,{className:"mr-1.5 h-4 w-4 animate-spin"}),u.id?"Save video":"Add video"]})})]})})]})},sdt={title:"",description:"",category:"Resources",resource_kind:"pdf",url:"",file_path:"",status:"published",sort_order:0},$Rs=({programId:s})=>{const{data:t=[],isLoading:n}=g6t(s),r=nCs(s),a=rCs(),[i,l]=j.useState(!1),[o,c]=j.useState({...sdt}),[d,u]=j.useState(!1),h=j.useRef(null),m=Array.from(new Set(t.map(b=>b.category))).filter(Boolean),p=()=>{c({...sdt,sort_order:t.length}),l(!0)},x=b=>{c({id:b.id,title:b.title,description:b.description||"",category:b.category||"Resources",resource_kind:b.resource_kind,url:b.url||"",file_path:b.file_path||"",status:b.status,sort_order:b.sort_order}),l(!0)},g=async b=>{if(!(!b||!s)){if(b.size>50*1024*1024)return ae.error("File must be under 50MB");u(!0);try{const v=b.name.split(".").pop()||"pdf",N=`programs/${s}/resources/${Date.now()}-${Math.random().toString(36).slice(2,8)}.${v}`,{error:C}=await U.storage.from(Dq).upload(N,b,{contentType:b.type||"application/pdf",upsert:!1});if(C)throw C;c(A=>({...A,file_path:N,url:"",title:A.title||b.name.replace(/\.[^.]+$/,""),resource_kind:b.type==="application/pdf"?"pdf":A.resource_kind})),ae.success("File uploaded")}catch(v){ae.error(v.message||"Upload failed")}finally{u(!1),h.current&&(h.current.value="")}}},y=async()=>{if(!o.title.trim())return ae.error("Give the resource a title");if(!o.file_path&&!o.url.trim())return ae.error("Upload a file or paste a link");await r.mutateAsync({...o,sort_order:Number(o.sort_order)||0}),l(!1)};return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex flex-wrap items-end justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:"Resources"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Upload PDFs, worksheets and checklists — or link to Canva/Google templates. Enrollees see them grouped by category in their program dashboard."})]}),e.jsxs($,{onClick:p,children:[e.jsx(sn,{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(_e,{className:"border-dashed",children:e.jsxs(Oe,{className:"flex flex-col items-center gap-3 p-12 text-center",children:[e.jsx(Wr,{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(b=>{const v=_ee(b);return e.jsx(_e,{className:"border-border/60",children:e.jsxs(Oe,{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:b.title}),e.jsx($e,{variant:"secondary",children:b.category}),e.jsx($e,{variant:"outline",className:"capitalize",children:b.resource_kind.replace("_"," ")}),b.status!=="published"&&e.jsx($e,{variant:"outline",className:"capitalize",children:b.status})]}),b.description&&e.jsx("p",{className:"max-w-2xl text-sm text-muted-foreground",children:b.description}),v&&e.jsxs("button",{type:"button",onClick:()=>_Y(b),className:"inline-flex items-center gap-1 text-xs text-primary hover:underline",children:[e.jsx(Tr,{className:"h-3 w-3"})," Open"]})]}),e.jsxs("div",{className:"flex gap-1",children:[e.jsx($,{variant:"ghost",size:"icon",onClick:()=>x(b),children:e.jsx(Ya,{className:"h-4 w-4"})}),e.jsx($,{variant:"ghost",size:"icon",onClick:async()=>{await Yi(`Remove "${b.title}"?`)&&a.mutate(b)},children:e.jsx(Pn,{className:"h-4 w-4 text-destructive"})})]})]})},b.id)})}),e.jsx(Os,{open:i,onOpenChange:l,children:e.jsxs(Rs,{className:"max-w-lg",children:[e.jsx(Us,{children:e.jsx(zs,{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(se,{children:"Title"}),e.jsx(be,{value:o.title,onChange:b=>c({...o,title:b.target.value}),placeholder:"90-Day Content Calendar"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:"Description"}),e.jsx(Is,{rows:2,value:o.description,onChange:b=>c({...o,description:b.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(se,{children:"Category"}),e.jsx(be,{value:o.category,onChange:b=>c({...o,category:b.target.value}),placeholder:"Getting started",list:"program-resource-categories"}),e.jsx("datalist",{id:"program-resource-categories",children:m.map(b=>e.jsx("option",{value:b},b))})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:"Type"}),e.jsxs(vs,{value:o.resource_kind,onValueChange:b=>c({...o,resource_kind:b}),children:[e.jsx(gs,{children:e.jsx(bs,{})}),e.jsx(ys,{children:x6t.map(b=>e.jsx(Ye,{value:b.value,children:b.label},b.value))})]})]})]}),e.jsxs("div",{className:"space-y-2 rounded-lg border p-3",children:[e.jsx(se,{children:"File"}),e.jsx("input",{ref:h,type:"file",className:"hidden",accept:".pdf,.doc,.docx,.xls,.xlsx,.ppt,.pptx,.csv,.zip,image/*",onChange:b=>{var v;return g((v=b.target.files)==null?void 0:v[0])}}),o.file_path?e.jsxs("div",{className:"flex items-center justify-between gap-2 text-sm",children:[e.jsx("span",{className:"truncate",children:o.file_path.split("/").pop()}),e.jsx($,{variant:"ghost",size:"sm",onClick:()=>c({...o,file_path:""}),children:"Remove"})]}):e.jsxs($,{variant:"outline",size:"sm",onClick:()=>{var b;return(b=h.current)==null?void 0:b.click()},disabled:d,children:[d?e.jsx(Ht,{className:"mr-1.5 h-4 w-4 animate-spin"}):e.jsx(si,{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(be,{value:o.url,onChange:b=>c({...o,url:b.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(se,{children:"Status"}),e.jsxs(vs,{value:o.status,onValueChange:b=>c({...o,status:b}),children:[e.jsx(gs,{children:e.jsx(bs,{})}),e.jsxs(ys,{children:[e.jsx(Ye,{value:"published",children:"Published (visible)"}),e.jsx(Ye,{value:"draft",children:"Draft (hidden)"}),e.jsx(Ye,{value:"archived",children:"Archived"})]})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:"Sort order"}),e.jsx(be,{type:"number",value:o.sort_order,onChange:b=>c({...o,sort_order:b.target.value})})]})]})]}),e.jsxs(kr,{children:[e.jsx($,{variant:"outline",onClick:()=>l(!1),children:"Cancel"}),e.jsxs($,{onClick:y,disabled:r.isPending||d,children:[r.isPending&&e.jsx(Ht,{className:"mr-1.5 h-4 w-4 animate-spin"})," Save resource"]})]})]})})]})},URs=({programId:s})=>{const{data:t=[],isLoading:n}=dCs(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(on,{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(_e,{children:e.jsxs(Oe,{className:"flex items-center gap-3 p-4",children:[e.jsx($3,{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(_e,{children:e.jsxs(Oe,{className:"flex items-center gap-3 p-4",children:[e.jsx(qn,{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(_e,{children:e.jsx(Oe,{className:"flex items-center gap-3 p-4",children:e.jsxs($e,{variant:"secondary",children:[t.filter(l=>l.notified_at).length," notified"]})})})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs($,{variant:"outline",size:"sm",disabled:!a,onClick:()=>{navigator.clipboard.writeText(a),ae.success("Emails copied")},children:[e.jsx(Ca,{className:"mr-2 h-4 w-4"})," Copy emails"]}),e.jsxs($,{variant:"outline",size:"sm",disabled:!t.length,onClick:i,children:[e.jsx(di,{className:"mr-2 h-4 w-4"})," Export CSV"]})]}),t.length===0?e.jsx("p",{className:"rounded-lg border border-dashed p-8 text-center text-sm text-muted-foreground",children:"Nobody has asked to be notified yet."}):e.jsx("div",{className:"rounded-lg border",children:e.jsxs(Va,{children:[e.jsx(Ha,{children:e.jsxs(hn,{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(Ga,{children:t.map(l=>e.jsxs(hn,{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:gd(l.created_at)})]},l.id))})]})})]})},ndt={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:""},qRs=()=>{const s=ts(),[t,n]=j.useState(null),[r,a]=j.useState(!1),[i,l]=j.useState({...ndt}),[o,c]=j.useState(!1),[d,u]=j.useState(!1),[h,m]=j.useState(null),{data:p=[],isLoading:x}=ht({queryKey:["admin-programs"],queryFn:async()=>{const{data:M,error:I}=await U.from("programs").select("*").order("created_at",{ascending:!1});if(I)throw I;return M||[]}}),g=p.find(M=>M.id===t)||p[0]||null,{data:y=[]}=ht({queryKey:["admin-program-enrollments",g==null?void 0:g.id],enabled:!!(g!=null&&g.id),queryFn:async()=>{const{data:M,error:I}=await U.from("program_enrollments").select("*").eq("program_id",g.id).order("created_at",{ascending:!1});if(I)throw I;const D=(M||[]).map(W=>W.user_id),{data:B}=D.length?await U.from("profiles").select("id, name, email").in("id",D):{data:[]},q=new Map((B||[]).map(W=>[W.id,W]));return(M||[]).map(W=>({...W,profile:q.get(W.user_id)}))}}),{data:b=[]}=ht({queryKey:["admin-program-intakes",g==null?void 0:g.id],enabled:!!(g!=null&&g.id),queryFn:async()=>{const{data:M,error:I}=await U.from("program_intake_responses").select("*").eq("program_id",g.id);if(I)throw I;return M||[]}}),{data:v=[]}=ht({queryKey:["admin-program-audit",g==null?void 0:g.id],enabled:!!(g!=null&&g.id),queryFn:async()=>{const{data:M,error:I}=await U.from("program_audit_logs").select("*").eq("program_id",g.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 U.from("programs").insert(M);if(I)throw I;ae.success("Program created"),a(!1),l({...ndt}),s.invalidateQueries({queryKey:["admin-programs"]})}catch(M){ae.error(M.message||"Could not create the program")}finally{c(!1)}},C=async M=>{if(!g)return;const{error:I}=await U.from("programs").update(M).eq("id",g.id);if(I)return ae.error(I.message);s.invalidateQueries({queryKey:["admin-programs"]})},A=async(M,I)=>{const{error:D}=await U.from("program_enrollments").update(I).eq("id",M);if(D)return ae.error(D.message);ae.success("Enrollment updated"),s.invalidateQueries({queryKey:["admin-program-enrollments"]})},T=async M=>{u(!0);const{data:I,error:D}=await U.functions.invoke("program-charge-due",{body:M?{enrollment_id:M}:{}});if(u(!1),D||I!=null&&I.error)return ae.error((I==null?void 0:I.error)||(D==null?void 0:D.message));ae.success(`Processed ${(I==null?void 0:I.processed)??0} charge(s)`),s.invalidateQueries({queryKey:["admin-program-enrollments"]})},P=M=>M==="paid"||M==="completed"?"default":M==="payment_failed"?"destructive":"secondary";return e.jsx(Ks,{children:e.jsxs("div",{className:"mx-auto w-full max-w-7xl space-y-6 p-4 md:p-8",children:[e.jsxs("header",{className:"flex flex-wrap items-end justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold tracking-tight",children:"Programs"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Manage cohorts, enrollments, delayed billing and program content."})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs($,{variant:"outline",onClick:()=>T(),disabled:d,children:[d?e.jsx(Ht,{className:"mr-1.5 h-4 w-4 animate-spin"}):e.jsx(yy,{className:"mr-1.5 h-4 w-4"}),"Run due charges"]}),e.jsxs(Os,{open:r,onOpenChange:a,children:[e.jsx(Ko,{asChild:!0,children:e.jsxs($,{children:[e.jsx(sn,{className:"mr-1.5 h-4 w-4"})," New program"]})}),e.jsxs(Rs,{className:"max-h-[85vh] overflow-y-auto",children:[e.jsx(Us,{children:e.jsx(zs,{children:"Create a program"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Name"}),e.jsx(be,{value:i.name,onChange:M=>l({...i,name:M.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Slug (URL)"}),e.jsx(be,{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(se,{children:"Subtitle"}),e.jsx(be,{value:i.subtitle,onChange:M=>l({...i,subtitle:M.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Description"}),e.jsx(Is,{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(se,{children:"One-time price (USD)"}),e.jsx(be,{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(se,{children:"Seats"}),e.jsx(be,{type:"number",value:i.capacity,onChange:M=>l({...i,capacity:Number(M.target.value)})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Weeks"}),e.jsx(be,{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(se,{children:"Videos per week"}),e.jsx(be,{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(se,{children:"Billing"}),e.jsxs(vs,{value:i.payment_mode,onValueChange:M=>l({...i,payment_mode:M}),children:[e.jsx(gs,{children:e.jsx(bs,{})}),e.jsxs(ys,{children:[e.jsx(Ye,{value:"delayed",children:"Save card, charge later"}),e.jsx(Ye,{value:"immediate",children:"Charge at checkout"}),e.jsx(Ye,{value:"free",children:"Free / included"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Kickoff"}),e.jsx(be,{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(se,{children:"Charge date"}),e.jsx(be,{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(se,{children:"Enrollment closes"}),e.jsx(be,{type:"datetime-local",value:i.enrollment_close_at,onChange:M=>l({...i,enrollment_close_at:M.target.value})})]})]})]}),e.jsx(kr,{children:e.jsxs($,{onClick:N,disabled:o||!i.name,children:[o&&e.jsx(Ht,{className:"mr-1.5 h-4 w-4 animate-spin"})," Create"]})})]})]})]})]}),x?e.jsx(on,{className:"h-40 w-full rounded-xl"}):p.length===0?e.jsx(_e,{className:"border-dashed",children:e.jsx(Oe,{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($,{variant:(g==null?void 0:g.id)===M.id?"default":"outline",size:"sm",onClick:()=>n(M.id),children:[M.name,e.jsx($e,{variant:"secondary",className:"ml-2 capitalize",children:M.status})]},M.id))}),g&&e.jsxs(ua,{defaultValue:"overview",children:[e.jsxs(ha,{className:"flex w-full flex-wrap justify-start",children:[e.jsx(Qt,{value:"overview",children:"Overview"}),e.jsx(Qt,{value:"details",children:"Details & pricing"}),e.jsx(Qt,{value:"sessions",children:"Live sessions"}),e.jsx(Qt,{value:"videos",children:"On-demand videos"}),e.jsx(Qt,{value:"resources",children:"Resources"}),e.jsx(Qt,{value:"intake-form",children:"Intake form"}),e.jsx(Qt,{value:"discounts",children:"Discount codes"}),e.jsx(Qt,{value:"experience",children:"Enrollee experience"}),e.jsx(Qt,{value:"interest",children:"Interest list"}),e.jsxs(Qt,{value:"enrollments",children:["Enrollments (",y.length,")"]}),e.jsxs(Qt,{value:"intake",children:["Intake (",b.length,")"]}),e.jsx(Qt,{value:"audit",children:"Audit"})]}),e.jsxs(Jt,{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(_e,{children:e.jsxs(Oe,{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:[" / ",g.capacity]})]})]})}),e.jsx(_e,{children:e.jsxs(Oe,{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(_e,{children:e.jsxs(Oe,{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(_e,{children:e.jsxs(Oe,{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:Mp(y.filter(M=>["scheduled_for_charge","paid","completed"].includes(M.status)).reduce((M,I)=>M+(I.amount_cents||0),0),g.currency)})]})})]}),e.jsx(_e,{children:e.jsxs(Oe,{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(Tn,{checked:g.status==="published",onCheckedChange:M=>C({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(Tn,{checked:g.is_featured,onCheckedChange:M=>C({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:Mp(g.price_cents,g.currency)})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-muted-foreground",children:"Kickoff"}),e.jsx("p",{className:"font-medium",children:gd(g.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:gd(g.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(Jt,{value:"details",className:"mt-6",children:e.jsx(kRs,{program:g,onSaved:()=>s.invalidateQueries({queryKey:["admin-programs"]})})}),e.jsx(Jt,{value:"sessions",className:"mt-6",children:e.jsx(zRs,{programId:g.id})}),e.jsx(Jt,{value:"videos",className:"mt-6",children:e.jsx(BRs,{programId:g.id})}),e.jsx(Jt,{value:"resources",className:"mt-6",children:e.jsx($Rs,{programId:g.id})}),e.jsx(Jt,{value:"discounts",className:"mt-6",children:e.jsx(ARs,{program:g})}),e.jsx(Jt,{value:"intake-form",className:"mt-6",children:e.jsx(LRs,{program:g,onSaved:()=>s.invalidateQueries({queryKey:["admin-programs"]})})}),e.jsx(Jt,{value:"experience",className:"mt-6",children:e.jsx(ERs,{program:g})}),e.jsx(Jt,{value:"interest",className:"mt-6",children:e.jsx(URs,{programId:g.id})}),e.jsx(Jt,{value:"enrollments",className:"mt-6",children:e.jsx(_e,{children:e.jsx(Oe,{className:"overflow-x-auto p-0",children:e.jsxs(Va,{children:[e.jsx(Ha,{children:e.jsxs(hn,{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(Ga,{children:[y.length===0&&e.jsx(hn,{children:e.jsxs(gt,{colSpan:6,className:"py-10 text-center text-sm text-muted-foreground",children:[e.jsx(qn,{className:"mx-auto mb-2 h-5 w-5"}),"No enrollments yet"]})}),y.map(M=>{var I,D;return e.jsxs(hn,{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:(D=M.profile)==null?void 0:D.email})]})}),e.jsxs(gt,{children:[e.jsx($e,{variant:P(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:gd(M.charge_scheduled_at)||"—"}),e.jsx(gt,{className:"text-sm",children:Mp(M.amount_cents,M.currency)}),e.jsx(gt,{children:e.jsx(Tn,{checked:M.access_override,onCheckedChange:B=>A(M.id,{access_override:B})})}),e.jsxs(gt,{className:"space-x-2 text-right",children:[["scheduled_for_charge","payment_failed"].includes(M.status)&&e.jsxs($,{size:"sm",variant:"outline",onClick:()=>T(M.id),disabled:d,children:[e.jsx(Wi,{className:"mr-1.5 h-3.5 w-3.5"})," Charge now"]}),!["canceled","refunded"].includes(M.status)&&e.jsx($,{size:"sm",variant:"ghost",onClick:()=>A(M.id,{status:"canceled",canceled_at:new Date().toISOString()}),children:"Cancel"})]})]},M.id)})]})]})})})}),e.jsx(Jt,{value:"intake",className:"mt-6",children:e.jsx(RRs,{program:g})}),e.jsx(Jt,{value:"audit",className:"mt-6",children:e.jsx(_e,{children:e.jsxs(Oe,{className:"space-y-2 p-5 text-sm",children:[v.length===0&&e.jsx("p",{className:"text-muted-foreground",children:"No activity yet."}),v.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($e,{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:gd(M.created_at,!0)})]},M.id))]})})})]}),g&&e.jsx(CRs,{program:g,enrollment:h,open:!!h,onOpenChange:M=>!M&&m(null),onUpdated:()=>s.invalidateQueries({queryKey:["admin-program-enrollments"]})})]})]})})},VRs=()=>{const{user:s}=_s(),[t,n]=j.useState(""),[r,a]=j.useState("all"),{data:i=[]}=ht({queryKey:["academy-categories"],queryFn:async()=>{const{data:m,error:p}=await U.from("academy_categories").select("*").order("sort_order",{ascending:!0});if(p)throw p;return m}}),{data:l=[],isLoading:o}=ht({queryKey:["academy-videos"],queryFn:async()=>{const{data:m,error:p}=await U.from("academy_videos").select(` *, category:academy_categories(id, name) `).eq("is_published",!0).order("publish_date",{ascending:!1});if(p)throw p;const{data:x,error:g}=await U.from("academy_resources").select("*").order("sort_order");if(g)throw g;return m.map(b=>({...b,resources:(x==null?void 0:x.filter(v=>v.video_id===b.id))||[]}))}}),{data:c=[]}=ht({queryKey:["academy-video-likes"],queryFn:async()=>{const{data:m,error:p}=await U.from("academy_video_likes").select("video_id, user_id");if(p)throw p;return m}}),d=l.filter(m=>{var g;const p=t===""||m.title.toLowerCase().includes(t.toLowerCase())||((g=m.description)==null?void 0:g.toLowerCase().includes(t.toLowerCase())),x=r==="all"||m.category_id===r;return p&&x}),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(Ks,{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(Vr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(be,{placeholder:"Search videos...",value:t,onChange:m=>n(m.target.value),className:"pl-10"})]})}),e.jsx(ua,{value:r,onValueChange:a,children:e.jsxs(ha,{className:"w-full justify-start flex-wrap h-auto gap-2 bg-transparent p-0",children:[e.jsx(Qt,{value:"all",className:"data-[state=active]:bg-primary data-[state=active]:text-primary-foreground",children:"All Videos"}),i.map(m=>e.jsx(Qt,{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(_e,{children:e.jsxs(Oe,{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(Xr,{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(Wn,{to:`/academy/${m.id}`,children:e.jsxs(_e,{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(Xr,{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(Td,{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(Hr,{className:"h-3 w-3"}),m.duration]})]}),e.jsxs(Bt,{className:"pb-2",children:[e.jsx("div",{className:"flex items-start justify-between gap-2",children:e.jsx(Ut,{className:"text-lg line-clamp-2",children:m.title})}),m.category&&e.jsx($e,{variant:"secondary",className:"w-fit",children:m.category.name})]}),e.jsxs(Oe,{className:"pt-0",children:[m.description&&e.jsx(vr,{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(Ox,{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(Wr,{className:"h-4 w-4"}),m.resources.length]})]})]})]})},m.id))})]})})};function fPt({resourceType:s,resourceId:t}){const{data:n=[]}=ht({queryKey:["linked-templates",s,t],queryFn:async()=>{if(s==="academy_video"){const{data:r,error:a}=await U.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 U.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(Rc,{className:"h-4 w-4"}),"Related Templates"]}),e.jsx("div",{className:"flex flex-wrap gap-2",children:n.map(r=>e.jsx(Wn,{to:`/templates/${r.id}`,children:e.jsxs($e,{variant:"secondary",className:"cursor-pointer hover:bg-secondary/80 transition-colors gap-1.5 px-3 py-1.5 text-xs font-medium rounded-full",children:[e.jsx(Rc,{className:"h-3 w-3"}),r.name]})},r.id))})]})}const HRs=(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},GRs=()=>{const{videoId:s}=Vi();Vn();const{user:t,isAdmin:n}=_s(),{toast:r}=gi(),a=ts(),{trackEngagement:i}=Iq(),[l,o]=j.useState(""),{data:c,isLoading:d}=ht({queryKey:["academy-video",s],queryFn:async()=>{const{data:N,error:C}=await U.from("academy_videos").select(` *, category:academy_categories(id, name) `).eq("id",s).eq("is_published",!0).single();if(C)throw C;const{data:A}=await U.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=[]}=ht({queryKey:["academy-video-likes",s],queryFn:async()=>{const{data:N,error:C}=await U.from("academy_video_likes").select("*").eq("video_id",s);if(C)throw C;return N},enabled:!!s}),{data:h=[]}=ht({queryKey:["academy-video-comments",s],queryFn:async()=>{const{data:N,error:C}=await U.from("academy_video_comments").select("*").eq("video_id",s).order("created_at",{ascending:!1});if(C)throw C;const A=[...new Set(N.map(M=>M.user_id))],{data:T}=await U.from("profiles").select("id, name").in("id",A),P=new Map((T==null?void 0:T.map(M=>[M.id,M.name]))||[]);return N.map(M=>({...M,user_name:P.get(M.user_id)||"Unknown User"}))},enabled:!!s}),m=yt({mutationFn:async N=>{const{error:C}=await U.from("academy_video_comments").insert({video_id:s,user_id:t.id,content:N});if(C)throw C},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:C}=await U.from("academy_video_comments").delete().eq("id",N);if(C)throw C},onSuccess:()=>{a.invalidateQueries({queryKey:["academy-video-comments",s]}),r({title:"Comment deleted"})}}),x=yt({mutationFn:async()=>{const N=u.find(C=>C.user_id===(t==null?void 0:t.id));if(N){const{error:C}=await U.from("academy_video_likes").delete().eq("id",N.id);if(C)throw C}else{const{error:C}=await U.from("academy_video_likes").insert({video_id:s,user_id:t.id});if(C)throw C}},onSuccess:()=>{a.invalidateQueries({queryKey:["academy-video-likes",s]})}}),g=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"📁"}},b=N=>N.split(" ").map(C=>C[0]).join("").toUpperCase().slice(0,2),v=N=>{N.preventDefault(),!(!l.trim()||!t)&&m.mutate(l.trim())};return d?e.jsx(Ks,{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(Ks,{title:c.title,children:e.jsxs("div",{className:"space-y-6 max-w-5xl mx-auto",children:[e.jsx($,{variant:"ghost",size:"sm",asChild:!0,className:"gap-2",children:e.jsxs(Wn,{to:"/academy",children:[e.jsx(ka,{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:HRs(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(Xr,{className:"h-16 w-16 opacity-50"}),e.jsx($,{variant:"secondary",asChild:!0,children:e.jsxs("a",{href:c.video_url,target:"_blank",rel:"noopener noreferrer",className:"gap-2",children:[e.jsx(Tr,{className:"h-4 w-4"}),"Open Video"]})})]})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-start sm:justify-between gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("h1",{className:"text-2xl font-bold text-foreground",children:c.title}),c.category&&e.jsx($e,{variant:"secondary",children:c.category.name})]}),e.jsxs("div",{className:"flex gap-2",children:[n&&e.jsx($,{variant:"outline",className:"gap-2 rounded-full",asChild:!0,children:e.jsxs(Wn,{to:`/admin/academy?edit=${c.id}`,children:[e.jsx(Ya,{className:"h-4 w-4"}),e.jsx("span",{children:"Edit"})]})}),e.jsx(Fq,{resourceType:"academy_video",resourceId:c.id,resourceTitle:c.title}),e.jsxs($,{variant:g?"default":"outline",className:"gap-2 w-fit",onClick:()=>x.mutate(),disabled:!t||x.isPending,children:[e.jsx(Ox,{className:`h-4 w-4 ${g?"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(_e,{children:e.jsxs(Oe,{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"}),"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(di,{className:"h-4 w-4 text-muted-foreground"})]},N.id))})]})}),e.jsx(fPt,{resourceType:"academy_video",resourceId:c.id}),e.jsx(Hl,{}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("h3",{className:"font-semibold flex items-center gap-2 text-lg",children:[e.jsx(Ed,{className:"h-5 w-5"}),"Comments (",h.length,")"]}),t?e.jsxs("form",{onSubmit:v,className:"flex gap-2",children:[e.jsx(Is,{placeholder:"Add a comment...",value:l,onChange:N=>o(N.target.value),className:"min-h-[80px] resize-none flex-1"}),e.jsx($,{type:"submit",size:"icon",className:"h-10 w-10",disabled:!l.trim()||m.isPending,children:e.jsx(Br,{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(_e,{children:e.jsx(Oe,{className:"py-8 text-center",children:e.jsx("p",{className:"text-muted-foreground",children:"No comments yet. Be the first to share your thoughts!"})})}):h.map(N=>e.jsx(_e,{children:e.jsx(Oe,{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(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:fc(new Date(N.created_at),{addSuffix:!0})}),N.user_id===(t==null?void 0:t.id)&&e.jsx($,{variant:"ghost",size:"icon",className:"h-6 w-6 ml-auto",onClick:()=>p.mutate(N.id),children:e.jsx(Pn,{className:"h-3 w-3 text-muted-foreground"})})]}),e.jsx("p",{className:"text-sm whitespace-pre-wrap",children:N.content})]})]})})},N.id))})]})]})}):e.jsx(Ks,{title:"Academy",children:e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(Xr,{className:"h-12 w-12 text-muted-foreground mb-4"}),e.jsx("h3",{className:"text-lg font-semibold",children:"Video not found"}),e.jsx("p",{className:"text-muted-foreground mt-1",children:"This video may have been removed or is not available."}),e.jsx($,{asChild:!0,className:"mt-4",children:e.jsx(Wn,{to:"/academy",children:"Back to Academy"})})]})})},k7="https://dashboard.relevelup.com",WRs=(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},KRs=[{icon:Sh,title:"100+ Training Videos",desc:"On-demand LevelUp Academy content covering lead gen, listings, buyer conversion, marketing, and more."},{icon:ox,title:"Marketing Studio & Tools",desc:"AI-powered marketing tools, listing videos, landing pages, and social content — done for you."},{icon:qn,title:"Coaching & Community",desc:"Live coaching sessions, private community, and a network of top-performing agents."},{icon:pl,title:"Business Scorecard",desc:"Track your deals, GCI, and pipeline in one dashboard built for real estate."}];function YRs(){var i;const{slug:s}=Vi(),{data:t,isLoading:n,error:r}=ht({queryKey:["public-academy-video",s],queryFn:async()=>{if(!s)return null;const{data:l,error:o}=await U.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){U.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?WRs(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:k7,children:e.jsx($,{className:"bg-[#406E71] hover:bg-[#4d8285] text-white",children:"Go to LevelUp"})})]}):e.jsxs("div",{className:"min-h-screen bg-[#0a1520] text-[#e8ecf1] overflow-x-hidden",children:[e.jsxs("div",{className:"pointer-events-none fixed inset-0 z-0",children:[e.jsx("div",{className:"absolute -top-40 -left-40 w-[600px] h-[600px] rounded-full bg-[#406E71]/20 blur-3xl"}),e.jsx("div",{className:"absolute top-1/2 -right-40 w-[500px] h-[500px] rounded-full bg-[#2a4c64]/30 blur-3xl"}),e.jsx("div",{className:"absolute bottom-0 left-1/3 w-[400px] h-[400px] rounded-full bg-[#406E71]/10 blur-3xl"})]}),e.jsx("header",{className:"relative z-10 border-b border-white/5 backdrop-blur-sm bg-[#0a1520]/70",children:e.jsxs("div",{className:"max-w-7xl mx-auto px-6 py-5 flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"w-9 h-9 rounded-lg bg-gradient-to-br from-[#406E71] to-[#2a4c64] flex items-center justify-center",children:e.jsx(dn,{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:k7,children:e.jsx($,{variant:"ghost",className:"text-[#e8ecf1] hover:bg-white/5 hover:text-white",children:"Sign In"})})]})}),e.jsxs("section",{className:"relative z-10 max-w-6xl mx-auto px-6 pt-12 pb-16",children:[e.jsxs("div",{className:"text-center mb-8 space-y-4",children:[e.jsxs($e,{className:"bg-[#406E71]/20 text-[#7ec0c3] border-[#406E71]/40 hover:bg-[#406E71]/30",children:[e.jsx(Sh,{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(w0,{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:k7,className:"w-full sm:w-auto",children:e.jsxs($,{size:"lg",className:"w-full sm:w-auto bg-[#f5f0e0] hover:bg-white text-[#0d1b26] font-semibold text-base h-12 px-8 shadow-xl",children:["Start Free Trial",e.jsx(ni,{className:"w-4 h-4 ml-2"})]})}),e.jsx("a",{href:k7,className:"w-full sm:w-auto",children:e.jsx($,{size:"lg",variant:"outline",className:"w-full sm:w-auto bg-transparent border-white/20 text-white hover:bg-white/10 hover:text-white h-12 px-8",children:"Join LevelUp"})})]}),e.jsx("p",{className:"text-xs text-[#7a8a99] mt-5",children:"No credit card required to preview the platform"})]})]})}),e.jsxs("section",{className:"relative z-10 max-w-6xl mx-auto px-6 pb-20",children:[e.jsxs("div",{className:"text-center mb-10",children:[e.jsx("div",{className:"text-xs uppercase tracking-[0.25em] text-[#5a9ea1] mb-2",children:"What's inside"}),e.jsx("h3",{className:"text-2xl md:text-3xl font-bold",children:"Built for agents who want more"})]}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:KRs.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(Fr,{className:"w-4 h-4 text-[#7ec0c3]"})," Trusted by top producers"]}),e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(Fr,{className:"w-4 h-4 text-[#7ec0c3]"})," New training weekly"]}),e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(Fr,{className:"w-4 h-4 text-[#7ec0c3]"})," Cancel anytime"]})]}),e.jsx("div",{className:"text-center",children:e.jsx("a",{href:k7,children:e.jsxs($,{size:"lg",className:"bg-[#406E71] hover:bg-[#4d8285] text-white h-12 px-10 shadow-lg",children:["Get Started at LevelUp",e.jsx(ni,{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:k7,className:"hover:text-[#7ec0c3]",children:"dashboard.relevelup.com"})]})]})}function ZRs(){const s=Vn(),[t,n]=j.useState(""),{data:r,isLoading:a}=ht({queryKey:["resource-kits-published"],queryFn:async()=>{const{data:p,error:x}=await U.from("resource_kits").select("*").eq("is_published",!0).order("publish_date",{ascending:!1});if(x)throw x;return p}}),{data:i}=ht({queryKey:["resource-kit-files-all"],queryFn:async()=>{const{data:p,error:x}=await U.from("resource_kit_files").select("*").order("sort_order",{ascending:!0});if(x)throw x;return p}}),{data:l}=ht({queryKey:["resource-kit-likes-all"],queryFn:async()=>{const{data:p,error:x}=await U.from("resource_kit_likes").select("kit_id");if(x)throw x;return p}}),{data:o}=ht({queryKey:["resource-kit-comments-all"],queryFn:async()=>{const{data:p,error:x}=await U.from("resource_kit_comments").select("kit_id");if(x)throw x;return p}}),c=r==null?void 0:r.filter(p=>{var x;return p.name.toLowerCase().includes(t.toLowerCase())||((x=p.description)==null?void 0:x.toLowerCase().includes(t.toLowerCase()))}),d=p=>(i==null?void 0:i.filter(x=>x.kit_id===p))||[],u=p=>(l==null?void 0:l.filter(x=>x.kit_id===p).length)||0,h=p=>(o==null?void 0:o.filter(x=>x.kit_id===p).length)||0,m=p=>{s(`/toolbox/${p}`)};return e.jsx(Ks,{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(Vr,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(be,{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,x)=>e.jsx(_e,{children:e.jsxs(Oe,{className:"p-4",children:[e.jsx(on,{className:"aspect-[4/3] w-full rounded-lg mb-4"}),e.jsx(on,{className:"h-5 w-3/4 mb-2"}),e.jsx(on,{className:"h-4 w-full mb-4"}),e.jsx(on,{className:"h-4 w-2/3"})]})},x))}):(c==null?void 0:c.length)===0?e.jsxs(_e,{className:"p-12 text-center",children:[e.jsx(Tu,{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 x=d(p.id).length,g=u(p.id),y=h(p.id);return e.jsxs(_e,{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(Tu,{className:"h-16 w-16 text-muted-foreground"})})}),e.jsxs(Oe,{className:"p-4",children:[e.jsx("h3",{className:"font-semibold text-foreground line-clamp-1 mb-1",children:p.name}),p.description&&e.jsx("p",{className:"text-sm text-muted-foreground line-clamp-2 mb-3",children:EZ(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(Wr,{className:"h-4 w-4"}),x," file",x!==1?"s":""]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Ox,{className:"h-3.5 w-3.5"}),g]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Ed,{className:"h-3.5 w-3.5"}),y]})]})]})]})]},p.id)})})]})})}const XRs=()=>{const{kitId:s}=Vi(),{user:t,isAdmin:n}=_s(),{toast:r}=gi(),a=ts(),{trackEngagement:i}=Iq(),[l,o]=j.useState(""),{data:c,isLoading:d}=ht({queryKey:["resource-kit-detail",s],queryFn:async()=>{const{data:N,error:C}=await U.from("resource_kits").select("*").eq("id",s).eq("is_published",!0).single();if(C)throw C;const{data:A}=await U.from("resource_kit_files").select("*").eq("kit_id",s).order("sort_order"),{data:T}=await U.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=[]}=ht({queryKey:["resource-kit-likes",s],queryFn:async()=>{const{data:N,error:C}=await U.from("resource_kit_likes").select("*").eq("kit_id",s);if(C)throw C;return N},enabled:!!s}),{data:h=[]}=ht({queryKey:["resource-kit-comments",s],queryFn:async()=>{const{data:N,error:C}=await U.from("resource_kit_comments").select("*").eq("kit_id",s).order("created_at",{ascending:!1});if(C)throw C;const A=[...new Set(N.map(M=>M.user_id))],{data:T}=await U.from("profiles").select("id, name").in("id",A),P=new Map((T==null?void 0:T.map(M=>[M.id,M.name]))||[]);return N.map(M=>({...M,user_name:P.get(M.user_id)||"Unknown User"}))},enabled:!!s}),m=yt({mutationFn:async N=>{const{error:C}=await U.from("resource_kit_comments").insert({kit_id:s,user_id:t.id,content:N});if(C)throw C},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:C}=await U.from("resource_kit_comments").delete().eq("id",N);if(C)throw C},onSuccess:()=>{a.invalidateQueries({queryKey:["resource-kit-comments",s]}),r({title:"Comment deleted"})}}),x=yt({mutationFn:async()=>{const N=u.find(C=>C.user_id===(t==null?void 0:t.id));if(N){const{error:C}=await U.from("resource_kit_likes").delete().eq("id",N.id);if(C)throw C}else{const{error:C}=await U.from("resource_kit_likes").insert({kit_id:s,user_id:t.id});if(C)throw C}},onSuccess:()=>{a.invalidateQueries({queryKey:["resource-kit-likes",s]})}}),g=u.some(N=>N.user_id===(t==null?void 0:t.id)),y=N=>N.split(" ").map(C=>C[0]).join("").toUpperCase().slice(0,2),b=N=>N?N<1024?N+" B":N<1024*1024?(N/1024).toFixed(1)+" KB":(N/(1024*1024)).toFixed(1)+" MB":"",v=N=>{N.preventDefault(),!(!l.trim()||!t)&&m.mutate(l.trim())};return d?e.jsx(Ks,{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(Ks,{title:c.name,children:e.jsxs("div",{className:"space-y-6 max-w-5xl mx-auto",children:[e.jsx($,{variant:"ghost",size:"sm",asChild:!0,className:"gap-2",children:e.jsxs(Wn,{to:"/toolbox",children:[e.jsx(ka,{className:"h-4 w-4"}),"Back to Toolbox"]})}),c.featured_image_url&&e.jsx("div",{className:"relative w-full rounded-lg overflow-hidden bg-muted",children:e.jsx("img",{src:c.featured_image_url,alt:c.name,className:"w-full max-h-[400px] object-cover"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-start sm:justify-between gap-4",children:[e.jsx("div",{className:"space-y-2",children:e.jsx("h1",{className:"text-2xl font-bold text-foreground",children:c.name})}),e.jsxs("div",{className:"flex items-center gap-2",children:[n&&e.jsx($,{variant:"outline",className:"gap-2 rounded-full",asChild:!0,children:e.jsxs(Wn,{to:`/admin/toolbox?edit=${c.id}`,children:[e.jsx(Ya,{className:"h-4 w-4"}),e.jsx("span",{children:"Edit"})]})}),e.jsx(Fq,{resourceType:"resource_kit",resourceId:c.id,resourceTitle:c.name,size:"default",className:"rounded-full"}),e.jsxs($,{variant:g?"default":"outline",className:"gap-2 rounded-full",onClick:()=>x.mutate(),disabled:!t||x.isPending,children:[e.jsx(Ox,{className:`h-4 w-4 ${g?"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(_e,{children:e.jsxs(Oe,{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"}),"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(Wr,{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:b(N.file_size)})]})]}),e.jsx(di,{className:"h-4 w-4 text-muted-foreground group-hover:text-primary transition-colors"})]},N.id))})]})}),c.links&&c.links.length>0&&e.jsx(_e,{children:e.jsxs(Oe,{className:"pt-6",children:[e.jsxs("h3",{className:"font-semibold flex items-center gap-2 mb-4",children:[e.jsx(Tr,{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(Tr,{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(fPt,{resourceType:"resource_kit",resourceId:c.id}),e.jsx(Hl,{}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("h3",{className:"font-semibold flex items-center gap-2 text-lg",children:[e.jsx(Ed,{className:"h-5 w-5"}),"Comments (",h.length,")"]}),t?e.jsxs("form",{onSubmit:v,className:"flex gap-2",children:[e.jsx(Is,{placeholder:"Add a comment...",value:l,onChange:N=>o(N.target.value),className:"min-h-[80px] resize-none flex-1"}),e.jsx($,{type:"submit",size:"icon",className:"h-10 w-10",disabled:!l.trim()||m.isPending,children:e.jsx(Br,{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(_e,{children:e.jsx(Oe,{className:"py-8 text-center",children:e.jsx("p",{className:"text-muted-foreground",children:"No comments yet. Be the first to share your thoughts!"})})}):h.map(N=>e.jsx(_e,{children:e.jsx(Oe,{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:fc(new Date(N.created_at),{addSuffix:!0})}),N.user_id===(t==null?void 0:t.id)&&e.jsx($,{variant:"ghost",size:"icon",className:"h-6 w-6 ml-auto",onClick:()=>p.mutate(N.id),children:e.jsx(Pn,{className:"h-3 w-3 text-muted-foreground"})})]}),e.jsx("p",{className:"text-sm whitespace-pre-wrap",children:N.content})]})]})})},N.id))})]})]})}):e.jsx(Ks,{title:"Toolbox",children:e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(Tu,{className:"h-12 w-12 text-muted-foreground mb-4"}),e.jsx("h3",{className:"text-lg font-semibold",children:"Resource kit not found"}),e.jsx("p",{className:"text-muted-foreground mt-1",children:"This resource kit may have been removed or is not available."}),e.jsx($,{asChild:!0,className:"mt-4",children:e.jsx(Wn,{to:"/toolbox",children:"Back to Toolbox"})})]})})},QRs=()=>{const s=Vn(),[t,n]=j.useState(""),[r,a]=j.useState("grid"),{data:i=[],isLoading:l}=ht({queryKey:["social-swag"],queryFn:async()=>{const{data:d,error:u}=await U.from("social_swag").select("*").eq("is_published",!0).order("publish_date",{ascending:!1});if(u)throw u;const{data:h,error:m}=await U.from("social_swag_links").select("*").order("sort_order");if(m)throw m;const{data:p}=await U.from("social_swag_likes").select("swag_id"),{data:x}=await U.from("social_swag_comments").select("swag_id"),g=new Map;p==null||p.forEach(v=>{g.set(v.swag_id,(g.get(v.swag_id)||0)+1)});const y=new Map;return x==null||x.forEach(v=>{y.set(v.swag_id,(y.get(v.swag_id)||0)+1)}),(d||[]).map(v=>({...v,links:(h||[]).filter(N=>N.swag_id===v.id)||[],likesCount:g.get(v.id)||0,commentsCount:y.get(v.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(Ks,{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(Vr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(be,{placeholder:"Search social swag...",value:t,onChange:d=>n(d.target.value),className:"pl-9"})]}),e.jsxs("div",{className:"flex gap-2",children:[t&&e.jsx($,{variant:"outline",size:"sm",onClick:()=>n(""),children:"Clear"}),e.jsxs("div",{className:"flex gap-1",children:[e.jsx($,{variant:r==="grid"?"secondary":"outline",size:"icon",onClick:()=>a("grid"),className:"rounded-full",children:e.jsx(_0,{className:"h-4 w-4"})}),e.jsx($,{variant:r==="list"?"secondary":"outline",size:"icon",onClick:()=>a("list"),className:"rounded-full",children:e.jsx(Sg,{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(_e,{children:e.jsxs(Oe,{className:"p-4",children:[e.jsx(on,{className:"aspect-[4/3] w-full rounded-lg mb-4"}),e.jsx(on,{className:"h-5 w-3/4 mb-2"}),e.jsx(on,{className:"h-4 w-full mb-4"})]})},u))}),!l&&o.length===0&&e.jsxs("div",{className:"text-center py-12",children:[e.jsx("div",{className:"text-muted-foreground mb-4",children:t?"No items match your search":"No social swag available yet"}),t&&e.jsx($,{variant:"outline",onClick:()=>n(""),children:"Clear Search"})]}),!l&&o.length>0&&e.jsx("div",{className:r==="grid"?"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6":"space-y-4",children:o.map(d=>e.jsxs(_e,{className:`group overflow-hidden hover:shadow-lg transition-all duration-200 cursor-pointer ${r==="list"?"flex flex-row":""}`,onClick:()=>c(d.id),children:[e.jsxs("div",{className:`relative overflow-hidden bg-muted ${r==="list"?"w-48 shrink-0":"aspect-[3/2]"}`,children:[d.preview_image_url?e.jsx("img",{src:d.preview_image_url,alt:d.title,className:"w-full h-full object-cover group-hover:scale-105 transition-transform duration-300"}):e.jsx("div",{className:"w-full h-full flex items-center justify-center text-muted-foreground",children:"No Preview"}),d.links.length>1&&e.jsx("div",{className:"absolute top-2 right-2",children:e.jsxs($e,{variant:"secondary",className:"gap-1 bg-background/90 backdrop-blur-sm",children:[e.jsx(kc,{className:"h-3 w-3"}),d.links.length]})})]}),e.jsxs(Oe,{className:`p-4 flex flex-col ${r==="list"?"flex-1":""}`,children:[e.jsx("h3",{className:"font-semibold text-foreground line-clamp-1 mb-1",children: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(Ox,{className:"h-3.5 w-3.5"}),d.likesCount]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Ed,{className:"h-3.5 w-3.5"}),d.commentsCount]})]}),e.jsxs($,{size:"sm",className:"w-full gap-2",onClick:u=>{u.stopPropagation(),c(d.id)},children:[e.jsx(Tr,{className:"h-4 w-4"}),"View Details"]})]})]},d.id))})]})})};var gl=function(){return gl=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(MOs,{displayMonth:s.displayMonth,hideNext:u,hidePrevious:h,nextMonth:a,previousMonth:r,onPreviousClick:m,onNextClick:p})}function LOs(s){var t,n=sm(),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:yPt,d;return a?d=e.jsx(c,{id:s.id,displayMonth:s.displayMonth}):l==="dropdown"?d=e.jsx(rdt,{displayMonth:s.displayMonth,id:s.id}):l==="dropdown-buttons"?d=e.jsxs(e.Fragment,{children:[e.jsx(rdt,{displayMonth:s.displayMonth,displayIndex:s.displayIndex,id:s.id}),e.jsx(adt,{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(adt,{displayMonth:s.displayMonth,id:s.id})]}),e.jsx("div",{className:r.caption,style:i.caption,children:d})}function POs(s){var t=sm(),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 IOs(s,t,n){for(var r=n?dC(new Date):Tg(new Date,{locale:s,weekStartsOn:t}),a=[],i=0;i<7;i++){var l=Bd(r,i);a.push(l)}return a}function DOs(){var s=sm(),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=IOs(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 ROs(){var s,t=sm(),n=t.classNames,r=t.styles,a=t.components,i=(s=a==null?void 0:a.HeadRow)!==null&&s!==void 0?s:DOs;return e.jsx("thead",{style:r.head,className:n.head,children:e.jsx(i,{})})}function OOs(s){var t=sm(),n=t.locale,r=t.formatters.formatDay;return e.jsx(e.Fragment,{children:r(s.date,{locale:n})})}var yWe=j.createContext(void 0);function FOs(s){if(!Aee(s.initialProps)){var t={selected:void 0,modifiers:{disabled:[]}};return e.jsx(yWe.Provider,{value:t,children:s.children})}return e.jsx(zOs,{initialProps:s.initialProps,children:s.children})}function zOs(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 x=!!(u.selected&&a&&(r==null?void 0:r.length)===a);if(!x){var g=!!(!u.selected&&i&&(r==null?void 0:r.length)===i);if(!g){var y=r?xPt([],r):[];if(u.selected){var b=y.findIndex(function(v){return hu(d,v)});y.splice(b,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 hu(m,d)});return!!(u&&!h)});var c={selected:r,onDayClick:l,modifiers:o};return e.jsx(yWe.Provider,{value:c,children:n})}function vWe(){var s=j.useContext(yWe);if(!s)throw new Error("useSelectMultiple must be used within a SelectMultipleProvider");return s}function BOs(s,t){var n=t||{},r=n.from,a=n.to;return r&&a?hu(a,s)&&hu(r,s)?void 0:hu(a,s)?{from:a,to:void 0}:hu(r,s)?void 0:Pb(r,s)?{from:s,to:a}:{from:r,to:s}:a?Pb(s,a)?{from:a,to:s}:{from:s,to:a}:r?aw(s,r)?{from:s,to:r}:{from:r,to:s}:{from:s,to:void 0}}var bWe=j.createContext(void 0);function $Os(s){if(!Eee(s.initialProps)){var t={selected:void 0,modifiers:{range_start:[],range_end:[],range_middle:[],disabled:[]}};return e.jsx(bWe.Provider,{value:t,children:s.children})}return e.jsx(UOs,{initialProps:s.initialProps,children:s.children})}function UOs(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,x,g){var y,b;(y=t.onDayClick)===null||y===void 0||y.call(t,p,x,g);var v=BOs(p,r);(b=t.onSelect)===null||b===void 0||b.call(t,v,p,x,g)},u={range_start:[],range_end:[],range_middle:[],disabled:[]};if(i?(u.range_start=[i],l?(u.range_end=[l],hu(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:fY(i,o-1),before:Bd(i,o-1)}),i&&l&&u.disabled.push({after:i,before:Bd(i,o-1)}),!i&&l&&u.disabled.push({after:fY(l,o-1),before:Bd(l,o-1)})),c){if(i&&!l&&(u.disabled.push({before:Bd(i,-c+1)}),u.disabled.push({after:Bd(i,c-1)})),i&&l){var h=av(l,i)+1,m=c-h;u.disabled.push({before:fY(i,m)}),u.disabled.push({after:Bd(l,m)})}!i&&l&&(u.disabled.push({before:Bd(l,-c+1)}),u.disabled.push({after:Bd(l,c-1)}))}return e.jsx(bWe.Provider,{value:{selected:r,onDayClick:d,modifiers:u},children:n})}function _We(){var s=j.useContext(bWe);if(!s)throw new Error("useSelectRange must be used within a SelectRangeProvider");return s}function F2e(s){return Array.isArray(s)?xPt([],s):s!==void 0?[s]:[]}function qOs(s){var t={};return Object.entries(s).forEach(function(n){var r=n[0],a=n[1];t[r]=F2e(a)}),t}var WN;(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"})(WN||(WN={}));var VOs=WN.Selected,j4=WN.Disabled,HOs=WN.Hidden,GOs=WN.Today,rIe=WN.RangeEnd,aIe=WN.RangeMiddle,iIe=WN.RangeStart,WOs=WN.Outside;function KOs(s,t,n){var r,a=(r={},r[VOs]=F2e(s.selected),r[j4]=F2e(s.disabled),r[HOs]=F2e(s.hidden),r[GOs]=[s.today],r[rIe]=[],r[aIe]=[],r[iIe]=[],r[WOs]=[],r);return s.fromDate&&a[j4].push({before:s.fromDate}),s.toDate&&a[j4].push({after:s.toDate}),Aee(s)?a[j4]=a[j4].concat(t.modifiers[j4]):Eee(s)&&(a[j4]=a[j4].concat(n.modifiers[j4]),a[iIe]=n.modifiers[iIe],a[aIe]=n.modifiers[aIe],a[rIe]=n.modifiers[rIe]),a}var _Pt=j.createContext(void 0);function YOs(s){var t=sm(),n=vWe(),r=_We(),a=KOs(t,n,r),i=qOs(t.modifiers),l=gl(gl({},a),i);return e.jsx(_Pt.Provider,{value:l,children:s.children})}function wPt(){var s=j.useContext(_Pt);if(!s)throw new Error("useModifiers must be used within a ModifiersProvider");return s}function ZOs(s){return!!(s&&typeof s=="object"&&"before"in s&&"after"in s)}function XOs(s){return!!(s&&typeof s=="object"&&"from"in s)}function QOs(s){return!!(s&&typeof s=="object"&&"after"in s)}function JOs(s){return!!(s&&typeof s=="object"&&"before"in s)}function eFs(s){return!!(s&&typeof s=="object"&&"dayOfWeek"in s)}function tFs(s,t){var n,r=t.from,a=t.to;if(r&&a){var i=av(a,r)<0;i&&(n=[a,r],r=n[0],a=n[1]);var l=av(s,r)>=0&&av(a,s)>=0;return l}return a?hu(a,s):r?hu(r,s):!1}function sFs(s){return lHe(s)}function nFs(s){return Array.isArray(s)&&s.every(lHe)}function rFs(s,t){return t.some(function(n){if(typeof n=="boolean")return n;if(sFs(n))return hu(s,n);if(nFs(n))return n.includes(s);if(XOs(n))return tFs(s,n);if(eFs(n))return n.dayOfWeek.includes(s.getDay());if(ZOs(n)){var r=av(n.before,s),a=av(n.after,s),i=r>0,l=a<0,o=Pb(n.before,n.after);return o?l&&i:i||l}return QOs(n)?av(s,n.after)>0:JOs(n)?av(n.before,s)>0:typeof n=="function"?n(s):!1})}function wWe(s,t,n){var r=Object.keys(t).reduce(function(i,l){var o=t[l];return rFs(s,o)&&i.push(l),i},[]),a={};return r.forEach(function(i){return a[i]=!0}),n&&!Cq(s,n)&&(a.outside=!0),a}function aFs(s,t){for(var n=Hu(s[0]),r=e1(s[s.length-1]),a,i,l=n;l<=r;){var o=wWe(l,t),c=!o.disabled&&!o.hidden;if(!c){l=Bd(l,1);continue}if(o.selected)return l;o.today&&!i&&(i=l),a||(a=l),l=Bd(l,1)}return i||a}var iFs=365;function jPt(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:Bd,week:P3,month:zx,year:U0s,startOfWeek:function(y){return a.ISOWeek?dC(y):Tg(y,{locale:h,weekStartsOn:c})},endOfWeek:function(y){return a.ISOWeek?aCt(y):eU(y,{locale:h,weekStartsOn:c})}},p=m[n](s,r==="after"?1:-1);r==="before"&&d?p=q0s([d,p]):r==="after"&&u&&(p=V0s([u,p]));var x=!0;if(i){var g=wWe(p,i);x=!g.disabled&&!g.hidden}return x?p:o.count>iFs?o.lastFocused:jPt(p,{moveBy:n,direction:r,context:a,modifiers:i,retry:gl(gl({},o),{count:o.count+1})})}var NPt=j.createContext(void 0);function oFs(s){var t=Tee(),n=wPt(),r=j.useState(),a=r[0],i=r[1],l=j.useState(),o=l[0],c=l[1],d=aFs(t.displayMonths,n),u=a??(o&&t.isDateDisplayed(o))?o:d,h=function(){c(a),i(void 0)},m=function(y){i(y)},p=sm(),x=function(y,b){if(a){var v=jPt(a,{moveBy:y,direction:b,context:p,modifiers:n});hu(a,v)||(t.goToDate(v,a),m(v))}},g={focusedDay:a,focusTarget:u,blur:h,focus:m,focusDayAfter:function(){return x("day","after")},focusDayBefore:function(){return x("day","before")},focusWeekAfter:function(){return x("week","after")},focusWeekBefore:function(){return x("week","before")},focusMonthBefore:function(){return x("month","before")},focusMonthAfter:function(){return x("month","after")},focusYearBefore:function(){return x("year","before")},focusYearAfter:function(){return x("year","after")},focusStartOfWeek:function(){return x("startOfWeek","before")},focusEndOfWeek:function(){return x("endOfWeek","after")}};return e.jsx(NPt.Provider,{value:g,children:s.children})}function jWe(){var s=j.useContext(NPt);if(!s)throw new Error("useFocusContext must be used within a FocusProvider");return s}function lFs(s,t){var n=wPt(),r=wWe(s,n,t);return r}var NWe=j.createContext(void 0);function cFs(s){if(!jAe(s.initialProps)){var t={selected:void 0};return e.jsx(NWe.Provider,{value:t,children:s.children})}return e.jsx(dFs,{initialProps:s.initialProps,children:s.children})}function dFs(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(NWe.Provider,{value:a,children:n})}function kPt(){var s=j.useContext(NWe);if(!s)throw new Error("useSelectSingle must be used within a SelectSingleProvider");return s}function uFs(s,t){var n=sm(),r=kPt(),a=vWe(),i=_We(),l=jWe(),o=l.focusDayAfter,c=l.focusDayBefore,d=l.focusWeekAfter,u=l.focusWeekBefore,h=l.blur,m=l.focus,p=l.focusMonthBefore,x=l.focusMonthAfter,g=l.focusYearBefore,y=l.focusYearAfter,b=l.focusStartOfWeek,v=l.focusEndOfWeek,N=function(J){var ce,ue,ne,ee;jAe(n)?(ce=r.onDayClick)===null||ce===void 0||ce.call(r,s,t,J):Aee(n)?(ue=a.onDayClick)===null||ue===void 0||ue.call(a,s,t,J):Eee(n)?(ne=i.onDayClick)===null||ne===void 0||ne.call(i,s,t,J):(ee=n.onDayClick)===null||ee===void 0||ee.call(n,s,t,J)},C=function(J){var ce;m(s),(ce=n.onDayFocus)===null||ce===void 0||ce.call(n,s,t,J)},A=function(J){var ce;h(),(ce=n.onDayBlur)===null||ce===void 0||ce.call(n,s,t,J)},T=function(J){var ce;(ce=n.onDayMouseEnter)===null||ce===void 0||ce.call(n,s,t,J)},P=function(J){var ce;(ce=n.onDayMouseLeave)===null||ce===void 0||ce.call(n,s,t,J)},M=function(J){var ce;(ce=n.onDayPointerEnter)===null||ce===void 0||ce.call(n,s,t,J)},I=function(J){var ce;(ce=n.onDayPointerLeave)===null||ce===void 0||ce.call(n,s,t,J)},D=function(J){var ce;(ce=n.onDayTouchCancel)===null||ce===void 0||ce.call(n,s,t,J)},B=function(J){var ce;(ce=n.onDayTouchEnd)===null||ce===void 0||ce.call(n,s,t,J)},q=function(J){var ce;(ce=n.onDayTouchMove)===null||ce===void 0||ce.call(n,s,t,J)},W=function(J){var ce;(ce=n.onDayTouchStart)===null||ce===void 0||ce.call(n,s,t,J)},V=function(J){var ce;(ce=n.onDayKeyUp)===null||ce===void 0||ce.call(n,s,t,J)},K=function(J){var ce;switch(J.key){case"ArrowLeft":J.preventDefault(),J.stopPropagation(),n.dir==="rtl"?o():c();break;case"ArrowRight":J.preventDefault(),J.stopPropagation(),n.dir==="rtl"?c():o();break;case"ArrowDown":J.preventDefault(),J.stopPropagation(),d();break;case"ArrowUp":J.preventDefault(),J.stopPropagation(),u();break;case"PageUp":J.preventDefault(),J.stopPropagation(),J.shiftKey?g():p();break;case"PageDown":J.preventDefault(),J.stopPropagation(),J.shiftKey?y():x();break;case"Home":J.preventDefault(),J.stopPropagation(),b();break;case"End":J.preventDefault(),J.stopPropagation(),v();break}(ce=n.onDayKeyDown)===null||ce===void 0||ce.call(n,s,t,J)},Q={onClick:N,onFocus:C,onBlur:A,onKeyDown:K,onKeyUp:V,onMouseEnter:T,onMouseLeave:P,onPointerEnter:M,onPointerLeave:I,onTouchCancel:D,onTouchEnd:B,onTouchMove:q,onTouchStart:W};return Q}function hFs(){var s=sm(),t=kPt(),n=vWe(),r=_We(),a=jAe(s)?t.selected:Aee(s)?n.selected:Eee(s)?r.selected:void 0;return a}function mFs(s){return Object.values(WN).includes(s)}function pFs(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(mFs(r)){var i=s.classNames["day_".concat(r)];i&&n.push(i)}}),n}function fFs(s,t){var n=gl({},s.styles.day);return Object.keys(t).forEach(function(r){var a;n=gl(gl({},n),(a=s.modifiersStyles)===null||a===void 0?void 0:a[r])}),n}function xFs(s,t,n){var r,a,i,l=sm(),o=jWe(),c=lFs(s,t),d=uFs(s,c),u=hFs(),h=!!(l.onDayClick||l.mode!=="default");j.useEffect(function(){var T;c.outside||o.focusedDay&&h&&hu(o.focusedDay,s)&&((T=n.current)===null||T===void 0||T.focus())},[o.focusedDay,s,n,h,c.outside]);var m=pFs(l,c).join(" "),p=fFs(l,c),x=!!(c.outside&&!l.showOutsideDays||c.hidden),g=(i=(a=l.components)===null||a===void 0?void 0:a.DayContent)!==null&&i!==void 0?i:OOs,y=e.jsx(g,{date:s,displayMonth:t,activeModifiers:c}),b={style:p,className:m,children:y,role:"gridcell"},v=o.focusTarget&&hu(o.focusTarget,s)&&!c.outside,N=o.focusedDay&&hu(o.focusedDay,s),C=gl(gl(gl({},b),(r={disabled:c.disabled,role:"gridcell"},r["aria-selected"]=c.selected,r.tabIndex=N||v?0:-1,r)),d),A={isButton:h,isHidden:x,activeModifiers:c,selectedDays:u,buttonProps:C,divProps:b};return A}function gFs(s){var t=j.useRef(null),n=xFs(s.date,s.displayMonth,t);return n.isHidden?e.jsx("div",{role:"gridcell"}):n.isButton?e.jsx(YSe,gl({name:"day",ref:t},n.buttonProps)):e.jsx("div",gl({},n.divProps))}function yFs(s){var t=s.number,n=s.dates,r=sm(),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(YSe,{name:"week-number","aria-label":h,className:l.weeknumber,style:i.weeknumber,onClick:m,children:u})}function vFs(s){var t,n,r=sm(),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:gFs,d=(n=o==null?void 0:o.WeekNumber)!==null&&n!==void 0?n:yFs,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})},Wys(h))})]})}function idt(s,t,n){for(var r=n!=null&&n.ISOWeek?aCt(t):eU(t,n),a=n!=null&&n.ISOWeek?dC(s):Tg(s,n),i=av(r,a),l=[],o=0;o<=i;o++)l.push(Bd(a,o));var c=l.reduce(function(d,u){var h=n!=null&&n.ISOWeek?cHe(u):uHe(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 bFs(s,t){var n=idt(Hu(s),e1(s),t);if(t!=null&&t.useFixedWeeks){var r=Yys(s,t);if(r<6){var a=n[n.length-1],i=a.dates[a.dates.length-1],l=P3(i,6-r),o=idt(P3(i,1),l,t);n.push.apply(n,o)}}return n}function _Fs(s){var t,n,r,a=sm(),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,x=bFs(s.displayMonth,{useFixedWeeks:!!d,ISOWeek:p,locale:i,weekStartsOn:h,firstWeekContainsDate:m}),g=(t=u==null?void 0:u.Head)!==null&&t!==void 0?t:ROs,y=(n=u==null?void 0:u.Row)!==null&&n!==void 0?n:vFs,b=(r=u==null?void 0:u.Footer)!==null&&r!==void 0?r:POs;return e.jsxs("table",{id:s.id,className:l.table,style:o.table,role:"grid","aria-labelledby":s["aria-labelledby"],children:[!c&&e.jsx(g,{}),e.jsx("tbody",{className:l.tbody,style:o.tbody,children:x.map(function(v){return e.jsx(y,{displayMonth:s.displayMonth,dates:v.dates,weekNumber:v.weekNumber},v.weekNumber)})}),e.jsx(b,{displayMonth:s.displayMonth})]})}function wFs(){return!!(typeof window<"u"&&window.document&&window.document.createElement)}var jFs=wFs()?j.useLayoutEffect:j.useEffect,oIe=!1,NFs=0;function odt(){return"react-day-picker-".concat(++NFs)}function kFs(s){var t,n=s??(oIe?odt():null),r=j.useState(n),a=r[0],i=r[1];return jFs(function(){a===null&&i(odt())},[]),j.useEffect(function(){oIe===!1&&(oIe=!0)},[]),(t=s??a)!==null&&t!==void 0?t:void 0}function SFs(s){var t,n,r=sm(),a=r.dir,i=r.classNames,l=r.styles,o=r.components,c=Tee().displayMonths,d=kFs(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,x=s.displayIndex===c.length-1,g=!p&&!x;a==="rtl"&&(t=[p,x],x=t[0],p=t[1]),p&&(h.push(i.caption_start),m=gl(gl({},m),l.caption_start)),x&&(h.push(i.caption_end),m=gl(gl({},m),l.caption_end)),g&&(h.push(i.caption_between),m=gl(gl({},m),l.caption_between));var y=(n=o==null?void 0:o.Caption)!==null&&n!==void 0?n:LOs;return e.jsxs("div",{className:h.join(" "),style:m,children:[e.jsx(y,{id:d,displayMonth:s.displayMonth,displayIndex:s.displayIndex}),e.jsx(_Fs,{id:u,"aria-labelledby":d,displayMonth:s.displayMonth})]},s.displayIndex)}function CFs(s){var t=sm(),n=t.classNames,r=t.styles;return e.jsx("div",{className:n.months,style:r.months,children:s.children})}function AFs(s){var t,n,r=s.initialProps,a=sm(),i=jWe(),l=Tee(),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=gl(gl({},a.styles.root),a.style),m=Object.keys(r).filter(function(x){return x.startsWith("data-")}).reduce(function(x,g){var y;return gl(gl({},x),(y={},y[g]=r[g],y))},{}),p=(n=(t=r.components)===null||t===void 0?void 0:t.Months)!==null&&n!==void 0?n:CFs;return e.jsx("div",gl({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(x,g){return e.jsx(SFs,{displayIndex:g,displayMonth:x},g)})})}))}function EFs(s){var t=s.children,n=JRs(s,["children"]);return e.jsx(yOs,{initialProps:n,children:e.jsx(AOs,{children:e.jsx(cFs,{initialProps:n,children:e.jsx(FOs,{initialProps:n,children:e.jsx($Os,{initialProps:n,children:e.jsx(YOs,{children:e.jsx(oFs,{children:t})})})})})})})}function TFs(s){return e.jsx(EFs,gl({},s,{children:e.jsx(AFs,{initialProps:s})}))}function y1({className:s,classNames:t,showOutsideDays:n=!0,...r}){return e.jsx(TFs,{showOutsideDays:n,className:Tt("p-3",s),classNames:{months:"flex flex-col sm:flex-row space-y-4 sm:space-x-4 sm:space-y-0",month:"space-y-4",caption:"flex justify-center pt-1 relative items-center",caption_label:"text-sm font-medium",nav:"space-x-1 flex items-center",nav_button:Tt(H$({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:Tt(H$({variant:"ghost"}),"h-9 w-9 p-0 font-normal aria-selected:opacity-100"),day_range_end:"day-range-end",day_selected:"bg-primary text-primary-foreground hover:bg-primary hover:text-primary-foreground focus:bg-primary focus:text-primary-foreground",day_today:"bg-accent text-accent-foreground",day_outside:"day-outside text-muted-foreground opacity-50 aria-selected:bg-accent/50 aria-selected:text-muted-foreground aria-selected:opacity-30",day_disabled:"text-muted-foreground opacity-50",day_range_middle:"aria-selected:bg-accent aria-selected:text-accent-foreground",day_hidden:"invisible",...t},components:{IconLeft:({...a})=>e.jsx(Ic,{className:"h-4 w-4"}),IconRight:({...a})=>e.jsx(Ja,{className:"h-4 w-4"})},...r})}y1.displayName="Calendar";var NAe="Popover",[SPt,JXn]=ip(NAe,[M5]),Mee=M5(),[MFs,F6]=SPt(NAe),CPt=s=>{const{__scopePopover:t,children:n,open:r,defaultOpen:a,onOpenChange:i,modal:l=!1}=s,o=Mee(t),c=j.useRef(null),[d,u]=j.useState(!1),[h,m]=Ux({prop:r,defaultProp:a??!1,onChange:i,caller:NAe});return e.jsx(eee,{...o,children:e.jsx(MFs,{scope:t,contentId:Fx(),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})})};CPt.displayName=NAe;var APt="PopoverAnchor",LFs=j.forwardRef((s,t)=>{const{__scopePopover:n,...r}=s,a=F6(APt,n),i=Mee(n),{onCustomAnchorAdd:l,onCustomAnchorRemove:o}=a;return j.useEffect(()=>(l(),()=>o()),[l,o]),e.jsx(yq,{...i,...r,ref:t})});LFs.displayName=APt;var EPt="PopoverTrigger",TPt=j.forwardRef((s,t)=>{const{__scopePopover:n,...r}=s,a=F6(EPt,n),i=Mee(n),l=Po(t,a.triggerRef),o=e.jsx(Ka.button,{type:"button","aria-haspopup":"dialog","aria-expanded":a.open,"aria-controls":a.contentId,"data-state":DPt(a.open),...r,ref:l,onClick:xa(s.onClick,a.onOpenToggle)});return a.hasCustomAnchor?o:e.jsx(yq,{asChild:!0,...i,children:o})});TPt.displayName=EPt;var kWe="PopoverPortal",[PFs,IFs]=SPt(kWe,{forceMount:void 0}),MPt=s=>{const{__scopePopover:t,forceMount:n,children:r,container:a}=s,i=F6(kWe,t);return e.jsx(PFs,{scope:t,forceMount:n,children:e.jsx(dx,{present:n||i.open,children:e.jsx(hq,{asChild:!0,container:a,children:r})})})};MPt.displayName=kWe;var dU="PopoverContent",LPt=j.forwardRef((s,t)=>{const n=IFs(dU,s.__scopePopover),{forceMount:r=n.forceMount,...a}=s,i=F6(dU,s.__scopePopover);return e.jsx(dx,{present:r||i.open,children:i.modal?e.jsx(RFs,{...a,ref:t}):e.jsx(OFs,{...a,ref:t})})});LPt.displayName=dU;var DFs=QT("PopoverContent.RemoveScroll"),RFs=j.forwardRef((s,t)=>{const n=F6(dU,s.__scopePopover),r=j.useRef(null),a=Po(t,r),i=j.useRef(!1);return j.useEffect(()=>{const l=r.current;if(l)return z3e(l)},[]),e.jsx(KJ,{as:DFs,allowPinchZoom:!0,children:e.jsx(PPt,{...s,ref:a,trapFocus:n.open,disableOutsidePointerEvents:!0,onCloseAutoFocus:xa(s.onCloseAutoFocus,l=>{var o;l.preventDefault(),i.current||(o=n.triggerRef.current)==null||o.focus()}),onPointerDownOutside:xa(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:xa(s.onFocusOutside,l=>l.preventDefault(),{checkForDefaultPrevented:!1})})})}),OFs=j.forwardRef((s,t)=>{const n=F6(dU,s.__scopePopover),r=j.useRef(!1),a=j.useRef(!1);return e.jsx(PPt,{...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()}})}),PPt=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=F6(dU,n),p=Mee(n);return O3e(),e.jsx(WJ,{asChild:!0,loop:!0,trapped:r,onMountAutoFocus:a,onUnmountAutoFocus:i,children:e.jsx(j6,{asChild:!0,disableOutsidePointerEvents:l,onInteractOutside:u,onEscapeKeyDown:o,onPointerDownOutside:c,onFocusOutside:d,onDismiss:()=>m.onOpenChange(!1),children:e.jsx(tee,{"data-state":DPt(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)"}})})})}),IPt="PopoverClose",FFs=j.forwardRef((s,t)=>{const{__scopePopover:n,...r}=s,a=F6(IPt,n);return e.jsx(Ka.button,{type:"button",...r,ref:t,onClick:xa(s.onClick,()=>a.onOpenChange(!1))})});FFs.displayName=IPt;var zFs="PopoverArrow",BFs=j.forwardRef((s,t)=>{const{__scopePopover:n,...r}=s,a=Mee(n);return e.jsx(see,{...a,...r,ref:t})});BFs.displayName=zFs;function DPt(s){return s?"open":"closed"}var $Fs=CPt,UFs=TPt,qFs=MPt,RPt=LPt;const Sc=$Fs,Cc=UFs,xc=j.forwardRef(({className:s,align:t="center",sideOffset:n=4,...r},a)=>e.jsx(qFs,{children:e.jsx(RPt,{ref:a,align:t,sideOffset:n,className:Tt("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})}));xc.displayName=RPt.displayName;async function OPt(s){if(s instanceof wSt)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 VFs=GO("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"}}),dX=j.forwardRef(({className:s,variant:t,...n},r)=>e.jsx("div",{ref:r,role:"alert",className:Tt(VFs({variant:t}),s),...n}));dX.displayName="Alert";const HFs=j.forwardRef(({className:s,...t},n)=>e.jsx("h5",{ref:n,className:Tt("mb-1 font-medium leading-none tracking-tight",s),...t}));HFs.displayName="AlertTitle";const uX=j.forwardRef(({className:s,...t},n)=>e.jsx("div",{ref:n,className:Tt("text-sm [&_p]:leading-relaxed",s),...t}));uX.displayName="AlertDescription";function GFs({open:s,onOpenChange:t,imageUrl:n,imageId:r,defaultCaption:a="",swagItemId:i,reelId:l}){const o=ts(),{user:c}=_s(),d=(c==null?void 0:c.id)??null,[u,h]=j.useState(a),[m,p]=j.useState([]),[x,g]=j.useState(null),[y,b]=j.useState("now"),[v,N]=j.useState(qat(Zat(new Date),1)),[C,A]=j.useState("12"),[T,P]=j.useState("00"),[M,I]=j.useState("PM");j.useEffect(()=>{if(s){h(a),b("now"),p([]);const ge=qat(Zat(new Date),1);N(ge);const fe=ge.getHours();A(String(fe>12?fe-12:fe===0?12:fe)),P("00"),I(fe>=12?"PM":"AM")}},[s,a]);const D=()=>{if(!v)return null;let ge=parseInt(C);const fe=parseInt(T);return M==="PM"&&ge!==12&&(ge+=12),M==="AM"&&ge===12&&(ge=0),fCt(pCt(v,ge),fe)},{data:B,isLoading:q}=ht({queryKey:["social-accounts-for-post",d],queryFn:async()=>{const{data:{user:ge}}=await U.auth.getUser();if(!ge)return[];const{data:fe,error:je}=await U.from("social_accounts").select("*").eq("user_id",ge.id).eq("is_active",!0).order("platform",{ascending:!0});if(je)throw je;return console.log("Fetched social accounts for posting:",fe),fe},enabled:s,staleTime:0}),W=yt({mutationFn:async({accountId:ge,platform:fe})=>{g(ge);const{data:je,error:Ee}=await U.functions.invoke("social-post",{body:{platform:fe,accountId:ge,imageUrl:n,caption:u}});if(Ee)throw new Error(await OPt(Ee));if(je!=null&&je.error)throw new Error(je.error);return je},onSuccess:ge=>{const fe=ge.platform==="facebook"?"Facebook":ge.platform==="instagram"?"Instagram":ge.platform==="linkedin"?"LinkedIn":"Google Business";ae.success(`Posted to ${fe}!`)},onError:ge=>{ae.error(`Failed to post: ${ge.message}`)},onSettled:()=>{g(null)}}),V=yt({mutationFn:async({accountId:ge,platform:fe,scheduledFor:je})=>{const{data:{user:Ee}}=await U.auth.getUser();if(!Ee)throw new Error("Not authenticated");const{error:Me}=await U.from("scheduled_posts").insert({user_id:Ee.id,social_account_id:ge,platform:fe,image_url:n,caption:u,swag_item_id:i||null,reel_id:l||null,scheduled_for:je.toISOString(),status:"scheduled"});if(Me)throw Me;return{platform:fe}},onSuccess:ge=>{const fe=ge.platform==="facebook"?"Facebook":ge.platform==="instagram"?"Instagram":"LinkedIn";ae.success(`Post scheduled for ${fe}!`)},onError:ge=>{ae.error(`Failed to schedule: ${ge.message}`)}}),K=async()=>{if(m.length===0){ae.error("Please select at least one account");return}if(y==="schedule"){const ge=D();if(!ge||ge<=new Date){ae.error("Please select a future date and time");return}for(const fe of m){const je=B==null?void 0:B.find(Ee=>Ee.id===fe);je&&await V.mutateAsync({accountId:fe,platform:je.platform,scheduledFor:ge})}o.invalidateQueries({queryKey:["scheduled-posts",d]}),ae.success(`${m.length} post(s) scheduled for ${Hs(ge,"PPp")}`)}else for(const ge of m){const fe=B==null?void 0:B.find(je=>je.id===ge);fe&&await W.mutateAsync({accountId:ge,platform:fe.platform})}o.invalidateQueries({queryKey:["scheduled-posts",d]}),h(""),p([]),t(!1)},Q=ge=>{p(fe=>fe.includes(ge)?fe.filter(je=>je!==ge):[...fe,ge])},J=(B==null?void 0:B.filter(ge=>ge.platform==="facebook"))||[],ce=(B==null?void 0:B.filter(ge=>ge.platform==="instagram"))||[],ue=(B==null?void 0:B.filter(ge=>ge.platform==="linkedin"))||[],ne=(B==null?void 0:B.filter(ge=>ge.platform==="google_business"))||[],ee=((B==null?void 0:B.length)||0)>0,le=W.isPending||V.isPending,he=Array.from({length:12},(ge,fe)=>String(fe+1)),ve=["00","15","30","45"];return e.jsx(Os,{open:s,onOpenChange:t,children:e.jsxs(Rs,{className:"sm:max-w-lg max-h-[90vh] overflow-y-auto",children:[e.jsxs(Us,{children:[e.jsx(zs,{children:"Create Social Post"}),e.jsx(Sr,{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(se,{htmlFor:"caption",children:"Caption"}),e.jsx(Is,{id:"caption",placeholder:"Write a caption for your post...",value:u,onChange:ge=>h(ge.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(se,{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:()=>b("now"),className:Tt("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:()=>b("schedule"),className:Tt("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(Hr,{className:"h-4 w-4"}),"Schedule for"]}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-3",children:[e.jsxs(Sc,{children:[e.jsx(Cc,{asChild:!0,children:e.jsxs($,{variant:"outline",className:Tt("justify-start text-left font-normal flex-1",!v&&"text-muted-foreground"),children:[e.jsx(ia,{className:"mr-2 h-4 w-4"}),v?Hs(v,"PPP"):e.jsx("span",{children:"Pick a date"})]})}),e.jsx(xc,{className:"w-auto p-0",align:"start",children:e.jsx(y1,{mode:"single",selected:v,onSelect:N,disabled:ge=>gee.jsx(Ye,{value:ge,children:ge},ge))})]}),e.jsx("span",{className:"text-muted-foreground",children:":"}),e.jsxs(vs,{value:T,onValueChange:P,children:[e.jsx(gs,{className:"w-[70px]",children:e.jsx(bs,{})}),e.jsx(ys,{children:ve.map(ge=>e.jsx(Ye,{value:ge,children:ge},ge))})]}),e.jsxs(vs,{value:M,onValueChange:ge=>I(ge),children:[e.jsx(gs,{className:"w-[70px]",children:e.jsx(bs,{})}),e.jsxs(ys,{children:[e.jsx(Ye,{value:"AM",children:"AM"}),e.jsx(Ye,{value:"PM",children:"PM"})]})]})]})]}),v&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Post will be published on ",Hs(D()||new Date,"PPP 'at' p")]})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx(se,{children:"Post to"}),q&&e.jsx("div",{className:"flex items-center justify-center py-4",children:e.jsx(Ht,{className:"h-6 w-6 animate-spin"})}),!q&&!ee&&e.jsxs(dX,{children:[e.jsx(xo,{className:"h-4 w-4"}),e.jsxs(uX,{className:"flex flex-col gap-2",children:[e.jsx("span",{children:"No social accounts connected yet."}),e.jsxs(Wn,{to:"/social-connections",className:"inline-flex items-center gap-1.5 text-primary hover:underline font-medium",children:[e.jsx(pc,{className:"h-3.5 w-3.5"}),"Connect your Facebook, Instagram & LinkedIn"]})]})]}),J.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(jf,{className:"h-4 w-4 text-blue-600"})," Facebook"]}),J.map(ge=>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(ui,{checked:m.includes(ge.id),onCheckedChange:()=>Q(ge.id),disabled:x===ge.id}),e.jsxs(Ea,{className:"h-8 w-8",children:[e.jsx(ki,{src:ge.profile_picture_url||""}),e.jsx(Ta,{children:e.jsx(jf,{className:"h-4 w-4"})})]}),e.jsx("span",{className:"flex-1 text-sm font-medium",children:ge.page_name||ge.platform_username}),x===ge.id&&e.jsx(Ht,{className:"h-4 w-4 animate-spin"})]},ge.id))]}),ce.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("p",{className:"text-sm font-medium text-muted-foreground flex items-center gap-2",children:[e.jsx(Qh,{className:"h-4 w-4 text-pink-600"})," Instagram"]}),ce.map(ge=>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(ui,{checked:m.includes(ge.id),onCheckedChange:()=>Q(ge.id),disabled:x===ge.id}),e.jsxs(Ea,{className:"h-8 w-8",children:[e.jsx(ki,{src:ge.profile_picture_url||""}),e.jsx(Ta,{children:e.jsx(Qh,{className:"h-4 w-4"})})]}),e.jsxs("span",{className:"flex-1 text-sm font-medium",children:["@",ge.platform_username]}),x===ge.id&&e.jsx(Ht,{className:"h-4 w-4 animate-spin"})]},ge.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(kg,{className:"h-4 w-4 text-blue-700"})," LinkedIn"]}),ue.map(ge=>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(ui,{checked:m.includes(ge.id),onCheckedChange:()=>Q(ge.id),disabled:x===ge.id}),e.jsxs(Ea,{className:"h-8 w-8",children:[e.jsx(ki,{src:ge.profile_picture_url||""}),e.jsx(Ta,{children:e.jsx(kg,{className:"h-4 w-4"})})]}),e.jsx("span",{className:"flex-1 text-sm font-medium",children:ge.platform_username}),x===ge.id&&e.jsx(Ht,{className:"h-4 w-4 animate-spin"})]},ge.id))]}),ne.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("p",{className:"text-sm font-medium text-muted-foreground flex items-center gap-2",children:[e.jsx(ai,{className:"h-4 w-4 text-red-600"})," Google Business"]}),ne.map(ge=>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(ui,{checked:m.includes(ge.id),onCheckedChange:()=>Q(ge.id),disabled:x===ge.id}),e.jsxs(Ea,{className:"h-8 w-8",children:[e.jsx(ki,{src:ge.profile_picture_url||""}),e.jsx(Ta,{children:e.jsx(ai,{className:"h-4 w-4"})})]}),e.jsx("span",{className:"flex-1 text-sm font-medium",children:ge.page_name||ge.platform_username}),x===ge.id&&e.jsx(Ht,{className:"h-4 w-4 animate-spin"})]},ge.id))]})]})]}),e.jsxs(kr,{children:[e.jsx($,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsxs($,{onClick:K,disabled:m.length===0||le,className:"gap-2",children:[le?e.jsx(Ht,{className:"h-4 w-4 animate-spin"}):y==="schedule"?e.jsx(ia,{className:"h-4 w-4"}):e.jsx(Br,{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 WFs(){const{user:s}=_s(),t=(s==null?void 0:s.id)??null,n=ts(),[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,x]=j.useState("12"),[g,y]=j.useState("00"),[b,v]=j.useState("PM"),{data:N=[],isLoading:C}=ht({queryKey:["scheduled-posts",t],enabled:!!t,queryFn:async()=>{const{data:ne,error:ee}=await U.from("scheduled_posts").select(` *, social_accounts ( page_name, platform_username, profile_picture_url ) `).eq("user_id",t).order("scheduled_for",{ascending:!1});if(ee)throw ee;return ne}}),A=N.filter(ne=>{if(i!=="all"&&ne.status!==i)return!1;if(r&&ne.scheduled_for){const ee=new Date(ne.scheduled_for);if(!hu(ee,r))return!1}return!0}),T=N.filter(ne=>ne.scheduled_for).map(ne=>ep(new Date(ne.scheduled_for))),P=yt({mutationFn:async ne=>{const{error:ee}=await U.from("scheduled_posts").update({caption:ne.caption,scheduled_for:ne.scheduled_for}).eq("id",ne.id);if(ee)throw ee},onSuccess:()=>{ae.success("Post updated!"),n.invalidateQueries({queryKey:["scheduled-posts",t]}),c(null)},onError:ne=>{ae.error(`Failed to update: ${ne.message}`)}}),M=yt({mutationFn:async ne=>{const{error:ee}=await U.from("scheduled_posts").update({status:"cancelled"}).eq("id",ne);if(ee)throw ee},onSuccess:()=>{ae.success("Post cancelled"),n.invalidateQueries({queryKey:["scheduled-posts",t]})},onError:ne=>{ae.error(`Failed to cancel: ${ne.message}`)}}),I=yt({mutationFn:async ne=>{const{error:ee}=await U.from("scheduled_posts").delete().eq("id",ne);if(ee)throw ee},onSuccess:()=>{ae.success("Post deleted"),n.invalidateQueries({queryKey:["scheduled-posts",t]})},onError:ne=>{ae.error(`Failed to delete: ${ne.message}`)}}),D=yt({mutationFn:async ne=>{const{data:ee,error:le}=await U.functions.invoke("social-post",{body:{platform:ne.platform,accountId:ne.social_account_id,imageUrl:ne.image_url,caption:ne.caption}});if(le)throw new Error(await OPt(le));if(ee!=null&&ee.error)throw new Error(ee.error);return await U.from("scheduled_posts").update({status:"posted",posted_at:new Date().toISOString(),post_id:ee.postId}).eq("id",ne.id),ee},onSuccess:ne=>{const ee=ne.platform==="facebook"?"Facebook":ne.platform==="instagram"?"Instagram":"LinkedIn";ae.success(`Posted to ${ee}!`),n.invalidateQueries({queryKey:["scheduled-posts",t]})},onError:ne=>{ae.error(`Failed to post: ${ne.message}`)}}),B=ne=>{if(c(ne),u(ne.caption||""),ne.scheduled_for){const ee=new Date(ne.scheduled_for);m(ee);const le=ee.getHours();x(String(le>12?le-12:le===0?12:le)),y(String(ee.getMinutes()).padStart(2,"0")),v(le>=12?"PM":"AM")}},q=()=>{if(!o||!h)return;let ne=parseInt(p);const ee=parseInt(g);b==="PM"&&ne!==12&&(ne+=12),b==="AM"&&ne===12&&(ne=0);const le=fCt(pCt(h,ne),ee);P.mutate({id:o.id,caption:d,scheduled_for:le.toISOString()})},W=ne=>{switch(ne){case"facebook":return e.jsx(jf,{className:"h-4 w-4 text-blue-600"});case"instagram":return e.jsx(Qh,{className:"h-4 w-4 text-pink-600"});case"linkedin":return e.jsx(kg,{className:"h-4 w-4 text-blue-700"});default:return null}},V=ne=>{switch(ne){case"scheduled":return e.jsxs($e,{variant:"secondary",className:"gap-1",children:[e.jsx(Hr,{className:"h-3 w-3"}),"Scheduled"]});case"posted":return e.jsxs($e,{variant:"default",className:"gap-1 bg-green-600",children:[e.jsx(Ro,{className:"h-3 w-3"}),"Posted"]});case"failed":return e.jsxs($e,{variant:"destructive",className:"gap-1",children:[e.jsx($d,{className:"h-3 w-3"}),"Failed"]});case"cancelled":return e.jsxs($e,{variant:"outline",className:"gap-1 text-muted-foreground",children:[e.jsx(xo,{className:"h-3 w-3"}),"Cancelled"]});default:return e.jsx($e,{variant:"outline",children:ne})}},K=Array.from({length:12},(ne,ee)=>String(ee+1)),Q=["00","15","30","45"],J=N.filter(ne=>ne.status==="scheduled").length,ce=N.filter(ne=>ne.status==="posted").length,ue=N.filter(ne=>ne.status==="scheduled"&&ne.scheduled_for&&Zys(new Date(ne.scheduled_for))).length;return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[e.jsxs(_e,{className:"p-4",children:[e.jsx("div",{className:"text-2xl font-bold",children:J}),e.jsx("div",{className:"text-sm text-muted-foreground",children:"Scheduled"})]}),e.jsxs(_e,{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(_e,{className:"p-4",children:[e.jsx("div",{className:"text-2xl font-bold",children:ce}),e.jsx("div",{className:"text-sm text-muted-foreground",children:"Posted"})]}),e.jsxs(_e,{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(_e,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-4",children:[e.jsx(Nl,{className:"h-5 w-5"}),e.jsx("h3",{className:"font-semibold",children:"Calendar"})]}),e.jsx(y1,{mode:"single",selected:r,onSelect:a,className:Tt("pointer-events-auto"),modifiers:{hasPost:T},modifiersStyles:{hasPost:{fontWeight:"bold",backgroundColor:"hsl(var(--primary) / 0.1)",borderRadius:"50%"}}}),r&&e.jsx($,{variant:"ghost",size:"sm",onClick:()=>a(void 0),className:"w-full mt-2",children:"Clear date filter"})]}),e.jsxs("div",{className:"flex-1 space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx($j,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("div",{className:"flex flex-wrap gap-1",children:["all","scheduled","posted","failed","cancelled"].map(ne=>e.jsx($,{variant:i===ne?"default":"outline",size:"sm",onClick:()=>l(ne),className:"capitalize",children:ne},ne))})]}),C&&e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx(Ht,{className:"h-8 w-8 animate-spin text-muted-foreground"})}),!C&&A.length===0&&e.jsxs(_e,{className:"p-8 text-center",children:[e.jsx(ia,{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 ${Hs(r,"PPP")}`:"Schedule a post from Social Swag to get started!"})]}),e.jsx("div",{className:"space-y-4",children:A.map(ne=>{var ee,le;return e.jsx(_e,{className:"overflow-hidden",children:e.jsxs("div",{className:"flex flex-col sm:flex-row",children:[e.jsx("div",{className:"sm:w-32 h-32 sm:h-auto bg-muted flex-shrink-0",children:e.jsx("img",{src:ne.image_url,alt:"Post preview",className:"w-full h-full object-cover"})}),e.jsxs(Oe,{className:"flex-1 p-4",children:[e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-2 mb-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[W(ne.platform),e.jsx("span",{className:"font-medium",children:((ee=ne.social_accounts)==null?void 0:ee.page_name)||((le=ne.social_accounts)==null?void 0:le.platform_username)||"Unknown"}),V(ne.status)]}),e.jsxs("div",{className:"flex items-center gap-1",children:[ne.status==="scheduled"&&e.jsxs(JN,{children:[e.jsxs(Mx,{children:[e.jsx(Lx,{asChild:!0,children:e.jsx($,{variant:"ghost",size:"icon",onClick:()=>B(ne),children:e.jsx(Ya,{className:"h-4 w-4"})})}),e.jsx(tx,{children:"Edit post"})]}),e.jsxs(Mx,{children:[e.jsx(Lx,{asChild:!0,children:e.jsx($,{variant:"ghost",size:"icon",onClick:()=>D.mutate(ne),disabled:D.isPending,children:D.isPending?e.jsx(Ht,{className:"h-4 w-4 animate-spin"}):e.jsx(Br,{className:"h-4 w-4"})})}),e.jsx(tx,{children:"Post now"})]}),e.jsxs(Ll,{children:[e.jsx(_f,{asChild:!0,children:e.jsx($,{variant:"ghost",size:"icon",className:"text-destructive",children:e.jsx(Pn,{className:"h-4 w-4"})})}),e.jsxs(yl,{children:[e.jsxs(vl,{children:[e.jsx(_l,{children:"Cancel this scheduled post?"}),e.jsx(wl,{children:"This will cancel the post. You can delete it entirely or keep it in your history."})]}),e.jsxs(bl,{children:[e.jsx(jl,{children:"Keep"}),e.jsx(fl,{onClick:()=>M.mutate(ne.id),className:"bg-amber-600 hover:bg-amber-700",children:"Cancel Post"}),e.jsx(fl,{onClick:()=>I.mutate(ne.id),className:"bg-destructive hover:bg-destructive/90",children:"Delete"})]})]})]})]}),(ne.status==="posted"||ne.status==="cancelled"||ne.status==="failed")&&e.jsxs(Ll,{children:[e.jsx(_f,{asChild:!0,children:e.jsx($,{variant:"ghost",size:"icon",className:"text-destructive",children:e.jsx(Pn,{className:"h-4 w-4"})})}),e.jsxs(yl,{children:[e.jsxs(vl,{children:[e.jsx(_l,{children:"Delete this post?"}),e.jsx(wl,{children:"This will permanently remove this post from your history."})]}),e.jsxs(bl,{children:[e.jsx(jl,{children:"Cancel"}),e.jsx(fl,{onClick:()=>I.mutate(ne.id),className:"bg-destructive hover:bg-destructive/90",children:"Delete"})]})]})]})]})]}),ne.caption&&e.jsx("p",{className:"text-sm text-muted-foreground line-clamp-2 mb-2",children:ne.caption}),e.jsxs("div",{className:"text-xs text-muted-foreground flex items-center gap-1",children:[e.jsx(Hr,{className:"h-3 w-3"}),ne.status==="posted"&&ne.posted_at?`Posted ${Hs(new Date(ne.posted_at),"PPp")}`:ne.scheduled_for?`Scheduled for ${Hs(new Date(ne.scheduled_for),"PPp")}`:"Not scheduled"]}),ne.status==="failed"&&ne.error_message&&e.jsxs("p",{className:"text-xs text-destructive mt-2",children:["Error: ",ne.error_message]})]})]})},ne.id)})})]})]}),e.jsx(Os,{open:!!o,onOpenChange:ne=>!ne&&c(null),children:e.jsxs(Rs,{className:"max-w-lg",children:[e.jsxs(Us,{children:[e.jsx(zs,{children:"Edit Scheduled Post"}),e.jsx(Sr,{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(se,{children:"Caption"}),e.jsx(Is,{value:d,onChange:ne=>u(ne.target.value),rows:3})]}),e.jsxs("div",{className:"space-y-3 p-4 border rounded-lg",children:[e.jsx(se,{children:"Schedule for"}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-3",children:[e.jsxs(Sc,{children:[e.jsx(Cc,{asChild:!0,children:e.jsxs($,{variant:"outline",className:Tt("justify-start text-left font-normal flex-1",!h&&"text-muted-foreground"),children:[e.jsx(ia,{className:"mr-2 h-4 w-4"}),h?Hs(h,"PPP"):"Pick a date"]})}),e.jsx(xc,{className:"w-auto p-0",align:"start",children:e.jsx(y1,{mode:"single",selected:h,onSelect:m,disabled:ne=>nee.jsx(Ye,{value:ne,children:ne},ne))})]}),e.jsx("span",{className:"text-muted-foreground",children:":"}),e.jsxs(vs,{value:g,onValueChange:y,children:[e.jsx(gs,{className:"w-[70px]",children:e.jsx(bs,{})}),e.jsx(ys,{children:Q.map(ne=>e.jsx(Ye,{value:ne,children:ne},ne))})]}),e.jsxs(vs,{value:b,onValueChange:ne=>v(ne),children:[e.jsx(gs,{className:"w-[70px]",children:e.jsx(bs,{})}),e.jsxs(ys,{children:[e.jsx(Ye,{value:"AM",children:"AM"}),e.jsx(Ye,{value:"PM",children:"PM"})]})]})]})]})]})]}),e.jsxs(kr,{children:[e.jsx($,{variant:"outline",onClick:()=>c(null),children:"Cancel"}),e.jsxs($,{onClick:q,disabled:P.isPending,children:[P.isPending?e.jsx(Ht,{className:"h-4 w-4 animate-spin mr-2"}):null,"Save Changes"]})]})]})})]})}function tre(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 FPt={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 tre=="function"&&tre;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(x){var g=r[d][1][x];return l(g||x)},p,p.exports,n,r,a,i)}return a[d].exports}for(var o=typeof tre=="function"&&tre,c=0;c>2,p=(3&d)<<4|u>>4,x=1>6:64,g=2>4,u=(15&m)<<4|(p=o.indexOf(c.charAt(g++)))>>2,h=(3&p)<<6|(x=o.indexOf(c.charAt(g++))),v[y++]=d,p!==64&&(v[y++]=u),x!==64&&(v[y++]=h);return v}},{"./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,x){this.compressedSize=u,this.uncompressedSize=h,this.crc32=m,this.compression=p,this.compressedContent=x}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,x=m+h;d^=-1;for(var g=m;g>>8^p[255&(d^u[g])];return-1^d}(0|c,o,o.length,0):function(d,u,h,m){var p=l,x=m+h;d^=-1;for(var g=m;g>>8^p[255&(d^u.charCodeAt(g))];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,x){var g,y="";for(g=0;g>>=8;return y}function l(p,x,g,y,b,v){var N,C,A=p.file,T=p.compression,P=v!==d.utf8encode,M=o.transformTo("string",v(A.name)),I=o.transformTo("string",d.utf8encode(A.name)),D=A.comment,B=o.transformTo("string",v(D)),q=o.transformTo("string",d.utf8encode(D)),W=I.length!==A.name.length,V=q.length!==D.length,K="",Q="",J="",ce=A.dir,ue=A.date,ne={crc32:0,compressedSize:0,uncompressedSize:0};x&&!g||(ne.crc32=p.crc32,ne.compressedSize=p.compressedSize,ne.uncompressedSize=p.uncompressedSize);var ee=0;x&&(ee|=8),P||!W&&!V||(ee|=2048);var le=0,he=0;ce&&(le|=16),b==="UNIX"?(he=798,le|=function(ge,fe){var je=ge;return ge||(je=fe?16893:33204),(65535&je)<<16}(A.unixPermissions,ce)):(he=20,le|=function(ge){return 63&(ge||0)}(A.dosPermissions)),N=ue.getUTCHours(),N<<=6,N|=ue.getUTCMinutes(),N<<=5,N|=ue.getUTCSeconds()/2,C=ue.getUTCFullYear()-1980,C<<=4,C|=ue.getUTCMonth()+1,C<<=5,C|=ue.getUTCDate(),W&&(Q=i(1,1)+i(u(M),4)+I,K+="up"+i(Q.length,2)+Q),V&&(J=i(1,1)+i(u(B),4)+q,K+="uc"+i(J.length,2)+J);var ve="";return ve+=` \0`,ve+=i(ee,2),ve+=T.magic,ve+=i(N,2),ve+=i(C,2),ve+=i(ne.crc32,4),ve+=i(ne.compressedSize,4),ve+=i(ne.uncompressedSize,4),ve+=i(M.length,2),ve+=i(K.length,2),{fileRecord:h.LOCAL_FILE_HEADER+ve+M+K,dirRecord:h.CENTRAL_FILE_HEADER+i(he,2)+ve+i(B.length,2)+"\0\0\0\0"+i(le,4)+i(y,4)+M+K+B}}var o=n("../utils"),c=n("../stream/GenericWorker"),d=n("../utf8"),u=n("../crc32"),h=n("../signature");function m(p,x,g,y){c.call(this,"ZipFileWorker"),this.bytesWritten=0,this.zipComment=x,this.zipPlatform=g,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 x=p.meta.percent||0,g=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:g?(x+100*(g-y-1))/g:100}}))},m.prototype.openedSource=function(p){this.currentSourceOffset=this.bytesWritten,this.currentFile=p.file.name;var x=this.streamFiles&&!p.file.dir;if(x){var g=l(p,x,!1,this.currentSourceOffset,this.zipPlatform,this.encodeFileName);this.push({data:g.fileRecord,meta:{percent:0}})}else this.accumulate=!0},m.prototype.closedSource=function(p){this.accumulate=!1;var x=this.streamFiles&&!p.file.dir,g=l(p,x,!0,this.currentSourceOffset,this.zipPlatform,this.encodeFileName);if(this.dirRecords.push(g.dirRecord),x)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:g.fileRecord,meta:{percent:0}});this.contentBuffer.length;)this.push(this.contentBuffer.shift());this.currentFile=null},m.prototype.flush=function(){for(var p=this.bytesWritten,x=0;x=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(x,g){return new u.Promise(function(y,b){var v=[],N=x._internalType,C=x._outputType,A=x._mimeType;x.on("data",function(T,P){v.push(T),g&&g(P)}).on("error",function(T){v=[],b(T)}).on("end",function(){try{var T=function(P,M,I){switch(P){case"blob":return i.newBlob(i.transformTo("arraybuffer",M),I);case"base64":return c.encode(M);default:return i.transformTo(P,M)}}(C,function(P,M){var I,D=0,B=null,q=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(x){var g,y,b,v,N,C=x.length,A=0;for(v=0;v>>6:(y<65536?g[N++]=224|y>>>12:(g[N++]=240|y>>>18,g[N++]=128|y>>>12&63),g[N++]=128|y>>>6&63),g[N++]=128|63&y);return g}(p)},a.utf8decode=function(p){return l.nodebuffer?i.transformTo("nodebuffer",p).toString("utf-8"):function(x){var g,y,b,v,N=x.length,C=new Array(2*N);for(g=y=0;g>10&1023,C[y++]=56320|1023&b)}return C.length!==y&&(C.subarray?C=C.subarray(0,y):C.length=y),i.applyFromCharCode(C)}(p=i.transformTo(l.uint8array?"uint8array":"array",p))},i.inherits(h,c),h.prototype.processChunk=function(p){var x=i.transformTo(l.uint8array?"uint8array":"array",p.data);if(this.leftOver&&this.leftOver.length){if(l.uint8array){var g=x;(x=new Uint8Array(g.length+this.leftOver.length)).set(this.leftOver,0),x.set(g,this.leftOver.length)}else x=this.leftOver.concat(x);this.leftOver=null}var y=function(v,N){var C;for((N=N||v.length)>v.length&&(N=v.length),C=N-1;0<=C&&(192&v[C])==128;)C--;return C<0||C===0?N:C+d[v[C]]>N?C:N}(x),b=x;y!==x.length&&(l.uint8array?(b=x.subarray(0,y),this.leftOver=x.subarray(y,x.length)):(b=x.slice(0,y),this.leftOver=x.slice(y,x.length))),this.push({data:a.utf8decode(b),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(g){return g}function u(g,y){for(var b=0;b>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 x,g,y,b=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,x=m.length;p>10&1023,v[x++]=56320|1023&g)}return u(v,x)},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,x=-2,g=-1,y=4,b=2,v=8,N=9,C=286,A=30,T=19,P=2*C+1,M=15,I=3,D=258,B=D+I+1,q=42,W=113,V=1,K=2,Q=3,J=4;function ce(Se,Re){return Se.msg=u[Re],Re}function ue(Se){return(Se<<1)-(4Se.avail_out&&(Ae=Se.avail_out),Ae!==0&&(l.arraySet(Se.output,Re.pending_buf,Re.pending_out,Ae,Se.next_out),Se.next_out+=Ae,Re.pending_out+=Ae,Se.total_out+=Ae,Se.avail_out-=Ae,Re.pending-=Ae,Re.pending===0&&(Re.pending_out=0))}function le(Se,Re){o._tr_flush_block(Se,0<=Se.block_start?Se.block_start:-1,Se.strstart-Se.block_start,Re),Se.block_start=Se.strstart,ee(Se.strm)}function he(Se,Re){Se.pending_buf[Se.pending++]=Re}function ve(Se,Re){Se.pending_buf[Se.pending++]=Re>>>8&255,Se.pending_buf[Se.pending++]=255&Re}function ge(Se,Re){var Ae,Be,qe=Se.max_chain_length,Ke=Se.strstart,Ze=Se.prev_length,Ue=Se.nice_match,et=Se.strstart>Se.w_size-B?Se.strstart-(Se.w_size-B):0,Qe=Se.window,Ge=Se.w_mask,nt=Se.prev,ft=Se.strstart+D,lt=Qe[Ke+Ze-1],Mt=Qe[Ke+Ze];Se.prev_length>=Se.good_match&&(qe>>=2),Ue>Se.lookahead&&(Ue=Se.lookahead);do if(Qe[(Ae=Re)+Ze]===Mt&&Qe[Ae+Ze-1]===lt&&Qe[Ae]===Qe[Ke]&&Qe[++Ae]===Qe[Ke+1]){Ke+=2,Ae++;do;while(Qe[++Ke]===Qe[++Ae]&&Qe[++Ke]===Qe[++Ae]&&Qe[++Ke]===Qe[++Ae]&&Qe[++Ke]===Qe[++Ae]&&Qe[++Ke]===Qe[++Ae]&&Qe[++Ke]===Qe[++Ae]&&Qe[++Ke]===Qe[++Ae]&&Qe[++Ke]===Qe[++Ae]&&Keet&&--qe!=0);return Ze<=Se.lookahead?Ze:Se.lookahead}function fe(Se){var Re,Ae,Be,qe,Ke,Ze,Ue,et,Qe,Ge,nt=Se.w_size;do{if(qe=Se.window_size-Se.lookahead-Se.strstart,Se.strstart>=nt+(nt-B)){for(l.arraySet(Se.window,Se.window,nt,nt,0),Se.match_start-=nt,Se.strstart-=nt,Se.block_start-=nt,Re=Ae=Se.hash_size;Be=Se.head[--Re],Se.head[Re]=nt<=Be?Be-nt:0,--Ae;);for(Re=Ae=nt;Be=Se.prev[--Re],Se.prev[Re]=nt<=Be?Be-nt:0,--Ae;);qe+=nt}if(Se.strm.avail_in===0)break;if(Ze=Se.strm,Ue=Se.window,et=Se.strstart+Se.lookahead,Qe=qe,Ge=void 0,Ge=Ze.avail_in,Qe=I)for(Ke=Se.strstart-Se.insert,Se.ins_h=Se.window[Ke],Se.ins_h=(Se.ins_h<=I&&(Se.ins_h=(Se.ins_h<=I)if(Be=o._tr_tally(Se,Se.strstart-Se.match_start,Se.match_length-I),Se.lookahead-=Se.match_length,Se.match_length<=Se.max_lazy_match&&Se.lookahead>=I){for(Se.match_length--;Se.strstart++,Se.ins_h=(Se.ins_h<=I&&(Se.ins_h=(Se.ins_h<=I&&Se.match_length<=Se.prev_length){for(qe=Se.strstart+Se.lookahead-I,Be=o._tr_tally(Se,Se.strstart-1-Se.prev_match,Se.prev_length-I),Se.lookahead-=Se.prev_length-1,Se.prev_length-=2;++Se.strstart<=qe&&(Se.ins_h=(Se.ins_h<Se.pending_buf_size-5&&(Ae=Se.pending_buf_size-5);;){if(Se.lookahead<=1){if(fe(Se),Se.lookahead===0&&Re===h)return V;if(Se.lookahead===0)break}Se.strstart+=Se.lookahead,Se.lookahead=0;var Be=Se.block_start+Ae;if((Se.strstart===0||Se.strstart>=Be)&&(Se.lookahead=Se.strstart-Be,Se.strstart=Be,le(Se,!1),Se.strm.avail_out===0)||Se.strstart-Se.block_start>=Se.w_size-B&&(le(Se,!1),Se.strm.avail_out===0))return V}return Se.insert=0,Re===m?(le(Se,!0),Se.strm.avail_out===0?Q:J):(Se.strstart>Se.block_start&&(le(Se,!1),Se.strm.avail_out),V)}),new Me(4,4,8,4,je),new Me(4,5,16,8,je),new Me(4,6,32,32,je),new Me(4,4,16,16,Ee),new Me(8,16,32,32,Ee),new Me(8,16,128,128,Ee),new Me(8,32,128,256,Ee),new Me(32,128,258,1024,Ee),new Me(32,258,258,4096,Ee)],a.deflateInit=function(Se,Re){return Xe(Se,Re,v,15,8,0)},a.deflateInit2=Xe,a.deflateReset=ke,a.deflateResetKeep=ze,a.deflateSetHeader=function(Se,Re){return Se&&Se.state?Se.state.wrap!==2?x:(Se.state.gzhead=Re,p):x},a.deflate=function(Se,Re){var Ae,Be,qe,Ke;if(!Se||!Se.state||5>8&255),he(Be,Be.gzhead.time>>16&255),he(Be,Be.gzhead.time>>24&255),he(Be,Be.level===9?2:2<=Be.strategy||Be.level<2?4:0),he(Be,255&Be.gzhead.os),Be.gzhead.extra&&Be.gzhead.extra.length&&(he(Be,255&Be.gzhead.extra.length),he(Be,Be.gzhead.extra.length>>8&255)),Be.gzhead.hcrc&&(Se.adler=d(Se.adler,Be.pending_buf,Be.pending,0)),Be.gzindex=0,Be.status=69):(he(Be,0),he(Be,0),he(Be,0),he(Be,0),he(Be,0),he(Be,Be.level===9?2:2<=Be.strategy||Be.level<2?4:0),he(Be,3),Be.status=W);else{var Ze=v+(Be.w_bits-8<<4)<<8;Ze|=(2<=Be.strategy||Be.level<2?0:Be.level<6?1:Be.level===6?2:3)<<6,Be.strstart!==0&&(Ze|=32),Ze+=31-Ze%31,Be.status=W,ve(Be,Ze),Be.strstart!==0&&(ve(Be,Se.adler>>>16),ve(Be,65535&Se.adler)),Se.adler=1}if(Be.status===69)if(Be.gzhead.extra){for(qe=Be.pending;Be.gzindex<(65535&Be.gzhead.extra.length)&&(Be.pending!==Be.pending_buf_size||(Be.gzhead.hcrc&&Be.pending>qe&&(Se.adler=d(Se.adler,Be.pending_buf,Be.pending-qe,qe)),ee(Se),qe=Be.pending,Be.pending!==Be.pending_buf_size));)he(Be,255&Be.gzhead.extra[Be.gzindex]),Be.gzindex++;Be.gzhead.hcrc&&Be.pending>qe&&(Se.adler=d(Se.adler,Be.pending_buf,Be.pending-qe,qe)),Be.gzindex===Be.gzhead.extra.length&&(Be.gzindex=0,Be.status=73)}else Be.status=73;if(Be.status===73)if(Be.gzhead.name){qe=Be.pending;do{if(Be.pending===Be.pending_buf_size&&(Be.gzhead.hcrc&&Be.pending>qe&&(Se.adler=d(Se.adler,Be.pending_buf,Be.pending-qe,qe)),ee(Se),qe=Be.pending,Be.pending===Be.pending_buf_size)){Ke=1;break}Ke=Be.gzindexqe&&(Se.adler=d(Se.adler,Be.pending_buf,Be.pending-qe,qe)),Ke===0&&(Be.gzindex=0,Be.status=91)}else Be.status=91;if(Be.status===91)if(Be.gzhead.comment){qe=Be.pending;do{if(Be.pending===Be.pending_buf_size&&(Be.gzhead.hcrc&&Be.pending>qe&&(Se.adler=d(Se.adler,Be.pending_buf,Be.pending-qe,qe)),ee(Se),qe=Be.pending,Be.pending===Be.pending_buf_size)){Ke=1;break}Ke=Be.gzindexqe&&(Se.adler=d(Se.adler,Be.pending_buf,Be.pending-qe,qe)),Ke===0&&(Be.status=103)}else Be.status=103;if(Be.status===103&&(Be.gzhead.hcrc?(Be.pending+2>Be.pending_buf_size&&ee(Se),Be.pending+2<=Be.pending_buf_size&&(he(Be,255&Se.adler),he(Be,Se.adler>>8&255),Se.adler=0,Be.status=W)):Be.status=W),Be.pending!==0){if(ee(Se),Se.avail_out===0)return Be.last_flush=-1,p}else if(Se.avail_in===0&&ue(Re)<=ue(Ae)&&Re!==m)return ce(Se,-5);if(Be.status===666&&Se.avail_in!==0)return ce(Se,-5);if(Se.avail_in!==0||Be.lookahead!==0||Re!==h&&Be.status!==666){var Ue=Be.strategy===2?function(et,Qe){for(var Ge;;){if(et.lookahead===0&&(fe(et),et.lookahead===0)){if(Qe===h)return V;break}if(et.match_length=0,Ge=o._tr_tally(et,0,et.window[et.strstart]),et.lookahead--,et.strstart++,Ge&&(le(et,!1),et.strm.avail_out===0))return V}return et.insert=0,Qe===m?(le(et,!0),et.strm.avail_out===0?Q:J):et.last_lit&&(le(et,!1),et.strm.avail_out===0)?V:K}(Be,Re):Be.strategy===3?function(et,Qe){for(var Ge,nt,ft,lt,Mt=et.window;;){if(et.lookahead<=D){if(fe(et),et.lookahead<=D&&Qe===h)return V;if(et.lookahead===0)break}if(et.match_length=0,et.lookahead>=I&&0et.lookahead&&(et.match_length=et.lookahead)}if(et.match_length>=I?(Ge=o._tr_tally(et,1,et.match_length-I),et.lookahead-=et.match_length,et.strstart+=et.match_length,et.match_length=0):(Ge=o._tr_tally(et,0,et.window[et.strstart]),et.lookahead--,et.strstart++),Ge&&(le(et,!1),et.strm.avail_out===0))return V}return et.insert=0,Qe===m?(le(et,!0),et.strm.avail_out===0?Q:J):et.last_lit&&(le(et,!1),et.strm.avail_out===0)?V:K}(Be,Re):i[Be.level].func(Be,Re);if(Ue!==Q&&Ue!==J||(Be.status=666),Ue===V||Ue===Q)return Se.avail_out===0&&(Be.last_flush=-1),p;if(Ue===K&&(Re===1?o._tr_align(Be):Re!==5&&(o._tr_stored_block(Be,0,0,!1),Re===3&&(ne(Be.head),Be.lookahead===0&&(Be.strstart=0,Be.block_start=0,Be.insert=0))),ee(Se),Se.avail_out===0))return Be.last_flush=-1,p}return Re!==m?p:Be.wrap<=0?1:(Be.wrap===2?(he(Be,255&Se.adler),he(Be,Se.adler>>8&255),he(Be,Se.adler>>16&255),he(Be,Se.adler>>24&255),he(Be,255&Se.total_in),he(Be,Se.total_in>>8&255),he(Be,Se.total_in>>16&255),he(Be,Se.total_in>>24&255)):(ve(Be,Se.adler>>>16),ve(Be,65535&Se.adler)),ee(Se),0=Ae.w_size&&(Ke===0&&(ne(Ae.head),Ae.strstart=0,Ae.block_start=0,Ae.insert=0),Qe=new l.Buf8(Ae.w_size),l.arraySet(Qe,Re,Ge-Ae.w_size,Ae.w_size,0),Re=Qe,Ge=Ae.w_size),Ze=Se.avail_in,Ue=Se.next_in,et=Se.input,Se.avail_in=Ge,Se.next_in=0,Se.input=Re,fe(Ae);Ae.lookahead>=I;){for(Be=Ae.strstart,qe=Ae.lookahead-(I-1);Ae.ins_h=(Ae.ins_h<>>=I=M>>>24,N-=I,(I=M>>>16&255)===0)K[u++]=65535&M;else{if(!(16&I)){if(!(64&I)){M=C[(65535&M)+(v&(1<>>=I,N-=I),N<15&&(v+=V[c++]<>>=I=M>>>24,N-=I,!(16&(I=M>>>16&255))){if(!(64&I)){M=A[(65535&M)+(v&(1<>>=I,N-=I,(I=u-h)>3,v&=(1<<(N-=D<<3))-1,i.next_in=c,i.next_out=u,i.avail_in=c>>24&255)+(q>>>8&65280)+((65280&q)<<8)+((255&q)<<24)}function v(){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(q){var W;return q&&q.state?(W=q.state,q.total_in=q.total_out=W.total=0,q.msg="",W.wrap&&(q.adler=1&W.wrap),W.mode=x,W.last=0,W.havedict=0,W.dmax=32768,W.head=null,W.hold=0,W.bits=0,W.lencode=W.lendyn=new i.Buf32(g),W.distcode=W.distdyn=new i.Buf32(y),W.sane=1,W.back=-1,m):p}function C(q){var W;return q&&q.state?((W=q.state).wsize=0,W.whave=0,W.wnext=0,N(q)):p}function A(q,W){var V,K;return q&&q.state?(K=q.state,W<0?(V=0,W=-W):(V=1+(W>>4),W<48&&(W&=15)),W&&(W<8||15=J.wsize?(i.arraySet(J.window,W,V-J.wsize,J.wsize,0),J.wnext=0,J.whave=J.wsize):(K<(Q=J.wsize-J.wnext)&&(Q=K),i.arraySet(J.window,W,V-K,Q,J.wnext),(K-=Q)?(i.arraySet(J.window,W,V-K,K,0),J.wnext=K,J.whave=J.wsize):(J.wnext+=Q,J.wnext===J.wsize&&(J.wnext=0),J.whave>>8&255,V.check=o(V.check,Ke,2,0),le=ee=0,V.mode=2;break}if(V.flags=0,V.head&&(V.head.done=!1),!(1&V.wrap)||(((255&ee)<<8)+(ee>>8))%31){q.msg="incorrect header check",V.mode=30;break}if((15&ee)!=8){q.msg="unknown compression method",V.mode=30;break}if(le-=4,Se=8+(15&(ee>>>=4)),V.wbits===0)V.wbits=Se;else if(Se>V.wbits){q.msg="invalid window size",V.mode=30;break}V.dmax=1<>8&1),512&V.flags&&(Ke[0]=255&ee,Ke[1]=ee>>>8&255,V.check=o(V.check,Ke,2,0)),le=ee=0,V.mode=3;case 3:for(;le<32;){if(ue===0)break e;ue--,ee+=K[J++]<>>8&255,Ke[2]=ee>>>16&255,Ke[3]=ee>>>24&255,V.check=o(V.check,Ke,4,0)),le=ee=0,V.mode=4;case 4:for(;le<16;){if(ue===0)break e;ue--,ee+=K[J++]<>8),512&V.flags&&(Ke[0]=255&ee,Ke[1]=ee>>>8&255,V.check=o(V.check,Ke,2,0)),le=ee=0,V.mode=5;case 5:if(1024&V.flags){for(;le<16;){if(ue===0)break e;ue--,ee+=K[J++]<>>8&255,V.check=o(V.check,Ke,2,0)),le=ee=0}else V.head&&(V.head.extra=null);V.mode=6;case 6:if(1024&V.flags&&(ue<(ge=V.length)&&(ge=ue),ge&&(V.head&&(Se=V.head.extra_len-V.length,V.head.extra||(V.head.extra=new Array(V.head.extra_len)),i.arraySet(V.head.extra,K,J,ge,Se)),512&V.flags&&(V.check=o(V.check,K,ge,J)),ue-=ge,J+=ge,V.length-=ge),V.length))break e;V.length=0,V.mode=7;case 7:if(2048&V.flags){if(ue===0)break e;for(ge=0;Se=K[J+ge++],V.head&&Se&&V.length<65536&&(V.head.name+=String.fromCharCode(Se)),Se&&ge>9&1,V.head.done=!0),q.adler=V.check=0,V.mode=12;break;case 10:for(;le<32;){if(ue===0)break e;ue--,ee+=K[J++]<>>=7&le,le-=7&le,V.mode=27;break}for(;le<3;){if(ue===0)break e;ue--,ee+=K[J++]<>>=1)){case 0:V.mode=14;break;case 1:if(D(V),V.mode=20,W!==6)break;ee>>>=2,le-=2;break e;case 2:V.mode=17;break;case 3:q.msg="invalid block type",V.mode=30}ee>>>=2,le-=2;break;case 14:for(ee>>>=7&le,le-=7≤le<32;){if(ue===0)break e;ue--,ee+=K[J++]<>>16^65535)){q.msg="invalid stored block lengths",V.mode=30;break}if(V.length=65535&ee,le=ee=0,V.mode=15,W===6)break e;case 15:V.mode=16;case 16:if(ge=V.length){if(ue>>=5,le-=5,V.ndist=1+(31&ee),ee>>>=5,le-=5,V.ncode=4+(15&ee),ee>>>=4,le-=4,286>>=3,le-=3}for(;V.have<19;)V.lens[Ze[V.have++]]=0;if(V.lencode=V.lendyn,V.lenbits=7,Ae={bits:V.lenbits},Re=d(0,V.lens,0,19,V.lencode,0,V.work,Ae),V.lenbits=Ae.bits,Re){q.msg="invalid code lengths set",V.mode=30;break}V.have=0,V.mode=19;case 19:for(;V.have>>16&255,De=65535&qe,!((Ee=qe>>>24)<=le);){if(ue===0)break e;ue--,ee+=K[J++]<>>=Ee,le-=Ee,V.lens[V.have++]=De;else{if(De===16){for(Be=Ee+2;le>>=Ee,le-=Ee,V.have===0){q.msg="invalid bit length repeat",V.mode=30;break}Se=V.lens[V.have-1],ge=3+(3&ee),ee>>>=2,le-=2}else if(De===17){for(Be=Ee+3;le>>=Ee)),ee>>>=3,le-=3}else{for(Be=Ee+7;le>>=Ee)),ee>>>=7,le-=7}if(V.have+ge>V.nlen+V.ndist){q.msg="invalid bit length repeat",V.mode=30;break}for(;ge--;)V.lens[V.have++]=Se}}if(V.mode===30)break;if(V.lens[256]===0){q.msg="invalid code -- missing end-of-block",V.mode=30;break}if(V.lenbits=9,Ae={bits:V.lenbits},Re=d(u,V.lens,0,V.nlen,V.lencode,0,V.work,Ae),V.lenbits=Ae.bits,Re){q.msg="invalid literal/lengths set",V.mode=30;break}if(V.distbits=6,V.distcode=V.distdyn,Ae={bits:V.distbits},Re=d(h,V.lens,V.nlen,V.ndist,V.distcode,0,V.work,Ae),V.distbits=Ae.bits,Re){q.msg="invalid distances set",V.mode=30;break}if(V.mode=20,W===6)break e;case 20:V.mode=21;case 21:if(6<=ue&&258<=ne){q.next_out=ce,q.avail_out=ne,q.next_in=J,q.avail_in=ue,V.hold=ee,V.bits=le,c(q,ve),ce=q.next_out,Q=q.output,ne=q.avail_out,J=q.next_in,K=q.input,ue=q.avail_in,ee=V.hold,le=V.bits,V.mode===12&&(V.back=-1);break}for(V.back=0;Me=(qe=V.lencode[ee&(1<>>16&255,De=65535&qe,!((Ee=qe>>>24)<=le);){if(ue===0)break e;ue--,ee+=K[J++]<>ze)])>>>16&255,De=65535&qe,!(ze+(Ee=qe>>>24)<=le);){if(ue===0)break e;ue--,ee+=K[J++]<>>=ze,le-=ze,V.back+=ze}if(ee>>>=Ee,le-=Ee,V.back+=Ee,V.length=De,Me===0){V.mode=26;break}if(32&Me){V.back=-1,V.mode=12;break}if(64&Me){q.msg="invalid literal/length code",V.mode=30;break}V.extra=15&Me,V.mode=22;case 22:if(V.extra){for(Be=V.extra;le>>=V.extra,le-=V.extra,V.back+=V.extra}V.was=V.length,V.mode=23;case 23:for(;Me=(qe=V.distcode[ee&(1<>>16&255,De=65535&qe,!((Ee=qe>>>24)<=le);){if(ue===0)break e;ue--,ee+=K[J++]<>ze)])>>>16&255,De=65535&qe,!(ze+(Ee=qe>>>24)<=le);){if(ue===0)break e;ue--,ee+=K[J++]<>>=ze,le-=ze,V.back+=ze}if(ee>>>=Ee,le-=Ee,V.back+=Ee,64&Me){q.msg="invalid distance code",V.mode=30;break}V.offset=De,V.extra=15&Me,V.mode=24;case 24:if(V.extra){for(Be=V.extra;le>>=V.extra,le-=V.extra,V.back+=V.extra}if(V.offset>V.dmax){q.msg="invalid distance too far back",V.mode=30;break}V.mode=25;case 25:if(ne===0)break e;if(ge=ve-ne,V.offset>ge){if((ge=V.offset-ge)>V.whave&&V.sane){q.msg="invalid distance too far back",V.mode=30;break}fe=ge>V.wnext?(ge-=V.wnext,V.wsize-ge):V.wnext-ge,ge>V.length&&(ge=V.length),je=V.window}else je=Q,fe=ce-V.offset,ge=V.length;for(neP?(I=fe[je+y[W]],le[he+y[W]]):(I=96,0),v=1<>ce)+(N-=v)]=M<<24|I<<16|D|0,N!==0;);for(v=1<>=1;if(v!==0?(ee&=v-1,ee+=v):ee=0,W++,--ve[q]==0){if(q===K)break;q=h[m+y[W]]}if(Q>>7)]}function he(qe,Ke){qe.pending_buf[qe.pending++]=255&Ke,qe.pending_buf[qe.pending++]=Ke>>>8&255}function ve(qe,Ke,Ze){qe.bi_valid>b-Ze?(qe.bi_buf|=Ke<>b-qe.bi_valid,qe.bi_valid+=Ze-b):(qe.bi_buf|=Ke<>>=1,Ze<<=1,0<--Ke;);return Ze>>>1}function je(qe,Ke,Ze){var Ue,et,Qe=new Array(y+1),Ge=0;for(Ue=1;Ue<=y;Ue++)Qe[Ue]=Ge=Ge+Ze[Ue-1]<<1;for(et=0;et<=Ke;et++){var nt=qe[2*et+1];nt!==0&&(qe[2*et]=fe(Qe[nt]++,nt))}}function Ee(qe){var Ke;for(Ke=0;Ke>1;1<=Ze;Ze--)ze(qe,Qe,Ze);for(et=ft;Ze=qe.heap[1],qe.heap[1]=qe.heap[qe.heap_len--],ze(qe,Qe,1),Ue=qe.heap[1],qe.heap[--qe.heap_max]=Ze,qe.heap[--qe.heap_max]=Ue,Qe[2*et]=Qe[2*Ze]+Qe[2*Ue],qe.depth[et]=(qe.depth[Ze]>=qe.depth[Ue]?qe.depth[Ze]:qe.depth[Ue])+1,Qe[2*Ze+1]=Qe[2*Ue+1]=et,qe.heap[1]=et++,ze(qe,Qe,1),2<=qe.heap_len;);qe.heap[--qe.heap_max]=qe.heap[1],function(Mt,Ft){var Ts,js,zt,Nt,Ds,_t,Xs=Ft.dyn_tree,rn=Ft.max_code,Ps=Ft.stat_desc.static_tree,_n=Ft.stat_desc.has_stree,Zs=Ft.stat_desc.extra_bits,gr=Ft.stat_desc.extra_base,Un=Ft.stat_desc.max_length,In=0;for(Nt=0;Nt<=y;Nt++)Mt.bl_count[Nt]=0;for(Xs[2*Mt.heap[Mt.heap_max]+1]=0,Ts=Mt.heap_max+1;Ts>=7;et>>=1)if(1<&&nt.dyn_ltree[2*ft]!==0)return l;if(nt.dyn_ltree[18]!==0||nt.dyn_ltree[20]!==0||nt.dyn_ltree[26]!==0)return o;for(ft=32;ft>>3,(Qe=qe.static_len+3+7>>>3)<=et&&(et=Qe)):et=Qe=Ze+5,Ze+4<=et&&Ke!==-1?Be(qe,Ke,Ze,Ue):qe.strategy===4||Qe===et?(ve(qe,2+(Ue?1:0),3),ke(qe,B,q)):(ve(qe,4+(Ue?1:0),3),function(nt,ft,lt,Mt){var Ft;for(ve(nt,ft-257,5),ve(nt,lt-1,5),ve(nt,Mt-4,4),Ft=0;Ft>>8&255,qe.pending_buf[qe.d_buf+2*qe.last_lit+1]=255&Ke,qe.pending_buf[qe.l_buf+qe.last_lit]=255&Ze,qe.last_lit++,Ke===0?qe.dyn_ltree[2*Ze]++:(qe.matches++,Ke--,qe.dyn_ltree[2*(V[Ze]+h+1)]++,qe.dyn_dtree[2*le(Ke)]++),qe.last_lit===qe.lit_bufsize-1},a._tr_align=function(qe){ve(qe,2,3),ge(qe,N,B),function(Ke){Ke.bi_valid===16?(he(Ke,Ke.bi_buf),Ke.bi_buf=0,Ke.bi_valid=0):8<=Ke.bi_valid&&(Ke.pending_buf[Ke.pending++]=255&Ke.bi_buf,Ke.bi_buf>>=8,Ke.bi_valid-=8)}(qe)}},{"../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={},x=!1,g=l.document,y=Object.getPrototypeOf&&Object.getPrototypeOf(l);y=y&&y.setTimeout?y:l,c={}.toString.call(l.process)==="[object process]"?function(C){process.nextTick(function(){v(C)})}:function(){if(l.postMessage&&!l.importScripts){var C=!0,A=l.onmessage;return l.onmessage=function(){C=!1},l.postMessage("","*"),l.onmessage=A,C}}()?(h="setImmediate$"+Math.random()+"$",l.addEventListener?l.addEventListener("message",N,!1):l.attachEvent("onmessage",N),function(C){l.postMessage(h+C,"*")}):l.MessageChannel?((u=new MessageChannel).port1.onmessage=function(C){v(C.data)},function(C){u.port2.postMessage(C)}):g&&"onreadystatechange"in g.createElement("script")?(d=g.documentElement,function(C){var A=g.createElement("script");A.onreadystatechange=function(){v(C),A.onreadystatechange=null,d.removeChild(A),A=null},d.appendChild(A)}):function(C){setTimeout(v,0,C)},y.setImmediate=function(C){typeof C!="function"&&(C=new Function(""+C));for(var A=new Array(arguments.length-1),T=0;T"u"?i===void 0?this:i:self)}).call(this,typeof Sm<"u"?Sm:typeof self<"u"?self:typeof window<"u"?window:{})},{}]},{},[10])(10)})})(FPt);var KFs=FPt.exports;const zPt=Uc(KFs);function lIe(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 BPt=({embedded:s=!1,onCompose:t}={})=>{_s();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),[x,g]=j.useState("images"),[y,b]=j.useState(null),{data:v=[],isLoading:N}=ht({queryKey:["social-swag-2"],queryFn:async()=>{const{data:ee,error:le}=await U.from("social_swag_2").select("*").order("month",{ascending:!1}).order("sort_order");if(le)throw le;return ee}}),{data:C=[]}=ht({queryKey:["social-swag-2-months"],queryFn:async()=>{const{data:ee,error:le}=await U.from("social_swag_2_months").select("*").order("month",{ascending:!1});if(le)throw le;return ee}}),{data:A=[]}=ht({queryKey:["social-swag-2-reels"],queryFn:async()=>{const{data:ee,error:le}=await U.from("social_swag_2_reels").select("*").order("month",{ascending:!1});if(le)throw le;return ee}}),{data:T=[]}=ht({queryKey:["my-social-accounts-count"],queryFn:async()=>{const{data:ee,error:le}=await U.from("social_accounts").select("id, platform").eq("is_active",!0);if(le)throw le;return ee||[]}}),P=T.length>0,M=j.useMemo(()=>l==="all"?null:A.find(ee=>ee.month===l)||null,[l,A]),I=j.useMemo(()=>[...new Set(v.map(le=>le.month))].sort((le,he)=>he.localeCompare(le)),[v]);j.useEffect(()=>{I.length>0&&l==="all"&&o(I[0])},[I,l]);const D=ee=>{try{const le=pHe(ee,"yyyy-MM",new Date);return Hs(le,"MMMM yyyy")}catch{return ee}},B=j.useMemo(()=>l==="all"?v:v.filter(ee=>ee.month===l),[l,v]),q=j.useMemo(()=>{var ee;return l==="all"?null:((ee=C.find(le=>le.month===l))==null?void 0:ee.canva_link)||null},[l,C]),W=async ee=>{try{await navigator.clipboard.writeText(ee),ae.success("Caption copied to clipboard!")}catch{ae.error("Failed to copy caption")}},V=async(ee,le)=>{try{const ve=await(await fetch(ee)).blob(),ge=/iPhone|iPad|iPod|Android/i.test(navigator.userAgent),fe=navigator.canShare&&navigator.canShare({files:[new File([ve],"test.jpg",{type:"image/jpeg"})]});if(ge&&fe){const je=new File([ve],`social-swag-${le}.jpg`,{type:"image/jpeg"});await navigator.share({files:[je],title:"Social Swag Image"}),ae.success("Image ready to save!")}else{const je=window.URL.createObjectURL(ve),Ee=document.createElement("a");Ee.href=je,Ee.download=`social-swag-${le}.jpg`,document.body.appendChild(Ee),Ee.click(),document.body.removeChild(Ee),window.URL.revokeObjectURL(je),ae.success("Image downloaded!")}}catch(he){he.name!=="AbortError"&&ae.error("Failed to download image")}},K=ee=>{d(le=>{const he=new Set(le);return he.has(ee)?he.delete(ee):he.add(ee),he})},Q=()=>{d(new Set(B.map(ee=>ee.id)))},J=()=>{d(new Set),h(!1)},ce=async()=>{const ee=B.filter(le=>c.has(le.id));if(ee.length===0){ae.error("No images selected");return}p(!0),ae.info(`Preparing ${ee.length} images for download...`);try{const le=new zPt,he=[...ee].sort((Ee,Me)=>Ee.sort_order-Me.sort_order);for(let Ee=0;Ee{u?K(ee.id):r(ee)},ne=({children:ee})=>s?e.jsx(e.Fragment,{children:ee}):e.jsx(Ks,{title:"Social Swag 2.0",children:ee});return e.jsx(ne,{children:e.jsxs("div",{className:"space-y-8",children:[!s&&e.jsxs("div",{className:"relative overflow-hidden rounded-2xl bg-gradient-to-br from-primary via-primary/80 to-info p-8 text-primary-foreground",children:[e.jsx("div",{className:"absolute inset-0 bg-[url('data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iNjAiIGhlaWdodD0iNjAiIHZpZXdCb3g9IjAgMCA2MCA2MCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj48ZyBmaWxsPSJub25lIiBmaWxsLXJ1bGU9ImV2ZW5vZGQiPjxnIGZpbGw9IiNmZmYiIGZpbGwtb3BhY2l0eT0iMC4xIj48cGF0aCBkPSJNMzYgMzRjMC0yIDItNCAyLTRzMiAyIDIgNC0yIDQtMiA0LTItMi0yLTR6Ii8+PC9nPjwvZz48L3N2Zz4=')] opacity-30"}),e.jsxs("div",{className:"relative",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-3 mb-4",children:[e.jsxs($e,{variant:"secondary",className:"bg-white/20 text-white border-0 backdrop-blur-sm",children:[e.jsx(dn,{className:"h-3 w-3 mr-1"}),"New content monthly"]}),e.jsxs($e,{variant:"secondary",className:"bg-white/20 text-white border-0 backdrop-blur-sm",children:[e.jsx(Jl,{className:"h-3 w-3 mr-1"}),v.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(ua,{defaultValue:"gallery",className:"space-y-6",children:[!s&&e.jsxs(ha,{className:"grid w-full max-w-md grid-cols-2",children:[e.jsxs(Qt,{value:"gallery",className:"gap-2",children:[e.jsx(Jl,{className:"h-4 w-4"}),"Gallery"]}),e.jsxs(Qt,{value:"scheduled",className:"gap-2",children:[e.jsx(Nl,{className:"h-4 w-4"}),"Scheduled"]})]}),e.jsxs(Jt,{value:"gallery",className:"space-y-6",children:[P?e.jsx(_e,{className:"border rounded-xl",children:e.jsx(Oe,{className:"p-6",children:e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsx("div",{className:"p-3 rounded-full bg-muted text-2xl",children:"📸"}),e.jsxs("div",{className:"flex-1",children:[e.jsx("h3",{className:"font-semibold text-foreground mb-1",children:"Ready to post!"}),e.jsx("p",{className:"text-muted-foreground",children:'Click any image and use "Create Post" to share directly to your connected accounts.'})]}),e.jsx($,{variant:"outline",size:"sm",asChild:!0,className:"gap-2",children:e.jsx(Wn,{to:"/mission-control/integrations",children:"Manage Accounts"})})]})})}):e.jsx(_e,{className:"border-2 border-dashed border-primary/30 bg-gradient-to-r from-pink-500/5 via-purple-500/5 to-blue-500/5 rounded-xl",children:e.jsx(Oe,{className:"p-6",children:e.jsxs("div",{className:"flex flex-col sm:flex-row items-start sm:items-center gap-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"p-2 rounded-full bg-blue-500/10",children:e.jsx(jf,{className:"h-5 w-5 text-blue-600"})}),e.jsx("div",{className:"p-2 rounded-full bg-pink-500/10",children:e.jsx(Qh,{className:"h-5 w-5 text-pink-600"})})]}),e.jsxs("div",{className:"flex-1",children:[e.jsx("h3",{className:"font-semibold text-foreground mb-1",children:"Post directly to social media"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Connect your Facebook & Instagram accounts to post images with one click!"})]}),e.jsx($,{asChild:!0,className:"gap-2 bg-gradient-to-r from-pink-500 via-purple-500 to-blue-500 hover:from-pink-600 hover:via-purple-600 hover:to-blue-600",children:e.jsxs(Wn,{to:"/social-connections",children:[e.jsx(Dc,{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(ee=>e.jsx("button",{onClick:()=>o(ee),className:Tt("px-4 py-2 rounded-full text-sm font-medium transition-all",l===ee?"bg-primary text-primary-foreground shadow-sm":"bg-muted text-muted-foreground hover:text-foreground"),children:D(ee)},ee))}),l!=="all"&&(q?e.jsxs("a",{href:q,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 ",D(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 ",D(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:()=>{g("images"),J()},className:Tt("flex items-center gap-2 px-4 py-2 rounded-full text-sm font-medium transition-all",x==="images"?"bg-background text-foreground shadow-sm":"text-muted-foreground hover:text-foreground"),children:[e.jsx(Jl,{className:"h-4 w-4"}),"Images"]}),e.jsxs("button",{onClick:()=>{g("reels"),J()},className:Tt("flex items-center gap-2 px-4 py-2 rounded-full text-sm font-medium transition-all",x==="reels"?"bg-background text-foreground shadow-sm":"text-muted-foreground hover:text-foreground"),children:[e.jsx(lh,{className:"h-4 w-4"}),"Reels"]})]}),x==="images"&&e.jsx("div",{className:"flex flex-wrap items-center gap-3",children:u?e.jsxs(e.Fragment,{children:[e.jsxs($,{variant:"outline",size:"sm",onClick:Q,className:"gap-2",children:["Select All (",B.length,")"]}),e.jsxs($,{variant:"outline",size:"sm",onClick:J,className:"gap-2",children:[e.jsx(pr,{className:"h-4 w-4"}),"Cancel"]}),c.size>0&&e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs($,{size:"sm",onClick:ce,disabled:m,className:"gap-2",children:[e.jsx(di,{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($,{variant:"outline",size:"sm",onClick:()=>h(!0),className:"gap-2",children:[e.jsx(oa,{className:"h-4 w-4"}),"Select Images"]})})]}),N&&e.jsx("div",{className:"text-center py-12 text-muted-foreground",children:"Loading..."}),!N&&x==="images"&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-4",children:B.map(ee=>{const le=c.has(ee.id);return e.jsx(_e,{className:Tt("group cursor-pointer overflow-hidden border-0 shadow-md hover:shadow-xl transition-all duration-300 rounded-2xl",u&&le&&"ring-2 ring-primary ring-offset-2"),onClick:()=>ue(ee),children:e.jsxs("div",{className:"relative aspect-[4/5] overflow-hidden",children:[e.jsx("img",{src:lIe(ee.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"}),ee.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:Hs(new Date(ee.post_date+"T00:00:00"),"MMM d")})}),u&&e.jsx("div",{className:Tt("absolute top-2 right-2 w-6 h-6 rounded-full border-2 flex items-center justify-center transition-all",le?"bg-primary border-primary text-primary-foreground":"bg-white/80 border-muted-foreground/50"),children:le&&e.jsx(oa,{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"})})]})},ee.id)})}),B.length===0&&e.jsxs("div",{className:"text-center py-12",children:[e.jsx(Jl,{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&&x==="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(_e,{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:lIe(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($e,{variant:"secondary",className:"bg-black/50 text-white border-0 backdrop-blur-sm text-xs",children:[e.jsx(lh,{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(lh,{className:"h-12 w-12 text-muted-foreground/50 mx-auto mb-4"}),e.jsx("p",{className:"text-muted-foreground",children:"No reel available for this month yet."})]})})]}),e.jsx(Os,{open:!!n,onOpenChange:()=>r(null),children:e.jsx(Rs,{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:lIe(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(ia,{className:"h-4 w-4"}),Hs(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(ia,{className:"h-3.5 w-3.5"}),"Post on ",Hs(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($,{onClick:()=>{if(t){t({mediaUrl:n.image_url,mediaType:"image",caption:n.caption,swagItemId:n.id}),r(null);return}b({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(Br,{className:"h-4 w-4"}),"Create Post"]}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-3",children:[e.jsxs($,{variant:"outline",onClick:()=>W(n.caption),className:"flex-1 gap-2",children:[e.jsx(Ca,{className:"h-4 w-4"}),"Copy Caption"]}),e.jsxs($,{variant:"outline",onClick:()=>V(n.image_url,n.id),className:"flex-1 gap-2",children:[e.jsx(di,{className:"h-4 w-4"}),"Download"]})]})]})]})]})})})}),e.jsx(Os,{open:!!a,onOpenChange:()=>i(null),children:e.jsx(Rs,{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(lh,{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($,{onClick:()=>W(a.caption||""),className:"flex-1 gap-2",children:[e.jsx(Ca,{className:"h-4 w-4"}),"Copy Caption"]}),a.canva_link&&e.jsxs($,{variant:"outline",onClick:()=>window.open(a.canva_link,"_blank"),className:"flex-1 gap-2",children:[e.jsx(Tr,{className:"h-4 w-4"}),"Open in Canva"]})]})]})]})})})}),e.jsx(GFs,{open:!!y,onOpenChange:ee=>!ee&&b(null),imageUrl:(y==null?void 0:y.imageUrl)||"",imageId:(y==null?void 0:y.imageId)||"",defaultCaption:(y==null?void 0:y.caption)||"",swagItemId:y==null?void 0:y.imageId})]}),e.jsx(Jt,{value:"scheduled",children:e.jsx(WFs,{})})]})]})})},ldt={facebook:{id:"facebook",label:"Facebook Page",icon:jf,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:Qh,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:kg,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:ai,dot:"bg-emerald-600",chip:"bg-emerald-600/10 text-emerald-700 border-emerald-600/20",captionLimit:1500,supportsVideo:!1,requiresMedia:!1}},Y3=s=>ldt[s]??ldt.facebook,YFs=[{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}],cdt="agent-uploads",ZFs="social-studio",XFs=200*1024*1024,ddt=s=>typeof s=="number"?new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(s):"";function QFs({onSelect:s}){const{user:t}=_s(),n=j.useRef(null),[r,a]=j.useState(!1),{data:i=[]}=ht({queryKey:["studio-uploads",t==null?void 0:t.id],enabled:!!(t!=null&&t.id),queryFn:async()=>{const{data:d,error:u}=await U.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=[]}=ht({queryKey:["studio-swag"],queryFn:async()=>{const{data:d,error:u}=await U.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=[]}=ht({queryKey:["studio-listings",t==null?void 0:t.id],enabled:!!(t!=null&&t.id),queryFn:async()=>{const{data:d,error:u}=await U.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>XFs){ae.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=`${ZFs}/${t.id}/${crypto.randomUUID()}.${h}`,{error:p}=await U.storage.from(cdt).upload(m,d,{cacheControl:"3600",upsert:!1,contentType:d.type});if(p)throw p;const{data:x}=U.storage.from(cdt).getPublicUrl(m),g=x.publicUrl;await U.from("social_media_assets").insert({user_id:t.id,storage_path:m,public_url:g,media_type:u?"video":"image",file_name:d.name,file_size:d.size}),s({mediaUrl:g,mediaType:u?"video":"image",source:"upload"}),ae.success("Media uploaded")}catch(h){console.error(h),ae.error("Upload failed. Please try again.")}finally{a(!1),n.current&&(n.current.value="")}};return e.jsxs(ua,{defaultValue:"upload",className:"space-y-4",children:[e.jsxs(ha,{className:"grid grid-cols-3 w-full",children:[e.jsxs(Qt,{value:"upload",className:"gap-2",children:[e.jsx(si,{className:"h-4 w-4"}),"Upload"]}),e.jsxs(Qt,{value:"swag",className:"gap-2",children:[e.jsx(dn,{className:"h-4 w-4"}),"Gallery"]}),e.jsxs(Qt,{value:"listings",className:"gap-2",children:[e.jsx(sa,{className:"h-4 w-4"}),"Listings"]})]}),e.jsxs(Jt,{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(_e,{className:"border-dashed border-2",children:e.jsxs(Oe,{className:"p-6 flex flex-col items-center text-center gap-3",children:[e.jsx(Jl,{className:"h-8 w-8 text-muted-foreground"}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:"Upload a photo or video"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"JPG, PNG or MP4 up to 200MB"})]}),e.jsxs($,{onClick:()=>{var d;return(d=n.current)==null?void 0:d.click()},disabled:r,className:"gap-2",children:[r?e.jsx(Ht,{className:"h-4 w-4 animate-spin"}):e.jsx(si,{className:"h-4 w-4"}),r?"Uploading…":"Choose file"]})]})}),i.length>0&&e.jsx(Oi,{className:"h-56",children:e.jsx("div",{className:"grid grid-cols-3 gap-2 pr-3",children:i.map(d=>e.jsxs("button",{type:"button",onClick:()=>s({mediaUrl:d.public_url,mediaType:d.media_type,source:"upload"}),className:"relative overflow-hidden rounded-lg border hover:ring-2 hover:ring-primary transition",children:[d.media_type==="video"?e.jsx("video",{src:d.public_url,className:"h-24 w-full object-cover"}):e.jsx("img",{src:d.public_url,alt:d.file_name??"",loading:"lazy",className:"h-24 w-full object-cover"}),d.media_type==="video"&&e.jsx($e,{className:"absolute bottom-1 left-1 text-[10px]",children:"Video"})]},d.id))})})]}),e.jsx(Jt,{value:"swag",children:e.jsx(Oi,{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(Jt,{value:"listings",children:e.jsx(Oi,{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}`,ddt(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(_e,{children:e.jsxs(Oe,{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:ddt(d.price)})]}),e.jsx($e,{variant:"secondary",className:"capitalize",children:String(d.status).replace(/_/g," ")})]}),u.length>0?e.jsx("div",{className:"grid grid-cols-4 gap-2",children:u.slice(0,8).map((m,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 JFs({platform:s,accountName:t,avatarUrl:n,caption:r,mediaUrl:a,mediaType:i}){const l=Y3(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(_e,{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(ki,{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(fo,{className:"h-5 w-5"}),e.jsx(Ed,{className:"h-5 w-5"}),e.jsx(Br,{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(Ox,{className:"h-4 w-4"})," Like"]}),e.jsxs("span",{className:"flex items-center gap-1 text-xs",children:[e.jsx(Ed,{className:"h-4 w-4"})," Comment"]}),e.jsxs("span",{className:"flex items-center gap-1 text-xs",children:[e.jsx(UK,{className:"h-4 w-4"})," Share"]})]})]})]})}function $Pt(){const{user:s}=_s();return ht({queryKey:["studio-accounts",s==null?void 0:s.id],enabled:!!(s!=null&&s.id),queryFn:async()=>{const{data:t,error:n}=await U.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 e7s(s){const{user:t}=_s();return ht({queryKey:["studio-posts",t==null?void 0:t.id,"all"],enabled:!!(t!=null&&t.id),queryFn:async()=>{let n=U.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 t7s(){const s=ts();return()=>{s.invalidateQueries({queryKey:["studio-posts"]}),s.invalidateQueries({queryKey:["studio-accounts"]})}}const sre=s=>s.page_name||s.platform_username||Y3(s.platform).label,cIe=s=>{const t=n=>String(n).padStart(2,"0");return`${s.getFullYear()}-${t(s.getMonth()+1)}-${t(s.getDate())}T${t(s.getHours())}:${t(s.getMinutes())}`};function s7s({seed:s,editingPost:t,onSaved:n,onCancelEdit:r}){const{user:a}=_s(),{data:i=[],isLoading:l}=$Pt(),[o,c]=j.useState(""),[d,u]=j.useState(null),[h,m]=j.useState("text"),[p,x]=j.useState("manual"),[g,y]=j.useState([]),[b,v]=j.useState({}),[N,C]=j.useState(!1),[A,T]=j.useState(!1),[P,M]=j.useState(""),[I,D]=j.useState(null);j.useEffect(()=>{s&&(s.mediaUrl&&(u(s.mediaUrl),m(s.mediaType??"image")),s.caption!==void 0&&c(s.caption),s.source&&x(s.source),s.scheduledFor&&(T(!0),M(cIe(s.scheduledFor))))},[s]),j.useEffect(()=>{var ne;if(!t)return;c(t.caption??""),u(((ne=t.media_urls)==null?void 0:ne[0])??null),m(t.media_type),x(t.source??"manual"),y(t.social_post_targets.map(ee=>ee.social_account_id));const ue={};t.social_post_targets.forEach(ee=>{ee.caption_override&&(ue[ee.social_account_id]=ee.caption_override)}),v(ue),C(Object.keys(ue).length>0),t.scheduled_for&&(T(!0),M(cIe(new Date(t.scheduled_for))))},[t]);const B=j.useMemo(()=>i.filter(ue=>g.includes(ue.id)),[i,g]),q=ue=>{var ne;return N&&((ne=b[ue])!=null&&ne.trim())?b[ue]:o},W=j.useMemo(()=>{const ue=[];return B.forEach(ne=>{const ee=Y3(ne.platform),le=q(ne.id);ee.requiresMedia&&!d&&ue.push(`${ee.label} requires a photo or video.`),!ee.supportsVideo&&h==="video"&&ue.push(`${ee.label} can't publish video from LevelUp yet.`),le.length>ee.captionLimit&&ue.push(`${ee.label} caption is over the ${ee.captionLimit.toLocaleString()} character limit.`)}),Array.from(new Set(ue))},[B,d,h,o,b,N]),V=()=>{c(""),u(null),m("text"),x("manual"),y([]),v({}),C(!1),T(!1),M("")},K=ue=>{u(ue.mediaUrl),m(ue.mediaType),x(ue.source),ue.caption&&!o.trim()&&c(ue.caption)},Q=ue=>y(ne=>ne.includes(ue)?ne.filter(ee=>ee!==ue):[...ne,ue]),J=async ue=>{if(a!=null&&a.id){if(ue!=="draft"&&g.length===0){ae.error("Choose at least one account to post to.");return}if(ue!=="draft"&&!o.trim()&&!d){ae.error("Add a caption or media before publishing.");return}if(ue==="schedule"&&!P){ae.error("Pick a date and time to schedule.");return}if(ue!=="draft"&&W.length>0){ae.error(W[0]);return}D(ue);try{const ne={user_id:a.id,caption:o.trim()||null,media_type:h,media_urls:d?[d]:[],source:p,status:ue==="draft"?"draft":ue==="schedule"?"scheduled":"publishing",scheduled_for:ue==="schedule"?new Date(P).toISOString():null};let ee=(t==null?void 0:t.id)??null;if(ee){const{error:le}=await U.from("social_posts").update(ne).eq("id",ee);if(le)throw le;await U.from("social_post_targets").delete().eq("post_id",ee)}else{const{data:le,error:he}=await U.from("social_posts").insert(ne).select("id").single();if(he)throw he;ee=le.id}if(g.length>0){const le=B.map(ve=>{var ge;return{post_id:ee,user_id:a.id,social_account_id:ve.id,platform:ve.platform,caption_override:N&&((ge=b[ve.id])!=null&&ge.trim())?b[ve.id].trim():null,status:ue==="now"?"pending":ue==="schedule"?"scheduled":"draft"}}),{error:he}=await U.from("social_post_targets").insert(le);if(he)throw he}if(ue==="now"){const{data:le,error:he}=await U.functions.invoke("social-publish-post",{body:{post_id:ee}});if(he)throw he;const ve=le==null?void 0:le.status;ve==="failed"?ae.error("Publishing failed. Check the Queue tab for details."):ve==="partial"?ae.warning("Some accounts failed. Check the Queue tab to retry."):ae.success("Posted to your accounts.")}else ae.success(ue==="draft"?"Draft saved":"Post scheduled");t||V(),n==null||n()}catch(ne){console.error(ne),ae.error((ne==null?void 0:ne.message)??"Something went wrong saving your post.")}finally{D(null)}}},ce=(ue,ne)=>{const ee=P?new Date(P):new Date;ee.setHours(ue,ne,0,0),ee.getTime(){u(null),m("text")},children:e.jsx(Pn,{className:"h-4 w-4"})})]}),e.jsx(QFs,{onSelect:K})]})]}),e.jsxs(_e,{children:[e.jsx(Bt,{className:"pb-3",children:e.jsx(Ut,{className:"text-base",children:"2. Write your caption"})}),e.jsxs(Oe,{className:"space-y-4",children:[e.jsx(Is,{value:o,onChange:ue=>c(ue.target.value),rows:6,placeholder:"What do you want to share with your audience?"}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("span",{className:"text-xs text-muted-foreground",children:[o.length," characters"]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(se,{htmlFor:"per-platform",className:"text-xs",children:"Customize per platform"}),e.jsx(Tn,{id:"per-platform",checked:N,onCheckedChange:C})]})]}),N&&B.length>0&&e.jsxs(ua,{defaultValue:B[0].id,className:"pt-2",children:[e.jsx(ha,{className:"flex-wrap h-auto",children:B.map(ue=>e.jsx(Qt,{value:ue.id,className:"text-xs",children:sre(ue)},ue.id))}),B.map(ue=>e.jsx(Jt,{value:ue.id,className:"pt-3",children:e.jsx(Is,{rows:5,value:b[ue.id]??"",placeholder:`Leave blank to use the main caption for ${Y3(ue.platform).label}`,onChange:ne=>v(ee=>({...ee,[ue.id]:ne.target.value}))})},ue.id))]})]})]}),e.jsxs(_e,{children:[e.jsx(Bt,{className:"pb-3",children:e.jsx(Ut,{className:"text-base",children:"3. Pick your accounts"})}),e.jsxs(Oe,{className:"space-y-3",children:[l&&e.jsx(Ht,{className:"h-4 w-4 animate-spin text-muted-foreground"}),!l&&i.length===0&&e.jsx("p",{className:"text-sm text-muted-foreground",children:"No connected accounts yet. Connect Facebook, Instagram, LinkedIn or Google Business in Social settings."}),e.jsx("div",{className:"grid gap-2 sm:grid-cols-2",children:i.map(ue=>{const ne=Y3(ue.platform),ee=ne.icon,le=g.includes(ue.id);return e.jsxs("button",{type:"button",onClick:()=>Q(ue.id),className:`flex items-center gap-3 rounded-lg border p-3 text-left transition ${le?"border-primary bg-primary/5":"hover:bg-muted/50"}`,children:[e.jsxs(Ea,{className:"h-9 w-9",children:[e.jsx(ki,{src:ue.profile_picture_url??void 0}),e.jsx(Ta,{children:sre(ue).slice(0,2).toUpperCase()})]}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:"text-sm font-medium truncate",children:sre(ue)}),e.jsxs("p",{className:"text-xs text-muted-foreground flex items-center gap-1",children:[e.jsx(ee,{className:"h-3 w-3"})," ",ne.label]})]}),le&&e.jsx(oa,{className:"h-4 w-4 text-primary"})]},ue.id)})})]})]}),e.jsxs(_e,{children:[e.jsx(Bt,{className:"pb-3",children:e.jsx(Ut,{className:"text-base",children:"4. Publish or schedule"})}),e.jsxs(Oe,{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(se,{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(Tn,{id:"schedule-toggle",checked:A,onCheckedChange:T})]}),A&&e.jsxs("div",{className:"space-y-3",children:[e.jsx(be,{type:"datetime-local",value:P,onChange:ue=>M(ue.target.value)}),e.jsx("div",{className:"flex flex-wrap gap-2",children:YFs.map(ue=>e.jsx($,{type:"button",variant:"outline",size:"sm",onClick:()=>ce(ue.hour,ue.minute),children:ue.label},ue.label))})]}),W.length>0&&e.jsxs(dX,{variant:"destructive",children:[e.jsx(mc,{className:"h-4 w-4"}),e.jsx(uX,{children:e.jsx("ul",{className:"list-disc pl-4 space-y-1",children:W.map(ue=>e.jsx("li",{children:ue},ue))})})]}),e.jsx(Hl,{}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs($,{variant:"outline",onClick:()=>J("draft"),disabled:!!I,className:"gap-2",children:[I==="draft"?e.jsx(Ht,{className:"h-4 w-4 animate-spin"}):e.jsx(Jo,{className:"h-4 w-4"}),"Save draft"]}),A?e.jsxs($,{onClick:()=>J("schedule"),disabled:!!I,className:"gap-2",children:[I==="schedule"?e.jsx(Ht,{className:"h-4 w-4 animate-spin"}):e.jsx(Xu,{className:"h-4 w-4"}),"Schedule post"]}):e.jsxs($,{onClick:()=>J("now"),disabled:!!I,className:"gap-2",children:[I==="now"?e.jsx(Ht,{className:"h-4 w-4 animate-spin"}):e.jsx(Br,{className:"h-4 w-4"}),"Post now"]})]})]})]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("h3",{className:"text-sm font-semibold",children:"Live preview"}),e.jsxs($e,{variant:"secondary",children:[B.length," selected"]})]}),B.length===0?e.jsx(_e,{children:e.jsx(Oe,{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:B.map(ue=>e.jsx(JFs,{platform:ue.platform,accountName:sre(ue),avatarUrl:ue.profile_picture_url,caption:q(ue.id),mediaUrl:d,mediaType:h},ue.id))})]})]})}const n7s=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],udt={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 r7s({posts:s,onCreateAt:t,onOpenPost:n}){const[r,a]=j.useState(()=>{const d=new Date;return new Date(d.getFullYear(),d.getMonth(),1)}),i=j.useMemo(()=>{const d=new Date(r);return d.setDate(1-d.getDay()),Array.from({length:42},(u,h)=>{const m=new Date(d);return m.setDate(d.getDate()+h),m})},[r]),l=j.useMemo(()=>{const d=new Map;return s.forEach(u=>{const h=u.scheduled_for??u.published_at;if(!h)return;const m=new Date(h),p=`${m.getFullYear()}-${m.getMonth()}-${m.getDate()}`;d.set(p,[...d.get(p)??[],u])}),d},[s]),o=new Date,c=d=>d.toDateString()===o.toDateString();return e.jsx(_e,{children:e.jsxs(Oe,{className:"p-4 space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("h3",{className:"text-lg font-semibold",children:r.toLocaleDateString("en-US",{month:"long",year:"numeric"})}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx($,{variant:"outline",size:"sm",onClick:()=>a(new Date(o.getFullYear(),o.getMonth(),1)),children:"Today"}),e.jsx($,{variant:"outline",size:"icon",className:"h-8 w-8",onClick:()=>a(new Date(r.getFullYear(),r.getMonth()-1,1)),children:e.jsx(Ic,{className:"h-4 w-4"})}),e.jsx($,{variant:"outline",size:"icon",className:"h-8 w-8",onClick:()=>a(new Date(r.getFullYear(),r.getMonth()+1,1)),children:e.jsx(Ja,{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:n7s.map(d=>e.jsx("div",{className:"py-1",children:d},d))}),e.jsx("div",{className:"grid grid-cols-7 gap-px bg-border rounded-lg overflow-hidden",children:i.map(d=>{const u=`${d.getFullYear()}-${d.getMonth()}-${d.getDate()}`,h=l.get(u)??[],m=d.getMonth()!==r.getMonth();return e.jsxs("div",{className:`group relative min-h-[104px] bg-background p-1.5 ${m?"opacity-50":""}`,children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:`text-xs ${c(d)?"flex h-5 w-5 items-center justify-center rounded-full bg-primary text-primary-foreground":"text-muted-foreground"}`,children:d.getDate()}),e.jsx("button",{type:"button","aria-label":"Create post",onClick:()=>{const p=new Date(d);p.setHours(9,0,0,0),t(p)},className:"opacity-0 group-hover:opacity-100 transition text-muted-foreground hover:text-foreground",children:e.jsx(sn,{className:"h-3.5 w-3.5"})})]}),e.jsxs("div",{className:"mt-1 space-y-1",children:[h.slice(0,3).map(p=>{var g;const x=new Date(p.scheduled_for??p.published_at);return e.jsxs("button",{type:"button",onClick:()=>n(p),className:`w-full rounded border px-1.5 py-1 text-left text-[10px] leading-tight ${udt[p.status]??udt.draft}`,children:[e.jsx("span",{className:"font-medium",children:x.toLocaleTimeString("en-US",{hour:"numeric",minute:"2-digit"})})," ",e.jsx("span",{className:"truncate",children:((g=p.caption)==null?void 0:g.slice(0,24))||"Media post"}),e.jsx("span",{className:"mt-1 flex gap-1",children:p.social_post_targets.slice(0,4).map(y=>e.jsx("span",{className:`h-1.5 w-1.5 rounded-full ${Y3(y.platform).dot}`},y.id))})]},p.id)}),h.length>3&&e.jsxs($e,{variant:"secondary",className:"text-[10px]",children:["+",h.length-3," more"]})]})]},u)})})]})})}const a7s=s=>{switch(s){case"published":case"success":return{label:"Published",variant:"default",icon:Fr};case"partial":return{label:"Partly published",variant:"secondary",icon:mc};case"failed":return{label:"Failed",variant:"destructive",icon:mc};case"publishing":case"pending":return{label:"Publishing",variant:"secondary",icon:Ht};case"scheduled":return{label:"Scheduled",variant:"outline",icon:Xu};default:return{label:"Draft",variant:"outline",icon:Ya}}};function hdt({posts:s,accounts:t,onEdit:n,onChanged:r,emptyLabel:a}){const[i,l]=j.useState(null),o=u=>t.find(h=>h.id===u),c=async u=>{l(u.id);try{await U.from("social_posts").update({status:"publishing",scheduled_for:null}).eq("id",u.id);const{data:h,error:m}=await U.functions.invoke("social-publish-post",{body:{post_id:u.id}});if(m)throw m;const p=h==null?void 0:h.status;p==="failed"?ae.error("Publishing failed. See the error details below."):p==="partial"?ae.warning("Some accounts failed."):ae.success("Published."),r()}catch(h){ae.error((h==null?void 0:h.message)??"Could not publish this post.")}finally{l(null)}},d=async u=>{l(u.id);try{const{error:h}=await U.from("social_posts").delete().eq("id",u.id);if(h)throw h;ae.success("Post deleted"),r()}catch(h){ae.error((h==null?void 0:h.message)??"Could not delete this post.")}finally{l(null)}};return s.length===0?e.jsx(_e,{children:e.jsx(Oe,{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(u=>{var x;const h=a7s(u.status),m=h.icon,p=u.scheduled_for??u.published_at??u.created_at;return e.jsx(_e,{children:e.jsx(Oe,{className:"p-4",children:e.jsxs("div",{className:"flex gap-4",children:[((x=u.media_urls)==null?void 0:x[0])&&(u.media_type==="video"?e.jsx("video",{src:u.media_urls[0],className:"h-20 w-20 rounded-lg object-cover shrink-0"}):e.jsx("img",{src:u.media_urls[0],alt:"",loading:"lazy",className:"h-20 w-20 rounded-lg object-cover shrink-0"})),e.jsxs("div",{className:"min-w-0 flex-1 space-y-2",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs($e,{variant:h.variant,className:"gap-1",children:[e.jsx(m,{className:`h-3 w-3 ${h.label==="Publishing"?"animate-spin":""}`}),h.label]}),e.jsx("span",{className:"text-xs text-muted-foreground",children:new Date(p).toLocaleString("en-US",{month:"short",day:"numeric",hour:"numeric",minute:"2-digit"})})]}),e.jsx("p",{className:"text-sm line-clamp-2 whitespace-pre-wrap",children:u.caption||"Media only post"}),e.jsx("div",{className:"flex flex-wrap gap-2",children:u.social_post_targets.map(g=>{const y=Y3(g.platform),b=y.icon,v=o(g.social_account_id),N=g.status==="success",C=g.status==="failed";return e.jsxs("div",{className:`flex items-center gap-2 rounded-full border px-2.5 py-1 text-xs ${C?"border-destructive/30 bg-destructive/5 text-destructive":y.chip}`,children:[e.jsxs(Ea,{className:"h-4 w-4",children:[e.jsx(ki,{src:(v==null?void 0:v.profile_picture_url)??void 0}),e.jsx(Ta,{className:"text-[8px]",children:e.jsx(b,{className:"h-2.5 w-2.5"})})]}),e.jsx("span",{className:"max-w-[140px] truncate",children:(v==null?void 0:v.page_name)||(v==null?void 0:v.platform_username)||y.label}),N&&g.permalink&&e.jsx("a",{href:g.permalink,target:"_blank",rel:"noopener noreferrer","aria-label":"View post",children:e.jsx(Tr,{className:"h-3 w-3"})}),C&&e.jsx(mc,{className:"h-3 w-3"})]},g.id)})}),u.social_post_targets.some(g=>g.status==="failed")&&e.jsx("div",{className:"rounded-md border border-destructive/20 bg-destructive/5 p-2 space-y-1",children:u.social_post_targets.filter(g=>g.status==="failed").map(g=>e.jsxs("p",{className:"text-xs text-destructive",children:[e.jsxs("span",{className:"font-medium",children:[Y3(g.platform).label,":"]})," ",g.error_message||"Publishing failed."]},g.id))})]}),e.jsxs("div",{className:"flex flex-col gap-2 shrink-0",children:[e.jsxs($,{variant:"outline",size:"sm",className:"gap-1",onClick:()=>n(u),children:[e.jsx(Ya,{className:"h-3.5 w-3.5"})," Edit"]}),u.status!=="published"&&e.jsxs($,{size:"sm",className:"gap-1",disabled:i===u.id,onClick:()=>c(u),children:[i===u.id?e.jsx(Ht,{className:"h-3.5 w-3.5 animate-spin"}):u.status==="failed"||u.status==="partial"?e.jsx(Wi,{className:"h-3.5 w-3.5"}):e.jsx(Br,{className:"h-3.5 w-3.5"}),u.status==="failed"||u.status==="partial"?"Retry":"Post now"]}),e.jsxs($,{variant:"ghost",size:"sm",className:"gap-1 text-muted-foreground",disabled:i===u.id,onClick:()=>d(u),children:[e.jsx(Pn,{className:"h-3.5 w-3.5"})," Delete"]})]})]})})},u.id)})})}const i7s=()=>{const[s,t]=j.useState("compose"),[n,r]=j.useState(null),[a,i]=j.useState(null),{data:l=[]}=$Pt(),{data:o=[],isLoading:c}=e7s(),d=t7s(),u=j.useMemo(()=>o.filter(g=>g.status==="scheduled"||g.status==="draft"||g.status==="publishing").sort((g,y)=>new Date(g.scheduled_for??g.created_at).getTime()-new Date(y.scheduled_for??y.created_at).getTime()),[o]),h=j.useMemo(()=>o.filter(g=>["published","partial","failed","cancelled"].includes(g.status)),[o]),m=h.filter(g=>g.status==="failed"||g.status==="partial").length,p=(g,y=null)=>{r(g),i(y),t("compose")},x=g=>{p({mediaUrl:g.mediaUrl,mediaType:g.mediaType,caption:g.caption,source:"swag",sourceRef:g.swagItemId??g.reelId})};return e.jsx(Ks,{title:"Social Studio",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(_e,{className:"overflow-hidden border-none bg-gradient-to-br from-primary/10 via-background to-background",children:e.jsxs(Oe,{className:"p-6 flex flex-col gap-5 md:flex-row md:items-center md:justify-between",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs($e,{variant:"secondary",className:"gap-1",children:[e.jsx(dn,{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(g=>e.jsxs(Ea,{className:"h-8 w-8 border-2 border-background",title:g.page_name??g.platform,children:[e.jsx(ki,{src:g.profile_picture_url??void 0}),e.jsx(Ta,{className:"text-[10px]",children:Y3(g.platform).label.slice(0,2)})]},g.id))}),e.jsx($,{variant:"outline",size:"sm",asChild:!0,className:"gap-2",children:e.jsxs(Wn,{to:"/social-connections",children:[e.jsx(G3,{className:"h-4 w-4"})," Manage accounts"]})})]}),e.jsxs($,{className:"gap-2",onClick:()=>p(null),children:[e.jsx(bm,{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:xR},{label:"Scheduled & drafts",value:u.length,icon:Nl},{label:"Published",value:h.filter(g=>g.status==="published").length,icon:Fr}].map(({label:g,value:y,icon:b})=>e.jsx(_e,{children:e.jsxs(Oe,{className:"p-4 flex items-center gap-3",children:[e.jsx("div",{className:"rounded-lg bg-primary/10 p-2",children:e.jsx(b,{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:g})]})]})},g))}),e.jsxs(ua,{value:s,onValueChange:t,className:"space-y-6",children:[e.jsxs(ha,{className:"flex-wrap h-auto",children:[e.jsxs(Qt,{value:"compose",className:"gap-2",children:[e.jsx(bm,{className:"h-4 w-4"}),"Compose"]}),e.jsxs(Qt,{value:"calendar",className:"gap-2",children:[e.jsx(Nl,{className:"h-4 w-4"}),"Calendar"]}),e.jsxs(Qt,{value:"queue",className:"gap-2",children:[e.jsx(Br,{className:"h-4 w-4"}),"Queue",u.length>0&&e.jsx($e,{variant:"secondary",className:"ml-1",children:u.length})]}),e.jsxs(Qt,{value:"history",className:"gap-2",children:[e.jsx(Fr,{className:"h-4 w-4"}),"History",m>0&&e.jsx($e,{variant:"destructive",className:"ml-1",children:m})]}),e.jsxs(Qt,{value:"gallery",className:"gap-2",children:[e.jsx(dn,{className:"h-4 w-4"}),"Swag gallery"]})]}),e.jsx(Jt,{value:"compose",children:e.jsx(s7s,{seed:n,editingPost:a,onSaved:()=>{d(),i(null),r(null)},onCancelEdit:()=>{i(null),r(null)}})}),e.jsx(Jt,{value:"calendar",children:e.jsx(r7s,{posts:o,onCreateAt:g=>p({scheduledFor:g}),onOpenPost:g=>p(null,g)})}),e.jsx(Jt,{value:"queue",children:e.jsx(hdt,{posts:u,accounts:l,onEdit:g=>p(null,g),onChanged:d,emptyLabel:c?"Loading your posts…":"Nothing scheduled yet. Compose a post to get started."})}),e.jsx(Jt,{value:"history",children:e.jsx(hdt,{posts:h,accounts:l,onEdit:g=>p(null,g),onChanged:d,emptyLabel:"Your published posts will show up here."})}),e.jsx(Jt,{value:"gallery",children:e.jsx(BPt,{embedded:!0,onCompose:x})})]})]})})},o7s=[{id:"branding-bar",title:"Branding Bar Studio",description:"Drop in any image — get a branded version with your headshot, logo, and contact info.",icon:Jl,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:sa,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:Lo,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:ml,comingSoon:!0,color:"from-orange-500 to-red-500"},{id:"milestones",title:"Client Milestones",description:"Closing day, home anniversaries, birthdays, referral thank-yous.",icon:np,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:Z_,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:H3,comingSoon:!0,color:"from-amber-500 to-yellow-500"}];function l7s(){return e.jsx(Ks,{title:"Marketing Studio",children:e.jsxs("div",{className:"container max-w-6xl py-8 space-y-6",children:[e.jsxs(Ul,{children:[e.jsx("title",{children:"Marketing Studio | LevelUp"}),e.jsx("meta",{name:"description",content:"Brand any image, video, listing, or milestone in seconds — no AI credits used."})]}),e.jsxs("div",{className:"flex flex-col md:flex-row md:items-end md:justify-between gap-4",children:[e.jsxs("div",{children:[e.jsxs($e,{variant:"secondary",className:"mb-2 gap-1",children:[e.jsx(dn,{className:"h-3 w-3"})," New"]}),e.jsx("h1",{className:"text-3xl md:text-4xl font-bold tracking-tight",children:"Marketing Studio"}),e.jsx("p",{className:"text-muted-foreground max-w-2xl mt-1",children:"Your one-stop creative hub. Drop in any photo or video, and walk away with a fully branded export — no design skills, no AI credits."})]}),e.jsx($,{variant:"outline",asChild:!0,children:e.jsxs(Wn,{to:"/marketing-studio/brand-kit",children:[e.jsx(Rc,{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:o7s.map(s=>{const t=s.icon,n=e.jsxs(_e,{className:`group relative overflow-hidden transition-all h-full ${s.comingSoon?"opacity-70":"hover:shadow-xl hover:-translate-y-0.5 cursor-pointer"}`,children:[e.jsx("div",{className:`absolute inset-x-0 top-0 h-1 bg-gradient-to-r ${s.color}`}),e.jsxs(Oe,{className:"p-5 space-y-3",children:[e.jsx("div",{className:`inline-flex h-10 w-10 items-center justify-center rounded-lg bg-gradient-to-br ${s.color} text-white shadow-md`,children:e.jsx(t,{className:"h-5 w-5"})}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("h3",{className:"font-semibold",children:s.title}),s.comingSoon&&e.jsx($e,{variant:"outline",className:"text-[10px]",children:"Coming soon"})]}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:s.description})]})]})]});return s.to&&!s.comingSoon?e.jsx(Wn,{to:s.to,className:"block",children:n},s.id):e.jsx("div",{children:n},s.id)})})]})})}function Lee(){const s=Za();return ht({queryKey:["marketing-brand-presets",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await U.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 c7s(){const{data:s,...t}=Lee();return{data:(s==null?void 0:s.find(n=>n.is_default))??(s==null?void 0:s[0])??null,...t}}function d7s(){const s=Za(),t=ts();return yt({mutationFn:async n=>{if(!s)throw new Error("Not signed in");if(n.is_default&&await U.from("marketing_brand_presets").update({is_default:!1}).eq("user_id",s),n.id){const{id:r,...a}=n,{data:i,error:l}=await U.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 U.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 u7s(){const s=Za(),t=ts();return yt({mutationFn:async n=>{const{error:r}=await U.from("marketing_brand_presets").delete().eq("id",n);if(r)throw r},onSuccess:()=>t.invalidateQueries({queryKey:["marketing-brand-presets",s]})})}async function h7s(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 U.storage.from("marketing-studio-uploads").upload(a,t,{upsert:!0,cacheControl:"3600"});if(i)throw i;const{data:l}=await U.storage.from("marketing-studio-uploads").createSignedUrl(a,60*60*24*365*5);return(l==null?void 0:l.signedUrl)??""}function m7s({preset:s,onSaved:t,onCancel:n}){var g;const r=Za(),a=d7s(),i=u7s(),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 mi(async()=>{const{supabase:v}=await Promise.resolve().then(()=>kds);return{supabase:v}},void 0),{data:b}=await y.from("profiles").select("name, email, phone, avatar_url, website_url, title, brokerage_id").eq("id",r).maybeSingle();b&&h(v=>({...v,display_name:v.display_name||(b.name??""),email:v.email||(b.email??""),phone:v.phone||(b.phone??""),headshot_url:v.headshot_url||(b.avatar_url??""),website_url:v.website_url||(b.website_url??""),tagline:v.tagline||(b.title??"")}))})()},[r]);const m=async(y,b)=>{if(r){d(y);try{const v=await h7s(r,b,y);h(N=>({...N,[y==="headshot"?"headshot_url":"brokerage_logo_url"]:v}))}catch(v){ae.error(v.message||"Upload failed")}finally{d(null)}}},p=async()=>{try{const y=await a.mutateAsync({id:s==null?void 0:s.id,...u});ae.success("Brand preset saved"),t==null||t(y)}catch(y){ae.error(y.message||"Save failed")}},x=async()=>{s!=null&&s.id&&await Yi("Delete this brand preset?")&&(await i.mutateAsync(s.id),ae.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(se,{children:"Preset name"}),e.jsx(be,{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(Tn,{checked:u.is_default,onCheckedChange:y=>h({...u,is_default:y})}),e.jsx(se,{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(se,{children:"Display name"}),e.jsx(be,{value:u.display_name,onChange:y=>h({...u,display_name:y.target.value})})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Phone"}),e.jsx(be,{value:u.phone,onChange:y=>h({...u,phone:y.target.value})})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Email"}),e.jsx(be,{value:u.email,onChange:y=>h({...u,email:y.target.value})})]}),e.jsxs("div",{children:[e.jsx(se,{children:"License #"}),e.jsx(be,{value:u.license_number,onChange:y=>h({...u,license_number:y.target.value})})]}),e.jsxs("div",{className:"md:col-span-2",children:[e.jsx(se,{children:"Tagline"}),e.jsx(be,{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(se,{children:"Website"}),e.jsx(be,{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(se,{children:"Headshot"}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs(Ea,{className:"h-16 w-16",children:[e.jsx(ki,{src:u.headshot_url||void 0}),e.jsx(Ta,{children:((g=u.display_name)==null?void 0:g[0])??"A"})]}),e.jsxs($,{type:"button",variant:"outline",size:"sm",onClick:()=>{var y;return(y=l.current)==null?void 0:y.click()},disabled:c==="headshot",children:[c==="headshot"?e.jsx(Ht,{className:"h-4 w-4 animate-spin"}):e.jsx(si,{className:"h-4 w-4 mr-1"}),"Upload"]}),e.jsx("input",{ref:l,type:"file",accept:"image/*",hidden:!0,onChange:y=>{var b;return((b=y.target.files)==null?void 0:b[0])&&m("headshot",y.target.files[0])}})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Brokerage logo"}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"h-16 w-24 bg-muted rounded flex items-center justify-center overflow-hidden border",children:u.brokerage_logo_url?e.jsx("img",{src:u.brokerage_logo_url,alt:"logo",className:"max-h-full max-w-full object-contain"}):e.jsx("span",{className:"text-xs text-muted-foreground",children:"No logo"})}),e.jsxs($,{type:"button",variant:"outline",size:"sm",onClick:()=>{var y;return(y=o.current)==null?void 0:y.click()},disabled:c==="logo",children:[c==="logo"?e.jsx(Ht,{className:"h-4 w-4 animate-spin"}):e.jsx(si,{className:"h-4 w-4 mr-1"}),"Upload"]}),e.jsx("input",{ref:o,type:"file",accept:"image/*",hidden:!0,onChange:y=>{var b;return((b=y.target.files)==null?void 0:b[0])&&m("logo",y.target.files[0])}})]})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx(se,{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(be,{value:u.brand_color,onChange:y=>h({...u,brand_color:y.target.value})})]})]}),e.jsxs("div",{children:[e.jsx(se,{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(be,{value:u.accent_color,onChange:y=>h({...u,accent_color:y.target.value})})]})]})]}),e.jsxs("div",{className:"flex justify-between pt-2",children:[e.jsx("div",{children:(s==null?void 0:s.id)&&e.jsxs($,{variant:"ghost",size:"sm",onClick:x,className:"text-destructive",children:[e.jsx(Pn,{className:"h-4 w-4 mr-1"})," Delete"]})}),e.jsxs("div",{className:"flex gap-2",children:[n&&e.jsx($,{variant:"outline",onClick:n,children:"Cancel"}),e.jsxs($,{onClick:p,disabled:a.isPending,children:[a.isPending&&e.jsx(Ht,{className:"h-4 w-4 mr-1 animate-spin"}),"Save preset"]})]})]})]})}function p7s(){const{data:s,isLoading:t}=Lee(),[n,r]=j.useState(null);return e.jsx(Ks,{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(Ul,{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(Wn,{to:"/marketing-studio",className:"text-sm text-muted-foreground inline-flex items-center gap-1 hover:underline",children:[e.jsx(ka,{className:"h-3 w-3"})," Back to Marketing Studio"]}),e.jsx("h1",{className:"text-2xl md:text-3xl font-bold tracking-tight mt-1",children:"Brand Kit"}),e.jsx("p",{className:"text-sm md:text-base text-muted-foreground",children:"Save your branding once — apply it across every Marketing Studio module."})]}),e.jsxs($,{onClick:()=>r("new"),className:"w-full sm:w-auto",children:[e.jsx(sn,{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(_e,{className:"border-dashed",children:e.jsxs(Oe,{className:"py-12 text-center space-y-3",children:[e.jsx("h3",{className:"font-semibold",children:"Create your first brand preset"}),e.jsx("p",{className:"text-sm text-muted-foreground max-w-md mx-auto",children:"We'll pre-fill from your profile. You can have multiple presets — Personal, Team, Luxury division — and switch between them."}),e.jsxs($,{onClick:()=>r("new"),children:[e.jsx(sn,{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(_e,{className:"overflow-hidden",children:[e.jsx("div",{className:"h-3",style:{background:`linear-gradient(90deg, ${a.brand_color}, ${a.accent_color})`}}),e.jsxs(Bt,{className:"pb-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(Ut,{className:"text-lg flex items-center gap-2",children:[a.name,a.is_default&&e.jsxs($e,{variant:"secondary",className:"gap-1",children:[e.jsx(Qa,{className:"h-3 w-3"})," Default"]})]}),e.jsx($,{size:"sm",variant:"ghost",onClick:()=>r(a),children:e.jsx(Ya,{className:"h-4 w-4"})})]}),e.jsx(vr,{children:a.display_name})]}),e.jsxs(Oe,{className:"text-sm text-muted-foreground space-y-1",children:[a.tagline&&e.jsxs("div",{className:"italic",children:['"',a.tagline,'"']}),a.phone&&e.jsx("div",{children:a.phone}),a.email&&e.jsx("div",{children:a.email})]})]},a.id))}),e.jsx(Os,{open:n!==null,onOpenChange:a=>!a&&r(null),children:e.jsxs(Rs,{className:"max-w-2xl max-h-[90vh] overflow-y-auto w-[calc(100vw-2rem)] sm:w-full",children:[e.jsx(Us,{children:e.jsx(zs,{children:n==="new"?"New brand preset":"Edit brand preset"})}),e.jsx(m7s,{preset:n==="new"?null:n,onSaved:()=>r(null),onCancel:()=>r(null)})]})})]})})}const J7e=[{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"}],f7s=s=>J7e.find(t=>t.id===s)??J7e[0];function x7s(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 g7s({value:s,onChange:t,mediaType:n}){const r=J7e.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:Tt("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(y7s,{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 y7s({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 v7s=Math.PI/180;function b7s(){return typeof window<"u"&&({}.toString.call(window)==="[object Window]"||{}.toString.call(window)==="[object global]")}const F8=typeof global<"u"?global:typeof window<"u"?window:typeof WorkerGlobalScope<"u"?self:{},ii={_global:F8,version:"10.2.5",isBrowser:b7s(),isUnminified:/param/.test((function(s){}).toString()),dblClickWindow:400,getAngle(s){return ii.angleDeg?s*v7s: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 ii.DD.isDragging},isTransforming(){var s,t;return(t=(s=ii.Transformer)===null||s===void 0?void 0:s.isTransforming())!==null&&t!==void 0?t:!1},isDragReady(){return!!ii.DD.node},releaseCanvasOnDestroy:!0,document:F8.document,_injectGlobal(s){typeof F8.Konva<"u"&&console.error("Several Konva instances detected. It is not recommended to use multiple Konva instances in the same environment."),F8.Konva=s}},Wp=s=>{ii[s.prototype.getClassName()]=s};ii._injectGlobal(ii);const _7s=`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"; `,mdt=()=>{if(typeof document>"u")throw new Error(_7s)};class W_{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 W_(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=tr._getRotation(c.rotation),c}}const w7s="[object Array]",j7s="[object Number]",N7s="[object String]",k7s="[object Boolean]",S7s=Math.PI/180,C7s=180/Math.PI,lG="#",A7s="",E7s="0",T7s="Konva warning: ",pdt="Konva error: ",M7s="rgb(",dIe={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]},L7s=/rgb\((\d{1,3}),(\d{1,3}),(\d{1,3})\)/;let nre=[],cG=null;const P7s=typeof requestAnimationFrame<"u"&&requestAnimationFrame||function(s){setTimeout(s,16)},tr={_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)===w7s},_isNumber(s){return Object.prototype.toString.call(s)===j7s&&!isNaN(s)&&isFinite(s)},_isString(s){return Object.prototype.toString.call(s)===N7s},_isBoolean(s){return Object.prototype.toString.call(s)===k7s},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){nre.push(s),nre.length===1&&P7s(function(){const t=nre;nre=[],t.forEach(function(n){n()})})},createCanvasElement(){mdt();const s=document.createElement("canvas");try{s.style=s.style||{}}catch{}return s},createImageElement(){return mdt(),document.createElement("img")},_isInDocument(s){for(;s=s.parentNode;)if(s==document)return!0;return!1},_urlToImage(s,t){const n=tr.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(lG,A7s);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=E7s+s;return lG+s},isCanvasFarblingActive(){if(cG!==null)return cG;if(typeof document>"u")return cG=!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 cG=r,this.releaseCanvas(s),cG},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),lG+this._rgbToHex(s,t,n)},getSnappedHexColor(s){const t=this._hexToRgb(s);return lG+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 dIe?(t=dIe[s],{r:t[0],g:t[1],b:t[2]}):s[0]===lG?this._hexToRgb(s.substring(1)):s.substr(0,4)===M7s?(t=L7s.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",tr._namedColorToRBA(s)||tr._hex3ColorToRGBA(s)||tr._hex4ColorToRGBA(s)||tr._hex6ColorToRGBA(s)||tr._hex8ColorToRGBA(s)||tr._rgbColorToRGBA(s)||tr._rgbaColorToRGBA(s)||tr._hslColorToRGBA(s)},_namedColorToRBA(s){const t=dIe[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=tr.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=tr._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+=D7s+d.join(fdt)+R7s)):(i+=o.property,t||(i+=$7s+o.val)),i+=z7s;return i}clearTrace(){this.traceArr=[]}_trace(t){let n=this.traceArr,r;n.push(t),r=n.length,r>=q7s&&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=xdt.length,r=this.setAttr,a,i;const l=function(o){let c=t[o],d;t[o]=function(){return i=I7s(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 zd._dragElements.forEach(t=>{s=t.node}),s},_dragElements:new Map,_drag(s){const t=[];zd._dragElements.forEach((n,r)=>{const{node:a}=n,i=a.getStage();i.setPointersPositions(s),n.pointerId===void 0&&(n.pointerId=tr._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=[];zd._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")&&(zd.justDragged=!0,ii._mouseListenClick=!1,ii._touchListenClick=!1,ii._pointerListenClick=!1,n.dragStatus="stopped");const l=n.node.getLayer()||n.node instanceof ii.Stage&&n.node;l&&t.indexOf(l)===-1&&t.push(l)}),t.forEach(n=>{n.draw()})},_endDragAfter(s){zd._dragElements.forEach((t,n)=>{t.dragStatus==="stopped"&&t.node.fire("dragend",{type:"dragend",target:t.node,evt:s},!0),t.dragStatus!=="dragging"&&zd._dragElements.delete(n)})}};ii.isBrowser&&(window.addEventListener("mouseup",zd._endDragBefore,!0),window.addEventListener("touchend",zd._endDragBefore,!0),window.addEventListener("touchcancel",zd._endDragBefore,!0),window.addEventListener("mousemove",zd._drag),window.addEventListener("touchmove",zd._drag),window.addEventListener("mouseup",zd._endDragAfter,!1),window.addEventListener("touchend",zd._endDragAfter,!1),window.addEventListener("touchcancel",zd._endDragAfter,!1));function z6(s){return tr._isString(s)?'"'+s+'"':Object.prototype.toString.call(s)==="[object Number]"||tr._isBoolean(s)?s:Object.prototype.toString.call(s)}function UPt(s){return s>255?255:s<0?0:Math.round(s)}function ei(){if(ii.isUnminified)return function(s,t){return tr._isNumber(s)||tr.warn(z6(s)+' is a not valid value for "'+t+'" attribute. The value should be a number.'),s}}function SAe(s){if(ii.isUnminified)return function(t,n){let r=tr._isNumber(t),a=tr._isArray(t)&&t.length==s;return!r&&!a&&tr.warn(z6(t)+' is a not valid value for "'+n+'" attribute. The value should be a number or Array('+s+")"),t}}function AWe(){if(ii.isUnminified)return function(s,t){return tr._isNumber(s)||s==="auto"||tr.warn(z6(s)+' is a not valid value for "'+t+'" attribute. The value should be a number or "auto".'),s}}function eF(){if(ii.isUnminified)return function(s,t){return tr._isString(s)||tr.warn(z6(s)+' is a not valid value for "'+t+'" attribute. The value should be a string.'),s}}function qPt(){if(ii.isUnminified)return function(s,t){const n=tr._isString(s),r=Object.prototype.toString.call(s)==="[object CanvasGradient]"||s&&s.addColorStop;return n||r||tr.warn(z6(s)+' is a not valid value for "'+t+'" attribute. The value should be a string or a native gradient.'),s}}function W7s(){if(ii.isUnminified)return function(s,t){const n=Int8Array?Object.getPrototypeOf(Int8Array):null;return n&&s instanceof n||(tr._isArray(s)?s.forEach(function(r){tr._isNumber(r)||tr.warn('"'+t+'" attribute has non numeric element '+r+". Make sure that all elements are numbers.")}):tr.warn(z6(s)+' is a not valid value for "'+t+'" attribute. The value should be a array of numbers.')),s}}function rk(){if(ii.isUnminified)return function(s,t){return s===!0||s===!1||tr.warn(z6(s)+' is a not valid value for "'+t+'" attribute. The value should be a boolean.'),s}}function K7s(s){if(ii.isUnminified)return function(t,n){return t==null||tr.isObject(t)||tr.warn(z6(t)+' is a not valid value for "'+n+'" attribute. The value should be an object with properties '+s),t}}const dG="get",uG="set",cn={addGetterSetter(s,t,n,r,a){cn.addGetter(s,t,n),cn.addSetter(s,t,r,a),cn.addOverloadedGetterSetter(s,t)},addGetter(s,t,n){const r=dG+tr._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=uG+tr._capitalize(t);s.prototype[a]||cn.overWriteSetter(s,t,n,r)},overWriteSetter(s,t,n,r){const a=uG+tr._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=tr._capitalize,o=dG+l(t),c=uG+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},cn.addOverloadedGetterSetter(s,t)},addOverloadedGetterSetter(s,t){const n=tr._capitalize(t),r=uG+n,a=dG+n;s.prototype[t]=function(){return arguments.length?(this[r](arguments[0]),this):this[a]()}},addDeprecatedGetterSetter(s,t,n,r){tr.error("Adding deprecated "+t);const a=dG+tr._capitalize(t),i=t+" property is deprecated and will be removed soon. Look at Konva change log for more information.";s.prototype[a]=function(){tr.error(i);const l=this.attrs[t];return l===void 0?n:l},cn.addSetter(s,t,r,function(){tr.error(i)}),cn.addOverloadedGetterSetter(s,t)},backCompat(s,t){tr.each(t,function(n,r){const a=s.prototype[r],i=dG+tr._capitalize(n),l=uG+tr._capitalize(n);function o(){a.apply(this,arguments),tr.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 Y7s(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=ii.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=ii.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=ii.Filters;c&&c.Contrast&&c.Contrast.call(this,l)}}case"grayscale":return function(i){const l=ii.Filters;l&&l.Grayscale&&l.Grayscale.call(this,i)};case"sepia":return function(i){const l=ii.Filters;l&&l.Sepia&&l.Sepia.call(this,i)};case"invert":return function(i){const l=ii.Filters;l&&l.Invert&&l.Invert.call(this,i)};default:tr.warn(`CSS filter "${r}" is not supported in fallback mode. Consider using function filters for better compatibility.`);break}}return()=>{}}const z2e="absoluteOpacity",ydt="allEventListeners",O4="absoluteTransform",vdt="absoluteScale",FM="canvas",Z7s="Change",X7s="children",Q7s="konva",e9e="listening",J7s="mouseenter",e9s="mouseleave",t9s="pointerenter",s9s="pointerleave",n9s="touchenter",r9s="touchleave",bdt="set",_dt="Shape",B2e=" ",wdt="stage",AA="transform",a9s="Stage",t9e="visible",i9s=["xChange.konva","yChange.konva","scaleXChange.konva","scaleYChange.konva","skewXChange.konva","skewYChange.konva","rotationChange.konva","offsetXChange.konva","offsetYChange.konva","transformsEnabledChange.konva"].join(B2e);let o9s=1,ci=class wW{constructor(t){this._id=o9s++,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===AA||t===O4)&&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===AA||t===O4)&&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(B2e);this.on(a,()=>{this._clearCache(t)}),this._attachedDepsListeners.set(t,!0)}return this._getCache(t,r)}_getCanvasCache(){return this._cache.get(FM)}_clearSelfAndDescendantCache(t){this._clearCache(t),t===O4&&this.fire("absoluteTransformChange")}clearCache(){if(this._cache.has(FM)){const{scene:t,filter:n,hit:r}=this._cache.get(FM);tr.releaseCanvas(t._canvas,n._canvas,r._canvas),this._cache.delete(FM)}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){tr.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 x=new sE({pixelRatio:l,width:a,height:i}),g=new sE({pixelRatio:l,width:0,height:0,willReadFrequently:!0}),y=new CWe({pixelRatio:h,width:a,height:i}),b=x.getContext(),v=y.getContext(),N=new sE({width:x.width/x.pixelRatio+Math.abs(o),height:x.height/x.pixelRatio+Math.abs(c),pixelRatio:x.pixelRatio}),C=N.getContext();return y.isCache=!0,x.isCache=!0,this._cache.delete(FM),this._filterUpToDate=!1,n.imageSmoothingEnabled===!1&&(x.getContext()._context.imageSmoothingEnabled=!1,g.getContext()._context.imageSmoothingEnabled=!1),b.save(),v.save(),C.save(),b.translate(-o,-c),v.translate(-o,-c),C.translate(-o,-c),N.x=o,N.y=c,this._isUnderCache=!0,this._clearSelfAndDescendantCache(z2e),this._clearSelfAndDescendantCache(vdt),this.drawScene(x,this,N),this.drawHit(y,this),this._isUnderCache=!1,b.restore(),v.restore(),u&&(b.save(),b.beginPath(),b.rect(0,0,a,i),b.closePath(),b.setAttr("strokeStyle","red"),b.setAttr("lineWidth",5),b.stroke(),b.restore()),tr.releaseCanvas(N._canvas),this._cache.set(FM,{scene:x,filter:g,hit:y,x:o,y:c}),this._requestDraw(),this}isCached(){return this._cache.has(FM)}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)&&zd._dragElements.delete(n)}),this._remove(),this}_clearCaches(){this._clearSelfAndDescendantCache(O4),this._clearSelfAndDescendantCache(z2e),this._clearSelfAndDescendantCache(vdt),this._clearSelfAndDescendantCache(wdt),this._clearSelfAndDescendantCache(t9e),this._clearSelfAndDescendantCache(e9e)}_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"+tr._capitalize(t);return tr._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!==X7s&&(r=bdt+tr._capitalize(n),tr._isFunction(this[r])?this[r](t[n]):this._setAttr(n,t[n]))}),this}isListening(){return this._getCache(e9e,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(t9e,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;zd._dragElements.forEach(l=>{l.dragStatus==="dragging"&&(l.node.nodeType==="Stage"||l.node.getLayer()===r)&&(a=!0)});const i=!n&&!ii.hitOnDragEnabled&&(a||ii.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!==a9s&&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(AA),this._clearSelfAndDescendantCache(O4)),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 W_,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(AA);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(AA),this._clearSelfAndDescendantCache(O4),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 tr.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 tr.warn("Node has no parent. zIndex parameter is ignored."),this;(t<0||t>=this.parent.children.length)&&tr.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(z2e,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=tr.isObject(r)&&!tr._isPlainObject(r)&&!tr._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 tr._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,tr._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():ii.dragDistance}_off(t,n,r){let a=this.eventListeners[t],i,l,o;for(i=0;i=0)||this.isDragging())return;let a=!1;zd._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=zd._dragElements.get(this._id),r=n&&n.dragStatus==="dragging",a=n&&n.dragStatus==="ready";r?this.stopDrag():a&&zd._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 tr.haveIntersection(r,this.getClientRect())}static create(t,n){return tr._isString(t)&&(t=JSON.parse(t)),this._createNode(t,n)}static _createNode(t,n){let r=wW.prototype.getClassName.call(t),a=t.children,i,l,o;n&&(t.attrs.container=n),ii[r]||(tr.warn('Can not find a node with class name "'+r+'". Fallback to "Shape".'),r="Shape");const c=ii[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=ci.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=ci.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 x=p.getMatrix();l.transform(x[0],x[1],x[2],x[3],x[4],x[5]),l.beginPath();let g;if(d)g=d.call(this,l,this);else{const y=this.clipX(),b=this.clipY();l.rect(y||0,b||0,o,c)}l.clip.apply(l,g),x=p.copy().invert().getMatrix(),l.transform(x[0],x[1],x[2],x[3],x[4],x[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 x=p.getClientRect({relativeTo:u,skipShadow:t.skipShadow,skipStroke:t.skipStroke});x.width===0&&x.height===0||(i===void 0?(i=x.x,l=x.y,o=x.x+x.width,c=x.y+x.height):(i=Math.min(i,x.x),l=Math.min(l,x.y),o=Math.max(o,x.x+x.width),c=Math.max(c,x.y+x.height)))});const h=this.find("Shape");let m=!1;for(let p=0;ps.indexOf("pointer")>=0?"pointer":s.indexOf("touch")>=0?"touch":"mouse",S7=s=>{const t=CW(s);if(t==="pointer")return ii.pointerEventsEnabled&&hIe.pointer;if(t==="touch")return hIe.touch;if(t==="mouse")return hIe.mouse};function Ndt(s={}){return(s.clipFunc||s.clipWidth||s.clipHeight)&&tr.warn("Stage does not support clipping. Please use clip for Layers or Groups."),s}const p9s="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);",IY=[];let CAe=class extends iw{constructor(t){super(Ndt(t)),this._pointerPositions=[],this._changedPointerPositions=[],this._buildDOM(),this._bindContentEvents(),IY.push(this),this.on("widthChange.konva heightChange.konva",this._resizeDOM),this.on("visibleChange.konva",this._checkVisibility),this.on("clipWidthChange.konva clipHeightChange.konva clipFuncChange.konva",()=>{Ndt(this.attrs)}),this._checkVisibility()}_validateAdd(t){const n=t.getType()==="Layer",r=t.getType()==="FastLayer";n||r||tr.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===c9s){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&&IY.splice(n,1),tr.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}:(tr.warn(p9s),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 sE({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+jdt,this.content.style.height=n+jdt),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;ah9s&&tr.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(),ii.isBrowser&&this.content.appendChild(t.canvas._canvas),this}getParent(){return null}getLayer(){return null}hasPointerCapture(t){return HPt(t,this)}setPointerCapture(t){GPt(t,this)}releaseCapture(t){PY(t)}getLayers(){return this.children}_bindContentEvents(){ii.isBrowser&&m9s.forEach(([t,n])=>{this.content.addEventListener(t,r=>{this[n](r)},{passive:!1})})}_pointerenter(t){this.setPointersPositions(t);const n=S7(t.type);n&&this._fire(n.pointerenter,{evt:t,target:this,currentTarget:this})}_pointerover(t){this.setPointersPositions(t);const n=S7(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=S7(t.type),r=CW(t.type);if(!n)return;this.setPointersPositions(t);const a=this._getTargetShape(r),i=!(ii.isDragging()||ii.isTransforming())||ii.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=S7(t.type),r=CW(t.type);if(!n)return;this.setPointersPositions(t);let a=!1;this._changedPointerPositions.forEach(i=>{const l=this.getIntersection(i);if(zd.justDragged=!1,ii["_"+r+"ListenClick"]=!0,!l||!l.isListening()){this[r+"ClickStartShape"]=void 0;return}ii.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=S7(t.type),r=CW(t.type);if(!n)return;const a=t.type.indexOf("touch")>=0||t.pointerType==="touch";if(ii.isDragging()&&zd.node.preventDefault()&&t.cancelable&&a&&t.preventDefault(),this.setPointersPositions(t),!(!(ii.isDragging()||ii.isTransforming())||ii.hitOnDragEnabled))return;const l={};let o=!1;const c=this._getTargetShape(r);this._changedPointerPositions.forEach(d=>{const u=uIe(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=S7(t.type),r=CW(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=uIe(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;ii["_"+r+"InDblClickWindow"]?(m=!0,clearTimeout(this[r+"DblTimeout"])):zd.justDragged||(ii["_"+r+"InDblClickWindow"]=!0,clearTimeout(this[r+"DblTimeout"])),this[r+"DblTimeout"]=setTimeout(function(){ii["_"+r+"InDblClickWindow"]=!1},ii.dblClickWindow),d&&d.isListening()?(o=!0,this[r+"ClickEndShape"]=d,d._fireAndBubble(n.pointerup,{...h}),ii["_"+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),ii["_"+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}),ii["_"+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(s9e,{evt:t}):this._fire(s9e,{evt:t,target:this,currentTarget:this})}_wheel(t){this.setPointersPositions(t);const n=this.getIntersection(this.getPointerPosition());n&&n.isListening()?n._fireAndBubble(n9e,{evt:t}):this._fire(n9e,{evt:t,target:this,currentTarget:this})}_pointercancel(t){this.setPointersPositions(t);const n=uIe(t.pointerId)||this.getIntersection(this.getPointerPosition());n&&n._fireAndBubble(K9,EWe(t)),PY(t.pointerId)}_lostpointercapture(t){PY(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:tr._getFirstPointerId(t)}],this._changedPointerPositions=[{x:r,y:a,id:tr._getFirstPointerId(t)}])}_setPointerPosition(t){tr.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 sE({width:this.width(),height:this.height()}),this.bufferHitCanvas=new CWe({pixelRatio:1,width:this.width(),height:this.height()}),!ii.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 tr.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}};CAe.prototype.nodeType=l9s;Wp(CAe);cn.addGetterSetter(CAe,"container");ii.isBrowser&&document.addEventListener("visibilitychange",()=>{IY.forEach(s=>{s.batchDraw()})});const nIt="hasShadow",rIt="shadowRGBA",aIt="patternImage",iIt="linearGradient",oIt="radialGradient";let cre;function mIe(){return cre||(cre=tr.createCanvasElement().getContext("2d"),cre)}const DY={};function f9s(s){const t=this.attrs.fillRule;t?s.fill(t):s.fill()}function x9s(s){s.stroke()}function g9s(s){const t=this.attrs.fillRule;t?s.fill(t):s.fill()}function y9s(s){s.stroke()}function v9s(){this._clearCache(nIt)}function b9s(){this._clearCache(rIt)}function _9s(){this._clearCache(aIt)}function w9s(){this._clearCache(iIt)}function j9s(){this._clearCache(oIt)}let $a=class extends ci{constructor(t){super(t);let n,r=0;for(;n=tr.getHitColor(),!(n&&!(n in DY));)if(r++,r>=1e4){tr.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=tr.getRandomColor();break}this.colorKey=n,DY[n]=this}getContext(){return tr.warn("shape.getContext() method is deprecated. Please do not use it."),this.getLayer().getContext()}getCanvas(){return tr.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(nIt,this._hasShadow)}_hasShadow(){return this.shadowEnabled()&&this.shadowOpacity()!==0&&!!(this.shadowColor()||this.shadowBlur()||this.shadowOffsetX()||this.shadowOffsetY())}_getFillPattern(){return this._getCache(aIt,this.__getFillPattern)}__getFillPattern(){if(this.fillPatternImage()){const n=mIe().createPattern(this.fillPatternImage(),this.fillPatternRepeat()||"repeat");if(n&&n.setTransform){const r=new W_;r.translate(this.fillPatternX(),this.fillPatternY()),r.rotate(ii.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(iIt,this.__getLinearGradient)}__getLinearGradient(){const t=this.fillLinearGradientColorStops();if(t){const n=mIe(),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 ci.prototype.destroy.call(this),delete DY[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){tr.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,x=d+Math.abs(m),g=u+Math.abs(p),y=h&&this.shadowBlur()||0,b=x+y*2,v=g+y*2,N={width:b,height:v,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,x=p.getContext();r?(x.save(),x.setTransform(1,0,0,1,0,0),x.clearRect(0,0,p.width,p.height),x.restore()):x.clear(),x.save(),x._applyLineJoin(this),x._applyMiterLimit(this);const g=this.getAbsoluteTransform(n).getMatrix();x.transform(g[0],g[1],g[2],g[3],g[4],g[5]),c.call(this,x,this),x.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||tr.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=tr._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){tr.error("Unable to draw hit graph from cached scene canvas. "+c.message)}return this}hasPointerCapture(t){return HPt(t,this)}setPointerCapture(t){GPt(t,this)}releaseCapture(t){PY(t)}};$a.prototype._fillFunc=f9s;$a.prototype._strokeFunc=x9s;$a.prototype._fillFuncHit=g9s;$a.prototype._strokeFuncHit=y9s;$a.prototype._centroid=!1;$a.prototype.nodeType="Shape";Wp($a);$a.prototype.eventListeners={};$a.prototype.on("shadowColorChange.konva shadowBlurChange.konva shadowOffsetChange.konva shadowOpacityChange.konva shadowEnabledChange.konva",v9s);$a.prototype.on("shadowColorChange.konva shadowOpacityChange.konva shadowEnabledChange.konva",b9s);$a.prototype.on("fillPriorityChange.konva fillPatternImageChange.konva fillPatternRepeatChange.konva fillPatternScaleXChange.konva fillPatternScaleYChange.konva fillPatternOffsetXChange.konva fillPatternOffsetYChange.konva fillPatternXChange.konva fillPatternYChange.konva fillPatternRotationChange.konva",_9s);$a.prototype.on("fillPriorityChange.konva fillLinearGradientColorStopsChange.konva fillLinearGradientStartPointXChange.konva fillLinearGradientStartPointYChange.konva fillLinearGradientEndPointXChange.konva fillLinearGradientEndPointYChange.konva",w9s);$a.prototype.on("fillPriorityChange.konva fillRadialGradientColorStopsChange.konva fillRadialGradientStartPointXChange.konva fillRadialGradientStartPointYChange.konva fillRadialGradientEndPointXChange.konva fillRadialGradientEndPointYChange.konva fillRadialGradientStartRadiusChange.konva fillRadialGradientEndRadiusChange.konva",j9s);cn.addGetterSetter($a,"stroke",void 0,qPt());cn.addGetterSetter($a,"strokeWidth",2,ei());cn.addGetterSetter($a,"fillAfterStrokeEnabled",!1);cn.addGetterSetter($a,"hitStrokeWidth","auto",AWe());cn.addGetterSetter($a,"strokeHitEnabled",!0,rk());cn.addGetterSetter($a,"perfectDrawEnabled",!0,rk());cn.addGetterSetter($a,"shadowForStrokeEnabled",!0,rk());cn.addGetterSetter($a,"lineJoin");cn.addGetterSetter($a,"lineCap");cn.addGetterSetter($a,"miterLimit");cn.addGetterSetter($a,"sceneFunc");cn.addGetterSetter($a,"hitFunc");cn.addGetterSetter($a,"dash");cn.addGetterSetter($a,"dashOffset",0,ei());cn.addGetterSetter($a,"shadowColor",void 0,eF());cn.addGetterSetter($a,"shadowBlur",0,ei());cn.addGetterSetter($a,"shadowOpacity",1,ei());cn.addComponentsGetterSetter($a,"shadowOffset",["x","y"]);cn.addGetterSetter($a,"shadowOffsetX",0,ei());cn.addGetterSetter($a,"shadowOffsetY",0,ei());cn.addGetterSetter($a,"fillPatternImage");cn.addGetterSetter($a,"fill",void 0,qPt());cn.addGetterSetter($a,"fillPatternX",0,ei());cn.addGetterSetter($a,"fillPatternY",0,ei());cn.addGetterSetter($a,"fillLinearGradientColorStops");cn.addGetterSetter($a,"strokeLinearGradientColorStops");cn.addGetterSetter($a,"fillRadialGradientStartRadius",0);cn.addGetterSetter($a,"fillRadialGradientEndRadius",0);cn.addGetterSetter($a,"fillRadialGradientColorStops");cn.addGetterSetter($a,"fillPatternRepeat","repeat");cn.addGetterSetter($a,"fillEnabled",!0);cn.addGetterSetter($a,"strokeEnabled",!0);cn.addGetterSetter($a,"shadowEnabled",!0);cn.addGetterSetter($a,"dashEnabled",!0);cn.addGetterSetter($a,"strokeScaleEnabled",!0);cn.addGetterSetter($a,"fillPriority","color");cn.addComponentsGetterSetter($a,"fillPatternOffset",["x","y"]);cn.addGetterSetter($a,"fillPatternOffsetX",0,ei());cn.addGetterSetter($a,"fillPatternOffsetY",0,ei());cn.addComponentsGetterSetter($a,"fillPatternScale",["x","y"]);cn.addGetterSetter($a,"fillPatternScaleX",1,ei());cn.addGetterSetter($a,"fillPatternScaleY",1,ei());cn.addComponentsGetterSetter($a,"fillLinearGradientStartPoint",["x","y"]);cn.addComponentsGetterSetter($a,"strokeLinearGradientStartPoint",["x","y"]);cn.addGetterSetter($a,"fillLinearGradientStartPointX",0);cn.addGetterSetter($a,"strokeLinearGradientStartPointX",0);cn.addGetterSetter($a,"fillLinearGradientStartPointY",0);cn.addGetterSetter($a,"strokeLinearGradientStartPointY",0);cn.addComponentsGetterSetter($a,"fillLinearGradientEndPoint",["x","y"]);cn.addComponentsGetterSetter($a,"strokeLinearGradientEndPoint",["x","y"]);cn.addGetterSetter($a,"fillLinearGradientEndPointX",0);cn.addGetterSetter($a,"strokeLinearGradientEndPointX",0);cn.addGetterSetter($a,"fillLinearGradientEndPointY",0);cn.addGetterSetter($a,"strokeLinearGradientEndPointY",0);cn.addComponentsGetterSetter($a,"fillRadialGradientStartPoint",["x","y"]);cn.addGetterSetter($a,"fillRadialGradientStartPointX",0);cn.addGetterSetter($a,"fillRadialGradientStartPointY",0);cn.addComponentsGetterSetter($a,"fillRadialGradientEndPoint",["x","y"]);cn.addGetterSetter($a,"fillRadialGradientEndPointX",0);cn.addGetterSetter($a,"fillRadialGradientEndPointY",0);cn.addGetterSetter($a,"fillPatternRotation",0);cn.addGetterSetter($a,"fillRule",void 0,eF());cn.backCompat($a,{dashArray:"dash",getDashArray:"getDash",setDashArray:"getDash",drawFunc:"sceneFunc",getDrawFunc:"getSceneFunc",setDrawFunc:"setSceneFunc",drawHitFunc:"hitFunc",getDrawHitFunc:"getHitFunc",setDrawHitFunc:"setHitFunc"});const N9s="beforeDraw",k9s="draw",lIt=[{x:0,y:0},{x:-1,y:-1},{x:1,y:-1},{x:1,y:1},{x:-1,y:1}],S9s=lIt.length;let tF=class extends iw{constructor(t){super(t),this.canvas=new sE,this.hitCanvas=new CWe({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(N9s,{node:this}),this.clearBeforeDraw()&&i.getContext().clear(),iw.prototype.drawScene.call(this,i,n,r),this._fire(k9s,{node:this}),this}drawHit(t,n){const r=this.getLayer(),a=t||r&&r.hitCanvas;return r&&r.clearBeforeDraw()&&r.getHitCanvas().getContext().clear(),iw.prototype.drawHit.call(this,a,n),this}enableHitGraph(){return this.hitGraphEnabled(!0),this}disableHitGraph(){return this.hitGraphEnabled(!1),this}setHitGraphEnabled(t){tr.warn("hitGraphEnabled method is deprecated. Please use layer.listening() instead."),this.listening(t)}getHitGraphEnabled(t){return tr.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 tr.releaseCanvas(this.getNativeCanvasElement(),this.getHitCanvas()._canvas),super.destroy()}};tF.prototype.nodeType="Layer";Wp(tF);cn.addGetterSetter(tF,"imageSmoothingEnabled",!0);cn.addGetterSetter(tF,"clearBeforeDraw",!0);cn.addGetterSetter(tF,"hitGraphEnabled",!0,rk());class TWe extends tF{constructor(t){super(t),this.listening(!1),tr.warn('Konva.Fast layer is deprecated. Please use "new Konva.Layer({ listening: false })" instead.')}}TWe.prototype.nodeType="FastLayer";Wp(TWe);let uU=class extends iw{_validateAdd(t){const n=t.getType();n!=="Group"&&n!=="Shape"&&tr.throw("You may only add groups and shapes to groups.")}};uU.prototype.nodeType="Group";Wp(uU);const pIe=function(){return F8.performance&&F8.performance.now?function(){return F8.performance.now()}:function(){return new Date().getTime()}}();class Aj{constructor(t,n){this.id=Aj.animIdCounter++,this.frame={time:0,timeDiff:0,lastTime:pIe(),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=kdt,this._startTime=this.getTimer()-this._time,this.onEnterFrame(),this.fire("onPlay")}reverse(){this.state=Sdt,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===kdt?this.setTime(t):this.state===Sdt&&this.setTime(this.duration-t)}pause(){this.state=A9s,this.fire("onPause")}getTimer(){return new Date().getTime()}}class Hh{constructor(t){const n=this,r=t.node,a=r._id,i=t.easing||RY.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=E9s++;const d=r.getLayer()||(r instanceof ii.Stage?r.getLayers():null);d||tr.error("Tween constructor have `node` that is not in a layer. Please add node into layer first."),this.anim=new Aj(function(){n.tween.onEnterFrame()},d),this.tween=new T9s(c,function(u){n._tweenFunc(u)},i,0,1,o*1e3,l),this._addListeners(),Hh.attrs[a]||(Hh.attrs[a]={}),Hh.attrs[a][this._id]||(Hh.attrs[a][this._id]={}),Hh.tweens[a]||(Hh.tweens[a]={});for(c in t)C9s[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=Hh.tweens[a][t];u&&delete Hh.attrs[a][u][t];let h=r.getAttr(t);if(tr._isArray(n))if(i=[],l=Math.max(n.length,h.length),t==="points"&&n.length!==h.length&&(n.length>h.length?(c=h,h=tr._prepareArrayForTween(h,n,r.closed())):(o=n,n=tr._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=Hh.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=Hh.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=Hh.tweens[t];this.pause(),this.anim&&this.anim.stop();for(const a in r)delete Hh.tweens[t][a];delete Hh.attrs[t][n],Hh.tweens[t]&&(Object.keys(Hh.tweens[t]).length===0&&delete Hh.tweens[t],Object.keys(Hh.attrs[t]).length===0&&delete Hh.attrs[t])}}Hh.attrs={};Hh.tweens={};ci.prototype.to=function(s){const t=s.onFinish;s.node=this,s.onFinish=function(){this.destroy(),t&&t()},new Hh(s).play()};const RY={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}}}NC.prototype._centroid=!0;NC.prototype.className="Arc";NC.prototype._attrsAffectingSize=["innerRadius","outerRadius","angle","clockwise"];Wp(NC);cn.addGetterSetter(NC,"innerRadius",0,ei());cn.addGetterSetter(NC,"outerRadius",0,ei());cn.addGetterSetter(NC,"angle",0,ei());cn.addGetterSetter(NC,"clockwise",!1,rk());function r9e(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),x=r+u*(i-t);return[h,m,p,x]}function Adt(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 kC=class extends $a{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*L9s[20][o]+l,r+=P9s[20][o]*D9s(s,t,a);return l*r},Tdt=(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,x=m*m+p>0?Math.sqrt(m*m+p):0,g=u*u+p>0?Math.sqrt(u*u+p):0,y=u+Math.sqrt(u*u+p)!==0?p*Math.log(Math.abs((m+x)/(u+g))):0;return Math.sqrt(o)/2*(m*x-u*g+y)};function D9s(s,t,n){const r=a9e(1,n,s),a=a9e(1,n,t),i=r*r+a*a;return Math.sqrt(i)}const a9e=(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+=I9s[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 Ej=class rb extends $a{constructor(t){super(t),this.dataArray=[],this.pathLength=0,this._readDataAttribute(),this.on("dataChange.konva",function(){this._readDataAttribute()})}_readDataAttribute(){this.dataArray=rb.parsePathData(this.data()),this.pathLength=rb.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,b=d>u?u/d:1;t.translate(o,c),t.rotate(p),t.scale(y,b),t.arc(0,0,g,h,h+m,1-x),t.scale(1/y,1/b),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 x=rb.getPointOnEllipticalArc(c.points[0],c.points[1],c.points[2],c.points[3],p,0);t.push(x.x,x.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 rb.getPointOnLine(t,l.start.x,l.start.y,o[0],o[1]);case"C":return rb.getPointOnCubicBezier(Mdt(t,rb.getPathLength(n),g=>Edt([l.start.x,o[0],o[2],o[4]],[l.start.y,o[1],o[3],o[5]],g)),l.start.x,l.start.y,o[0],o[1],o[2],o[3],o[4],o[5]);case"Q":return rb.getPointOnQuadraticBezier(Mdt(t,rb.getPathLength(n),g=>Tdt([l.start.x,o[0],o[2]],[l.start.y,o[1],o[3]],g)),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 x=o[4];return x+=m*t/l.pathLength,rb.getPointOnEllipticalArc(c,d,u,h,x,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&&(g+=2,g>=7&&(g-=7));continue}if(g>=0){if(g===3){if(/^[01]{2}\d+(?:\.\d+)?$/.test(v)){x.push(parseInt(v[0],10)),x.push(parseInt(v[1],10)),x.push(parseFloat(v.slice(2))),g+=3,g>=7&&(g-=7);continue}if(v==="11"||v==="10"||v==="01"){x.push(parseInt(v[0],10)),x.push(parseInt(v[1],10)),g+=2,g>=7&&(g-=7);continue}if(v==="0"||v==="1"){x.push(parseInt(v,10)),g+=1,g>=7&&(g-=7);continue}}else if(g===4){if(/^[01]\d+(?:\.\d+)?$/.test(v)){x.push(parseInt(v[0],10)),x.push(parseFloat(v.slice(1))),g+=2,g>=7&&(g-=7);continue}if(v==="0"||v==="1"){x.push(parseInt(v,10)),g+=1,g>=7&&(g-=7);continue}}const N=parseFloat(v);isNaN(N)?x.push(0):x.push(N),g+=1,g>=7&&(g-=7)}else{const N=parseFloat(v);isNaN(N)?x.push(0):x.push(N)}}for(;x.length>0&&!isNaN(x[0]);){let y="",b=[];const v=o,N=c;let C,A,T,P,M,I,D,B,q,W;switch(p){case"l":o+=x.shift(),c+=x.shift(),y="L",b.push(o,c);break;case"L":o=x.shift(),c=x.shift(),b.push(o,c);break;case"m":const V=x.shift(),K=x.shift();if(o+=V,c+=K,y="M",i.length>2&&i[i.length-1].command==="z"){for(let Q=i.length-2;Q>=0;Q--)if(i[Q].command==="M"){o=i[Q].points[0]+V,c=i[Q].points[1]+K;break}}b.push(o,c),p="l";break;case"M":o=x.shift(),c=x.shift(),y="M",b.push(o,c),p="L";break;case"h":o+=x.shift(),y="L",b.push(o,c);break;case"H":o=x.shift(),y="L",b.push(o,c);break;case"v":c+=x.shift(),y="L",b.push(o,c);break;case"V":c=x.shift(),y="L",b.push(o,c);break;case"C":b.push(x.shift(),x.shift(),x.shift(),x.shift()),o=x.shift(),c=x.shift(),b.push(o,c);break;case"c":b.push(o+x.shift(),c+x.shift(),o+x.shift(),c+x.shift()),o+=x.shift(),c+=x.shift(),y="C",b.push(o,c);break;case"S":A=o,T=c,C=i[i.length-1],C.command==="C"&&(A=o+(o-C.points[2]),T=c+(c-C.points[3])),b.push(A,T,x.shift(),x.shift()),o=x.shift(),c=x.shift(),y="C",b.push(o,c);break;case"s":A=o,T=c,C=i[i.length-1],C.command==="C"&&(A=o+(o-C.points[2]),T=c+(c-C.points[3])),b.push(A,T,o+x.shift(),c+x.shift()),o+=x.shift(),c+=x.shift(),y="C",b.push(o,c);break;case"Q":b.push(x.shift(),x.shift()),o=x.shift(),c=x.shift(),b.push(o,c);break;case"q":b.push(o+x.shift(),c+x.shift()),o+=x.shift(),c+=x.shift(),y="Q",b.push(o,c);break;case"T":A=o,T=c,C=i[i.length-1],C.command==="Q"&&(A=o+(o-C.points[0]),T=c+(c-C.points[1])),o=x.shift(),c=x.shift(),y="Q",b.push(A,T,o,c);break;case"t":A=o,T=c,C=i[i.length-1],C.command==="Q"&&(A=o+(o-C.points[0]),T=c+(c-C.points[1])),o+=x.shift(),c+=x.shift(),y="Q",b.push(A,T,o,c);break;case"A":P=x.shift(),M=x.shift(),I=x.shift(),D=x.shift(),B=x.shift(),q=o,W=c,o=x.shift(),c=x.shift(),y="A",b=this.convertEndpointToCenterParameterization(q,W,o,c,D,B,P,M,I);break;case"a":P=x.shift(),M=x.shift(),I=x.shift(),D=x.shift(),B=x.shift(),q=o,W=c,o+=x.shift(),c+=x.shift(),y="A",b=this.convertEndpointToCenterParameterization(q,W,o,c,D,B,P,M,I);break}i.push({command:y||p,points:b,start:{x:v,y:N},pathLength:this.calcLength(v,N,y||p,b)})}(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=rb;switch(r){case"L":return d.getLineLength(t,n,a[0],a[1]);case"C":return Edt([t,a[0],a[2],a[4]],[n,a[1],a[3],a[5]],1);case"Q":return Tdt([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 x=Math.sqrt((o*o*(c*c)-o*o*(m*m)-c*c*(h*h))/(o*o*(m*m)+c*c*(h*h)));i===l&&(x*=-1),isNaN(x)&&(x=0);const g=x*o*m/c,y=x*-c*h/o,b=(t+r)/2+Math.cos(u)*g-Math.sin(u)*y,v=(n+a)/2+Math.sin(u)*g+Math.cos(u)*y,N=function(D){return Math.sqrt(D[0]*D[0]+D[1]*D[1])},C=function(D,B){return(D[0]*B[0]+D[1]*B[1])/(N(D)*N(B))},A=function(D,B){return(D[0]*B[1]=1&&(I=0),l===0&&I>0&&(I=I-2*Math.PI),l===1&&I<0&&(I=I+2*Math.PI),[b,v,o,c,T,I,u,l]}};Ej.prototype.className="Path";Ej.prototype._attrsAffectingSize=["data"];Wp(Ej);cn.addGetterSetter(Ej,"data");class sF extends kC{_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=Ej.calcLength(a[a.length-4],a[a.length-3],"C",m),x=Ej.getPointOnQuadraticBezier(Math.min(1,1-l/p),m[0],m[1],m[2],m[3],m[4],m[5]);c=r[o-2]-x.x,d=r[o-1]-x.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}}}sF.prototype.className="Arrow";Wp(sF);cn.addGetterSetter(sF,"pointerLength",10,ei());cn.addGetterSetter(sF,"pointerWidth",10,ei());cn.addGetterSetter(sF,"pointerAtBeginning",!1);cn.addGetterSetter(sF,"pointerAtEnding",!0);class zq extends $a{_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)}}zq.prototype._centroid=!0;zq.prototype.className="Circle";zq.prototype._attrsAffectingSize=["radius"];Wp(zq);cn.addGetterSetter(zq,"radius",0,ei());class B6 extends $a{_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)}}B6.prototype.className="Ellipse";B6.prototype._centroid=!0;B6.prototype._attrsAffectingSize=["radiusX","radiusY"];Wp(B6);cn.addComponentsGetterSetter(B6,"radius",["x","y"]);cn.addGetterSetter(B6,"radiusX",0,ei());cn.addGetterSetter(B6,"radiusY",0,ei());let ak=class cIt extends $a{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?tr.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?tr.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=tr.createImageElement();a.onload=function(){const i=new cIt({image:a});n(i)},a.onerror=r,a.crossOrigin="Anonymous",a.src=t}};ak.prototype.className="Image";ak.prototype._attrsAffectingSize=["image"];Wp(ak);cn.addGetterSetter(ak,"cornerRadius",0,SAe(4));cn.addGetterSetter(ak,"image");cn.addComponentsGetterSetter(ak,"crop",["x","y","width","height"]);cn.addGetterSetter(ak,"cropX",0,ei());cn.addGetterSetter(ak,"cropY",0,ei());cn.addGetterSetter(ak,"cropWidth",0,ei());cn.addGetterSetter(ak,"cropHeight",0,ei());const dIt=["fontFamily","fontSize","fontStyle","padding","lineHeight","text","width","height","pointerDirection","pointerWidth","pointerHeight"],R9s="Change.konva",O9s="none",i9e="up",o9e="right",l9e="down",c9e="left",F9s=dIt.length;let MWe=class extends uU{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)}}$6.prototype.className="RegularPolygon";$6.prototype._centroid=!0;$6.prototype._attrsAffectingSize=["radius"];Wp($6);cn.addGetterSetter($6,"radius",0,ei());cn.addGetterSetter($6,"sides",0,ei());cn.addGetterSetter($6,"cornerRadius",0,SAe(4));const Ldt=Math.PI*2;let rF=class extends $a{_sceneFunc(t){t.beginPath(),t.arc(0,0,this.innerRadius(),0,Ldt,!1),t.moveTo(this.outerRadius(),0),t.arc(0,0,this.outerRadius(),Ldt,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)}};rF.prototype.className="Ring";rF.prototype._centroid=!0;rF.prototype._attrsAffectingSize=["innerRadius","outerRadius"];Wp(rF);cn.addGetterSetter(rF,"innerRadius",0,ei());cn.addGetterSetter(rF,"outerRadius",0,ei());class D5 extends $a{constructor(t){super(t),this._updated=!0,this.anim=new Aj(()=>{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 C7="auto",z9s="center",uIt="inherit",hG="justify",B9s="Change.konva",hIt="2d",Pdt="-",mIt="left",$9s="text",U9s="Text",q9s="top",V9s="bottom",Idt="middle",pIt="normal",H9s="px ",dre=" ",G9s="right",Ddt="rtl",W9s="word",K9s="char",Rdt="none",fIe="…",fIt=["direction","fontFamily","fontSize","fontStyle","fontVariant","padding","align","verticalAlign","lineHeight","text","width","height","wrap","ellipsis","letterSpacing"],Y9s=fIt.length;let mG=null;function Z9s(){if(mG!==null)return mG;mG=!1;try{const s=document.createElement("canvas");s.width=10,s.height=10;const t=s.getContext(hIt);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){mG=!0;break}}}catch{}return mG}function X9s(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 ure;function xIe(){return ure||(ure=tr.createCanvasElement().getContext(hIt),ure)}function Q9s(s){s.fillText(this._partialText,this._partialTextX,this._partialTextY)}function J9s(s){s.setAttr("miterLimit",2),s.strokeText(this._partialText,this._partialTextX,this._partialTextY)}function ezs(s){return s=s||{},!s.fillLinearGradientColorStops&&!s.fillRadialGradientColorStops&&!s.fillPatternImage&&(s.fill=s.fill||"black"),s}let tm=class extends $a{constructor(t){super(ezs(t)),this._partialTextX=0,this._partialTextY=0;for(let n=0;nle+EA(he.text).length,0),ee=J+ne;g({char:ce,index:ee,x:M,y:T+I,lineIndex:A,column:J,isLastInLine:W,width:this.measureSize(ce).width,context:t})}t.fillStrokeShape(this),g&&t.restore(),M+=this.measureSize(ce).width+x}}else x!==0&&t.setAttr("letterSpacing",`${x}px`),this._partialTextX=M,this._partialTextY=T+I,this._partialText=B,t.fillStrokeShape(this);if(C){t.save(),t.beginPath();const K=ii.legacyTextRendering?0:-Math.round(o/4),Q=V;t.moveTo(Q,T+I+K);const J=m===hG&&!W?p-l*2:q;t.lineTo(Q+Math.round(J),T+I+K),t.lineWidth=o/15;const ce=this._getLinearGradient();t.strokeStyle=ce||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=tr._isString(t)?t:t==null?"":t+"";return this._setAttr($9s,n),this}getWidth(){return this.attrs.width===C7||this.attrs.width===void 0?this.getTextWidth()+this.padding()*2:this.attrs.width}getHeight(){return this.attrs.height===C7||this.attrs.height===void 0?this.fontSize()*this.textArr.length*this.lineHeight()+this.padding()*2:this.attrs.height}getTextWidth(){return this.textWidth}getTextHeight(){return tr.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=xIe(),x=this.fontSize(),g;p.save(),p.font=this._getContextFont(),g=p.measureText(t),p.restore();const y=x/100;return{actualBoundingBoxAscent:(n=g.actualBoundingBoxAscent)!==null&&n!==void 0?n:71.58203125*y,actualBoundingBoxDescent:(r=g.actualBoundingBoxDescent)!==null&&r!==void 0?r:0,actualBoundingBoxLeft:(a=g.actualBoundingBoxLeft)!==null&&a!==void 0?a:-7.421875*y,actualBoundingBoxRight:(i=g.actualBoundingBoxRight)!==null&&i!==void 0?i:75.732421875*y,alphabeticBaseline:(l=g.alphabeticBaseline)!==null&&l!==void 0?l:0,emHeightAscent:(o=g.emHeightAscent)!==null&&o!==void 0?o:100*y,emHeightDescent:(c=g.emHeightDescent)!==null&&c!==void 0?c:-20*y,fontBoundingBoxAscent:(d=g.fontBoundingBoxAscent)!==null&&d!==void 0?d:91*y,fontBoundingBoxDescent:(u=g.fontBoundingBoxDescent)!==null&&u!==void 0?u:21*y,hangingBaseline:(h=g.hangingBaseline)!==null&&h!==void 0?h:72.80000305175781*y,ideographicBaseline:(m=g.ideographicBaseline)!==null&&m!==void 0?m:-21*y,width:g.width,height:x}}_getContextFont(){return this.fontStyle()+dre+this.fontVariant()+dre+(this.fontSize()+H9s)+X9s(this.fontFamily())}_addTextLine(t){this.align()===hG&&(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 xIe().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!==C7&&i!==void 0,c=l!==C7&&l!==void 0,d=this.padding(),u=i-d*2,h=l-d*2,m=0,p=this.wrap(),x=p!==Rdt,g=p!==K9s&&x,y=this.ellipsis();this.textArr=[],xIe().font=this._getContextFont();const b=y?this._getTextWidth(fIe):0;for(let v=0,N=t.length;vu)for(;C.length>0;){let T=0,P=EA(C).length,M="",I=0;for(;T>>1,B=EA(C),q=B.slice(0,D+1).join(""),W=this._getTextWidth(q);(y&&c&&m+a>h?W+b:W)<=u?(T=D+1,M=q,I=W):P=D}if(M){if(g){const q=EA(C),W=EA(M),V=q[W.length],K=V===dre||V===Pdt;let Q;if(K&&I<=u)Q=W.length;else{const J=W.lastIndexOf(dre),ce=W.lastIndexOf(Pdt);Q=Math.max(J,ce)+1}Q>0&&(T=Q,M=q.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(C=EA(C).slice(T).join("").trimLeft(),C.length>0&&(A=this._getTextWidth(C),A<=u)){this._addTextLine(C),m+=a,r=Math.max(r,A);break}}else break}else this._addTextLine(C),m+=a,r=Math.max(r,A),this._shouldHandleEllipsis(m)&&vh)break}this.textHeight=n,this.textWidth=r}_shouldHandleEllipsis(t){const n=+this.fontSize(),r=this.lineHeight()*n,a=this.attrs.height,i=a!==C7&&a!==void 0,l=this.padding(),o=a-l*2;return!(this.wrap()!==Rdt)||i&&t+r>o}_tryToAddEllipsisToLastLine(){const t=this.attrs.width,n=t!==C7&&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+fIe)n?null:Ej.getPointAtLengthOfDataArray(t,this.dataArray)}_readDataAttribute(){this.dataArray=Ej.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&&b-this.pathLength<=d?this.pathLength:b);if(!v)return;const N=Ej.getLineLength(x.x,x.y,v.x,v.y);let C=0;if(c)try{C=c(n[p-1].char,g)*this.fontSize()}catch{C=0}x.x+=C,v.x+=C,this.textWidth+=C;const A=Ej.getPointOnLine(C+N/2,x.x,x.y,v.x,v.y),T=Math.atan2(v.y-x.y,v.x-x.x);this.glyphInfo.push({transposeX:A.x,transposeY:A.y,text:t[p],rotation:T,p0:x,p1:v,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+`.${vIt}`).join(" "),Odt="nodesRect",nzs=["widthChange","heightChange","scaleXChange","scaleYChange","skewXChange","skewYChange","rotationChange","offsetXChange","offsetYChange","transformsEnabledChange","strokeWidthChange","draggableChange"],rzs={"top-left":-45,"top-center":0,"top-right":45,"middle-right":-90,"middle-left":90,"bottom-left":-135,"bottom-center":180,"bottom-right":135},azs="ontouchstart"in ii._global;function izs(s,t,n){if(s==="rotater")return n;t+=tr.degToRad(rzs[s]||0);const r=(tr.radToDeg(t)%360+360)%360;return tr._inRange(r,315+22.5,360)||tr._inRange(r,0,22.5)?"ns-resize":tr._inRange(r,45-22.5,45+22.5)?"nesw-resize":tr._inRange(r,90-22.5,90+22.5)?"ew-resize":tr._inRange(r,135-22.5,135+22.5)?"nwse-resize":tr._inRange(r,180-22.5,180+22.5)?"ns-resize":tr._inRange(r,225-22.5,225+22.5)?"nesw-resize":tr._inRange(r,270-22.5,270+22.5)?"ew-resize":tr._inRange(r,315-22.5,315+22.5)?"nwse-resize":(tr.error("Transformer has unknown angle for cursor detection: "+r),"pointer")}const ZSe=["top-left","top-center","top-right","middle-right","middle-left","bottom-left","bottom-center","bottom-right"],Fdt=1e8;function ozs(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 bIt(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 lzs(s,t){const n=ozs(s);return bIt(s,t,n)}function czs(s,t,n){let r=t;for(let a=0;aa.isAncestorOf(this)?(tr.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(nzs.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(Odt),this._clearCache("transform"),this._clearSelfAndDescendantCache("absoluteTransform")}_getNodeRect(){return this._getCache(Odt,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=(ii.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 bIt(u,-ii.getAngle(n),{x:0,y:0})}__getNodeRect(){if(!this.getNode())return{x:-Fdt,y:-Fdt,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 x=m.point(p);n.push(x)})});const r=new W_;r.rotate(-ii.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:ii.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(),ZSe.forEach(t=>{this._createAnchor(t)}),this._createAnchor("rotater"),this._elementsCreated=!0}_createAnchor(t){const n=new Pee({stroke:"rgb(0, 161, 255)",fill:"white",strokeWidth:1,name:t+" _anchor",dragDistance:0,draggable:!0,hitStrokeWidth:azs?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=ii.getAngle(this.rotation()),i=this.rotateAnchorCursor(),l=izs(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 $a({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=tr.degToRad(c),h=Math.sin(u),m=-Math.cos(u),p=l/2,x=o/2;let g=1/0;m<0?g=Math.min(g,-x/m):m>0&&(g=Math.min(g,(o-x)/m)),h<0?g=Math.min(g,-p/h):h>0&&(g=Math.min(g,(l-p)/h));const y=p+h*g,b=x+m*g,v=tr._sign(o),N=y+h*d*v,C=b+m*d*v;n.moveTo(y,b),n.lineTo(N,C)}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},d9e++,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 v=this._getNodeRect();n=i.x()-v.width/2,r=-i.y()+v.height/2;const N=ii.getAngle(this.rotateAnchorAngle());let C=Math.atan2(-r,n)+Math.PI/2-N;v.height<0&&(C-=Math.PI);const T=ii.getAngle(this.rotation())+C,P=ii.getAngle(this.rotationSnapTolerance()),I=czs(this.rotationSnaps(),T,P)-v.rotation,D=lzs(v,I);this._fitNodesInto(D,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 v=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(v.x-i.x(),2)+Math.pow(v.y-i.y(),2));const N=this.findOne(".top-left").x()>v.x?-1:1,C=this.findOne(".top-left").y()>v.y?-1:1;n=a*this.cos*N,r=a*this.sin*C,this.findOne(".top-left").x(v.x-n),this.findOne(".top-left").y(v.y-r)}}else if(this._movingAnchorName==="top-center")this.findOne(".top-left").y(i.y());else if(this._movingAnchorName==="top-right"){if(m){const v=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()-v.x,2)+Math.pow(v.y-i.y(),2));const N=this.findOne(".top-right").x()v.y?-1:1;n=a*this.cos*N,r=a*this.sin*C,this.findOne(".top-right").x(v.x+n),this.findOne(".top-right").y(v.y-r)}var x=i.position();this.findOne(".top-left").y(x.y),this.findOne(".bottom-right").x(x.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 v=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(v.x-i.x(),2)+Math.pow(i.y()-v.y,2));const N=v.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(tr._inRange(t.width,-this.padding()*2-a,a)){this.update();return}if(tr._inRange(t.height,-this.padding()*2-a,a)){this.update();return}const i=new W_;if(i.rotate(ii.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:tr.warn("boundBoxFunc returned falsy. You should return new bound rect from it!")}const l=1e7,o=new W_;o.translate(r.x,r.y),o.rotate(r.rotation),o.scale(r.width/l,r.height/l);const c=new W_,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 x=m.getParent().getAbsoluteTransform(),g=m.getTransform().copy();g.translate(m.offsetX(),m.offsetY());const y=new W_;y.multiply(x.copy().invert()).multiply(h).multiply(x).multiply(g);const b=y.decompose();m.setAttrs(b),(p=m.getLayer())===null||p===void 0||p.batchDraw()}),this.rotation(tr._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(tr._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=tr.degToRad(u),p=Math.sin(m),x=-Math.cos(m),g=r/2,y=a/2;let b=1/0;x<0?b=Math.min(b,-y/x):x>0&&(b=Math.min(b,(a-y)/x)),p<0?b=Math.min(b,-g/p):p>0&&(b=Math.min(b,(r-g)/p));const v=g+p*b,N=y+x*b,C=tr._sign(a);this._batchChangeChild(".rotater",{x:v+p*h*C,y:N+x*h*C-o*x,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=""),uU.prototype.destroy.call(this),this.detach(),this._removeEvents(),this}add(...t){return this._elementsCreated?(tr.error("You cannot add external nodes to the Transformer. Use tr.nodes([node]) instead."),this):super.add(...t)}toObject(){return ci.prototype.toObject.call(this)}clone(t){return ci.prototype.clone.call(this,t)}getClientRect(){return this.nodes().length>0?super.getClientRect():{x:0,y:0,width:0,height:0}}};id.isTransforming=()=>d9e>0;function dzs(s){return s instanceof Array||tr.warn("enabledAnchors value should be an array"),s instanceof Array&&s.forEach(function(t){ZSe.indexOf(t)===-1&&tr.warn("Unknown anchor name: "+t+". Available names are: "+ZSe.join(", "))}),s||[]}id.prototype.className="Transformer";Wp(id);cn.addGetterSetter(id,"enabledAnchors",ZSe,dzs);cn.addGetterSetter(id,"flipEnabled",!0,rk());cn.addGetterSetter(id,"resizeEnabled",!0);cn.addGetterSetter(id,"anchorSize",10,ei());cn.addGetterSetter(id,"rotateEnabled",!0);cn.addGetterSetter(id,"rotateLineVisible",!0);cn.addGetterSetter(id,"rotationSnaps",[]);cn.addGetterSetter(id,"rotateAnchorOffset",50,ei());cn.addGetterSetter(id,"rotateAnchorAngle",0,ei());cn.addGetterSetter(id,"rotateAnchorCursor","crosshair");cn.addGetterSetter(id,"rotationSnapTolerance",5,ei());cn.addGetterSetter(id,"borderEnabled",!0);cn.addGetterSetter(id,"anchorStroke","rgb(0, 161, 255)");cn.addGetterSetter(id,"anchorStrokeWidth",1,ei());cn.addGetterSetter(id,"anchorFill","white");cn.addGetterSetter(id,"anchorCornerRadius",0,ei());cn.addGetterSetter(id,"borderStroke","rgb(0, 161, 255)");cn.addGetterSetter(id,"borderStrokeWidth",1,ei());cn.addGetterSetter(id,"borderDash");cn.addGetterSetter(id,"keepRatio",!0);cn.addGetterSetter(id,"shiftBehavior","default");cn.addGetterSetter(id,"centeredScaling",!1);cn.addGetterSetter(id,"ignoreStroke",!1);cn.addGetterSetter(id,"padding",0,ei());cn.addGetterSetter(id,"nodes");cn.addGetterSetter(id,"node");cn.addGetterSetter(id,"boundBoxFunc");cn.addGetterSetter(id,"anchorDragBoundFunc");cn.addGetterSetter(id,"anchorStyleFunc");cn.addGetterSetter(id,"shouldOverdrawWholeArea",!1);cn.addGetterSetter(id,"useSingleNodeRotation",!0);cn.backCompat(id,{lineEnabled:"borderEnabled",rotateHandlerOffset:"rotateAnchorOffset",enabledHandlers:"enabledAnchors"});class SC extends $a{_sceneFunc(t){t.beginPath(),t.arc(0,0,this.radius(),0,ii.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)}}SC.prototype.className="Wedge";SC.prototype._centroid=!0;SC.prototype._attrsAffectingSize=["radius"];Wp(SC);cn.addGetterSetter(SC,"radius",0,ei());cn.addGetterSetter(SC,"angle",0,ei());cn.addGetterSetter(SC,"clockwise",!1);cn.backCompat(SC,{angleDeg:"angle",getAngleDeg:"getAngle",setAngleDeg:"setAngle"});function zdt(){this.r=0,this.g=0,this.b=0,this.a=0,this.next=null}const uzs=[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],hzs=[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 mzs(s,t){const n=s.data,r=s.width,a=s.height;let i,l,o,c,d,u,h,m,p,x,g,y,b,v,N,C,A,T,P,M;const I=t+t+1,D=r-1,B=a-1,q=t+1,W=q*(q+1)/2,V=new zdt,K=uzs[t],Q=hzs[t];let J=null,ce=V,ue=null,ne=null;for(let ee=1;ee>Q,P!==0?(P=255/P,n[l]=(c*K>>Q)*P,n[l+1]=(d*K>>Q)*P,n[l+2]=(u*K>>Q)*P):n[l]=n[l+1]=n[l+2]=0,c-=m,d-=p,u-=x,h-=g,m-=ue.r,p-=ue.g,x-=ue.b,g-=ue.a,i=o+((i=le+t+1)>Q,P>0?(P=255/P,n[i]=(c*K>>Q)*P,n[i+1]=(d*K>>Q)*P,n[i+2]=(u*K>>Q)*P):n[i]=n[i+1]=n[i+2]=0,c-=m,d-=p,u-=x,h-=g,m-=ue.r,p-=ue.g,x-=ue.b,g-=ue.a,i=ee+((i=he+q)0&&mzs(t,n)};cn.addGetterSetter(ci,"blurRadius",0,ei(),cn.afterSetFilter);const fzs=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};cn.addGetterSetter(ci,"contrast",0,ei(),cn.afterSetFilter);const yzs=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)),x=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,b=!!((d=(c=this.embossBlend)===null||c===void 0?void 0:c.call(this))!==null&&d!==void 0&&d),v=p*10,N=x*255,C=y*Math.PI/180,A=Math.cos(C),T=Math.sin(C),P=128/1020*v,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,x,g,y,b,v;if(m>0)p=a+m*(255-a),x=r-m*(r-0),g=o+m*(255-o),y=l-m*(l-0),b=u+m*(255-u),v=d-m*(d-0);else{const N=(a+r)*.5;p=a+m*(a-N),x=r+m*(r-N);const C=(o+l)*.5;g=o+m*(o-C),y=l+m*(l-C);const A=(u+d)*.5;b=u+m*(u-A),v=d+m*(d-A)}for(let N=0;Nd?m:d;const p=l,x=i,g=360/x*Math.PI/180;for(let y=0;yd?m:d;const p=l,x=i,g=0;let y,b;for(u=0;ut&&(C=N,A=0,T=-1),a=0;a=0&&p=0&&x=0&&p=0&&x=255*4?255:0}return l}function Lzs(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&&x=n))for(let N=g;N=r)continue;const C=(n*N+v)*4;d+=l[C+0],u+=l[C+1],h+=l[C+2],m+=l[C+3],b+=1}d=d/b,u=u/b,h=h/b,m=m/b;for(let v=p;v=n))for(let N=g;N=r)continue;const C=(n*N+v)*4;l[C+0]=d,l[C+1]=u,l[C+2]=h,l[C+3]=m}}};cn.addGetterSetter(ci,"pixelSize",8,ei(),cn.afterSetFilter);const Rzs=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)});cn.addGetterSetter(ci,"green",0,function(s){return this._filterUpToDate=!1,s>255?255:s<0?0:Math.round(s)});cn.addGetterSetter(ci,"blue",0,UPt,cn.afterSetFilter);const Fzs=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)});cn.addGetterSetter(ci,"green",0,function(s){return this._filterUpToDate=!1,s>255?255:s<0?0:Math.round(s)});cn.addGetterSetter(ci,"blue",0,UPt,cn.afterSetFilter);cn.addGetterSetter(ci,"alpha",1,function(s){return this._filterUpToDate=!1,s>1?1:s<0?0:s});const zzs=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},$zs=function(s){const t=this.threshold()*255,n=s.data,r=n.length;for(let a=0;aYn||ct[Fs]!==Et[Yn]){var Pr=` `+ct[Fs].replace(" at new "," at ");return te.displayName&&Pr.includes("")&&(Pr=Pr.replace("",te.displayName)),Pr}while(1<=Fs&&0<=Yn);break}}}finally{ta=!1,Error.prepareStackTrace=Pe}return(te=te?te.displayName||te.name:"")?Or(te):""}var va=Object.prototype.hasOwnProperty,hi=[],el=-1;function Oo(te){return{current:te}}function Ei(te){0>el||(te.current=hi[el],hi[el]=null,el--)}function Wa(te,ie){el++,hi[el]=te.current,te.current=ie}var wo={},Io=Oo(wo),is=Oo(!1),zr=wo;function Sa(te,ie){var Pe=te.type.contextTypes;if(!Pe)return wo;var st=te.stateNode;if(st&&st.__reactInternalMemoizedUnmaskedChildContext===ie)return st.__reactInternalMemoizedMaskedChildContext;var ct={},Et;for(Et in Pe)ct[Et]=ie[Et];return st&&(te=te.stateNode,te.__reactInternalMemoizedUnmaskedChildContext=ie,te.__reactInternalMemoizedMaskedChildContext=ct),ct}function Kn(te){return te=te.childContextTypes,te!=null}function wn(){Ei(is),Ei(Io)}function Ur(te,ie,Pe){if(Io.current!==wo)throw Error(l(168));Wa(Io,ie),Wa(is,Pe)}function ca(te,ie,Pe){var st=te.stateNode;if(ie=ie.childContextTypes,typeof st.getChildContext!="function")return Pe;st=st.getChildContext();for(var ct in st)if(!(ct in ie))throw Error(l(108,M(te)||"Unknown",ct));return i({},Pe,st)}function yo(te){return te=(te=te.stateNode)&&te.__reactInternalMemoizedMergedChildContext||wo,zr=Io.current,Wa(Io,te),Wa(is,is.current),!0}function vo(te,ie,Pe){var st=te.stateNode;if(!st)throw Error(l(169));Pe?(te=ca(te,ie,zr),st.__reactInternalMemoizedMergedChildContext=te,Ei(is),Ei(Io),Wa(Io,te)):Ei(is),Wa(is,Pe)}var Vo=Math.clz32?Math.clz32:bo,Xc=Math.log,uo=Math.LN2;function bo(te){return te>>>=0,te===0?32:31-(Xc(te)/uo|0)|0}var od=64,Ju=4194304;function Ld(te){switch(te&-te){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 te&4194240;case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:return te&130023424;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 1073741824;default:return te}}function bd(te,ie){var Pe=te.pendingLanes;if(Pe===0)return 0;var st=0,ct=te.suspendedLanes,Et=te.pingedLanes,Fs=Pe&268435455;if(Fs!==0){var Yn=Fs&~ct;Yn!==0?st=Ld(Yn):(Et&=Fs,Et!==0&&(st=Ld(Et)))}else Fs=Pe&~ct,Fs!==0?st=Ld(Fs):Et!==0&&(st=Ld(Et));if(st===0)return 0;if(ie!==0&&ie!==st&&!(ie&ct)&&(ct=st&-st,Et=ie&-ie,ct>=Et||ct===16&&(Et&4194240)!==0))return ie;if(st&4&&(st|=Pe&16),ie=te.entangledLanes,ie!==0)for(te=te.entanglements,ie&=st;0Pe;Pe++)ie.push(te);return ie}function Lf(te,ie,Pe){te.pendingLanes|=ie,ie!==536870912&&(te.suspendedLanes=0,te.pingedLanes=0),te=te.eventTimes,ie=31-Vo(ie),te[ie]=Pe}function eh(te,ie){var Pe=te.pendingLanes&~ie;te.pendingLanes=ie,te.suspendedLanes=0,te.pingedLanes=0,te.expiredLanes&=ie,te.mutableReadLanes&=ie,te.entangledLanes&=ie,ie=te.entanglements;var st=te.eventTimes;for(te=te.expirationTimes;0>=Fs,ct-=Fs,_d=1<<32-Vo(ie)+ct|Pe<xl?(zm=so,so=null):zm=so.sibling;var zc=yi(Er,so,zn[xl],Ci);if(zc===null){so===null&&(so=zm);break}te&&so&&zc.alternate===null&&ie(Er,so),Nn=Et(zc,Nn,xl),Wo===null?zi=zc:Wo.sibling=zc,Wo=zc,so=zm}if(xl===zn.length)return Pe(Er,so),jn&&om(Er,xl),zi;if(so===null){for(;xlxl?(zm=so,so=null):zm=so.sibling;var G1=yi(Er,so,zc.value,Ci);if(G1===null){so===null&&(so=zm);break}te&&so&&G1.alternate===null&&ie(Er,so),Nn=Et(G1,Nn,xl),Wo===null?zi=G1:Wo.sibling=G1,Wo=G1,so=zm}if(zc.done)return Pe(Er,so),jn&&om(Er,xl),zi;if(so===null){for(;!zc.done;xl++,zc=zn.next())zc=Sl(Er,zc.value,Ci),zc!==null&&(Nn=Et(zc,Nn,xl),Wo===null?zi=zc:Wo.sibling=zc,Wo=zc);return jn&&om(Er,xl),zi}for(so=st(Er,so);!zc.done;xl++,zc=zn.next())zc=Ou(so,Er,xl,zc.value,Ci),zc!==null&&(te&&zc.alternate!==null&&so.delete(zc.key===null?xl:zc.key),Nn=Et(zc,Nn,xl),Wo===null?zi=zc:Wo.sibling=zc,Wo=zc);return te&&so.forEach(function(dM){return ie(Er,dM)}),jn&&om(Er,xl),zi}function W0(Er,Nn,zn,Ci){if(typeof zn=="object"&&zn!==null&&zn.type===u&&zn.key===null&&(zn=zn.props.children),typeof zn=="object"&&zn!==null){switch(zn.$$typeof){case c:e:{for(var zi=zn.key,Wo=Nn;Wo!==null;){if(Wo.key===zi){if(zi=zn.type,zi===u){if(Wo.tag===7){Pe(Er,Wo.sibling),Nn=ct(Wo,zn.props.children),Nn.return=Er,Er=Nn;break e}}else if(Wo.elementType===zi||typeof zi=="object"&&zi!==null&&zi.$$typeof===N&&Bg(zi)===Wo.type){Pe(Er,Wo.sibling),Nn=ct(Wo,zn.props),Nn.ref=lm(Er,Wo,zn),Nn.return=Er,Er=Nn;break e}Pe(Er,Wo);break}else ie(Er,Wo);Wo=Wo.sibling}zn.type===u?(Nn=$s(zn.props.children,Er.mode,Ci,zn.key),Nn.return=Er,Er=Nn):(Ci=bc(zn.type,zn.key,zn.props,null,Er.mode,Ci),Ci.ref=lm(Er,Nn,zn),Ci.return=Er,Er=Ci)}return Fs(Er);case d:e:{for(Wo=zn.key;Nn!==null;){if(Nn.key===Wo)if(Nn.tag===4&&Nn.stateNode.containerInfo===zn.containerInfo&&Nn.stateNode.implementation===zn.implementation){Pe(Er,Nn.sibling),Nn=ct(Nn,zn.children||[]),Nn.return=Er,Er=Nn;break e}else{Pe(Er,Nn);break}else ie(Er,Nn);Nn=Nn.sibling}Nn=r4(zn,Er.mode,Ci),Nn.return=Er,Er=Nn}return Fs(Er);case N:return Wo=zn._init,W0(Er,Nn,Wo(zn._payload),Ci)}if(K(zn))return Cl(Er,Nn,zn,Ci);if(T(zn))return $f(Er,Nn,zn,Ci);zg(Er,zn)}return typeof zn=="string"&&zn!==""||typeof zn=="number"?(zn=""+zn,Nn!==null&&Nn.tag===6?(Pe(Er,Nn.sibling),Nn=ct(Nn,zn),Nn.return=Er,Er=Nn):(Pe(Er,Nn),Nn=Sk(zn,Er.mode,Ci),Nn.return=Er,Er=Nn),Fs(Er)):Pe(Er,Nn)}return W0}var tc=gu(!0),L1=gu(!1),Hx=Oo(null),I0=null,Yd=null,up=null;function D0(){up=Yd=I0=null}function My(te,ie,Pe){De?(Wa(Hx,ie._currentValue),ie._currentValue=Pe):(Wa(Hx,ie._currentValue2),ie._currentValue2=Pe)}function cd(te){var ie=Hx.current;Ei(Hx),De?te._currentValue=ie:te._currentValue2=ie}function wd(te,ie,Pe){for(;te!==null;){var st=te.alternate;if((te.childLanes&ie)!==ie?(te.childLanes|=ie,st!==null&&(st.childLanes|=ie)):st!==null&&(st.childLanes&ie)!==ie&&(st.childLanes|=ie),te===Pe)break;te=te.return}}function Pu(te,ie){I0=te,up=Yd=null,te=te.dependencies,te!==null&&te.firstContext!==null&&(te.lanes&ie&&(Qp=!0),te.firstContext=null)}function Lm(te){var ie=De?te._currentValue:te._currentValue2;if(up!==te)if(te={context:te,memoizedValue:ie,next:null},Yd===null){if(I0===null)throw Error(l(308));Yd=te,I0.dependencies={lanes:0,firstContext:te}}else Yd=Yd.next=te;return ie}var Rf=null;function kl(te){Rf===null?Rf=[te]:Rf.push(te)}function Ma(te,ie,Pe,st){var ct=ie.interleaved;return ct===null?(Pe.next=Pe,kl(ie)):(Pe.next=ct.next,ct.next=Pe),ie.interleaved=Pe,qr(te,st)}function qr(te,ie){te.lanes|=ie;var Pe=te.alternate;for(Pe!==null&&(Pe.lanes|=ie),Pe=te,te=te.return;te!==null;)te.childLanes|=ie,Pe=te.alternate,Pe!==null&&(Pe.childLanes|=ie),Pe=te,te=te.return;return Pe.tag===3?Pe.stateNode:null}var Yl=!1;function La(te){te.updateQueue={baseState:te.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,interleaved:null,lanes:0},effects:null}}function Pm(te,ie){te=te.updateQueue,ie.updateQueue===te&&(ie.updateQueue={baseState:te.baseState,firstBaseUpdate:te.firstBaseUpdate,lastBaseUpdate:te.lastBaseUpdate,shared:te.shared,effects:te.effects})}function dd(te,ie){return{eventTime:te,lane:ie,tag:0,payload:null,callback:null,next:null}}function pa(te,ie,Pe){var st=te.updateQueue;if(st===null)return null;if(st=st.shared,No&2){var ct=st.pending;return ct===null?ie.next=ie:(ie.next=ct.next,ct.next=ie),st.pending=ie,qr(te,Pe)}return ct=st.interleaved,ct===null?(ie.next=ie,kl(st)):(ie.next=ct.next,ct.next=ie),st.interleaved=ie,qr(te,Pe)}function Gx(te,ie,Pe){if(ie=ie.updateQueue,ie!==null&&(ie=ie.shared,(Pe&4194240)!==0)){var st=ie.lanes;st&=te.pendingLanes,Pe|=st,ie.lanes=Pe,L0(te,Pe)}}function $g(te,ie){var Pe=te.updateQueue,st=te.alternate;if(st!==null&&(st=st.updateQueue,Pe===st)){var ct=null,Et=null;if(Pe=Pe.firstBaseUpdate,Pe!==null){do{var Fs={eventTime:Pe.eventTime,lane:Pe.lane,tag:Pe.tag,payload:Pe.payload,callback:Pe.callback,next:null};Et===null?ct=Et=Fs:Et=Et.next=Fs,Pe=Pe.next}while(Pe!==null);Et===null?ct=Et=ie:Et=Et.next=ie}else ct=Et=ie;Pe={baseState:st.baseState,firstBaseUpdate:ct,lastBaseUpdate:Et,shared:st.shared,effects:st.effects},te.updateQueue=Pe;return}te=Pe.lastBaseUpdate,te===null?Pe.firstBaseUpdate=ie:te.next=ie,Pe.lastBaseUpdate=ie}function px(te,ie,Pe,st){var ct=te.updateQueue;Yl=!1;var Et=ct.firstBaseUpdate,Fs=ct.lastBaseUpdate,Yn=ct.shared.pending;if(Yn!==null){ct.shared.pending=null;var Pr=Yn,Pa=Pr.next;Pr.next=null,Fs===null?Et=Pa:Fs.next=Pa,Fs=Pr;var Ri=te.alternate;Ri!==null&&(Ri=Ri.updateQueue,Yn=Ri.lastBaseUpdate,Yn!==Fs&&(Yn===null?Ri.firstBaseUpdate=Pa:Yn.next=Pa,Ri.lastBaseUpdate=Pr))}if(Et!==null){var Sl=ct.baseState;Fs=0,Ri=Pa=Pr=null,Yn=Et;do{var yi=Yn.lane,Ou=Yn.eventTime;if((st&yi)===yi){Ri!==null&&(Ri=Ri.next={eventTime:Ou,lane:0,tag:Yn.tag,payload:Yn.payload,callback:Yn.callback,next:null});e:{var Cl=te,$f=Yn;switch(yi=ie,Ou=Pe,$f.tag){case 1:if(Cl=$f.payload,typeof Cl=="function"){Sl=Cl.call(Ou,Sl,yi);break e}Sl=Cl;break e;case 3:Cl.flags=Cl.flags&-65537|128;case 0:if(Cl=$f.payload,yi=typeof Cl=="function"?Cl.call(Ou,Sl,yi):Cl,yi==null)break e;Sl=i({},Sl,yi);break e;case 2:Yl=!0}}Yn.callback!==null&&Yn.lane!==0&&(te.flags|=64,yi=ct.effects,yi===null?ct.effects=[Yn]:yi.push(Yn))}else Ou={eventTime:Ou,lane:yi,tag:Yn.tag,payload:Yn.payload,callback:Yn.callback,next:null},Ri===null?(Pa=Ri=Ou,Pr=Sl):Ri=Ri.next=Ou,Fs|=yi;if(Yn=Yn.next,Yn===null){if(Yn=ct.shared.pending,Yn===null)break;yi=Yn,Yn=yi.next,yi.next=null,ct.lastBaseUpdate=yi,ct.shared.pending=null}}while(!0);if(Ri===null&&(Pr=Sl),ct.baseState=Pr,ct.firstBaseUpdate=Pa,ct.lastBaseUpdate=Ri,ie=ct.shared.interleaved,ie!==null){ct=ie;do Fs|=ct.lane,ct=ct.next;while(ct!==ie)}else Et===null&&(ct.shared.lanes=0);Av|=Fs,te.lanes=Fs,te.memoizedState=Sl}}function R0(te,ie,Pe){if(te=ie.effects,ie.effects=null,te!==null)for(ie=0;iePe?Pe:4,te(!0);var st=P1.transition;P1.transition={};try{te(!1),ie()}finally{jo=Pe,P1.transition=st}}function mk(){return bu().memoizedState}function K5(te,ie,Pe){var st=V0(te);if(Pe={lane:st,action:Pe,hasEagerState:!1,eagerState:null,next:null},Y5(te))MC(ie,Pe);else if(Pe=Ma(te,ie,Pe,st),Pe!==null){var ct=wu();Bf(Pe,te,st,ct),Ec(Pe,ie,st)}}function rM(te,ie,Pe){var st=V0(te),ct={lane:st,action:Pe,hasEagerState:!1,eagerState:null,next:null};if(Y5(te))MC(ie,ct);else{var Et=te.alternate;if(te.lanes===0&&(Et===null||Et.lanes===0)&&(Et=ie.lastRenderedReducer,Et!==null))try{var Fs=ie.lastRenderedState,Yn=Et(Fs,Pe);if(ct.hasEagerState=!0,ct.eagerState=Yn,Tm(Yn,Fs)){var Pr=ie.interleaved;Pr===null?(ct.next=ct,kl(ie)):(ct.next=Pr.next,Pr.next=ct),ie.interleaved=ct;return}}catch{}finally{}Pe=Ma(te,ie,ct,st),Pe!==null&&(ct=wu(),Bf(Pe,te,st,ct),Ec(Pe,ie,st))}}function Y5(te){var ie=te.alternate;return te===Zl||ie!==null&&ie===Zl}function MC(te,ie){Jc=Zd=!0;var Pe=te.pending;Pe===null?ie.next=ie:(ie.next=Pe.next,Pe.next=ie),te.pending=ie}function Ec(te,ie,Pe){if(Pe&4194240){var st=ie.lanes;st&=te.pendingLanes,Pe|=st,ie.lanes=Pe,L0(te,Pe)}}var s_={readContext:Lm,useCallback:gh,useContext:gh,useEffect:gh,useImperativeHandle:gh,useInsertionEffect:gh,useLayoutEffect:gh,useMemo:gh,useReducer:gh,useRef:gh,useState:gh,useDebugValue:gh,useDeferredValue:gh,useTransition:gh,useMutableSource:gh,useSyncExternalStore:gh,useId:gh,unstable_isNewReconciler:!1},Z5={readContext:Lm,useCallback:function(te,ie){return Yx().memoizedState=[te,ie===void 0?null:ie],te},useContext:Lm,useEffect:Sv,useImperativeHandle:function(te,ie,Pe){return Pe=Pe!=null?Pe.concat([te]):null,R1(4194308,4,t_.bind(null,ie,te),Pe)},useLayoutEffect:function(te,ie){return R1(4194308,4,te,ie)},useInsertionEffect:function(te,ie){return R1(4,2,te,ie)},useMemo:function(te,ie){var Pe=Yx();return ie=ie===void 0?null:ie,te=te(),Pe.memoizedState=[te,ie],te},useReducer:function(te,ie,Pe){var st=Yx();return ie=Pe!==void 0?Pe(ie):ie,st.memoizedState=st.baseState=ie,te={pending:null,interleaved:null,lanes:0,dispatch:null,lastRenderedReducer:te,lastRenderedState:ie},st.queue=te,te=te.dispatch=K5.bind(null,Zl,te),[st.memoizedState,te]},useRef:function(te){var ie=Yx();return te={current:te},ie.memoizedState=te},useState:pp,useDebugValue:j2,useDeferredValue:function(te){return Yx().memoizedState=te},useTransition:function(){var te=pp(!1),ie=te[0];return te=ho.bind(null,te[1]),Yx().memoizedState=te,[ie,te]},useMutableSource:function(){},useSyncExternalStore:function(te,ie,Pe){var st=Zl,ct=Yx();if(jn){if(Pe===void 0)throw Error(l(407));Pe=Pe()}else{if(Pe=ie(),Fc===null)throw Error(l(349));vu&30||_2(st,ie,Pe)}ct.memoizedState=Pe;var Et={value:Pe,getSnapshot:ie};return ct.queue=Et,Sv(D1.bind(null,st,Et,te),[te]),st.flags|=2048,yh(9,I1.bind(null,st,Et,Pe,ie),void 0,null),Pe},useId:function(){var te=Yx(),ie=Fc.identifierPrefix;if(jn){var Pe=dp,st=_d;Pe=(st&~(1<<32-Vo(st)-1)).toString(32)+Pe,ie=":"+ie+"R"+Pe,Pe=Kx++,0Hg&&(ie.flags|=128,st=!0,Cn(ct,!1),ie.lanes=4194304)}else{if(!st)if(te=Wx(Et),te!==null){if(ie.flags|=128,st=!0,te=te.updateQueue,te!==null&&(ie.updateQueue=te,ie.flags|=4),Cn(ct,!0),ct.tail===null&&ct.tailMode==="hidden"&&!Et.alternate&&!jn)return Xn(ie),null}else 2*ql()-ct.renderingStartTime>Hg&&Pe!==1073741824&&(ie.flags|=128,st=!0,Cn(ct,!1),ie.lanes=4194304);ct.isBackwards?(Et.sibling=ie.child,ie.child=Et):(te=ct.last,te!==null?te.sibling=Et:ie.child=Et,ct.last=Et)}return ct.tail!==null?(ie=ct.tail,ct.rendering=ie,ct.tail=ie.sibling,ct.renderingStartTime=ql(),ie.sibling=null,te=Ac.current,Wa(Ac,st?te&1|2:te&1),ie):(Xn(ie),null);case 22:case 23:return Lv(),Pe=ie.memoizedState!==null,te!==null&&te.memoizedState!==null!==Pe&&(ie.flags|=8192),Pe&&ie.mode&1?dm&1073741824&&(Xn(ie),ze&&ie.subtreeFlags&6&&(ie.flags|=8192)):Xn(ie),null;case 24:return null;case 25:return null}throw Error(l(156,ie.tag))}function On(te,ie){switch(Wt(ie),ie.tag){case 1:return Kn(ie.type)&&wn(),te=ie.flags,te&65536?(ie.flags=te&-65537|128,ie):null;case 3:return mp(),Ei(is),Ei(Io),xh(),te=ie.flags,te&65536&&!(te&128)?(ie.flags=te&-65537|128,ie):null;case 5:return kv(ie),null;case 13:if(Ei(Ac),te=ie.memoizedState,te!==null&&te.dehydrated!==null){if(ie.alternate===null)throw Error(l(340));Ra()}return te=ie.flags,te&65536?(ie.flags=te&-65537|128,ie):null;case 19:return Ei(Ac),null;case 4:return mp(),null;case 10:return cd(ie.type._context),null;case 22:case 23:return Lv(),null;case 24:return null;default:return null}}var nr=!1,Mr=!1,xr=typeof WeakSet=="function"?WeakSet:Set,Fn=null;function $r(te,ie){var Pe=te.ref;if(Pe!==null)if(typeof Pe=="function")try{Pe(null)}catch(st){Si(te,ie,st)}else Pe.current=null}function ba(te,ie,Pe){try{Pe()}catch(st){Si(te,ie,st)}}var fa=!1;function Fi(te,ie){for(ue(te.containerInfo),Fn=ie;Fn!==null;)if(te=Fn,ie=te.child,(te.subtreeFlags&1028)!==0&&ie!==null)ie.return=te,Fn=ie;else for(;Fn!==null;){te=Fn;try{var Pe=te.alternate;if(te.flags&1024)switch(te.tag){case 0:case 11:case 15:break;case 1:if(Pe!==null){var st=Pe.memoizedProps,ct=Pe.memoizedState,Et=te.stateNode,Fs=Et.getSnapshotBeforeUpdate(te.elementType===te.type?st:qg(te.type,st),ct);Et.__reactInternalSnapshotBeforeUpdate=Fs}break;case 3:ze&&Un(te.stateNode.containerInfo);break;case 5:case 6:case 4:case 17:break;default:throw Error(l(163))}}catch(Yn){Si(te,te.return,Yn)}if(ie=te.sibling,ie!==null){ie.return=te.return,Fn=ie;break}Fn=te.return}return Pe=fa,fa=!1,Pe}function bi(te,ie,Pe){var st=ie.updateQueue;if(st=st!==null?st.lastEffect:null,st!==null){var ct=st=st.next;do{if((ct.tag&te)===te){var Et=ct.destroy;ct.destroy=void 0,Et!==void 0&&ba(ie,Pe,Et)}ct=ct.next}while(ct!==st)}}function sl(te,ie){if(ie=ie.updateQueue,ie=ie!==null?ie.lastEffect:null,ie!==null){var Pe=ie=ie.next;do{if((Pe.tag&te)===te){var st=Pe.create;Pe.destroy=st()}Pe=Pe.next}while(Pe!==ie)}}function Li(te){var ie=te.ref;if(ie!==null){var Pe=te.stateNode;switch(te.tag){case 5:te=Q(Pe);break;default:te=Pe}typeof ie=="function"?ie(te):ie.current=te}}function Dl(te){var ie=te.alternate;ie!==null&&(te.alternate=null,Dl(ie)),te.child=null,te.deletions=null,te.sibling=null,te.tag===5&&(ie=te.stateNode,ie!==null&&Be(ie)),te.stateNode=null,te.return=null,te.dependencies=null,te.memoizedProps=null,te.memoizedState=null,te.pendingProps=null,te.stateNode=null,te.updateQueue=null}function Pd(te){return te.tag===5||te.tag===3||te.tag===4}function nl(te){e:for(;;){for(;te.sibling===null;){if(te.return===null||Pd(te.return))return null;te=te.return}for(te.sibling.return=te.return,te=te.sibling;te.tag!==5&&te.tag!==6&&te.tag!==18;){if(te.flags&2||te.child===null||te.tag===4)continue e;te.child.return=te,te=te.child}if(!(te.flags&2))return te.stateNode}}function Di(te,ie,Pe){var st=te.tag;if(st===5||st===6)te=te.stateNode,ie?Ds(Pe,te,ie):Ft(Pe,te);else if(st!==4&&(te=te.child,te!==null))for(Di(te,ie,Pe),te=te.sibling;te!==null;)Di(te,ie,Pe),te=te.sibling}function ti(te,ie,Pe){var st=te.tag;if(st===5||st===6)te=te.stateNode,ie?Nt(Pe,te,ie):Mt(Pe,te);else if(st!==4&&(te=te.child,te!==null))for(ti(te,ie,Pe),te=te.sibling;te!==null;)ti(te,ie,Pe),te=te.sibling}var ol=null,co=!1;function Yo(te,ie,Pe){for(Pe=Pe.child;Pe!==null;)jd(te,ie,Pe),Pe=Pe.sibling}function jd(te,ie,Pe){if(Ti&&typeof Ti.onCommitFiberUnmount=="function")try{Ti.onCommitFiberUnmount(Kd,Pe)}catch{}switch(Pe.tag){case 5:Mr||$r(Pe,ie);case 6:if(ze){var st=ol,ct=co;ol=null,Yo(te,ie,Pe),ol=st,co=ct,ol!==null&&(co?Xs(ol,Pe.stateNode):_t(ol,Pe.stateNode))}else Yo(te,ie,Pe);break;case 18:ze&&ol!==null&&(co?Gs(ol,Pe.stateNode):qt(ol,Pe.stateNode));break;case 4:ze?(st=ol,ct=co,ol=Pe.stateNode.containerInfo,co=!0,Yo(te,ie,Pe),ol=st,co=ct):(ke&&(st=Pe.stateNode.containerInfo,ct=Ar(st),yr(st,ct)),Yo(te,ie,Pe));break;case 0:case 11:case 14:case 15:if(!Mr&&(st=Pe.updateQueue,st!==null&&(st=st.lastEffect,st!==null))){ct=st=st.next;do{var Et=ct,Fs=Et.destroy;Et=Et.tag,Fs!==void 0&&(Et&2||Et&4)&&ba(Pe,ie,Fs),ct=ct.next}while(ct!==st)}Yo(te,ie,Pe);break;case 1:if(!Mr&&($r(Pe,ie),st=Pe.stateNode,typeof st.componentWillUnmount=="function"))try{st.props=Pe.memoizedProps,st.state=Pe.memoizedState,st.componentWillUnmount()}catch(Yn){Si(Pe,ie,Yn)}Yo(te,ie,Pe);break;case 21:Yo(te,ie,Pe);break;case 22:Pe.mode&1?(Mr=(st=Mr)||Pe.memoizedState!==null,Yo(te,ie,Pe),Mr=st):Yo(te,ie,Pe);break;default:Yo(te,ie,Pe)}}function Oh(te){var ie=te.updateQueue;if(ie!==null){te.updateQueue=null;var Pe=te.stateNode;Pe===null&&(Pe=te.stateNode=new xr),ie.forEach(function(st){var ct=kk.bind(null,te,st);Pe.has(st)||(Pe.add(st),st.then(ct,ct))})}}function Nd(te,ie){var Pe=ie.deletions;if(Pe!==null)for(var st=0;st";case Iu:return":has("+(Id(te)||"")+")";case Im:return'[role="'+te.value+'"]';case th:return'"'+te.value+'"';case Vc:return'[data-testname="'+te.value+'"]';default:throw Error(l(365))}}function ef(te,ie){var Pe=[];te=[te,0];for(var st=0;stct&&(ct=Fs),st&=~Et}if(st=ct,st=ql()-st,st=(120>st?120:480>st?480:1080>st?1080:1920>st?1920:3e3>st?3e3:4320>st?4320:1960*Rm(st/1960))-st,10te?16:te,gx===null)var st=!1;else{if(te=gx,gx=null,o_=0,No&6)throw Error(l(331));var ct=No;for(No|=4,Fn=te.current;Fn!==null;){var Et=Fn,Fs=Et.child;if(Fn.flags&16){var Yn=Et.deletions;if(Yn!==null){for(var Pr=0;Prql()-Uw?Gg(te,0):Ev|=Pe),nf(te,ie)}function s4(te,ie){ie===0&&(te.mode&1?(ie=Ju,Ju<<=1,!(Ju&130023424)&&(Ju=4194304)):ie=1);var Pe=wu();te=qr(te,ie),te!==null&&(Lf(te,ie,Pe),nf(te,Pe))}function PC(te){var ie=te.memoizedState,Pe=0;ie!==null&&(Pe=ie.retryLane),s4(te,Pe)}function kk(te,ie){var Pe=0;switch(te.tag){case 13:var st=te.stateNode,ct=te.memoizedState;ct!==null&&(Pe=ct.retryLane);break;case 19:st=te.stateNode;break;default:throw Error(l(314))}st!==null&&st.delete(ie),s4(te,Pe)}var IC;IC=function(te,ie,Pe){if(te!==null)if(te.memoizedProps!==ie.pendingProps||is.current)Qp=!0;else{if(!(te.lanes&Pe)&&!(ie.flags&128))return Qp=!1,mt(te,ie,Pe);Qp=!!(te.flags&131072)}else Qp=!1,jn&&ie.flags&1048576&&Rh(ie,P0,ie.index);switch(ie.lanes=0,ie.tag){case 2:var st=ie.type;Ce(te,ie),te=ie.pendingProps;var ct=Sa(ie,Io.current);Pu(ie,Pe),ct=Tw(null,ie,st,te,ct,Pe);var Et=Qb();return ie.flags|=1,typeof ct=="object"&&ct!==null&&typeof ct.render=="function"&&ct.$$typeof===void 0?(ie.tag=1,ie.memoizedState=null,ie.updateQueue=null,Kn(st)?(Et=!0,yo(ie)):Et=!1,ie.memoizedState=ct.state!==null&&ct.state!==void 0?ct.state:null,La(ie),ct.updater=n_,ie.stateNode=ct,ct._reactInternals=ie,zf(ie,st,te,Pe),ie=Fw(null,ie,st,!0,Et,Pe)):(ie.tag=0,jn&&Et&&at(ie),fp(null,ie,ct,Pe),ie=ie.child),ie;case 16:st=ie.elementType;e:{switch(Ce(te,ie),te=ie.pendingProps,ct=st._init,st=ct(st._payload),ie.type=st,ct=ie.tag=ar(st),te=qg(st,te),ct){case 0:ie=gk(null,ie,st,te,Pe);break e;case 1:ie=yk(null,ie,st,te,Pe);break e;case 11:ie=Q5(null,ie,st,te,Pe);break e;case 14:ie=Py(null,ie,st,qg(st.type,te),Pe);break e}throw Error(l(306,st,""))}return ie;case 0:return st=ie.type,ct=ie.pendingProps,ct=ie.elementType===st?ct:qg(st,ct),gk(te,ie,st,ct,Pe);case 1:return st=ie.type,ct=ie.pendingProps,ct=ie.elementType===st?ct:qg(st,ct),yk(te,ie,st,ct,Pe);case 3:e:{if(zw(ie),te===null)throw Error(l(387));st=ie.pendingProps,Et=ie.memoizedState,ct=Et.element,Pm(te,ie),px(ie,st,null,Pe);var Fs=ie.memoizedState;if(st=Fs.element,Xe&&Et.isDehydrated)if(Et={element:st,isDehydrated:!1,cache:Fs.cache,pendingSuspenseBoundaries:Fs.pendingSuspenseBoundaries,transitions:Fs.transitions},ie.updateQueue.baseState=Et,ie.memoizedState=Et,ie.flags&256){ct=eu(Error(l(423)),ie),ie=r_(te,ie,st,Pe,ct);break e}else if(st!==ct){ct=eu(Error(l(424)),ie),ie=r_(te,ie,st,Pe,ct);break e}else for(Xe&&(Ys=ot(ie.stateNode.containerInfo),Bs=ie,jn=!0,kt=null,Ir=!1),Pe=L1(ie,null,st,Pe),ie.child=Pe;Pe;)Pe.flags=Pe.flags&-3|4096,Pe=Pe.sibling;else{if(Ra(),st===ct){ie=Fe(te,ie,Pe);break e}fp(te,ie,st,Pe)}ie=ie.child}return ie;case 5:return Nv(ie),te===null&&Dr(ie),st=ie.type,ct=ie.pendingProps,Et=te!==null?te.memoizedProps:null,Fs=ct.children,ge(st,ct)?Fs=null:Et!==null&&ge(st,Et)&&(ie.flags|=32),xk(te,ie),fp(te,ie,Fs,Pe),ie.child;case 6:return te===null&&Dr(ie),null;case 13:return LC(te,ie,Pe);case 4:return Qc(ie,ie.stateNode.containerInfo),st=ie.pendingProps,te===null?ie.child=tc(ie,null,st,Pe):fp(te,ie,st,Pe),ie.child;case 11:return st=ie.type,ct=ie.pendingProps,ct=ie.elementType===st?ct:qg(st,ct),Q5(te,ie,st,ct,Pe);case 7:return fp(te,ie,ie.pendingProps,Pe),ie.child;case 8:return fp(te,ie,ie.pendingProps.children,Pe),ie.child;case 12:return fp(te,ie,ie.pendingProps.children,Pe),ie.child;case 10:e:{if(st=ie.type._context,ct=ie.pendingProps,Et=ie.memoizedProps,Fs=ct.value,My(ie,st,Fs),Et!==null)if(Tm(Et.value,Fs)){if(Et.children===ct.children&&!is.current){ie=Fe(te,ie,Pe);break e}}else for(Et=ie.child,Et!==null&&(Et.return=ie);Et!==null;){var Yn=Et.dependencies;if(Yn!==null){Fs=Et.child;for(var Pr=Yn.firstContext;Pr!==null;){if(Pr.context===st){if(Et.tag===1){Pr=dd(-1,Pe&-Pe),Pr.tag=2;var Pa=Et.updateQueue;if(Pa!==null){Pa=Pa.shared;var Ri=Pa.pending;Ri===null?Pr.next=Pr:(Pr.next=Ri.next,Ri.next=Pr),Pa.pending=Pr}}Et.lanes|=Pe,Pr=Et.alternate,Pr!==null&&(Pr.lanes|=Pe),wd(Et.return,Pe,ie),Yn.lanes|=Pe;break}Pr=Pr.next}}else if(Et.tag===10)Fs=Et.type===ie.type?null:Et.child;else if(Et.tag===18){if(Fs=Et.return,Fs===null)throw Error(l(341));Fs.lanes|=Pe,Yn=Fs.alternate,Yn!==null&&(Yn.lanes|=Pe),wd(Fs,Pe,ie),Fs=Et.sibling}else Fs=Et.child;if(Fs!==null)Fs.return=Et;else for(Fs=Et;Fs!==null;){if(Fs===ie){Fs=null;break}if(Et=Fs.sibling,Et!==null){Et.return=Fs.return,Fs=Et;break}Fs=Fs.return}Et=Fs}fp(te,ie,ct.children,Pe),ie=ie.child}return ie;case 9:return ct=ie.type,st=ie.pendingProps.children,Pu(ie,Pe),ct=Lm(ct),st=st(ct),ie.flags|=1,fp(te,ie,st,Pe),ie.child;case 14:return st=ie.type,ct=qg(st,ie.pendingProps),ct=qg(st.type,ct),Py(te,ie,st,ct,Pe);case 15:return Rw(te,ie,ie.type,ie.pendingProps,Pe);case 17:return st=ie.type,ct=ie.pendingProps,ct=ie.elementType===st?ct:qg(st,ct),Ce(te,ie),ie.tag=1,Kn(st)?(te=!0,yo(ie)):te=!1,Pu(ie,Pe),z1(ie,st,ct),zf(ie,st,ct,Pe),Fw(null,ie,st,!0,te,Pe);case 19:return i_(te,ie,Pe);case 22:return Ow(te,ie,Pe)}throw Error(l(156,ie.tag))};function DC(te,ie){return Ey(te,ie)}function E2(te,ie,Pe,st){this.tag=te,this.key=Pe,this.sibling=this.child=this.return=this.stateNode=this.type=this.elementType=null,this.index=0,this.ref=null,this.pendingProps=ie,this.dependencies=this.memoizedState=this.updateQueue=this.memoizedProps=null,this.mode=st,this.subtreeFlags=this.flags=0,this.deletions=null,this.childLanes=this.lanes=0,this.alternate=null}function Fm(te,ie,Pe,st){return new E2(te,ie,Pe,st)}function ir(te){return te=te.prototype,!(!te||!te.isReactComponent)}function ar(te){if(typeof te=="function")return ir(te)?1:0;if(te!=null){if(te=te.$$typeof,te===g)return 11;if(te===v)return 14}return 2}function G0(te,ie){var Pe=te.alternate;return Pe===null?(Pe=Fm(te.tag,ie,te.key,te.mode),Pe.elementType=te.elementType,Pe.type=te.type,Pe.stateNode=te.stateNode,Pe.alternate=te,te.alternate=Pe):(Pe.pendingProps=ie,Pe.type=te.type,Pe.flags=0,Pe.subtreeFlags=0,Pe.deletions=null),Pe.flags=te.flags&14680064,Pe.childLanes=te.childLanes,Pe.lanes=te.lanes,Pe.child=te.child,Pe.memoizedProps=te.memoizedProps,Pe.memoizedState=te.memoizedState,Pe.updateQueue=te.updateQueue,ie=te.dependencies,Pe.dependencies=ie===null?null:{lanes:ie.lanes,firstContext:ie.firstContext},Pe.sibling=te.sibling,Pe.index=te.index,Pe.ref=te.ref,Pe}function bc(te,ie,Pe,st,ct,Et){var Fs=2;if(st=te,typeof te=="function")ir(te)&&(Fs=1);else if(typeof te=="string")Fs=5;else e:switch(te){case u:return $s(Pe.children,ct,Et,ie);case h:Fs=8,ct|=8;break;case m:return te=Fm(12,Pe,ie,ct|2),te.elementType=m,te.lanes=Et,te;case y:return te=Fm(13,Pe,ie,ct),te.elementType=y,te.lanes=Et,te;case b:return te=Fm(19,Pe,ie,ct),te.elementType=b,te.lanes=Et,te;case C:return n4(Pe,ct,Et,ie);default:if(typeof te=="object"&&te!==null)switch(te.$$typeof){case p:Fs=10;break e;case x:Fs=9;break e;case g:Fs=11;break e;case v:Fs=14;break e;case N:Fs=16,st=null;break e}throw Error(l(130,te==null?te:typeof te,""))}return ie=Fm(Fs,Pe,ie,ct),ie.elementType=te,ie.type=st,ie.lanes=Et,ie}function $s(te,ie,Pe,st){return te=Fm(7,te,st,ie),te.lanes=Pe,te}function n4(te,ie,Pe,st){return te=Fm(22,te,st,ie),te.elementType=C,te.lanes=Pe,te.stateNode={isHidden:!1},te}function Sk(te,ie,Pe){return te=Fm(6,te,null,ie),te.lanes=Pe,te}function r4(te,ie,Pe){return ie=Fm(4,te.children!==null?te.children:[],te.key,ie),ie.lanes=Pe,ie.stateNode={containerInfo:te.containerInfo,pendingChildren:null,implementation:te.implementation},ie}function RC(te,ie,Pe,st,ct){this.tag=ie,this.containerInfo=te,this.finishedWork=this.pingCache=this.current=this.pendingChildren=null,this.timeoutHandle=Me,this.callbackNode=this.pendingContext=this.context=null,this.callbackPriority=0,this.eventTimes=Em(0),this.expirationTimes=Em(-1),this.entangledLanes=this.finishedLanes=this.mutableReadLanes=this.expiredLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=Em(0),this.identifierPrefix=st,this.onRecoverableError=ct,Xe&&(this.mutableSourceEagerHydrationData=null)}function oM(te,ie,Pe,st,ct,Et,Fs,Yn,Pr){return te=new RC(te,ie,Pe,Yn,Pr),ie===1?(ie=1,Et===!0&&(ie|=8)):ie=0,Et=Fm(3,null,null,ie),te.current=Et,Et.stateNode=te,Et.memoizedState={element:st,isDehydrated:Pe,cache:null,transitions:null,pendingSuspenseBoundaries:null},La(Et),te}function lM(te){if(!te)return wo;te=te._reactInternals;e:{if(I(te)!==te||te.tag!==1)throw Error(l(170));var ie=te;do{switch(ie.tag){case 3:ie=ie.stateNode.context;break e;case 1:if(Kn(ie.type)){ie=ie.stateNode.__reactInternalMemoizedMergedChildContext;break e}}ie=ie.return}while(ie!==null);throw Error(l(171))}if(te.tag===1){var Pe=te.type;if(Kn(Pe))return ca(te,Pe,ie)}return ie}function T2(te){var ie=te._reactInternals;if(ie===void 0)throw typeof te.render=="function"?Error(l(188)):(te=Object.keys(te).join(","),Error(l(268,te)));return te=q(ie),te===null?null:te.stateNode}function cM(te,ie){if(te=te.memoizedState,te!==null&&te.dehydrated!==null){var Pe=te.retryLane;te.retryLane=Pe!==0&&Pe=Pa&&Et>=Sl&&ct<=Ri&&Fs<=yi){te.splice(ie,1);break}else if(st!==Pa||Pe.width!==Pr.width||yiFs){if(!(Et!==Sl||Pe.height!==Pr.height||Rict)){Pa>st&&(Pr.width+=Pa-st,Pr.x=st),RiEt&&(Pr.height+=Sl-Et,Pr.y=Et),yiPe&&(Pe=Fs)),Fs ")+` No matching component was found for: `)+te.join(" > ")}return null},n.getPublicRootInstance=function(te){if(te=te.current,!te.child)return null;switch(te.child.tag){case 5:return Q(te.child.stateNode);default:return te.child.stateNode}},n.injectIntoDevTools=function(te){if(te={bundleType:te.bundleType,version:te.version,rendererPackageName:te.rendererPackageName,rendererConfig:te.rendererConfig,overrideHookState:null,overrideHookStateDeletePath:null,overrideHookStateRenamePath:null,overrideProps:null,overridePropsDeletePath:null,overridePropsRenamePath:null,setErrorHandler:null,setSuspenseHandler:null,scheduleUpdate:null,currentDispatcherRef:o.ReactCurrentDispatcher,findHostInstanceByFiber:SF,findFiberByHostInstance:te.findFiberByHostInstance||FC,findHostInstancesForRefresh:null,scheduleRefresh:null,scheduleRoot:null,setRefreshHandler:null,getCurrentFiber:null,reconcilerVersion:"18.3.1"},typeof __REACT_DEVTOOLS_GLOBAL_HOOK__>"u")te=!1;else{var ie=__REACT_DEVTOOLS_GLOBAL_HOOK__;if(ie.isDisabled||!ie.supportsFiber)te=!0;else{try{Kd=ie.inject(te),Ti=ie}catch{}te=!!ie.checkDCE}}return te},n.isAlreadyRendering=function(){return!1},n.observeVisibleRects=function(te,ie,Pe,st){if(!Ze)throw Error(l(363));te=tf(te,ie);var ct=lt(te,Pe,st).disconnect;return{disconnect:function(){ct()}}},n.registerMutableSourceForHydration=function(te,ie){var Pe=ie._getVersion;Pe=Pe(ie._source),te.mutableSourceEagerHydrationData==null?te.mutableSourceEagerHydrationData=[ie,Pe]:te.mutableSourceEagerHydrationData.push(ie,Pe)},n.runWithPriority=function(te,ie){var Pe=jo;try{return jo=te,ie()}finally{jo=Pe}},n.shouldError=function(){return null},n.shouldSuspend=function(){return!1},n.updateContainer=function(te,ie,Pe,st){var ct=ie.current,Et=wu(),Fs=V0(ct);return Pe=lM(Pe),ie.context===null?ie.context=Pe:ie.pendingContext=Pe,ie=dd(Et,Fs),ie.payload={element:te},st=st===void 0?null:st,st!==null&&(ie.callback=st),te=pa(ct,ie,Fs),te!==null&&(Bf(te,ct,Fs,Et),Gx(te,ct,Fs)),Fs},n};_It.exports=Uzs;var qzs=_It.exports;const Vzs=Uc(qzs);var wIt={exports:{}},aF={};/** * @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. */aF.ConcurrentRoot=1;aF.ContinuousEventPriority=4;aF.DefaultEventPriority=16;aF.DiscreteEventPriority=1;aF.IdleEventPriority=536870912;aF.LegacyRoot=0;wIt.exports=aF;var jIt=wIt.exports;const Bdt={children:!0,ref:!0,key:!0,style:!0,forwardedRef:!0,unstable_applyCache:!0,unstable_applyDrawHitFromCache:!0};let $dt=!1,Udt=!1;const LWe=".react-konva-event",Hzs=`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 `,Gzs=`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 `,Wzs={};function AAe(s,t,n=Wzs){if(!$dt&&"zIndex"in t&&(console.warn(Gzs),$dt=!0),!Udt&&t.draggable){var r=t.x!==void 0||t.y!==void 0,a=t.onDragEnd||t.onDragMove;r&&!a&&(console.warn(Hzs),Udt=!0)}for(var i in n)if(!Bdt[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(!Bdt[i]){var l=i.slice(0,2)==="on",x=n[i]!==t[i];if(l&&x){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),q6(s));for(var c in p)s.on(c+LWe,p[c])}function q6(s){if(!ii.autoDrawEnabled){var t=s.getLayer()||s.getStage();t&&t.batchDraw()}}const NIt={},Kzs={};bO.Node.prototype._applyProps=AAe;function Yzs(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),q6(s)}function Zzs(s,t,n){let r=bO[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=bO.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 AAe(c,i),c}function Xzs(s,t,n){console.error(`Text components are not supported for now in ReactKonva. Your text is: "${s}"`)}function Qzs(s,t,n){return!1}function Jzs(s){return s}function eBs(){return null}function tBs(){return null}function sBs(s,t,n,r){return Kzs}function nBs(){}function rBs(s){}function aBs(s,t){return!1}function iBs(){return NIt}function oBs(){return NIt}const lBs=setTimeout,cBs=clearTimeout,dBs=-1;function uBs(s,t){return!1}const hBs=!1,mBs=!0,pBs=!0;function fBs(s,t){t.parent===s?t.moveToTop():s.add(t),q6(s)}function xBs(s,t){t.parent===s?t.moveToTop():s.add(t),q6(s)}function kIt(s,t,n){t._remove(),s.add(t),t.setZIndex(n.getZIndex()),q6(s)}function gBs(s,t,n){kIt(s,t,n)}function yBs(s,t){t.destroy(),t.off(LWe),q6(s)}function vBs(s,t){t.destroy(),t.off(LWe),q6(s)}function bBs(s,t,n){console.error(`Text components are not yet supported in ReactKonva. You text is: "${n}"`)}function _Bs(s,t,n){}function wBs(s,t,n,r,a){AAe(s,a,r)}function jBs(s){s.hide(),q6(s)}function NBs(s){}function kBs(s,t){(t.visible==null||t.visible)&&s.show()}function SBs(s,t){}function CBs(s){}function ABs(){}const EBs=()=>jIt.DefaultEventPriority,TBs=Object.freeze(Object.defineProperty({__proto__:null,appendChild:fBs,appendChildToContainer:xBs,appendInitialChild:Yzs,cancelTimeout:cBs,clearContainer:CBs,commitMount:_Bs,commitTextUpdate:bBs,commitUpdate:wBs,createInstance:Zzs,createTextInstance:Xzs,detachDeletedInstance:ABs,finalizeInitialChildren:Qzs,getChildHostContext:oBs,getCurrentEventPriority:EBs,getPublicInstance:Jzs,getRootHostContext:iBs,hideInstance:jBs,hideTextInstance:NBs,idlePriority:nK.unstable_IdlePriority,insertBefore:kIt,insertInContainerBefore:gBs,isPrimaryRenderer:hBs,noTimeout:dBs,now:nK.unstable_now,prepareForCommit:eBs,preparePortalMount:tBs,prepareUpdate:sBs,removeChild:yBs,removeChildFromContainer:vBs,resetAfterCommit:nBs,resetTextContent:rBs,run:nK.unstable_runWithPriority,scheduleTimeout:lBs,shouldDeprioritizeSubtree:aBs,shouldSetTextContent:uBs,supportsMutation:pBs,unhideInstance:kBs,unhideTextInstance:SBs,warnsIfNotActing:mBs},Symbol.toStringTag,{value:"Module"}));var MBs=Object.defineProperty,LBs=Object.defineProperties,PBs=Object.getOwnPropertyDescriptors,qdt=Object.getOwnPropertySymbols,IBs=Object.prototype.hasOwnProperty,DBs=Object.prototype.propertyIsEnumerable,Vdt=(s,t,n)=>t in s?MBs(s,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):s[t]=n,Hdt=(s,t)=>{for(var n in t||(t={}))IBs.call(t,n)&&Vdt(s,n,t[n]);if(qdt)for(var n of qdt(t))DBs.call(t,n)&&Vdt(s,n,t[n]);return s},RBs=(s,t)=>LBs(s,PBs(t)),Gdt,Wdt;typeof window<"u"&&((Gdt=window.document)!=null&&Gdt.createElement||((Wdt=window.navigator)==null?void 0:Wdt.product)==="ReactNative")?j.useLayoutEffect:j.useEffect;function SIt(s,t,n){if(!s)return;if(n(s)===!0)return s;let r=s.child;for(;r;){const a=SIt(r,t,n);if(a)return a;r=r.sibling}}function CIt(s){try{return Object.defineProperties(s,{_currentRenderer:{get(){return null},set(){}},_currentRenderer2:{get(){return null},set(){}}})}catch{return s}}const Kdt=console.error;console.error=function(){const s=[...arguments].join("");if(s!=null&&s.startsWith("Warning:")&&s.includes("useContext")){console.error=Kdt;return}return Kdt.apply(this,arguments)};const PWe=CIt(j.createContext(null));class AIt extends j.Component{render(){return j.createElement(PWe.Provider,{value:this._reactInternals},this.props.children)}}function OBs(){const s=j.useContext(PWe);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=SIt(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 FBs(){const s=OBs(),[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!==PWe&&!t.has(a)&&t.set(a,j.useContext(CIt(a)))}n=n.return}return t}function zBs(){const s=FBs();return j.useMemo(()=>Array.from(s.keys()).reduce((t,n)=>r=>j.createElement(t,null,j.createElement(n.Provider,RBs(Hdt({},r),{value:s.get(n)}))),t=>j.createElement(AIt,Hdt({},t))),[s])}function BBs(s){const t=It.useRef({});return It.useLayoutEffect(()=>{t.current=s}),It.useLayoutEffect(()=>()=>{t.current={}},[]),t.current}const $Bs=s=>{const t=It.useRef(null),n=It.useRef(null),r=It.useRef(null),a=BBs(s),i=zBs(),l=o=>{const{forwardedRef:c}=s;c&&(typeof c=="function"?c(o):c.current=o)};return It.useLayoutEffect(()=>(n.current=new bO.Stage({width:s.width,height:s.height,container:t.current}),l(n.current),r.current=AW.createContainer(n.current,jIt.LegacyRoot,!1,null),AW.updateContainer(It.createElement(i,{},s.children),r.current),()=>{bO.isBrowser&&(l(null),AW.updateContainer(null,r.current,null),n.current.destroy())}),[]),It.useLayoutEffect(()=>{l(n.current),AAe(n.current,s,a),AW.updateContainer(It.createElement(i,{},s.children),r.current,null)}),It.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})},UBs="Layer",XE="Group",Zk="Rect",Y9="Image",A7="Text",uQn="Transformer",AW=Vzs(TBs);AW.injectIntoDevTools({findHostInstanceByFiber:()=>null,bundleType:0,version:It.version,rendererPackageName:"react-konva"});const qBs=It.forwardRef((s,t)=>It.createElement(AIt,{},It.createElement($Bs,{...s,forwardedRef:t})));function VBs({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)??"",x=(t==null?void 0:t.brokerage_logo_url)??"";j.useEffect(()=>{if(!s){c(null);return}const W=new window.Image;W.crossOrigin="anonymous",W.onload=()=>c(W),W.onerror=()=>c(null),W.src=s},[s]),j.useEffect(()=>{if(!p){u(null);return}const W=new window.Image;W.crossOrigin="anonymous",W.onload=()=>u(W),W.onerror=()=>u(null),W.src=p},[p]),j.useEffect(()=>{if(!x){m(null);return}const W=new window.Image;W.crossOrigin="anonymous",W.onload=()=>m(W),W.onerror=()=>m(null),W.src=x},[x]);const g=f7s(n),y=(o==null?void 0:o.naturalWidth)??1080,b=(o==null?void 0:o.naturalHeight)??1080,v=j.useMemo(()=>Math.min(1,a/y),[y,a]),N=y*v,C=b*v,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",P=(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)??"",D=(r==null?void 0:r.tagline)??(t==null?void 0:t.tagline)??"",B=new Set((r==null?void 0:r.hidden_fields)??(t==null?void 0:t.hidden_fields)??[]),q=W=>g.fields.includes(W)&&!B.has(W);return e.jsx("div",{className:"border rounded-lg overflow-hidden bg-muted/40 inline-block",children:e.jsx(qBs,{ref:W=>{l.current=W,i&&(i.current=W)},width:N,height:C,scaleX:v,scaleY:v,children:e.jsxs(UBs,{children:[o&&e.jsx(Y9,{image:o,width:y,height:b,listening:!1}),!o&&e.jsx(Zk,{x:0,y:0,width:y,height:b,fill:"#e2e8f0"}),e.jsx(HBs,{style:g,canvasW:y,canvasH:b,brandColor:A,accentColor:T,name:P,phone:M,email:I,tagline:D,headshot:d,logo:h,hidden:B,has:q})]})})})}function HBs({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,x=s.textColor==="light"?"#ffffff":s.textColor==="dark"?"#0f172a":s.background==="dark"||s.background==="gradient"?"#ffffff":x7s(r),g=x==="#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(XE,{children:[e.jsx(Zk,{x:0,y,width:t,height:m,fill:r}),e.jsx(Zk,{x:0,y:s.position==="bottom"?y:m-4,width:t,height:4,fill:a}),e.jsx(mre,{x:p,y:y+p,width:t-p*2,height:m-p*2,textColor:x,subTextColor:g,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,b=m,v=t-y-n*.025,N=n-b-n*.025;return e.jsxs(XE,{children:[e.jsx(Zk,{x:v,y:N,width:y,height:b,fill:r,cornerRadius:b*.12,opacity:.92}),e.jsx(Zk,{x:v,y:N+b-4,width:y,height:4,fill:a,cornerRadius:2}),e.jsx(mre,{x:v+p,y:N+p,width:y-p*2,height:b-p*2,textColor:x,subTextColor:g,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)),b=y*.12;return e.jsxs(XE,{children:[e.jsx(Zk,{x:t-y,y:0,width:y,height:n,fill:r}),e.jsx(Zk,{x:t-y,y:0,width:4,height:n,fill:a}),e.jsx(mre,{x:t-y+b,y:n*.08,width:y-b*2,height:n*.84,textColor:x,subTextColor:g,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(XE,{children:[e.jsx(Zk,{x:0,y:0,width:t,height:m,fill:"#0a0a0a"}),e.jsx(Zk,{x:0,y:n-m,width:t,height:m,fill:"#0a0a0a"}),e.jsx(Zk,{x:0,y:n-m,width:t,height:3,fill:a}),e.jsx(mre,{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(Y9,{image:u,x:t-p-m*.7,y:p,height:m-p*2,width:m*.7})]}):null}function mre({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:x,railWidth:g}){if(x){const W=g??n,V=Math.min(n,W*.7),K=Math.max(14,W*.13),Q=Math.max(11,W*.085),J=W*.08,ce=W*.35;let ue=t;const ne=ue;ue+=V+J;const ee=ue,le=l.length>12?2:1;ue+=K*1.15*le+J*.5;const he=ue;m("phone")&&o&&(ue+=Q*1.3+J*.4);const ve=ue;m("email")&&c&&(ue+=Q*1.3+J*.4);const ge=ue+J*.5;return e.jsxs(XE,{children:[m("headshot")&&u&&e.jsx(XE,{clipFunc:p?fe=>{fe.beginPath(),fe.arc(s+n/2,ne+V/2,V/2,0,Math.PI*2),fe.closePath()}:void 0,children:e.jsx(Y9,{image:u,x:s+(n-V)/2,y:ne,width:V,height:V})}),m("name")&&l&&e.jsx(A7,{text:l,x:s,y:ee,width:n,align:"center",fontSize:K,fontStyle:"bold",fill:a}),m("phone")&&o&&e.jsx(A7,{text:o,x:s,y:he,width:n,align:"center",fontSize:Q,fill:i}),m("email")&&c&&e.jsx(A7,{text:c,x:s,y:ve,width:n,align:"center",fontSize:Q,fill:i,ellipsis:!0,wrap:"none"}),m("logo")&&h&&e.jsx(Y9,{image:h,x:s,y:ge,width:n,height:ce})]})}const y=r*.95,b=u&&m("headshot")?s+y+r*.18:s,v=n-(b-s)-(h&&m("logo")?r*1.6:0),N=Math.max(20,r*.34),C=Math.max(13,r*.22),A=r*.06,T=m("tagline")&&d?1:0,P=m("phone")&&o?1:0,M=m("email")&&c?1:0,I=1+T+(P||M?1:0),D=I*N+(I-1)*A;let q=t+(r-D)/2;return e.jsxs(XE,{children:[m("headshot")&&u&&e.jsx(XE,{clipFunc:p?W=>{W.beginPath(),W.arc(s+y/2,t+y/2,y/2,0,Math.PI*2),W.closePath()}:void 0,children:e.jsx(Y9,{image:u,x:s,y:t+(r-y)/2,width:y,height:y})}),m("name")&&l&&e.jsx(A7,{text:l,x:b,y:q,width:v,fontSize:N,fontStyle:"bold",fill:a,ellipsis:!0,wrap:"none"}),(q+=N+A,null),m("tagline")&&d&&e.jsxs(e.Fragment,{children:[e.jsx(A7,{text:d,x:b,y:q,width:v,fontSize:C*1.1,fontStyle:"italic",fill:i,ellipsis:!0,wrap:"none"}),(q+=C*1.1+A,null)]}),P||M?e.jsx(A7,{text:[o,c].filter(Boolean).join(" • "),x:b,y:q,width:v,fontSize:C,fill:i,ellipsis:!0,wrap:"none"}):null,m("logo")&&h&&e.jsx(Y9,{image:h,x:s+n-r*1.4,y:t+(r-r*.8)/2,width:r*1.4,height:r*.8})]})}function GBs(){const{data:s}=Lee(),t=(s==null?void 0:s.find(q=>q.is_default))??(s==null?void 0:s[0])??null,[n,r]=j.useState(void 0),a=(s==null?void 0:s.find(q=>q.id===n))??t,[i,l]=j.useState([]),[o,c]=j.useState(0),[d,u]=j.useState("minimal-stripe"),[h,m]=j.useState({}),[p,x]=j.useState(!1),g=j.useRef(null),[y,b]=j.useState(780),v=j.useRef(null),N=q=>{if(v.current&&(v.current.disconnect(),v.current=null),!q)return;const W=()=>{const K=q.clientWidth;K>0&&b(Math.min(780,K-16))};W();const V=new ResizeObserver(W);V.observe(q),v.current=V};j.useEffect(()=>()=>{var q;(q=v.current)==null||q.disconnect()},[]);const C=j.useRef(null),A=q=>{if(!q)return;const W=[];Array.from(q).forEach(V=>{V.type.startsWith("image/")&&W.push({id:crypto.randomUUID(),url:URL.createObjectURL(V),file:V,name:V.name})}),l(V=>[...V,...W])},T=q=>{l(W=>{const V=W.find(K=>K.id===q);return V&&URL.revokeObjectURL(V.url),W.filter(K=>K.id!==q)}),c(0)},P=typeof navigator<"u"&&/iPad|iPhone|iPod/.test(navigator.userAgent),M=q=>{var ce;const[W,V]=q.split(","),K=((ce=W.match(/:(.*?);/))==null?void 0:ce[1])??"image/jpeg",Q=atob(V),J=new Uint8Array(Q.length);for(let ue=0;ue{var q;if(C.current){x(!0);try{const W=C.current,V=W.toDataURL({pixelRatio:1/(W.scaleX()||1),mimeType:"image/jpeg",quality:.95}),Q=`${((q=i[o])==null?void 0:q.name.replace(/\.[^.]+$/,""))||"branded"}-branded.jpg`,J=M(V),ce=URL.createObjectURL(J);if(P)window.open(ce,"_blank")||(window.location.href=ce),ae.success('Long-press the image and tap "Save to Photos"');else{const ue=document.createElement("a");ue.href=ce,ue.download=Q,document.body.appendChild(ue),ue.click(),ue.remove(),ae.success("Image exported")}setTimeout(()=>URL.revokeObjectURL(ce),6e4)}catch(W){ae.error(W.message||"Export failed")}finally{x(!1)}}},D=async()=>{if(i.length){x(!0);try{const q=new zPt,W=i.length,V=o;for(let J=0;JsetTimeout(le,600)),!C.current)continue;const ce=C.current,ne=ce.toDataURL({pixelRatio:1/(ce.scaleX()||1),mimeType:"image/jpeg",quality:.95}).split(",")[1],ee=i[J].name.replace(/\.[^.]+$/,"")||`image-${J+1}`;q.file(`${ee}-branded.jpg`,ne,{base64:!0})}c(V);const K=await q.generateAsync({type:"blob"}),Q=document.createElement("a");Q.href=URL.createObjectURL(K),Q.download=`branded-images-${Date.now()}.zip`,Q.click(),URL.revokeObjectURL(Q.href),ae.success(`${W} images exported`)}catch(q){ae.error(q.message||"Batch export failed")}finally{x(!1)}}},B=i[o];return e.jsx(Ks,{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(Ul,{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(Wn,{to:"/marketing-studio",className:"text-sm text-muted-foreground inline-flex items-center gap-1 hover:underline",children:[e.jsx(ka,{className:"h-3 w-3"})," Marketing Studio"]}),e.jsx("h1",{className:"text-2xl md:text-3xl font-bold tracking-tight mt-1",children:"Branding Bar Studio"}),e.jsx("p",{className:"text-sm md:text-base text-muted-foreground",children:"Drop in any image, get a branded export. No AI credits used."})]}),e.jsx($,{variant:"outline",asChild:!0,className:"w-full sm:w-auto",children:e.jsxs(Wn,{to:"/marketing-studio/brand-kit",children:[e.jsx(Rc,{className:"h-4 w-4 mr-1"})," Brand Kit"]})})]}),!a&&e.jsx(_e,{className:"border-dashed border-amber-500/50 bg-amber-500/5",children:e.jsxs(Oe,{className:"py-5 flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"font-semibold",children:"Create your brand kit first"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"We'll pre-fill it from your profile so you can be exporting in seconds."})]}),e.jsx($,{asChild:!0,className:"w-full sm:w-auto",children:e.jsx(Wn,{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(_e,{className:"overflow-hidden",children:e.jsxs(Oe,{className:"p-4",children:[B?e.jsx("div",{ref:N,className:"flex justify-center bg-muted/30 rounded p-2 overflow-hidden",children:e.jsx(VBs,{imageUrl:B.url,preset:a,barStyleId:d,overrides:h,maxDisplayWidth:y,stageRef:C})}):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 q;return(q=g.current)==null?void 0:q.click()},onDragOver:q=>q.preventDefault(),onDrop:q=>{q.preventDefault(),A(q.dataTransfer.files)},children:[e.jsx(Jl,{className:"h-12 w-12 mx-auto text-muted-foreground/60"}),e.jsxs("div",{children:[e.jsx("h3",{className:"font-medium",children:"Drop images here or click to browse"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Add up to 50 photos at once. We'll batch-brand them all."})]}),e.jsxs($,{type:"button",children:[e.jsx(si,{className:"h-4 w-4 mr-1"})," Choose images"]})]}),e.jsx("input",{ref:g,type:"file",accept:"image/*",multiple:!0,hidden:!0,onChange:q=>A(q.target.files)})]})}),i.length>0&&e.jsx(_e,{className:"overflow-hidden",children:e.jsx(Oe,{className:"p-3",children:e.jsxs("div",{className:"flex gap-2 overflow-x-auto py-1",children:[i.map((q,W)=>e.jsxs("div",{className:"relative group flex-shrink-0",children:[e.jsx("button",{onClick:()=>c(W),className:`block h-16 w-16 rounded overflow-hidden border-2 transition-all ${W===o?"border-primary":"border-transparent hover:border-muted-foreground/30"}`,children:e.jsx("img",{src:q.url,alt:"",className:"h-full w-full object-cover"})}),e.jsx("button",{onClick:()=>T(q.id),className:"absolute -top-1 -right-1 bg-destructive text-destructive-foreground rounded-full p-0.5 opacity-0 group-hover:opacity-100 transition-opacity",children:e.jsx(pr,{className:"h-3 w-3"})})]},q.id)),e.jsx("button",{onClick:()=>{var q;return(q=g.current)==null?void 0:q.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(sn,{className:"h-5 w-5 text-muted-foreground"})})]})})}),i.length>0&&e.jsxs("div",{className:"flex flex-wrap gap-2 justify-end",children:[e.jsx($,{variant:"outline",onClick:()=>{i.forEach(q=>URL.revokeObjectURL(q.url)),l([])},children:"Clear all"}),e.jsxs($,{onClick:I,disabled:p||!B,children:[p?e.jsx(Ht,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(di,{className:"h-4 w-4 mr-1"}),"Download this image"]}),i.length>1&&e.jsxs($,{onClick:D,disabled:p,children:[p?e.jsx(Ht,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(di,{className:"h-4 w-4 mr-1"}),"Download all (",i.length,") as ZIP"]})]})]}),e.jsxs("div",{className:"space-y-4 min-w-0",children:[e.jsxs(_e,{className:"overflow-hidden",children:[e.jsx(Bt,{className:"pb-2",children:e.jsx(Ut,{className:"text-base",children:"Brand preset"})}),e.jsx(Oe,{children:e.jsxs(vs,{value:(a==null?void 0:a.id)??"",onValueChange:r,children:[e.jsx(gs,{children:e.jsx(bs,{placeholder:"Choose preset"})}),e.jsx(ys,{children:s==null?void 0:s.map(q=>e.jsxs(Ye,{value:q.id,children:[q.name," ",q.is_default?"(default)":""]},q.id))})]})})]}),e.jsxs(_e,{className:"overflow-hidden",children:[e.jsx(Bt,{className:"pb-2",children:e.jsx(Ut,{className:"text-base",children:"Bar style"})}),e.jsx(Oe,{children:e.jsx(g7s,{value:d,onChange:u,mediaType:"image"})})]}),e.jsxs(_e,{className:"overflow-hidden",children:[e.jsx(Bt,{className:"pb-2",children:e.jsx(Ut,{className:"text-base",children:"Tweak this design"})}),e.jsx(Oe,{children:e.jsxs(ua,{defaultValue:"text",children:[e.jsxs(ha,{className:"grid grid-cols-2 w-full",children:[e.jsx(Qt,{value:"text",children:"Text"}),e.jsx(Qt,{value:"colors",children:"Colors"})]}),e.jsxs(Jt,{value:"text",className:"space-y-3 pt-3",children:[e.jsxs("div",{children:[e.jsx(se,{children:"Display name"}),e.jsx(be,{value:h.display_name??(a==null?void 0:a.display_name)??"",onChange:q=>m({...h,display_name:q.target.value})})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Phone"}),e.jsx(be,{value:h.phone??(a==null?void 0:a.phone)??"",onChange:q=>m({...h,phone:q.target.value})})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Email"}),e.jsx(be,{value:h.email??(a==null?void 0:a.email)??"",onChange:q=>m({...h,email:q.target.value})})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Tagline"}),e.jsx(be,{value:h.tagline??(a==null?void 0:a.tagline)??"",onChange:q=>m({...h,tagline:q.target.value})})]})]}),e.jsxs(Jt,{value:"colors",className:"space-y-3 pt-3",children:[e.jsxs("div",{children:[e.jsx(se,{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:q=>m({...h,brand_color:q.target.value}),className:"h-10 w-14 rounded border cursor-pointer"}),e.jsx(be,{value:h.brand_color??(a==null?void 0:a.brand_color)??"#0f172a",onChange:q=>m({...h,brand_color:q.target.value})})]})]}),e.jsxs("div",{children:[e.jsx(se,{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:q=>m({...h,accent_color:q.target.value}),className:"h-10 w-14 rounded border cursor-pointer"}),e.jsx(be,{value:h.accent_color??(a==null?void 0:a.accent_color)??"#3b82f6",onChange:q=>m({...h,accent_color:q.target.value})})]})]}),e.jsx($,{variant:"ghost",size:"sm",onClick:()=>m({}),children:"Reset to preset"})]})]})})]})]})]})]})})}function WBs(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 KBs=(()=>{let s=0;const t=()=>`0000${(Math.random()*36**4<<0).toString(36)}`.slice(-4);return()=>(s+=1,`u${t()}${s}`)})();function UT(s){const t=[];for(let n=0,r=s.length;nh_||s.height>h_)&&(s.width>h_&&s.height>h_?s.width>s.height?(s.height*=h_/s.width,s.width=h_):(s.width*=h_/s.height,s.height=h_):s.width>h_?(s.height*=h_/s.width,s.width=h_):(s.width*=h_/s.height,s.height=h_))}function QSe(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 JBs(s){return Promise.resolve().then(()=>new XMLSerializer().serializeToString(s)).then(encodeURIComponent).then(t=>`data:image/svg+xml;charset=utf-8,${t}`)}async function e$s(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),JBs(a)}const Rb=(s,t)=>{if(s instanceof t)return!0;const n=Object.getPrototypeOf(s);return n===null?!1:n.constructor.name===t.name||Rb(n,t)};function t$s(s){const t=s.getPropertyValue("content");return`${s.cssText} content: '${t.replace(/'|"/g,"")}';`}function s$s(s,t){return EIt(t).map(n=>{const r=s.getPropertyValue(n),a=s.getPropertyPriority(n);return`${n}: ${r}${a?" !important":""};`}).join(" ")}function n$s(s,t,n,r){const a=`.${s}:${t}`,i=n.cssText?t$s(n):s$s(n,r);return document.createTextNode(`${a}{${i}}`)}function Ydt(s,t,n,r){const a=window.getComputedStyle(s,n),i=a.getPropertyValue("content");if(i===""||i==="none")return;const l=KBs();try{t.className=`${t.className} ${l}`}catch{return}const o=document.createElement("style");o.appendChild(n$s(l,n,a,r)),t.appendChild(o)}function r$s(s,t,n){Ydt(s,t,":before",n),Ydt(s,t,":after",n)}const Zdt="application/font-woff",Xdt="image/jpeg",a$s={woff:Zdt,woff2:Zdt,ttf:"application/font-truetype",eot:"application/vnd.ms-fontobject",png:"image/png",jpg:Xdt,jpeg:Xdt,gif:"image/gif",tiff:"image/tiff",svg:"image/svg+xml",webp:"image/webp"};function i$s(s){const t=/\.([^./]*?)$/g.exec(s);return t?t[1]:""}function IWe(s){const t=i$s(s).toLowerCase();return a$s[t]||""}function o$s(s){return s.split(/,/)[1]}function u9e(s){return s.search(/^(data:)/)!==-1}function l$s(s,t){return`data:${t};base64,${s}`}async function MIt(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 yIe={};function c$s(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 DWe(s,t,n){const r=c$s(s,t,n.includeQueryParams);if(yIe[r]!=null)return yIe[r];n.cacheBust&&(s+=(/\?/.test(s)?"&":"?")+new Date().getTime());let a;try{const i=await MIt(s,n.fetchRequestInit,({res:l,result:o})=>(t||(t=l.headers.get("Content-Type")||""),o$s(o)));a=l$s(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 yIe[r]=a,a}async function d$s(s){const t=s.toDataURL();return t==="data:,"?s.cloneNode(!1):QSe(t)}async function u$s(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 QSe(o)}const n=s.poster,r=IWe(n),a=await DWe(n,r,t);return QSe(a)}async function h$s(s,t){var n;try{if(!((n=s==null?void 0:s.contentDocument)===null||n===void 0)&&n.body)return await EAe(s.contentDocument.body,t,!0)}catch{}return s.cloneNode(!1)}async function m$s(s,t){return Rb(s,HTMLCanvasElement)?d$s(s):Rb(s,HTMLVideoElement)?u$s(s,t):Rb(s,HTMLIFrameElement)?h$s(s,t):s.cloneNode(LIt(s))}const p$s=s=>s.tagName!=null&&s.tagName.toUpperCase()==="SLOT",LIt=s=>s.tagName!=null&&s.tagName.toUpperCase()==="SVG";async function f$s(s,t,n){var r,a;if(LIt(t))return t;let i=[];return p$s(s)&&s.assignedNodes?i=UT(s.assignedNodes()):Rb(s,HTMLIFrameElement)&&(!((r=s.contentDocument)===null||r===void 0)&&r.body)?i=UT(s.contentDocument.body.childNodes):i=UT(((a=s.shadowRoot)!==null&&a!==void 0?a:s).childNodes),i.length===0||Rb(s,HTMLVideoElement)||await i.reduce((l,o)=>l.then(()=>EAe(o,n)).then(c=>{c&&t.appendChild(c)}),Promise.resolve()),t}function x$s(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):EIt(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`),Rb(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 g$s(s,t){Rb(s,HTMLTextAreaElement)&&(t.innerHTML=s.value),Rb(s,HTMLInputElement)&&t.setAttribute("value",s.value)}function y$s(s,t){if(Rb(s,HTMLSelectElement)){const n=t,r=Array.from(n.children).find(a=>s.value===a.getAttribute("value"));r&&r.setAttribute("selected","")}}function v$s(s,t,n){return Rb(t,Element)&&(x$s(s,t,n),r$s(s,t,n),g$s(s,t),y$s(s,t)),t}async function b$s(s,t){const n=s.querySelectorAll?s.querySelectorAll("use"):[];if(n.length===0)return s;const r={};for(let i=0;im$s(r,t)).then(r=>f$s(s,r,t)).then(r=>v$s(s,r,t)).then(r=>b$s(r,t))}const PIt=/url\((['"]?)([^'"]+?)\1\)/g,_$s=/url\([^)]+\)\s*format\((["']?)([^"']+)\1\)/g,w$s=/src:\s*(?:url\([^)]+\)\s*format\([^)]+\)[,;]\s*)+/g;function j$s(s){const t=s.replace(/([.*+?^${}()|\[\]\/\\])/g,"\\$1");return new RegExp(`(url\\(['"]?)(${t})(['"]?\\))`,"g")}function N$s(s){const t=[];return s.replace(PIt,(n,r,a)=>(t.push(a),n)),t.filter(n=>!u9e(n))}async function k$s(s,t,n,r,a){try{const i=n?WBs(t,n):t,l=IWe(t);let o;return a||(o=await DWe(i,l,r)),s.replace(j$s(t),`$1${o}$3`)}catch{}return s}function S$s(s,{preferredFontFormat:t}){return t?s.replace(w$s,n=>{for(;;){const[r,,a]=_$s.exec(n)||[];if(!a)return"";if(a===t)return`src: ${r};`}}):s}function IIt(s){return s.search(PIt)!==-1}async function DIt(s,t,n){if(!IIt(s))return s;const r=S$s(s,n);return N$s(r).reduce((i,l)=>i.then(o=>k$s(o,l,t,n)),Promise.resolve(r))}async function T7(s,t,n){var r;const a=(r=t.style)===null||r===void 0?void 0:r.getPropertyValue(s);if(a){const i=await DIt(a,null,n);return t.style.setProperty(s,i,t.style.getPropertyPriority(s)),!0}return!1}async function C$s(s,t){await T7("background",s,t)||await T7("background-image",s,t),await T7("mask",s,t)||await T7("-webkit-mask",s,t)||await T7("mask-image",s,t)||await T7("-webkit-mask-image",s,t)}async function A$s(s,t){const n=Rb(s,HTMLImageElement);if(!(n&&!u9e(s.src))&&!(Rb(s,SVGImageElement)&&!u9e(s.href.baseVal)))return;const r=n?s.src:s.href.baseVal,a=await DWe(r,IWe(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 E$s(s,t){const r=UT(s.childNodes).map(a=>RIt(a,t));await Promise.all(r).then(()=>s)}async function RIt(s,t){Rb(s,Element)&&(await C$s(s,t),await A$s(s,t),await E$s(s,t))}function T$s(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 Qdt={};async function Jdt(s){let t=Qdt[s];if(t!=null)return t;const r=await(await fetch(s)).text();return t={url:s,cssText:r},Qdt[s]=t,t}async function eut(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),MIt(o,t.fetchRequestInit,({result:c})=>(n=n.replace(l,`url(${c})`),[l,c]))});return Promise.all(i).then(()=>n)}function tut(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 M$s(s,t){const n=[],r=[];return s.forEach(a=>{if("cssRules"in a)try{UT(a.cssRules||[]).forEach((i,l)=>{if(i.type===CSSRule.IMPORT_RULE){let o=l+1;const c=i.href,d=Jdt(c).then(u=>eut(u,t)).then(u=>tut(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(Jdt(a.href).then(o=>eut(o,t)).then(o=>tut(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{UT(a.cssRules||[]).forEach(i=>{n.push(i)})}catch(i){console.error(`Error while reading CSS rules from ${a.href}`,i)}}),n))}function L$s(s){return s.filter(t=>t.type===CSSRule.FONT_FACE_RULE).filter(t=>IIt(t.style.getPropertyValue("src")))}async function P$s(s,t){if(s.ownerDocument==null)throw new Error("Provided element is not within a Document");const n=UT(s.ownerDocument.styleSheets),r=await M$s(n,t);return L$s(r)}function OIt(s){return s.trim().replace(/["']/g,"")}function I$s(s){const t=new Set;function n(r){(r.style.fontFamily||getComputedStyle(r).fontFamily).split(",").forEach(i=>{t.add(OIt(i))}),Array.from(r.children).forEach(i=>{i instanceof HTMLElement&&n(i)})}return n(s),t}async function D$s(s,t){const n=await P$s(s,t),r=I$s(s);return(await Promise.all(n.filter(i=>r.has(OIt(i.style.fontFamily))).map(i=>{const l=i.parentStyleSheet?i.parentStyleSheet.href:null;return DIt(i.cssText,l,t)}))).join(` `)}async function R$s(s,t){const n=t.fontEmbedCSS!=null?t.fontEmbedCSS:t.skipFonts?null:await D$s(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 FIt(s,t={}){const{width:n,height:r}=TIt(s,t),a=await EAe(s,t,!0);return await R$s(a,t),await RIt(a,t),T$s(a,t),await e$s(a,n,r)}async function zIt(s,t={}){const{width:n,height:r}=TIt(s,t),a=await FIt(s,t),i=await QSe(a),l=document.createElement("canvas"),o=l.getContext("2d"),c=t.pixelRatio||XBs(),d=t.canvasWidth||n,u=t.canvasHeight||r;return l.width=d*c,l.height=u*c,t.skipAutoScale||QBs(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 hU(s,t={}){return(await zIt(s,t)).toDataURL()}const BIt=Object.freeze(Object.defineProperty({__proto__:null,toCanvas:zIt,toPng:hU,toSvg:FIt},Symbol.toStringTag,{value:"Module"})),mU=s=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(s),TAe={"just-listed":"JUST LISTED","just-sold":"JUST SOLD","open-house":"OPEN HOUSE","price-drop":"PRICE DROP"},QE={"instagram-square":{width:1080,height:1080},"instagram-story":{width:1080,height:1920},"facebook-post":{width:1200,height:630}},O$s=({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})]})]}),RWe=It.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=TAe[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:mU(s.price)}),t==="just-sold"&&s.soldPrice&&e.jsxs("div",{style:{fontSize:l.w*.028,color:"#C9A84C",marginBottom:l.w*.01},children:["Sold for ",mU(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(O$s,{branding:r,dim:l})]})]})]})});RWe.displayName="LuxuryDarkTemplate";const F$s=({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})]})]}),OWe=It.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=TAe[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:mU(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(F$s,{branding:r,dim:l,accentColor:m})]})]})});OWe.displayName="ModernCleanTemplate";const z$s=({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})]})]}),FWe=It.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=TAe[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:mU(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(z$s,{branding:r,dim:l})]})]})]})});FWe.displayName="BoldColorfulTemplate";const B$s=({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})]})]}),zWe=It.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=TAe[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:mU(s.price)}),t==="just-sold"&&s.soldPrice&&e.jsxs("div",{style:{fontSize:l.w*.02,color:"#8B7355",marginBottom:l.w*.01},children:["Sold: ",mU(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(B$s,{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"}})]})]})})});zWe.displayName="EditorialTemplate";const $$s=[{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:"📉"}],sut=[{value:"instagram-square",label:"IG Post",dimensions:"1080×1080",icon:e.jsx(Qh,{className:"h-4 w-4"})},{value:"instagram-story",label:"IG Story",dimensions:"1080×1920",icon:e.jsx(Qh,{className:"h-4 w-4"})},{value:"facebook-post",label:"Facebook",dimensions:"1200×630",icon:e.jsx(jf,{className:"h-4 w-4"})}],U$s=[{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:"📰"}],nut={"luxury-dark":RWe,"modern-clean":OWe,"bold-colorful":FWe,editorial:zWe},vIe=s=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(s);function q$s(s){var l;const[t,n]=s.split(","),r=((l=t.match(/:(.*?);/))==null?void 0:l[1])||"image/png",a=atob(n),i=new Uint8Array(a.length);for(let o=0;oEe.is_default))??(s==null?void 0:s[0])??null,[n,r]=j.useState(void 0),a=(s==null?void 0:s.find(Ee=>Ee.id===n))??t,i=Za(),[l,o]=j.useState("mine"),[c,d]=j.useState(""),[u,h]=j.useState("address"),[m,p]=j.useState(!1),[x,g]=j.useState([]),[y,b]=j.useState(null),[v,N]=j.useState(0),[C,A]=j.useState("just-listed"),[T,P]=j.useState(["instagram-square"]),[M,I]=j.useState("luxury-dark"),[D,B]=j.useState(!0),[q,W]=j.useState(!1),[V,K]=j.useState([]),[Q,J]=j.useState("search"),ce=j.useRef({}),{data:ue=[],isLoading:ne}=ht({queryKey:["marketing-studio-my-listings",i],enabled:!!i,queryFn:async()=>{const{data:Ee,error:Me}=await U.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(Me)throw Me;return(Ee||[]).map(De=>{const ze=(De.listing_photos||[]).slice().sort((Xe,Se)=>(Se.is_primary?1:0)-(Xe.is_primary?1:0)||(Xe.sort_order??0)-(Se.sort_order??0)).map(Xe=>Xe.photo_url).filter(Boolean),ke=String(De.status||"");return{mlsNumber:De.id,address:De.property_address||"",city:De.city||"",state:De.state||"",zip:"",price:Number(De.price||0),status:ke,bedrooms:Number(De.bedrooms||0),bathrooms:Number(De.bathrooms||0),sqft:Number(De.square_footage||0),lotSize:"",yearBuilt:De.year_built??null,propertyType:De.property_type||"",description:De.description||"",photos:ze,listDate:De.created_at,soldDate:ke.toLowerCase().includes("sold")?De.created_at:null,soldPrice:null,agent:{name:"",office:""}}})}}),ee=j.useMemo(()=>!D||!a?{enabled:!1}:{enabled:!0,agentName:a.display_name||"",brokerage:a.tagline||"",agentPhotoUrl:a.headshot_url||void 0},[D,a]),le=async()=>{if(c.trim()){p(!0),g([]);try{const{data:Ee,error:Me}=await U.functions.invoke("repliers-mls-search",{body:{searchType:u,query:c.trim()}});if(Me)throw Me;if(Ee!=null&&Ee.error)throw new Error(Ee.error);g((Ee==null?void 0:Ee.listings)||[]),((Ee==null?void 0:Ee.listings)||[]).length===0&&ae.info("No listings found. Try a different search.")}catch(Ee){ae.error(Ee.message||"Search failed")}finally{p(!1)}}},he=Ee=>{var Me;b(Ee),N(0),J("customize"),Ee.soldDate||(Me=Ee.status)!=null&&Me.toLowerCase().includes("sold")?A("just-sold"):A("just-listed")},ve=Ee=>P(Me=>Me.includes(Ee)?Me.filter(De=>De!==Ee):[...Me,Ee]),ge=y?{listing:y,postType:C,format:"instagram-square",branding:ee,selectedPhotoIndex:v}:null,fe=j.useCallback(async()=>{if(!(!y||T.length===0)){W(!0),K([]),J("generate");try{await new Promise(Me=>setTimeout(Me,600));const Ee=[];for(const Me of T){const De=`${M}-${Me}`,ze=ce.current[De];if(!ze)continue;const ke=QE[Me],Xe=await hU(ze,{width:ke.width,height:ke.height,pixelRatio:1,cacheBust:!0,style:{transform:"none",transformOrigin:"top left"}});Ee.push({format:Me,url:Xe})}K(Ee),ae.success(`Generated ${Ee.length} design${Ee.length>1?"s":""}!`)}catch(Ee){ae.error(Ee.message||"Generation failed")}finally{W(!1)}}},[y,T,M]),je=(Ee,Me)=>{const De=`${((y==null?void 0:y.address)||"listing").replace(/\s+/g,"-")}-${C}-${Me}.png`;try{const ze=q$s(Ee),ke=URL.createObjectURL(ze);if(V$s)window.open(ke,"_blank"),ae.message("Long-press the image to save to Photos");else{const Xe=document.createElement("a");Xe.href=ke,Xe.download=De,document.body.appendChild(Xe),Xe.click(),document.body.removeChild(Xe)}setTimeout(()=>URL.revokeObjectURL(ke),6e4)}catch{const ze=document.createElement("a");ze.href=Ee,ze.download=De,ze.click()}};return j.useEffect(()=>{!n&&t&&r(t.id)},[t,n]),e.jsx(Ks,{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(Ul,{children:[e.jsx("title",{children:"Listing Templates | Marketing Studio"}),e.jsx("meta",{name:"description",content:"Just Listed, Just Sold, Open House and Price Drop templates pulled directly from your MLS."})]}),e.jsx("div",{className:"flex items-center gap-2",children:e.jsx($,{variant:"ghost",size:"sm",asChild:!0,children:e.jsxs(Wn,{to:"/marketing-studio",children:[e.jsx(ka,{className:"h-4 w-4 mr-1"})," Marketing Studio"]})})}),e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-end sm:justify-between gap-3",children:[e.jsxs("div",{children:[e.jsxs($e,{variant:"secondary",className:"mb-2 gap-1",children:[e.jsx(dn,{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(se,{className:"text-xs text-muted-foreground",children:"Brand preset"}),e.jsxs(vs,{value:n,onValueChange:r,children:[e.jsx(gs,{children:e.jsx(bs,{placeholder:"Default"})}),e.jsx(ys,{children:s.map(Ee=>e.jsxs(Ye,{value:Ee.id,children:[Ee.name,Ee.is_default?" (default)":""]},Ee.id))})]})]})]}),e.jsxs("div",{className:"flex items-center gap-1.5 text-xs sm:text-sm overflow-x-auto -mx-1 px-1 pb-1",children:[e.jsxs("button",{onClick:()=>J("search"),className:`flex items-center gap-1.5 px-3 py-1.5 rounded-full whitespace-nowrap ${Q==="search"?"bg-primary text-primary-foreground":"bg-muted text-muted-foreground"}`,children:[e.jsx(Vr,{className:"h-3.5 w-3.5"})," 1. Find listing"]}),e.jsx(Ja,{className:"h-4 w-4 text-muted-foreground shrink-0"}),e.jsxs("button",{onClick:()=>y&&J("customize"),disabled:!y,className:`flex items-center gap-1.5 px-3 py-1.5 rounded-full whitespace-nowrap ${Q==="customize"?"bg-primary text-primary-foreground":y?"bg-muted text-muted-foreground":"bg-muted text-muted-foreground/50"}`,children:[e.jsx(dn,{className:"h-3.5 w-3.5"})," 2. Customize"]}),e.jsx(Ja,{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 ${Q==="generate"?"bg-primary text-primary-foreground":"bg-muted text-muted-foreground/50"}`,children:[e.jsx(di,{className:"h-3.5 w-3.5"})," 3. Download"]})]}),Q==="search"&&e.jsxs("div",{className:"space-y-4",children:[e.jsx(ua,{value:l,onValueChange:Ee=>o(Ee),children:e.jsxs(ha,{className:"grid grid-cols-2 w-full sm:w-auto",children:[e.jsxs(Qt,{value:"mine",children:[e.jsx(sa,{className:"h-4 w-4 mr-1.5"})," My Listings"]}),e.jsxs(Qt,{value:"mls",children:[e.jsx(Vr,{className:"h-4 w-4 mr-1.5"})," MLS Search"]})]})}),l==="mine"&&e.jsx("div",{className:"space-y-3",children:ne?e.jsx(_e,{children:e.jsx(Oe,{className:"py-12 flex items-center justify-center",children:e.jsx(Ht,{className:"h-6 w-6 animate-spin text-muted-foreground"})})}):ue.length===0?e.jsx(_e,{children:e.jsxs(Oe,{className:"py-10 text-center space-y-2",children:[e.jsx(sa,{className:"h-10 w-10 mx-auto text-muted-foreground/40"}),e.jsx("p",{className:"text-sm font-medium",children:"No listings yet"}),e.jsx("p",{className:"text-xs text-muted-foreground max-w-sm mx-auto",children:"Add a listing to your Listing Exchange first, and it'll show up here ready to brand."}),e.jsx($,{variant:"outline",size:"sm",asChild:!0,className:"mt-2",children:e.jsx(Wn,{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((Ee,Me)=>{var De;return e.jsx(_e,{className:"cursor-pointer hover:border-primary/50 hover:shadow-md transition-all group overflow-hidden",onClick:()=>he(Ee),children:e.jsx(Oe,{className:"p-0",children:e.jsxs("div",{className:"flex",children:[e.jsx("div",{className:"w-28 h-28 sm:w-32 sm:h-28 flex-shrink-0 bg-muted overflow-hidden",children:(De=Ee.photos)!=null&&De[0]?e.jsx("img",{src:Ee.photos[0],alt:Ee.address,className:"w-full h-full object-cover group-hover:scale-105 transition-transform"}):e.jsx("div",{className:"w-full h-full flex items-center justify-center",children:e.jsx(sa,{className:"h-8 w-8 text-muted-foreground/40"})})}),e.jsxs("div",{className:"flex-1 p-3 min-w-0",children:[e.jsx("p",{className:"font-bold",children:Ee.price>0?vIe(Ee.price):"—"}),e.jsx("p",{className:"text-sm text-muted-foreground truncate",children:Ee.address}),e.jsxs("p",{className:"text-xs text-muted-foreground truncate",children:[Ee.city,Ee.state?`, ${Ee.state}`:""]}),e.jsxs("div",{className:"flex items-center gap-3 mt-1.5 text-xs text-muted-foreground",children:[Ee.bedrooms>0&&e.jsxs("span",{className:"flex items-center gap-0.5",children:[e.jsx(JS,{className:"h-3 w-3"})," ",Ee.bedrooms]}),Ee.bathrooms>0&&e.jsxs("span",{className:"flex items-center gap-0.5",children:[e.jsx(_g,{className:"h-3 w-3"})," ",Ee.bathrooms]}),Ee.sqft>0&&e.jsxs("span",{className:"flex items-center gap-0.5",children:[e.jsx(_R,{className:"h-3 w-3"})," ",Ee.sqft.toLocaleString()]})]}),Ee.status&&e.jsx("div",{className:"flex items-center gap-2 mt-1 flex-wrap",children:e.jsx($e,{variant:"outline",className:"text-[10px]",children:Ee.status})})]})]})})},Ee.mlsNumber||Me)})})]})}),l==="mls"&&e.jsxs(e.Fragment,{children:[e.jsxs(_e,{className:"overflow-hidden",children:[e.jsxs(Bt,{children:[e.jsxs(Ut,{className:"flex items-center gap-2 text-base md:text-lg",children:[e.jsx(Vr,{className:"h-5 w-5 text-primary"})," Search MLS"]}),e.jsxs(vr,{children:["Search by address or MLS number. Requires an MLS data connection — if your account doesn't have one, use ",e.jsx("button",{type:"button",className:"underline",onClick:()=>o("mine"),children:"My Listings"})," instead."]})]}),e.jsxs(Oe,{className:"space-y-3",children:[e.jsx(ua,{value:u,onValueChange:Ee=>h(Ee),children:e.jsxs(ha,{children:[e.jsxs(Qt,{value:"address",children:[e.jsx(ai,{className:"h-4 w-4 mr-1.5"})," Address"]}),e.jsxs(Qt,{value:"mls",children:[e.jsx(Up,{className:"h-4 w-4 mr-1.5"})," MLS #"]})]})}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-2",children:[e.jsx(be,{value:c,onChange:Ee=>d(Ee.target.value),placeholder:u==="mls"?"Enter MLS number...":"Enter property address...",className:"flex-1",onKeyDown:Ee=>Ee.key==="Enter"&&le()}),e.jsxs($,{onClick:le,disabled:m||!c.trim(),className:"sm:w-auto w-full",children:[m?e.jsx(Ht,{className:"h-4 w-4 animate-spin mr-1.5"}):e.jsx(Vr,{className:"h-4 w-4 mr-1.5"})," Search"]})]})]})]}),x.length>0&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("h3",{className:"text-sm font-medium text-muted-foreground",children:[x.length," listing",x.length!==1?"s":""," found"]}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3",children:x.map((Ee,Me)=>{var De;return e.jsx(_e,{className:"cursor-pointer hover:border-primary/50 hover:shadow-md transition-all group overflow-hidden",onClick:()=>he(Ee),children:e.jsx(Oe,{className:"p-0",children:e.jsxs("div",{className:"flex",children:[e.jsx("div",{className:"w-28 h-28 sm:w-32 sm:h-28 flex-shrink-0 bg-muted overflow-hidden",children:(De=Ee.photos)!=null&&De[0]?e.jsx("img",{src:Ee.photos[0],alt:Ee.address,className:"w-full h-full object-cover group-hover:scale-105 transition-transform"}):e.jsx("div",{className:"w-full h-full flex items-center justify-center",children:e.jsx(sa,{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:vIe(Ee.price)}),e.jsx("p",{className:"text-sm text-muted-foreground truncate",children:Ee.address}),e.jsxs("p",{className:"text-xs text-muted-foreground truncate",children:[Ee.city,", ",Ee.state," ",Ee.zip]}),e.jsxs("div",{className:"flex items-center gap-3 mt-1.5 text-xs text-muted-foreground",children:[Ee.bedrooms>0&&e.jsxs("span",{className:"flex items-center gap-0.5",children:[e.jsx(JS,{className:"h-3 w-3"})," ",Ee.bedrooms]}),Ee.bathrooms>0&&e.jsxs("span",{className:"flex items-center gap-0.5",children:[e.jsx(_g,{className:"h-3 w-3"})," ",Ee.bathrooms]}),Ee.sqft>0&&e.jsxs("span",{className:"flex items-center gap-0.5",children:[e.jsx(_R,{className:"h-3 w-3"})," ",Ee.sqft.toLocaleString()]})]}),e.jsxs("div",{className:"flex items-center gap-2 mt-1 flex-wrap",children:[Ee.mlsNumber&&e.jsx($e,{variant:"outline",className:"text-[10px]",children:Ee.mlsNumber}),Ee.status&&e.jsx($e,{variant:"outline",className:"text-[10px]",children:Ee.status})]})]})]})})},Ee.mlsNumber||Me)})})]})]})]}),Q==="customize"&&y&&ge&&e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-3 gap-4 md:gap-6",children:[e.jsxs(_e,{className:"lg:col-span-1 overflow-hidden min-w-0",children:[e.jsx(Bt,{className:"pb-3",children:e.jsx(Ut,{className:"text-base",children:"Selected listing"})}),e.jsxs(Oe,{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[v],alt:"",className:"w-full h-full object-cover"})}),y.photos.length>1&&e.jsxs("div",{className:"flex items-center justify-between mt-2",children:[e.jsx($,{variant:"outline",size:"icon",className:"h-7 w-7",onClick:()=>N(Ee=>Math.max(0,Ee-1)),disabled:v===0,children:e.jsx(Ic,{className:"h-4 w-4"})}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:[v+1," of ",y.photos.length]}),e.jsx($,{variant:"outline",size:"icon",className:"h-7 w-7",onClick:()=>N(Ee=>Math.min(y.photos.length-1,Ee+1)),disabled:v===y.photos.length-1,children:e.jsx(Ja,{className:"h-4 w-4"})})]})]}),e.jsxs("div",{children:[e.jsx("p",{className:"font-bold text-lg",children:vIe(y.price)}),e.jsx("p",{className:"text-sm text-muted-foreground",children:y.address}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[y.city,", ",y.state," ",y.zip]})]}),e.jsxs("div",{className:"grid grid-cols-3 gap-2 text-center",children:[y.bedrooms>0&&e.jsxs("div",{className:"bg-muted/50 rounded-lg p-2",children:[e.jsx("p",{className:"text-sm font-semibold",children:y.bedrooms}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:"Beds"})]}),y.bathrooms>0&&e.jsxs("div",{className:"bg-muted/50 rounded-lg p-2",children:[e.jsx("p",{className:"text-sm font-semibold",children:y.bathrooms}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:"Baths"})]}),y.sqft>0&&e.jsxs("div",{className:"bg-muted/50 rounded-lg p-2",children:[e.jsx("p",{className:"text-sm font-semibold",children:y.sqft.toLocaleString()}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:"Sq Ft"})]})]}),e.jsxs($,{variant:"outline",size:"sm",className:"w-full",onClick:()=>{J("search"),b(null)},children:[e.jsx(Ih,{className:"h-3.5 w-3.5 mr-1.5"})," Choose different listing"]})]})]}),e.jsxs(_e,{className:"lg:col-span-2 overflow-hidden min-w-0",children:[e.jsxs(Bt,{children:[e.jsxs(Ut,{className:"flex items-center gap-2 text-base",children:[e.jsx(dn,{className:"h-5 w-5 text-primary"})," Customize"]}),e.jsx(vr,{children:"Pick a template, post type, and output format."})]}),e.jsxs(Oe,{className:"space-y-5",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs(se,{className:"text-sm font-medium flex items-center gap-2",children:[e.jsx(Rc,{className:"h-4 w-4"})," Template style"]}),e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-2",children:U$s.map(Ee=>e.jsxs("button",{onClick:()=>I(Ee.value),className:`flex flex-col items-center gap-1 px-2 py-3 rounded-lg border-2 transition-all text-center ${M===Ee.value?"border-primary bg-primary/5":"border-border hover:border-primary/30"}`,children:[e.jsx("span",{className:"text-2xl",children:Ee.preview}),e.jsx("span",{className:"text-sm font-medium",children:Ee.label}),e.jsx("span",{className:"text-[10px] text-muted-foreground leading-tight",children:Ee.description})]},Ee.value))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{className:"text-sm font-medium",children:"Post type"}),e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-2",children:$$s.map(Ee=>e.jsxs("button",{onClick:()=>A(Ee.value),className:`flex items-center justify-center gap-2 px-3 py-2.5 rounded-lg border-2 transition-all text-sm font-medium ${C===Ee.value?"border-primary bg-primary/5":"border-border hover:border-primary/30"}`,children:[e.jsx("span",{className:"text-lg",children:Ee.icon})," ",e.jsx("span",{className:"truncate",children:Ee.label})]},Ee.value))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{className:"text-sm font-medium",children:"Output formats"}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-2",children:sut.map(Ee=>e.jsxs("button",{onClick:()=>ve(Ee.value),className:`flex items-center gap-2 px-3 py-2.5 rounded-lg border-2 transition-all text-sm ${T.includes(Ee.value)?"border-primary bg-primary/5":"border-border hover:border-primary/30"}`,children:[Ee.icon,e.jsxs("div",{className:"text-left min-w-0",children:[e.jsx("p",{className:"font-medium truncate",children:Ee.label}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:Ee.dimensions})]})]},Ee.value))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(se,{className:"text-sm font-medium flex items-center gap-2",children:[e.jsx(Lo,{className:"h-4 w-4"})," Show my branding"]}),e.jsx(Tn,{checked:D,onCheckedChange:B})]}),D&&!a&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:["No brand preset yet. ",e.jsx(Wn,{to:"/marketing-studio/brand-kit",className:"underline",children:"Create one"})," to add your headshot and name."]}),D&&a&&e.jsxs("div",{className:"flex items-center gap-3 p-3 rounded-lg border bg-muted/30",children:[a.headshot_url&&e.jsx("img",{src:a.headshot_url,alt:"",className:"w-10 h-10 rounded-full object-cover border"}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-sm font-medium truncate",children:a.display_name||"Unnamed agent"}),e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:a.tagline||a.email||""})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{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*(QE[T[0]||"instagram-square"].height/QE[T[0]||"instagram-square"].width)},children:(()=>{const Ee=nut[M],Me=T[0]||"instagram-square";return e.jsx(Ee,{...ge,format:Me})})()})})]}),e.jsx($,{onClick:fe,disabled:T.length===0||q,size:"lg",className:"w-full gap-2",children:q?e.jsxs(e.Fragment,{children:[e.jsx(Ht,{className:"h-5 w-5 animate-spin"})," Generating..."]}):e.jsxs(e.Fragment,{children:[e.jsx(dn,{className:"h-5 w-5"})," Generate ",T.length," design",T.length>1?"s":""]})})]})]})]}),Q==="generate"&&e.jsxs("div",{className:"space-y-4",children:[q&&e.jsx(_e,{children:e.jsxs(Oe,{className:"flex flex-col items-center justify-center py-16",children:[e.jsx(Ht,{className:"h-12 w-12 animate-spin text-primary mb-3"}),e.jsx("p",{className:"text-base font-medium",children:"Rendering your designs..."}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:"High-resolution PNGs, no AI credits used."})]})}),V.length>0&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center justify-between flex-wrap gap-2",children:[e.jsx("h3",{className:"text-lg font-semibold",children:"Your designs"}),e.jsxs($,{variant:"outline",size:"sm",onClick:()=>J("customize"),children:[e.jsx(Ih,{className:"h-3.5 w-3.5 mr-1.5"})," Tweak & regenerate"]})]}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:V.map((Ee,Me)=>{const De=sut.find(ze=>ze.value===Ee.format);return e.jsxs(_e,{className:"overflow-hidden",children:[e.jsx("div",{className:"bg-muted/30 p-1",children:e.jsx("img",{src:Ee.url,alt:"",className:"w-full rounded"})}),e.jsxs(Oe,{className:"p-3 space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[De==null?void 0:De.icon,e.jsx("span",{className:"text-sm font-medium",children:De==null?void 0:De.label})]}),e.jsx($e,{variant:"outline",className:"text-[10px]",children:De==null?void 0:De.dimensions})]}),e.jsxs($,{size:"sm",className:"w-full gap-1.5",onClick:()=>je(Ee.url,Ee.format),children:[e.jsx(di,{className:"h-3.5 w-3.5"})," Download"]})]})]},Me)})})]})]}),Q==="generate"&&y&&ge&&e.jsx("div",{style:{position:"fixed",left:"-99999px",top:0,pointerEvents:"none"},"aria-hidden":!0,children:T.map(Ee=>{const Me=nut[M],De=QE[Ee];return e.jsx("div",{style:{width:De.width,height:De.height},children:e.jsx(Me,{ref:ze=>{ce.current[`${M}-${Ee}`]=ze},...ge,format:Ee})},`${M}-${Ee}`)})})]})})}var $It="Toggle",BWe=j.forwardRef((s,t)=>{const{pressed:n,defaultPressed:r,onPressedChange:a,...i}=s,[l,o]=Ux({prop:n,onChange:a,defaultProp:r??!1,caller:$It});return e.jsx(Ka.button,{type:"button","aria-pressed":l,"data-state":l?"on":"off","data-disabled":s.disabled?"":void 0,...i,ref:t,onClick:xa(s.onClick,()=>{s.disabled||o(!l)})})});BWe.displayName=$It;var UIt=BWe,V6="ToggleGroup",[qIt,hQn]=ip(V6,[k6]),VIt=k6(),$We=It.forwardRef((s,t)=>{const{type:n,...r}=s;if(n==="single"){const a=r;return e.jsx(G$s,{...a,ref:t})}if(n==="multiple"){const a=r;return e.jsx(W$s,{...a,ref:t})}throw new Error(`Missing prop \`type\` expected on \`${V6}\``)});$We.displayName=V6;var[HIt,GIt]=qIt(V6),G$s=It.forwardRef((s,t)=>{const{value:n,defaultValue:r,onValueChange:a=()=>{},...i}=s,[l,o]=Ux({prop:n,defaultProp:r??"",onChange:a,caller:V6});return e.jsx(HIt,{scope:s.__scopeToggleGroup,type:"single",value:It.useMemo(()=>l?[l]:[],[l]),onItemActivate:o,onItemDeactivate:It.useCallback(()=>o(""),[o]),children:e.jsx(WIt,{...i,ref:t})})}),W$s=It.forwardRef((s,t)=>{const{value:n,defaultValue:r,onValueChange:a=()=>{},...i}=s,[l,o]=Ux({prop:n,defaultProp:r??[],onChange:a,caller:V6}),c=It.useCallback(u=>o((h=[])=>[...h,u]),[o]),d=It.useCallback(u=>o((h=[])=>h.filter(m=>m!==u)),[o]);return e.jsx(HIt,{scope:s.__scopeToggleGroup,type:"multiple",value:l,onItemActivate:c,onItemDeactivate:d,children:e.jsx(WIt,{...i,ref:t})})});$We.displayName=V6;var[K$s,Y$s]=qIt(V6),WIt=It.forwardRef((s,t)=>{const{__scopeToggleGroup:n,disabled:r=!1,rovingFocus:a=!0,orientation:i,dir:l,loop:o=!0,...c}=s,d=VIt(n),u=jC(l),h={role:"group",dir:u,...c};return e.jsx(K$s,{scope:n,rovingFocus:a,disabled:r,children:a?e.jsx(iCe,{asChild:!0,...d,orientation:i,dir:u,loop:o,children:e.jsx(Ka.div,{...h,ref:t})}):e.jsx(Ka.div,{...h,ref:t})})}),JSe="ToggleGroupItem",KIt=It.forwardRef((s,t)=>{const n=GIt(JSe,s.__scopeToggleGroup),r=Y$s(JSe,s.__scopeToggleGroup),a=VIt(s.__scopeToggleGroup),i=n.value.includes(s.value),l=r.disabled||s.disabled,o={...s,pressed:i,disabled:l},c=It.useRef(null);return r.rovingFocus?e.jsx(oCe,{asChild:!0,...a,focusable:!l,active:i,ref:c,children:e.jsx(rut,{...o,ref:t})}):e.jsx(rut,{...o,ref:t})});KIt.displayName=JSe;var rut=It.forwardRef((s,t)=>{const{__scopeToggleGroup:n,value:r,...a}=s,i=GIt(JSe,n),l={role:"radio","aria-checked":s.pressed,"aria-pressed":void 0},o=i.type==="single"?l:void 0;return e.jsx(BWe,{...o,...a,ref:t,onPressedChange:c=>{c?i.onItemActivate(r):i.onItemDeactivate(r)}})}),YIt=$We,ZIt=KIt;const XIt=GO("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"}}),Z$s=j.forwardRef(({className:s,variant:t,size:n,...r},a)=>e.jsx(UIt,{ref:a,className:Tt(XIt({variant:t,size:n,className:s})),...r}));Z$s.displayName=UIt.displayName;const QIt=j.createContext({size:"default",variant:"default"}),iB=j.forwardRef(({className:s,variant:t,size:n,children:r,...a},i)=>e.jsx(YIt,{ref:i,className:Tt("flex items-center justify-center gap-1",s),...a,children:e.jsx(QIt.Provider,{value:{variant:t,size:n},children:r})}));iB.displayName=YIt.displayName;const OR=j.forwardRef(({className:s,children:t,variant:n,size:r,...a},i)=>{const l=j.useContext(QIt);return e.jsx(ZIt,{ref:i,className:Tt(XIt({variant:l.variant||n,size:l.size||r}),s),...a,children:t})});OR.displayName=ZIt.displayName;const X$s=[{id:"meet",label:"Meet Your Agent",icon:Lo,description:"Polished intro card with your headshot, story, and contact."},{id:"testimonial",label:"Testimonial",icon:RN,description:"Turn a Zillow / Google review into a branded graphic."},{id:"milestone",label:"Milestone",icon:pl,description:"Celebrate homes sold, awards, anniversaries, achievements."},{id:"tip",label:"Pro Tip",icon:i5,description:"Drop a value-bomb tip — buyer/seller advice, market insight."},{id:"quote",label:"Quote / Mantra",icon:Eh,description:"Personal philosophy, mantra, or rallying call."}],bIe={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"}},Q$s=[{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."}],aut={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 J$s(){const{data:s}=c7s(),{data:t}=Lee(),[n,r]=j.useState(void 0),a=j.useMemo(()=>(t==null?void 0:t.find(x=>x.id===n))??s??null,[t,n,s]),[i,l]=j.useState({template:"meet",style:"editorial",aspect:"portrait",rating:5,...aut.meet}),o=x=>l(g=>({...g,...x})),c=x=>l(g=>({...g,template:x,...aut[x]})),d=j.useRef(null),[u,h]=j.useState(!1),m=async()=>{if(!d.current)return;h(!0);const x=d.current,g=x.style.transform;try{x.style.transform="none",await new Promise(v=>requestAnimationFrame(()=>v(null)));const y=await hU(x,{cacheBust:!0,pixelRatio:2,width:x.offsetWidth,height:x.offsetHeight,backgroundColor:"#ffffff"}),b=document.createElement("a");b.href=y,b.download=`personal-branding-${i.template}-${Date.now()}.png`,document.body.appendChild(b),b.click(),b.remove(),ae.success("Downloaded to your device")}catch(y){ae.error((y==null?void 0:y.message)||"Export failed")}finally{x.style.transform=g,h(!1)}},p=bIe[i.aspect];return e.jsx(Ks,{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(Ul,{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(Wn,{to:"/marketing-studio",className:"text-sm text-muted-foreground inline-flex items-center gap-1 hover:underline",children:[e.jsx(ka,{className:"h-3 w-3"})," Back to Marketing Studio"]}),e.jsx("div",{className:"flex items-center gap-2 mt-1",children:e.jsxs($e,{variant:"secondary",className:"gap-1",children:[e.jsx(dn,{className:"h-3 w-3"})," New"]})}),e.jsx("h1",{className:"text-2xl md:text-3xl font-bold tracking-tight mt-1",children:"Personal Branding"}),e.jsx("p",{className:"text-sm md:text-base text-muted-foreground max-w-2xl",children:"Five editorial-grade templates, four distinct aesthetics. Pick one, drop in your story, export in seconds."})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx($,{variant:"outline",asChild:!0,children:e.jsxs(Wn,{to:"/marketing-studio/brand-kit",children:[e.jsx(Rc,{className:"h-4 w-4 mr-1"})," Brand Kit"]})}),e.jsxs($,{onClick:m,disabled:u,children:[e.jsx(di,{className:"h-4 w-4 mr-1"})," ",u?"Exporting…":"Download"]})]})]}),e.jsxs("div",{className:"grid lg:grid-cols-[380px_1fr] gap-6",children:[e.jsxs("div",{className:"space-y-5",children:[e.jsx(_e,{children:e.jsxs(Oe,{className:"p-4 space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{className:"text-xs uppercase tracking-wider text-muted-foreground",children:"Template"}),e.jsx("div",{className:"grid grid-cols-2 gap-2",children:X$s.map(x=>{const g=x.icon,y=i.template===x.id;return e.jsxs("button",{onClick:()=>c(x.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(g,{className:"h-4 w-4 mb-1"}),e.jsx("div",{className:"text-xs font-semibold",children:x.label})]},x.id)})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{className:"text-xs uppercase tracking-wider text-muted-foreground",children:"Style"}),e.jsx(iB,{type:"single",value:i.style,onValueChange:x=>x&&o({style:x}),className:"grid grid-cols-2 gap-1",children:Q$s.map(x=>e.jsx(OR,{value:x.id,className:"text-xs h-9",children:x.label},x.id))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{className:"text-xs uppercase tracking-wider text-muted-foreground",children:"Format"}),e.jsx(iB,{type:"single",value:i.aspect,onValueChange:x=>x&&o({aspect:x}),className:"grid grid-cols-3 gap-1",children:Object.keys(bIe).map(x=>e.jsx(OR,{value:x,className:"text-xs h-9",children:bIe[x].label},x))})]}),t&&t.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{className:"text-xs uppercase tracking-wider text-muted-foreground",children:"Brand preset"}),e.jsxs(vs,{value:n??(s==null?void 0:s.id)??"",onValueChange:r,children:[e.jsx(gs,{children:e.jsx(bs,{placeholder:"Choose preset"})}),e.jsx(ys,{children:t.map(x=>e.jsx(Ye,{value:x.id,children:x.name},x.id))})]})]})]})}),e.jsx(_e,{children:e.jsxs(Oe,{className:"p-4 space-y-3",children:[e.jsx(se,{className:"text-xs uppercase tracking-wider text-muted-foreground",children:"Content"}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{htmlFor:"headline",className:"text-xs",children:"Headline"}),e.jsx(Is,{id:"headline",value:i.headline,onChange:x=>o({headline:x.target.value}),rows:2})]}),i.template!=="quote"&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{htmlFor:"subline",className:"text-xs",children:"Subline"}),e.jsx(be,{id:"subline",value:i.subline,onChange:x=>o({subline:x.target.value})})]}),i.template!=="quote"&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{htmlFor:"body",className:"text-xs",children:"Body"}),e.jsx(Is,{id:"body",value:i.body,onChange:x=>o({body:x.target.value}),rows:4})]}),(i.template==="testimonial"||i.template==="quote")&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{htmlFor:"attribution",className:"text-xs",children:"Attribution"}),e.jsx(be,{id:"attribution",value:i.attribution,onChange:x=>o({attribution:x.target.value}),placeholder:"— Client name / Source"})]}),i.template==="testimonial"&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{className:"text-xs",children:"Rating"}),e.jsx(iB,{type:"single",value:String(i.rating),onValueChange:x=>x&&o({rating:Number(x)}),className:"grid grid-cols-5 gap-1",children:[1,2,3,4,5].map(x=>e.jsxs(OR,{value:String(x),className:"text-xs h-9",children:[x,"★"]},x))})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{htmlFor:"badge",className:"text-xs",children:"Eyebrow tag"}),e.jsx(be,{id:"badge",value:i.badgeText,onChange:x=>o({badgeText:x.target.value})})]})]})})]}),e.jsx(eUs,{aspect:p,canvasRef:d,children:e.jsx(tUs,{form:i,preset:a,width:p.w,height:p.h})})]})]})})}function eUs({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 tUs({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(sUs,{...p}):s.style==="bold"?e.jsx(nUs,{...p}):s.style==="luxury"?e.jsx(aUs,{...p}):e.jsx(rUs,{...p})}function JIt({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 MAe({rating:s,color:t}){return e.jsx("div",{style:{display:"flex",gap:4},children:Array.from({length:5}).map((n,r)=>e.jsx(Qa,{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(MAe,{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(JIt,{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 nUs(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%, ${iUs(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(MAe,{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(JIt,{name:l,phone:o,email:c,website:d,color:"#fff"})]})]})}function rUs(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(MAe,{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 aUs(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(MAe,{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 iUs(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 oUs=()=>{const{swagId:s}=Vi(),{user:t}=_s(),{toast:n}=gi(),r=ts(),{trackEngagement:a}=Iq(),[i,l]=j.useState(""),{data:o,isLoading:c}=ht({queryKey:["social-swag-detail",s],queryFn:async()=>{const{data:b,error:v}=await U.from("social_swag").select("*").eq("id",s).single();if(v)throw v;const{data:N}=await U.from("social_swag_links").select("*").eq("swag_id",s).order("sort_order");return{...b,links:N||[]}},enabled:!!s});j.useEffect(()=>{o&&a("social_swag",o.id,o.title,"view")},[o==null?void 0:o.id]);const{data:d=[]}=ht({queryKey:["social-swag-likes",s],queryFn:async()=>{const{data:b,error:v}=await U.from("social_swag_likes").select("*").eq("swag_id",s);if(v)throw v;return b},enabled:!!s}),{data:u=[]}=ht({queryKey:["social-swag-comments",s],queryFn:async()=>{const{data:b,error:v}=await U.from("social_swag_comments").select("*").eq("swag_id",s).order("created_at",{ascending:!1});if(v)throw v;const N=[...new Set(b.map(T=>T.user_id))],{data:C}=await U.from("profiles").select("id, name").in("id",N),A=new Map((C==null?void 0:C.map(T=>[T.id,T.name]))||[]);return b.map(T=>({...T,user_name:A.get(T.user_id)||"Unknown User"}))},enabled:!!s}),h=yt({mutationFn:async b=>{const{error:v}=await U.from("social_swag_comments").insert({swag_id:s,user_id:t.id,content:b});if(v)throw v},onSuccess:()=>{r.invalidateQueries({queryKey:["social-swag-comments",s]}),l(""),n({title:"Comment added!"})},onError:b=>{n({title:"Error adding comment",description:b.message,variant:"destructive"})}}),m=yt({mutationFn:async b=>{const{error:v}=await U.from("social_swag_comments").delete().eq("id",b);if(v)throw v},onSuccess:()=>{r.invalidateQueries({queryKey:["social-swag-comments",s]}),n({title:"Comment deleted"})}}),p=yt({mutationFn:async()=>{const b=d.find(v=>v.user_id===(t==null?void 0:t.id));if(b){const{error:v}=await U.from("social_swag_likes").delete().eq("id",b.id);if(v)throw v}else{const{error:v}=await U.from("social_swag_likes").insert({swag_id:s,user_id:t.id});if(v)throw v}},onSuccess:()=>{r.invalidateQueries({queryKey:["social-swag-likes",s]})}}),x=d.some(b=>b.user_id===(t==null?void 0:t.id)),g=b=>b.split(" ").map(v=>v[0]).join("").toUpperCase().slice(0,2),y=b=>{b.preventDefault(),!(!i.trim()||!t)&&h.mutate(i.trim())};return c?e.jsx(Ks,{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(Ks,{title:o.title,children:e.jsxs("div",{className:"space-y-6 max-w-5xl mx-auto",children:[e.jsx($,{variant:"ghost",size:"sm",asChild:!0,className:"gap-2",children:e.jsxs(Wn,{to:"/social-swag",children:[e.jsx(ka,{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(Fq,{resourceType:"social_swag",resourceId:o.id,resourceTitle:o.title}),e.jsxs($,{variant:x?"default":"outline",className:"gap-2 w-fit",onClick:()=>p.mutate(),disabled:!t||p.isPending,children:[e.jsx(Ox,{className:`h-4 w-4 ${x?"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(_e,{children:e.jsxs(Oe,{className:"pt-6",children:[e.jsxs("h3",{className:"font-semibold flex items-center gap-2 mb-4",children:[e.jsx(kc,{className:"h-4 w-4"}),o.links.length===1?"Canva Link":"Canva Links"]}),e.jsx("div",{className:"grid gap-2",children:o.links.map(b=>e.jsxs($,{variant:"outline",className:"w-full justify-between gap-2 h-auto py-3",onClick:()=>{a("social_swag",o.id,o.title,"click_canva"),window.open(b.canva_share_link,"_blank")},children:[e.jsx("span",{className:"font-medium",children:b.title}),e.jsx(Tr,{className:"h-4 w-4 text-muted-foreground"})]},b.id))})]})}),e.jsx(Hl,{}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("h3",{className:"font-semibold flex items-center gap-2 text-lg",children:[e.jsx(Ed,{className:"h-5 w-5"}),"Comments (",u.length,")"]}),t?e.jsxs("form",{onSubmit:y,className:"flex gap-2",children:[e.jsx(Is,{placeholder:"Add a comment...",value:i,onChange:b=>l(b.target.value),className:"min-h-[80px] resize-none flex-1"}),e.jsx($,{type:"submit",size:"icon",className:"h-10 w-10",disabled:!i.trim()||h.isPending,children:e.jsx(Br,{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(_e,{children:e.jsx(Oe,{className:"py-8 text-center",children:e.jsx("p",{className:"text-muted-foreground",children:"No comments yet. Be the first to share your thoughts!"})})}):u.map(b=>e.jsx(_e,{children:e.jsx(Oe,{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:g(b.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:b.user_name}),e.jsx("span",{className:"text-sm text-muted-foreground",children:fc(new Date(b.created_at),{addSuffix:!0})}),b.user_id===(t==null?void 0:t.id)&&e.jsx($,{variant:"ghost",size:"icon",className:"h-6 w-6 ml-auto",onClick:()=>m.mutate(b.id),children:e.jsx(Pn,{className:"h-3 w-3 text-muted-foreground"})})]}),e.jsx("p",{className:"text-sm whitespace-pre-wrap",children:b.content})]})]})})},b.id))})]})]})}):e.jsx(Ks,{title:"Social Swag",children:e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(kc,{className:"h-12 w-12 text-muted-foreground mb-4"}),e.jsx("h3",{className:"text-lg font-semibold",children:"Item not found"}),e.jsx("p",{className:"text-muted-foreground mt-1",children:"This item may have been removed or is not available."}),e.jsx($,{asChild:!0,className:"mt-4",children:e.jsx(Wn,{to:"/social-swag",children:"Back to Social Swag"})})]})})},lUs=({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($,{variant:n==="all"?"secondary":"ghost",className:"w-full justify-start",onClick:()=>r("all"),children:[e.jsx(vT,{className:"h-4 w-4 mr-2"}),"All Posts"]}),e.jsxs(uv,{open:i,onOpenChange:l,children:[e.jsx(hv,{asChild:!0,children:e.jsxs($,{variant:"ghost",className:"w-full justify-between text-muted-foreground hover:text-foreground",children:[e.jsx("span",{className:"text-xs font-semibold uppercase tracking-wider",children:"Categories"}),i?e.jsx(_o,{className:"h-4 w-4"}):e.jsx(Ja,{className:"h-4 w-4"})]})}),e.jsx(mv,{className:"space-y-1 pl-2",children:s.map(m=>e.jsxs($,{variant:n===m.id?"secondary":"ghost",size:"sm",className:"w-full justify-start h-9",onClick:()=>r(m.id),children:[e.jsx("span",{className:"mr-2",children:m.icon||"📂"}),e.jsx("span",{className:"truncate",children:m.name})]},m.id))})]}),t.length>0&&e.jsxs(uv,{open:o,onOpenChange:c,children:[e.jsx(hv,{asChild:!0,children:e.jsxs($,{variant:"ghost",className:"w-full justify-between text-muted-foreground hover:text-foreground",children:[e.jsxs("span",{className:"text-xs font-semibold uppercase tracking-wider flex items-center gap-1",children:[e.jsx(Ad,{className:"h-3 w-3"}),"Your Groups"]}),o?e.jsx(_o,{className:"h-4 w-4"}):e.jsx(Ja,{className:"h-4 w-4"})]})}),e.jsx(mv,{className:"space-y-1 pl-2",children:t.map(m=>e.jsxs($,{variant:n===`group:${m.id}`?"secondary":"ghost",size:"sm",className:"w-full justify-start h-9",onClick:()=>r(`group:${m.id}`),children:[e.jsx("span",{className:"mr-2",children:m.icon||"🔒"}),e.jsx("span",{className:"truncate",children:m.name})]},m.id))})]}),e.jsxs(uv,{open:d,onOpenChange:u,children:[e.jsx(hv,{asChild:!0,children:e.jsxs($,{variant:"ghost",className:"w-full justify-between text-muted-foreground hover:text-foreground",children:[e.jsxs("span",{className:"text-xs font-semibold uppercase tracking-wider flex items-center gap-1",children:[e.jsx(qn,{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(_o,{className:"h-4 w-4"}):e.jsx(Ja,{className:"h-4 w-4"})]})}),e.jsx(mv,{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(ki,{src:m.avatarUrl}),e.jsx(Ta,{className:"text-xs",children:h(m.name)})]}),e.jsx(Bp,{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))})]})]})})})},cUs=({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(Hd,{children:[e.jsx(Gd,{asChild:!0,children:e.jsxs($,{variant:"outline",className:"flex-1 justify-between",children:[e.jsx("span",{className:"truncate",children:c()}),e.jsx(_o,{className:"h-4 w-4 ml-2 shrink-0"})]})}),e.jsxs(Md,{className:"w-56 bg-background border",children:[e.jsxs(Na,{onClick:()=>r("all"),children:[e.jsx(vT,{className:"h-4 w-4 mr-2"}),"All Posts"]}),e.jsx(S0,{}),e.jsx(iO,{className:"text-xs text-muted-foreground",children:"Categories"}),s.map(d=>e.jsxs(Na,{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(S0,{}),e.jsxs(iO,{className:"text-xs text-muted-foreground flex items-center gap-1",children:[e.jsx(Ad,{className:"h-3 w-3"}),"Your Groups"]}),t.map(d=>e.jsxs(Na,{onClick:()=>r(`group:${d.id}`),children:[e.jsx("span",{className:"mr-2",children:d.icon||"🔒"}),d.name]},d.id))]})]})]}),e.jsxs(Ub,{open:i,onOpenChange:l,children:[e.jsx(cee,{asChild:!0,children:e.jsxs($,{variant:"outline",size:"icon",className:"relative",children:[e.jsx(qn,{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(T1,{children:[e.jsx(kw,{children:e.jsxs(Sw,{className:"flex items-center gap-2",children:[e.jsx(qn,{className:"h-5 w-5"}),"Online Now (",a.length,")"]})}),e.jsx(Oi,{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(ki,{src:d.avatarUrl}),e.jsx(Ta,{children:o(d.name)})]}),e.jsx(Bp,{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 _Ie,LAe="HoverCard",[e8t,mQn]=ip(LAe,[M5]),PAe=M5(),[dUs,UWe]=e8t(LAe),t8t=s=>{const{__scopeHoverCard:t,children:n,open:r,defaultOpen:a,onOpenChange:i,openDelay:l=700,closeDelay:o=300}=s,c=PAe(t),d=j.useRef(0),u=j.useRef(0),h=j.useRef(!1),m=j.useRef(!1),[p,x]=Ux({prop:r,defaultProp:a??!1,onChange:i,caller:LAe}),g=j.useCallback(()=>{clearTimeout(u.current),d.current=window.setTimeout(()=>x(!0),l)},[l,x]),y=j.useCallback(()=>{clearTimeout(d.current),!h.current&&!m.current&&(u.current=window.setTimeout(()=>x(!1),o))},[o,x]),b=j.useCallback(()=>x(!1),[x]);return j.useEffect(()=>()=>{clearTimeout(d.current),clearTimeout(u.current)},[]),e.jsx(dUs,{scope:t,open:p,onOpenChange:x,onOpen:g,onClose:y,onDismiss:b,hasSelectionRef:h,isPointerDownOnContentRef:m,children:e.jsx(eee,{...c,children:n})})};t8t.displayName=LAe;var s8t="HoverCardTrigger",n8t=j.forwardRef((s,t)=>{const{__scopeHoverCard:n,...r}=s,a=UWe(s8t,n),i=PAe(n);return e.jsx(yq,{asChild:!0,...i,children:e.jsx(Ka.a,{"data-state":a.open?"open":"closed",...r,ref:t,onPointerEnter:xa(s.onPointerEnter,t5e(a.onOpen)),onPointerLeave:xa(s.onPointerLeave,t5e(a.onClose)),onFocus:xa(s.onFocus,a.onOpen),onBlur:xa(s.onBlur,a.onClose),onTouchStart:xa(s.onTouchStart,l=>l.preventDefault())})})});n8t.displayName=s8t;var uUs="HoverCardPortal",[pQn,hUs]=e8t(uUs,{forceMount:void 0}),e5e="HoverCardContent",r8t=j.forwardRef((s,t)=>{const n=hUs(e5e,s.__scopeHoverCard),{forceMount:r=n.forceMount,...a}=s,i=UWe(e5e,s.__scopeHoverCard);return e.jsx(dx,{present:r||i.open,children:e.jsx(mUs,{"data-state":i.open?"open":"closed",...a,onPointerEnter:xa(s.onPointerEnter,t5e(i.onOpen)),onPointerLeave:xa(s.onPointerLeave,t5e(i.onClose)),ref:t})})});r8t.displayName=e5e;var mUs=j.forwardRef((s,t)=>{const{__scopeHoverCard:n,onEscapeKeyDown:r,onPointerDownOutside:a,onFocusOutside:i,onInteractOutside:l,...o}=s,c=UWe(e5e,n),d=PAe(n),u=j.useRef(null),h=Po(t,u),[m,p]=j.useState(!1);return j.useEffect(()=>{if(m){const x=document.body;return _Ie=x.style.userSelect||x.style.webkitUserSelect,x.style.userSelect="none",x.style.webkitUserSelect="none",()=>{x.style.userSelect=_Ie,x.style.webkitUserSelect=_Ie}}},[m]),j.useEffect(()=>{if(u.current){const x=()=>{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",x),()=>{document.removeEventListener("pointerup",x),c.hasSelectionRef.current=!1,c.isPointerDownOnContentRef.current=!1}}},[c.isPointerDownOnContentRef,c.hasSelectionRef]),j.useEffect(()=>{u.current&&xUs(u.current).forEach(g=>g.setAttribute("tabindex","-1"))}),e.jsx(j6,{asChild:!0,disableOutsidePointerEvents:!1,onInteractOutside:l,onEscapeKeyDown:r,onPointerDownOutside:a,onFocusOutside:xa(i,x=>{x.preventDefault()}),onDismiss:c.onDismiss,children:e.jsx(tee,{...d,...o,onPointerDown:xa(o.onPointerDown,x=>{x.currentTarget.contains(x.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)"}})})}),pUs="HoverCardArrow",fUs=j.forwardRef((s,t)=>{const{__scopeHoverCard:n,...r}=s,a=PAe(n);return e.jsx(see,{...a,...r,ref:t})});fUs.displayName=pUs;function t5e(s){return t=>t.pointerType==="touch"?void 0:s()}function xUs(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 gUs=t8t,yUs=n8t,a8t=r8t;const vUs=gUs,bUs=yUs,i8t=j.forwardRef(({className:s,align:t="center",sideOffset:n=4,...r},a)=>e.jsx(a8t,{ref:a,align:t,sideOffset:n,className:Tt("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}));i8t.displayName=a8t.displayName;const _Us=[{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"}],wUs=s=>s.split(" ").map(t=>t[0]).join("").toUpperCase().slice(0,2),o8t=({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(vUs,{openDelay:200,closeDelay:100,children:[e.jsx(bUs,{asChild:!0,children:e.jsx("div",{className:"cursor-pointer",children:t})}),e.jsx(i8t,{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=_Us.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(ki,{src:l.user_avatar||void 0}),e.jsx(Ta,{className:"text-[10px]",children:wUs(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 jUs({images:s,initialIndex:t=0,open:n,onOpenChange:r}){const[a,i]=j.useState(t),[l,o]=j.useState(!1);j.useEffect(()=>{n&&(i(t),o(!1))},[n,t]);const c=()=>{i(m=>m>0?m-1:s.length-1),o(!1)},d=()=>{i(m=>m{n&&(m.key==="ArrowLeft"&&c(),m.key==="ArrowRight"&&d(),m.key==="Escape"&&r(!1))},[n,s.length]);j.useEffect(()=>(window.addEventListener("keydown",u),()=>window.removeEventListener("keydown",u)),[u]);const h=s[a];return e.jsx(Os,{open:n,onOpenChange:r,children:e.jsxs(Rs,{className:"max-w-[95vw] max-h-[95vh] w-auto h-auto p-0 border-none bg-black/95 overflow-hidden",children:[e.jsx($,{variant:"ghost",size:"icon",className:"absolute top-2 right-2 z-50 text-white hover:bg-white/20 h-10 w-10",onClick:()=>r(!1),children:e.jsx(pr,{className:"h-6 w-6"})}),s.length>1&&e.jsxs(e.Fragment,{children:[e.jsx($,{variant:"ghost",size:"icon",className:"absolute left-2 top-1/2 -translate-y-1/2 z-50 text-white hover:bg-white/20 h-12 w-12",onClick:c,children:e.jsx(Ic,{className:"h-8 w-8"})}),e.jsx($,{variant:"ghost",size:"icon",className:"absolute right-2 top-1/2 -translate-y-1/2 z-50 text-white hover:bg-white/20 h-12 w-12",onClick:d,children:e.jsx(Ja,{className:"h-8 w-8"})})]}),s.length>1&&e.jsxs("div",{className:"absolute bottom-4 left-1/2 -translate-x-1/2 z-50 text-white text-sm bg-black/50 px-3 py-1 rounded-full",children:[a+1," / ",s.length]}),(h==null?void 0:h.type)==="image"&&e.jsx($,{variant:"ghost",size:"icon",className:"absolute top-2 left-2 z-50 text-white hover:bg-white/20 h-10 w-10",onClick:()=>o(!l),children:l?e.jsx(Wz,{className:"h-5 w-5"}):e.jsx(IT,{className:"h-5 w-5"})}),e.jsx("div",{className:Tt("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:Tt("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:Tt("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 pre=[{type:"like",emoji:"👍",label:"Like"},{type:"love",emoji:"❤️",label:"Love"}],NUs=({commentId:s,reactions:t,currentUserId:n})=>{var d,u;const r=ts(),[a,i]=j.useState(!1),l=t.find(h=>h.user_id===n),o=yt({mutationFn:async h=>{l?l.reaction_type===h?await U.from("community_comment_reactions").delete().eq("id",l.id):await U.from("community_comment_reactions").update({reaction_type:h}).eq("id",l.id):await U.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(o8t,{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=pre.find(p=>p.type===h))==null?void 0:m.emoji},h)})}),e.jsx("span",{children:t.length})]})}),n&&e.jsxs(Sc,{open:a,onOpenChange:i,children:[e.jsx(Cc,{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=pre.find(h=>h.type===l.reaction_type))==null?void 0:d.emoji," ",(u=pre.find(h=>h.type===l.reaction_type))==null?void 0:u.label]}):e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(fo,{className:"h-3 w-3"}),"Like"]})})}),e.jsx(xc,{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:pre.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 qWe({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(Wn,{to:u?`/templates/${d}`:`/profile?user=${d}`,className:Tt("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 s5e({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),[x,g]=j.useState("user"),[y,b]=j.useState(""),[v,N]=j.useState(null),[C,A]=j.useState(0),[T,P]=j.useState({top:0,left:0,width:0}),M=j.useRef(new Map),I=j.useRef(new Map),D=le=>{if(c==="plain"){const fe=[];return M.current.forEach((Ee,Me)=>{le.includes(`@${Me}`)&&fe.push(Ee)}),[...new Set(fe)]}const he=/@\[([^\]]+)\]\(([^)]+)\)/g,ve=[];let ge;for(;(ge=he.exec(le))!==null;)ve.push(ge[2]);return[...new Set(ve)]},B=le=>{if(c==="plain"){const fe=[];return I.current.forEach((Ee,Me)=>{le.includes(`#${Me}`)&&fe.push(Ee)}),[...new Set(fe)]}const he=/#\[([^\]]+)\]\(([^)]+)\)/g,ve=[];let ge;for(;(ge=he.exec(le))!==null;)ve.push(ge[2]);return[...new Set(ve)]};j.useEffect(()=>{if(i){const le=D(s);i(le)}if(l){const le=B(s);l(le)}},[s,i,l,c]);const{data:q=[],isLoading:W}=ht({queryKey:["mention-users",y],queryFn:async()=>{const le=U.from("profiles").select("id, name").limit(8),he=y.length>=1?le.ilike("name",`%${y}%`):le.order("name"),{data:ve,error:ge}=await he;if(ge)throw ge;const fe=ve.map(Ee=>Ee.id),je=await d4t(fe);return ve.map(Ee=>({id:Ee.id,name:Ee.name||"Unknown",avatar_url:je.get(Ee.id)}))},enabled:m&&x==="user",staleTime:3e4}),{data:V=[],isLoading:K}=ht({queryKey:["mention-templates",y],queryFn:async()=>{let le=U.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&&(le=le.ilike("name",`%${y}%`));const{data:he,error:ve}=await le;if(ve)throw ve;return he||[]},enabled:m&&x==="template"&&d,staleTime:3e4}),Q=x==="user"?W:K,J=x==="user"?q:V,ce=le=>le.split(" ").map(he=>he[0]).join("").toUpperCase().slice(0,2),ue=le=>{const he=le.target.value,ve=le.target.selectionStart;t(he);const ge=he.substring(0,ve),fe=ge.lastIndexOf("@"),je=d?ge.lastIndexOf("#"):-1;let Ee=-1,Me="user";if(fe>je?(Ee=fe,Me="user"):je>fe&&d&&(Ee=je,Me="template"),Ee!==-1){const De=ge.substring(Ee+1),ze=De.includes(" "),ke=De.includes(` `);if(!ze&&!ke&&De.length<=30){N(Ee),b(De),g(Me),p(!0),A(0);return}}p(!1),N(null)},ne=le=>{if(v===null)return;const he=s.substring(0,v),ve=s.substring(v+y.length+1),ge=x==="user"?"@":"#",fe=c==="plain"?`${ge}${le.name} `:`${ge}[${le.name}](${le.id}) `;c==="plain"&&(x==="user"?M.current.set(le.name,le.id):I.current.set(le.name,le.id));const je=he+fe+ve;t(je),p(!1),N(null),b(""),setTimeout(()=>{if(u.current){const Ee=he.length+fe.length;u.current.focus(),u.current.setSelectionRange(Ee,Ee)}},0)},ee=le=>{if(!(!m||J.length===0))switch(le.key){case"ArrowDown":le.preventDefault(),A(he=>(he+1)%J.length);break;case"ArrowUp":le.preventDefault(),A(he=>(he-1+J.length)%J.length);break;case"Enter":J[C]&&(le.preventDefault(),ne(J[C]));break;case"Escape":le.preventDefault(),p(!1);break;case"Tab":J[C]&&(le.preventDefault(),ne(J[C]));break}};return j.useEffect(()=>{const le=he=>{h.current&&!h.current.contains(he.target)&&u.current&&!u.current.contains(he.target)&&p(!1)};return document.addEventListener("mousedown",le),()=>document.removeEventListener("mousedown",le)},[]),j.useEffect(()=>{if(!m)return;const le=()=>{const he=u.current;if(!he)return;const ve=he.getBoundingClientRect();P({top:ve.bottom+4,left:ve.left,width:ve.width})};return le(),window.addEventListener("resize",le),window.addEventListener("scroll",le,!0),()=>{window.removeEventListener("resize",le),window.removeEventListener("scroll",le,!0)}},[m,s]),e.jsxs("div",{className:"relative flex-1",children:[e.jsx(Is,{ref:u,value:s,onChange:ue,onKeyDown:le=>{ee(le),le.defaultPrevented||o==null||o(le)},placeholder:n,className:Tt("resize-none",r),style:{minHeight:a}}),m&&n1.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:x==="user"?"👤 Mention a person":"📋 Link a template"}),Q?e.jsx("div",{className:"px-3 py-2 text-sm text-muted-foreground",children:"Searching..."}):J.length===0?e.jsx("div",{className:"px-3 py-2 text-sm text-muted-foreground",children:y.length<1?`Type to search ${x==="user"?"people":"templates"}...`:`No ${x==="user"?"users":"templates"} found`}):e.jsx("ul",{className:"py-1 max-h-[180px] overflow-y-auto",children:J.map((le,he)=>e.jsx("li",{className:Tt("flex items-center gap-2 px-3 py-2 cursor-pointer transition-colors",he===C?"bg-accent":"hover:bg-accent/50"),onClick:()=>ne(le),onMouseEnter:()=>A(he),children:x==="user"?e.jsxs(e.Fragment,{children:[e.jsxs(Ea,{className:"h-6 w-6",children:[e.jsx(ki,{src:le.avatar_url}),e.jsx(Ta,{className:"text-xs",children:ce(le.name)})]}),e.jsx("span",{className:"text-sm font-medium truncate",children:le.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:le.preview_image_url?e.jsx("img",{src:le.preview_image_url,alt:"",className:"w-full h-full object-cover"}):e.jsx(Rc,{className:"h-4 w-4 text-muted-foreground"})}),e.jsx("span",{className:"text-sm font-medium truncate",children:le.name})]})},le.id))})]}),document.body)]})}function kUs(s){const t=/#\[([^\]]+)\]\(([^)]+)\)/g,n=[];let r;for(;(r=t.exec(s))!==null;)n.push(r[2]);return[...new Set(n)]}const iut=s=>s.split(" ").map(t=>t[0]).join("").toUpperCase().slice(0,2);function l8t({comment:s,postId:t,currentUserId:n,currentUserAvatar:r,currentUserEmail:a,canModerate:i,depth:l=0}){const o=ts(),[c,d]=j.useState(!1),[u,h]=j.useState(""),[m,p]=j.useState([]),x=yt({mutationFn:async({content:v,parentCommentId:N})=>{const{data:C,error:A}=await U.from("community_comments").insert({post_id:t,user_id:n,content:v,parent_comment_id:N}).select("id").single();if(A)throw A;const T=m;if(T.length>0&&C){const P=T.filter(M=>M!==n).map(M=>({comment_id:C.id,mentioned_user_id:M,mentioned_by_user_id:n}));P.length>0&&await U.from("community_comment_mentions").insert(P)}},onSuccess:()=>{o.invalidateQueries({queryKey:["community-posts"]}),h(""),p([]),d(!1)}}),g=yt({mutationFn:async v=>{const{error:N}=await U.from("community_comments").delete().eq("id",v);if(N)throw N},onSuccess:()=>o.invalidateQueries({queryKey:["community-posts"]})}),y=()=>{u.trim()&&x.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(ki,{src:s.user_avatar||void 0}),e.jsx(Ta,{className:"text-xs",children:iut(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(qWe,{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:fc(new Date(s.created_at),{addSuffix:!0})}),e.jsx(NUs,{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(qK,{className:"h-3 w-3"}),"Reply"]}),(s.user_id===n||i)&&e.jsx("button",{onClick:()=>g.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(ki,{src:r||void 0}),e.jsx(Ta,{className:"text-xs",children:iut((a==null?void 0:a.split("@")[0])||"U")})]}),e.jsxs("div",{className:"flex-1 flex gap-2 items-start",children:[e.jsx(s5e,{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($,{size:"sm",variant:"ghost",onClick:y,disabled:!u.trim()||x.isPending,className:"h-8 px-2 mt-0.5",children:e.jsx(Br,{className:"h-3 w-3"})})]})]})]})]}),s.replies&&s.replies.length>0&&e.jsx("div",{className:"mt-2 space-y-2",children:s.replies.map(v=>e.jsx(l8t,{comment:v,postId:t,currentUserId:n,currentUserAvatar:r,currentUserEmail:a,canModerate:i,depth:l+1},v.id))})]})}const fre=[{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"}],SUs=()=>{const{user:s,isBrokerageManager:t,managedBrokerages:n,isAdmin:r}=_s(),{avatarUrl:a}=c4t(s==null?void 0:s.id),{onlineUsers:i}=YSt(),{toast:l}=gi(),o=ts(),c=j.useRef(null),[d,u]=j.useState("all"),[h,m]=j.useState(""),[p,x]=j.useState(""),[g,y]=j.useState(""),[b,v]=j.useState([]),[N,C]=j.useState([]),[A,T]=j.useState(""),[P,M]=j.useState(!1),[I,D]=j.useState(null),[B,q]=j.useState(""),[W,V]=j.useState(new Set),[K,Q]=j.useState({}),[J,ce]=j.useState({}),[ue,ne]=j.useState([]),[ee,le]=j.useState([]),[he,ve]=j.useState({open:!1,images:[],index:0});j.useEffect(()=>{if(d.startsWith("group:")){const lt=d.replace("group:","");y(lt),x("")}else d!=="all"?(x(d),y("")):(x(""),y(""))},[d]);const{data:ge=[]}=ht({queryKey:["community-categories"],queryFn:async()=>{const{data:lt,error:Mt}=await U.from("community_categories").select("*").order("sort_order");if(Mt)throw Mt;return lt}}),{data:fe=[]}=ht({queryKey:["community-private-groups"],queryFn:async()=>{const{data:lt,error:Mt}=await U.from("community_private_groups").select("id, name, description, icon, brokerage_id, sort_order").order("sort_order");if(Mt)throw Mt;return lt}}),je=20,{data:Ee,isLoading:Me,hasNextPage:De,fetchNextPage:ze,isFetchingNextPage:ke}=Pis({queryKey:["community-posts",d],initialPageParam:0,queryFn:async({pageParam:lt})=>{var pt;const Mt=lt*je,Ft=Mt+je;let Ts=U.from("community_posts").select("*").order("is_pinned",{ascending:!1}).order("pinned_at",{ascending:!1,nullsFirst:!1}).order("created_at",{ascending:!1}).range(Mt,Ft);if(d.startsWith("group:")){const vt=d.replace("group:","");Ts=Ts.eq("private_group_id",vt)}else d==="all"||(Ts=Ts.eq("category_id",d).is("private_group_id",null));const{data:js,error:zt}=await Ts;if(zt)throw zt;const Nt=((js==null?void 0:js.length)||0)>je,Ds=(js||[]).slice(0,je);if(Ds.length===0)return{posts:[],hasMore:!1,nextPage:lt+1};const _t=Ds.map(vt=>vt.id),Xs=[...new Set(Ds.filter(vt=>vt.category_id).map(vt=>vt.category_id))].filter(Boolean),[rn,Ps,_n,Zs,gr]=await Promise.all([Xs.length?U.from("community_categories").select("*").in("id",Xs):Promise.resolve({data:[]}),U.from("community_post_media").select("*").in("post_id",_t).order("sort_order"),U.from("community_reactions").select("*").in("post_id",_t),U.from("community_comments").select("*").in("post_id",_t).order("created_at",{ascending:!0}),U.from("community_post_resources").select("*").in("post_id",_t)]),Un=rn==null?void 0:rn.data,In=Ps==null?void 0:Ps.data,Ar=_n==null?void 0:_n.data,or=Zs==null?void 0:Zs.data,qs=gr==null?void 0:gr.data,yr=(or||[]).map(vt=>vt.id),[fn,Zn]=await Promise.all([yr.length?U.from("community_comment_reactions").select("*").in("comment_id",yr):Promise.resolve({data:[]}),(()=>{const vt=(qs||[]).filter(At=>At.resource_type==="template").map(At=>At.resource_id);return vt.length===0?Promise.resolve({data:[]}):U.from("canva_templates").select("id, name, preview_image_url").in("id",vt)})()]),Xt=(fn==null?void 0:fn.data)||[],rr=(Zn==null?void 0:Zn.data)||[],Qn=new Map(rr.map(vt=>[vt.id,{name:vt.name,preview_image_url:vt.preview_image_url}])),Sn=Array.from(new Set([...Ds.map(vt=>vt.user_id),...(Ar||[]).map(vt=>vt.user_id),...(or||[]).map(vt=>vt.user_id),...Xt.map(vt=>vt.user_id)])),[$n,tn]=await Promise.all([Sn.length?U.from("profiles").select("id, name").in("id",Sn):Promise.resolve({data:[]}),d4t(Sn)]),ln=new Map(((pt=$n==null?void 0:$n.data)==null?void 0:pt.map(vt=>[vt.id,vt.name]))||[]),Cr=new Map((Un||[]).map(vt=>[vt.id,vt])),ms=vt=>{const At=new Map,Zt=[];return vt.forEach(as=>{At.set(as.id,{...as,user_name:ln.get(as.user_id)||"Unknown User",user_avatar:tn.get(as.user_id),reactions:Xt.filter(Ls=>Ls.comment_id===as.id).map(Ls=>({...Ls,user_name:ln.get(Ls.user_id)||"Unknown User",user_avatar:tn.get(Ls.user_id)})),replies:[]})}),vt.forEach(as=>{const Ls=At.get(as.id);if(as.parent_comment_id&&At.has(as.parent_comment_id)){const cs=At.get(as.parent_comment_id);cs.replies=cs.replies||[],cs.replies.push(Ls)}else Zt.push(Ls)}),Zt};return{posts:Ds.map(vt=>{const At=(qs||[]).filter(Zt=>Zt.post_id===vt.id).map(Zt=>{let as="",Ls=null;if(Zt.resource_type==="template"){const cs=Qn.get(Zt.resource_id);as=(cs==null?void 0:cs.name)||"Unknown Template",Ls=(cs==null?void 0:cs.preview_image_url)||null}return{id:Zt.id,resource_type:Zt.resource_type,resource_id:Zt.resource_id,resource_name:as,resource_preview_url:Ls}});return{...vt,user_name:ln.get(vt.user_id)||"Unknown User",user_avatar:tn.get(vt.user_id),category:vt.category_id?Cr.get(vt.category_id):null,media:(In||[]).filter(Zt=>Zt.post_id===vt.id),reactions:((Ar||[]).filter(Zt=>Zt.post_id===vt.id)||[]).map(Zt=>({...Zt,user_name:ln.get(Zt.user_id)||"Unknown User",user_avatar:tn.get(Zt.user_id)})),comments:ms((or||[]).filter(Zt=>Zt.post_id===vt.id)),resources:At}}),hasMore:Nt,nextPage:lt+1}},getNextPageParam:lt=>lt.hasMore?lt.nextPage:void 0}),Xe=j.useMemo(()=>(Ee==null?void 0:Ee.pages.flatMap(lt=>lt.posts))??[],[Ee]),Se=yt({mutationFn:async()=>{M(!0);const{data:lt,error:Mt}=await U.from("community_posts").insert({user_id:s.id,category_id:g?null:p||null,private_group_id:g||null,content:h,link_url:A||null}).select().single();if(Mt)throw Mt;for(let Ts=0;Ts0){const Ts=ue.filter(js=>js!==s.id).map(js=>({post_id:lt.id,mentioned_user_id:js,mentioned_by_user_id:s.id}));Ts.length>0&&await U.from("community_post_mentions").insert(Ts)}const Ft=kUs(h);if(Ft.length>0){const Ts=Ft.map(js=>({post_id:lt.id,resource_type:"template",resource_id:js}));await U.from("community_post_resources").insert(Ts)}return lt},onSuccess:async lt=>{var Mt;o.invalidateQueries({queryKey:["community-posts"]}),m(""),ne([]),le([]),x(""),y(""),v([]),C([]),T(""),l({title:"Post created!"});try{const Ft=((Mt=s==null?void 0:s.user_metadata)==null?void 0:Mt.name)||"Someone",Ts=h.replace(/@\[([^\]]+)\]\([^)]+\)/g,"@$1"),js=Ts.length>50?Ts.substring(0,50)+"...":Ts;await U.functions.invoke("send-push-notification",{body:{title:"New Community Post",body:`${Ft}: ${js}`,url:"/community"}})}catch(Ft){console.error("Failed to send push notification:",Ft)}},onError:lt=>{l({title:"Error creating post",description:lt.message,variant:"destructive"})},onSettled:()=>M(!1)}),Re=yt({mutationFn:async({postId:lt,content:Mt})=>{const{error:Ft}=await U.from("community_posts").update({content:Mt}).eq("id",lt);if(Ft)throw Ft},onSuccess:()=>{o.invalidateQueries({queryKey:["community-posts"]}),D(null),q(""),l({title:"Post updated!"})}}),Ae=yt({mutationFn:async lt=>{const{error:Mt}=await U.from("community_posts").delete().eq("id",lt);if(Mt)throw Mt},onSuccess:()=>{o.invalidateQueries({queryKey:["community-posts"]}),l({title:"Post deleted"})}}),Be=yt({mutationFn:async({postId:lt,isPinned:Mt})=>{const{error:Ft}=await U.from("community_posts").update({is_pinned:!Mt,pinned_at:Mt?null:new Date().toISOString(),pinned_by:Mt?null:s==null?void 0:s.id}).eq("id",lt);if(Ft)throw Ft},onSuccess:(lt,{isPinned:Mt})=>{o.invalidateQueries({queryKey:["community-posts"]}),l({title:Mt?"Post unpinned":"Post pinned to top"})}}),qe=yt({mutationFn:async({postId:lt,reactionType:Mt})=>{var Ts;const Ft=(Ts=Xe.find(js=>js.id===lt))==null?void 0:Ts.reactions.find(js=>js.user_id===(s==null?void 0:s.id));Ft?Ft.reaction_type===Mt?await U.from("community_reactions").delete().eq("id",Ft.id):await U.from("community_reactions").update({reaction_type:Mt}).eq("id",Ft.id):await U.from("community_reactions").insert({post_id:lt,user_id:s.id,reaction_type:Mt})},onSuccess:()=>o.invalidateQueries({queryKey:["community-posts"]})}),Ke=yt({mutationFn:async({postId:lt,content:Mt})=>{const{data:Ft,error:Ts}=await U.from("community_comments").insert({post_id:lt,user_id:s.id,content:Mt}).select("id").single();if(Ts)throw Ts;const js=J[lt]||[];if(js.length>0&&Ft){const zt=js.filter(Nt=>Nt!==s.id).map(Nt=>({comment_id:Ft.id,mentioned_user_id:Nt,mentioned_by_user_id:s.id}));zt.length>0&&await U.from("community_comment_mentions").insert(zt)}},onSuccess:(lt,{postId:Mt})=>{o.invalidateQueries({queryKey:["community-posts"]}),Q(Ft=>({...Ft,[Mt]:""})),ce(Ft=>({...Ft,[Mt]:[]}))}});yt({mutationFn:async lt=>{const{error:Mt}=await U.from("community_comments").delete().eq("id",lt);if(Mt)throw Mt},onSuccess:()=>o.invalidateQueries({queryKey:["community-posts"]})});const Ze=lt=>{const Mt=Array.from(lt.target.files||[]);if(Mt.length+b.length>10){l({title:"Maximum 10 files allowed",variant:"destructive"});return}v(Ft=>[...Ft,...Mt]),Mt.forEach(Ft=>{const Ts=new FileReader;Ts.onloadend=()=>{C(js=>[...js,Ts.result])},Ts.readAsDataURL(Ft)})},Ue=lt=>{v(Mt=>Mt.filter((Ft,Ts)=>Ts!==lt)),C(Mt=>Mt.filter((Ft,Ts)=>Ts!==lt))},et=lt=>lt.split(" ").map(Mt=>Mt[0]).join("").toUpperCase().slice(0,2),Qe=lt=>{const Mt={};return lt.forEach(Ft=>{Mt[Ft.reaction_type]=(Mt[Ft.reaction_type]||0)+1}),Mt},Ge=lt=>{var Mt;return(Mt=lt.find(Ft=>Ft.user_id===(s==null?void 0:s.id)))==null?void 0:Mt.reaction_type},nt=lt=>lt.reduce((Mt,Ft)=>Mt+1+(Ft.replies?nt(Ft.replies):0),0),ft=lt=>{if(r)return!0;if(!t||!lt.private_group_id)return!1;const Mt=fe.find(Ft=>Ft.id===lt.private_group_id);return Mt!=null&&Mt.brokerage_id?n.some(Ft=>Ft.id===Mt.brokerage_id):!1};return e.jsx(Ks,{title:"Community",children:e.jsxs("div",{className:"flex gap-6 w-full isolate z-0",children:[e.jsx(lUs,{categories:ge,privateGroups:fe,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(cUs,{categories:ge,privateGroups:fe,selectedFilter:d,onFilterChange:u,onlineUsers:i}),e.jsx(_e,{children:e.jsx(Oe,{className:"pt-6",children:e.jsxs("div",{className:"flex gap-3",children:[e.jsxs(Ea,{className:"h-10 w-10",children:[e.jsx(ki,{src:a||void 0}),e.jsx(Ta,{children:s!=null&&s.email?et(s.email.split("@")[0]):"U"})]}),e.jsxs("div",{className:"flex-1 space-y-3",children:[e.jsx(s5e,{placeholder:r?"What's on your mind? Use @ to mention someone, # to link a template":"What's on your mind? Use @ to mention someone",value:h,onChange:m,onMentionsChange:ne,onTemplatesChange:le,mentionFormat:"encoded",minHeight:"80px",enableTemplateMentions:r}),N.length>0&&e.jsx("div",{className:"grid grid-cols-3 gap-2",children:N.map((lt,Mt)=>{var Ft;return e.jsxs("div",{className:"relative aspect-square rounded-lg overflow-hidden bg-muted",children:[(Ft=b[Mt])!=null&&Ft.type.startsWith("video/")?e.jsx("video",{src:lt,className:"w-full h-full object-cover"}):e.jsx("img",{src:lt,alt:"",className:"w-full h-full object-cover"}),e.jsx($,{variant:"destructive",size:"icon",className:"absolute top-1 right-1 h-6 w-6",onClick:()=>Ue(Mt),children:e.jsx(pr,{className:"h-3 w-3"})})]},Mt)})}),A&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(kc,{className:"h-4 w-4 text-muted-foreground"}),e.jsx(be,{value:A,onChange:lt=>T(lt.target.value),placeholder:"https://...",className:"flex-1"}),e.jsx($,{variant:"ghost",size:"icon",onClick:()=>T(""),children:e.jsx(pr,{className:"h-4 w-4"})})]}),e.jsxs("div",{className:"flex flex-col sm:flex-row items-start sm:items-center justify-between gap-3",children:[e.jsxs("div",{className:"flex gap-1 flex-wrap",children:[e.jsx("input",{type:"file",ref:c,onChange:Ze,accept:"image/*,video/*",multiple:!0,className:"hidden"}),e.jsxs($,{variant:"ghost",size:"sm",onClick:()=>{var lt;return(lt=c.current)==null?void 0:lt.click()},children:[e.jsx(Jl,{className:"h-4 w-4 mr-1"}),"Photo"]}),e.jsxs($,{variant:"ghost",size:"sm",onClick:()=>{var lt;return(lt=c.current)==null?void 0:lt.click()},children:[e.jsx(Xr,{className:"h-4 w-4 mr-1"}),"Video"]}),e.jsxs($,{variant:"ghost",size:"sm",onClick:()=>T("https://"),children:[e.jsx(kc,{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:[fe.length>0?e.jsxs(vs,{value:g||p||"none",onValueChange:lt=>{lt==="none"?(x(""),y("")):lt.startsWith("group:")?(y(lt.replace("group:","")),x("")):(x(lt),y(""))},children:[e.jsx(gs,{className:"w-[130px] sm:w-[160px] h-8 text-xs sm:text-sm",children:e.jsx(bs,{placeholder:"Select..."})}),e.jsxs(ys,{children:[e.jsx(Ye,{value:"none",children:"No category"}),ge.map(lt=>e.jsxs(Ye,{value:lt.id,children:[lt.icon," ",lt.name]},lt.id)),fe.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"}),fe.map(lt=>e.jsxs(Ye,{value:`group:${lt.id}`,children:[lt.icon||"🔒"," ",lt.name]},lt.id))]})]})]}):e.jsxs(vs,{value:p,onValueChange:x,children:[e.jsx(gs,{className:"w-[110px] sm:w-[140px] h-8 text-xs sm:text-sm",children:e.jsx(bs,{placeholder:"Category"})}),e.jsx(ys,{children:ge.map(lt=>e.jsxs(Ye,{value:lt.id,children:[lt.icon," ",lt.name]},lt.id))})]}),e.jsxs($,{size:"sm",onClick:()=>Se.mutate(),disabled:!h.trim()||P,children:[e.jsx(Br,{className:"h-4 w-4 mr-1"}),"Post"]})]})]})]})]})})}),Me?e.jsx("div",{className:"space-y-4",children:[...Array(3)].map((lt,Mt)=>e.jsx(_e,{children:e.jsx(Oe,{className:"pt-6",children:e.jsxs("div",{className:"flex gap-3",children:[e.jsx(on,{className:"h-10 w-10 rounded-full"}),e.jsxs("div",{className:"flex-1 space-y-2",children:[e.jsx(on,{className:"h-4 w-32"}),e.jsx(on,{className:"h-4 w-full"}),e.jsx(on,{className:"h-4 w-3/4"})]})]})})},Mt))}):Xe.length===0?e.jsx(_e,{children:e.jsxs(Oe,{className:"py-12 text-center",children:[e.jsx(Ed,{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:[Xe.map(lt=>{var Mt,Ft,Ts,js;return e.jsx(_e,{children:e.jsxs(Oe,{className:"pt-6",children:[e.jsxs("div",{className:"flex items-start justify-between mb-3",children:[e.jsxs("div",{className:"flex gap-3 min-w-0",children:[e.jsxs(Ea,{className:"h-10 w-10",children:[e.jsx(ki,{src:lt.user_avatar||void 0}),e.jsx(Ta,{children:et(lt.user_name||"U")})]}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"font-semibold break-words",children:lt.user_name}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2 text-sm text-muted-foreground",children:[e.jsx("span",{children:fc(new Date(lt.created_at),{addSuffix:!0})}),lt.category&&e.jsxs(e.Fragment,{children:[e.jsx("span",{children:"•"}),e.jsxs($e,{variant:"secondary",className:"text-xs",children:[lt.category.icon," ",lt.category.name]})]})]})]})]}),(lt.user_id===(s==null?void 0:s.id)||ft(lt))&&e.jsxs(Hd,{children:[e.jsx(Gd,{asChild:!0,children:e.jsx($,{variant:"ghost",size:"icon",className:"h-8 w-8",children:e.jsx(p0,{className:"h-4 w-4"})})}),e.jsxs(Md,{align:"end",children:[ft(lt)&<.private_group_id&&e.jsx(Na,{onClick:()=>Be.mutate({postId:lt.id,isPinned:lt.is_pinned}),children:lt.is_pinned?e.jsxs(e.Fragment,{children:[e.jsx(zK,{className:"h-4 w-4 mr-2"}),"Unpin Post"]}):e.jsxs(e.Fragment,{children:[e.jsx(CT,{className:"h-4 w-4 mr-2"}),"Pin to Top"]})}),lt.user_id===(s==null?void 0:s.id)&&e.jsxs(Na,{onClick:()=>{D(lt),q(lt.content)},children:[e.jsx(Ya,{className:"h-4 w-4 mr-2"}),"Edit"]}),e.jsxs(Na,{className:"text-destructive",onClick:()=>Ae.mutate(lt.id),children:[e.jsx(Pn,{className:"h-4 w-4 mr-2"}),lt.user_id!==(s==null?void 0:s.id)?"Remove (Moderate)":"Delete"]})]})]})]}),lt.is_pinned&&e.jsxs("div",{className:"flex items-center gap-2 mb-2 text-sm text-primary",children:[e.jsx(CT,{className:"h-4 w-4"}),e.jsx("span",{className:"font-medium",children:"Pinned"})]}),e.jsx("div",{className:"mb-3",children:e.jsx(qWe,{content:lt.content})}),lt.media.length>0&&e.jsx("div",{className:`grid gap-2 mb-3 ${lt.media.length===1?"grid-cols-1":lt.media.length===2?"grid-cols-2":lt.media.length===3?"grid-cols-3":"grid-cols-2"}`,children:lt.media.slice(0,4).map((zt,Nt)=>{const Ds=Nt===3&<.media.length>4,_t=lt.media.length-4;return e.jsxs("div",{className:`relative rounded-lg overflow-hidden bg-muted cursor-pointer group ${lt.media.length===1?"max-h-[500px]":lt.media.length===2?"aspect-[4/3]":"aspect-square"}`,onClick:()=>ve({open:!0,images:lt.media.map(Xs=>({url:Xs.media_url,type:Xs.media_type==="video"?"video":"image"})),index:Nt}),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"})})})}),Ds&&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:["+",_t]})})]},zt.id)})}),lt.link_url&&e.jsxs("a",{href:lt.link_url,target:"_blank",rel:"noopener noreferrer",className:"block rounded-lg border hover:bg-muted transition-colors mb-3 overflow-hidden",children:[lt.link_image&&e.jsx("div",{className:"aspect-video bg-muted",children:e.jsx("img",{src:lt.link_image,alt:lt.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:lt.link_title?e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"font-medium text-foreground line-clamp-2",children:lt.link_title}),lt.link_description&&e.jsx("p",{className:"text-sm text-muted-foreground line-clamp-2 mt-1",children:lt.link_description}),e.jsx("p",{className:"text-xs text-muted-foreground mt-2 truncate",children:new URL(lt.link_url).hostname})]}):e.jsxs("div",{className:"flex items-center gap-2 text-sm text-primary",children:[e.jsx(kc,{className:"h-4 w-4 flex-shrink-0"}),e.jsx("span",{className:"truncate",children:lt.link_url})]})})]}),lt.reactions.length>0&&e.jsx(o8t,{reactions:lt.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(Qe(lt.reactions)).slice(0,3).map(([zt])=>{var Nt;return e.jsx("span",{className:"text-base",children:(Nt=fre.find(Ds=>Ds.type===zt))==null?void 0:Nt.emoji},zt)})}),e.jsx("span",{children:lt.reactions.length})]})}),e.jsxs("div",{className:"flex items-center gap-1 border-t border-b py-1 my-2",children:[e.jsxs(Sc,{children:[e.jsx(Cc,{asChild:!0,children:e.jsxs($,{variant:"ghost",size:"sm",className:"flex-1",children:[Ge(lt.reactions)?e.jsx("span",{className:"mr-1",children:(Mt=fre.find(zt=>zt.type===Ge(lt.reactions)))==null?void 0:Mt.emoji}):e.jsx(Ox,{className:"h-4 w-4 mr-1"}),Ge(lt.reactions)?(Ft=fre.find(zt=>zt.type===Ge(lt.reactions)))==null?void 0:Ft.label:"Like"]})}),e.jsx(xc,{className:"w-auto p-2",side:"top",children:e.jsx("div",{className:"flex gap-1",children:fre.map(zt=>e.jsx("button",{onClick:()=>qe.mutate({postId:lt.id,reactionType:zt.type}),className:"text-2xl hover:scale-125 transition-transform p-1",title:zt.label,children:zt.emoji},zt.type))})})]}),e.jsxs($,{variant:"ghost",size:"sm",className:"flex-1",onClick:()=>V(zt=>{const Nt=new Set(zt);return Nt.has(lt.id)?Nt.delete(lt.id):Nt.add(lt.id),Nt}),children:[e.jsx(Ed,{className:"h-4 w-4 mr-1"}),(()=>{const zt=nt(lt.comments);return zt>0?`Comment (${zt})`:"Comment"})()]})]}),W.has(lt.id)&&e.jsxs("div",{className:"space-y-3 mt-3",children:[lt.comments.map(zt=>e.jsx(l8t,{comment:zt,postId:lt.id,currentUserId:s==null?void 0:s.id,currentUserAvatar:a,currentUserEmail:s==null?void 0:s.email,canModerate:ft(lt)},zt.id)),s&&e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(Ea,{className:"h-8 w-8",children:[e.jsx(ki,{src:a||void 0}),e.jsx(Ta,{className:"text-xs",children:et(((Ts=s.email)==null?void 0:Ts.split("@")[0])||"U")})]}),e.jsxs("div",{className:"flex-1 flex gap-2",children:[e.jsx(s5e,{placeholder:"Write a comment... (use @ to mention)",value:K[lt.id]||"",onChange:zt=>Q(Nt=>({...Nt,[lt.id]:zt})),onMentionsChange:zt=>ce(Nt=>({...Nt,[lt.id]:zt})),mentionFormat:"plain",onKeyDown:zt=>{var Nt;zt.defaultPrevented||zt.key==="Enter"&&!zt.shiftKey&&((Nt=K[lt.id])!=null&&Nt.trim())&&(zt.preventDefault(),Ke.mutate({postId:lt.id,content:K[lt.id]}))},className:"text-sm min-h-0 py-1.5",minHeight:"32px"}),e.jsx($,{size:"sm",variant:"ghost",onClick:()=>{var zt;(zt=K[lt.id])!=null&&zt.trim()&&Ke.mutate({postId:lt.id,content:K[lt.id]})},disabled:!((js=K[lt.id])!=null&&js.trim()),className:"h-8 px-2 mt-0.5",children:e.jsx(Br,{className:"h-4 w-4"})})]})]})]})]})},lt.id)}),De&&e.jsx("div",{className:"flex justify-center pt-2",children:e.jsx($,{variant:"outline",onClick:()=>ze(),disabled:ke,children:ke?"Loading…":"Load more posts"})})]}),e.jsx(Os,{open:!!I,onOpenChange:()=>D(null),children:e.jsxs(Rs,{children:[e.jsx(Us,{children:e.jsx(zs,{children:"Edit Post"})}),e.jsx(Is,{value:B,onChange:lt=>q(lt.target.value),className:"min-h-[120px]"}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx($,{variant:"outline",onClick:()=>D(null),children:"Cancel"}),e.jsx($,{onClick:()=>{I&&Re.mutate({postId:I.id,content:B})},disabled:!B.trim(),children:"Save Changes"})]})]})}),e.jsx(jUs,{images:he.images,initialIndex:he.index,open:he.open,onOpenChange:lt=>ve(Mt=>({...Mt,open:lt}))})]})]})})},CUs=50*1024*1024;function c8t({value:s,onChange:t,disabled:n}){const{user:r}=_s(),a=j.useRef(null),[i,l]=j.useState(!1),o=async d=>{if(!d||!r)return;const u=[];l(!0);try{for(const h of Array.from(d)){if(!h.type.startsWith("image/")&&!h.type.startsWith("video/")){ae.error(`${h.name}: only images and videos allowed`);continue}if(h.size>CUs){ae.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:x}=await U.storage.from("support-attachments").upload(p,h,{contentType:h.type,upsert:!1});if(x){ae.error(`${h.name}: ${x.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 U.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(kK,{className:"h-3.5 w-3.5 text-muted-foreground"}):e.jsx(gT,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"max-w-[160px] truncate",children:d.name}),e.jsx("button",{type:"button",onClick:()=>c(u),className:"text-muted-foreground hover:text-foreground",children:e.jsx(pr,{className:"h-3 w-3"})})]},d.path))}),e.jsxs($,{type:"button",variant:"outline",size:"sm",onClick:()=>{var d;return(d=a.current)==null?void 0:d.click()},disabled:n||i,className:"gap-1.5",children:[i?e.jsx(Ht,{className:"h-3.5 w-3.5 animate-spin"}):e.jsx(NT,{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 d8t({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 U.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(Ht,{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 M7={open:{label:"Open",icon:Hr,color:"bg-yellow-500"},in_progress:{label:"In Progress",icon:Ed,color:"bg-blue-500"},resolved:{label:"Resolved",icon:Ro,color:"bg-green-500"},closed:{label:"Closed",icon:$d,color:"bg-muted-foreground"}},out={general:"General Support",technology:"Technology Support",crm:"CRM Support",marketing:"Marketing Support"};function AUs(){const{user:s}=_s(),t=ts(),[n,r]=j.useState(null),[a,i]=j.useState(""),[l,o]=j.useState([]),{data:c=[],isLoading:d}=ht({queryKey:["support-tickets"],queryFn:async()=>{const{data:p,error:x}=await U.from("support_tickets").select("*").eq("user_id",s==null?void 0:s.id).order("created_at",{ascending:!1});if(x)throw x;return p},enabled:!!s}),{data:u=[]}=ht({queryKey:["ticket-replies",n==null?void 0:n.id],queryFn:async()=>{if(!n)return[];const{data:p,error:x}=await U.from("support_ticket_replies").select("*, profiles(name)").eq("ticket_id",n.id).order("created_at",{ascending:!0});if(x)throw x;return p},enabled:!!n}),h=yt({mutationFn:async({content:p,attachments:x})=>{if(!n||!s)throw new Error("Missing data");const{error:g}=await U.from("support_ticket_replies").insert({ticket_id:n.id,user_id:s.id,content:p,is_admin_reply:!1,attachments:x});if(g)throw g},onSuccess:()=>{t.invalidateQueries({queryKey:["ticket-replies",n==null?void 0:n.id]}),i(""),o([]),ae.success("Reply sent!")},onError:()=>{ae.error("Failed to send reply")}}),m=()=>{!a.trim()&&l.length===0||h.mutate({content:a,attachments:l})};if(n){const p=M7[n.status].icon;return e.jsx(Ks,{children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx($,{variant:"ghost",size:"icon",onClick:()=>r(null),children:e.jsx(ka,{className:"h-5 w-5"})}),e.jsxs("div",{className:"flex-1",children:[e.jsx("h1",{className:"text-2xl font-bold",children:n.subject}),e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[e.jsx($e,{variant:"secondary",children:out[n.category]}),e.jsxs($e,{className:M7[n.status].color,children:[e.jsx(p,{className:"h-3 w-3 mr-1"}),M7[n.status].label]})]})]})]}),e.jsxs(_e,{children:[e.jsx(Bt,{children:e.jsxs(vr,{children:["Created on ",Hs(new Date(n.created_at),"MMM d, yyyy 'at' h:mm a")]})}),e.jsx(Oe,{children:e.jsx("p",{className:"text-muted-foreground whitespace-pre-wrap",children:n.description})})]}),e.jsxs(_e,{children:[e.jsx(Bt,{children:e.jsx(Ut,{className:"text-lg",children:"Conversation"})}),e.jsxs(Oe,{children:[e.jsx(Oi,{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(x=>{var g;return e.jsxs("div",{className:`p-4 rounded-lg ${x.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:x.is_admin_reply?"Support Team":((g=x.profiles)==null?void 0:g.name)||"You"}),e.jsx("span",{className:"text-xs text-muted-foreground",children:Hs(new Date(x.created_at),"MMM d, h:mm a")})]}),e.jsx("p",{className:"text-sm whitespace-pre-wrap",children:x.content}),x.attachments&&x.attachments.length>0&&e.jsx(d8t,{attachments:x.attachments})]},x.id)})})}),n.status!=="closed"&&e.jsxs(e.Fragment,{children:[e.jsx(Hl,{className:"my-4"}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex gap-2",children:[e.jsx(Is,{placeholder:"Type your reply...",value:a,onChange:x=>i(x.target.value),className:"min-h-[80px]"}),e.jsx($,{onClick:m,disabled:!a.trim()&&l.length===0||h.isPending,className:"self-end",children:e.jsx(Br,{className:"h-4 w-4"})})]}),e.jsx(c8t,{value:l,onChange:o,disabled:h.isPending})]})]})]})]})]})})}return e.jsx(Ks,{children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(_e,{className:"bg-gradient-to-br from-primary/10 via-primary/5 to-background border-primary/20",children:e.jsx(Oe,{className:"p-6 sm:p-8",children:e.jsxs("div",{className:"flex flex-col sm:flex-row items-start sm:items-center gap-6",children:[e.jsx("div",{className:"p-4 bg-primary/20 rounded-full",children:e.jsx(Z4,{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(AFe,{trigger:e.jsxs($,{size:"lg",className:"gap-2",children:[e.jsx(sn,{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(ya,{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(AFe,{trigger:e.jsxs($,{variant:"outline",size:"sm",className:"gap-2",children:[e.jsx(sn,{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(_e,{className:"border-dashed",children:e.jsxs(Oe,{className:"text-center py-12",children:[e.jsx(Ed,{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 x=M7[p.status].icon;return e.jsx(_e,{className:"cursor-pointer hover:bg-muted/50 transition-colors",onClick:()=>r(p),children:e.jsx(Oe,{className:"p-4",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("h3",{className:"font-medium truncate",children:p.subject}),e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[e.jsx($e,{variant:"outline",className:"text-xs",children:out[p.category]}),e.jsx("span",{className:"text-xs text-muted-foreground",children:Hs(new Date(p.created_at),"MMM d, yyyy")})]})]}),e.jsxs($e,{className:M7[p.status].color,children:[e.jsx(x,{className:"h-3 w-3 mr-1"}),M7[p.status].label]})]})})},p.id)})})]})})}function EUs({open:s,onOpenChange:t}){return e.jsx(Os,{open:s,onOpenChange:t,children:e.jsxs(Rs,{className:"max-w-3xl max-h-[90vh] overflow-hidden",children:[e.jsx(Us,{children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-2 bg-primary/10 rounded-lg",children:e.jsx(ia,{className:"h-5 w-5 text-primary"})}),e.jsxs("div",{children:[e.jsx(zs,{children:"Schedule Agent Onboarding"}),e.jsx(Sr,{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 TUs({open:s,onOpenChange:t}){const{brokerageId:n}=_s(),[r,a]=j.useState(""),[i,l]=j.useState([]),[o,c]=j.useState(!1),{data:d,isLoading:u}=ht({queryKey:["brokerage-agents-for-onboarding",n],queryFn:async()=>{if(!n)return[];const{data:g,error:y}=await U.from("profiles").select("id, name, email").eq("brokerage_id",n).order("name",{ascending:!0});if(y)throw y;return g},enabled:s&&!!n}),h=d==null?void 0:d.filter(g=>g.name.toLowerCase().includes(r.toLowerCase())||g.email.toLowerCase().includes(r.toLowerCase())),m=g=>{l(y=>y.includes(g)?y.filter(b=>b!==g):[...y,g])},p=async()=>{if(i.length===0){ae.error("Please select at least one agent");return}c(!0);try{const{data:g,error:y}=await U.functions.invoke("send-onboarding-link",{body:{agentIds:i}});if(y)throw y;ae.success(`Onboarding link sent to ${i.length} agent${i.length>1?"s":""}`),l([]),t(!1)}catch(g){console.error("Error sending onboarding link:",g),ae.error(g.message||"Failed to send onboarding link")}finally{c(!1)}},x=g=>{g||(l([]),a("")),t(g)};return e.jsx(Os,{open:s,onOpenChange:x,children:e.jsxs(Rs,{className:"max-w-md",children:[e.jsx(Us,{children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-2 bg-primary/10 rounded-lg",children:e.jsx(Br,{className:"h-5 w-5 text-primary"})}),e.jsxs("div",{children:[e.jsx(zs,{children:"Send Onboarding Link"}),e.jsx(Sr,{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(Vr,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(be,{placeholder:"Search agents...",value:r,onChange:g=>a(g.target.value),className:"pl-10"})]}),u?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx(Ht,{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(qn,{className:"h-8 w-8 mx-auto mb-2 opacity-50"}),e.jsx("p",{children:"No agents found"})]}):e.jsx(Oi,{className:"h-[300px] border rounded-lg",children:e.jsx("div",{className:"p-2 space-y-1",children:h==null?void 0:h.map(g=>e.jsxs("div",{className:"flex items-center gap-3 p-2 rounded-lg hover:bg-muted cursor-pointer",onClick:()=>m(g.id),children:[e.jsx(ui,{checked:i.includes(g.id),onCheckedChange:()=>m(g.id)}),e.jsx(Ea,{className:"h-8 w-8",children:e.jsx(Ta,{className:"text-xs",children:g.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:g.name}),e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:g.email})]})]},g.id))})}),i.length>0&&e.jsxs("p",{className:"text-sm text-muted-foreground",children:[i.length," agent",i.length>1?"s":""," selected"]})]}),e.jsxs(kr,{children:[e.jsx($,{variant:"outline",onClick:()=>x(!1),children:"Cancel"}),e.jsx($,{onClick:p,disabled:i.length===0||o,children:o?e.jsxs(e.Fragment,{children:[e.jsx(Ht,{className:"h-4 w-4 mr-2 animate-spin"}),"Sending..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Br,{className:"h-4 w-4 mr-2"}),"Send Link"]})})]})]})})}function MUs(){const[s,t]=j.useState(!1),[n,r]=j.useState(!1);return e.jsxs(e.Fragment,{children:[e.jsxs(_e,{className:"mb-8",children:[e.jsx(Bt,{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(qn,{className:"h-6 w-6 text-primary"})}),e.jsxs("div",{children:[e.jsx(Ut,{children:"Agent Onboarding"}),e.jsx(vr,{children:"Schedule onboarding sessions for yourself or your agents"})]})]})}),e.jsx(Oe,{children:e.jsxs("div",{className:"flex flex-wrap gap-4",children:[e.jsxs($,{onClick:()=>t(!0),className:"flex items-center gap-2",children:[e.jsx(ia,{className:"h-4 w-4"}),"Schedule Agent Onboarding"]}),e.jsxs($,{variant:"outline",onClick:()=>r(!0),className:"flex items-center gap-2",children:[e.jsx(Br,{className:"h-4 w-4"}),"Send New Agent Onboarding Link"]})]})})]}),e.jsx(EUs,{open:s,onOpenChange:t}),e.jsx(TUs,{open:n,onOpenChange:r})]})}function LUs({open:s,onOpenChange:t}){return e.jsx(Os,{open:s,onOpenChange:t,children:e.jsxs(Rs,{className:"max-w-3xl max-h-[90vh] overflow-hidden",children:[e.jsx(Us,{children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-2 bg-primary/10 rounded-lg",children:e.jsx(w0,{className:"h-5 w-5 text-primary"})}),e.jsxs("div",{children:[e.jsx(zs,{children:"Schedule Launch Meeting"}),e.jsx(Sr,{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 PUs(){const[s,t]=j.useState(!1);return e.jsxs(e.Fragment,{children:[e.jsxs(_e,{className:"mb-8",children:[e.jsx(Bt,{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(w0,{className:"h-6 w-6 text-primary"})}),e.jsxs("div",{children:[e.jsx(Ut,{children:"Launch or ReLaunch Meeting"}),e.jsx(vr,{children:"Schedule a private LevelUp information session for your brokerage. Have one of our staff host a meeting to help your team get the most out of all our trainings, tools, and resources."})]})]})}),e.jsx(Oe,{children:e.jsxs($,{onClick:()=>t(!0),className:"flex items-center gap-2",children:[e.jsx(w0,{className:"h-4 w-4"}),"Schedule Launch Meeting"]})})]}),e.jsx(LUs,{open:s,onOpenChange:t})]})}function IUs(){const s=Vn(),[t,n]=j.useState(""),[r,a]=j.useState(null),{data:i,isLoading:l}=ht({queryKey:["brokerage-resources-published"],queryFn:async()=>{const{data:g,error:y}=await U.from("brokerage_resources").select("*").eq("is_published",!0).order("publish_date",{ascending:!1});if(y)throw y;return g}}),{data:o}=ht({queryKey:["brokerage-resource-categories"],queryFn:async()=>{const{data:g,error:y}=await U.from("brokerage_resource_categories").select("*").order("sort_order",{ascending:!0});if(y)throw y;return g}}),{data:c}=ht({queryKey:["brokerage-resource-pdfs-all"],queryFn:async()=>{const{data:g,error:y}=await U.from("brokerage_resource_pdfs").select("resource_id");if(y)throw y;return g}}),{data:d}=ht({queryKey:["brokerage-resource-videos-all"],queryFn:async()=>{const{data:g,error:y}=await U.from("brokerage_resource_videos").select("resource_id");if(y)throw y;return g}}),{data:u}=ht({queryKey:["brokerage-resource-links-all"],queryFn:async()=>{const{data:g,error:y}=await U.from("brokerage_resource_links").select("resource_id");if(y)throw y;return g}}),h=i==null?void 0:i.filter(g=>{var v;const y=g.title.toLowerCase().includes(t.toLowerCase())||((v=g.description)==null?void 0:v.toLowerCase().includes(t.toLowerCase())),b=!r||g.category_id===r;return y&&b}),m=o==null?void 0:o.filter(g=>i==null?void 0:i.some(y=>y.category_id===g.id)),p=g=>{const y=(c==null?void 0:c.filter(N=>N.resource_id===g).length)||0,b=(d==null?void 0:d.filter(N=>N.resource_id===g).length)||0,v=(u==null?void 0:u.filter(N=>N.resource_id===g).length)||0;return{pdfCount:y,videoCount:b,linkCount:v}},x=g=>{s(`/brokerage-resources/${g}`)};return e.jsx(Ks,{title:"Brokerage Resources",description:"Access exclusive resources for brokerage managers",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(MUs,{}),e.jsx(PUs,{}),e.jsxs("div",{className:"relative max-w-md",children:[e.jsx(Vr,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(be,{placeholder:"Search resources...",value:t,onChange:g=>n(g.target.value),className:"pl-10"})]}),m&&m.length>0&&e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx($e,{variant:r===null?"default":"outline",className:"cursor-pointer",onClick:()=>a(null),children:"All"}),m.map(g=>e.jsx($e,{variant:r===g.id?"default":"outline",className:"cursor-pointer",onClick:()=>a(g.id),children:g.name},g.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((g,y)=>e.jsxs(_e,{children:[e.jsx(on,{className:"h-40 w-full"}),e.jsx(Bt,{children:e.jsx(on,{className:"h-5 w-3/4"})}),e.jsxs(Oe,{children:[e.jsx(on,{className:"h-4 w-full mb-2"}),e.jsx(on,{className:"h-4 w-2/3"})]})]},y))}):(h==null?void 0:h.length)===0?e.jsxs(_e,{className:"p-12 text-center",children:[e.jsx(ix,{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(g=>{const{pdfCount:y,videoCount:b,linkCount:v}=p(g.id),N=o==null?void 0:o.find(C=>C.id===g.category_id);return e.jsxs(_e,{className:"overflow-hidden cursor-pointer hover:shadow-lg transition-shadow",onClick:()=>x(g.id),children:[g.preview_image_url?e.jsx("img",{src:g.preview_image_url,alt:g.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(ix,{className:"h-16 w-16 text-muted-foreground"})}),e.jsx(Bt,{className:"pb-2",children:e.jsxs("div",{className:"flex items-start justify-between gap-2",children:[e.jsx(Ut,{className:"text-lg line-clamp-1",children:g.title}),N&&e.jsx($e,{variant:"secondary",className:"shrink-0 text-xs",children:N.name})]})}),e.jsxs(Oe,{children:[g.description&&e.jsx("p",{className:"text-sm text-muted-foreground line-clamp-2 mb-3",children:g.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(Wr,{className:"h-4 w-4"}),y]}),b>0&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Xr,{className:"h-4 w-4"}),b]}),v>0&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(kc,{className:"h-4 w-4"}),v]})]})]})]},g.id)})})]})})}const DUs=()=>{const{resourceId:s}=Vi(),{data:t,isLoading:n}=ht({queryKey:["brokerage-resource-detail",s],queryFn:async()=>{const{data:a,error:i}=await U.from("brokerage_resources").select("*").eq("id",s).eq("is_published",!0).single();if(i)throw i;const{data:l}=await U.from("brokerage_resource_pdfs").select("*").eq("resource_id",s).order("sort_order"),{data:o}=await U.from("brokerage_resource_videos").select("*").eq("resource_id",s).order("sort_order"),{data:c}=await U.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(Ks,{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(Ks,{title:t.title,children:e.jsxs("div",{className:"space-y-6 max-w-5xl mx-auto",children:[e.jsx($,{variant:"ghost",size:"sm",asChild:!0,className:"gap-2",children:e.jsxs(Wn,{to:"/brokerage-resources",children:[e.jsx(ka,{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(_e,{children:e.jsxs(Oe,{className:"pt-6",children:[e.jsxs("h3",{className:"font-semibold flex items-center gap-2 mb-4",children:[e.jsx(Xr,{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(_e,{children:e.jsxs(Oe,{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"}),"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(Wr,{className:"h-4 w-4 text-primary"})}),e.jsxs("div",{children:[e.jsx("div",{className:"font-medium text-sm",children:a.name}),a.file_size&&e.jsx("div",{className:"text-xs text-muted-foreground",children:r(a.file_size)})]})]}),e.jsx(di,{className:"h-4 w-4 text-muted-foreground group-hover:text-primary transition-colors"})]},a.id))})]})}),t.links&&t.links.length>0&&e.jsx(_e,{children:e.jsxs(Oe,{className:"pt-6",children:[e.jsxs("h3",{className:"font-semibold flex items-center gap-2 mb-4",children:[e.jsx(Tr,{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(Tr,{className:"h-4 w-4 text-primary"})}),e.jsx("div",{className:"font-medium text-sm",children:a.title})]}),e.jsx(Tr,{className:"h-4 w-4 text-muted-foreground group-hover:text-primary transition-colors"})]},a.id))})]})})]})}):e.jsx(Ks,{title:"Brokerage Resources",children:e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(ix,{className:"h-12 w-12 text-muted-foreground mb-4"}),e.jsx("h3",{className:"text-lg font-semibold",children:"Resource not found"}),e.jsx("p",{className:"text-muted-foreground mt-1",children:"This resource may have been removed or is not available."}),e.jsx($,{asChild:!0,className:"mt-4",children:e.jsx(Wn,{to:"/brokerage-resources",children:"Back to Resources"})})]})})};function RUs(){const{onlineUsers:s,totalOnline:t}=YSt(),{user:n}=_s();return e.jsxs(_e,{children:[e.jsx(Bt,{className:"pb-3",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(Ut,{className:"text-base flex items-center gap-2",children:[e.jsx(qn,{className:"h-4 w-4"}),"Online Now"]}),e.jsxs($e,{variant:"secondary",className:"bg-green-100 text-green-700",children:[e.jsx(Bp,{className:"h-2 w-2 fill-green-500 text-green-500 mr-1"}),t," online"]})]})}),e.jsx(Oe,{children:s.length===0?e.jsx("p",{className:"text-sm text-muted-foreground text-center py-4",children:"No users online right now"}):e.jsx(Oi,{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(ki,{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 ",fc(new Date(r.onlineSince),{addSuffix:!1})]})]})]},r.id)})})})})]})}const lut={users:{label:"Users & Access",sections:[{title:"Member Broadcasts",description:"Email a filtered group of members (paste HTML or write it)",icon:Eh,path:"/admin/broadcasts",color:"bg-rose-500/10 text-rose-600"},{title:"Members",description:"Manage users, roles, and brokerage assignments",icon:qn,path:"/admin/members",color:"bg-blue-500/10 text-blue-600"},{title:"Partnerships",description:"Manage partnership packages, rosters, and upgrade requests",icon:Co,path:"/admin/partnerships",color:"bg-indigo-500/10 text-indigo-600"},{title:"Invite Codes",description:"Create and manage signup invite codes",icon:CR,path:"/admin/invite-codes",color:"bg-amber-500/10 text-amber-600"},{title:"Subscriptions",description:"Track and manage user subscriptions",icon:yy,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:_K,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:Up,path:"/admin/discounts",color:"bg-red-500/10 text-red-600"},{title:"Referral Program",description:"Track brokerage referrals and discounts",icon:vd,path:"/admin/referrals",color:"bg-teal-500/10 text-teal-600"},{title:"Teams",description:"Manage agent teams across all brokerages",icon:qn,path:"/admin/members?tab=teams",color:"bg-violet-500/10 text-violet-600"},{title:"Prospector",description:"Send free trial invites and track conversions",icon:Mu,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:il,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:pl,path:"/admin/coaching",color:"bg-gradient-to-br from-teal-500/20 to-cyan-500/10 text-teal-600"}]},content:{label:"Content",sections:[{title:"Manage Templates",description:"Upload and organize Canva templates",icon:Rc,path:"/admin/templates",color:"bg-pink-500/10 text-pink-600"},{title:"Manage Programs",description:"Cohorts, enrollments and delayed billing",icon:Ph,path:"/admin/programs",color:"bg-emerald-500/10 text-emerald-600"},{title:"Manage Academy",description:"Upload videos and training content",icon:Ph,path:"/admin/academy",color:"bg-indigo-500/10 text-indigo-600"},{title:"Manage Toolbox",description:"Create and manage resource kits",icon:c5,path:"/admin/toolbox",color:"bg-orange-500/10 text-orange-600"},{title:"Social Swag",description:"Manage social media content and links",icon:dn,path:"/admin/social-swag",color:"bg-fuchsia-500/10 text-fuchsia-600"},{title:"Social Swag 2.0",description:"New monthly social media images",icon:dn,path:"/admin/social-swag-2",color:"bg-cyan-500/10 text-cyan-600"},{title:"Newsletters",description:"Manage monthly newsletter templates",icon:Gj,path:"/admin/newsletters",color:"bg-violet-500/10 text-violet-600"},{title:"Newsletter Graphics",description:"Upload branded graphics agents drop into newsletters & emails",icon:Gj,path:"/admin/newsletter-graphics",color:"bg-fuchsia-500/10 text-fuchsia-600"},{title:"Manage Events",description:"Create and publish events with Zoom integration",icon:Nl,path:"/admin/events",color:"bg-green-500/10 text-green-600"},{title:"LevelUp Live",description:"Public streaming pages, invite links, and live leads",icon:Cg,path:"/admin/live",color:"bg-red-500/10 text-red-600"},{title:"Additional Services",description:"Manage additional service offerings",icon:ix,path:"/admin/additional-services",color:"bg-lime-500/10 text-lime-600"},{title:"Brokerage Resources",description:"Manage resources for brokerage managers",icon:ix,path:"/admin/brokerage-resources",color:"bg-slate-500/10 text-slate-600"},{title:"Agent Email Templates",description:"Manage curated email templates for agents",icon:nn,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:Eh,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:gR,path:"/admin/dashboard-management",color:"bg-teal-500/10 text-teal-600"},{title:"Manage Apps",description:"Configure app tiles and access requirements",icon:R_,path:"/admin/apps",color:"bg-purple-500/10 text-purple-600"},{title:"Email Templates",description:"Customize system email templates",icon:nn,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:Eh,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:n5,path:"/admin/onboarding-checklist",color:"bg-emerald-500/10 text-emerald-600"},{title:"Marketplace",description:"Manage store categories, products, and orders",icon:l5,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:Co,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:pl,path:"/admin/agent-points",color:"bg-amber-500/10 text-amber-600"},{title:"Integrations",description:"Connect Canva, Facebook & Instagram for platform-level features",icon:Dc,path:"/admin/integrations",color:"bg-blue-500/10 text-blue-600"},{title:"Agent Cards",description:"Manage digital business cards for agents",icon:qn,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:Eh,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:Ji,path:"/admin/community",color:"bg-cyan-500/10 text-cyan-600"},{title:"Support Tickets",description:"View and respond to agent support requests",icon:Nz,path:"/admin/support-tickets",color:"bg-rose-500/10 text-rose-600"},{title:"Wishlist",description:"Review and manage community feature requests",icon:i5,path:"/admin/wishlist",color:"bg-yellow-500/10 text-yellow-600"},{title:"Membership Reviews",description:"View member feedback and ratings",icon:Qa,path:"/admin/membership-reviews",color:"bg-amber-500/10 text-amber-600"},{title:"Weekly Digest",description:"Configure automated weekly email digests",icon:nn,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:ml,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:wf,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:by,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:Ph,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:fo,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:sa,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:il,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:il,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:by,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:Wr,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:dn,path:"/admin/listing-revival",color:"bg-gradient-to-br from-amber-500/20 to-yellow-500/10 text-amber-600"},{title:"Weekly Reels",description:"Manage Weekly Reels access, generation runs, and email delivery",icon:lh,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:wf,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:Jl,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:nn,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:yT,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:Gl,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:wK,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:Co,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:Il,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:Wr,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:Wr,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:Wr,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:qd,path:"/admin/mls-fee-tracker",color:"bg-gradient-to-br from-teal-500/20 to-cyan-500/10 text-teal-600"}]}};function cut(){const s=Vn();return console.log("[AdminDashboard] render"),e.jsx(Ks,{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(ua,{defaultValue:"users",className:"w-full",children:[e.jsx(ha,{className:"w-full justify-start flex-wrap h-auto gap-1 bg-muted/50 p-1 overflow-x-auto",children:Object.entries(lut).map(([t,n])=>e.jsx(Qt,{value:t,className:"data-[state=active]:bg-background",children:n.label},t))}),Object.entries(lut).map(([t,n])=>e.jsx(Jt,{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(_e,{className:"cursor-pointer hover:shadow-md transition-all hover:border-primary/50 group",onClick:()=>s(r.path),children:[e.jsxs(Bt,{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(Ut,{className:"text-base",children:r.title})]}),e.jsx(Oe,{className:"pt-0",children:e.jsx(vr,{className:"text-sm",children:r.description})})]},r.path))})},t))]}),e.jsx(RUs,{})]})})}const OUs=()=>{const{isAdmin:s}=_s(),t=Vn(),[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:g,error:y}=await U.from("app_tiles").select("*").order("name");if(y)throw y;r(g||[])}catch(g){console.error("Error loading apps:",g),ae.error("Failed to load apps")}finally{i(!1)}},h=async g=>{g.preventDefault();const y=new FormData(g.currentTarget),b={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(v=>v.trim()).filter(Boolean)};try{if(c){const{error:v}=await U.from("app_tiles").update(b).eq("id",c.id);if(v)throw v;ae.success("App updated successfully")}else{const{error:v}=await U.from("app_tiles").insert([b]);if(v)throw v;ae.success("App created successfully")}o(!1),d(null),u()}catch(v){console.error("Error saving app:",v),ae.error("Failed to save app")}},m=async g=>{if(await Yi("Are you sure you want to delete this app?"))try{const{error:y}=await U.from("app_tiles").delete().eq("id",g);if(y)throw y;ae.success("App deleted successfully"),u()}catch(y){console.error("Error deleting app:",y),ae.error("Failed to delete app")}},p=g=>{d(g),o(!0)},x=()=>{d(null),o(!0)};return a?e.jsx("div",{className:"flex items-center justify-center min-h-screen",children:"Loading..."}):e.jsxs("div",{className:"min-h-screen bg-background",children:[e.jsx("header",{className:"border-b bg-card",children:e.jsx("div",{className:"container mx-auto px-4 py-4",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsxs($,{variant:"ghost",size:"sm",onClick:()=>t("/dashboard"),children:[e.jsx(ka,{className:"h-4 w-4 mr-2"}),"Back"]}),e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold",children:"Manage Apps"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Create and configure application tiles"})]})]}),e.jsxs(Os,{open:l,onOpenChange:o,children:[e.jsx(Ko,{asChild:!0,children:e.jsxs($,{onClick:x,children:[e.jsx(sn,{className:"mr-2 h-4 w-4"}),"Add App"]})}),e.jsxs(Rs,{className:"max-w-2xl",children:[e.jsxs(Us,{children:[e.jsx(zs,{children:c?"Edit App":"Create New App"}),e.jsx(Sr,{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(se,{htmlFor:"name",children:"App Name"}),e.jsx(be,{id:"name",name:"name",defaultValue:c==null?void 0:c.name,required:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"app_id",children:"App ID"}),e.jsx(be,{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(se,{htmlFor:"description",children:"Description"}),e.jsx(Is,{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(se,{htmlFor:"icon",children:"Icon (emoji)"}),e.jsx(be,{id:"icon",name:"icon",defaultValue:c==null?void 0:c.icon,placeholder:"🚀",required:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"target_url",children:"Target URL"}),e.jsx(be,{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(se,{htmlFor:"required_tags",children:"Required Tags (comma-separated)"}),e.jsx(be,{id:"required_tags",name:"required_tags",defaultValue:c==null?void 0:c.required_tags.join(", "),placeholder:"levelup-member, agent-connect"})]}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx($,{type:"button",variant:"outline",onClick:()=>o(!1),children:"Cancel"}),e.jsx($,{type:"submit",children:c?"Update":"Create"})]})]})]})]})]})})}),e.jsx("div",{className:"container mx-auto px-4 py-8",children:e.jsxs(_e,{children:[e.jsxs(Bt,{children:[e.jsx(Ut,{children:"Application Tiles"}),e.jsx(vr,{children:"Manage the apps that appear on the member dashboard"})]}),e.jsx(Oe,{children:n.length===0?e.jsxs("div",{className:"text-center py-12",children:[e.jsx("p",{className:"text-muted-foreground mb-4",children:"No apps configured yet"}),e.jsxs($,{onClick:x,children:[e.jsx(sn,{className:"mr-2 h-4 w-4"}),"Create First App"]})]}):e.jsxs(Va,{children:[e.jsx(Ha,{children:e.jsxs(hn,{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(Ga,{children:n.map(g=>e.jsxs(hn,{children:[e.jsx(gt,{className:"text-2xl",children:g.icon}),e.jsx(gt,{className:"font-medium",children:g.name}),e.jsx(gt,{className:"font-mono text-sm",children:g.app_id}),e.jsx(gt,{className:"text-sm text-muted-foreground max-w-xs truncate",children:g.target_url}),e.jsx(gt,{children:e.jsx("div",{className:"flex flex-wrap gap-1",children:g.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($,{size:"sm",variant:"ghost",onClick:()=>p(g),children:e.jsx(Ya,{className:"h-4 w-4"})}),e.jsx($,{size:"sm",variant:"ghost",onClick:()=>m(g.id),children:e.jsx(Pn,{className:"h-4 w-4"})})]})})]},g.id))})]})})]})})]})};function hh({title:s,description:t,children:n}){return e.jsxs("div",{className:"space-y-4",children:[e.jsx(Wn,{to:"/admin",children:e.jsxs($,{variant:"ghost",size:"sm",className:"gap-2 text-muted-foreground hover:text-foreground",children:[e.jsx(ka,{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 dut=({expiresAt:s,className:t})=>{const n=new Date().getTime(),r=new Date(s).getTime(),a=Math.ceil((r-n)/(1e3*60*60*24));return a<=0?e.jsxs($e,{variant:"destructive",className:Tt("gap-1",t),children:[e.jsx(mc,{className:"h-3 w-3"}),"Trial Expired"]}):a<=1?e.jsxs($e,{variant:"destructive",className:Tt("gap-1",t),children:[e.jsx(Hr,{className:"h-3 w-3"}),"Trial: <1 day left"]}):a<=3?e.jsxs($e,{className:Tt("gap-1 bg-amber-500 hover:bg-amber-600",t),children:[e.jsx(Hr,{className:"h-3 w-3"}),"Trial: ",a," days left"]}):e.jsxs($e,{variant:"secondary",className:Tt("gap-1",t),children:[e.jsx(Hr,{className:"h-3 w-3"}),"Trial: ",a," days left"]})},u8t=({open:s,onOpenChange:t,brokerages:n,fixedBrokerageId:r,onSuccess:a})=>{const{toast:i}=gi(),l=j.useRef(null),[o,c]=j.useState([]),[d,u]=j.useState(""),[h,m]=j.useState(!1),[p,x]=j.useState("upload"),[g,y]=j.useState(null),b=()=>{c([]),u(""),x("upload"),y(null),l.current&&(l.current.value="")},v=()=>{b(),t(!1)},N=M=>{const I=M.split(` `).map(V=>V.trim()).filter(V=>V);if(I.length===0)return[];const D=I[0].toLowerCase(),q=D.includes("first")||D.includes("last")||D.includes("email")||D.includes("name")||D.includes("phone")||D.includes("sms")||D.includes("consent")?I.slice(1):I,W=[];for(const V of q){const Q=(V.includes(" ")?V.split(" "):V.split(",")).map(J=>J.trim().replace(/^["']|["']$/g,""));if(Q.length>=2){let J="",ce="",ue="",ne="",ee;if(Q.length===2){const ve=Q[0].split(" ");J=ve[0]||"",ce=ve.slice(1).join(" ")||"",ue=Q[1]}else if(Q.length===3)J=Q[0],ce=Q[1],ue=Q[2];else if(Q.length===4)J=Q[0],ce=Q[1],ue=Q[2],ne=Q[3];else if(Q.length>=5){J=Q[0],ce=Q[1],ue=Q[2],ne=Q[3];const ve=Q[4].toLowerCase();ee=ve==="true"||ve==="yes"||ve==="1"||ve==="y"}const he=/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(ue);W.push({firstName:J.trim(),lastName:ce.trim(),email:ue.trim().toLowerCase(),phone:ne.trim()||void 0,smsConsent:ee,isValid:he&&J.trim().length>0,error:he?J.trim()?void 0:"Missing name":"Invalid email"})}}return W},C=M=>{var B;const I=(B=M.target.files)==null?void 0:B[0];if(!I)return;const D=new FileReader;D.onload=q=>{var K;const W=(K=q.target)==null?void 0:K.result,V=N(W);if(V.length===0){i({title:"No data found",description:"The CSV file appears to be empty or in an unsupported format.",variant:"destructive"});return}c(V),x("preview")},D.readAsText(I)},A=async()=>{const M=o.filter(D=>D.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:D}}=await U.auth.getSession(),B=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/bulk-create-users",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${D==null?void 0:D.access_token}`},body:JSON.stringify({users:M.map(W=>({firstName:W.firstName,lastName:W.lastName,email:W.email,phone:W.phone,smsConsent:W.smsConsent})),brokerageId:I})}),q=await B.json();if(!B.ok)throw new Error(q.error||"Failed to import users");y(q),x("result"),q.created>0&&a(),i({title:"Import Complete",description:`${q.created} user(s) created successfully.${q.failed>0?` ${q.failed} failed.`:""}`})}catch(D){console.error("Import error:",D),i({title:"Import Failed",description:D.message||"Failed to import users",variant:"destructive"})}finally{m(!1)}},T=o.filter(M=>M.isValid).length,P=o.filter(M=>!M.isValid).length;return e.jsx(Os,{open:s,onOpenChange:v,children:e.jsxs(Rs,{className:"max-w-2xl max-h-[85vh] overflow-hidden flex flex-col",children:[e.jsxs(Us,{children:[e.jsxs(zs,{className:"flex items-center gap-2",children:[e.jsx(PN,{className:"h-5 w-5"}),"Import Agents from CSV"]}),e.jsx(Sr,{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:C,className:"hidden"}),e.jsx(si,{className:"h-10 w-10 mx-auto text-muted-foreground mb-4"}),e.jsx("p",{className:"text-sm text-muted-foreground mb-4",children:"Click to upload or drag and drop a CSV file"}),e.jsx($,{onClick:()=>{var 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(se,{children:"Assign to Brokerage (optional)"}),e.jsxs(vs,{value:d||"none",onValueChange:M=>u(M==="none"?"":M),children:[e.jsx(gs,{children:e.jsx(bs,{placeholder:"Select a brokerage..."})}),e.jsxs(ys,{children:[e.jsx(Ye,{value:"none",children:"No brokerage"}),n.map(M=>e.jsx(Ye,{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(Fr,{className:"h-4 w-4 text-green-500"}),e.jsxs("span",{children:[T," valid"]})]}),P>0&&e.jsxs("div",{className:"flex items-center gap-2 text-destructive",children:[e.jsx(xo,{className:"h-4 w-4"}),e.jsxs("span",{children:[P," invalid"]})]})]}),e.jsxs("div",{className:"flex-1 overflow-auto border rounded-lg",children:[e.jsxs(Va,{children:[e.jsx(Ha,{children:e.jsxs(hn,{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(Ga,{children:o.slice(0,100).map((M,I)=>e.jsxs(hn,{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($e,{variant:"default",className:"bg-green-500/10 text-green-600",children:"Valid"}):e.jsx($e,{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"&&g&&e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{className:"text-center",children:[e.jsx(Fr,{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:[g.created," agent(s) created and invited"]}),g.failed>0&&e.jsxs("p",{className:"text-destructive mt-1",children:[g.failed," failed to create"]})]}),g.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:[g.errors.slice(0,10).map((M,I)=>e.jsxs("li",{children:["• ",M]},I)),g.errors.length>10&&e.jsxs("li",{children:["...and ",g.errors.length-10," more"]})]})]})]}),e.jsxs(kr,{children:[p==="upload"&&e.jsx($,{variant:"outline",onClick:v,children:"Cancel"}),p==="preview"&&e.jsxs(e.Fragment,{children:[e.jsx($,{variant:"outline",onClick:b,children:"Back"}),e.jsx($,{onClick:A,disabled:h||T===0,children:h?e.jsxs(e.Fragment,{children:[e.jsx(Ht,{className:"mr-2 h-4 w-4 animate-spin"}),"Importing..."]}):`Import ${T} Agent${T!==1?"s":""}`})]}),p==="result"&&e.jsx($,{onClick:v,children:"Done"})]})]})})};function Ku({sortKey:s,currentSortKey:t,currentDirection:n,onSort:r,children:a,className:i,...l}){const o=t===s;return e.jsx(Lt,{className:Tt("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(sp,{className:"h-3.5 w-3.5 shrink-0"}):e.jsx(ax,{className:"h-3.5 w-3.5 shrink-0"}):e.jsx(Tx,{className:"h-3.5 w-3.5 shrink-0 opacity-40"})]})})}function Iee(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),x=u(m);if(p==null&&x==null)return 0;if(p==null)return 1;if(x==null)return-1;let g;return typeof p=="string"&&typeof x=="string"?g=p.localeCompare(x,void 0,{sensitivity:"base"}):g=p-x,a==="asc"?g:-g})},[n,a]);return{sortKey:n,sortDirection:a,handleSort:l,sortData:o}}const FUs=[{type:"custom",title:"Great job!",message:"Keep up the amazing work!",icon:Qa},{type:"custom",title:"You're on fire!",message:"Your dedication is inspiring!",icon:pl},{type:"custom",title:"Congratulations!",message:"You earned this celebration!",icon:Nf}];function h8t({open:s,onOpenChange:t,userId:n,userName:r}){const[a,i]=j.useState("custom"),[l,o]=j.useState(""),[c,d]=j.useState(""),u=Cbs(),h=p=>{i(p.type),o(p.title),d(p.message)},m=async p=>{if(p.preventDefault(),!l.trim()){ja({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}),ja({title:"Celebration sent! 🎉",description:`${r} will see confetti on their next visit!`}),t(!1),o(""),d(""),i("custom")}catch{ja({title:"Error",description:"Failed to send celebration",variant:"destructive"})}};return e.jsx(Os,{open:s,onOpenChange:t,children:e.jsxs(Rs,{className:"sm:max-w-md",children:[e.jsxs(Us,{children:[e.jsxs(zs,{className:"flex items-center gap-2",children:[e.jsx(Nf,{className:"h-5 w-5 text-primary"}),"Send Celebration to ",r]}),e.jsx(Sr,{children:"They'll see confetti and this message next time they log in!"})]}),e.jsxs("div",{className:"mb-4",children:[e.jsx(se,{className:"text-sm text-muted-foreground mb-2 block",children:"Quick presets:"}),e.jsx("div",{className:"flex gap-2 flex-wrap",children:FUs.map((p,x)=>e.jsxs($,{variant:"outline",size:"sm",onClick:()=>h(p),className:"text-xs",children:[e.jsx(p.icon,{className:"h-3 w-3 mr-1"}),p.title]},x))})]}),e.jsxs("form",{onSubmit:m,className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(se,{htmlFor:"type",children:"Celebration Type"}),e.jsxs(vs,{value:a,onValueChange:p=>i(p),children:[e.jsx(gs,{children:e.jsx(bs,{})}),e.jsxs(ys,{children:[e.jsx(Ye,{value:"custom",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Qa,{className:"h-4 w-4"})," Custom"]})}),e.jsx(Ye,{value:"points_earned",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(pl,{className:"h-4 w-4"})," Points Earned"]})}),e.jsx(Ye,{value:"listing_created",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(sa,{className:"h-4 w-4"})," Listing Created"]})}),e.jsx(Ye,{value:"deal_closed",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(qd,{className:"h-4 w-4"})," Deal Closed"]})})]})]})]}),e.jsxs("div",{children:[e.jsx(se,{htmlFor:"title",children:"Title *"}),e.jsx(be,{id:"title",value:l,onChange:p=>o(p.target.value),placeholder:"e.g., Congratulations!",maxLength:100})]}),e.jsxs("div",{children:[e.jsx(se,{htmlFor:"message",children:"Message (optional)"}),e.jsx(Is,{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($,{type:"button",variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsxs($,{type:"submit",disabled:u.isPending,children:[e.jsx(Nf,{className:"h-4 w-4 mr-2"}),u.isPending?"Sending...":"Send Celebration"]})]})]})]})})}const wIe={points_earned:{label:"Points Earned",icon:pl,color:"bg-yellow-500"},listing_created:{label:"Listing Created",icon:sa,color:"bg-blue-500"},deal_closed:{label:"Deal Closed",icon:qd,color:"bg-green-500"},custom:{label:"Custom",icon:dn,color:"bg-purple-500"}};function zUs(){const[s,t]=j.useState(""),[n,r]=j.useState("all"),[a,i]=j.useState("all"),{data:l=[],isLoading:o}=ht({queryKey:["admin-celebrations"],queryFn:async()=>{const{data:u,error:h}=await U.from("celebration_queue").select("*").order("created_at",{ascending:!1}).limit(500);if(h)throw h;const m=[...new Set([...u.map(g=>g.user_id),...u.map(g=>g.created_by).filter(Boolean)])],{data:p}=await U.from("profiles").select("id, name, email").in("id",m),x=new Map((p==null?void 0:p.map(g=>[g.id,g]))||[]);return u.map(g=>{var y,b,v;return{...g,user_name:((y=x.get(g.user_id))==null?void 0:y.name)||"Unknown",user_email:((b=x.get(g.user_id))==null?void 0:b.email)||"",creator_name:g.created_by?((v=x.get(g.created_by))==null?void 0:v.name)||"System":"Auto-triggered"}})}}),c=l.filter(u=>{var x,g;const h=((x=u.user_name)==null?void 0:x.toLowerCase().includes(s.toLowerCase()))||((g=u.user_email)==null?void 0:g.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(wIe).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(Ht,{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(_e,{children:[e.jsx(Bt,{className:"pb-2",children:e.jsx(Ut,{className:"text-sm font-medium",children:"Total Celebrations"})}),e.jsx(Oe,{children:e.jsx("div",{className:"text-2xl font-bold",children:d.total})})]}),e.jsxs(_e,{children:[e.jsx(Bt,{className:"pb-2",children:e.jsx(Ut,{className:"text-sm font-medium text-green-600",children:"Seen"})}),e.jsx(Oe,{children:e.jsx("div",{className:"text-2xl font-bold text-green-600",children:d.seen})})]}),e.jsxs(_e,{children:[e.jsx(Bt,{className:"pb-2",children:e.jsx(Ut,{className:"text-sm font-medium text-orange-600",children:"Pending"})}),e.jsx(Oe,{children:e.jsx("div",{className:"text-2xl font-bold text-orange-600",children:d.unseen})})]}),e.jsxs(_e,{children:[e.jsx(Bt,{className:"pb-2",children:e.jsx(Ut,{className:"text-sm font-medium text-purple-600",children:"Custom Sent"})}),e.jsx(Oe,{children:e.jsx("div",{className:"text-2xl font-bold text-purple-600",children:d.byType.custom||0})})]})]}),e.jsxs(_e,{children:[e.jsxs(Bt,{children:[e.jsxs(Ut,{className:"flex items-center gap-2",children:[e.jsx(Nf,{className:"h-5 w-5"}),"Celebration History"]}),e.jsx(vr,{children:"View all celebrations awarded to agents"})]}),e.jsxs(Oe,{className:"space-y-4",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row gap-4",children:[e.jsxs("div",{className:"relative flex-1",children:[e.jsx(Vr,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(be,{placeholder:"Search by agent name, email, or title...",value:s,onChange:u=>t(u.target.value),className:"pl-9"})]}),e.jsxs(vs,{value:n,onValueChange:r,children:[e.jsx(gs,{className:"w-[180px]",children:e.jsx(bs,{placeholder:"Filter by type"})}),e.jsxs(ys,{children:[e.jsx(Ye,{value:"all",children:"All Types"}),Object.entries(wIe).map(([u,h])=>e.jsx(Ye,{value:u,children:h.label},u))]})]}),e.jsxs(vs,{value:a,onValueChange:i,children:[e.jsx(gs,{className:"w-[140px]",children:e.jsx(bs,{placeholder:"Status"})}),e.jsxs(ys,{children:[e.jsx(Ye,{value:"all",children:"All Status"}),e.jsx(Ye,{value:"seen",children:"Seen"}),e.jsx(Ye,{value:"unseen",children:"Pending"})]})]})]}),e.jsx("div",{className:"rounded-md border",children:e.jsxs(Va,{children:[e.jsx(Ha,{children:e.jsxs(hn,{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(Ga,{children:c.length===0?e.jsx(hn,{children:e.jsx(gt,{colSpan:7,className:"text-center py-8 text-muted-foreground",children:"No celebrations found"})}):c.map(u=>{const h=wIe[u.celebration_type],m=h.icon;return e.jsxs(hn,{children:[e.jsx(gt,{children:e.jsxs($e,{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($e,{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:Hs(new Date(u.created_at),"MMM d, yyyy h:mm a")})}),e.jsx(gt,{children:u.seen_at?e.jsx($e,{variant:"outline",className:"bg-green-50 text-green-700 border-green-200",children:"Seen"}):e.jsx($e,{variant:"outline",className:"bg-orange-50 text-orange-700 border-orange-200",children:"Pending"})})]},u.id)})})]})}),c.length>0&&e.jsxs("p",{className:"text-sm text-muted-foreground text-right",children:["Showing ",c.length," of ",l.length," celebrations"]})]})]})]})}const BUs=()=>{const{user:s}=_s(),{toast:t}=gi(),[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"),[x,g]=j.useState(new Set),y=j.useCallback(async()=>{try{i(!0);const{data:W,error:V}=await U.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:Q}=await U.from("trial_email_exports").select("user_id");if(Q)throw Q;const J=new Set((K||[]).map(ue=>ue.user_id)),ce=(W||[]).map(ue=>({...ue,converted_from_trial_at:ue.converted_from_trial_at??null,already_exported:J.has(ue.id)}));ce.sort((ue,ne)=>new Date(ne.created_at).getTime()-new Date(ue.created_at).getTime()),r(ce)}catch(W){console.error("Error loading trial users:",W),t({title:"Error",description:"Failed to load trial users",variant:"destructive"})}finally{i(!1)}},[t]);j.useEffect(()=>{y()},[y]);const b=W=>W.trial_started_at?"ghl":"stripe",v=W=>W.trial_expires_at?W.trial_expires_at:W.subscription_end_date?W.subscription_end_date:null,N=W=>W.converted_from_trial_at!==null,C=W=>{if(N(W))return!1;const V=v(W);return V?new Date(V).getTime()<=Date.now():!1},A=n.filter(W=>!(c!=="all"&&b(W)!==c||u==="active"&&(C(W)||N(W))||u==="expired"&&!C(W)||u==="converted"&&!N(W)||m==="new"&&W.already_exported||m==="exported"&&!W.already_exported)),T=()=>{x.size===A.length?g(new Set):g(new Set(A.map(W=>W.id)))},P=W=>{const V=new Set(x);V.has(W)?V.delete(W):V.add(W),g(V)},M=async()=>{if(x.size===0){t({title:"No users selected",description:"Select users to export",variant:"destructive"});return}o(!0);try{const W=n.filter(ee=>x.has(ee.id)),V="First Name,Last Name,Email,Phone,Trial Type,Status,Signup Date,Expiry Date",K=W.map(ee=>{const le=(ee.name||"").split(" "),he=le[0]||"",ve=le.slice(1).join(" ")||"",ge=b(ee)==="stripe"?"Credit Card Trial":"Free Trial (No CC)",fe=N(ee)?"Converted":C(ee)?"Expired":"Active",je=ee.created_at?new Date(ee.created_at).toLocaleDateString():"",Ee=v(ee)?new Date(v(ee)).toLocaleDateString():"";return`"${he}","${ve}","${ee.email}","${ee.phone||""}","${ge}","${fe}","${je}","${Ee}"`}),Q=[V,...K].join(` `),J=new Blob([Q],{type:"text/csv"}),ce=URL.createObjectURL(J),ue=document.createElement("a");ue.href=ce,ue.download=`trial-users-${new Date().toISOString().split("T")[0]}.csv`,ue.click(),URL.revokeObjectURL(ce);const ne=W.filter(ee=>!ee.already_exported).map(ee=>({user_id:ee.id,exported_by:s.id}));if(ne.length>0){const{error:ee}=await U.from("trial_email_exports").upsert(ne,{onConflict:"user_id"});ee&&console.error("Error marking exports:",ee)}t({title:"Export complete",description:`Downloaded ${W.length} trial user(s). ${ne.length} newly marked as exported.`}),g(new Set),y()}catch(W){console.error("Export error:",W),t({title:"Error",description:"Failed to export",variant:"destructive"})}finally{o(!1)}},I=n.filter(W=>!W.already_exported).length,D=n.filter(W=>W.already_exported).length,B=n.filter(W=>N(W)).length,q=n.filter(W=>!C(W)&&!N(W)).length;return a?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx(Ht,{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(_e,{children:e.jsxs(Bt,{className:"pb-2",children:[e.jsx(vr,{children:"Total"}),e.jsx(Ut,{className:"text-2xl",children:n.length})]})}),e.jsx(_e,{children:e.jsxs(Bt,{className:"pb-2",children:[e.jsx(vr,{children:"New (Not Exported)"}),e.jsx(Ut,{className:"text-2xl text-green-600",children:I})]})}),e.jsx(_e,{children:e.jsxs(Bt,{className:"pb-2",children:[e.jsx(vr,{children:"Active Trials"}),e.jsx(Ut,{className:"text-2xl",children:q})]})}),e.jsx(_e,{children:e.jsxs(Bt,{className:"pb-2",children:[e.jsx(vr,{children:"Converted 🎉"}),e.jsx(Ut,{className:"text-2xl text-primary",children:B})]})}),e.jsx(_e,{children:e.jsxs(Bt,{className:"pb-2",children:[e.jsx(vr,{children:"Already Exported"}),e.jsx(Ut,{className:"text-2xl text-muted-foreground",children:D})]})})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[e.jsxs(vs,{value:m,onValueChange:W=>p(W),children:[e.jsx(gs,{className:"w-[160px]",children:e.jsx(bs,{})}),e.jsxs(ys,{children:[e.jsx(Ye,{value:"all",children:"All Users"}),e.jsx(Ye,{value:"new",children:"New Only"}),e.jsx(Ye,{value:"exported",children:"Already Exported"})]})]}),e.jsxs(vs,{value:c,onValueChange:W=>d(W),children:[e.jsx(gs,{className:"w-[180px]",children:e.jsx(bs,{})}),e.jsxs(ys,{children:[e.jsx(Ye,{value:"all",children:"All Trial Types"}),e.jsx(Ye,{value:"stripe",children:"Credit Card Trial"}),e.jsx(Ye,{value:"ghl",children:"Free Trial (No CC)"})]})]}),e.jsxs(vs,{value:u,onValueChange:W=>h(W),children:[e.jsx(gs,{className:"w-[160px]",children:e.jsx(bs,{})}),e.jsxs(ys,{children:[e.jsx(Ye,{value:"all",children:"All Statuses"}),e.jsx(Ye,{value:"active",children:"Active Trial"}),e.jsx(Ye,{value:"expired",children:"Expired"}),e.jsx(Ye,{value:"converted",children:"Converted ✓"})]})]}),e.jsx("div",{className:"ml-auto",children:e.jsxs($,{onClick:M,disabled:l||x.size===0,children:[l?e.jsx(Ht,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(di,{className:"h-4 w-4 mr-2"}),"Export Selected (",x.size,")"]})})]}),e.jsx("div",{className:"border rounded-lg",children:e.jsxs(Va,{children:[e.jsx(Ha,{children:e.jsxs(hn,{className:"bg-muted/30 hover:bg-muted/30",children:[e.jsx(Lt,{className:"w-[40px]",children:e.jsx(ui,{checked:A.length>0&&x.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(Ga,{children:A.length===0?e.jsx(hn,{children:e.jsx(gt,{colSpan:9,className:"text-center py-8 text-muted-foreground",children:"No trial users match the current filters"})}):A.map(W=>{const V=b(W),K=N(W),Q=C(W),J=v(W);return e.jsxs(hn,{className:`hover:bg-muted/30 ${K?"bg-primary/5":""}`,children:[e.jsx(gt,{children:e.jsx(ui,{checked:x.has(W.id),onCheckedChange:()=>P(W.id)})}),e.jsx(gt,{className:"font-medium",children:e.jsxs("div",{className:"flex items-center gap-2",children:[W.name,K&&e.jsx(Il,{className:"h-3.5 w-3.5 text-primary"})]})}),e.jsx(gt,{className:"text-muted-foreground",children:W.email}),e.jsx(gt,{children:V==="stripe"?e.jsxs($e,{variant:"outline",className:"gap-1",children:[e.jsx(yy,{className:"h-3 w-3"}),"Credit Card"]}):e.jsxs($e,{variant:"secondary",className:"gap-1",children:[e.jsx(nn,{className:"h-3 w-3"}),"Free (No CC)"]})}),e.jsx(gt,{children:K?e.jsxs($e,{className:"bg-primary/10 text-primary hover:bg-primary/20 gap-1",children:[e.jsx(Il,{className:"h-3 w-3"}),"Converted"]}):Q?e.jsx($e,{variant:"destructive",children:"Expired"}):e.jsx($e,{className:"bg-green-500/10 text-green-600 hover:bg-green-500/20",children:"Active Trial"})}),e.jsx(gt,{className:"text-sm",children:W.created_at?new Date(W.created_at).toLocaleDateString():"—"}),e.jsx(gt,{className:"text-sm",children:W.last_login?e.jsxs("div",{className:"flex flex-col",children:[e.jsx("span",{children:new Date(W.last_login).toLocaleDateString()}),e.jsx("span",{className:"text-xs text-muted-foreground",children:new Date(W.last_login).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})})]}):e.jsx("span",{className:"text-muted-foreground",children:"Never"})}),e.jsx(gt,{className:"text-sm",children:K&&J?e.jsxs("span",{className:"text-muted-foreground",children:["Renews ",new Date(J).toLocaleDateString()]}):J?new Date(J).toLocaleDateString():"—"}),e.jsx(gt,{children:W.already_exported?e.jsx(Fr,{className:"h-4 w-4 text-muted-foreground"}):e.jsx($e,{variant:"outline",className:"text-green-600 border-green-300",children:"New"})})]},W.id)})})]})}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:["Showing ",A.length," of ",n.length," trial users · ",B," converted to paid"]})]})},$Us=s=>s==null?'""':`"${String(s).replace(/"/g,'""')}"`,UUs=()=>{const[s,t]=j.useState([]),[n,r]=j.useState(!0);j.useEffect(()=>{(async()=>{const{data:l,error:o}=await U.from("user_deletion_log").select("*").order("created_at",{ascending:!1});!o&&l&&t(l),r(!1)})()},[]);const a=()=>{if(s.length===0){ae.info("No deletion records to export");return}const i=["Date","Deleted User","Deleted Email","Brokerage","Type","Deleted By"],l=s.map(h=>[Hs(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($Us).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),ae.success(`Exported ${s.length} deletion record(s)`)};return n?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx(Ht,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):s.length===0?e.jsx(_e,{children:e.jsxs(Oe,{className:"py-12 text-center text-muted-foreground",children:[e.jsx(Pn,{className:"h-10 w-10 mx-auto mb-3 opacity-40"}),e.jsx("p",{children:"No deletion records yet"})]})}):e.jsxs(_e,{children:[e.jsxs(Bt,{className:"flex flex-row items-center justify-between",children:[e.jsx(Ut,{className:"text-lg",children:"User Deletion History"}),e.jsxs($,{variant:"outline",size:"sm",onClick:a,children:[e.jsx(di,{className:"h-4 w-4 mr-2"}),"Export CSV"]})]}),e.jsx(Oe,{children:e.jsxs(Va,{children:[e.jsx(Ha,{children:e.jsxs(hn,{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(Ga,{children:s.map(i=>e.jsxs(hn,{children:[e.jsx(gt,{className:"whitespace-nowrap text-sm",children:Hs(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($e,{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))})]})})]})},CC=s=>{const{user:t}=_s(),n=ts(),r=ht({queryKey:["teams",s],queryFn:async()=>{let h=U.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=>ht({queryKey:["team-members",h],queryFn:async()=>{const{data:m,error:p}=await U.from("team_members").select("*").eq("team_id",h).order("role",{ascending:!0});if(p)throw p;const x=(m||[]).map(b=>b.user_id),{data:g}=await U.from("profiles").select("id, name, email, avatar_url").in("id",x),y=new Map((g||[]).map(b=>[b.id,b]));return(m||[]).map(b=>({...b,profile:y.get(b.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:x}=await U.from("teams").insert(m).select().single();if(x)throw x;return p},onSuccess:()=>{n.invalidateQueries({queryKey:["teams"]}),ae.success("Team created!")},onError:h=>{ae.error("Failed to create team: "+h.message)}}),l=yt({mutationFn:async({id:h,...m})=>{const{data:p,error:x}=await U.from("teams").update(m).eq("id",h).select().single();if(x)throw x;return p},onSuccess:()=>{n.invalidateQueries({queryKey:["teams"]}),ae.success("Team updated")},onError:h=>{ae.error("Failed to update team: "+h.message)}}),o=yt({mutationFn:async h=>{const{error:m}=await U.from("teams").delete().eq("id",h);if(m)throw m},onSuccess:()=>{n.invalidateQueries({queryKey:["teams"]}),ae.success("Team deleted")},onError:h=>{ae.error("Failed to delete team: "+h.message)}}),c=yt({mutationFn:async h=>{const{data:m,error:p}=await U.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]}),ae.success("Member added to team")},onError:h=>{ae.error(h.message)}}),d=yt({mutationFn:async h=>{const{error:m}=await U.from("team_members").delete().eq("id",h.member_id);if(m)throw m},onSuccess:(h,m)=>{n.invalidateQueries({queryKey:["team-members",m.team_id]}),ae.success("Member removed from team")},onError:h=>{ae.error("Failed to remove member: "+h.message)}}),u=yt({mutationFn:async h=>{const{error:m}=await U.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]}),ae.success("Member role updated")},onError:h=>{ae.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}},VWe=s=>{const t=ts(),n=ht({queryKey:["team-ponds",s],queryFn:async()=>{const{data:o,error:c}=await U.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 U.from("team_ponds").insert({team_id:s,name:o.name,description:o.description||null}).select().single();if(d)throw d;return c},onSuccess:()=>{r(),ae.success("Pond created")},onError:o=>ae.error(o.message)}),i=yt({mutationFn:async({id:o,...c})=>{const{error:d}=await U.from("team_ponds").update(c).eq("id",o);if(d)throw d},onSuccess:()=>{r(),ae.success("Pond updated")},onError:o=>ae.error(o.message)}),l=yt({mutationFn:async o=>{const{error:c}=await U.from("team_ponds").delete().eq("id",o);if(c)throw c},onSuccess:()=>{r(),ae.success("Pond deleted")},onError:o=>ae.error(o.message)});return{ponds:n.data||[],isLoading:n.isLoading,createPond:a,updatePond:i,deletePond:l}},qUs=s=>{const t=ts(),n=ht({queryKey:["pond-assignments",s],queryFn:async()=>{const{data:a,error:i}=await U.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 U.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 U.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=>ae.error(a.message)});return{assignedUserIds:(n.data||[]).map(a=>a.user_id),isLoading:n.isLoading,setAssigned:r}},VUs=({pond:s,teamId:t})=>{const{useTeamMembers:n}=CC(),{data:r=[],isLoading:a}=n(t),{assignedUserIds:i,isLoading:l,setAssigned:o}=qUs(s.id);return a||l?e.jsx(on,{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(qn,{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(ui,{checked:d,onCheckedChange:m=>o.mutate({user_id:c.user_id,assigned:!!m})}),e.jsx("span",{className:"truncate",children:((u=c.profile)==null?void 0:u.name)||((h=c.profile)==null?void 0:h.email)||"Unknown"}),c.role==="team_leader"&&e.jsx($e,{variant:"secondary",className:"ml-auto text-[10px]",children:"Leader"})]},c.id)})})]})},m8t=({teamId:s})=>{const{ponds:t,isLoading:n,createPond:r,updatePond:a,deletePond:i}=VWe(s),[l,o]=j.useState(!1),[c,d]=j.useState(""),[u,h]=j.useState(""),[m,p]=j.useState(null),[x,g]=j.useState(null),y=async()=>{c.trim()&&(await r.mutateAsync({name:c.trim(),description:u.trim()}),d(""),h(""),o(!1))};return e.jsxs(_e,{children:[e.jsxs(Bt,{className:"flex flex-row items-start justify-between gap-4 space-y-0",children:[e.jsxs("div",{children:[e.jsx(Ut,{className:"text-lg",children:"Lead Ponds"}),e.jsx(vr,{children:"Create multiple ponds (by area, source, or specialty) and assign which agents can see each one."})]}),e.jsxs($,{size:"sm",onClick:()=>o(!0),children:[e.jsx(sn,{className:"mr-1 h-4 w-4"})," New Pond"]})]}),e.jsxs(Oe,{className:"space-y-3",children:[n&&e.jsx(on,{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(b=>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(f1,{className:"h-4 w-4 text-primary"}),e.jsx("p",{className:"font-medium",children:b.name}),b.is_default&&e.jsx($e,{variant:"secondary",className:"text-[10px]",children:"Default"})]}),b.description&&e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:b.description}),e.jsxs("div",{className:"mt-1 flex flex-wrap gap-2 text-[11px] text-muted-foreground",children:[e.jsxs("span",{children:[b.available_count," available"]}),e.jsx("span",{children:"·"}),e.jsxs("span",{children:[b.claimed_count," claimed"]})]})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsxs($,{size:"sm",variant:"ghost",onClick:()=>g(x===b.id?null:b.id),children:[e.jsx(qn,{className:"mr-1 h-3.5 w-3.5"}),x===b.id?"Hide agents":"Assign agents"]}),e.jsx($,{size:"icon",variant:"ghost",onClick:()=>p(b),children:e.jsx(Ya,{className:"h-3.5 w-3.5"})}),e.jsx($,{size:"icon",variant:"ghost",onClick:()=>{confirm(`Delete "${b.name}"? Leads in this pond will no longer be shared.`)&&i.mutate(b.id)},children:e.jsx(Pn,{className:"h-3.5 w-3.5 text-destructive"})})]})]}),x===b.id&&e.jsx(VUs,{pond:b,teamId:s})]},b.id))]}),e.jsx(Os,{open:l,onOpenChange:o,children:e.jsxs(Rs,{children:[e.jsxs(Us,{children:[e.jsx(zs,{children:"New Lead Pond"}),e.jsx(Sr,{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(se,{children:"Pond name"}),e.jsx(be,{value:c,onChange:b=>d(b.target.value),placeholder:"e.g. Northland Buyers"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:"Description (optional)"}),e.jsx(be,{value:u,onChange:b=>h(b.target.value),placeholder:"What kind of leads go in this pond?"})]})]}),e.jsxs(kr,{children:[e.jsx($,{variant:"outline",onClick:()=>o(!1),children:"Cancel"}),e.jsx($,{onClick:y,disabled:!c.trim()||r.isPending,children:"Create Pond"})]})]})}),e.jsx(Os,{open:!!m,onOpenChange:b=>!b&&p(null),children:e.jsxs(Rs,{children:[e.jsx(Us,{children:e.jsx(zs,{children:"Edit Pond"})}),m&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:"Pond name"}),e.jsx(be,{value:m.name,onChange:b=>p({...m,name:b.target.value})})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:"Description"}),e.jsx(be,{value:m.description||"",onChange:b=>p({...m,description:b.target.value})})]})]}),e.jsxs(kr,{children:[e.jsx($,{variant:"outline",onClick:()=>p(null),children:"Cancel"}),e.jsx($,{onClick:async()=>{m&&(await a.mutateAsync({id:m.id,name:m.name,description:m.description||""}),p(null))},disabled:a.isPending,children:"Save"})]})]})})]})},HUs=(s,t=!0)=>ht({queryKey:["lead-pond-activity",s],queryFn:async()=>{const{data:n,error:r}=await U.rpc("get_lead_pond_activity",{_lead_pond_id:s});if(r)throw r;return n||[]},enabled:!!s&&t}),GUs=()=>{const{user:s}=_s();return ht({queryKey:["team-contacts",s==null?void 0:s.id],queryFn:async()=>{const{data:t,error:n}=await U.rpc("get_team_contacts",{_user_id:s.id});if(n)throw n;return t||[]},enabled:!!s})},p8t=(s,t)=>{const{user:n}=_s(),r=ts(),a=ht({queryKey:["lead-pond",s,t||"all"],queryFn:async()=>{const{data:c,error:d}=await U.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 U.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"]}),ae.success("Contact added to Lead Pond")},onError:c=>{ae.error(c.message)}}),l=yt({mutationFn:async c=>{const{error:d}=await U.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"]}),ae.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=>{ae.error(c.message)}}),o=yt({mutationFn:async c=>{const{error:d}=await U.rpc("return_lead_pond_contact",{_lead_pond_id:c});if(d)throw d},onSuccess:()=>{r.invalidateQueries({queryKey:["lead-pond"]}),ae.success("Lead returned to pond")},onError:c=>{ae.error(c.message)}});return{leadPondItems:a.data||[],isLoading:a.isLoading,addToLeadPond:i,claimLead:l,returnLead:o}},WUs=(s,t,n=100)=>ht({queryKey:["team-pond-history",s,t||"all",n],queryFn:async()=>{const{data:r,error:a}=await U.rpc("get_team_pond_history",{_team_id:s,_pond_id:t||null,_limit:n});if(a)throw a;return r||[]},enabled:!!s}),KUs=()=>{const s=ts();return yt({mutationFn:async t=>{const{data:n,error:r}=await U.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"]}),ae.success("Contact transferred successfully")},onError:t=>{ae.error(t.message||"Failed to transfer contact")}})};function f8t({open:s,onOpenChange:t,contactIds:n,contactNames:r=[],onComplete:a}){var A;const{user:i}=_s(),{data:l}=Nw(),{useTeamMembers:o}=CC(),{data:c=[]}=o((l==null?void 0:l.teamId)||""),d=KUs(),[u,h]=j.useState(null),[m,p]=j.useState(""),[x,g]=j.useState(!1),y=c.filter(T=>T.user_id!==(i==null?void 0:i.id)),b=async()=>{if(u){g(!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{g(!1)}}},v=y.find(T=>T.user_id===u),N=n.length>1,C=r.length>0?N?`${r.length} contacts`:r[0]:N?`${n.length} contacts`:"this contact";return e.jsx(Os,{open:s,onOpenChange:t,children:e.jsxs(Rs,{className:"sm:max-w-md",children:[e.jsxs(Us,{children:[e.jsxs(zs,{className:"flex items-center gap-2",children:[e.jsx(QS,{className:"h-5 w-5"}),"Transfer ",C]}),e.jsxs(Sr,{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(se,{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 P,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(ki,{src:((P=T.profile)==null?void 0:P.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(se,{htmlFor:"transfer-notes",className:"text-sm font-medium",children:"Notes (optional)"}),e.jsx(Is,{id:"transfer-notes",value:m,onChange:T=>p(T.target.value),placeholder:"Reason for transfer...",className:"mt-1",rows:2})]})]}),e.jsxs(kr,{children:[e.jsx($,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsxs($,{onClick:b,disabled:!u||x,children:[x?e.jsx(Ht,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(QS,{className:"h-4 w-4 mr-2"}),"Transfer",v?` to ${(A=v.profile)==null?void 0:A.name}`:""]})]})]})})}const HWe=()=>{const s=Vn(),{data:t,isLoading:n}=GUs(),{data:r}=Nw(),[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 g=new Map;return t.forEach(y=>{g.has(y.owner_user_id)||g.set(y.owner_user_id,{id:y.owner_user_id,name:y.owner_name||"Unknown",avatar:y.owner_avatar_url})}),Array.from(g.values())},[t]),x=j.useMemo(()=>{if(!t)return[];let g=t;if(l!=="all"&&(g=g.filter(y=>y.owner_user_id===l)),a.trim()){const y=a.toLowerCase();g=g.filter(b=>{var v,N,C;return(b.first_name+" "+(b.last_name||"")).toLowerCase().includes(y)||((v=b.email)==null?void 0:v.toLowerCase().includes(y))||((N=b.phone)==null?void 0:N.includes(y))||((C=b.owner_name)==null?void 0:C.toLowerCase().includes(y))})}return g},[t,a,l]);return n?e.jsxs("div",{className:"space-y-4",children:[e.jsx(on,{className:"h-10 w-full"}),e.jsx(on,{className:"h-64 w-full"})]}):!t||t.length===0?e.jsx(_e,{children:e.jsxs(Oe,{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(qn,{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(_e,{children:e.jsx(Oe,{className:"p-4",children:e.jsxs("div",{className:"flex flex-col sm:flex-row gap-4",children:[e.jsxs("div",{className:"relative flex-1",children:[e.jsx(Vr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(be,{placeholder:"Search by name, email, phone, or agent...",value:a,onChange:g=>i(g.target.value),className:"pl-9"})]}),e.jsxs(vs,{value:l,onValueChange:o,children:[e.jsx(gs,{className:"w-[200px]",children:e.jsx(bs,{placeholder:"Filter by agent"})}),e.jsxs(ys,{children:[e.jsx(Ye,{value:"all",children:"All Team Members"}),p.map(g=>e.jsx(Ye,{value:g.id,children:g.name},g.id))]})]})]})})}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[x.length," contact",x.length!==1?"s":""," from ",p.length," teammate",p.length!==1?"s":""]}),e.jsx(_e,{children:e.jsx(Oe,{className:"p-0 overflow-x-auto",children:e.jsxs(Va,{className:"min-w-[800px]",children:[e.jsx(Ha,{children:e.jsxs(hn,{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(Ga,{children:x.length===0?e.jsx(hn,{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"})}):x.map(g=>e.jsxs(hn,{className:`hover:bg-accent/50 ${m?"cursor-pointer":""}`,onClick:m?()=>s(`/mission-control/contacts/${g.id}`):void 0,children:[e.jsx(gt,{className:"font-medium",children:e.jsxs("span",{className:m?"hover:text-primary hover:underline transition-colors":"",children:[g.first_name," ",g.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(ki,{src:g.owner_avatar_url||""}),e.jsx(Ta,{className:"text-[10px]",children:(g.owner_name||"?").charAt(0).toUpperCase()})]}),e.jsx("span",{className:"text-sm text-muted-foreground truncate max-w-[120px]",children:g.owner_name||"Unknown"})]})}),e.jsx(gt,{children:e.jsxs("div",{className:"space-y-1 text-sm",children:[g.email&&e.jsxs("div",{className:"flex items-center gap-1 text-muted-foreground",children:[e.jsx(nn,{className:"h-3 w-3 shrink-0"}),e.jsx("span",{className:"truncate",children:g.email})]}),g.phone&&e.jsxs("div",{className:"flex items-center gap-1 text-muted-foreground",children:[e.jsx(ya,{className:"h-3 w-3 shrink-0"}),e.jsx("span",{children:g.phone})]}),!g.email&&!g.phone&&e.jsx("span",{className:"text-xs text-muted-foreground italic",children:"No contact info"})]})}),e.jsx(gt,{children:g.address?e.jsxs("div",{className:"flex items-center gap-1 text-sm text-muted-foreground",children:[e.jsx(ai,{className:"h-3 w-3 shrink-0"}),e.jsx("span",{className:"truncate max-w-[180px]",children:g.address})]}):e.jsx("span",{className:"text-xs text-muted-foreground italic",children:"—"})}),e.jsx(gt,{children:g.lead_source?e.jsx($e,{variant:"outline",className:"text-xs border-primary/30 text-primary",children:g.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:Hs(new Date(g.created_at),"MMM d, yyyy")})}),m&&e.jsx(gt,{children:e.jsx($,{variant:"ghost",size:"sm",className:"h-8 px-2",onClick:y=>{y.stopPropagation(),d(g.id),h(`${g.first_name} ${g.last_name||""}`.trim())},title:"Transfer to team member",children:e.jsx(QS,{className:"h-4 w-4"})})})]},g.id))})]})})}),e.jsx(f8t,{open:!!c,onOpenChange:g=>{g||d(null)},contactIds:c?[c]:[],contactNames:u?[u]:[],onComplete:()=>d(null)})]})},YUs=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)},ZUs=({leadPondId:s})=>{const{data:t,isLoading:n,error:r}=HUs(s);return n?e.jsxs("div",{className:"space-y-2 pt-2",children:[e.jsx(on,{className:"h-4 w-2/3"}),e.jsx(on,{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(SR,{className:"mt-0.5 h-3 w-3 shrink-0 text-muted-foreground"}):e.jsx(zp,{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:YUs(a.occurred_at)})]})]},i))})},XUs=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)):"",QUs=s=>{var n;const t=((n=s.contact_name)==null?void 0:n.trim())||"A lead";switch(s.event_type){case"claimed":return{icon:bz,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:Ih,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:f1,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"]})}}},uut=({teamId:s,pondId:t})=>{const{data:n,isLoading:r}=WUs(s,t),[a,i]=j.useState(!1),l=n||[],o=a?l:l.slice(0,8);return e.jsxs(_e,{children:[e.jsx(Bt,{className:"pb-3",children:e.jsxs(Ut,{className:"flex items-center gap-2 text-sm",children:[e.jsx(Uj,{className:"h-4 w-4"}),"Pond Activity History"]})}),e.jsx(Oe,{className:"space-y-3",children:r?e.jsx("div",{className:"space-y-2",children:[1,2,3].map(c=>e.jsx(on,{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=QUs(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(ki,{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:XUs(c.occurred_at)}),c.pond_name&&e.jsx($e,{variant:"secondary",className:"text-[9px]",children:c.pond_name})]}),c.notes&&e.jsx("p",{className:"whitespace-pre-wrap text-[11px] text-muted-foreground",children:c.notes})]})]},`${c.lead_pond_id}-${c.event_type}-${d}`)})}),l.length>8&&e.jsxs($,{size:"sm",variant:"ghost",className:"h-7 px-2 text-xs",onClick:()=>i(c=>!c),children:[a?e.jsx(jg,{className:"mr-1 h-3 w-3"}):e.jsx(_o,{className:"mr-1 h-3 w-3"}),a?"Show less":`Show all ${l.length} events`]})]})})]})},JUs=s=>s?new Intl.DateTimeFormat("en-US",{timeZone:"America/New_York",month:"short",day:"numeric"}).format(new Date(s)):null,eqs=({item:s,isClaimer:t,onReturn:n,returning:r})=>{var o,c,d;const[a,i]=j.useState(!1),l=JUs(s.last_activity_at);return e.jsx(_e,{children:e.jsxs(Oe,{className:"space-y-3 p-4",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0 space-y-1.5",children:[e.jsxs("p",{className:"text-sm font-medium",children:[(o=s.contact)==null?void 0:o.first_name," ",((c=s.contact)==null?void 0:c.last_name)||""]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs($e,{variant:"secondary",className:"text-xs",children:["Claimed by ",((d=s.claimer)==null?void 0:d.name)||"Unknown"]}),e.jsxs($e,{variant:"outline",className:"text-[10px]",children:[s.touch_count||0," follow-up",(s.touch_count||0)===1?"":"s"]}),e.jsxs("span",{className:"flex items-center gap-1 text-[11px] text-muted-foreground",children:[e.jsx(Hr,{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(ga,{className:"h-3 w-3"}),"Your notes and follow-ups on this lead are visible to the team leader and the agent who shared it."]})]}),t&&e.jsxs($,{size:"sm",variant:"outline",onClick:n,disabled:r,children:[e.jsx(Ih,{className:"mr-1 h-3 w-3"}),"Return"]})]}),s.can_view_activity&&e.jsxs("div",{className:"border-t pt-2",children:[e.jsxs($,{size:"sm",variant:"ghost",className:"h-7 px-2 text-xs",onClick:()=>i(u=>!u),children:[a?e.jsx(jg,{className:"mr-1 h-3 w-3"}):e.jsx(_o,{className:"mr-1 h-3 w-3"}),a?"Hide notes & activity":"View notes & activity"]}),a&&e.jsx(ZUs,{leadPondId:s.id})]})]})})},GWe=({teamId:s})=>{const{user:t}=_s(),[n,r]=j.useState(null),{ponds:a,isLoading:i}=VWe(s),l=a.filter(x=>x.has_access),{leadPondItems:o,isLoading:c,claimLead:d,returnLead:u}=p8t(s,n),h=l.length>1?e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx($,{size:"sm",variant:n===null?"default":"outline",onClick:()=>r(null),children:"All Ponds"}),l.map(x=>e.jsxs($,{size:"sm",variant:n===x.id?"default":"outline",onClick:()=>r(x.id),children:[e.jsx(f1,{className:"mr-1 h-3 w-3"}),x.name,e.jsx($e,{variant:"secondary",className:"ml-2 text-[10px]",children:x.available_count})]},x.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(x=>e.jsx(on,{className:"h-20 w-full"},x))});if(o.length===0)return e.jsxs("div",{className:"space-y-4",children:[h,e.jsx(_e,{children:e.jsxs(Oe,{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(f1,{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(uut,{teamId:s,pondId:n})]});const m=o.filter(x=>x.status==="available"),p=o.filter(x=>x.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(x=>{var g,y,b,v,N,C,A,T,P,M,I;return e.jsx(_e,{children:e.jsxs(Oe,{className:"flex flex-col gap-3 p-4 sm:flex-row sm:items-start sm:justify-between",children:[e.jsxs("div",{className:"min-w-0 space-y-1.5",children:[e.jsxs("p",{className:"font-medium text-sm",children:[((g=x.contact)==null?void 0:g.first_name)||"Unnamed"," ",((y=x.contact)==null?void 0:y.last_name)||""]}),e.jsxs("div",{className:"flex flex-wrap gap-x-4 gap-y-1",children:[((b=x.contact)==null?void 0:b.email)&&e.jsxs("span",{className:"text-xs text-muted-foreground flex items-center gap-1",children:[e.jsx(nn,{className:"h-3 w-3"})," ",x.contact.email]}),((v=x.contact)==null?void 0:v.phone)&&e.jsxs("span",{className:"text-xs text-muted-foreground flex items-center gap-1",children:[e.jsx(ya,{className:"h-3 w-3"})," ",x.contact.phone]}),((N=x.contact)==null?void 0:N.address)&&e.jsxs("span",{className:"text-xs text-muted-foreground flex items-center gap-1",children:[e.jsx(ai,{className:"h-3 w-3"})," ",x.contact.address]})]}),x.pond_name&&n===null&&l.length>1&&e.jsxs($e,{variant:"secondary",className:"text-[10px]",children:[e.jsx(f1,{className:"mr-1 h-2.5 w-2.5"})," ",x.pond_name]}),((C=x.contact)==null?void 0:C.lead_source)&&e.jsxs($e,{variant:"outline",className:"text-[10px]",children:["Source: ",x.contact.lead_source]}),(x.notes||((A=x.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(SR,{className:"h-3 w-3 mt-0.5 shrink-0"}),e.jsx("span",{className:"whitespace-pre-wrap",children:x.notes||((T=x.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(ki,{src:((P=x.contributor)==null?void 0:P.avatar_url)||""}),e.jsx(Ta,{className:"text-[8px]",children:(((M=x.contributor)==null?void 0:M.name)||"?").charAt(0)})]}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:["from ",((I=x.contributor)==null?void 0:I.name)||"Unknown"]})]})]}),e.jsxs($,{size:"sm",className:"shrink-0",onClick:()=>d.mutate(x.id),disabled:d.isPending,children:[e.jsx(bz,{className:"mr-1 h-3 w-3"}),"Claim"]})]})},x.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(x=>e.jsx(eqs,{item:x,isClaimer:x.claimed_by===(t==null?void 0:t.id),onReturn:()=>u.mutate(x.id),returning:u.isPending},x.id))})]}),e.jsx(uut,{teamId:s,pondId:n})]})},x8t=({teamId:s})=>{const{useTeamMembers:t}=CC(),{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}=ht({queryKey:["team-shared-presentations",s,r],queryFn:async()=>{if(r.length===0)return[];const{data:p,error:x}=await U.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(x)throw x;return p||[]},enabled:r.length>0}),{data:o=[],isLoading:c}=ht({queryKey:["team-shared-open-houses",s,r],queryFn:async()=>{if(r.length===0)return[];const{data:p,error:x}=await U.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(x)throw x;return p||[]},enabled:r.length>0}),{data:d=[],isLoading:u}=ht({queryKey:["team-shared-videos",s,r],queryFn:async()=>{if(r.length===0)return[];const{data:p,error:x}=await U.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(x)throw x;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(on,{className:"h-20 w-full"},p))});const m=p=>{const x=a.get(p);return{name:(x==null?void 0:x.name)||"Unknown",avatar:(x==null?void 0:x.avatar_url)||"",initials:((x==null?void 0:x.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(_e,{children:e.jsxs(Oe,{className:"flex items-center gap-3 p-4",children:[e.jsx(by,{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(_e,{children:e.jsxs(Oe,{className:"flex items-center gap-3 p-4",children:[e.jsx(sa,{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(_e,{children:e.jsxs(Oe,{className:"flex items-center gap-3 p-4",children:[e.jsx(Xr,{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(ua,{defaultValue:"presentations",className:"space-y-4",children:[e.jsxs(ha,{children:[e.jsxs(Qt,{value:"presentations",children:["Presentations (",i.length,")"]}),e.jsxs(Qt,{value:"guest-books",children:["Guest Books (",o.length,")"]}),e.jsxs(Qt,{value:"videos",children:["Videos (",d.length,")"]})]}),e.jsx(Jt,{value:"presentations",className:"space-y-2",children:i.length===0?e.jsx(jIe,{icon:e.jsx(by,{className:"h-10 w-10"}),label:"No presentations yet"}):i.map(p=>{const x=m(p.owner_user_id);return e.jsx(_e,{children:e.jsxs(Oe,{className:"flex items-center justify-between p-4",children:[e.jsxs("div",{className:"flex items-center gap-3 min-w-0",children:[e.jsxs(Ea,{className:"h-8 w-8 shrink-0",children:[e.jsx(ki,{src:x.avatar}),e.jsx(Ta,{className:"text-xs",children:x.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:[x.name," · ",Hs(new Date(p.created_at),"MMM d, yyyy")]})]})]}),e.jsxs("div",{className:"flex items-center gap-3 shrink-0",children:[e.jsx($e,{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(ga,{className:"h-3 w-3"}),p.view_count||0]})]})]})},p.id)})}),e.jsx(Jt,{value:"guest-books",className:"space-y-2",children:o.length===0?e.jsx(jIe,{icon:e.jsx(sa,{className:"h-10 w-10"}),label:"No guest books yet"}):o.map(p=>{const x=m(p.agent_id);return e.jsx(_e,{children:e.jsxs(Oe,{className:"flex items-center justify-between p-4",children:[e.jsxs("div",{className:"flex items-center gap-3 min-w-0",children:[e.jsxs(Ea,{className:"h-8 w-8 shrink-0",children:[e.jsx(ki,{src:x.avatar}),e.jsx(Ta,{className:"text-xs",children:x.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:[x.name," · ",Hs(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($e,{className:"text-xs",children:"Active"}):e.jsx($e,{variant:"secondary",className:"text-xs",children:"Inactive"}),e.jsxs("div",{className:"flex items-center gap-1 text-xs text-muted-foreground",children:[e.jsx(qn,{className:"h-3 w-3"}),p.visitor_count||0]})]})]})},p.id)})}),e.jsx(Jt,{value:"videos",className:"space-y-2",children:d.length===0?e.jsx(jIe,{icon:e.jsx(Xr,{className:"h-10 w-10"}),label:"No videos yet"}):d.map(p=>{const x=m(p.owner_user_id);return e.jsx(_e,{children:e.jsxs(Oe,{className:"flex items-center justify-between p-4",children:[e.jsxs("div",{className:"flex items-center gap-3 min-w-0",children:[e.jsxs(Ea,{className:"h-8 w-8 shrink-0",children:[e.jsx(ki,{src:x.avatar}),e.jsx(Ta,{className:"text-xs",children:x.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:[x.name," · ",Hs(new Date(p.created_at),"MMM d, yyyy")]})]})]}),e.jsxs("div",{className:"flex items-center gap-3 shrink-0",children:[e.jsx($e,{variant:"secondary",className:"text-xs capitalize",children:p.touch_type}),e.jsxs("div",{className:"flex items-center gap-1 text-xs text-muted-foreground",children:[e.jsx(ga,{className:"h-3 w-3"}),p.view_count||0]})]})]})},p.id)})})]})]})},jIe=({icon:s,label:t})=>e.jsx(_e,{children:e.jsxs(Oe,{className:"flex flex-col items-center justify-center py-8 text-center text-muted-foreground",children:[s,e.jsx("p",{className:"mt-2 text-sm",children:t})]})}),g8t=({team:s,brokerageAgents:t,onBack:n,onUpdate:r,onAddMember:a,onRemoveMember:i,onUpdateRole:l,onDeleteTeam:o,isUpdating:c,isAddingMember:d})=>{var P,M;const{useTeamMembers:u}=CC(),{data:h=[],isLoading:m}=u(s.id),[p,x]=j.useState(!1),[g,y]=j.useState(""),[b,v]=j.useState("team_member"),{data:N}=ht({queryKey:["agents-on-other-teams",s.id],queryFn:async()=>{const{data:I}=await U.from("team_members").select("user_id, team_id, teams:team_id(name)").neq("team_id",s.id),D=new Map;return(I||[]).forEach(B=>{var W;const q=D.get(B.user_id)||[];q.push(((W=B.teams)==null?void 0:W.name)||"another team"),D.set(B.user_id,q)}),D}}),C=new Set(h.map(I=>I.user_id)),A=t.filter(I=>!C.has(I.id)),T=async()=>{g&&(await a(g,b),y(""),v("team_member"),x(!1))};return e.jsxs("div",{className:"space-y-6",children:[e.jsx($,{variant:"ghost",onClick:n,className:"mb-2",children:"← Back to Teams"}),e.jsxs(ua,{defaultValue:"members",className:"space-y-4",children:[e.jsxs(ha,{children:[e.jsx(Qt,{value:"members",children:"Members"}),e.jsxs(Qt,{value:"contacts",children:[e.jsx(hR,{className:"mr-1 h-3.5 w-3.5"}),"Team Contacts"]}),s.lead_pond_enabled&&e.jsxs(Qt,{value:"lead-pond",children:[e.jsx(f1,{className:"mr-1 h-3.5 w-3.5"}),"Lead Pond"]}),s.shared_assets_enabled&&e.jsxs(Qt,{value:"shared-assets",children:[e.jsx(cv,{className:"mr-1 h-3.5 w-3.5"}),"Shared Assets"]}),e.jsx(Qt,{value:"settings",children:"Settings"})]}),e.jsxs(Jt,{value:"members",className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("h3",{className:"text-lg font-semibold",children:[s.name," — Members"]}),e.jsxs(Os,{open:p,onOpenChange:x,children:[e.jsx(Ko,{asChild:!0,children:e.jsxs($,{size:"sm",children:[e.jsx(il,{className:"mr-2 h-4 w-4"}),"Add Member"]})}),e.jsxs(Rs,{children:[e.jsxs(Us,{children:[e.jsx(zs,{children:"Add Team Member"}),e.jsxs(Sr,{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(se,{children:"Agent"}),e.jsxs(Sc,{children:[e.jsx(Cc,{asChild:!0,children:e.jsxs($,{variant:"outline",role:"combobox",className:"w-full justify-between font-normal",children:[g&&(((P=A.find(I=>I.id===g))==null?void 0:P.name)||((M=A.find(I=>I.id===g))==null?void 0:M.email))||"Select an agent",e.jsx(sw,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(xc,{className:"w-[--radix-popover-trigger-width] p-0",align:"start",children:e.jsxs(pw,{children:[e.jsx(fw,{placeholder:"Search agents..."}),e.jsxs(xw,{children:[e.jsx(gw,{children:"No agents found."}),e.jsx($b,{children:A.map(I=>{const D=N==null?void 0:N.get(I.id);return e.jsxs(iv,{value:I.name||I.email||I.id,onSelect:()=>y(I.id),children:[e.jsx(oa,{className:Tt("mr-2 h-4 w-4",g===I.id?"opacity-100":"opacity-0")}),I.name||I.email,D!=null&&D.length?e.jsxs("span",{className:"text-xs text-muted-foreground ml-1",children:["(also on ",D.join(", "),")"]}):null]},I.id)})})]})]})})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Role"}),e.jsxs(vs,{value:b,onValueChange:v,children:[e.jsx(gs,{children:e.jsx(bs,{})}),e.jsxs(ys,{children:[e.jsx(Ye,{value:"team_leader",children:"Team Leader"}),e.jsx(Ye,{value:"team_member",children:"Team Member"})]})]})]})]}),e.jsxs(kr,{children:[e.jsx($,{variant:"outline",onClick:()=>x(!1),children:"Cancel"}),e.jsx($,{onClick:T,disabled:!g||d,children:d?"Adding...":"Add to Team"})]})]})]})]}),m?e.jsx("div",{className:"space-y-3",children:[1,2,3].map(I=>e.jsx(on,{className:"h-16 w-full"},I))}):h.length===0?e.jsx(_e,{children:e.jsxs(Oe,{className:"flex flex-col items-center justify-center py-8 text-center",children:[e.jsx(qn,{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 D,B,q,W,V;return e.jsx(_e,{children:e.jsxs(Oe,{className:"flex items-center justify-between p-4",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs(Ea,{className:"h-10 w-10",children:[e.jsx(ki,{src:((D=I.profile)==null?void 0:D.avatar_url)||""}),e.jsx(Ta,{children:(((B=I.profile)==null?void 0:B.name)||"?").charAt(0).toUpperCase()})]}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:((q=I.profile)==null?void 0:q.name)||"Unknown"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:(W=I.profile)==null?void 0:W.email})]}),I.role==="team_leader"?e.jsxs($e,{className:"bg-[hsl(var(--chart-4)/0.1)] text-[hsl(var(--chart-4))] border-[hsl(var(--chart-4))]",children:[e.jsx(Ng,{className:"mr-1 h-3 w-3"})," Leader"]}):e.jsx($e,{variant:"secondary",children:"Member"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(vs,{value:I.role,onValueChange:K=>l(I.id,K),children:[e.jsx(gs,{className:"w-[140px]",children:e.jsx(bs,{})}),e.jsxs(ys,{children:[e.jsx(Ye,{value:"team_leader",children:"Team Leader"}),e.jsx(Ye,{value:"team_member",children:"Team Member"})]})]}),e.jsxs(Ll,{children:[e.jsx(_f,{asChild:!0,children:e.jsx($,{variant:"ghost",size:"icon",className:"text-muted-foreground hover:text-destructive",children:e.jsx(Hz,{className:"h-4 w-4"})})}),e.jsxs(yl,{children:[e.jsxs(vl,{children:[e.jsx(_l,{children:"Remove Member?"}),e.jsxs(wl,{children:["Remove ",((V=I.profile)==null?void 0:V.name)||"this member"," from ",s.name,"?"]})]}),e.jsxs(bl,{children:[e.jsx(jl,{children:"Cancel"}),e.jsx(fl,{onClick:()=>i(I.id),className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Remove"})]})]})]})]})]})},I.id)})})]}),e.jsx(Jt,{value:"contacts",className:"space-y-4",children:e.jsx(HWe,{})}),s.lead_pond_enabled&&e.jsx(Jt,{value:"lead-pond",className:"space-y-4",children:e.jsx(GWe,{teamId:s.id})}),s.shared_assets_enabled&&e.jsx(Jt,{value:"shared-assets",className:"space-y-4",children:e.jsx(x8t,{teamId:s.id})}),e.jsxs(Jt,{value:"settings",className:"space-y-4",children:[e.jsxs(_e,{children:[e.jsxs(Bt,{children:[e.jsx(Ut,{className:"text-lg",children:"Team Settings"}),e.jsx(vr,{children:"Configure how this team operates."})]}),e.jsxs(Oe,{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Team Name"}),e.jsx(be,{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(se,{children:"Description"}),e.jsx(Is,{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(se,{children:"Contact Visibility"}),e.jsxs(vs,{defaultValue:s.contact_visibility,onValueChange:I=>r({contact_visibility:I}),children:[e.jsx(gs,{children:e.jsx(bs,{})}),e.jsxs(ys,{children:[e.jsx(Ye,{value:"private",children:"Private — Members keep their contacts private"}),e.jsx(Ye,{value:"leader_only",children:"Leader Only — Only team leaders can see member contacts"}),e.jsx(Ye,{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(se,{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(Tn,{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(se,{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(Tn,{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(se,{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(Tn,{checked:s.shared_videos_enabled??!1,onCheckedChange:I=>r({shared_videos_enabled:I})})]})]})]}),s.lead_pond_enabled&&e.jsx(m8t,{teamId:s.id}),e.jsxs(Ll,{children:[e.jsx(_f,{asChild:!0,children:e.jsxs($,{variant:"destructive",size:"sm",children:[e.jsx(Pn,{className:"mr-2 h-4 w-4"}),"Delete Team"]})}),e.jsxs(yl,{children:[e.jsxs(vl,{children:[e.jsx(_l,{children:"Delete Team?"}),e.jsxs(wl,{children:['This will permanently delete "',s.name,'" and remove all team members. This cannot be undone.']})]}),e.jsxs(bl,{children:[e.jsx(jl,{children:"Cancel"}),e.jsx(fl,{onClick:()=>{o(),n()},className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Delete Team"})]})]})]})]})]})]})},y8t=({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(""),[x,g]=j.useState(""),[y,b]=j.useState(""),[v,N]=j.useState([]),C=()=>{d(1),h(""),p(""),g(""),b(""),N([])},A=I=>{I||C(),t(I)},T=async()=>{const I=x&&x!=="none"?x:o||null;await n({name:u.trim(),description:m.trim()||void 0,brokerage_id:I,leaderId:y||void 0,memberIds:v.length>0?v:void 0}),C()},P=I=>{I!==y&&N(D=>D.includes(I)?D.filter(B=>B!==I):[...D,I])},M=a.filter(I=>I.id!==y);return e.jsx(Os,{open:s,onOpenChange:A,children:e.jsxs(Rs,{className:"sm:max-w-lg max-h-[90vh] flex flex-col",children:[e.jsxs(Us,{children:[e.jsx(zs,{children:c===1?"Create New Team":"Assign Team Members"}),e.jsx(Sr,{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:Tt("h-1.5 flex-1 rounded-full transition-colors","bg-primary")}),e.jsx("div",{className:Tt("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(se,{htmlFor:"team-name",children:"Team Name *"}),e.jsx(be,{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(se,{htmlFor:"team-desc",children:"Description"}),e.jsx(Is,{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(se,{children:"Brokerage"}),e.jsxs(vs,{value:x,onValueChange:g,children:[e.jsx(gs,{children:e.jsx(bs,{placeholder:"No brokerage (independent team)"})}),e.jsxs(ys,{children:[e.jsx(Ye,{value:"none",children:"No brokerage (independent)"}),l.map(I=>e.jsx(Ye,{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(se,{className:"flex items-center gap-1.5",children:[e.jsx(Ng,{className:"h-3.5 w-3.5 text-[hsl(var(--chart-4))]"}),"Team Leader"]}),e.jsxs(vs,{value:y,onValueChange:I=>{b(I),N(D=>D.filter(B=>B!==I))},children:[e.jsx(gs,{children:e.jsx(bs,{placeholder:"Select a team leader (optional)"})}),e.jsxs(ys,{children:[e.jsx(Ye,{value:"none",children:"No leader for now"}),a.map(I=>e.jsx(Ye,{value:I.id,children:I.name||I.email||"Unknown"},I.id))]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(se,{className:"flex items-center gap-1.5",children:[e.jsx(il,{className:"h-3.5 w-3.5"}),"Initial Members",v.length>0&&e.jsxs($e,{variant:"secondary",className:"ml-1 text-xs",children:[v.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(qn,{className:"h-8 w-8 mx-auto mb-2 opacity-50"}),"No agents available"]}):M.map(I=>{const D=v.includes(I.id);return e.jsxs("button",{type:"button",className:Tt("w-full flex items-center gap-3 p-3 text-left transition-colors hover:bg-accent/50",D&&"bg-primary/5"),onClick:()=>P(I.id),children:[e.jsxs(Ea,{className:"h-8 w-8",children:[e.jsx(ki,{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:Tt("h-5 w-5 rounded-full border-2 flex items-center justify-center transition-colors shrink-0",D?"bg-primary border-primary text-primary-foreground":"border-muted-foreground/30"),children:D&&e.jsx(oa,{className:"h-3 w-3"})})]},I.id)})})]})]})}),e.jsx(kr,{className:"gap-2 sm:gap-0",children:c===1?e.jsxs(e.Fragment,{children:[e.jsx($,{variant:"outline",onClick:()=>A(!1),children:"Cancel"}),e.jsxs($,{onClick:()=>d(2),disabled:!u.trim(),children:["Next",e.jsx(ni,{className:"ml-2 h-4 w-4"})]})]}):e.jsxs(e.Fragment,{children:[e.jsxs($,{variant:"outline",onClick:()=>d(1),children:[e.jsx(ka,{className:"mr-2 h-4 w-4"}),"Back"]}),e.jsx($,{onClick:T,disabled:r,children:r?"Creating…":"Create Team"})]})})]})})},tqs=()=>{const{teams:s,isLoading:t,createTeam:n,updateTeam:r,deleteTeam:a,addMember:i,removeMember:l,updateMemberRole:o}=CC(),[c,d]=j.useState(!1),[u,h]=j.useState(null),[m,p]=j.useState(""),{data:x}=ht({queryKey:["all-brokerages-for-teams"],queryFn:async()=>{const{data:A,error:T}=await U.from("brokerages").select("id, name").order("name");if(T)throw T;return A||[]}}),{data:g}=ht({queryKey:["admin-team-member-info",s.map(A=>A.id).join(",")],queryFn:async()=>{var I;if(s.length===0)return{};const{data:A}=await U.from("team_members").select("team_id, user_id, role").in("team_id",s.map(D=>D.id));if(!A)return{};const T=A.filter(D=>D.role==="team_leader").map(D=>D.user_id);let P={};if(T.length>0){const{data:D}=await U.from("profiles").select("id, name").in("id",T);D&&(P=Object.fromEntries(D.map(B=>[B.id,{name:B.name}])))}const M={};for(const D of s){const B=A.filter(W=>W.team_id===D.id),q=B.find(W=>W.role==="team_leader");M[D.id]={count:B.length,leaderName:q&&((I=P[q.user_id])==null?void 0:I.name)||null}}return M},enabled:s.length>0}),y=(u==null?void 0:u.brokerage_id)||null,{data:b}=ht({queryKey:["brokerage-agents-for-teams",y],queryFn:async()=>{let A=U.from("profiles").select("id, name, email, avatar_url").order("name");y&&(A=A.eq("brokerage_id",y));const{data:T,error:P}=await A;if(P)throw P;return T||[]},enabled:!!u}),v=Object.fromEntries((x||[]).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 P of A.memberIds)await i.mutateAsync({team_id:T.id,user_id:P,role:"team_member"});d(!1)};if(u)return e.jsx(g8t,{team:u,brokerageAgents:b||[],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 C=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(Vr,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(be,{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:[C.length," of ",s.length," teams"]})]}),e.jsxs($,{size:"sm",onClick:()=>d(!0),children:[e.jsx(sn,{className:"mr-2 h-4 w-4"}),"Create Team"]})]}),e.jsx(y8t,{open:c,onOpenChange:d,onCreateTeam:N,isCreating:n.isPending,brokerageAgents:[],isAdmin:!0,allBrokerages:x,activeBrokerageId:null}),e.jsx("div",{className:"border rounded-lg bg-card overflow-hidden",children:e.jsxs(Va,{children:[e.jsx(Ha,{children:e.jsxs(hn,{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(Ga,{children:t?e.jsx(e.Fragment,{children:[1,2,3].map(A=>e.jsxs(hn,{children:[e.jsx(gt,{children:e.jsx(on,{className:"h-4 w-32"})}),e.jsx(gt,{children:e.jsx(on,{className:"h-4 w-24"})}),e.jsx(gt,{children:e.jsx(on,{className:"h-4 w-28"})}),e.jsx(gt,{children:e.jsx(on,{className:"h-4 w-12"})}),e.jsx(gt,{children:e.jsx(on,{className:"h-4 w-20"})}),e.jsx(gt,{children:e.jsx(on,{className:"h-4 w-16"})})]},A))}):C.length===0?e.jsx(hn,{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."})}):C.map(A=>{const T=g==null?void 0:g[A.id];return e.jsxs(hn,{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:v[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(Ng,{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($e,{variant:"secondary",className:"text-xs",children:[e.jsx(qn,{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(kf,{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($,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:()=>h(A),title:"Edit team",children:e.jsx(Ya,{className:"h-3.5 w-3.5"})}),e.jsx($,{variant:"ghost",size:"icon",className:"h-8 w-8 text-destructive hover:text-destructive",onClick:async()=>{await Yi(`Delete team "${A.name}"? This cannot be undone.`)&&a.mutate(A.id)},title:"Delete team",children:e.jsx(Pn,{className:"h-3.5 w-3.5"})})]})})]},A.id)})})]})})]})};function hut(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 sqs({open:s,onOpenChange:t,recipients:n}){const{toast:r}=gi(),[a,i]=j.useState([]),[l,o]=j.useState(!1),[c,d]=j.useState(""),[u,h]=j.useState(""),[m,p]=j.useState(""),[x,g]=j.useState(!1),[y,b]=j.useState(!1),v=j.useMemo(()=>a.find(T=>T.id===c)||null,[a,c]);j.useEffect(()=>{s&&(o(!0),(async()=>{const T=new Date().toISOString(),{data:P,error:M}=await U.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(P||[]),o(!1)})())},[s,r]);const N=j.useMemo(()=>n.filter(T=>T.email&&/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(T.email)),[n]),C=()=>{if(!v){r({title:"Pick an event first",variant:"destructive"});return}if(N.length===0){r({title:"No valid recipient emails",variant:"destructive"});return}b(!0)},A=async()=>{if(v){b(!1),g(!0);try{const{data:{session:T}}=await U.auth.getSession(),P=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:v.id,recipients:N.map(q=>({email:q.email,name:q.name,user_id:q.id})),custom_subject:u.trim()||void 0,custom_intro:m.trim()||void 0})}),M=await P.json().catch(()=>({}));if(!P.ok)throw new Error((M==null?void 0:M.error)||"Failed to send event invite");const I=(M==null?void 0:M.sent)??0,D=(M==null?void 0:M.failed)??0,B=(M==null?void 0:M.already_invited)??0;r({title:"Invites sent",description:`Sent: ${I}${B?` · Skipped (already invited): ${B}`:""}${D?` · Failed: ${D}`:""}`}),t(!1),p(""),h(""),d("")}catch(T){const P=T instanceof Error?T.message:"Send failed";r({title:"Send failed",description:P,variant:"destructive"})}finally{g(!1)}}};return e.jsxs(e.Fragment,{children:[e.jsx(Os,{open:s,onOpenChange:t,children:e.jsxs(Rs,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsxs(Us,{children:[e.jsxs(zs,{className:"flex items-center gap-2",children:[e.jsx(nn,{className:"h-5 w-5 text-primary"}),"Send Event Invite"]}),e.jsxs(Sr,{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(se,{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(Ht,{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(vs,{value:c,onValueChange:d,children:[e.jsx(gs,{id:"event-select",children:e.jsx(bs,{placeholder:"Pick an upcoming event..."})}),e.jsx(ys,{children:a.map(T=>e.jsx(Ye,{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:[hut(T.event_date),!T.is_published&&" · (Draft)"]})]})},T.id))})]})]}),v&&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(ia,{className:"h-4 w-4 text-primary"}),v.title]}),e.jsx("div",{className:"text-xs text-muted-foreground",children:hut(v.event_date)}),v.description&&e.jsx("p",{className:"text-xs text-muted-foreground line-clamp-2 mt-1",children:v.description})]}),e.jsxs("div",{children:[e.jsx(se,{htmlFor:"subject",children:"Subject line (optional)"}),e.jsx(be,{id:"subject",placeholder:v?`You're invited: ${v.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(se,{htmlFor:"intro",children:"Personal message (optional)"}),e.jsx(Is,{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($e,{variant:"secondary",className:"text-xs font-normal",children:T.name||T.email},T.id)),N.length>30&&e.jsxs($e,{variant:"outline",className:"text-xs",children:["+",N.length-30," more"]})]})]})]}),e.jsxs(kr,{children:[e.jsx($,{variant:"outline",onClick:()=>t(!1),disabled:x,children:"Cancel"}),e.jsx($,{onClick:C,disabled:x||!c||N.length===0,children:x?e.jsxs(e.Fragment,{children:[e.jsx(Ht,{className:"h-4 w-4 mr-2 animate-spin"})," Sending..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Br,{className:"h-4 w-4 mr-2"})," Send to ",N.length]})})]})]})}),e.jsx(Ll,{open:y,onOpenChange:b,children:e.jsxs(yl,{children:[e.jsxs(vl,{children:[e.jsx(_l,{children:"Send event invite?"}),e.jsx(wl,{children:v?e.jsxs(e.Fragment,{children:["Send invite for ",e.jsxs("span",{className:"font-medium text-foreground",children:['"',v.title,'"']})," to"," ",e.jsxs("span",{className:"font-medium text-foreground",children:[N.length," member",N.length===1?"":"s"]}),"?"]}):null})]}),e.jsxs(bl,{children:[e.jsx(jl,{children:"Cancel"}),e.jsxs(fl,{onClick:A,children:[e.jsx(Br,{className:"h-4 w-4 mr-2"})," Send"]})]})]})})]})}const nqs=()=>{var Ir;const s=Vn(),{user:t,isAdmin:n}=_s(),{startImpersonation:r,isLoading:a}=aCe(),{toast:i}=gi(),[l,o]=j.useState([]),[c,d]=j.useState([]),[u,h]=j.useState([]),[m,p]=j.useState({}),[x,g]=j.useState(!0);j.useState({});const[y,b]=j.useState(!1),[v,N]=j.useState({email:"",name:"",password:"",brokerage_id:"",role:"user",phone:"",trial_days:""}),[C,A]=j.useState(!1),[T,P]=j.useState(""),[M,I]=j.useState(1),[D,B]=j.useState(50),[q,W]=j.useState("all"),[V,K]=j.useState("all"),[Q,J]=j.useState("all"),[ce,ue]=j.useState("all"),[ne,ee]=j.useState("all"),[le,he]=j.useState(!1),[ve,ge]=j.useState(!1),[fe,je]=j.useState(!1),[Ee,Me]=j.useState(null),[De,ze]=j.useState(null),[ke,Xe]=j.useState(!1),[Se,Re]=j.useState({name:"",email:"",brokerage_id:"",phone:""}),[Ae,Be]=j.useState(null),[qe,Ke]=j.useState(!1),[Ze,Ue]=j.useState(""),[et,Qe]=j.useState(!1),[Ge,nt]=j.useState(!1),[ft,lt]=j.useState(null),[Mt,Ft]=j.useState(""),[Ts,js]=j.useState(!1),[zt,Nt]=j.useState(!1),[Ds,_t]=j.useState(null),[Xs,rn]=j.useState(!1),[Ps,_n]=j.useState(!1),[Zs,gr]=j.useState(null),[Un,In]=j.useState(""),[Ar,or]=j.useState(!1),[qs,yr]=j.useState({email:"",name:"",password:"",phone:""}),[fn,Zn]=j.useState(!1),[Xt,rr]=j.useState(null),[Qn,Sn]=j.useState([]),[$n,tn]=j.useState("none"),[ln,Cr]=j.useState(!1),[ms,ot]=j.useState(""),[pt,vt]=j.useState(!1),[At,Zt]=j.useState(!1),[as,Ls]=j.useState(""),[cs,qt]=j.useState(new Set),[Gs,Vs]=j.useState(!1),[Hn,Kr]=j.useState(!1),[ma,Or]=j.useState(null),[ta,da]=j.useState(!1),[va,hi]=j.useState(null),[el,Oo]=j.useState([]),[Ei,Wa]=j.useState([]),[wo,Io]=j.useState(!1),[is,zr]=j.useState({});j.useEffect(()=>{!t||!n||(Kn(),wn())},[t,n]);const Sa=async()=>{try{const{data:kt,error:Cs}=await U.from("brokerage_manager_assignments").select("user_id, brokerage_id");if(Cs)throw Cs;const xn={};for(const Rr of kt??[])xn[Rr.brokerage_id]||(xn[Rr.brokerage_id]=[]),xn[Rr.brokerage_id].push(Rr.user_id);p(xn)}catch(kt){console.error("Error loading brokerage manager assignments:",kt)}},Kn=async()=>{try{g(!0);const{data:kt,error:Cs}=await U.functions.invoke("get-user-details");if(Cs)throw Cs;const xn=kt.users||[];o(xn),h(kt.brokerages||[]),await Sa();const Rr=xn.filter(Dr=>Dr.roles.includes("assistant"));if(Rr.length>0){const Dr=Rr.map(Ua=>Ua.id),{data:Aa}=await U.from("agent_assistant_assignments").select("agent_id, assistant_id").in("assistant_id",Dr);if(Aa&&Aa.length>0){const Ua=[...new Set(Aa.map(ri=>ri.agent_id))],{data:sr}=await U.from("profiles").select("id, name, email").in("id",Ua),Ra={};for(const ri of Aa){const Ho=sr==null?void 0:sr.find(Kl=>Kl.id===ri.agent_id);Ho&&(Ra[ri.assistant_id]={agent_name:Ho.name||"",agent_email:Ho.email||""})}zr(Ra)}}}catch(kt){console.error("Error loading members:",kt),i({title:"Error",description:"Failed to load members",variant:"destructive"})}finally{g(!1)}},wn=async()=>{try{const{data:kt,error:Cs}=await U.from("app_tiles").select("id, name, icon, app_id, required_tags").order("name");if(Cs)throw Cs;d(kt||[])}catch(kt){console.error("Error loading apps:",kt),i({title:"Error",description:"Failed to load apps",variant:"destructive"})}},Ur=async kt=>{if(!Se.name.trim()||!Se.email.trim()){i({title:"Error",description:"Name and email are required",variant:"destructive"});return}if(!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(Se.email)){i({title:"Error",description:"Please enter a valid email address",variant:"destructive"});return}try{const{error:xn}=await U.from("profiles").update({name:Se.name.trim(),email:Se.email.trim(),brokerage_id:Se.brokerage_id||null,phone:Se.phone.trim()||null}).eq("id",kt);if(xn)throw xn;i({title:"Success",description:"Member details updated successfully"}),Me(null),Kn()}catch(xn){console.error("Error updating member:",xn),i({title:"Error",description:xn.message||"Failed to update member",variant:"destructive"})}},ca=async kt=>{try{const{data:{session:Cs}}=await U.auth.getSession(),xn=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/resend-welcome-email",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${Cs==null?void 0:Cs.access_token}`},body:JSON.stringify({userId:kt})}),Rr=await xn.json();if(!xn.ok)throw new Error(Rr.error||"Failed to resend welcome email");i({title:"Success",description:"Welcome email sent successfully"})}catch(Cs){console.error("Error resending welcome email:",Cs),i({title:"Error",description:Cs.message||"Failed to resend welcome email",variant:"destructive"})}},yo=async(kt,Cs)=>{try{const{error:xn}=await U.functions.invoke("send-password-reset",{body:{email:kt,redirectTo:window.location.origin}});if(xn)throw xn;i({title:"Password Reset Sent",description:`Password reset email sent to ${Cs}`})}catch(xn){console.error("Error sending password reset:",xn),i({title:"Error",description:xn.message||"Failed to send password reset email",variant:"destructive"})}},vo=async(kt,Cs)=>{if(await Yi(`Are you sure you want to delete ${Cs}? This action cannot be undone.`))try{const{data:{session:xn}}=await U.auth.getSession(),Rr=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/delete-user",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${xn==null?void 0:xn.access_token}`},body:JSON.stringify({userId:kt})}),Dr=await Rr.json();if(!Rr.ok)throw new Error(Dr.error||"Failed to delete user");i({title:"Success",description:"User deleted successfully"}),Kn()}catch(xn){console.error("Error deleting user:",xn),i({title:"Error",description:xn.message||"Failed to delete user",variant:"destructive"})}},Vo=async()=>{if(!v.email||!v.name||!v.password){i({title:"Error",description:"Please fill in all fields",variant:"destructive"});return}if(v.role==="brokerage_manager"&&!v.brokerage_id){i({title:"Error",description:"Please select a brokerage for this manager",variant:"destructive"});return}b(!0);try{const{data:{session:kt}}=await U.auth.getSession(),Cs=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(v)}),xn=await Cs.json();if(!Cs.ok)throw new Error(xn.error||"Failed to create user");if(v.role&&v.role!=="user"&&xn.userId){const Rr=v.role==="brokerage_manager"?v.brokerage_id:void 0;await Xc(xn.userId,v.role,"add",Rr)}i({title:"Success",description:`User ${v.email} created successfully`}),N({email:"",name:"",password:"",brokerage_id:"",role:"user",phone:"",trial_days:""}),A(!1),Kn()}catch(kt){console.error("Error creating user:",kt),i({title:"Error",description:kt.message||"Failed to create user",variant:"destructive"})}finally{b(!1)}},Xc=async(kt,Cs,xn,Rr)=>{try{const{data:{session:Dr}}=await U.auth.getSession(),Aa={userId:kt,role:Cs,action:xn};if(Cs==="brokerage_manager"){if(!Rr){i({title:"Error",description:"Please choose a brokerage for this manager assignment",variant:"destructive"});return}Aa.brokerageId=Rr}const Ua=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/manage-user-roles",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${Dr==null?void 0:Dr.access_token}`},body:JSON.stringify(Aa)}),sr=await Ua.json();if(!Ua.ok)throw new Error(sr.error||"Failed to manage user role");i({title:"Success",description:`Role ${xn==="add"?"added":"removed"} successfully`}),Kn()}catch(Dr){console.error("Error managing user role:",Dr),i({title:"Error",description:Dr.message||"Failed to manage user role",variant:"destructive"})}},uo=(kt,Cs)=>Cs.length===0?!0:Cs.some(xn=>kt.includes(xn)),bo=async(kt,Cs,xn)=>{const Rr=`${kt}-${Cs.id}`;Be(Rr);try{if(xn){const Dr=l.find(Ua=>Ua.id===kt),Aa=Cs.required_tags.filter(Ua=>Dr==null?void 0:Dr.tags.includes(Ua));for(const Ua of Aa){const{error:sr}=await U.from("user_tags").delete().eq("user_id",kt).eq("tag",Ua);if(sr)throw sr}i({title:"Access Removed",description:`Removed access to ${Cs.name}`})}else if(Cs.required_tags.length>0){const{error:Dr}=await U.from("user_tags").insert({user_id:kt,tag:Cs.required_tags[0]});if(Dr)throw Dr;i({title:"Access Granted",description:`Granted access to ${Cs.name}`})}await Kn()}catch(Dr){console.error("Error toggling access:",Dr),i({title:"Error",description:Dr.message||"Failed to update access",variant:"destructive"})}finally{Be(null)}},od=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(xn=>xn.name.toLowerCase()===kt.toLowerCase())){i({title:"Error",description:"A brokerage with this name already exists",variant:"destructive"});return}Qe(!0);try{const{error:xn}=await U.from("brokerages").insert({name:kt});if(xn)throw xn;i({title:"Success",description:`Brokerage "${kt}" created successfully`}),Ue(""),Ke(!1),Kn()}catch(xn){console.error("Error creating brokerage:",xn),i({title:"Error",description:xn.message||"Failed to create brokerage",variant:"destructive"})}finally{Qe(!1)}},Ju=kt=>{lt(kt),Ft(kt.name),nt(!0)},Ld=()=>{lt(null),Ft(""),nt(!1)},bd=async()=>{if(!ft)return;const kt=Mt.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}js(!0);try{const{error:Cs}=await U.from("brokerages").update({name:kt}).eq("id",ft.id);if(Cs)throw Cs;i({title:"Success",description:"Brokerage updated successfully"}),Ld(),Kn()}catch(Cs){console.error("Error updating brokerage:",Cs),i({title:"Error",description:Cs.message||"Failed to update brokerage",variant:"destructive"})}finally{js(!1)}},hx=async(kt,Cs)=>{var xn;if(!Cs||typeof Cs!="string"){i({title:"Error",description:"Please select a brokerage first",variant:"destructive"});return}try{const Rr={userId:kt,role:"brokerage_manager",action:"add",brokerageId:Cs};console.debug("[assignManagerToBrokerage] payload",Rr);const{data:{session:Dr}}=await U.auth.getSession(),Aa=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/manage-user-roles",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${Dr==null?void 0:Dr.access_token}`},body:JSON.stringify(Rr)}),Ua=await Aa.json();if(!Aa.ok&&!((xn=Ua.error)!=null&&xn.includes("duplicate")))throw new Error(Ua.error||"Failed to add role");i({title:"Success",description:"Manager assigned to brokerage"}),await Kn()}catch(Rr){console.error("Error assigning manager:",Rr),i({title:"Error",description:Rr.message||"Failed to assign manager",variant:"destructive"})}},Ay=kt=>{_t(kt),Nt(!0)},Kp=async()=>{if(Ds){rn(!0);try{const kt=l.filter(Rr=>Rr.brokerage_id===Ds.id),{data:{session:Cs}}=await U.auth.getSession();for(const Rr of kt){const Dr=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/delete-user",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${Cs==null?void 0:Cs.access_token}`},body:JSON.stringify({userId:Rr.id})});if(!Dr.ok){const Aa=await Dr.json();console.error(`Failed to delete user ${Rr.email}:`,Aa.error)}}const{error:xn}=await U.from("brokerages").delete().eq("id",Ds.id);if(xn)throw xn;i({title:"Success",description:`Brokerage "${Ds.name}" and ${kt.length} member(s) deleted`}),Nt(!1),_t(null),Kn()}catch(kt){console.error("Error deleting brokerage:",kt),i({title:"Error",description:kt.message||"Failed to delete brokerage",variant:"destructive"})}finally{rn(!1)}}},Dg=kt=>{gr(kt),In(""),_n(!0)},Em=()=>{gr(null),In(""),_n(!1)},Lf=async kt=>{try{const{error:Cs}=await U.from("profiles").update({brokerage_id:null}).eq("id",kt);if(Cs)throw Cs;i({title:"Success",description:"User removed from brokerage"}),Kn()}catch(Cs){console.error("Error removing user from brokerage:",Cs),i({title:"Error",description:Cs.message||"Failed to remove user",variant:"destructive"})}},eh=async(kt,Cs)=>{try{const{error:xn}=await U.from("profiles").update({brokerage_id:Cs}).eq("id",kt);if(xn)throw xn;i({title:"Success",description:"User added to brokerage"}),Kn()}catch(xn){console.error("Error adding user to brokerage:",xn),i({title:"Error",description:xn.message||"Failed to add user",variant:"destructive"})}};j.useEffect(()=>{(async()=>{var Cs;if(!(Zs!=null&&Zs.id)){rr(null),Sn([]),tn("none");return}try{const{data:xn}=await U.from("partnership_programs").select("id, name, enabled").eq("brokerage_id",Zs.id).maybeSingle();if(!xn||!xn.enabled){rr(null),Sn([]),tn("none");return}const{data:Rr}=await U.from("partnership_packages").select("id, name, description, sort_order").eq("program_id",xn.id).order("sort_order",{ascending:!0});rr({id:xn.id,name:xn.name}),Sn(Rr||[]),tn(((Cs=Rr==null?void 0:Rr[0])==null?void 0:Cs.id)||"none")}catch(xn){console.error("Error loading partnership packages:",xn)}})()},[Zs==null?void 0:Zs.id]);const L0=async()=>{if(!Zs||!qs.email||!qs.name||!qs.password){i({title:"Error",description:"Please fill in all fields",variant:"destructive"});return}Zn(!0);try{const{data:{session:kt}}=await U.auth.getSession(),Cs=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({...qs,brokerage_id:Zs.id,role:"user",partnershipPackageId:Xt&&$n!=="none"?$n:void 0})}),xn=await Cs.json();if(!Cs.ok)throw new Error(xn.error||"Failed to create agent");i({title:"Success",description:`Agent ${qs.email} created successfully`}),yr({email:"",name:"",password:"",phone:""}),or(!1),Kn()}catch(kt){console.error("Error creating agent:",kt),i({title:"Error",description:kt.message||"Failed to create agent",variant:"destructive"})}finally{Zn(!1)}},jo=kt=>l.filter(Cs=>Cs.brokerage_id===kt),Zi=kt=>{const Cs=jo(kt);if(!Un)return Cs;const xn=Un.toLowerCase();return Cs.filter(Rr=>Rr.name.toLowerCase().includes(xn)||Rr.email.toLowerCase().includes(xn))},Ey=kt=>l.filter(Cs=>Cs.brokerage_id!==kt),Pf=l.filter(kt=>{var xn;if(T){const Rr=T.toLowerCase();if(!(kt.name.toLowerCase().includes(Rr)||kt.email.toLowerCase().includes(Rr)||((xn=kt.brokerage_name)==null?void 0:xn.toLowerCase().includes(Rr))))return!1}if(q==="claimed"&&!kt.claimed||q==="unclaimed"&&kt.claimed||V!=="all"&&!kt.roles.includes(V))return!1;const Cs=kt.is_trial||kt.subscription_status==="trialing";if(Q==="trial"&&!Cs||Q==="non-trial"&&Cs||ce==="none"&&kt.brokerage_id||ce!=="all"&&ce!=="none"&&kt.brokerage_id!==ce)return!1;if(ne!=="all"){if(!kt.created_at)return!1;const Rr=parseInt(ne,10),Dr=Date.now()-Rr*24*60*60*1e3;if(new Date(kt.created_at).getTime(){var Cs;return((Cs=kt.name)==null?void 0:Cs.toLowerCase())||""},brokerage:kt=>{var Cs;return((Cs=kt.brokerage_name)==null?void 0:Cs.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}),lp=Lu.length,Ty=D===0,Kd=Ty?1:Math.ceil(lp/D),Ti=Ty?0:(M-1)*D,rm=Ty?lp:Ti+D,mh=Lu.slice(Ti,rm),Tm=kt=>{P(kt),I(1)},Yp=kt=>{B(kt),I(1)},ph=(kt,Cs)=>{kt(Cs),I(1)},am=async(kt,Cs)=>{ge(!0);try{const xn=l.find(Ua=>Ua.id===kt);if(!xn)return;const Rr=xn.trial_expires_at?new Date(xn.trial_expires_at):new Date,Dr=new Date(Rr.getTime()+Cs*24*60*60*1e3),{error:Aa}=await U.from("profiles").update({trial_expires_at:Dr.toISOString()}).eq("id",kt);if(Aa)throw Aa;i({title:"Trial Extended",description:`Trial extended by ${Cs} days`}),Kn()}catch(xn){console.error("Error extending trial:",xn),i({title:"Error",description:xn.message||"Failed to extend trial",variant:"destructive"})}finally{ge(!1)}},Og=async kt=>{je(!0);try{const{error:Cs}=await U.from("profiles").update({is_trial:!1,trial_expires_at:null,trial_started_at:null,trial_claimed_at:null}).eq("id",kt);if(Cs)throw Cs;i({title:"Account Converted",description:"User has been converted to a full account"}),Kn(),P0()}catch(Cs){console.error("Error converting trial:",Cs),i({title:"Error",description:Cs.message||"Failed to convert account",variant:"destructive"})}finally{je(!1)}},[Fg,Mm]=j.useState(!1),im=async(kt,Cs)=>{if(await Yi(`Revert this user to a ${Cs}-day free trial? This will clear their paid/grandfathered status. Any active Stripe subscription will need to be cancelled separately.`)){Mm(!0);try{const xn=new Date,Rr=new Date(xn.getTime()+Cs*24*60*60*1e3),{error:Dr}=await U.from("profiles").update({is_trial:!0,trial_started_at:xn.toISOString(),trial_expires_at:Rr.toISOString(),trial_claimed_at:xn.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(Dr)throw Dr;i({title:"Reverted to Trial",description:`User is now on a ${Cs}-day free trial.`}),Kn()}catch(xn){console.error("Error reverting to trial:",xn),i({title:"Error",description:xn.message||"Failed to revert to trial",variant:"destructive"})}finally{Mm(!1)}}},Vx=async kt=>{Io(!0);try{const{data:Cs}=await U.from("agent_assistant_assignments").select("id, assistant_id, permissions").eq("agent_id",kt);if(Cs&&Cs.length>0){const Rr=Cs.map(Aa=>Aa.assistant_id),{data:Dr}=await U.from("profiles").select("id, name, email").in("id",Rr);Oo(Cs.map(Aa=>{const Ua=Dr==null?void 0:Dr.find(sr=>sr.id===Aa.assistant_id);return{id:Aa.id,assistant_id:Aa.assistant_id,assistant_name:(Ua==null?void 0:Ua.name)||"Unknown",assistant_email:(Ua==null?void 0:Ua.email)||"",permissions:Aa.permissions||{}}}))}else Oo([]);const{data:xn}=await U.from("agent_assistant_assignments").select("id, agent_id, permissions").eq("assistant_id",kt);if(xn&&xn.length>0){const Rr=xn.map(Aa=>Aa.agent_id),{data:Dr}=await U.from("profiles").select("id, name, email").in("id",Rr);Wa(xn.map(Aa=>{const Ua=Dr==null?void 0:Dr.find(sr=>sr.id===Aa.agent_id);return{id:Aa.id,agent_id:Aa.agent_id,agent_name:(Ua==null?void 0:Ua.name)||"Unknown",agent_email:(Ua==null?void 0:Ua.email)||"",permissions:Aa.permissions||{}}}))}else Wa([])}catch(Cs){console.error("Error loading assistant data:",Cs)}finally{Io(!1)}},mx=kt=>{ze(kt),Re({name:kt.name,email:kt.email,brokerage_id:kt.brokerage_id||"",phone:kt.phone||""}),Xe(!0),Vx(kt.id)},P0=()=>{ze(null),Xe(!1),Re({name:"",email:"",brokerage_id:"",phone:""})},ld=async()=>{De&&(await Ur(De.id),P0())},Oc=kt=>{qt(Cs=>{const xn=new Set(Cs);return xn.has(kt)?xn.delete(kt):xn.add(kt),xn})},cp=()=>{if(cs.size===mh.length&&mh.every(kt=>cs.has(kt.id))){const kt=new Set(cs);mh.forEach(Cs=>kt.delete(Cs.id)),qt(kt)}else{const kt=new Set(cs);mh.forEach(Cs=>kt.add(Cs.id)),qt(kt)}},_d=()=>{qt(new Set)},dp=async()=>{if(cs.size===0)return;Vs(!0);let kt=0,Cs=0;try{const{data:{session:xn}}=await U.auth.getSession();for(const Rr of cs)try{(await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/resend-welcome-email",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${xn==null?void 0:xn.access_token}`},body:JSON.stringify({userId:Rr})})).ok?kt++:Cs++}catch{Cs++}i({title:"Bulk Email Complete",description:`Sent ${kt} emails${Cs>0?`, ${Cs} failed`:""}`}),_d()}catch(xn){i({title:"Error",description:xn.message||"Failed to send emails",variant:"destructive"})}finally{Vs(!1)}},om=async()=>{if(cs.size===0)return;Vs(!0);let kt=0,Cs=0;try{const{data:{session:xn}}=await U.auth.getSession();for(const Rr of cs)try{(await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/send-password-reset",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${xn==null?void 0:xn.access_token}`},body:JSON.stringify({userId:Rr})})).ok?kt++:Cs++}catch{Cs++}i({title:"Bulk Password Reset Complete",description:`Sent ${kt} reset emails${Cs>0?`, ${Cs} failed`:""}`}),_d()}catch(xn){i({title:"Error",description:xn.message||"Failed to send password reset emails",variant:"destructive"})}finally{Vs(!1)}},Rh=async()=>{if(cs.size===0)return;const kt=l.filter(Dr=>cs.has(Dr.id)).map(Dr=>Dr.name).slice(0,5).join(", "),Cs=cs.size>5?` and ${cs.size-5} more`:"";if(!await Yi(`Are you sure you want to delete ${cs.size} users (${kt}${Cs})? This action cannot be undone.`))return;Vs(!0);let xn=0,Rr=0;try{const{data:{session:Dr}}=await U.auth.getSession();for(const Aa of cs)try{(await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/delete-user",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${Dr==null?void 0:Dr.access_token}`},body:JSON.stringify({userId:Aa})})).ok?xn++:Rr++}catch{Rr++}i({title:"Bulk Delete Complete",description:`Deleted ${xn} users${Rr>0?`, ${Rr} failed`:""}`}),_d(),Kn()}catch(Dr){i({title:"Error",description:Dr.message||"Failed to delete users",variant:"destructive"})}finally{Vs(!1)}},at=async()=>{Kr(!0);try{const{data:{session:kt}}=await U.auth.getSession(),Cs=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(!Cs.ok){const Rr=await Cs.json();throw new Error(Rr.error||"Failed to sync phones")}const xn=await Cs.json();i({title:"Phone Sync Complete",description:`Pulled ${xn.summary.pulledFromGHL} from GHL, pushed ${xn.summary.pushedToGHL} to GHL, ${xn.summary.alreadySynced} already synced`}),Kn()}catch(kt){i({title:"Error",description:kt.message||"Failed to sync phones with GHL",variant:"destructive"})}finally{Kr(!1)}},Wt=async(kt,Cs)=>{Or(kt);try{const{data:{session:xn}}=await U.auth.getSession(),{data:Rr}=await U.from("profiles").select("phone").eq("id",kt).single(),Dr=(Rr==null?void 0:Rr.phone)||"",Aa=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/ghl-tag-sync",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${xn==null?void 0:xn.access_token}`},body:JSON.stringify({email:Cs,action:"update",phone:Dr||void 0})});if(!Aa.ok){const sr=await Aa.json();throw new Error(sr.error||"Failed to sync with GHL")}const Ua=await fetch(`https://services.leadconnectorhq.com/contacts/lookup?locationId=&email=${encodeURIComponent(Cs)}`,{method:"GET",headers:{"Content-Type":"application/json"}});i({title:"Phone Synced",description:Dr?`Phone ${Dr} synced to GHL`:"Sync attempted - run bulk sync to pull phone from GHL"}),Kn()}catch(xn){i({title:"Error",description:xn.message||"Failed to sync phone",variant:"destructive"})}finally{Or(null)}},Bs=async kt=>{await r(kt)},Ys=()=>{if(cs.size===0){i({title:"No members selected",description:"Please select members to export",variant:"destructive"});return}const kt=l.filter(sr=>cs.has(sr.id)),Cs=["Name","Email","Phone","Brokerage","Roles","Status","Created At"],xn=kt.map(sr=>[sr.name,sr.email,sr.phone||"",sr.brokerage_name||"",sr.roles.join("; "),sr.claimed?"Claimed":"Unclaimed",new Date(sr.created_at).toLocaleDateString()]),Rr=[Cs.join(","),...xn.map(sr=>sr.map(Ra=>`"${(Ra||"").replace(/"/g,'""')}"`).join(","))].join(` `),Dr=new Blob([Rr],{type:"text/csv"}),Aa=URL.createObjectURL(Dr),Ua=document.createElement("a");Ua.href=Aa,Ua.download=`members-export-${new Date().toISOString().split("T")[0]}.csv`,Ua.click(),URL.revokeObjectURL(Aa),i({title:"Export complete",description:`Exported ${kt.length} member(s)`})},jn=()=>{if(Pf.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"],Cs=Pf.map(sr=>[sr.name,sr.email,sr.phone||"",sr.brokerage_name||"",sr.roles.join("; "),sr.claimed?"Claimed":"Unclaimed",sr.created_at?new Date(sr.created_at).toLocaleDateString():""]),xn=[kt.join(","),...Cs.map(sr=>sr.map(Ra=>`"${(Ra||"").replace(/"/g,'""')}"`).join(","))].join(` `),Rr=new Blob([xn],{type:"text/csv"}),Dr=URL.createObjectURL(Rr),Aa=document.createElement("a"),Ua=ne!=="all"?`-last-${ne}days`:"";Aa.href=Dr,Aa.download=`members-export${Ua}-${new Date().toISOString().split("T")[0]}.csv`,Aa.click(),URL.revokeObjectURL(Dr),i({title:"Export complete",description:`Exported ${Pf.length} member(s)`})};return x?e.jsx(Ks,{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(Ks,{title:"Members",children:[e.jsxs("div",{className:"space-y-6",children:[e.jsx(hh,{title:"Member Management",description:"Manage users, roles, and permissions",children:e.jsxs($,{size:"sm",variant:"outline",onClick:()=>s("/admin/unassigned-members"),className:"gap-2",children:[e.jsx(mc,{className:"h-4 w-4 text-amber-500"}),"Unassigned Members"]})}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("div",{}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs($,{size:"sm",variant:"outline",onClick:at,disabled:Hn,children:[Hn?e.jsx(Ht,{className:"mr-2 h-4 w-4 animate-spin"}):e.jsx(ya,{className:"mr-2 h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline",children:Hn?"Syncing...":"Sync Phones with GHL"}),e.jsx("span",{className:"sm:hidden",children:Hn?"Syncing...":"Sync GHL"})]}),e.jsxs($,{size:"sm",variant:"outline",onClick:()=>Cr(!0),children:[e.jsx(PN,{className:"mr-2 h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Import CSV"}),e.jsx("span",{className:"sm:hidden",children:"Import"})]}),e.jsxs(Os,{open:C,onOpenChange:A,children:[e.jsx(Ko,{asChild:!0,children:e.jsxs($,{size:"sm",children:[e.jsx(il,{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(Rs,{children:[e.jsxs(Us,{children:[e.jsx(zs,{children:"Create New User"}),e.jsx(Sr,{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(se,{htmlFor:"name",children:"Name"}),e.jsx(be,{id:"name",placeholder:"John Doe",value:v.name,onChange:kt=>N({...v,name:kt.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"email",children:"Email"}),e.jsx(be,{id:"email",type:"email",placeholder:"john@example.com",value:v.email,onChange:kt=>N({...v,email:kt.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"password",children:"Password"}),e.jsx(be,{id:"password",type:"password",placeholder:"Min 6 characters",value:v.password,onChange:kt=>N({...v,password:kt.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"phone",children:"Phone (optional)"}),e.jsx(be,{id:"phone",type:"tel",placeholder:"555-123-4567",value:v.phone,onChange:kt=>N({...v,phone:kt.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(se,{htmlFor:"brokerage",children:["Brokerage",v.role==="brokerage_manager"?" (required)":""]}),e.jsxs(vs,{value:v.brokerage_id||"none",onValueChange:kt=>N({...v,brokerage_id:kt==="none"?"":kt}),children:[e.jsx(gs,{id:"brokerage",children:e.jsx(bs,{placeholder:v.role==="brokerage_manager"?"Select brokerage":"Select brokerage (optional)"})}),e.jsxs(ys,{children:[e.jsx(Ye,{value:"none",children:"None"}),u.map(kt=>e.jsx(Ye,{value:kt.id,children:kt.name},kt.id))]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"role",children:"Role"}),e.jsxs(vs,{value:v.role,onValueChange:kt=>N({...v,role:kt}),children:[e.jsx(gs,{id:"role",children:e.jsx(bs,{placeholder:"Select role"})}),e.jsxs(ys,{children:[e.jsx(Ye,{value:"user",children:"User"}),e.jsx(Ye,{value:"moderator",children:"Moderator"}),e.jsx(Ye,{value:"brokerage_manager",children:"Brokerage Manager"}),e.jsx(Ye,{value:"admin",children:"Admin"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"trial_days",children:"Trial Period (optional)"}),e.jsxs(vs,{value:v.trial_days||"none",onValueChange:kt=>N({...v,trial_days:kt==="none"?"":kt}),children:[e.jsx(gs,{id:"trial_days",children:e.jsx(bs,{placeholder:"No trial (full access)"})}),e.jsxs(ys,{children:[e.jsx(Ye,{value:"none",children:"No trial (full access)"}),e.jsx(Ye,{value:"7",children:"7-day trial"}),e.jsx(Ye,{value:"30",children:"30-day trial"}),e.jsx(Ye,{value:"60",children:"60-day trial"}),e.jsx(Ye,{value:"90",children:"90-day trial"}),e.jsx(Ye,{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(kr,{children:[e.jsx($,{variant:"outline",onClick:()=>A(!1),children:"Cancel"}),e.jsx($,{onClick:Vo,disabled:y,children:y?"Creating...":"Create User"})]})]})]})]})]}),e.jsxs(ua,{defaultValue:new URLSearchParams(window.location.search).get("tab")||"members",className:"space-y-6",children:[e.jsxs(ha,{children:[e.jsx(Qt,{value:"members",children:"Members"}),e.jsx(Qt,{value:"brokerages",children:"Brokerages"}),e.jsx(Qt,{value:"teams",children:"Teams"}),e.jsx(Qt,{value:"trials",children:"Trial Users"}),e.jsx(Qt,{value:"access",children:"Access Matrix"}),e.jsx(Qt,{value:"celebrations",children:"Celebrations"}),e.jsx(Qt,{value:"deletions",children:"Deletion Log"})]}),e.jsxs(Jt,{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(Vr,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(be,{placeholder:"Search members...",value:T,onChange:kt=>Tm(kt.target.value),className:"pl-10 h-9"})]}),e.jsxs(vs,{value:q,onValueChange:kt=>ph(W,kt),children:[e.jsx(gs,{className:"w-[130px] h-9",children:e.jsx(bs,{})}),e.jsxs(ys,{children:[e.jsx(Ye,{value:"all",children:"All Status"}),e.jsx(Ye,{value:"claimed",children:"Active"}),e.jsx(Ye,{value:"unclaimed",children:"Pending"})]})]}),e.jsxs(vs,{value:V,onValueChange:kt=>ph(K,kt),children:[e.jsx(gs,{className:"w-[130px] h-9",children:e.jsx(bs,{})}),e.jsxs(ys,{children:[e.jsx(Ye,{value:"all",children:"All Roles"}),e.jsx(Ye,{value:"admin",children:"Admin"}),e.jsx(Ye,{value:"brokerage_manager",children:"Manager"}),e.jsx(Ye,{value:"assistant",children:"Assistant"}),e.jsx(Ye,{value:"user",children:"User"})]})]}),e.jsxs(vs,{value:Q,onValueChange:kt=>ph(J,kt),children:[e.jsx(gs,{className:"w-[130px] h-9",children:e.jsx(bs,{})}),e.jsxs(ys,{children:[e.jsx(Ye,{value:"all",children:"All Users"}),e.jsx(Ye,{value:"trial",children:"Trial Only"}),e.jsx(Ye,{value:"non-trial",children:"Full Only"})]})]}),e.jsxs(vs,{value:ce,onValueChange:kt=>ph(ue,kt),children:[e.jsx(gs,{className:"w-[150px] h-9",children:e.jsx(bs,{})}),e.jsxs(ys,{children:[e.jsx(Ye,{value:"all",children:"All Brokerages"}),e.jsx(Ye,{value:"none",children:"No Brokerage"}),u.map(kt=>e.jsx(Ye,{value:kt.id,children:kt.name},kt.id))]})]}),e.jsxs(vs,{value:ne,onValueChange:kt=>ph(ee,kt),children:[e.jsx(gs,{className:"w-[150px] h-9",children:e.jsx(bs,{})}),e.jsxs(ys,{children:[e.jsx(Ye,{value:"all",children:"Any Join Date"}),e.jsx(Ye,{value:"30",children:"Joined Last 30 Days"}),e.jsx(Ye,{value:"60",children:"Joined Last 60 Days"}),e.jsx(Ye,{value:"90",children:"Joined Last 90 Days"})]})]}),e.jsxs($,{size:"sm",variant:"outline",className:"h-9",onClick:jn,title:"Export currently filtered members to CSV",children:[e.jsx(di,{className:"h-4 w-4 mr-1"}),"Export Filtered"]}),(T||q!=="all"||V!=="all"||Q!=="all"||ce!=="all"||ne!=="all")&&e.jsxs($,{variant:"ghost",size:"sm",className:"h-9",onClick:()=>{P(""),W("all"),K("all"),J("all"),ue("all"),ee("all"),I(1)},children:[e.jsx(pr,{className:"h-4 w-4 mr-1"}),"Clear"]}),e.jsxs("div",{className:"flex items-center gap-2 ml-auto",children:[e.jsx("span",{className:"text-sm text-muted-foreground",children:Ty?`Showing all ${lp} members`:`Showing ${Ti+1}-${Math.min(rm,lp)} of ${lp} members`}),e.jsxs(vs,{value:D.toString(),onValueChange:kt=>Yp(Number(kt)),children:[e.jsx(gs,{className:"h-9 w-[110px]",children:e.jsx(bs,{})}),e.jsxs(ys,{children:[e.jsx(Ye,{value:"50",children:"50 / page"}),e.jsx(Ye,{value:"100",children:"100 / page"}),e.jsx(Ye,{value:"250",children:"250 / page"}),e.jsx(Ye,{value:"0",children:"All"})]})]})]})]}),cs.size>0&&e.jsxs("div",{className:"flex flex-col gap-2 p-3 bg-primary/10 border border-primary/20 rounded-lg",children:[mh.length>0&&mh.every(kt=>cs.has(kt.id))&&Lu.length>cs.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 ",cs.size," on this page are selected."]}),e.jsxs($,{size:"sm",variant:"link",className:"h-auto p-0 text-primary",onClick:()=>qt(new Set(Lu.map(kt=>kt.id))),children:["Select all ",Lu.length," filtered members"]})]}),Lu.length>0&&cs.size===Lu.length&&e.jsxs("div",{className:"px-1 text-sm text-muted-foreground",children:["All ",Lu.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(TS,{className:"h-4 w-4 text-primary"}),e.jsxs("span",{className:"text-sm font-medium",children:[cs.size," selected"]})]}),e.jsx("div",{className:"flex-1"}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs($,{size:"sm",variant:"outline",onClick:dp,disabled:Gs,children:[Gs?e.jsx(Ht,{className:"h-4 w-4 animate-spin mr-1"}):e.jsx(nn,{className:"h-4 w-4 mr-1"}),e.jsx("span",{className:"hidden sm:inline",children:"Resend Invite"}),e.jsx("span",{className:"sm:hidden",children:"Invite"})]}),e.jsxs($,{size:"sm",variant:"outline",onClick:om,disabled:Gs,children:[Gs?e.jsx(Ht,{className:"h-4 w-4 animate-spin mr-1"}):e.jsx(Mb,{className:"h-4 w-4 mr-1"}),e.jsx("span",{className:"hidden sm:inline",children:"Password Reset"}),e.jsx("span",{className:"sm:hidden",children:"Reset"})]}),e.jsxs($,{size:"sm",variant:"outline",onClick:()=>he(!0),disabled:Gs,className:"bg-primary/5 border-primary/30 text-primary hover:bg-primary/10",children:[e.jsx(LN,{className:"h-4 w-4 mr-1"}),e.jsx("span",{className:"hidden sm:inline",children:"Send Event Invite"}),e.jsx("span",{className:"sm:hidden",children:"Invite"})]}),e.jsxs($,{size:"sm",variant:"outline",onClick:Ys,children:[e.jsx(di,{className:"h-4 w-4 mr-1"}),e.jsx("span",{className:"hidden sm:inline",children:"Export"}),e.jsx("span",{className:"sm:hidden",children:"CSV"})]}),e.jsxs($,{size:"sm",variant:"destructive",onClick:Rh,disabled:Gs,children:[Gs?e.jsx(Ht,{className:"h-4 w-4 animate-spin mr-1"}):e.jsx(Pn,{className:"h-4 w-4 mr-1"}),e.jsx("span",{className:"hidden sm:inline",children:"Delete"}),e.jsx("span",{className:"sm:hidden",children:"Del"})]}),e.jsx($,{size:"sm",variant:"ghost",onClick:_d,disabled:Gs,children:e.jsx(pr,{className:"h-4 w-4"})})]})]})]}),e.jsx("div",{className:"border rounded-lg bg-card overflow-hidden",children:e.jsxs(Va,{children:[e.jsx(Ha,{children:e.jsxs(hn,{className:"bg-muted/30 hover:bg-muted/30",children:[e.jsx(Lt,{className:"w-[50px]",children:e.jsx(ui,{checked:mh.length>0&&mh.every(kt=>cs.has(kt.id)),onCheckedChange:cp,"aria-label":"Select all on page"})}),e.jsx(Ku,{sortKey:"name",currentSortKey:If,currentDirection:Rg,onSort:ql,children:"Name"}),e.jsx(Ku,{sortKey:"brokerage",currentSortKey:If,currentDirection:Rg,onSort:ql,children:"Brokerage"}),e.jsx(Ku,{sortKey:"status",currentSortKey:If,currentDirection:Rg,onSort:ql,children:"Status"}),e.jsx(Ku,{sortKey:"role",currentSortKey:If,currentDirection:Rg,onSort:ql,children:"Role"}),e.jsx(Ku,{sortKey:"last_login",currentSortKey:If,currentDirection:Rg,onSort:ql,children:"Last Login"}),e.jsx(Ku,{sortKey:"created_at",currentSortKey:If,currentDirection:Rg,onSort:ql,children:"Member Since"}),e.jsx(Lt,{className:"w-[100px]"})]})}),e.jsx(Ga,{children:mh.length===0?e.jsx(hn,{children:e.jsx(gt,{colSpan:8,className:"text-center py-12 text-muted-foreground",children:"No members found"})}):mh.map(kt=>e.jsxs(hn,{className:`hover:bg-muted/30 ${cs.has(kt.id)?"bg-primary/5":""}`,children:[e.jsx(gt,{children:e.jsx(ui,{checked:cs.has(kt.id),onCheckedChange:()=>Oc(kt.id),"aria-label":`Select ${kt.name}`})}),e.jsx(gt,{children:e.jsxs("div",{children:[e.jsx("button",{onClick:()=>mx(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 Cs=kt.trial_expires_at||kt.subscription_end_date;if((kt.is_trial||kt.subscription_status==="trialing")&&Cs){const Rr=Math.ceil((new Date(Cs).getTime()-Date.now())/864e5),Dr=Rr<=0,Aa=Rr<=3;return e.jsx($e,{variant:"outline",className:Tt("w-fit",Dr?"border-destructive text-destructive":Aa?"border-amber-500 text-amber-600":"border-violet-300 text-violet-700 bg-violet-50"),children:Dr?"Trial Expired":`Trial · ${Rr}d left`})}return e.jsx($e,{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")&&is[kt.id]&&e.jsxs("span",{className:"text-xs text-muted-foreground",children:["→ ",is[kt.id].agent_name||is[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($,{size:"icon",variant:"ghost",className:"h-8 w-8 text-yellow-500 hover:text-yellow-600 hover:bg-yellow-50",onClick:()=>{hi(kt),da(!0)},title:"Send celebration",children:e.jsx(Nf,{className:"h-4 w-4"})}),e.jsx($,{size:"icon",variant:"ghost",className:"h-8 w-8",onClick:()=>mx(kt),title:"Edit member",children:e.jsx(Ya,{className:"h-4 w-4"})}),e.jsx($,{size:"icon",variant:"ghost",className:"h-8 w-8",onClick:()=>Wt(kt.id,kt.email),disabled:ma===kt.id,title:"Sync phone with GHL",children:ma===kt.id?e.jsx(Ht,{className:"h-4 w-4 animate-spin"}):e.jsx(ya,{className:"h-4 w-4"})}),e.jsx($,{size:"icon",variant:"ghost",className:"h-8 w-8",onClick:()=>ca(kt.id),title:"Resend welcome email",children:e.jsx(nn,{className:"h-4 w-4"})}),e.jsx($,{size:"icon",variant:"ghost",className:"h-8 w-8",onClick:()=>yo(kt.email,kt.name),title:"Send password reset",children:e.jsx(q3,{className:"h-4 w-4"})}),e.jsx($,{size:"icon",variant:"ghost",className:"h-8 w-8 text-blue-600 hover:text-blue-700 hover:bg-blue-50",onClick:()=>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(Ht,{className:"h-4 w-4 animate-spin"}):e.jsx(yR,{className:"h-4 w-4"})}),e.jsx($,{size:"icon",variant:"ghost",className:"h-8 w-8 text-destructive hover:text-destructive hover:bg-destructive/10",onClick:()=>vo(kt.id,kt.name),title:"Delete user",children:e.jsx(Pn,{className:"h-4 w-4"})})]})})]},kt.id))})]})}),Kd>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 ",Kd]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx($,{variant:"outline",size:"sm",onClick:()=>I(1),disabled:M===1,children:"First"}),e.jsx($,{variant:"outline",size:"icon",className:"h-8 w-8",onClick:()=>I(kt=>Math.max(1,kt-1)),disabled:M===1,children:e.jsx(Ic,{className:"h-4 w-4"})}),e.jsx("div",{className:"flex items-center gap-1",children:Array.from({length:Math.min(5,Kd)},(kt,Cs)=>{let xn;return Kd<=5||M<=3?xn=Cs+1:M>=Kd-2?xn=Kd-4+Cs:xn=M-2+Cs,e.jsx($,{variant:M===xn?"default":"outline",size:"sm",className:"h-8 w-8 p-0",onClick:()=>I(xn),children:xn},xn)})}),e.jsx($,{variant:"outline",size:"icon",className:"h-8 w-8",onClick:()=>I(kt=>Math.min(Kd,kt+1)),disabled:M===Kd,children:e.jsx(Ja,{className:"h-4 w-4"})}),e.jsx($,{variant:"outline",size:"sm",onClick:()=>I(Kd),disabled:M===Kd,children:"Last"})]})]})]}),e.jsx(Os,{open:ke,onOpenChange:Xe,children:e.jsxs(Rs,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsxs(Us,{children:[e.jsx(zs,{children:"Edit Member"}),e.jsx(Sr,{children:"Update member details, roles, and app access"})]}),De&&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(se,{htmlFor:"edit-name",children:"Name"}),e.jsx(be,{id:"edit-name",value:Se.name,onChange:kt=>Re({...Se,name:kt.target.value}),maxLength:100})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"edit-email",children:"Email"}),e.jsx(be,{id:"edit-email",type:"email",value:Se.email,onChange:kt=>Re({...Se,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(se,{htmlFor:"edit-phone",children:"Phone"}),e.jsx(be,{id:"edit-phone",type:"tel",value:Se.phone,onChange:kt=>Re({...Se,phone:kt.target.value}),placeholder:"555-123-4567"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"edit-brokerage",children:"Brokerage"}),e.jsxs(vs,{value:Se.brokerage_id||"none",onValueChange:kt=>Re({...Se,brokerage_id:kt==="none"?"":kt}),children:[e.jsx(gs,{id:"edit-brokerage",children:e.jsx(bs,{placeholder:"Select brokerage"})}),e.jsxs(ys,{children:[e.jsx(Ye,{value:"none",children:"None"}),u.map(kt=>e.jsx(Ye,{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:[De.roles.map(kt=>e.jsxs($e,{variant:"default",className:"gap-1",children:[e.jsx(kf,{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:()=>Xc(De.id,kt,"remove"),className:"ml-1 rounded-full hover:bg-destructive/20",title:"Remove role",children:e.jsx(pr,{className:"h-3 w-3"})})]},kt)),De.roles.length===0&&e.jsx("span",{className:"text-sm text-muted-foreground",children:"No roles assigned"})]}),e.jsxs(vs,{onValueChange:kt=>Xc(De.id,kt,"add"),children:[e.jsx(gs,{className:"w-[200px]",children:e.jsx(bs,{placeholder:"Add role..."})}),e.jsxs(ys,{children:[!De.roles.includes("admin")&&e.jsx(Ye,{value:"admin",children:"Admin"}),!De.roles.includes("user")&&e.jsx(Ye,{value:"user",children:"User"})]})]}),!De.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"})]}),(el.length>0||Ei.length>0||De.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(qn,{className:"h-4 w-4"}),"Assistant Relationships"]}),wo?e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(Ht,{className:"h-4 w-4 animate-spin"}),"Loading..."]}):e.jsxs("div",{className:"space-y-3",children:[el.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:"}),el.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($e,{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(([,Cs])=>Cs).map(([Cs])=>e.jsx($e,{variant:"secondary",className:"text-[10px] capitalize",children:Cs},Cs))})]},kt.id))]}),Ei.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:"}),Ei.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($e,{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(([,Cs])=>Cs).map(([Cs])=>e.jsx($e,{variant:"secondary",className:"text-[10px] capitalize",children:Cs},Cs))})]},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 Cs=uo(De.tags,kt.required_tags),xn=`${De.id}-${kt.id}`,Rr=Ae===xn,Dr=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}),Dr&&e.jsx("span",{className:"text-xs text-muted-foreground",children:"Available to all members"})]})]}),e.jsx("div",{className:"flex items-center gap-2",children:Rr?e.jsx(Ht,{className:"h-4 w-4 animate-spin text-muted-foreground"}):Dr?e.jsx($e,{variant:"secondary",className:"text-xs",children:"Always On"}):e.jsx(Tn,{checked:Cs,onCheckedChange:()=>bo(De.id,kt,Cs)})})]},kt.id)})})]}),(De.is_trial||De.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(Hr,{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:[De.trial_expires_at&&e.jsx(dut,{expiresAt:De.trial_expires_at}),!De.trial_expires_at&&De.subscription_status==="trialing"&&De.subscription_end_date&&e.jsx(dut,{expiresAt:De.subscription_end_date})]}),(De.trial_expires_at||De.subscription_end_date)&&e.jsxs("span",{className:"text-sm text-muted-foreground",children:["Expires: ",new Date(De.trial_expires_at||De.subscription_end_date).toLocaleDateString()]})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs($,{size:"sm",variant:"outline",onClick:()=>am(De.id,7),disabled:ve,children:[e.jsx(gg,{className:"h-4 w-4 mr-1"}),"+7 Days"]}),e.jsxs($,{size:"sm",variant:"outline",onClick:()=>am(De.id,14),disabled:ve,children:[e.jsx(gg,{className:"h-4 w-4 mr-1"}),"+14 Days"]}),e.jsxs($,{size:"sm",variant:"outline",onClick:()=>am(De.id,30),disabled:ve,children:[e.jsx(gg,{className:"h-4 w-4 mr-1"}),"+30 Days"]}),e.jsxs($,{size:"sm",variant:"default",onClick:()=>Og(De.id),disabled:fe,className:"bg-green-600 hover:bg-green-700",children:[e.jsx(Yj,{className:"h-4 w-4 mr-1"}),"Convert to Full Account"]})]}),De.trial_started_at&&e.jsxs("div",{className:"mt-3 text-xs text-muted-foreground",children:["Trial started: ",new Date(De.trial_started_at).toLocaleDateString(),De.trial_claimed_at&&e.jsxs("span",{children:[" • Claimed: ",new Date(De.trial_claimed_at).toLocaleDateString()]})]})]})]}),!(De.is_trial||De.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(Hr,{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($,{size:"sm",variant:"outline",onClick:()=>im(De.id,kt),disabled:Fg,children:[e.jsx(gg,{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:[De.email_confirmed_at&&e.jsxs("div",{children:["Claimed: ",new Date(De.email_confirmed_at).toLocaleString()]}),De.last_sign_in_at&&e.jsxs("div",{children:["Last login: ",new Date(De.last_sign_in_at).toLocaleString()]}),e.jsxs("div",{children:["Created: ",new Date(De.created_at).toLocaleString()]})]})]})]}),e.jsxs(kr,{children:[e.jsx($,{variant:"outline",onClick:P0,children:"Cancel"}),e.jsx($,{onClick:ld,children:"Save Changes"})]})]})}),e.jsxs(Jt,{value:"access",children:[c.length===0?e.jsx(_e,{children:e.jsxs(Oe,{className:"py-12 text-center",children:[e.jsx("p",{className:"text-muted-foreground mb-4",children:"No apps configured yet"}),e.jsx($,{onClick:()=>s("/admin/apps"),children:"Configure Apps"})]})}):e.jsxs(_e,{children:[e.jsxs(Bt,{className:"flex flex-col sm:flex-row sm:items-center justify-between gap-4 space-y-0",children:[e.jsxs("div",{children:[e.jsx(Ut,{children:"Member Access Matrix"}),e.jsx(vr,{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(Vr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(be,{placeholder:"Search agents by name or email...",value:T,onChange:kt=>{P(kt.target.value),I(1)},className:"pl-9"})]})]}),e.jsxs(Oe,{children:[e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b",children:[e.jsx("th",{className:"text-left p-4 font-semibold sticky left-0 bg-card z-10",children:"Member"}),c.map(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:[mh.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(Cs=>{const xn=uo(kt.tags,Cs.required_tags),Rr=`${kt.id}-${Cs.id}`,Dr=Ae===Rr;return e.jsx("td",{className:"p-4 text-center",children:e.jsx("div",{className:"flex items-center justify-center",children:Dr?e.jsx(Ht,{className:"h-5 w-5 animate-spin text-muted-foreground"}):e.jsx(Tn,{checked:xn,onCheckedChange:()=>bo(kt.id,Cs,xn),disabled:Cs.required_tags.length===0})})},Cs.id)})]},kt.id)),mh.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"})})]})]})}),Kd>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 ",Ti+1,"-",Math.min(rm,lp)," of ",lp," • Page ",M," of ",Kd]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx($,{variant:"outline",size:"icon",className:"h-8 w-8",onClick:()=>I(kt=>Math.max(1,kt-1)),disabled:M===1,children:e.jsx(Ic,{className:"h-4 w-4"})}),e.jsx($,{variant:"outline",size:"icon",className:"h-8 w-8",onClick:()=>I(kt=>Math.min(Kd,kt+1)),disabled:M===Kd,children:e.jsx(Ja,{className:"h-4 w-4"})})]})]})]})]}),e.jsx("div",{className:"mt-6",children:e.jsx($,{variant:"outline",onClick:()=>s("/admin/apps"),children:"Manage Apps"})})]}),e.jsxs(Jt,{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(Vr,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(be,{placeholder:"Search brokerages...",value:ms,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(ms.toLowerCase())).length," of ",u.length," brokerages"]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs($,{size:"sm",variant:"outline",onClick:()=>{const kt=[];for(const Ua of u){const sr=m[Ua.id]??[];for(const Ra of sr){const ri=l.find(Ho=>Ho.id===Ra);if(ri){const Ho=(ri.name||"").trim().split(/\s+/),Kl=Ho[0]||"",Hi=Ho.slice(1).join(" ")||"";kt.push({firstName:Kl,lastName:Hi,email:ri.email,brokerageName:Ua.name})}}}if(kt.length===0){i({title:"No managers found to export"});return}const xn=[["First Name","Last Name","Email","Brokerage Name"].join(","),...kt.map(Ua=>[Ua.firstName,Ua.lastName,Ua.email,Ua.brokerageName].map(sr=>`"${(sr||"").replace(/"/g,'""')}"`).join(","))].join(` `),Rr=new Blob([xn],{type:"text/csv"}),Dr=URL.createObjectURL(Rr),Aa=document.createElement("a");Aa.href=Dr,Aa.download=`brokerage-managers-${new Date().toISOString().slice(0,10)}.csv`,Aa.click(),URL.revokeObjectURL(Dr),i({title:`Exported ${kt.length} managers`})},children:[e.jsx(di,{className:"mr-2 h-4 w-4"}),"Export Managers"]}),e.jsxs(Os,{open:qe,onOpenChange:Ke,children:[e.jsx(Ko,{asChild:!0,children:e.jsxs($,{size:"sm",children:[e.jsx(Ai,{className:"mr-2 h-4 w-4"}),"Add Brokerage"]})}),e.jsxs(Rs,{children:[e.jsxs(Us,{children:[e.jsx(zs,{children:"Create New Brokerage"}),e.jsx(Sr,{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(se,{htmlFor:"brokerage-name",children:"Brokerage Name"}),e.jsx(be,{id:"brokerage-name",placeholder:"Enter brokerage name",value:Ze,onChange:kt=>Ue(kt.target.value),maxLength:100})]})}),e.jsxs(kr,{children:[e.jsx($,{variant:"outline",onClick:()=>Ke(!1),children:"Cancel"}),e.jsx($,{onClick:od,disabled:et,children:et?"Creating...":"Create Brokerage"})]})]})]})]})]}),e.jsx("div",{className:"border rounded-lg bg-card overflow-hidden",children:e.jsxs(Va,{children:[e.jsx(Ha,{children:e.jsxs(hn,{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(Ga,{children:(()=>{const kt=u.filter(Cs=>Cs.name.toLowerCase().includes(ms.toLowerCase()));return kt.length===0?e.jsx(hn,{children:e.jsx(gt,{colSpan:4,className:"text-center py-12 text-muted-foreground",children:ms?"No brokerages match your search":"No brokerages found"})}):kt.map(Cs=>{const xn=l.filter(Ua=>Ua.brokerage_id===Cs.id),Dr=(m[Cs.id]??[]).map(Ua=>l.find(sr=>sr.id===Ua)).filter(Boolean),Aa=xn.length;return e.jsxs(hn,{className:"hover:bg-muted/30",children:[e.jsx(gt,{children:e.jsx("button",{onClick:()=>Ju(Cs),className:"text-primary hover:underline font-medium",children:Cs.name})}),e.jsx(gt,{children:Dr.length>0?e.jsx("div",{className:"flex flex-wrap gap-1",children:Dr.map(Ua=>e.jsx($e,{variant:"secondary",className:"text-xs",children:Ua.name},Ua.id))}):e.jsx("span",{className:"text-muted-foreground text-sm",children:"No manager"})}),e.jsxs(gt,{children:[Aa," member",Aa!==1?"s":""]}),e.jsx(gt,{children:e.jsxs("div",{className:"flex gap-1 justify-end",children:[e.jsxs($,{size:"sm",variant:"outline",className:"h-8",onClick:()=>Dg(Cs),children:[e.jsx(qn,{className:"h-4 w-4 mr-1"}),"Manage"]}),e.jsx($,{size:"icon",variant:"ghost",className:"h-8 w-8",onClick:()=>Ju(Cs),title:"Edit brokerage",children:e.jsx(Ya,{className:"h-4 w-4"})}),e.jsx($,{size:"icon",variant:"ghost",className:"h-8 w-8 text-destructive hover:text-destructive hover:bg-destructive/10",onClick:()=>Ay(Cs),title:"Delete brokerage",children:e.jsx(Pn,{className:"h-4 w-4"})})]})})]},Cs.id)})})()})]})}),e.jsx(Os,{open:Ge,onOpenChange:nt,children:e.jsxs(Rs,{className:"max-w-lg",children:[e.jsxs(Us,{children:[e.jsx(zs,{children:"Edit Brokerage"}),e.jsx(Sr,{children:"Update brokerage details and manage managers"})]}),ft&&e.jsxs("div",{className:"space-y-6 py-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"edit-brokerage-name",children:"Brokerage Name"}),e.jsx(be,{id:"edit-brokerage-name",value:Mt,onChange:kt=>Ft(kt.target.value),maxLength:100})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx(se,{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 Cs=(m[ft.id]??[]).map(xn=>l.find(Rr=>Rr.id===xn)).filter(Boolean);return Cs.length===0?e.jsx("span",{className:"text-sm text-muted-foreground",children:"No managers assigned"}):Cs.map(xn=>e.jsxs($e,{variant:"default",className:"gap-1",children:[e.jsx(kf,{className:"h-3 w-3"}),xn.name,e.jsx("button",{onClick:()=>Xc(xn.id,"brokerage_manager","remove",ft.id),className:"ml-1 rounded-full hover:bg-destructive/20",title:"Remove manager from this brokerage",children:e.jsx(pr,{className:"h-3 w-3"})})]},xn.id))})()}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{className:"text-sm text-muted-foreground",children:"Assign manager from existing members:"}),e.jsxs(Sc,{open:pt,onOpenChange:vt,children:[e.jsx(Cc,{asChild:!0,children:e.jsxs($,{variant:"outline",role:"combobox","aria-expanded":pt,className:"w-full justify-between",children:["Search for a member...",e.jsx(Vr,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(xc,{className:"w-full p-0",align:"start",children:e.jsxs(pw,{children:[e.jsx(fw,{placeholder:"Search by name or email..."}),e.jsxs(xw,{className:"max-h-[200px]",children:[e.jsx(gw,{children:"No members found."}),e.jsx($b,{children:(()=>{const kt=new Set(m[ft.id]??[]);return l.filter(Cs=>!kt.has(Cs.id)&&(n||Cs.brokerage_id===ft.id)).map(Cs=>e.jsxs(iv,{value:`${Cs.name} ${Cs.email}`,onSelect:()=>{hx(Cs.id,ft.id),vt(!1)},children:[Cs.name," (",Cs.email,")"]},Cs.id))})()})]})]})})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{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===ft.id).length===0?e.jsx("span",{className:"text-sm text-muted-foreground",children:"No members"}):l.filter(kt=>kt.brokerage_id===ft.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($e,{variant:"outline",className:"text-xs",children:"Manager"})]},kt.id))})]})]}),e.jsxs(kr,{children:[e.jsx($,{variant:"outline",onClick:Ld,children:"Cancel"}),e.jsx($,{onClick:bd,disabled:Ts,children:Ts?"Saving...":"Save Changes"})]})]})}),e.jsx(Os,{open:zt,onOpenChange:Nt,children:e.jsxs(Rs,{children:[e.jsxs(Us,{children:[e.jsx(zs,{className:"text-destructive",children:"Delete Brokerage"}),e.jsxs(Sr,{children:['Are you sure you want to delete "',Ds==null?void 0:Ds.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 "',Ds==null?void 0:Ds.name,'"']}),e.jsxs("li",{children:["All ",l.filter(kt=>kt.brokerage_id===(Ds==null?void 0:Ds.id)).length," member(s) assigned to this brokerage"]}),e.jsx("li",{children:"All their data, roles, and access"})]})]})}),e.jsxs(kr,{children:[e.jsx($,{variant:"outline",onClick:()=>Nt(!1),children:"Cancel"}),e.jsx($,{variant:"destructive",onClick:Kp,disabled:Xs,children:Xs?"Deleting...":"Yes, Delete Brokerage"})]})]})}),e.jsx(Os,{open:Ps,onOpenChange:_n,children:e.jsxs(Rs,{className:"max-w-4xl max-h-[85vh] overflow-hidden flex flex-col",children:[e.jsxs(Us,{children:[e.jsxs(zs,{className:"flex items-center gap-2",children:[e.jsx(Ai,{className:"h-5 w-5"}),"Manage ",Zs==null?void 0:Zs.name]}),e.jsx(Sr,{children:"Add, remove, or manage users in this brokerage"})]}),Zs&&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(Vr,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(be,{placeholder:"Search members...",value:Un,onChange:kt=>In(kt.target.value),className:"pl-10 h-9"})]}),e.jsxs(Os,{open:Ar,onOpenChange:or,children:[e.jsx(Ko,{asChild:!0,children:e.jsxs($,{size:"sm",children:[e.jsx(il,{className:"h-4 w-4 mr-1"}),"Add New Agent"]})}),e.jsxs(Rs,{children:[e.jsxs(Us,{children:[e.jsx(zs,{children:"Add New Agent"}),e.jsxs(Sr,{children:["Create a new agent for ",Zs.name]})]}),e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"agent-name",children:"Name"}),e.jsx(be,{id:"agent-name",placeholder:"John Doe",value:qs.name,onChange:kt=>yr({...qs,name:kt.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"agent-email",children:"Email"}),e.jsx(be,{id:"agent-email",type:"email",placeholder:"john@example.com",value:qs.email,onChange:kt=>yr({...qs,email:kt.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"agent-password",children:"Password"}),e.jsx(be,{id:"agent-password",type:"password",placeholder:"Min 6 characters",value:qs.password,onChange:kt=>yr({...qs,password:kt.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"agent-phone",children:"Phone (optional)"}),e.jsx(be,{id:"agent-phone",type:"tel",placeholder:"555-123-4567",value:qs.phone,onChange:kt=>yr({...qs,phone:kt.target.value})})]}),Xt&&Qn.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs(se,{htmlFor:"agent-package",children:[Xt.name," Package"]}),e.jsxs(vs,{value:$n,onValueChange:tn,children:[e.jsx(gs,{id:"agent-package",children:e.jsx(bs,{placeholder:"Select a package"})}),e.jsxs(ys,{children:[Qn.map(kt=>e.jsx(Ye,{value:kt.id,children:kt.name},kt.id)),e.jsx(Ye,{value:"none",children:"No package (full access)"})]})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:$n==="none"?"Agent gets unrestricted access; welcome email has no package block.":((Ir=Qn.find(kt=>kt.id===$n))==null?void 0:Ir.description)||"Entitlements and the welcome email reflect this package."})]})]}),e.jsxs(kr,{children:[e.jsx($,{variant:"outline",onClick:()=>or(!1),children:"Cancel"}),e.jsx($,{onClick:L0,disabled:fn,children:fn?"Creating...":"Create Agent"})]})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(se,{className:"text-sm text-muted-foreground whitespace-nowrap",children:"Add existing user:"}),e.jsxs(Sc,{open:At,onOpenChange:Zt,children:[e.jsx(Cc,{asChild:!0,children:e.jsxs($,{variant:"outline",role:"combobox","aria-expanded":At,className:"w-[300px] justify-between",children:["Select a user to add...",e.jsx(Vr,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(xc,{className:"w-[300px] p-0",align:"start",children:e.jsxs(pw,{children:[e.jsx(fw,{placeholder:"Search users...",value:as,onValueChange:Ls}),e.jsxs(xw,{children:[e.jsx(gw,{children:"No users found."}),e.jsx($b,{children:Ey(Zs.id).filter(kt=>as===""||kt.name.toLowerCase().includes(as.toLowerCase())||kt.email.toLowerCase().includes(as.toLowerCase())).map(kt=>e.jsxs(iv,{value:`${kt.name} ${kt.email}`,onSelect:()=>{eh(kt.id,Zs.id),Zt(!1),Ls("")},children:[kt.name," (",kt.email,")"]},kt.id))})]})]})})]})]}),e.jsx("div",{className:"flex-1 overflow-auto border rounded-lg",children:e.jsxs(Va,{children:[e.jsx(Ha,{children:e.jsxs(hn,{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(Ga,{children:Zi(Zs.id).length===0?e.jsx(hn,{children:e.jsx(gt,{colSpan:5,className:"text-center py-8 text-muted-foreground",children:Un?"No matching members found":"No members in this brokerage"})}):Zi(Zs.id).map(kt=>e.jsxs(hn,{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($e,{variant:"default",className:"bg-green-500/10 text-green-600 hover:bg-green-500/20",children:"Active"}):e.jsx($e,{variant:"secondary",children:"Pending"})}),e.jsx(gt,{children:kt.roles.includes("brokerage_manager")?e.jsxs($e,{variant:"outline",className:"gap-1",children:[e.jsx(kf,{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($,{size:"icon",variant:"ghost",className:"h-8 w-8",onClick:()=>ca(kt.id),title:"Resend welcome email",children:e.jsx(nn,{className:"h-4 w-4"})}),e.jsx($,{size:"icon",variant:"ghost",className:"h-8 w-8",onClick:()=>Lf(kt.id),title:"Remove from brokerage",children:e.jsx(pr,{className:"h-4 w-4"})}),e.jsx($,{size:"icon",variant:"ghost",className:"h-8 w-8 text-blue-600 hover:text-blue-700 hover:bg-blue-50",onClick:()=>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(Ht,{className:"h-4 w-4 animate-spin"}):e.jsx(yR,{className:"h-4 w-4"})}),e.jsx($,{size:"icon",variant:"ghost",className:"h-8 w-8 text-destructive hover:text-destructive hover:bg-destructive/10",onClick:()=>vo(kt.id,kt.name),title:"Delete user",children:e.jsx(Pn,{className:"h-4 w-4"})})]})})]},kt.id))})]})}),e.jsxs("div",{className:"text-sm text-muted-foreground",children:[jo(Zs.id).length," total member",jo(Zs.id).length!==1?"s":""," •",jo(Zs.id).filter(kt=>kt.roles.includes("brokerage_manager")).length," manager",jo(Zs.id).filter(kt=>kt.roles.includes("brokerage_manager")).length!==1?"s":""]})]}),e.jsx(kr,{children:e.jsx($,{variant:"outline",onClick:Em,children:"Close"})})]})})]}),e.jsx(Jt,{value:"teams",children:e.jsx(tqs,{})}),e.jsx(Jt,{value:"trials",children:e.jsx(BUs,{})}),e.jsx(Jt,{value:"celebrations",children:e.jsx(zUs,{})}),e.jsx(Jt,{value:"deletions",children:e.jsx(UUs,{})})]})]}),e.jsx(u8t,{open:ln,onOpenChange:Cr,brokerages:u,onSuccess:Kn}),va&&e.jsx(h8t,{open:ta,onOpenChange:kt=>{da(kt),kt||hi(null)},userId:va.id,userName:va.name}),e.jsx(sqs,{open:le,onOpenChange:he,recipients:l.filter(kt=>cs.has(kt.id)).map(kt=>({id:kt.id,name:kt.name,email:kt.email}))})]})};function rqs(){const{toast:s}=gi(),t=ts(),[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:x=[],isLoading:g}=ht({queryKey:["unassigned-members"],queryFn:async()=>{const{data:M,error:I}=await U.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=[]}=ht({queryKey:["brokerages-all"],queryFn:async()=>{const{data:M,error:I}=await U.from("brokerages").select("id, name").order("name");if(I)throw I;return M||[]}}),b=j.useMemo(()=>{const M=n.toLowerCase().trim();return M?x.filter(I=>(I.name||"").toLowerCase().includes(M)||(I.email||"").toLowerCase().includes(M)||(I.phone||"").toLowerCase().includes(M)):x},[x,n]),v=j.useMemo(()=>{var I;const M=new Map;for(const D of x){const B=(I=(D.email||"").split("@")[1])==null?void 0:I.toLowerCase();B&&(["gmail.com","yahoo.com","hotmail.com","outlook.com","icloud.com","aol.com","me.com","comcast.net"].includes(B)||M.set(B,(M.get(B)||0)+1))}return Array.from(M.entries()).sort((D,B)=>B[1]-D[1]).slice(0,10)},[x]),N=M=>{i(I=>{const D=new Set(I);return D.has(M)?D.delete(M):D.add(M),D})},C=()=>{a.size===b.length?i(new Set):i(new Set(b.map(M=>M.id)))},A=async(M,I)=>{if(I){d(D=>({...D,[M]:!0}));try{const{data:D,error:B}=await U.functions.invoke("assign-brokerage",{body:{userId:M,brokerageId:I}});if(B)throw B;if(D!=null&&D.error)throw new Error(D.error);s({title:"Assigned",description:"Member added to brokerage."}),t.invalidateQueries({queryKey:["unassigned-members"]}),i(q=>{const W=new Set(q);return W.delete(M),W})}catch(D){s({title:"Failed",description:D.message,variant:"destructive"})}finally{d(D=>({...D,[M]:!1}))}}},T=async()=>{if(!u||a.size===0)return;p(!0);let M=0,I=0;for(const D of a)try{const{data:B,error:q}=await U.functions.invoke("assign-brokerage",{body:{userId:D,brokerageId:u}});if(q||B!=null&&B.error)throw new Error((q==null?void 0:q.message)||B.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"]})},P=(M,I)=>{const D={...l};for(const B of x)(B.email||"").toLowerCase().endsWith(`@${M}`)&&(D[B.id]=I);o(D),s({title:"Suggestions applied",description:`Pre-filled brokerage for @${M}`})};return e.jsx(Ks,{children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(hh,{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(_e,{children:[e.jsx(Bt,{className:"pb-2",children:e.jsxs(Ut,{className:"text-sm font-medium text-muted-foreground flex items-center gap-2",children:[e.jsx(qn,{className:"h-4 w-4"})," Orphan members"]})}),e.jsx(Oe,{children:e.jsx("div",{className:"text-3xl font-bold",children:x.length})})]}),e.jsxs(_e,{children:[e.jsx(Bt,{className:"pb-2",children:e.jsxs(Ut,{className:"text-sm font-medium text-muted-foreground flex items-center gap-2",children:[e.jsx(Ai,{className:"h-4 w-4"})," Selected"]})}),e.jsx(Oe,{children:e.jsx("div",{className:"text-3xl font-bold",children:a.size})})]}),e.jsxs(_e,{children:[e.jsx(Bt,{className:"pb-2",children:e.jsxs(Ut,{className:"text-sm font-medium text-muted-foreground flex items-center gap-2",children:[e.jsx(dn,{className:"h-4 w-4"})," Top email domains"]})}),e.jsx(Oe,{children:e.jsx("div",{className:"text-3xl font-bold",children:v.length})})]})]}),v.length>0&&e.jsxs(_e,{children:[e.jsx(Bt,{children:e.jsx(Ut,{className:"text-base",children:"Domain suggestions"})}),e.jsx(Oe,{children:e.jsx("div",{className:"flex flex-wrap gap-2",children:v.map(([M,I])=>{const D=y.find(B=>B.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($e,{variant:"secondary",children:I}),e.jsxs(vs,{onValueChange:B=>P(M,B),defaultValue:D==null?void 0:D.id,children:[e.jsx(gs,{className:"h-8 w-[220px]",children:e.jsx(bs,{placeholder:"Apply brokerage…"})}),e.jsx(ys,{children:y.map(B=>e.jsx(Ye,{value:B.id,children:B.name},B.id))})]})]},M)})})})]}),e.jsxs(_e,{children:[e.jsxs(Bt,{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(Vr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(be,{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(vs,{value:u,onValueChange:h,children:[e.jsx(gs,{className:"w-[240px]",children:e.jsx(bs,{placeholder:"Bulk assign to brokerage…"})}),e.jsx(ys,{children:y.map(M=>e.jsx(Ye,{value:M.id,children:M.name},M.id))})]}),e.jsxs($,{onClick:T,disabled:!u||a.size===0||m,children:[m&&e.jsx(Ht,{className:"h-4 w-4 mr-2 animate-spin"}),"Assign ",a.size||""]})]})]}),e.jsx(Oe,{children:g?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx(Ht,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):b.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(Va,{children:[e.jsx(Ha,{children:e.jsxs(hn,{children:[e.jsx(Lt,{className:"w-10",children:e.jsx(ui,{checked:a.size===b.length&&b.length>0,onCheckedChange:C})}),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(Ga,{children:b.map(M=>{const I=l[M.id]||"";return e.jsxs(hn,{children:[e.jsx(gt,{children:e.jsx(ui,{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:fc(new Date(M.created_at),{addSuffix:!0})}),e.jsx(gt,{children:e.jsx($e,{variant:"outline",children:M.subscription_status||"none"})}),e.jsx(gt,{children:e.jsxs(vs,{value:I,onValueChange:D=>o(B=>({...B,[M.id]:D})),children:[e.jsx(gs,{className:"h-9 w-[240px]",children:e.jsx(bs,{placeholder:"Pick brokerage…"})}),e.jsx(ys,{children:y.map(D=>e.jsx(Ye,{value:D.id,children:D.name},D.id))})]})}),e.jsx(gt,{children:e.jsx($,{size:"sm",disabled:!I||c[M.id],onClick:()=>A(M.id,I),children:c[M.id]?e.jsx(Ht,{className:"h-4 w-4 animate-spin"}):"Assign"})})]},M.id)})})]})})})]})]})})}const aqs=()=>{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(()=>{x()},[]);const x=async()=>{const{data:A,error:T}=await U.from("invite_codes").select("*").order("created_at",{ascending:!1});T?(ae.error("Failed to load invite codes"),console.error(T)):t(A||[]),r(!1)},g=async A=>{if(A.preventDefault(),!l.trim()){ae.error("Please enter a code");return}i(!0);const{error:T}=await U.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"?ae.error("This code already exists"):(ae.error("Failed to create invite code"),console.error(T)):(ae.success("Invite code created"),o(""),d(""),h(""),p(""),x()),i(!1)},y=async(A,T)=>{const{error:P}=await U.from("invite_codes").update({is_active:!T}).eq("id",A);P?ae.error("Failed to update code"):t(s.map(M=>M.id===A?{...M,is_active:!T}:M))},b=async A=>{const{error:T}=await U.from("invite_codes").delete().eq("id",A);T?ae.error("Failed to delete code"):(ae.success("Code deleted"),t(s.filter(P=>P.id!==A)))},v="https://dashboard.relevelup.com",N=A=>{const T=`${v}/join?code=${A}`;navigator.clipboard.writeText(T),ae.success("Link copied to clipboard")},C=`${v}/join`;return e.jsx(Ks,{title:"Invite Codes",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(hh,{title:"Invite Codes",description:"Manage signup invite codes"}),e.jsxs(_e,{children:[e.jsxs(Bt,{children:[e.jsx(Ut,{children:"Create New Code"}),e.jsxs(vr,{children:["Share link: ",e.jsx("code",{className:"bg-muted px-2 py-1 rounded text-sm",children:C})]})]}),e.jsx(Oe,{children:e.jsxs("form",{onSubmit:g,className:"flex flex-wrap gap-4 items-end",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"code",children:"Code"}),e.jsx(be,{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(se,{htmlFor:"description",children:"Description (optional)"}),e.jsx(be,{id:"description",placeholder:"For marketing campaign",value:c,onChange:A=>d(A.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"maxUses",children:"Max Uses"}),e.jsx(be,{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(se,{htmlFor:"trialDays",children:"Trial Days"}),e.jsx(be,{id:"trialDays",type:"number",placeholder:"None",value:m,onChange:A=>p(A.target.value),className:"w-28"})]}),e.jsxs($,{type:"submit",disabled:a,children:[a?e.jsx(Ht,{className:"h-4 w-4 animate-spin"}):e.jsx(sn,{className:"h-4 w-4 mr-2"}),"Create"]})]})})]}),e.jsxs(_e,{children:[e.jsx(Bt,{children:e.jsx(Ut,{children:"Active Codes"})}),e.jsx(Oe,{children:n?e.jsx("div",{className:"flex justify-center py-8",children:e.jsx(Ht,{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(Va,{children:[e.jsx(Ha,{children:e.jsxs(hn,{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(Ga,{children:s.map(A=>e.jsxs(hn,{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:Hs(new Date(A.created_at),"MMM d, yyyy")}),e.jsx(gt,{children:e.jsx(Tn,{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($,{variant:"ghost",size:"icon",onClick:()=>N(A.code),title:"Copy invite link",children:e.jsx(Ca,{className:"h-4 w-4"})}),e.jsx($,{variant:"ghost",size:"icon",onClick:()=>b(A.id),className:"text-destructive hover:text-destructive",title:"Delete code",children:e.jsx(Pn,{className:"h-4 w-4"})})]})})]},A.id))})]})})]})]})})},D3=U;function fQn(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 iqs(s){return s.toLowerCase().replace(/[^a-z0-9\s-]/g,"").trim().replace(/\s+/g,"-").slice(0,70)}const oqs="https://dashboard.relevelup.com";function xQn(s,t){const r=`${typeof window<"u"&&window.location.hostname==="localhost"?window.location.origin:oqs}/live/${s}`;return t?`${r}?i=${t}`:r}function gQn(){const s=ts(),t=ht({queryKey:["live-events"],queryFn:async()=>{const{data:i,error:l}=await D3.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 U.auth.getUser(),{data:o,error:c}=await D3.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"]}),ae.success("Live event created")},onError:i=>ae.error((i==null?void 0:i.message)||"Could not create event")}),r=yt({mutationFn:async({id:i,...l})=>{const{error:o}=await D3.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]}),ae.success("Saved")},onError:i=>ae.error((i==null?void 0:i.message)||"Could not save")}),a=yt({mutationFn:async i=>{const{error:l}=await D3.from("live_events").delete().eq("id",i);if(l)throw l},onSuccess:()=>{s.invalidateQueries({queryKey:["live-events"]}),ae.success("Event deleted")},onError:i=>ae.error((i==null?void 0:i.message)||"Could not delete")});return{list:t,create:n,update:r,remove:a}}function yQn(s){return ht({queryKey:["live-event",s],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await D3.from("live_events").select("*").eq("id",s).maybeSingle();if(n)throw n;return t}})}function vQn(s){return ht({queryKey:["live-registrations",s],enabled:!!s,refetchInterval:2e4,queryFn:async()=>{const{data:t,error:n}=await D3.from("live_registrations").select("*").eq("event_id",s).order("created_at",{ascending:!1});if(n)throw n;return t||[]}})}function bQn(s){const t=ts(),n=ht({queryKey:["live-invites",s],enabled:!!s,queryFn:async()=>{const{data:i,error:l}=await D3.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 U.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 D3.from("live_invites").insert(o).select();if(d)throw d;return c||[]},onSuccess:i=>{t.invalidateQueries({queryKey:["live-invites",s]}),ae.success(`${i.length} invite link${i.length===1?"":"s"} created`)},onError:i=>ae.error((i==null?void 0:i.message)||"Could not create invites")}),a=yt({mutationFn:async i=>{const{error:l}=await D3.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 Dee=async s=>{try{const{data:t,error:n}=await U.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}},Bq=async s=>{try{const{data:t,error:n}=await U.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}}},lqs=async(s,t)=>await Dee("new_templates")?Bq({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}),cqs=async(s,t)=>Bq({title:"New Academy Video",body:`New video added: ${s}`,url:`/academy/${t}`}),dqs=async(s,t)=>await Dee("new_events")?Bq({title:"New Event",body:`New event: ${s}`,url:`/events/${t}`}):(console.log("New event notifications are disabled"),{success:!1,skipped:!0}),uqs=async(s,t)=>await Dee("new_toolbox")?Bq({title:"New Resource Kit",body:`New resource kit available: ${s}`,url:`/toolbox/${t}`}):(console.log("New toolbox notifications are disabled"),{success:!1,skipped:!0}),h9e=async(s,t)=>await Dee("new_social_swag")?Bq({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}),hqs=async(s,t)=>await Dee("new_newsletters")?Bq({title:"New Newsletter",body:`New newsletter available: ${s}`,url:`/newsletters/${t}`}):(console.log("New newsletter notifications are disabled"),{success:!1,skipped:!0}),NIe=400;function mqs(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 pqs(){const s=[];let t=0;const n=1e3;for(;;){const{data:r,error:a}=await U.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 Q=!1;return(async()=>{h(!0);try{const[J,ce,ue]=await Promise.all([pqs(),mut("event_registrations",n.id),mut("event_attendees",n.id)]);if(Q)return;p(J),g(ce),b(ue)}catch(J){Q||r({title:"Could not load audience",description:J instanceof Error?J.message:"Unknown error",variant:"destructive"})}finally{Q||h(!1)}})(),()=>{Q=!0}},[s,n,r]),j.useEffect(()=>{s||(A(null),d(""),o(""),i("not_registered"))},[s]);const D=j.useMemo(()=>a==="all"?m:a==="not_registered"?m.filter(Q=>!x.has(Q.id)):m.filter(Q=>x.has(Q.id)&&!y.has(Q.id)),[a,m,x,y]),B={all:m.length,not_registered:m.filter(Q=>!x.has(Q.id)).length,registered_never_attended:m.filter(Q=>x.has(Q.id)&&!y.has(Q.id)).length},q=async(Q,J=!1)=>{const{data:{session:ce}}=await U.auth.getSession(),ue=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/admin-send-event-invite",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${ce==null?void 0:ce.access_token}`},body:JSON.stringify({event_id:n.id,recipients:Q.map(ee=>({email:ee.email,name:ee.name,user_id:ee.id})),custom_subject:l.trim()||void 0,custom_intro:c.trim()||void 0,force_resend:J||void 0})}),ne=await ue.json().catch(()=>({}));if(!ue.ok)throw new Error((ne==null?void 0:ne.error)||`HTTP ${ue.status}`);return{sent:(ne==null?void 0:ne.sent)??0,failed:(ne==null?void 0:ne.failed)??0,alreadyInvited:(ne==null?void 0:ne.already_invited)??0}},W=async()=>{var Q;if(n){I(!0);try{const{data:{session:J}}=await U.auth.getSession(),ce=J==null?void 0:J.user;if(!(ce!=null&&ce.email))throw new Error("No signed-in email found");const ue=await q([{id:ce.id,name:((Q=ce.user_metadata)==null?void 0:Q.name)||"",email:ce.email}],!0);r({title:"Test sent",description:`Sent to ${ce.email} · Sent: ${ue.sent} · Failed: ${ue.failed}`})}catch(J){r({title:"Test failed",description:J instanceof Error?J.message:"Unknown error",variant:"destructive"})}finally{I(!1)}}},V=async()=>{if(!(!n||D.length===0)){P(!1),N(!0),A({done:0,total:D.length,sent:0,failed:0});try{let Q=0,J=0,ce=0;for(let ue=0;ue!v&&t(Q),children:e.jsxs(Rs,{className:"max-w-2xl max-h-[92vh] overflow-y-auto",children:[e.jsxs(Us,{children:[e.jsxs(zs,{className:"flex items-center gap-2",children:[e.jsx(dn,{className:"h-5 w-5 text-primary"}),"Invite Members to Event"]}),e.jsx(Sr,{children:n?e.jsxs("span",{className:"flex items-center gap-2 text-sm",children:[e.jsx(Xu,{className:"h-4 w-4"}),e.jsx("span",{className:"font-medium text-foreground",children:n.title}),e.jsx("span",{children:"·"}),e.jsx("span",{children:mqs(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(se,{className:"flex items-center gap-2",children:[e.jsx(qn,{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(Ht,{className:"h-4 w-4 animate-spin"})," Loading members..."]}):e.jsxs(wb,{value:a,onValueChange:Q=>i(Q),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(rh,{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:B.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(rh,{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:B.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(rh,{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:B.registered_never_attended.toLocaleString()})]})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{htmlFor:"ev-inv-subject",children:"Subject line (optional)"}),e.jsx(be,{id:"ev-inv-subject",placeholder:n?`You're invited: ${n.title}`:"You're invited to...",value:l,onChange:Q=>o(Q.target.value),disabled:v}),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(se,{htmlFor:"ev-inv-intro",children:"Personal message (optional)"}),e.jsx(Is,{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:Q=>d(Q.target.value),rows:4,disabled:v}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Appears at the top of the email above the event details."})]}),C&&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 ",C.done.toLocaleString()," / ",C.total.toLocaleString()]}),e.jsxs("span",{className:"font-medium",children:["✓ ",C.sent.toLocaleString(),C.failed>0&&e.jsxs("span",{className:"text-destructive",children:[" · ✗ ",C.failed.toLocaleString()]})]})]}),e.jsx(Ki,{value:K})]})]}),e.jsxs(kr,{className:"gap-2 sm:gap-2",children:[e.jsx($,{variant:"outline",onClick:W,disabled:v||M||u,children:M?e.jsxs(e.Fragment,{children:[e.jsx(Ht,{className:"h-4 w-4 mr-2 animate-spin"})," Sending test..."]}):e.jsxs(e.Fragment,{children:[e.jsx(nn,{className:"h-4 w-4 mr-2"})," Send test to me"]})}),e.jsx($,{variant:"ghost",onClick:()=>t(!1),disabled:v,children:"Cancel"}),e.jsx($,{onClick:()=>P(!0),disabled:v||u||D.length===0,children:v?e.jsxs(e.Fragment,{children:[e.jsx(Ht,{className:"h-4 w-4 mr-2 animate-spin"})," Sending..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Br,{className:"h-4 w-4 mr-2"})," Send to ",D.length.toLocaleString()]})})]})]})}),e.jsx(Ll,{open:T,onOpenChange:P,children:e.jsxs(yl,{children:[e.jsxs(vl,{children:[e.jsx(_l,{children:"Send event invite?"}),e.jsxs(wl,{children:["This will send a branded invite to"," ",e.jsxs("span",{className:"font-semibold text-foreground",children:[D.length.toLocaleString()," member",D.length===1?"":"s"]})," ","for"," ",e.jsxs("span",{className:"font-semibold text-foreground",children:['"',n==null?void 0:n.title,'"']}),". This can't be undone."]})]}),e.jsxs(bl,{children:[e.jsx(jl,{children:"Cancel"}),e.jsxs(fl,{onClick:V,children:[e.jsx(Br,{className:"h-4 w-4 mr-2"})," Send now"]})]})]})})]})}const xre={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 xqs(){const s=Vn(),t=ts(),[n,r]=j.useState(!1),[a,i]=j.useState(null),[l,o]=j.useState(xre),[c,d]=j.useState(null),[u,h]=j.useState(null),[m,p]=j.useState(!1),x=j.useRef(null),[g,y]=j.useState(!1),[b,v]=j.useState(null),[N,C]=j.useState(!1),[A,T]=j.useState(null),[P,M]=j.useState(null),[I,D]=j.useState(!0),[B,q]=j.useState(""),[W,V]=j.useState(!1),[K,Q]=j.useState(null),{data:J,isLoading:ce}=ht({queryKey:["admin-events"],queryFn:async()=>{const{data:Ge,error:nt}=await U.from("events").select("*").order("event_date",{ascending:!0});if(nt)throw nt;return Ge}}),{data:ue}=ht({queryKey:["event-registrations-count"],queryFn:async()=>{let Ge=[],nt=0;const ft=1e3;for(;;){const{data:Mt,error:Ft}=await U.from("event_registrations").select("event_id").range(nt,nt+ft-1);if(Ft)throw Ft;if(!Mt||Mt.length===0||(Ge=Ge.concat(Mt),Mt.length{lt[Mt.event_id]=(lt[Mt.event_id]||0)+1}),lt}}),{data:ne,isLoading:ee}=ht({queryKey:["event-registrations-details",b==null?void 0:b.id],queryFn:async()=>{if(!b)return[];const{data:Ge,error:nt}=await U.from("event_registrations").select("id, user_id, registered_at, zoom_join_url, zoom_name, zoom_email").eq("event_id",b.id).order("registered_at",{ascending:!1});if(nt)throw nt;if(!Ge||Ge.length===0)return[];const ft=Ge.map(Ft=>Ft.user_id).filter(Boolean);let lt=[];if(ft.length>0){const{data:Ft,error:Ts}=await U.from("profiles").select("id, name, email").in("id",ft);if(Ts)throw Ts;lt=Ft||[]}const Mt=new Map((lt==null?void 0:lt.map(Ft=>[Ft.id,Ft]))||[]);return Ge.map(Ft=>({...Ft,profiles:Ft.user_id&&Mt.get(Ft.user_id)||null}))},enabled:!!b}),{data:le,isLoading:he}=ht({queryKey:["event-attendees-details",b==null?void 0:b.id],queryFn:async()=>{if(!b)return[];const{data:Ge,error:nt}=await U.from("event_attendees").select("id, user_id, zoom_email, zoom_name, join_time, leave_time, duration_minutes, manually_added, created_at").eq("event_id",b.id).order("created_at",{ascending:!1});if(nt)throw nt;if(!Ge||Ge.length===0)return[];const ft=Ge.map(js=>js.user_id).filter(Boolean);let lt=[];if(ft.length>0){const{data:js,error:zt}=await U.from("profiles").select("id, name, email").in("id",ft);if(zt)throw zt;lt=js||[]}const{data:Mt}=await U.from("agent_points").select("user_id").eq("event_id",b.id),Ft=new Set((Mt==null?void 0:Mt.map(js=>js.user_id))||[]),Ts=new Map((lt==null?void 0:lt.map(js=>[js.id,js]))||[]);return Ge.map(js=>({...js,profiles:js.user_id&&Ts.get(js.user_id)||null,points_awarded:js.user_id?Ft.has(js.user_id):!1}))},enabled:!!b}),ve=Ge=>{v(Ge),y(!0)},ge=yt({mutationFn:async Ge=>{const{data:{session:nt}}=await U.auth.getSession();if(!nt)throw new Error("Not authenticated");const ft=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/zoom-sync-registrations",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${nt.access_token}`},body:JSON.stringify({event_id:Ge})}),lt=await ft.json();if(!ft.ok){const Mt=new Error(lt.error||"Failed to sync");throw Mt.scopeError=!!lt.scope_error,Mt.details=lt.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,Mt}return lt},onSuccess:Ge=>{if(t.invalidateQueries({queryKey:["event-registrations-details",b==null?void 0:b.id]}),t.invalidateQueries({queryKey:["event-registrations-count"]}),Ge!=null&&Ge.scope_error||(Ge==null?void 0:Ge.success)===!1){ae.error("Zoom needs one more authorization step",{description:Ge!=null&&Ge.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.":(Ge==null?void 0:Ge.message)||"Zoom registration sync could not complete.",duration:2e4});return}ae.success(Ge.message)},onError:Ge=>{ae.error("Failed to sync Zoom registrations",{description:Ge.scopeError&&Ge.details||Ge.message,duration:Ge.scopeError?2e4:5e3})}}),fe=yt({mutationFn:async Ge=>{const{data:{session:nt}}=await U.auth.getSession();if(!nt)throw new Error("Not authenticated");const ft=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/zoom-sync-attendees",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${nt.access_token}`},body:JSON.stringify({event_id:Ge})}),lt=await ft.json();if(!ft.ok)throw new Error(lt.error||"Failed to sync attendees");return lt},onSuccess:Ge=>{if(t.invalidateQueries({queryKey:["event-attendees-details",b==null?void 0:b.id]}),t.invalidateQueries({queryKey:["event-leaderboard"]}),t.invalidateQueries({queryKey:["admin-agent-points"]}),Ge!=null&&Ge.scope_error||(Ge==null?void 0:Ge.success)===!1){ae.error((Ge==null?void 0:Ge.message)||"Zoom sync failed",{description:Ge!=null&&Ge.scope_error?"Zoom must be re-authorized after adding the missing report scope.":void 0,duration:15e3});return}Ge!=null&&Ge.message?ae.success(Ge.message):ae.success(`Synced ${Ge.synced||0} attendees. ${Ge.points_awarded||0} points awarded!`)},onError:Ge=>{ae.error("Failed to sync attendees: "+Ge.message)}}),je=yt({mutationFn:async()=>{const{data:Ge,error:nt}=await U.functions.invoke("zoom-retry-registrations",{body:{}});if(nt)throw nt;return Ge},onSuccess:Ge=>{t.invalidateQueries({queryKey:["event-registrations-details",b==null?void 0:b.id]}),t.invalidateQueries({queryKey:["event-registrations-count"]}),ae.success(`Retry complete: ${(Ge==null?void 0:Ge.successCount)??0} fixed, ${(Ge==null?void 0:Ge.failCount)??0} still failing, ${(Ge==null?void 0:Ge.rateLimitedCount)??0} rate-limited`)},onError:Ge=>{ae.error("Retry failed: "+Ge.message)}}),Ee=yt({mutationFn:async({eventId:Ge,testMode:nt})=>{const{data:{session:ft}}=await U.auth.getSession();if(!ft)throw new Error("Not authenticated");const lt=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/send-event-reminder",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${ft.access_token}`},body:JSON.stringify({event_id:Ge,test_mode:nt})}),Mt=await lt.json();if(!lt.ok)throw new Error(Mt.error||"Failed to send reminders");return Mt},onSuccess:Ge=>{Ge.test?ae.success(Ge.message||"Test email sent!"):ae.success(Ge.message||`Reminder emails sent to ${Ge.sent} registrants!`)},onError:Ge=>{ae.error("Failed to send reminders: "+Ge.message)}}),{data:Me}=ht({queryKey:["all-profiles-for-linking"],queryFn:async()=>{let Ge=[],nt=0;const ft=1e3;for(;;){const{data:lt,error:Mt}=await U.from("profiles").select("id, name, email").order("name",{ascending:!0}).range(nt,nt+ft-1);if(Mt)throw Mt;if(!lt||lt.length===0||(Ge=[...Ge,...lt],lt.length{const{error:Mt}=await U.from("event_attendees").update({user_id:nt}).eq("id",Ge);if(Mt)throw Mt;if(lt&&ft){const{error:Ts}=await U.from("zoom_email_aliases").upsert({user_id:nt,zoom_email:ft.toLowerCase()},{onConflict:"zoom_email"});Ts&&console.error("Failed to save alias:",Ts)}const Ft=b==null?void 0:b.id;if(Ft){const{data:Ts}=await U.from("user_roles").select("id").eq("user_id",nt).eq("role","admin").single();if(!Ts){const{data:js}=await U.from("agent_points").select("id").eq("user_id",nt).eq("event_id",Ft).single();js||(await U.rpc("award_attendance_points",{p_user_id:nt,p_event_id:Ft,p_points:10,p_reason:"Event Attendance (Manual Link)"}),await U.rpc("check_and_award_badges",{p_user_id:nt}))}}return{userId:nt,zoomEmail:ft,shouldSaveAlias:lt}},onSuccess:Ge=>{t.invalidateQueries({queryKey:["event-attendees-details",b==null?void 0:b.id]}),t.invalidateQueries({queryKey:["event-leaderboard"]}),t.invalidateQueries({queryKey:["admin-agent-points"]});let nt="Attendee linked and points awarded!";Ge.shouldSaveAlias&&Ge.zoomEmail&&(nt+=` Email "${Ge.zoomEmail}" will be auto-matched in the future.`),ae.success(nt),C(!1),T(null),M(null),q("")},onError:Ge=>{ae.error("Failed to link attendee: "+Ge.message)}}),ze=Ge=>{T(Ge),M(null),D(!0),q(""),C(!0)},ke=()=>{!A||!P||De.mutate({attendeeId:A.id,userId:P,zoomEmail:A.zoom_email,shouldSaveAlias:I})},Xe=(Me==null?void 0:Me.filter(Ge=>{var ft,lt;if(!B)return!0;const nt=B.toLowerCase();return((ft=Ge.name)==null?void 0:ft.toLowerCase().includes(nt))||((lt=Ge.email)==null?void 0:lt.toLowerCase().includes(nt))}))||[],Se=async Ge=>{const nt=Ge.name.split(".").pop(),lt=`${`${crypto.randomUUID()}.${nt}`}`,{error:Mt}=await U.storage.from("event-images").upload(lt,Ge);if(Mt)throw Mt;const{data:{publicUrl:Ft}}=U.storage.from("event-images").getPublicUrl(lt);return Ft},Re=Ge=>{var ft;const nt=(ft=Ge.target.files)==null?void 0:ft[0];if(nt){if(nt.size>5*1024*1024){ae.error("Image must be less than 5MB");return}d(nt),h(URL.createObjectURL(nt))}},Ae=()=>{d(null),h(null),o({...l,image_url:""}),x.current&&(x.current.value="")},Be=yt({mutationFn:async Ge=>{p(!0);let nt=Ge.image_url;c&&(nt=await Se(c)||"");const ft=new Date(Ge.event_date),[lt,Mt]=Ge.event_time.split(":");ft.setHours(parseInt(lt),parseInt(Mt));const Ft=[new Date(ft)];if(Ge.is_recurring&&Ge.recurrence_end_date){let Nt=new Date(ft);for(;Ge.recurrence_pattern==="weekly"?Nt=P3(Nt,1):Ge.recurrence_pattern==="biweekly"?Nt=P3(Nt,2):Nt=zx(Nt,1),!(Nt>Ge.recurrence_end_date);)Ft.push(new Date(Nt))}const Ts=Ft.map(Nt=>({title:Ge.title,description:Ge.description||null,image_url:nt||null,video_url:Ge.video_url||null,event_date:Nt.toISOString(),zoom_link:Ge.zoom_link,zoom_meeting_id:Ge.zoom_meeting_id||null,capacity:Ge.capacity?parseInt(Ge.capacity):null,is_published:Ge.is_published})),{data:js,error:zt}=await U.from("events").insert(Ts).select();if(zt)throw zt;return js&&js.length>0&&dqs(Ge.title,js[0].id),Ft.length},onSuccess:Ge=>{t.invalidateQueries({queryKey:["admin-events"]}),ae.success(Ge>1?`${Ge} recurring events created successfully`:"Event created successfully"),r(!1),o(xre),d(null),h(null),p(!1)},onError:Ge=>{ae.error("Failed to create event: "+Ge.message),p(!1)}}),qe=yt({mutationFn:async({id:Ge,data:nt})=>{p(!0);let ft=nt.image_url;c&&(ft=await Se(c)||"");const lt=new Date(nt.event_date),[Mt,Ft]=nt.event_time.split(":");lt.setHours(parseInt(Mt),parseInt(Ft));const{error:Ts}=await U.from("events").update({title:nt.title,description:nt.description||null,image_url:ft||null,video_url:nt.video_url||null,event_date:lt.toISOString(),zoom_link:nt.zoom_link,zoom_meeting_id:nt.zoom_meeting_id||null,capacity:nt.capacity?parseInt(nt.capacity):null,is_published:nt.is_published}).eq("id",Ge);if(Ts)throw Ts},onSuccess:()=>{t.invalidateQueries({queryKey:["admin-events"]}),ae.success("Event updated successfully"),r(!1),i(null),o(xre),d(null),h(null),p(!1)},onError:Ge=>{ae.error("Failed to update event: "+Ge.message),p(!1)}}),Ke=yt({mutationFn:async Ge=>{const{error:nt}=await U.from("events").delete().eq("id",Ge);if(nt)throw nt},onSuccess:()=>{t.invalidateQueries({queryKey:["admin-events"]}),ae.success("Event deleted successfully")},onError:Ge=>{ae.error("Failed to delete event: "+Ge.message)}}),Ze=yt({mutationFn:async Ge=>{var Nt;const{data:nt}=await U.auth.getUser(),ft=new Date(Ge.event_date),lt=new Date(ft.getTime()+60*60*1e3),Mt=iqs(Ge.title),Ft=Math.random().toString(36).slice(2,7),Ts=`${Mt}-${Ft}`,{data:js,error:zt}=await U.from("live_events").insert({slug:Ts,title:Ge.title,description:Ge.description||null,hero_image_url:Ge.image_url||null,starts_at:Ge.event_date,ends_at:lt.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:Ge.zoom_meeting_id||null,cta_label:"Join the training",cta_url:Ge.zoom_link||"https://dashboard.relevelup.com/trial",created_by:(Nt=nt.user)==null?void 0:Nt.id,agenda:[],offer_bullets:[]}).select().single();if(zt)throw zt;return js},onSuccess:Ge=>{t.invalidateQueries({queryKey:["live-events"]}),ae.success("Cloned to LevelUp Live — configure stream next"),s(`/admin/live/${Ge.id}`)},onError:Ge=>{ae.error("Failed to clone to LevelUp Live: "+Ge.message)}}),Ue=Ge=>{var ft;const nt=new Date(Ge.event_date);i(Ge),o({title:Ge.title,description:Ge.description||"",image_url:Ge.image_url||"",video_url:Ge.video_url||"",event_date:nt,event_time:Hs(nt,"HH:mm"),zoom_link:Ge.zoom_link,zoom_meeting_id:Ge.zoom_meeting_id||"",capacity:((ft=Ge.capacity)==null?void 0:ft.toString())||"",is_published:Ge.is_published,is_recurring:!1,recurrence_pattern:"weekly",recurrence_end_date:void 0}),h(Ge.image_url||null),d(null),r(!0)},et=Ge=>{if(Ge.preventDefault(),!l.event_date){ae.error("Please select a date");return}if(l.is_recurring&&!l.recurrence_end_date){ae.error("Please select an end date for recurring events");return}a?qe.mutate({id:a.id,data:l}):Be.mutate(l)},Qe=()=>{r(!1),i(null),o(xre),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(hh,{title:"Event Management",description:"Create and manage upcoming events"}),e.jsxs(_e,{className:"mb-6",children:[e.jsxs(Bt,{className:"flex flex-row items-center justify-between",children:[e.jsx(Ut,{children:"All Events"}),e.jsxs(Os,{open:n,onOpenChange:Ge=>!Ge&&Qe(),children:[e.jsx(Ko,{asChild:!0,children:e.jsxs($,{onClick:()=>r(!0),children:[e.jsx(sn,{className:"h-4 w-4 mr-2"}),"Add Event"]})}),e.jsxs(Rs,{className:"max-w-lg max-h-[90vh] overflow-y-auto",children:[e.jsx(Us,{children:e.jsx(zs,{children:a?"Edit Event":"Create New Event"})}),e.jsxs("form",{onSubmit:et,className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"title",children:"Title *"}),e.jsx(be,{id:"title",value:l.title,onChange:Ge=>o({...l,title:Ge.target.value}),placeholder:"Event title",required:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Description"}),e.jsx(m2,{content:l.description,onChange:Ge=>o({...l,description:Ge}),placeholder:"Event description",minHeight:"120px"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Event Image"}),e.jsx("input",{type:"file",ref:x,accept:"image/*",onChange:Re,className:"hidden"}),u?e.jsxs("div",{className:"relative",children:[e.jsx("img",{src:u,alt:"Event preview",className:"w-full h-32 object-cover rounded-lg border"}),e.jsx($,{type:"button",variant:"destructive",size:"icon",className:"absolute top-2 right-2 h-6 w-6",onClick:Ae,children:e.jsx(pr,{className:"h-4 w-4"})})]}):e.jsxs($,{type:"button",variant:"outline",className:"w-full h-32 border-dashed flex flex-col gap-2",onClick:()=>{var Ge;return(Ge=x.current)==null?void 0:Ge.click()},children:[e.jsx(si,{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(se,{children:"Date *"}),e.jsxs(Sc,{children:[e.jsx(Cc,{asChild:!0,children:e.jsxs($,{variant:"outline",className:Tt("w-full justify-start text-left font-normal",!l.event_date&&"text-muted-foreground"),children:[e.jsx(ia,{className:"mr-2 h-4 w-4"}),l.event_date?Hs(l.event_date,"PPP"):"Pick a date"]})}),e.jsx(xc,{className:"w-auto p-0",align:"start",children:e.jsx(y1,{mode:"single",selected:l.event_date,onSelect:Ge=>o({...l,event_date:Ge}),initialFocus:!0,className:"p-3 pointer-events-auto"})})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"time",children:"Time *"}),e.jsx(be,{id:"time",type:"time",value:l.event_time,onChange:Ge=>o({...l,event_time:Ge.target.value}),required:!0})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"zoom_link",children:"Zoom Link *"}),e.jsx(be,{id:"zoom_link",value:l.zoom_link,onChange:Ge=>o({...l,zoom_link:Ge.target.value}),placeholder:"https://zoom.us/j/...",required:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"zoom_meeting_id",children:"Zoom Meeting ID (for API registration)"}),e.jsx(be,{id:"zoom_meeting_id",value:l.zoom_meeting_id,onChange:Ge=>o({...l,zoom_meeting_id:Ge.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(se,{htmlFor:"video_url",children:"Promo Video URL (optional)"}),e.jsx(be,{id:"video_url",value:l.video_url,onChange:Ge=>o({...l,video_url:Ge.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(se,{htmlFor:"capacity",children:"Capacity (optional)"}),e.jsx(be,{id:"capacity",type:"number",value:l.capacity,onChange:Ge=>o({...l,capacity:Ge.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(Oz,{className:"h-4 w-4 text-muted-foreground"}),e.jsx(se,{htmlFor:"is_recurring",children:"Recurring Event"})]}),e.jsx(Tn,{id:"is_recurring",checked:l.is_recurring,onCheckedChange:Ge=>o({...l,is_recurring:Ge})})]}),l.is_recurring&&e.jsxs("div",{className:"space-y-3 pt-1",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Frequency"}),e.jsxs(vs,{value:l.recurrence_pattern,onValueChange:Ge=>o({...l,recurrence_pattern:Ge}),children:[e.jsx(gs,{children:e.jsx(bs,{})}),e.jsxs(ys,{children:[e.jsx(Ye,{value:"weekly",children:"Weekly"}),e.jsx(Ye,{value:"biweekly",children:"Every 2 Weeks"}),e.jsx(Ye,{value:"monthly",children:"Monthly"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Repeat Until"}),e.jsxs(Sc,{children:[e.jsx(Cc,{asChild:!0,children:e.jsxs($,{variant:"outline",className:Tt("w-full justify-start text-left font-normal",!l.recurrence_end_date&&"text-muted-foreground"),children:[e.jsx(ia,{className:"mr-2 h-4 w-4"}),l.recurrence_end_date?Hs(l.recurrence_end_date,"PPP"):"Pick end date"]})}),e.jsx(xc,{className:"w-auto p-0",align:"start",children:e.jsx(y1,{mode:"single",selected:l.recurrence_end_date,onSelect:Ge=>o({...l,recurrence_end_date:Ge}),disabled:Ge=>Ge<(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 Ge=1,nt=new Date(l.event_date);for(;nt=l.recurrence_pattern==="weekly"?P3(nt,1):l.recurrence_pattern==="biweekly"?P3(nt,2):zx(nt,1),!(nt>l.recurrence_end_date);)Ge++;return Ge})()," events with the same Zoom link"]})]})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(se,{htmlFor:"is_published",children:"Published"}),e.jsx(Tn,{id:"is_published",checked:l.is_published,onCheckedChange:Ge=>o({...l,is_published:Ge})})]}),e.jsxs("div",{className:"flex gap-2 pt-4",children:[e.jsx($,{type:"button",variant:"outline",onClick:Qe,className:"flex-1",children:"Cancel"}),e.jsx($,{type:"submit",className:"flex-1",disabled:Be.isPending||qe.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(Oe,{children:ce?e.jsx("div",{className:"text-center py-8 text-muted-foreground",children:"Loading events..."}):(J==null?void 0:J.length)===0?e.jsx("div",{className:"text-center py-8 text-muted-foreground",children:"No events yet. Create your first event!"}):(()=>{const Ge=new Date,nt=[...J||[]],ft=nt.filter(js=>new Date(js.event_date)>=Ge).sort((js,zt)=>new Date(js.event_date).getTime()-new Date(zt.event_date).getTime()),lt=nt.filter(js=>new Date(js.event_date)new Date(zt.event_date).getTime()-new Date(js.event_date).getTime()),Mt=ft[0],Ft=js=>e.jsxs(hn,{children:[e.jsx(gt,{className:"font-medium",children:js.title}),e.jsx(gt,{className:"whitespace-nowrap",children:Hs(new Date(js.event_date),"PPP p")}),e.jsx(gt,{children:e.jsxs($,{variant:"ghost",size:"sm",className:"gap-1",onClick:()=>ve(js),children:[e.jsx(qn,{className:"h-4 w-4"}),(ue==null?void 0:ue[js.id])||0,js.capacity&&` / ${js.capacity}`]})}),e.jsx(gt,{children:e.jsx("span",{className:Tt("px-2 py-1 rounded-full text-xs font-medium",js.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:js.is_published?"Published":"Draft"})}),e.jsx(gt,{className:"text-right",children:e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsxs($,{variant:"outline",size:"sm",className:"gap-1.5",onClick:()=>{Q(js),V(!0)},title:"Send invite email to members",children:[e.jsx(Br,{className:"h-3.5 w-3.5"}),e.jsx("span",{className:"hidden sm:inline",children:"Invite Members"})]}),e.jsxs($,{variant:"outline",size:"sm",className:"gap-1.5 border-primary/50 text-primary hover:bg-primary/10",onClick:()=>Ze.mutate(js),disabled:Ze.isPending,title:"Clone to LevelUp Live",children:[e.jsx(Cg,{className:"h-3.5 w-3.5"}),e.jsx("span",{className:"hidden sm:inline",children:"LevelUp Live"})]}),e.jsx($,{variant:"ghost",size:"icon",onClick:()=>window.open(js.zoom_link,"_blank"),title:"Open Zoom Link",children:e.jsx(Tr,{className:"h-4 w-4"})}),e.jsx($,{variant:"ghost",size:"icon",onClick:()=>Ue(js),children:e.jsx(Ya,{className:"h-4 w-4"})}),e.jsx($,{variant:"ghost",size:"icon",onClick:async()=>{await Yi("Are you sure you want to delete this event?")&&Ke.mutate(js.id)},children:e.jsx(Pn,{className:"h-4 w-4 text-destructive"})})]})})]},js.id),Ts=(js,zt)=>js.length===0?e.jsx("div",{className:"text-center py-8 text-muted-foreground",children:zt}):e.jsxs(Va,{children:[e.jsx(Ha,{children:e.jsxs(hn,{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(Ga,{children:js.map(Ft)})]});return e.jsxs("div",{className:"space-y-6",children:[Mt&&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(Hr,{className:"h-3.5 w-3.5"}),"Next Upcoming Event"]}),e.jsx("h3",{className:"text-xl font-bold truncate",children:Mt.title}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:Hs(new Date(Mt.event_date),"EEEE, PPP 'at' p")}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-1",children:[(ue==null?void 0:ue[Mt.id])||0," registered",Mt.capacity?` of ${Mt.capacity}`:""]})]}),e.jsxs("div",{className:"flex gap-2 flex-wrap",children:[e.jsxs($,{size:"sm",className:"gap-1.5",onClick:()=>{Q(Mt),V(!0)},children:[e.jsx(Br,{className:"h-4 w-4"}),"Invite Members"]}),e.jsxs($,{size:"sm",variant:"outline",className:"gap-1.5",onClick:()=>ve(Mt),children:[e.jsx(qn,{className:"h-4 w-4"}),"Registrations"]}),e.jsxs($,{size:"sm",variant:"outline",className:"gap-1.5 border-primary/50 text-primary hover:bg-primary/10",onClick:()=>Ze.mutate(Mt),disabled:Ze.isPending,children:[e.jsx(Cg,{className:"h-4 w-4"}),"LevelUp Live"]}),e.jsxs($,{size:"sm",variant:"outline",className:"gap-1.5",onClick:()=>window.open(Mt.zoom_link,"_blank"),children:[e.jsx(Tr,{className:"h-4 w-4"}),"Zoom"]})]})]})}),e.jsxs(ua,{defaultValue:"upcoming",className:"w-full",children:[e.jsxs(ha,{children:[e.jsxs(Qt,{value:"upcoming",className:"gap-2",children:[e.jsx(Hr,{className:"h-4 w-4"}),"Upcoming",e.jsx("span",{className:"ml-1 rounded-full bg-muted px-2 py-0.5 text-xs",children:ft.length})]}),e.jsxs(Qt,{value:"past",className:"gap-2",children:[e.jsx(Fr,{className:"h-4 w-4"}),"Past",e.jsx("span",{className:"ml-1 rounded-full bg-muted px-2 py-0.5 text-xs",children:lt.length})]})]}),e.jsx(Jt,{value:"upcoming",className:"mt-4",children:Ts(ft,"No upcoming events scheduled.")}),e.jsx(Jt,{value:"past",className:"mt-4",children:Ts(lt,"No past events.")})]})]})})()})]}),e.jsx(fqs,{open:W,onOpenChange:V,event:K}),e.jsx(Os,{open:g,onOpenChange:y,children:e.jsxs(Rs,{className:"max-w-3xl max-h-[80vh] overflow-y-auto",children:[e.jsxs(Us,{children:[e.jsxs(zs,{className:"flex items-center gap-2",children:[e.jsx(qn,{className:"h-5 w-5"}),b==null?void 0:b.title]}),e.jsx(Sr,{children:"View registrations and attendees for this event"})]}),e.jsxs("div",{className:"flex items-center justify-end mb-4 gap-2 flex-wrap",children:[e.jsxs($,{variant:"ghost",size:"sm",onClick:()=>Ee.mutate({eventId:b.id,testMode:!0}),disabled:Ee.isPending,children:[e.jsx(nn,{className:Tt("h-4 w-4 mr-2",Ee.isPending&&"animate-spin")}),"Send Test to Me"]}),e.jsxs($,{variant:"outline",size:"sm",onClick:()=>Ee.mutate({eventId:b.id}),disabled:Ee.isPending||!(ne!=null&&ne.length),children:[e.jsx(nn,{className:Tt("h-4 w-4 mr-2",Ee.isPending&&"animate-spin")}),Ee.isPending?"Sending...":"Send Reminder to All"]}),(b==null?void 0:b.zoom_meeting_id)&&e.jsxs(e.Fragment,{children:[e.jsxs($,{variant:"outline",size:"sm",onClick:()=>ge.mutate(b.id),disabled:ge.isPending,children:[e.jsx(Wi,{className:Tt("h-4 w-4 mr-2",ge.isPending&&"animate-spin")}),ge.isPending?"Syncing...":"Sync Registrations"]}),e.jsxs($,{variant:"outline",size:"sm",onClick:()=>je.mutate(),disabled:je.isPending,children:[e.jsx(Wi,{className:Tt("h-4 w-4 mr-2",je.isPending&&"animate-spin")}),je.isPending?"Retrying...":"Retry Failed Registrations"]}),e.jsxs($,{variant:"default",size:"sm",onClick:()=>fe.mutate(b.id),disabled:fe.isPending,children:[e.jsx(pl,{className:Tt("h-4 w-4 mr-2",fe.isPending&&"animate-spin")}),fe.isPending?"Syncing...":"Sync Attendees & Award Points"]})]})]}),e.jsxs(ua,{defaultValue:"registrations",className:"w-full",children:[e.jsxs(ha,{className:"grid w-full grid-cols-2",children:[e.jsxs(Qt,{value:"registrations",className:"gap-2",children:[e.jsx(qn,{className:"h-4 w-4"}),"Registrations (",(ne==null?void 0:ne.length)||0,")"]}),e.jsxs(Qt,{value:"attendees",className:"gap-2",children:[e.jsx(Fr,{className:"h-4 w-4"}),"Attendees (",(le==null?void 0:le.length)||0,")"]})]}),e.jsx(Jt,{value:"registrations",className:"mt-4",children:ee?e.jsx("div",{className:"text-center py-8 text-muted-foreground",children:"Loading registrations..."}):(ne==null?void 0:ne.length)===0?e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx("p",{children:"No registrations yet for this event."}),(b==null?void 0:b.zoom_meeting_id)&&e.jsx("p",{className:"text-xs mt-2",children:'Click "Sync Registrations" to import from Zoom.'})]}):e.jsxs(Va,{children:[e.jsx(Ha,{children:e.jsxs(hn,{children:[e.jsx(Lt,{children:"Name"}),e.jsx(Lt,{children:"Email"}),e.jsx(Lt,{children:"Registered"}),e.jsx(Lt,{children:"Status"})]})}),e.jsx(Ga,{children:ne==null?void 0:ne.map(Ge=>{var Mt,Ft;const nt=((Mt=Ge.profiles)==null?void 0:Mt.name)||Ge.zoom_name||"Unknown",ft=((Ft=Ge.profiles)==null?void 0:Ft.email)||Ge.zoom_email||null,lt=!Ge.user_id;return e.jsxs(hn,{children:[e.jsx(gt,{className:"font-medium",children:e.jsxs("div",{className:"flex items-center gap-2",children:[nt,lt&&e.jsx("span",{className:"text-xs px-1.5 py-0.5 rounded bg-muted text-muted-foreground",children:"External"})]})}),e.jsx(gt,{children:ft?e.jsxs("a",{href:`mailto:${ft}`,className:"flex items-center gap-1 text-primary hover:underline",children:[e.jsx(nn,{className:"h-3 w-3"}),ft]}):e.jsx("span",{className:"text-muted-foreground",children:"No email"})}),e.jsx(gt,{className:"text-muted-foreground text-sm",children:Hs(new Date(Ge.registered_at),"MMM d, yyyy h:mm a")}),e.jsx(gt,{children:Ge.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"})})]},Ge.id)})})]})}),e.jsx(Jt,{value:"attendees",className:"mt-4",children:he?e.jsx("div",{className:"text-center py-8 text-muted-foreground",children:"Loading attendees..."}):(le==null?void 0:le.length)===0?e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx("p",{children:"No attendees recorded yet."}),(b==null?void 0:b.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:[(le==null?void 0:le.filter(Ge=>!Ge.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(xo,{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 (",le==null?void 0:le.filter(Ge=>!Ge.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:le==null?void 0:le.filter(Ge=>!Ge.user_id).map(Ge=>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:Ge.zoom_name||"Unknown"}),e.jsx("span",{className:"text-xs text-muted-foreground",children:Ge.zoom_email||"No email"})]}),e.jsxs($,{variant:"outline",size:"sm",onClick:()=>ze(Ge),className:"gap-1",children:[e.jsx(Dc,{className:"h-3 w-3"}),"Link to Profile"]})]},Ge.id))})]}),e.jsxs(Va,{children:[e.jsx(Ha,{children:e.jsxs(hn,{children:[e.jsx(Lt,{children:"Name"}),e.jsx(Lt,{children:"Email"}),e.jsx(Lt,{children:"Duration"}),e.jsx(Lt,{children:"Points"})]})}),e.jsx(Ga,{children:le==null?void 0:le.filter(Ge=>Ge.user_id).map(Ge=>{var lt,Mt;const nt=((lt=Ge.profiles)==null?void 0:lt.name)||Ge.zoom_name||"Unknown",ft=((Mt=Ge.profiles)==null?void 0:Mt.email)||Ge.zoom_email||null;return e.jsxs(hn,{children:[e.jsx(gt,{className:"font-medium",children:e.jsxs("div",{className:"flex items-center gap-2",children:[nt,Ge.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:ft?e.jsxs("a",{href:`mailto:${ft}`,className:"flex items-center gap-1 text-primary hover:underline",children:[e.jsx(nn,{className:"h-3 w-3"}),ft]}):e.jsx("span",{className:"text-muted-foreground",children:"No email"})}),e.jsx(gt,{children:Ge.duration_minutes?e.jsxs("span",{className:"flex items-center gap-1 text-muted-foreground text-sm",children:[e.jsx(Hr,{className:"h-3 w-3"}),Ge.duration_minutes," min"]}):e.jsx("span",{className:"text-muted-foreground text-sm",children:"—"})}),e.jsx(gt,{children:Ge.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(pl,{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"})})]},Ge.id)})})]})]})})]})]})}),e.jsx(Os,{open:N,onOpenChange:C,children:e.jsxs(Rs,{className:"max-w-md",children:[e.jsxs(Us,{children:[e.jsxs(zs,{className:"flex items-center gap-2",children:[e.jsx(Dc,{className:"h-5 w-5"}),"Link Attendee to Profile"]}),e.jsx(Sr,{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(se,{children:"Search for a profile"}),e.jsxs("div",{className:"relative",children:[e.jsx(Vr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(be,{placeholder:"Search by name or email...",value:B,onChange:Ge=>q(Ge.target.value),className:"pl-9"})]})]}),e.jsx("div",{className:"max-h-48 overflow-y-auto border rounded-md",children:Xe.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:Xe.slice(0,20).map(Ge=>e.jsxs("button",{type:"button",onClick:()=>M(Ge.id),className:Tt("w-full p-3 text-left hover:bg-muted/50 transition-colors",P===Ge.id&&"bg-primary/10 border-l-2 border-primary"),children:[e.jsx("p",{className:"text-sm font-medium",children:Ge.name||"Unnamed"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:Ge.email})]},Ge.id))})}),A.zoom_email&&e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(ui,{id:"save-alias",checked:I,onCheckedChange:Ge=>D(Ge)}),e.jsx("label",{htmlFor:"save-alias",className:"text-sm text-muted-foreground cursor-pointer",children:"Remember this email for future auto-matching"})]}),e.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[e.jsx($,{variant:"outline",onClick:()=>C(!1),children:"Cancel"}),e.jsx($,{onClick:ke,disabled:!P||De.isPending,children:De.isPending?"Linking...":"Link & Award Points"})]})]})]})})]})})}const gqs={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 yqs(){const[s,t]=j.useState([]),[n,r]=j.useState(!0),[a,i]=j.useState("issues");async function l(){r(!0);let o=U.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(Ks,{title:"MCP Audit Log",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(hh,{title:"MCP Audit Log",description:"Recent LevelUp MCP tool calls — ChatGPT / Claude / Codex activity, denials, and rate limits."}),e.jsxs(_e,{children:[e.jsxs(Bt,{className:"flex flex-row items-center justify-between",children:[e.jsxs(Ut,{className:"flex items-center gap-2",children:[e.jsx(zz,{className:"h-5 w-5"}),"Recent activity"]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx($,{variant:a==="issues"?"default":"outline",size:"sm",onClick:()=>i("issues"),children:"Issues only"}),e.jsx($,{variant:a==="all"?"default":"outline",size:"sm",onClick:()=>i("all"),children:"All calls"}),e.jsx($,{variant:"ghost",size:"sm",onClick:l,disabled:n,children:e.jsx(Wi,{className:`h-4 w-4 ${n?"animate-spin":""}`})})]})]}),e.jsx(Oe,{children:n?e.jsx("p",{className:"text-sm text-muted-foreground",children:"Loading…"}):s.length===0?e.jsx("p",{className:"text-sm text-muted-foreground",children:"No entries."}):e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{className:"border-b text-left text-muted-foreground",children:e.jsxs("tr",{children:[e.jsx("th",{className:"py-2 pr-4",children:"When"}),e.jsx("th",{className:"py-2 pr-4",children:"Tool"}),e.jsx("th",{className:"py-2 pr-4",children:"Outcome"}),e.jsx("th",{className:"py-2 pr-4",children:"User"}),e.jsx("th",{className:"py-2 pr-4",children:"Client"}),e.jsx("th",{className:"py-2 pr-4",children:"ms"}),e.jsx("th",{className:"py-2 pr-4",children:"Error"})]})}),e.jsx("tbody",{children:s.map(o=>e.jsxs("tr",{className:"border-b last:border-0",children:[e.jsx("td",{className:"py-2 pr-4 whitespace-nowrap",children:new Date(o.created_at).toLocaleString()}),e.jsx("td",{className:"py-2 pr-4 font-mono text-xs",children:o.tool_name}),e.jsx("td",{className:"py-2 pr-4",children:e.jsx($e,{className:gqs[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 vqs({selectedKitIds:s,onChange:t}){const[n,r]=j.useState(""),[a,i]=j.useState(!1),{data:l=[]}=ht({queryKey:["all-resource-kits-picker"],queryFn:async()=>{const{data:h,error:m}=await U.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(se,{className:"flex items-center gap-2",children:[e.jsx(Tu,{className:"h-4 w-4"}),"Linked Toolkits"]}),o.length>0&&e.jsx("div",{className:"flex flex-wrap gap-1.5",children:o.map(h=>e.jsxs($e,{variant:"secondary",className:"gap-1 pr-1",children:[h.name,e.jsx("button",{type:"button",onClick:()=>u(h.id),className:"ml-1 rounded-full hover:bg-muted-foreground/20 p-0.5",children:e.jsx(pr,{className:"h-3 w-3"})})]},h.id))}),e.jsxs(Sc,{open:a,onOpenChange:i,children:[e.jsx(Cc,{asChild:!0,children:e.jsxs($,{type:"button",variant:"outline",size:"sm",className:"gap-1",children:[e.jsx(Tu,{className:"h-3.5 w-3.5"}),"Add Toolkit"]})}),e.jsxs(xc,{className:"w-80 p-2",align:"start",children:[e.jsxs("div",{className:"relative mb-2",children:[e.jsx(Vr,{className:"absolute left-2 top-2.5 h-3.5 w-3.5 text-muted-foreground"}),e.jsx(be,{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(Tu,{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 bqs=()=>{const{user:s}=_s(),{toast:t}=gi(),n=ts(),[r,a]=oc(),[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,x]=j.useState(0),[g,y]=j.useState(!1),[b,v]=j.useState(null),[N,C]=j.useState(""),[A,T]=j.useState([]),[P,M]=j.useState(""),[I,D]=j.useState(""),[B,q]=j.useState(!1),[W,V]=j.useState(!1),{data:K=[]}=ht({queryKey:["template-categories"],queryFn:async()=>{const{data:Ae,error:Be}=await U.from("template_categories").select("*").order("name");if(Be)throw Be;return Ae}}),{data:Q=[]}=ht({queryKey:["template-types"],queryFn:async()=>{const{data:Ae,error:Be}=await U.from("template_types").select("*").order("name");if(Be)throw Be;return Ae}}),{data:J=[],isLoading:ce}=ht({queryKey:["canva-templates-admin"],queryFn:async()=>{const{data:Ae,error:Be}=await U.from("canva_templates").select(` *, category:template_categories(id, name), type:template_types(id, name) `).order("publish_date",{ascending:!1});if(Be)throw Be;const{data:qe,error:Ke}=await U.from("template_links").select("*").order("sort_order");if(Ke)throw Ke;const{data:Ze,error:Ue}=await U.from("template_guides").select("*").order("sort_order");if(Ue)throw Ue;return Ae.map(Qe=>({...Qe,links:(qe==null?void 0:qe.filter(Ge=>Ge.template_id===Qe.id))||[],guides:(Ze==null?void 0:Ze.filter(Ge=>Ge.template_id===Qe.id))||[]}))}});j.useEffect(()=>{const Ae=r.get("edit");if(Ae&&J.length>0){const Be=J.find(qe=>qe.id===Ae);Be&&(ge(Be),a({},{replace:!0}))}},[J,r]);const ue=yt({mutationFn:async Ae=>{const{data:Be,error:qe}=await U.from("template_categories").insert({name:Ae}).select().single();if(qe)throw qe;return Be},onSuccess:Ae=>{n.invalidateQueries({queryKey:["template-categories"]}),u({...d,category_id:Ae.id}),M(""),q(!1),t({title:"Category added"})},onError:Ae=>{t({title:"Error adding category",description:Ae.message,variant:"destructive"})}}),ne=yt({mutationFn:async Ae=>{const{data:Be,error:qe}=await U.from("template_types").insert({name:Ae}).select().single();if(qe)throw qe;return Be},onSuccess:Ae=>{n.invalidateQueries({queryKey:["template-types"]}),u({...d,type_id:Ae.id}),D(""),V(!1),t({title:"Type added"})},onError:Ae=>{t({title:"Error adding type",description:Ae.message,variant:"destructive"})}}),ee=yt({mutationFn:async Ae=>{var Ue;let Be=Ae.existingImageUrl;if(Ae.image){const et=Ae.image.name.split(".").pop(),Qe=`${Date.now()}-${Math.random().toString(36).substring(7)}.${et}`,{error:Ge}=await U.storage.from("template-previews").upload(Qe,Ae.image);if(Ge)throw Ge;const{data:nt}=U.storage.from("template-previews").getPublicUrl(Qe);Be=nt.publicUrl}const qe={name:Ae.template.name,description:Ae.template.description||null,category_id:Ae.template.category_id||null,type_id:Ae.template.type_id||null,preview_image_url:Be,video_url:Ae.videoUrl||null,publish_date:Ae.template.publish_date?new Date(Ae.template.publish_date).toISOString():new Date().toISOString(),created_by:s==null?void 0:s.id};let Ke=Ae.templateId;if(Ke){const{error:et}=await U.from("canva_templates").update(qe).eq("id",Ke);if(et)throw et;const{error:Qe}=await U.from("template_links").delete().eq("template_id",Ke);if(Qe)throw Qe;const Ge=((Ue=Ae.existingGuides)==null?void 0:Ue.map(lt=>lt.id).filter(Boolean))||[],nt=Ae.template.guides.map(lt=>lt.id).filter(Boolean),ft=Ge.filter(lt=>!nt.includes(lt));ft.length>0&&await U.from("template_guides").delete().in("id",ft)}else{const{data:et,error:Qe}=await U.from("canva_templates").insert(qe).select().single();if(Qe)throw Qe;Ke=et.id,lqs(Ae.template.name,et.id)}const Ze=Ae.template.links.filter(et=>et.title.trim()&&et.canva_share_link.trim());if(Ze.length>0){const et=Ze.map((Ge,nt)=>({template_id:Ke,title:Ge.title.trim(),canva_share_link:Ge.canva_share_link.trim(),sort_order:nt})),{error:Qe}=await U.from("template_links").insert(et);if(Qe)throw Qe}for(let et=0;et0)){const{error:et}=await U.from("resource_kit_templates").insert(Ae.linkedKitIds.map(Qe=>({template_id:Ke,kit_id:Qe})));if(et)throw et}},onSuccess:()=>{n.invalidateQueries({queryKey:["canva-templates-admin"]}),n.invalidateQueries({queryKey:["canva-templates"]}),ve(),l(!1),t({title:o?"Template updated":"Template created"})},onError:Ae=>{t({title:"Error saving template",description:Ae.message,variant:"destructive"})}}),le=yt({mutationFn:async Ae=>{const{error:Be}=await U.from("canva_templates").delete().eq("id",Ae);if(Be)throw Be},onSuccess:()=>{n.invalidateQueries({queryKey:["canva-templates-admin"]}),n.invalidateQueries({queryKey:["canva-templates"]}),t({title:"Template deleted"})},onError:Ae=>{t({title:"Error deleting template",description:Ae.message,variant:"destructive"})}}),he=yt({mutationFn:async({id:Ae,is_featured:Be})=>{const{error:qe}=await U.from("canva_templates").update({is_featured:Be}).eq("id",Ae);if(qe)throw qe},onSuccess:()=>{n.invalidateQueries({queryKey:["canva-templates-admin"]}),n.invalidateQueries({queryKey:["canva-templates"]})},onError:Ae=>{t({title:"Error updating featured",description:Ae.message,variant:"destructive"})}}),ve=()=>{u({name:"",description:"",category_id:"",type_id:"",publish_date:new Date().toISOString().split("T")[0],links:[{title:"",canva_share_link:"",sort_order:0}],guides:[],video_url:""}),v(null),C(""),c(null),q(!1),V(!1),M(""),D(""),m(null),x(0),y(!1),T([])},ge=async Ae=>{var qe;c(Ae),u({name:Ae.name,description:Ae.description||"",category_id:Ae.category_id||"",type_id:Ae.type_id||"",publish_date:Ae.publish_date?new Date(Ae.publish_date).toISOString().split("T")[0]:new Date().toISOString().split("T")[0],links:Ae.links&&Ae.links.length>0?Ae.links.map(Ke=>({id:Ke.id,title:Ke.title,canva_share_link:Ke.canva_share_link,sort_order:Ke.sort_order})):[{title:"",canva_share_link:"",sort_order:0}],guides:((qe=Ae.guides)==null?void 0:qe.map(Ke=>({id:Ke.id,name:Ke.name,file_url:Ke.file_url,file_type:Ke.file_type,file_size:Ke.file_size,sort_order:Ke.sort_order})))||[],video_url:Ae.video_url||""}),C(Ae.preview_image_url||""),m(null);const{data:Be}=await U.from("resource_kit_templates").select("kit_id").eq("template_id",Ae.id);T((Be||[]).map(Ke=>Ke.kit_id)),l(!0)},fe=Ae=>{var qe;const Be=(qe=Ae.target.files)==null?void 0:qe[0];Be&&(v(Be),C(URL.createObjectURL(Be)))},je=()=>{u({...d,links:[...d.links,{title:"",canva_share_link:"",sort_order:d.links.length}]})},Ee=Ae=>{if(d.links.length<=1)return;const Be=d.links.filter((qe,Ke)=>Ke!==Ae);u({...d,links:Be})},Me=(Ae,Be,qe)=>{const Ke=[...d.links];Ke[Ae]={...Ke[Ae],[Be]:qe},u({...d,links:Ke})},De=Ae=>{const Be=Ae.target.files;if(!Be)return;const qe=Array.from(Be).map((Ke,Ze)=>({name:Ke.name.replace(/\.[^/.]+$/,""),file_url:"",file_type:Ke.type,file_size:Ke.size,sort_order:d.guides.length+Ze,file:Ke}));u({...d,guides:[...d.guides,...qe]}),Ae.target.value=""},ze=Ae=>{const Be=d.guides.filter((qe,Ke)=>Ke!==Ae);u({...d,guides:Be})},ke=(Ae,Be)=>{const qe=[...d.guides];qe[Ae]={...qe[Ae],name:Be},u({...d,guides:qe})},Xe=async()=>{if(!h)return null;y(!0),x(0);try{const{data:Ae,error:Be}=await U.functions.invoke("bunny-upload",{body:{action:"create",title:d.name||h.name}});if(Be)throw new Error(Be.message);const{videoId:qe,libraryId:Ke}=Ae,{data:Ze,error:Ue}=await U.functions.invoke("bunny-upload",{body:{action:"upload-url",videoId:qe}});if(Ue)throw new Error(Ue.message);const et=new XMLHttpRequest;return await new Promise((Ge,nt)=>{et.upload.addEventListener("progress",ft=>{if(ft.lengthComputable){const lt=Math.round(ft.loaded/ft.total*100);x(lt)}}),et.addEventListener("load",()=>{et.status>=200&&et.status<300?Ge():nt(new Error(`Upload failed with status ${et.status}`))}),et.addEventListener("error",()=>nt(new Error("Upload failed"))),et.open("PUT",Ze.uploadUrl),et.setRequestHeader("AccessKey",Ze.apiKey),et.send(h)}),`https://player.mediadelivery.net/embed/${Ke}/${qe}`}catch(Ae){return console.error("Bunny upload error:",Ae),t({title:"Video upload failed",description:Ae instanceof Error?Ae.message:"Unknown error",variant:"destructive"}),null}finally{y(!1)}},Se=Ae=>{var qe;const Be=(qe=Ae.target.files)==null?void 0:qe[0];Be&&m(Be),Ae.target.value=""},Re=async Ae=>{if(Ae.preventDefault(),!d.name.trim()){t({title:"Please enter a template name",variant:"destructive"});return}if(d.links.filter(Ke=>Ke.title.trim()&&Ke.canva_share_link.trim()).length===0){t({title:"Please add at least one Canva link",variant:"destructive"});return}let qe=d.video_url;if(h){const Ke=await Xe();if(!Ke)return;qe=Ke}ee.mutate({template:d,image:b,existingImageUrl:(o==null?void 0:o.preview_image_url)||null,templateId:o==null?void 0:o.id,existingGuides:o==null?void 0:o.guides,videoUrl:qe,linkedKitIds:A})};return e.jsx(Ks,{title:"Manage Templates",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(hh,{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(_e,{children:[e.jsx(Bt,{className:"pb-2",children:e.jsx(Ut,{className:"text-sm font-medium text-muted-foreground",children:"Total Templates"})}),e.jsx(Oe,{children:e.jsx("div",{className:"text-2xl font-bold",children:J.length})})]}),e.jsxs(_e,{children:[e.jsx(Bt,{className:"pb-2",children:e.jsx(Ut,{className:"text-sm font-medium text-muted-foreground",children:"Categories"})}),e.jsx(Oe,{children:e.jsx("div",{className:"text-2xl font-bold",children:K.length})})]}),e.jsxs(_e,{children:[e.jsx(Bt,{className:"pb-2",children:e.jsx(Ut,{className:"text-sm font-medium text-muted-foreground",children:"Template Types"})}),e.jsx(Oe,{children:e.jsx("div",{className:"text-2xl font-bold",children:Q.length})})]})]}),e.jsxs(Os,{open:i,onOpenChange:Ae=>{l(Ae),Ae||ve()},children:[e.jsx(Ko,{asChild:!0,children:e.jsxs($,{className:"gap-2",children:[e.jsx(sn,{className:"h-4 w-4"}),"Add Template"]})}),e.jsxs(Rs,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsx(Us,{children:e.jsx(zs,{children:o?"Edit Template":"Add New Template"})}),e.jsxs("form",{onSubmit:Re,className:"space-y-6 pt-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"name",children:"Name *"}),e.jsx(be,{id:"name",value:d.name,onChange:Ae=>u({...d,name:Ae.target.value}),placeholder:"Template name",required:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Description"}),e.jsx(m2,{content:d.description,onChange:Ae=>u({...d,description:Ae}),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(se,{children:"Canva Links *"}),e.jsxs($,{type:"button",variant:"outline",size:"sm",onClick:je,className:"gap-1",children:[e.jsx(sn,{className:"h-3 w-3"}),"Add Link"]})]}),e.jsx("div",{className:"space-y-3",children:d.links.map((Ae,Be)=>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(be,{value:Ae.title,onChange:qe=>Me(Be,"title",qe.target.value),placeholder:"Link title (e.g., Instagram Post, Story)"}),e.jsx(be,{value:Ae.canva_share_link,onChange:qe=>Me(Be,"canva_share_link",qe.target.value),placeholder:"https://www.canva.com/design/..."})]}),d.links.length>1&&e.jsx($,{type:"button",variant:"ghost",size:"icon",className:"shrink-0 text-muted-foreground hover:text-destructive",onClick:()=>Ee(Be),children:e.jsx(pr,{className:"h-4 w-4"})})]},Be))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Category"}),B?e.jsxs("div",{className:"flex gap-2",children:[e.jsx(be,{value:P,onChange:Ae=>M(Ae.target.value),placeholder:"New category name",className:"flex-1"}),e.jsx($,{type:"button",size:"sm",onClick:()=>P.trim()&&ue.mutate(P.trim()),disabled:ue.isPending,children:"Add"}),e.jsx($,{type:"button",size:"sm",variant:"ghost",onClick:()=>{q(!1),M("")},children:e.jsx(pr,{className:"h-4 w-4"})})]}):e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(vs,{value:d.category_id,onValueChange:Ae=>u({...d,category_id:Ae}),children:[e.jsx(gs,{className:"flex-1",children:e.jsx(bs,{placeholder:"Select category"})}),e.jsx(ys,{children:K.map(Ae=>e.jsx(Ye,{value:Ae.id,children:Ae.name},Ae.id))})]}),e.jsx($,{type:"button",variant:"outline",size:"icon",onClick:()=>q(!0),children:e.jsx(sn,{className:"h-4 w-4"})})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Template Type"}),W?e.jsxs("div",{className:"flex gap-2",children:[e.jsx(be,{value:I,onChange:Ae=>D(Ae.target.value),placeholder:"New type name",className:"flex-1"}),e.jsx($,{type:"button",size:"sm",onClick:()=>I.trim()&&ne.mutate(I.trim()),disabled:ne.isPending,children:"Add"}),e.jsx($,{type:"button",size:"sm",variant:"ghost",onClick:()=>{V(!1),D("")},children:e.jsx(pr,{className:"h-4 w-4"})})]}):e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(vs,{value:d.type_id,onValueChange:Ae=>u({...d,type_id:Ae}),children:[e.jsx(gs,{className:"flex-1",children:e.jsx(bs,{placeholder:"Select type"})}),e.jsx(ys,{children:Q.map(Ae=>e.jsx(Ye,{value:Ae.id,children:Ae.name},Ae.id))})]}),e.jsx($,{type:"button",variant:"outline",size:"icon",onClick:()=>V(!0),children:e.jsx(sn,{className:"h-4 w-4"})})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"publish_date",children:"Publish Date"}),e.jsx(be,{id:"publish_date",type:"date",value:d.publish_date,onChange:Ae=>u({...d,publish_date:Ae.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(se,{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($,{type:"button",size:"icon",variant:"destructive",className:"absolute top-1 right-1 h-6 w-6",onClick:()=>{v(null),C("")},children:e.jsx(pr,{className:"h-3 w-3"})})]}):e.jsx("div",{className:"w-32 h-24 rounded-lg border-2 border-dashed border-muted-foreground/25 flex items-center justify-center",children:e.jsx(Jl,{className:"h-8 w-8 text-muted-foreground/50"})}),e.jsxs("div",{className:"flex-1",children:[e.jsx(be,{type:"file",accept:"image/*",onChange:fe,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(se,{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(Xr,{className:"h-5 w-5 text-primary shrink-0"}),e.jsx("span",{className:"text-sm flex-1 truncate",children:"Video uploaded"}),e.jsx($,{type:"button",variant:"ghost",size:"sm",onClick:()=>u({...d,video_url:""}),className:"text-destructive hover:text-destructive",children:"Remove"})]}),e.jsx("div",{className:"aspect-video max-w-md rounded-lg overflow-hidden border",children:e.jsx("iframe",{src:d.video_url,className:"w-full h-full",allow:"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture",allowFullScreen:!0})})]}):g?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(Ht,{className:"h-4 w-4 animate-spin"}),e.jsxs("span",{className:"text-sm",children:["Uploading video... ",p,"%"]})]}),e.jsx(Ki,{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(Xr,{className:"h-5 w-5 text-muted-foreground shrink-0"}),e.jsx("span",{className:"text-sm flex-1 truncate",children:h.name}),e.jsxs("span",{className:"text-xs text-muted-foreground shrink-0",children:[(h.size/1024/1024).toFixed(1)," MB"]}),e.jsx($,{type:"button",variant:"ghost",size:"icon",className:"shrink-0 text-muted-foreground hover:text-destructive h-8 w-8",onClick:()=>m(null),children:e.jsx(pr,{className:"h-4 w-4"})})]}):e.jsxs("div",{className:"space-y-2",children:[e.jsxs("label",{className:"cursor-pointer",children:[e.jsx(be,{type:"file",accept:"video/*",onChange:Se,className:"hidden"}),e.jsxs("div",{className:"flex items-center justify-center gap-2 p-6 border-2 border-dashed rounded-lg hover:border-primary/50 transition-colors",children:[e.jsx(Xr,{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(se,{children:"Guide Files (PDFs)"}),e.jsxs("label",{className:"cursor-pointer",children:[e.jsx(be,{type:"file",accept:".pdf,.doc,.docx",multiple:!0,onChange:De,className:"hidden"}),e.jsx($,{type:"button",variant:"outline",size:"sm",className:"gap-1",asChild:!0,children:e.jsxs("span",{children:[e.jsx(si,{className:"h-3 w-3"}),"Add Files"]})})]})]}),d.guides.length>0?e.jsx("div",{className:"space-y-2",children:d.guides.map((Ae,Be)=>e.jsxs("div",{className:"flex gap-2 items-center p-3 border rounded-lg bg-muted/30",children:[e.jsx(Wr,{className:"h-5 w-5 text-muted-foreground shrink-0"}),e.jsx(be,{value:Ae.name,onChange:qe=>ke(Be,qe.target.value),placeholder:"Guide name",className:"flex-1"}),Ae.file_size&&e.jsxs("span",{className:"text-xs text-muted-foreground shrink-0",children:[(Ae.file_size/1024).toFixed(0)," KB"]}),e.jsx($,{type:"button",variant:"ghost",size:"icon",className:"shrink-0 text-muted-foreground hover:text-destructive h-8 w-8",onClick:()=>ze(Be),children:e.jsx(pr,{className:"h-4 w-4"})})]},Ae.id||Be))}):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(vqs,{selectedKitIds:A,onChange:T}),e.jsxs("div",{className:"flex justify-end gap-2 pt-4",children:[e.jsx($,{type:"button",variant:"outline",onClick:()=>{l(!1),ve()},children:"Cancel"}),e.jsx($,{type:"submit",disabled:ee.isPending,children:ee.isPending?"Saving...":o?"Update":"Create"})]})]})]})]})]}),e.jsx(_e,{children:e.jsx(Oe,{className:"p-0",children:ce?e.jsx("div",{className:"text-center py-8 text-muted-foreground",children:"Loading..."}):J.length===0?e.jsx("div",{className:"text-center py-8 text-muted-foreground",children:"No templates yet. Add your first template!"}):e.jsxs(Va,{children:[e.jsx(Ha,{children:e.jsxs(hn,{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(Ga,{children:J.map(Ae=>{var Be,qe,Ke,Ze,Ue;return e.jsxs(hn,{children:[e.jsx(gt,{children:e.jsx("div",{className:"w-16 h-12 rounded overflow-hidden bg-muted",children:Ae.preview_image_url?e.jsx("img",{src:Ae.preview_image_url,alt:Ae.name,className:"w-full h-full object-cover"}):e.jsx("div",{className:"w-full h-full flex items-center justify-center",children:e.jsx(Jl,{className:"h-4 w-4 text-muted-foreground"})})})}),e.jsx(gt,{className:"font-medium",children:Ae.name}),e.jsx(gt,{children:e.jsxs("div",{className:"flex flex-col gap-1",children:[e.jsxs($e,{variant:"secondary",children:[((Be=Ae.links)==null?void 0:Be.length)||0," link",(((qe=Ae.links)==null?void 0:qe.length)||0)!==1?"s":""]}),(((Ke=Ae.guides)==null?void 0:Ke.length)||0)>0&&e.jsxs($e,{variant:"outline",className:"gap-1",children:[e.jsx(Wr,{className:"h-3 w-3"}),(Ze=Ae.guides)==null?void 0:Ze.length," guide",(((Ue=Ae.guides)==null?void 0:Ue.length)||0)!==1?"s":""]})]})}),e.jsx(gt,{children:Ae.category?e.jsx($e,{variant:"secondary",children:Ae.category.name}):e.jsx("span",{className:"text-muted-foreground",children:"-"})}),e.jsx(gt,{children:Ae.type?e.jsx($e,{variant:"outline",children:Ae.type.name}):e.jsx("span",{className:"text-muted-foreground",children:"-"})}),e.jsx(gt,{className:"text-muted-foreground",children:new Date(Ae.publish_date).toLocaleDateString()}),e.jsx(gt,{className:"text-center",children:e.jsx($,{type:"button",size:"icon",variant:"ghost",className:"mx-auto",title:Ae.is_featured?"Remove from featured templates":"Add to featured templates",onClick:()=>he.mutate({id:Ae.id,is_featured:!Ae.is_featured}),children:e.jsx(Qa,{className:`h-4 w-4 ${Ae.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($,{size:"icon",variant:"ghost",onClick:()=>ge(Ae),children:e.jsx(Ya,{className:"h-4 w-4"})}),e.jsx($,{size:"icon",variant:"ghost",className:"text-destructive hover:text-destructive",onClick:async()=>{await Yi("Delete this template?")&&le.mutate(Ae.id)},children:e.jsx(Pn,{className:"h-4 w-4"})})]})})]},Ae.id)})})]})})})]})})};function v8t({selectedTemplateIds:s,onChange:t}){const[n,r]=j.useState(""),[a,i]=j.useState(!1),{data:l=[]}=ht({queryKey:["all-canva-templates-picker"],queryFn:async()=>{const{data:h,error:m}=await U.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(se,{className:"flex items-center gap-2",children:[e.jsx(nw,{className:"h-4 w-4"}),"Linked Templates"]}),o.length>0&&e.jsx("div",{className:"flex flex-wrap gap-1.5",children:o.map(h=>e.jsxs($e,{variant:"secondary",className:"gap-1 pr-1",children:[h.name,e.jsx("button",{type:"button",onClick:()=>u(h.id),className:"ml-1 rounded-full hover:bg-muted-foreground/20 p-0.5",children:e.jsx(pr,{className:"h-3 w-3"})})]},h.id))}),e.jsxs(Sc,{open:a,onOpenChange:i,children:[e.jsx(Cc,{asChild:!0,children:e.jsxs($,{type:"button",variant:"outline",size:"sm",className:"gap-1",children:[e.jsx(nw,{className:"h-3.5 w-3.5"}),"Add Template"]})}),e.jsxs(xc,{className:"w-80 p-2",align:"start",children:[e.jsxs("div",{className:"relative mb-2",children:[e.jsx(Vr,{className:"absolute left-2 top-2.5 h-3.5 w-3.5 text-muted-foreground"}),e.jsx(be,{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(nw,{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 _qs=[{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"}],put=new Intl.DateTimeFormat("en-CA",{timeZone:"America/New_York",year:"numeric",month:"2-digit",day:"2-digit"}).format(new Date),fut=s=>{const[t,n,r]=s.split(/[-/T]/);return`${Number(n)}/${Number(r)}/${t}`},wqs=()=>{const{user:s}=_s(),[t,n]=oc(),{toast:r}=gi(),a=ts(),[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,x]=j.useState(""),[g,y]=j.useState([]),[b,v]=j.useState([]),[N,C]=j.useState([]),[A,T]=j.useState([]),[P,M]=j.useState(""),[I,D]=j.useState(!1),[B,q]=j.useState(null),[W,V]=j.useState(0),[K,Q]=j.useState(!1),[J,ce]=j.useState(null),{data:ue=[]}=ht({queryKey:["academy-categories"],queryFn:async()=>{const{data:Ae,error:Be}=await U.from("academy_categories").select("*").order("sort_order",{ascending:!0});if(Be)throw Be;return Ae}}),{data:ne=[],isLoading:ee}=ht({queryKey:["academy-videos-admin"],queryFn:async()=>{const{data:Ae,error:Be}=await U.from("academy_videos").select(` *, category:academy_categories(id, name) `).order("publish_date",{ascending:!1});if(Be)throw Be;const{data:qe,error:Ke}=await U.from("academy_resources").select("*").order("sort_order");if(Ke)throw Ke;return Ae.map(Ue=>({...Ue,resources:(qe==null?void 0:qe.filter(et=>et.video_id===Ue.id))||[]}))}});j.useEffect(()=>{const Ae=t.get("edit");if(Ae&&ne.length>0){const Be=ne.find(qe=>qe.id===Ae);Be&&(Me(Be),n({},{replace:!0}))}},[ne,t]);const le=yt({mutationFn:async Ae=>{const{data:Be,error:qe}=await U.from("academy_categories").insert({name:Ae,sort_order:ue.length}).select().single();if(qe)throw qe;return Be},onSuccess:Ae=>{a.invalidateQueries({queryKey:["academy-categories"]}),u({...d,category_id:Ae.id}),M(""),D(!1),r({title:"Category added"})},onError:Ae=>{r({title:"Error adding category",description:Ae.message,variant:"destructive"})}}),he=yt({mutationFn:async Ae=>{let Be=Ae.existingThumbnailUrl;if(Ae.thumbnail){const Ze=Ae.thumbnail.name.split(".").pop(),Ue=`thumbnails/${Date.now()}-${Math.random().toString(36).substring(7)}.${Ze}`,{error:et}=await U.storage.from("academy-resources").upload(Ue,Ae.thumbnail);if(et)throw et;const{data:Qe}=U.storage.from("academy-resources").getPublicUrl(Ue);Be=Qe.publicUrl}const qe={title:Ae.video.title,description:Ae.video.description||null,video_url:Ae.video.video_url,video_type:Ae.video.video_type,duration:Ae.video.duration||null,thumbnail_url:Be,category_id:Ae.video.category_id||null,publish_date:Ae.video.publish_date?new Date(Ae.video.publish_date).toISOString():new Date().toISOString(),is_published:Ae.video.is_published,created_by:s==null?void 0:s.id};let Ke=Ae.videoId;if(Ke){const{error:Ze}=await U.from("academy_videos").update(qe).eq("id",Ke);if(Ze)throw Ze}else{const{data:Ze,error:Ue}=await U.from("academy_videos").insert(qe).select().single();if(Ue)throw Ue;Ke=Ze.id,cqs(Ae.video.title,Ze.id)}if(Ae.resourcesToDelete.length>0){const{error:Ze}=await U.from("academy_resources").delete().in("id",Ae.resourcesToDelete);if(Ze)throw Ze}for(let Ze=0;Ze0){const{error:Ze}=await U.from("academy_video_templates").insert(A.map(Ue=>({video_id:Ke,template_id:Ue})));if(Ze)throw Ze}},onSuccess:()=>{a.invalidateQueries({queryKey:["academy-videos-admin"]}),a.invalidateQueries({queryKey:["academy-videos"]}),Ee(),l(!1),r({title:o?"Video updated":"Video created"})},onError:Ae=>{r({title:"Error saving video",description:Ae.message,variant:"destructive"})}}),ve=yt({mutationFn:async Ae=>{const{error:Be}=await U.from("academy_videos").delete().eq("id",Ae);if(Be)throw Be},onSuccess:()=>{a.invalidateQueries({queryKey:["academy-videos-admin"]}),a.invalidateQueries({queryKey:["academy-videos"]}),r({title:"Video deleted"})},onError:Ae=>{r({title:"Error deleting video",description:Ae.message,variant:"destructive"})}}),ge=yt({mutationFn:async({id:Ae,is_published:Be})=>{const{error:qe}=await U.from("academy_videos").update({is_published:Be}).eq("id",Ae);if(qe)throw qe},onSuccess:()=>{a.invalidateQueries({queryKey:["academy-videos-admin"]}),a.invalidateQueries({queryKey:["academy-videos"]})},onError:Ae=>{r({title:"Error updating video",description:Ae.message,variant:"destructive"})}}),fe=async Ae=>{try{let Be=Ae.public_slug||null,qe=!!Ae.is_public;if(!Be||!qe){const Ze=(Ae.title||"video").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,60)||"video";if(!Be){let et=Ze;const{data:Qe}=await U.from("academy_videos").select("id").eq("public_slug",et).maybeSingle();Qe&&Qe.id!==Ae.id&&(et=`${Ze}-${Ae.id.slice(0,6)}`),Be=et}const{error:Ue}=await U.from("academy_videos").update({public_slug:Be,is_public:!0}).eq("id",Ae.id);if(Ue)throw Ue;a.invalidateQueries({queryKey:["academy-videos-admin"]})}const Ke=`${window.location.origin}/watch/${Be}`;await navigator.clipboard.writeText(Ke),r({title:"Public link copied",description:Ke})}catch(Be){r({title:"Could not copy link",description:Be.message,variant:"destructive"})}},je=async Ae=>{if(!await Yi("Disable the public teaser link for this video?"))return;const{error:Be}=await U.from("academy_videos").update({is_public:!1}).eq("id",Ae.id);if(Be){r({title:"Error",description:Be.message,variant:"destructive"});return}a.invalidateQueries({queryKey:["academy-videos-admin"]}),r({title:"Public link disabled"})},Ee=()=>{u({title:"",description:"",video_url:"",video_type:"bunny_stream",duration:"",category_id:"",publish_date:new Date().toISOString().split("T")[0],is_published:!1}),m(null),x(""),y([]),v([]),C([]),c(null),T([]),M(""),q(null),V(0),Q(!1),ce(null)},Me=async Ae=>{c(Ae),u({title:Ae.title,description:Ae.description||"",video_url:Ae.video_url,video_type:Ae.video_type,duration:Ae.duration||"",category_id:Ae.category_id||"",publish_date:Ae.publish_date?new Date(Ae.publish_date).toISOString().split("T")[0]:new Date().toISOString().split("T")[0],is_published:Ae.is_published}),x(Ae.thumbnail_url||""),v(Ae.resources||[]),y([]),C([]);const{data:Be}=await U.from("academy_video_templates").select("template_id").eq("video_id",Ae.id);T((Be||[]).map(qe=>qe.template_id)),l(!0)},De=Ae=>{var qe;const Be=(qe=Ae.target.files)==null?void 0:qe[0];Be&&(m(Be),x(URL.createObjectURL(Be)))},ze=Ae=>{const Be=Ae.target.files;if(Be){const qe=Array.from(Be).map(Ke=>({file:Ke,title:Ke.name.replace(/\.[^/.]+$/,"")}));y([...g,...qe])}Ae.target.value=""},ke=Ae=>{y(g.filter((Be,qe)=>qe!==Ae))},Xe=Ae=>{C([...N,Ae]),v(b.filter(Be=>Be.id!==Ae))},Se=async()=>{if(!B)return null;Q(!0),V(0);try{const{data:Ae,error:Be}=await U.functions.invoke("bunny-upload",{body:{action:"create",title:d.title||B.name}});if(Be)throw new Error(Be.message);const{videoId:qe,libraryId:Ke}=Ae;ce(qe);const{data:Ze,error:Ue}=await U.functions.invoke("bunny-upload",{body:{action:"upload-url",videoId:qe}});if(Ue)throw new Error(Ue.message);const et=new XMLHttpRequest;return await new Promise((Ge,nt)=>{et.upload.addEventListener("progress",ft=>{if(ft.lengthComputable){const lt=Math.round(ft.loaded/ft.total*100);V(lt)}}),et.addEventListener("load",()=>{et.status>=200&&et.status<300?Ge():nt(new Error(`Upload failed with status ${et.status}`))}),et.addEventListener("error",()=>nt(new Error("Upload failed"))),et.open("PUT",Ze.uploadUrl),et.setRequestHeader("AccessKey",Ze.apiKey),et.send(B)}),`https://player.mediadelivery.net/embed/${Ke}/${qe}`}catch(Ae){return console.error("Bunny upload error:",Ae),r({title:"Video upload failed",description:Ae instanceof Error?Ae.message:"Unknown error",variant:"destructive"}),null}finally{Q(!1)}},Re=async Ae=>{if(Ae.preventDefault(),!d.title.trim()){r({title:"Please enter a video title",variant:"destructive"});return}let Be=d.video_url;if(d.video_type==="bunny_stream"&&B&&!o){const qe=await Se();if(!qe)return;Be=qe}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"&&!B&&!d.video_url&&!o){r({title:"Please select a video file to upload",variant:"destructive"});return}he.mutate({video:{...d,video_url:Be},thumbnail:h,existingThumbnailUrl:(o==null?void 0:o.thumbnail_url)||null,videoId:o==null?void 0:o.id,newResources:g,resourcesToDelete:N})};return e.jsx(Ks,{title:"Manage Academy",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(hh,{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(_e,{children:[e.jsx(Bt,{className:"pb-2",children:e.jsx(Ut,{className:"text-sm font-medium text-muted-foreground",children:"Total Videos"})}),e.jsx(Oe,{children:e.jsx("div",{className:"text-2xl font-bold",children:ne.length})})]}),e.jsxs(_e,{children:[e.jsx(Bt,{className:"pb-2",children:e.jsx(Ut,{className:"text-sm font-medium text-muted-foreground",children:"Published"})}),e.jsx(Oe,{children:e.jsx("div",{className:"text-2xl font-bold",children:ne.filter(Ae=>Ae.is_published).length})})]}),e.jsxs(_e,{children:[e.jsx(Bt,{className:"pb-2",children:e.jsx(Ut,{className:"text-sm font-medium text-muted-foreground",children:"Public Teasers"})}),e.jsx(Oe,{children:e.jsx("div",{className:"text-2xl font-bold",children:ne.filter(Ae=>Ae.is_public).length})})]}),e.jsxs(_e,{children:[e.jsx(Bt,{className:"pb-2",children:e.jsx(Ut,{className:"text-sm font-medium text-muted-foreground",children:"Total Public Views"})}),e.jsx(Oe,{children:e.jsx("div",{className:"text-2xl font-bold",children:ne.reduce((Ae,Be)=>Ae+(Be.public_view_count||0),0).toLocaleString()})})]})]}),e.jsxs(Os,{open:i,onOpenChange:Ae=>{l(Ae),Ae||Ee()},children:[e.jsx(Ko,{asChild:!0,children:e.jsxs($,{className:"gap-2",children:[e.jsx(sn,{className:"h-4 w-4"}),"Add Video"]})}),e.jsxs(Rs,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsx(Us,{children:e.jsx(zs,{children:o?"Edit Video":"Add New Video"})}),e.jsxs("form",{onSubmit:Re,className:"space-y-6 pt-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"title",children:"Title *"}),e.jsx(be,{id:"title",value:d.title,onChange:Ae=>u({...d,title:Ae.target.value}),placeholder:"Video title",required:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Description"}),e.jsx(m2,{content:d.description,onChange:Ae=>u({...d,description:Ae}),placeholder:"Brief description of the video",minHeight:"120px"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Video Type"}),e.jsxs(vs,{value:d.video_type,onValueChange:Ae=>{u({...d,video_type:Ae,video_url:""}),q(null)},disabled:K,children:[e.jsx(gs,{children:e.jsx(bs,{})}),e.jsx(ys,{children:_qs.map(Ae=>e.jsx(Ye,{value:Ae.value,children:Ae.label},Ae.value))})]})]}),d.video_type==="bunny_stream"?e.jsxs("div",{className:"space-y-3",children:[e.jsxs(se,{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(be,{type:"file",accept:"video/*",onChange:Ae=>{var qe;const Be=(qe=Ae.target.files)==null?void 0:qe[0];Be&&q(Be)},disabled:K}),B&&e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(Xr,{className:"h-4 w-4"}),B.name," (",(B.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(Ht,{className:"h-4 w-4 animate-spin"}),e.jsx("span",{className:"text-sm",children:"Uploading to Bunny.net..."})]}),e.jsx(Ki,{value:W,className:"h-2"}),e.jsxs("p",{className:"text-xs text-muted-foreground text-right",children:[W,"%"]})]})]})]}):e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"video_url",children:"Video URL *"}),e.jsx(be,{id:"video_url",value:d.video_url,onChange:Ae=>u({...d,video_url:Ae.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(se,{htmlFor:"duration",children:"Duration"}),e.jsx(be,{id:"duration",value:d.duration,onChange:Ae=>u({...d,duration:Ae.target.value}),placeholder:"e.g., 45:30"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"publish_date",children:"Publish Date (go-live)"}),e.jsx(be,{id:"publish_date",type:"date",value:d.publish_date,onChange:Ae=>u({...d,publish_date:Ae.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(se,{children:"Category"}),I?e.jsxs("div",{className:"flex gap-2",children:[e.jsx(be,{value:P,onChange:Ae=>M(Ae.target.value),placeholder:"New category name",className:"flex-1"}),e.jsx($,{type:"button",size:"sm",onClick:()=>P.trim()&&le.mutate(P.trim()),disabled:le.isPending,children:"Add"}),e.jsx($,{type:"button",size:"sm",variant:"ghost",onClick:()=>{D(!1),M("")},children:e.jsx(pr,{className:"h-4 w-4"})})]}):e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(vs,{value:d.category_id,onValueChange:Ae=>u({...d,category_id:Ae}),children:[e.jsx(gs,{className:"flex-1",children:e.jsx(bs,{placeholder:"Select category"})}),e.jsx(ys,{children:ue.map(Ae=>e.jsx(Ye,{value:Ae.id,children:Ae.name},Ae.id))})]}),e.jsx($,{type:"button",variant:"outline",size:"sm",onClick:()=>D(!0),children:e.jsx(sn,{className:"h-4 w-4"})})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{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(be,{type:"file",accept:"image/*",onChange:De,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(se,{children:"Resource Files"}),e.jsx($,{type:"button",variant:"outline",size:"sm",asChild:!0,children:e.jsxs("label",{className:"cursor-pointer gap-1",children:[e.jsx(si,{className:"h-3 w-3"}),"Add Files",e.jsx("input",{type:"file",multiple:!0,accept:".pdf,.pptx,.ppt,.xlsx,.xls,.docx,.doc,.zip",onChange:ze,className:"hidden"})]})})]}),(b.length>0||g.length>0)&&e.jsxs("div",{className:"space-y-2 mt-2",children:[b.map(Ae=>e.jsxs("div",{className:"flex items-center gap-2 p-2 border rounded-md bg-muted/30",children:[e.jsx(Wr,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"flex-1 text-sm truncate",children:Ae.title}),e.jsx($e,{variant:"outline",className:"text-xs",children:Ae.file_type}),e.jsx($,{type:"button",variant:"ghost",size:"sm",onClick:()=>Xe(Ae.id),className:"text-destructive hover:text-destructive",children:e.jsx(pr,{className:"h-4 w-4"})})]},Ae.id)),g.map((Ae,Be)=>e.jsxs("div",{className:"flex items-center gap-2 p-2 border rounded-md bg-muted/30",children:[e.jsx(Wr,{className:"h-4 w-4 text-muted-foreground"}),e.jsx(be,{value:Ae.title,onChange:qe=>{const Ke=[...g];Ke[Be].title=qe.target.value,y(Ke)},className:"flex-1 h-8",placeholder:"Resource title"}),e.jsx($e,{variant:"secondary",className:"text-xs",children:"New"}),e.jsx($,{type:"button",variant:"ghost",size:"sm",onClick:()=>ke(Be),className:"text-destructive hover:text-destructive",children:e.jsx(pr,{className:"h-4 w-4"})})]},Be))]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Supported: PDF, PowerPoint, Excel, Word, ZIP"})]}),e.jsx(v8t,{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(Tn,{id:"is_published",checked:d.is_published,onCheckedChange:Ae=>u({...d,is_published:Ae})}),e.jsx(se,{htmlFor:"is_published",children:"Published"})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:d.is_published?d.publish_date>put?`Scheduled — goes live automatically on ${fut(d.publish_date)}.`:"Live now for members.":"Draft — hidden from members until you turn this on."})]}),e.jsxs(kr,{children:[e.jsx($,{type:"button",variant:"outline",onClick:()=>l(!1),disabled:K,children:"Cancel"}),e.jsx($,{type:"submit",disabled:he.isPending||K,children:K?e.jsxs(e.Fragment,{children:[e.jsx(Ht,{className:"h-4 w-4 mr-2 animate-spin"}),"Uploading..."]}):he.isPending?"Saving...":o?"Update Video":"Add Video"})]})]})]})]})]}),e.jsx(_e,{children:e.jsx(Oe,{className:"p-0",children:ee?e.jsx("div",{className:"flex justify-center py-8",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})}):ne.length===0?e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(Xr,{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(Va,{children:[e.jsx(Ha,{children:e.jsxs(hn,{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(Ga,{children:ne.map(Ae=>e.jsxs(hn,{children:[e.jsx(gt,{children:e.jsxs("div",{className:"flex items-center gap-3",children:[Ae.thumbnail_url?e.jsx("img",{src:Ae.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(Xr,{className:"h-4 w-4 text-muted-foreground"})}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:Ae.title}),e.jsx("p",{className:"text-xs text-muted-foreground capitalize",children:Ae.video_type.replace("_"," ")})]})]})}),e.jsx(gt,{children:Ae.category?e.jsx($e,{variant:"outline",children:Ae.category.name}):e.jsx("span",{className:"text-muted-foreground text-sm",children:"-"})}),e.jsx(gt,{children:Ae.duration||"-"}),e.jsx(gt,{children:Ae.resources&&Ae.resources.length>0?e.jsxs($e,{variant:"secondary",children:[Ae.resources.length," file(s)"]}):e.jsx("span",{className:"text-muted-foreground text-sm",children:"-"})}),e.jsx(gt,{children:fut(Ae.publish_date)}),e.jsx(gt,{children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Tn,{checked:Ae.is_published,onCheckedChange:Be=>ge.mutate({id:Ae.id,is_published:Be})}),Ae.is_published?Ae.publish_date.slice(0,10)>put?e.jsxs($e,{variant:"outline",className:"gap-1",children:[e.jsx(Hr,{className:"h-3 w-3"})," Scheduled"]}):e.jsx($e,{variant:"secondary",children:"Live"}):e.jsx($e,{variant:"outline",className:"text-muted-foreground",children:"Draft"})]})}),e.jsx(gt,{children:Ae.is_public?e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(ga,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"text-sm font-medium",children:(Ae.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($,{variant:"ghost",size:"sm",title:Ae.is_public?"Copy public teaser link":"Make public & copy teaser link",onClick:()=>fe(Ae),children:Ae.is_public?e.jsx(Ca,{className:"h-4 w-4 text-primary"}):e.jsx(vd,{className:"h-4 w-4"})}),Ae.is_public&&e.jsx($,{variant:"ghost",size:"sm",title:"Disable public link",onClick:()=>je(Ae),children:e.jsx(Gl,{className:"h-4 w-4 text-emerald-500"})}),e.jsx($,{variant:"ghost",size:"sm",onClick:()=>Me(Ae),children:e.jsx(Ya,{className:"h-4 w-4"})}),e.jsx($,{variant:"ghost",size:"sm",onClick:()=>ve.mutate(Ae.id),className:"text-destructive hover:text-destructive",children:e.jsx(Pn,{className:"h-4 w-4"})})]})})]},Ae.id))})]})})})]})})};function jqs(){var he,ve,ge;const s=ts(),[t,n]=oc(),[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}),[d,u]=j.useState(null),[h,m]=j.useState(""),[p,x]=j.useState([]),[g,y]=j.useState([]),[b,v]=j.useState([]),[N,C]=j.useState(null),{data:A,isLoading:T}=ht({queryKey:["resource-kits"],queryFn:async()=>{const{data:fe,error:je}=await U.from("resource_kits").select("*").order("publish_date",{ascending:!1});if(je)throw je;return fe}}),{data:P}=ht({queryKey:["resource-kit-files"],queryFn:async()=>{const{data:fe,error:je}=await U.from("resource_kit_files").select("*").order("sort_order",{ascending:!0});if(je)throw je;return fe}}),{data:M}=ht({queryKey:["resource-kit-links"],queryFn:async()=>{const{data:fe,error:je}=await U.from("resource_kit_links").select("*").order("sort_order",{ascending:!0});if(je)throw je;return fe}});j.useEffect(()=>{const fe=t.get("edit");if(fe&&A&&A.length>0&&P&&M){const je=A.find(Ee=>Ee.id===fe);je&&(D(je),n({},{replace:!0}))}},[A,P,M,t]);const I=()=>{c({name:"",description:"",publish_date:new Date().toISOString().split("T")[0],is_published:!1}),u(null),m(""),x([]),y([]),v([]),l(null)},D=async fe=>{l(fe),c({name:fe.name,description:fe.description||"",publish_date:fe.publish_date.split("T")[0],is_published:fe.is_published}),m(fe.featured_image_url||"");const je=(P==null?void 0:P.filter(De=>De.kit_id===fe.id))||[];x(je.map(De=>({id:De.id,name:De.name,file_url:De.file_url,file_type:De.file_type,file_size:De.file_size,sort_order:De.sort_order})));const Ee=(M==null?void 0:M.filter(De=>De.kit_id===fe.id))||[];y(Ee.map(De=>({id:De.id,title:De.title,canva_share_link:De.canva_share_link,sort_order:De.sort_order})));const{data:Me}=await U.from("resource_kit_templates").select("template_id").eq("kit_id",fe.id);v((Me||[]).map(De=>De.template_id)),a(!0)},B=fe=>{var Ee;const je=(Ee=fe.target.files)==null?void 0:Ee[0];je&&(u(je),m(URL.createObjectURL(je)))},q=()=>{x([...p,{name:"",file_url:"",sort_order:p.length}])},W=fe=>{x(p.filter((je,Ee)=>Ee!==fe))},V=(fe,je,Ee)=>{const Me=[...p];Me[fe]={...Me[fe],[je]:Ee},x(Me)},K=()=>{y([...g,{title:"",canva_share_link:"",sort_order:g.length}])},Q=fe=>{y(g.filter((je,Ee)=>Ee!==fe))},J=(fe,je,Ee)=>{const Me=[...g];Me[fe]={...Me[fe],[je]:Ee},y(Me)},ce=(fe,je)=>{var Me;const Ee=(Me=je.target.files)==null?void 0:Me[0];if(Ee){const De=[...p],ze=Ee.name.replace(/\.[^/.]+$/,"");De[fe]={...De[fe],file:Ee,file_type:Ee.type,file_size:Ee.size,name:De[fe].name||ze},x(De)}},ue=yt({mutationFn:async()=>{let fe=(i==null?void 0:i.featured_image_url)||null;if(d){const ze=d.name.split(".").pop(),ke=`${Date.now()}.${ze}`,{error:Xe}=await U.storage.from("resource-kits").upload(`featured/${ke}`,d);if(Xe)throw Xe;const{data:Se}=U.storage.from("resource-kits").getPublicUrl(`featured/${ke}`);fe=Se.publicUrl}const je={name:o.name,description:o.description||null,featured_image_url:fe,publish_date:o.publish_date,is_published:o.is_published};let Ee;const Me=!i,De=(i==null?void 0:i.is_published)||!1;if(i){const{error:ze}=await U.from("resource_kits").update(je).eq("id",i.id);if(ze)throw ze;Ee=i.id;const ke=(P==null?void 0:P.filter(qe=>qe.kit_id===i.id).map(qe=>qe.id))||[],Xe=p.filter(qe=>qe.id).map(qe=>qe.id),Se=ke.filter(qe=>!Xe.includes(qe));Se.length>0&&await U.from("resource_kit_files").delete().in("id",Se);const Re=(M==null?void 0:M.filter(qe=>qe.kit_id===i.id).map(qe=>qe.id))||[],Ae=g.filter(qe=>qe.id).map(qe=>qe.id),Be=Re.filter(qe=>!Ae.includes(qe));Be.length>0&&await U.from("resource_kit_links").delete().in("id",Be)}else{const{data:ze,error:ke}=await U.from("resource_kits").insert(je).select().single();if(ke)throw ke;Ee=ze.id}for(let ze=0;ze0){const{error:ze}=await U.from("resource_kit_templates").insert(b.map(ke=>({kit_id:Ee,template_id:ke})));if(ze)throw ze}return{kitId:Ee,kitName:o.name,isNewKit:Me,wasPublished:De,isPublished:o.is_published}},onSuccess:fe=>{s.invalidateQueries({queryKey:["resource-kits"]}),s.invalidateQueries({queryKey:["resource-kit-files"]}),s.invalidateQueries({queryKey:["resource-kit-links"]}),ae.success(i?"Resource kit updated":"Resource kit created"),fe.isPublished&&(fe.isNewKit||!fe.wasPublished)&&uqs(fe.kitName,fe.kitId),a(!1),I()},onError:fe=>{ae.error("Failed to save resource kit: "+fe.message)}}),ne=yt({mutationFn:async fe=>{const{error:je}=await U.from("resource_kits").delete().eq("id",fe);if(je)throw je},onSuccess:()=>{s.invalidateQueries({queryKey:["resource-kits"]}),s.invalidateQueries({queryKey:["resource-kit-files"]}),ae.success("Resource kit deleted")},onError:fe=>{ae.error("Failed to delete: "+fe.message)}}),ee=fe=>{if(fe.preventDefault(),!o.name){ae.error("Please enter a name");return}ue.mutate()},le=fe=>(P==null?void 0:P.filter(je=>je.kit_id===fe).length)||0;return e.jsx(Ks,{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(_e,{children:[e.jsx(Bt,{className:"pb-2",children:e.jsx(Ut,{className:"text-sm font-medium text-muted-foreground",children:"Total Kits"})}),e.jsx(Oe,{children:e.jsx("div",{className:"text-2xl font-bold",children:(A==null?void 0:A.length)||0})})]}),e.jsxs(_e,{children:[e.jsx(Bt,{className:"pb-2",children:e.jsx(Ut,{className:"text-sm font-medium text-muted-foreground",children:"Published"})}),e.jsx(Oe,{children:e.jsx("div",{className:"text-2xl font-bold",children:(A==null?void 0:A.filter(fe=>fe.is_published).length)||0})})]})]}),e.jsxs($,{onClick:()=>{I(),a(!0)},children:[e.jsx(sn,{className:"h-4 w-4 mr-2"}),"Add Resource Kit"]})]}),e.jsx(_e,{children:e.jsx(Oe,{className:"p-0",children:e.jsxs(Va,{children:[e.jsx(Ha,{children:e.jsxs(hn,{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(Ga,{children:T?e.jsx(hn,{children:e.jsx(gt,{colSpan:5,className:"text-center py-8",children:"Loading..."})}):(A==null?void 0:A.length)===0?e.jsx(hn,{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(fe=>e.jsxs(hn,{children:[e.jsx(gt,{children:e.jsxs("div",{className:"flex items-center gap-3",children:[fe.featured_image_url?e.jsx("img",{src:fe.featured_image_url,alt:fe.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(Tu,{className:"h-5 w-5 text-muted-foreground"})}),e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:fe.name}),fe.description&&e.jsx("div",{className:"text-sm text-muted-foreground line-clamp-1",children:fe.description})]})]})}),e.jsx(gt,{children:e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(Wr,{className:"h-4 w-4 text-muted-foreground"}),le(fe.id)]})}),e.jsx(gt,{children:Hs(new Date(fe.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 ${fe.is_published?"bg-green-100 text-green-800":"bg-yellow-100 text-yellow-800"}`,children:fe.is_published?"Published":"Draft"})}),e.jsx(gt,{className:"text-right",children:e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx($,{variant:"ghost",size:"icon",onClick:()=>{const je=(P==null?void 0:P.filter(Me=>Me.kit_id===fe.id))||[],Ee=(M==null?void 0:M.filter(Me=>Me.kit_id===fe.id))||[];C({...fe,files:je,links:Ee})},children:e.jsx(ga,{className:"h-4 w-4"})}),e.jsx($,{variant:"ghost",size:"icon",onClick:()=>D(fe),children:e.jsx(Ya,{className:"h-4 w-4"})}),e.jsx($,{variant:"ghost",size:"icon",onClick:async()=>{await Yi("Delete this resource kit?")&&ne.mutate(fe.id)},children:e.jsx(Pn,{className:"h-4 w-4 text-destructive"})})]})})]},fe.id))})]})})}),e.jsx(Os,{open:r,onOpenChange:a,children:e.jsxs(Rs,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsx(Us,{children:e.jsx(zs,{children:i?"Edit Resource Kit":"Add Resource Kit"})}),e.jsxs("form",{onSubmit:ee,className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{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(Tu,{className:"h-8 w-8 text-muted-foreground"})}),e.jsx(be,{type:"file",accept:"image/*",onChange:B})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"name",children:"Name *"}),e.jsx(be,{id:"name",value:o.name,onChange:fe=>c({...o,name:fe.target.value}),placeholder:"Resource Kit Name"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Description"}),e.jsx(m2,{content:o.description,onChange:fe=>c({...o,description:fe}),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(se,{htmlFor:"publish_date",children:"Publish Date"}),e.jsx(be,{id:"publish_date",type:"date",value:o.publish_date,onChange:fe=>c({...o,publish_date:fe.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Published"}),e.jsxs("div",{className:"flex items-center space-x-2 pt-2",children:[e.jsx(Tn,{checked:o.is_published,onCheckedChange:fe=>c({...o,is_published:fe})}),e.jsx("span",{className:"text-sm text-muted-foreground",children:o.is_published?"Visible to agents":"Hidden from agents"})]})]})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsx(se,{children:"Resource Files"}),e.jsxs($,{type:"button",variant:"outline",size:"sm",onClick:q,children:[e.jsx(sn,{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((fe,je)=>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 ",je+1]}),e.jsx($,{type:"button",variant:"ghost",size:"icon",className:"h-6 w-6",onClick:()=>W(je),children:e.jsx(pr,{className:"h-4 w-4"})})]}),e.jsx(be,{placeholder:"File name (e.g., Getting Started Guide)",value:fe.name,onChange:Ee=>V(je,"name",Ee.target.value)}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(be,{type:"file",onChange:Ee=>ce(je,Ee),className:"flex-1"}),fe.file_url&&!fe.file&&e.jsx("a",{href:fe.file_url,target:"_blank",rel:"noopener noreferrer",className:"text-sm text-primary hover:underline whitespace-nowrap",children:"Current file"}),fe.file&&e.jsx("span",{className:"text-sm text-green-600 whitespace-nowrap",children:"New file selected"})]})]},je))})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsx(se,{children:"Canva Links"}),e.jsxs($,{type:"button",variant:"outline",size:"sm",onClick:K,children:[e.jsx(sn,{className:"h-4 w-4 mr-1"}),"Add Canva Link"]})]}),g.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:g.map((fe,je)=>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 ",je+1]}),e.jsx($,{type:"button",variant:"ghost",size:"icon",className:"h-6 w-6",onClick:()=>Q(je),children:e.jsx(pr,{className:"h-4 w-4"})})]}),e.jsx(be,{placeholder:"Link title (e.g., Social Media Post Template)",value:fe.title,onChange:Ee=>J(je,"title",Ee.target.value)}),e.jsx(be,{placeholder:"Canva share link (e.g., https://www.canva.com/design/...)",value:fe.canva_share_link,onChange:Ee=>J(je,"canva_share_link",Ee.target.value)})]},je))})]}),e.jsx(v8t,{selectedTemplateIds:b,onChange:v}),e.jsxs("div",{className:"flex justify-end gap-2 pt-4",children:[e.jsx($,{type:"button",variant:"outline",onClick:()=>a(!1),children:"Cancel"}),e.jsx($,{type:"submit",disabled:ue.isPending,children:ue.isPending?"Saving...":i?"Update":"Create"})]})]})]})}),e.jsx(Os,{open:!!N,onOpenChange:()=>C(null),children:e.jsxs(Rs,{className:"max-w-lg",children:[e.jsx(Us,{children:e.jsx(zs,{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 (",((he=N==null?void 0:N.files)==null?void 0:he.length)||0,")"]}),((ve=N==null?void 0:N.files)==null?void 0:ve.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:(ge=N==null?void 0:N.files)==null?void 0:ge.map(fe=>e.jsxs("a",{href:fe.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(Wr,{className:"h-4 w-4 text-primary"}),e.jsx("span",{className:"text-sm",children:fe.name})]},fe.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(fe=>e.jsxs("a",{href:fe.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(kc,{className:"h-4 w-4 text-primary"}),e.jsx("span",{className:"text-sm",children:fe.title})]},fe.id))})]})]})]})})]})})}const Nqs=()=>{const{user:s}=_s(),{toast:t}=gi(),n=ts(),[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:x}=ht({queryKey:["social-swag-admin"],queryFn:async()=>{const{data:M,error:I}=await U.from("social_swag").select("*").order("publish_date",{ascending:!1});if(I)throw I;const{data:D,error:B}=await U.from("social_swag_links").select("*").order("sort_order");if(B)throw B;return M.map(W=>({...W,links:(D==null?void 0:D.filter(V=>V.swag_id===W.id))||[]}))}}),g=yt({mutationFn:async M=>{let I=M.existingImageUrl;if(M.image){const K=M.image.name.split(".").pop(),Q=`${Date.now()}-${Math.random().toString(36).substring(7)}.${K}`,{error:J}=await U.storage.from("template-previews").upload(Q,M.image);if(J)throw J;const{data:ce}=U.storage.from("template-previews").getPublicUrl(Q);I=ce.publicUrl}const D={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 B=M.itemId;const q=!B,W=(i==null?void 0:i.is_published)||!1;if(B){const{error:K}=await U.from("social_swag").update(D).eq("id",B);if(K)throw K;await U.from("social_swag_links").delete().eq("swag_id",B)}else{const{data:K,error:Q}=await U.from("social_swag").insert(D).select().single();if(Q)throw Q;B=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((J,ce)=>({swag_id:B,title:J.title.trim(),canva_share_link:J.canva_share_link.trim(),sort_order:ce})),{error:Q}=await U.from("social_swag_links").insert(K);if(Q)throw Q}return{itemId:B,itemTitle:M.item.title,isNewItem:q,wasPublished:W,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)&&h9e(M.itemTitle,M.itemId),a(!1),b()},onError:M=>{t({title:"Error saving item",description:M.message,variant:"destructive"})}}),y=yt({mutationFn:async M=>{const{error:I}=await U.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"})}}),b=()=>{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)},v=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 D;const I=(D=M.target.files)==null?void 0:D[0];I&&(u(I),m(URL.createObjectURL(I)))},C=()=>{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((D,B)=>B!==M);c({...o,links:I})},T=(M,I,D)=>{const B=[...o.links];B[M]={...B[M],[I]:D},c({...o,links:B})},P=M=>{if(M.preventDefault(),!o.title.trim()){t({title:"Title is required",variant:"destructive"});return}g.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(Ks,{title:"Manage Social Swag",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(hh,{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(_e,{children:[e.jsx(Bt,{className:"pb-2",children:e.jsx(Ut,{className:"text-sm font-medium text-muted-foreground",children:"Total Items"})}),e.jsx(Oe,{children:e.jsx("div",{className:"text-2xl font-bold",children:p.length})})]}),e.jsxs(_e,{children:[e.jsx(Bt,{className:"pb-2",children:e.jsx(Ut,{className:"text-sm font-medium text-muted-foreground",children:"Published"})}),e.jsx(Oe,{children:e.jsx("div",{className:"text-2xl font-bold",children:p.filter(M=>M.is_published).length})})]})]}),e.jsxs(Os,{open:r,onOpenChange:M=>{a(M),M||b()},children:[e.jsx(Ko,{asChild:!0,children:e.jsxs($,{className:"gap-2",children:[e.jsx(sn,{className:"h-4 w-4"}),"Add Item"]})}),e.jsxs(Rs,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsx(Us,{children:e.jsx(zs,{children:i?"Edit Item":"Add New Item"})}),e.jsxs("form",{onSubmit:P,className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"title",children:"Title *"}),e.jsx(be,{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(se,{children:"Description"}),e.jsx(m2,{content:o.description,onChange:M=>c({...o,description:M}),placeholder:"Enter description",minHeight:"120px"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"publish_date",children:"Publish Date"}),e.jsx(be,{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(Tn,{id:"is_published",checked:o.is_published,onCheckedChange:M=>c({...o,is_published:M})}),e.jsx(se,{htmlFor:"is_published",children:"Published"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Preview Image"}),h?e.jsxs("div",{className:"relative",children:[e.jsx("img",{src:h,alt:"Preview",className:"w-full max-h-48 object-contain rounded-lg border"}),e.jsx($,{type:"button",variant:"destructive",size:"icon",className:"absolute top-2 right-2 h-6 w-6",onClick:()=>{u(null),m("")},children:e.jsx(pr,{className:"h-3 w-3"})})]}):e.jsxs("div",{className:"border-2 border-dashed rounded-lg p-4 text-center",children:[e.jsx(Jl,{className:"h-8 w-8 mx-auto text-muted-foreground mb-2"}),e.jsx(be,{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(se,{children:"Canva Links"}),e.jsxs($,{type:"button",variant:"outline",size:"sm",onClick:C,children:[e.jsx(sn,{className:"h-3 w-3 mr-1"}),"Add Link"]})]}),o.links.map((M,I)=>e.jsx(_e,{children:e.jsxs(Oe,{className:"pt-4 pb-4 space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("span",{className:"text-sm font-medium text-muted-foreground",children:["Link ",I+1]}),o.links.length>1&&e.jsx($,{type:"button",variant:"ghost",size:"icon",className:"h-6 w-6 ml-auto",onClick:()=>A(I),children:e.jsx(pr,{className:"h-3 w-3"})})]}),e.jsx(be,{placeholder:"Link title (e.g., Instagram Post)",value:M.title,onChange:D=>T(I,"title",D.target.value)}),e.jsx(be,{placeholder:"Canva share link",value:M.canva_share_link,onChange:D=>T(I,"canva_share_link",D.target.value)})]})},I))]}),e.jsxs("div",{className:"flex justify-end gap-2 pt-4",children:[e.jsx($,{type:"button",variant:"outline",onClick:()=>a(!1),children:"Cancel"}),e.jsx($,{type:"submit",disabled:g.isPending,children:g.isPending?"Saving...":i?"Update":"Create"})]})]})]})]})]}),e.jsx(_e,{children:e.jsx(Oe,{className:"p-0",children:x?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(Va,{children:[e.jsx(Ha,{children:e.jsxs(hn,{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(Ga,{children:p.map(M=>{var I;return e.jsxs(hn,{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(Jl,{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($e,{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($,{variant:"ghost",size:"icon",onClick:()=>window.open(`/social-swag/${M.id}`,"_blank"),children:e.jsx(ga,{className:"h-4 w-4"})}),e.jsx($,{variant:"ghost",size:"icon",onClick:()=>v(M),children:e.jsx(Ya,{className:"h-4 w-4"})}),e.jsx($,{variant:"ghost",size:"icon",onClick:async()=>{await Yi("Are you sure you want to delete this item?")&&y.mutate(M.id)},children:e.jsx(Pn,{className:"h-4 w-4"})})]})})]},M.id)})})]})})})]})})};function kqs(){for(var s=arguments.length,t=new Array(s),n=0;nr=>{t.forEach(a=>a(r))},t)}const IAe=typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u";function $q(s){const t=Object.prototype.toString.call(s);return t==="[object Window]"||t==="[object global]"}function WWe(s){return"nodeType"in s}function Gb(s){var t,n;return s?$q(s)?s:WWe(s)&&(t=(n=s.ownerDocument)==null?void 0:n.defaultView)!=null?t:window:window}function KWe(s){const{Document:t}=Gb(s);return s instanceof t}function Ree(s){return $q(s)?!1:s instanceof Gb(s).HTMLElement}function b8t(s){return s instanceof Gb(s).SVGElement}function Uq(s){return s?$q(s)?s.document:WWe(s)?KWe(s)?s:Ree(s)||b8t(s)?s.ownerDocument:document:document:document}const N5=IAe?j.useLayoutEffect:j.useEffect;function YWe(s){const t=j.useRef(s);return N5(()=>{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 mX(s,t){t===void 0&&(t=[s]);const n=j.useRef(s);return N5(()=>{n.current!==s&&(n.current=s)},t),n}function Oee(s,t){const n=j.useRef();return j.useMemo(()=>{const r=s(n.current);return n.current=r,r},[...t])}function n5e(s){const t=YWe(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 m9e(s){const t=j.useRef();return j.useEffect(()=>{t.current=s},[s]),t.current}let kIe={};function Fee(s,t){return j.useMemo(()=>{if(t)return t;const n=kIe[s]==null?0:kIe[s]+1;return kIe[s]=n,s+"-"+n},[s,t])}function _8t(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 oB=_8t(1),pX=_8t(-1);function Cqs(s){return"clientX"in s&&"clientY"in s}function ZWe(s){if(!s)return!1;const{KeyboardEvent:t}=Gb(s.target);return t&&s instanceof t}function Aqs(s){if(!s)return!1;const{TouchEvent:t}=Gb(s.target);return t&&s instanceof t}function p9e(s){if(Aqs(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 Cqs(s)?{x:s.clientX,y:s.clientY}:null}const l6=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[l6.Translate.toString(s),l6.Scale.toString(s)].join(" ")}},Transition:{toString(s){let{property:t,duration:n,easing:r}=s;return t+" "+n+"ms "+r}}}),xut="a,frame,iframe,input:not([type=hidden]):not(:disabled),select:not(:disabled),textarea:not(:disabled),button:not(:disabled),*[tabindex]";function Eqs(s){return s.matches(xut)?s:s.querySelector(xut)}const Tqs={display:"none"};function Mqs(s){let{id:t,value:n}=s;return It.createElement("div",{id:t,style:Tqs},n)}function Lqs(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 It.createElement("div",{id:t,style:a,role:"status","aria-live":r,"aria-atomic":!0},n)}function Pqs(){const[s,t]=j.useState("");return{announce:j.useCallback(r=>{r!=null&&t(r)},[]),announcement:s}}const w8t=j.createContext(null);function Iqs(s){const t=j.useContext(w8t);j.useEffect(()=>{if(!t)throw new Error("useDndMonitor must be used within a children of ");return t(s)},[s,t])}function Dqs(){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 Rqs={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. `},Oqs={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 Fqs(s){let{announcements:t=Oqs,container:n,hiddenTextDescribedById:r,screenReaderInstructions:a=Rqs}=s;const{announce:i,announcement:l}=Pqs(),o=Fee("DndLiveRegion"),[c,d]=j.useState(!1);if(j.useEffect(()=>{d(!0)},[]),Iqs(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=It.createElement(It.Fragment,null,It.createElement(Mqs,{id:r,value:a.draggable}),It.createElement(Lqs,{id:o,announcement:l}));return n?n1.createPortal(u,n):u}var dg;(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"})(dg||(dg={}));function r5e(){}function pU(s,t){return j.useMemo(()=>({sensor:s,options:t??{}}),[s,t])}function DAe(){for(var s=arguments.length,t=new Array(s),n=0;n[...t].filter(r=>r!=null),[...t])}const KN=Object.freeze({x:0,y:0});function j8t(s,t){return Math.sqrt(Math.pow(s.x-t.x,2)+Math.pow(s.y-t.y,2))}function N8t(s,t){let{data:{value:n}}=s,{data:{value:r}}=t;return n-r}function zqs(s,t){let{data:{value:n}}=s,{data:{value:r}}=t;return r-n}function gut(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 k8t(s,t){if(!s||s.length===0)return null;const[n]=s;return n[t]}function yut(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 RAe=s=>{let{collisionRect:t,droppableRects:n,droppableContainers:r}=s;const a=yut(t,t.left,t.top),i=[];for(const l of r){const{id:o}=l,c=n.get(o);if(c){const d=j8t(yut(c),a);i.push({id:o,data:{droppableContainer:l,value:d}})}}return i.sort(N8t)},Bqs=s=>{let{collisionRect:t,droppableRects:n,droppableContainers:r}=s;const a=gut(t),i=[];for(const l of r){const{id:o}=l,c=n.get(o);if(c){const d=gut(c),u=a.reduce((m,p,x)=>m+j8t(d[x],p),0),h=Number((u/4).toFixed(4));i.push({id:o,data:{droppableContainer:l,value:h}})}}return i.sort(N8t)};function $qs(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=$qs(o,t);c>0&&a.push({id:l,data:{droppableContainer:i,value:c}})}}return a.sort(zqs)};function qqs(s,t,n){return{...s,scaleX:t&&n?t.width/n.width:1,scaleY:t&&n?t.height/n.height:1}}function S8t(s,t){return s&&t?{x:s.left-t.left,y:s.top-t.top}:KN}function Vqs(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 Hqs=Vqs(1);function Gqs(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 Wqs(s,t,n){const r=Gqs(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 Kqs={ignoreTransform:!1};function qq(s,t){t===void 0&&(t=Kqs);let n=s.getBoundingClientRect();if(t.ignoreTransform){const{transform:d,transformOrigin:u}=Gb(s).getComputedStyle(s);d&&(n=Wqs(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 vut(s){return qq(s,{ignoreTransform:!0})}function Yqs(s){const t=s.innerWidth,n=s.innerHeight;return{top:0,left:0,right:t,bottom:n,width:t,height:n}}function Zqs(s,t){return t===void 0&&(t=Gb(s).getComputedStyle(s)),t.position==="fixed"}function Xqs(s,t){t===void 0&&(t=Gb(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 OAe(s,t){const n=[];function r(a){if(t!=null&&n.length>=t||!a)return n;if(KWe(a)&&a.scrollingElement!=null&&!n.includes(a.scrollingElement))return n.push(a.scrollingElement),n;if(!Ree(a)||b8t(a)||n.includes(a))return n;const i=Gb(s).getComputedStyle(a);return a!==s&&Xqs(a,i)&&n.push(a),Zqs(a,i)?n:r(a.parentNode)}return s?r(s):n}function C8t(s){const[t]=OAe(s,1);return t??null}function SIe(s){return!IAe||!s?null:$q(s)?s:WWe(s)?KWe(s)||s===Uq(s).scrollingElement?window:Ree(s)?s:null:null}function A8t(s){return $q(s)?s.scrollX:s.scrollLeft}function E8t(s){return $q(s)?s.scrollY:s.scrollTop}function f9e(s){return{x:A8t(s),y:E8t(s)}}var u0;(function(s){s[s.Forward=1]="Forward",s[s.Backward=-1]="Backward"})(u0||(u0={}));function T8t(s){return!IAe||!s?!1:s===document.scrollingElement}function M8t(s){const t={x:0,y:0},n=T8t(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 Qqs={x:.2,y:.2};function Jqs(s,t,n,r,a){let{top:i,left:l,right:o,bottom:c}=n;r===void 0&&(r=10),a===void 0&&(a=Qqs);const{isTop:d,isBottom:u,isLeft:h,isRight:m}=M8t(s),p={x:0,y:0},x={x:0,y:0},g={height:t.height*a.y,width:t.width*a.x};return!d&&i<=t.top+g.height?(p.y=u0.Backward,x.y=r*Math.abs((t.top+g.height-i)/g.height)):!u&&c>=t.bottom-g.height&&(p.y=u0.Forward,x.y=r*Math.abs((t.bottom-g.height-c)/g.height)),!m&&o>=t.right-g.width?(p.x=u0.Forward,x.x=r*Math.abs((t.right-g.width-o)/g.width)):!h&&l<=t.left+g.width&&(p.x=u0.Backward,x.x=r*Math.abs((t.left+g.width-l)/g.width)),{direction:p,speed:x}}function eVs(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 L8t(s){return s.reduce((t,n)=>oB(t,f9e(n)),KN)}function tVs(s){return s.reduce((t,n)=>t+A8t(n),0)}function sVs(s){return s.reduce((t,n)=>t+E8t(n),0)}function nVs(s,t){if(t===void 0&&(t=qq),!s)return;const{top:n,left:r,bottom:a,right:i}=t(s);C8t(s)&&(a<=0||i<=0||n>=window.innerHeight||r>=window.innerWidth)&&s.scrollIntoView({block:"center",inline:"center"})}const rVs=[["x",["left","right"],tVs],["y",["top","bottom"],sVs]];class XWe{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=OAe(n),a=L8t(r);this.rect={...t},this.width=t.width,this.height=t.height;for(const[i,l,o]of rVs)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 OY{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 aVs(s){const{EventTarget:t}=Gb(s);return s instanceof t?s:Uq(s)}function CIe(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 wj;(function(s){s.Click="click",s.DragStart="dragstart",s.Keydown="keydown",s.ContextMenu="contextmenu",s.Resize="resize",s.SelectionChange="selectionchange",s.VisibilityChange="visibilitychange"})(wj||(wj={}));function but(s){s.preventDefault()}function iVs(s){s.stopPropagation()}var pd;(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"})(pd||(pd={}));const P8t={start:[pd.Space,pd.Enter],cancel:[pd.Esc],end:[pd.Space,pd.Enter,pd.Tab]},oVs=(s,t)=>{let{currentCoordinates:n}=t;switch(s.code){case pd.Right:return{...n,x:n.x+25};case pd.Left:return{...n,x:n.x-25};case pd.Down:return{...n,y:n.y+25};case pd.Up:return{...n,y:n.y-25}}};class FAe{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 OY(Uq(n)),this.windowListeners=new OY(Gb(n)),this.handleKeyDown=this.handleKeyDown.bind(this),this.handleCancel=this.handleCancel.bind(this),this.attach()}attach(){this.handleStart(),this.windowListeners.add(wj.Resize,this.handleCancel),this.windowListeners.add(wj.VisibilityChange,this.handleCancel),setTimeout(()=>this.listeners.add(wj.Keydown,this.handleKeyDown))}handleStart(){const{activeNode:t,onStart:n}=this.props,r=t.node.current;r&&nVs(r),n(KN)}handleKeyDown(t){if(ZWe(t)){const{active:n,context:r,options:a}=this.props,{keyboardCodes:i=P8t,coordinateGetter:l=oVs,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}:KN;this.referenceCoordinates||(this.referenceCoordinates=u);const h=l(t,{active:n,context:r.current,currentCoordinates:u});if(h){const m=pX(h,u),p={x:0,y:0},{scrollableAncestors:x}=r.current;for(const g of x){const y=t.code,{isTop:b,isRight:v,isLeft:N,isBottom:C,maxScroll:A,minScroll:T}=M8t(g),P=eVs(g),M={x:Math.min(y===pd.Right?P.right-P.width/2:P.right,Math.max(y===pd.Right?P.left:P.left+P.width/2,h.x)),y:Math.min(y===pd.Down?P.bottom-P.height/2:P.bottom,Math.max(y===pd.Down?P.top:P.top+P.height/2,h.y))},I=y===pd.Right&&!v||y===pd.Left&&!N,D=y===pd.Down&&!C||y===pd.Up&&!b;if(I&&M.x!==h.x){const B=g.scrollLeft+m.x,q=y===pd.Right&&B<=A.x||y===pd.Left&&B>=T.x;if(q&&!m.y){g.scrollTo({left:B,behavior:o});return}q?p.x=g.scrollLeft-B:p.x=y===pd.Right?g.scrollLeft-A.x:g.scrollLeft-T.x,p.x&&g.scrollBy({left:-p.x,behavior:o});break}else if(D&&M.y!==h.y){const B=g.scrollTop+m.y,q=y===pd.Down&&B<=A.y||y===pd.Up&&B>=T.y;if(q&&!m.x){g.scrollTo({top:B,behavior:o});return}q?p.y=g.scrollTop-B:p.y=y===pd.Down?g.scrollTop-A.y:g.scrollTop-T.y,p.y&&g.scrollBy({top:-p.y,behavior:o});break}}this.handleMove(t,oB(pX(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()}}FAe.activators=[{eventName:"onKeyDown",handler:(s,t,n)=>{let{keyboardCodes:r=P8t,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 _ut(s){return!!(s&&"distance"in s)}function wut(s){return!!(s&&"delay"in s)}class QWe{constructor(t,n,r){var a;r===void 0&&(r=aVs(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=Uq(l),this.documentListeners=new OY(this.document),this.listeners=new OY(r),this.windowListeners=new OY(Gb(l)),this.initialCoordinates=(a=p9e(i))!=null?a:KN,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(wj.Resize,this.handleCancel),this.windowListeners.add(wj.DragStart,but),this.windowListeners.add(wj.VisibilityChange,this.handleCancel),this.windowListeners.add(wj.ContextMenu,but),this.documentListeners.add(wj.Keydown,this.handleKeydown),n){if(r!=null&&r({event:this.props.event,activeNode:this.props.activeNode,options:this.props.options}))return this.handleStart();if(wut(n)){this.timeoutId=setTimeout(this.handleStart,n.delay),this.handlePending(n);return}if(_ut(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(wj.Click,iVs,{capture:!0}),this.removeTextSelection(),this.documentListeners.add(wj.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=p9e(t))!=null?n:KN,d=pX(a,c);if(!r&&o){if(_ut(o)){if(o.tolerance!=null&&CIe(d,o.tolerance))return this.handleCancel();if(CIe(d,o.distance))return this.handleStart()}if(wut(o)&&CIe(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===pd.Esc&&this.handleCancel()}removeTextSelection(){var t;(t=this.document.getSelection())==null||t.removeAllRanges()}}const lVs={cancel:{name:"pointercancel"},move:{name:"pointermove"},end:{name:"pointerup"}};class Vq extends QWe{constructor(t){const{event:n}=t,r=Uq(n.target);super(t,lVs,r)}}Vq.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 cVs={move:{name:"mousemove"},end:{name:"mouseup"}};var x9e;(function(s){s[s.RightClick=2]="RightClick"})(x9e||(x9e={}));class dVs extends QWe{constructor(t){super(t,cVs,Uq(t.event.target))}}dVs.activators=[{eventName:"onMouseDown",handler:(s,t)=>{let{nativeEvent:n}=s,{onActivation:r}=t;return n.button===x9e.RightClick?!1:(r==null||r({event:n}),!0)}}];const AIe={cancel:{name:"touchcancel"},move:{name:"touchmove"},end:{name:"touchend"}};class uVs extends QWe{constructor(t){super(t,AIe)}static setup(){return window.addEventListener(AIe.move.name,t,{capture:!1,passive:!1}),function(){window.removeEventListener(AIe.move.name,t)};function t(){}}}uVs.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 FY;(function(s){s[s.Pointer=0]="Pointer",s[s.DraggableRect=1]="DraggableRect"})(FY||(FY={}));var a5e;(function(s){s[s.TreeOrder=0]="TreeOrder",s[s.ReversedTreeOrder=1]="ReversedTreeOrder"})(a5e||(a5e={}));function hVs(s){let{acceleration:t,activator:n=FY.Pointer,canScroll:r,draggingRect:a,enabled:i,interval:l=5,order:o=a5e.TreeOrder,pointerCoordinates:c,scrollableAncestors:d,scrollableAncestorRects:u,delta:h,threshold:m}=s;const p=pVs({delta:h,disabled:!i}),[x,g]=Sqs(),y=j.useRef({x:0,y:0}),b=j.useRef({x:0,y:0}),v=j.useMemo(()=>{switch(n){case FY.Pointer:return c?{top:c.y,bottom:c.y,left:c.x,right:c.x}:null;case FY.DraggableRect:return a}},[n,a,c]),N=j.useRef(null),C=j.useCallback(()=>{const T=N.current;if(!T)return;const P=y.current.x*b.current.x,M=y.current.y*b.current.y;T.scrollBy(P,M)},[]),A=j.useMemo(()=>o===a5e.TreeOrder?[...d].reverse():d,[o,d]);j.useEffect(()=>{if(!i||!d.length||!v){g();return}for(const T of A){if((r==null?void 0:r(T))===!1)continue;const P=d.indexOf(T),M=u[P];if(!M)continue;const{direction:I,speed:D}=Jqs(T,M,v,t,m);for(const B of["x","y"])p[B][I[B]]||(D[B]=0,I[B]=0);if(D.x>0||D.y>0){g(),N.current=T,x(C,l),y.current=D,b.current=I;return}}y.current={x:0,y:0},b.current={x:0,y:0},g()},[t,C,r,g,i,l,JSON.stringify(v),JSON.stringify(p),x,d,A,u,JSON.stringify(m)])}const mVs={x:{[u0.Backward]:!1,[u0.Forward]:!1},y:{[u0.Backward]:!1,[u0.Forward]:!1}};function pVs(s){let{delta:t,disabled:n}=s;const r=m9e(t);return Oee(a=>{if(n||!r||!a)return mVs;const i={x:Math.sign(t.x-r.x),y:Math.sign(t.y-r.y)};return{x:{[u0.Backward]:a.x[u0.Backward]||i.x===-1,[u0.Forward]:a.x[u0.Forward]||i.x===1},y:{[u0.Backward]:a.y[u0.Backward]||i.y===-1,[u0.Forward]:a.y[u0.Forward]||i.y===1}}},[n,t,r])}function fVs(s,t){const n=t!=null?s.get(t):void 0,r=n?n.node.current:null;return Oee(a=>{var i;return t==null?null:(i=r??a)!=null?i:null},[r,t])}function xVs(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 fX;(function(s){s[s.Always=0]="Always",s[s.BeforeDragging=1]="BeforeDragging",s[s.WhileDragging=2]="WhileDragging"})(fX||(fX={}));var g9e;(function(s){s.Optimized="optimized"})(g9e||(g9e={}));const jut=new Map;function gVs(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=mX(h),p=j.useCallback(function(b){b===void 0&&(b=[]),!m.current&&l(v=>v===null?b:v.concat(b.filter(N=>!v.includes(N))))},[m]),x=j.useRef(null),g=Oee(b=>{if(h&&!n)return jut;if(!b||b===jut||u.current!==s||i!=null){const v=new Map;for(let N of s){if(!N)continue;if(i&&i.length>0&&!i.includes(N.id)&&N.rect.current){v.set(N.id,N.rect.current);continue}const C=N.node.current,A=C?new XWe(c(C),C):null;N.rect.current=A,A&&v.set(N.id,A)}return v}return b},[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"||x.current!==null||(x.current=setTimeout(()=>{p(),x.current=null},o))},[o,h,p,...r]),{droppableRects:g,measureDroppableContainers:p,measuringScheduled:i!=null};function y(){switch(d){case fX.Always:return!1;case fX.BeforeDragging:return n;default:return!n}}}function I8t(s,t){return Oee(n=>s?n||(typeof t=="function"?t(s):s):null,[t,s])}function yVs(s,t){return I8t(s,t)}function vVs(s){let{callback:t,disabled:n}=s;const r=YWe(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 zAe(s){let{callback:t,disabled:n}=s;const r=YWe(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 bVs(s){return new XWe(qq(s),s)}function Nut(s,t,n){t===void 0&&(t=bVs);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=vVs({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=zAe({callback:i});return N5(()=>{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 _Vs(s){const t=I8t(s);return S8t(s,t)}const kut=[];function wVs(s){const t=j.useRef(s),n=Oee(r=>s?r&&r!==kut&&s&&t.current&&s.parentNode===t.current.parentNode?r:OAe(s):kut,[s]);return j.useEffect(()=>{t.current=s},[s]),n}function jVs(s){const[t,n]=j.useState(null),r=j.useRef(s),a=j.useCallback(i=>{const l=SIe(i.target);l&&n(o=>o?(o.set(l,f9e(l)),new Map(o)):null)},[]);return j.useEffect(()=>{const i=r.current;if(s!==i){l(i);const o=s.map(c=>{const d=SIe(c);return d?(d.addEventListener("scroll",a,{passive:!0}),[d,f9e(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=SIe(c);d==null||d.removeEventListener("scroll",a)})}},[a,s]),j.useMemo(()=>s.length?t?Array.from(t.values()).reduce((i,l)=>oB(i,l),KN):L8t(s):KN,[s,t])}function Sut(s,t){t===void 0&&(t=[]);const n=j.useRef(null);return j.useEffect(()=>{n.current=null},t),j.useEffect(()=>{const r=s!==KN;r&&!n.current&&(n.current=s),!r&&n.current&&(n.current=null)},[s]),n.current?pX(s,n.current):KN}function NVs(s){j.useEffect(()=>{if(!IAe)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 kVs(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 D8t(s){return j.useMemo(()=>s?Yqs(s):null,[s])}const Cut=[];function SVs(s,t){t===void 0&&(t=qq);const[n]=s,r=D8t(n?Gb(n):null),[a,i]=j.useState(Cut);function l(){i(()=>s.length?s.map(c=>T8t(c)?r:new XWe(t(c),c)):Cut)}const o=zAe({callback:l});return N5(()=>{o==null||o.disconnect(),l(),s.forEach(c=>o==null?void 0:o.observe(c))},[s]),a}function CVs(s){if(!s)return null;if(s.children.length>1)return s;const t=s.children[0];return Ree(t)?t:s}function AVs(s){let{measure:t}=s;const[n,r]=j.useState(null),a=j.useCallback(d=>{for(const{target:u}of d)if(Ree(u)){r(h=>{const m=t(u);return h?{...h,width:m.width,height:m.height}:m});break}},[t]),i=zAe({callback:a}),l=j.useCallback(d=>{const u=CVs(d);i==null||i.disconnect(),u&&(i==null||i.observe(u)),r(u?t(u):null)},[t,i]),[o,c]=n5e(l);return j.useMemo(()=>({nodeRef:o,rect:n,setRef:c}),[n,o,c])}const EVs=[{sensor:Vq,options:{}},{sensor:FAe,options:{}}],TVs={current:{}},$2e={draggable:{measure:vut},droppable:{measure:vut,strategy:fX.WhileDragging,frequency:g9e.Optimized},dragOverlay:{measure:qq}};class zY 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 MVs={activatorEvent:null,active:null,activeNode:null,activeNodeRect:null,collisions:null,containerNodeRect:null,draggableNodes:new Map,droppableRects:new Map,droppableContainers:new zY,over:null,dragOverlay:{nodeRef:{current:null},rect:null,setRef:r5e},scrollableAncestors:[],scrollableAncestorRects:[],measuringConfiguration:$2e,measureDroppableContainers:r5e,windowRect:null,measuringScheduled:!1},LVs={activatorEvent:null,activators:[],active:null,activeNodeRect:null,ariaDescribedById:{draggable:""},dispatch:r5e,draggableNodes:new Map,over:null,measureDroppableContainers:r5e},BAe=j.createContext(LVs),R8t=j.createContext(MVs);function PVs(){return{draggable:{active:null,initialCoordinates:{x:0,y:0},nodes:new Map,translate:{x:0,y:0}},droppable:{containers:new zY}}}function IVs(s,t){switch(t.type){case dg.DragStart:return{...s,draggable:{...s.draggable,initialCoordinates:t.initialCoordinates,active:t.active}};case dg.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 dg.DragEnd:case dg.DragCancel:return{...s,draggable:{...s.draggable,active:null,initialCoordinates:{x:0,y:0},translate:{x:0,y:0}}};case dg.RegisterDroppable:{const{element:n}=t,{id:r}=n,a=new zY(s.droppable.containers);return a.set(r,n),{...s,droppable:{...s.droppable,containers:a}}}case dg.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 zY(s.droppable.containers);return l.set(n,{...i,disabled:a}),{...s,droppable:{...s.droppable,containers:l}}}case dg.UnregisterDroppable:{const{id:n,key:r}=t,a=s.droppable.containers.get(n);if(!a||r!==a.key)return s;const i=new zY(s.droppable.containers);return i.delete(n),{...s,droppable:{...s.droppable,containers:i}}}default:return s}}function DVs(s){let{disabled:t}=s;const{active:n,activatorEvent:r,draggableNodes:a}=j.useContext(BAe),i=m9e(r),l=m9e(n==null?void 0:n.id);return j.useEffect(()=>{if(!t&&!r&&i&&l!=null){if(!ZWe(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=Eqs(u);if(h){h.focus();break}}})}},[r,t,a,l,i]),null}function RVs(s,t){let{transform:n,...r}=t;return s!=null&&s.length?s.reduce((a,i)=>i({transform:a,...r}),n):n}function OVs(s){return j.useMemo(()=>({draggable:{...$2e.draggable,...s==null?void 0:s.draggable},droppable:{...$2e.droppable,...s==null?void 0:s.droppable},dragOverlay:{...$2e.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 FVs(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;N5(()=>{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=S8t(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=C8t(d);m&&m.scrollBy({top:h.y,left:h.x})}},[t,l,o,r,n])}const O8t=j.createContext({...KN,scaleX:1,scaleY:1});var qA;(function(s){s[s.Uninitialized=0]="Uninitialized",s[s.Initializing=1]="Initializing",s[s.Initialized=2]="Initialized"})(qA||(qA={}));const $Ae=j.memo(function(t){var n,r,a,i;let{id:l,accessibility:o,autoScroll:c=!0,children:d,sensors:u=EVs,collisionDetection:h=Uqs,measuring:m,modifiers:p,...x}=t;const g=j.useReducer(IVs,void 0,PVs),[y,b]=g,[v,N]=Dqs(),[C,A]=j.useState(qA.Uninitialized),T=C===qA.Initialized,{draggable:{active:P,nodes:M,translate:I},droppable:{containers:D}}=y,B=P!=null?M.get(P):null,q=j.useRef({initial:null,translated:null}),W=j.useMemo(()=>{var Un;return P!=null?{id:P,data:(Un=B==null?void 0:B.data)!=null?Un:TVs,rect:q}:null},[P,B]),V=j.useRef(null),[K,Q]=j.useState(null),[J,ce]=j.useState(null),ue=mX(x,Object.values(x)),ne=Fee("DndDescribedBy",l),ee=j.useMemo(()=>D.getEnabled(),[D]),le=OVs(m),{droppableRects:he,measureDroppableContainers:ve,measuringScheduled:ge}=gVs(ee,{dragging:T,dependencies:[I.x,I.y],config:le.droppable}),fe=fVs(M,P),je=j.useMemo(()=>J?p9e(J):null,[J]),Ee=gr(),Me=yVs(fe,le.draggable.measure);FVs({activeNode:P!=null?M.get(P):null,config:Ee.layoutShiftCompensation,initialRect:Me,measure:le.draggable.measure});const De=Nut(fe,le.draggable.measure,Me),ze=Nut(fe?fe.parentElement:null),ke=j.useRef({activatorEvent:null,active:null,activeNode:fe,collisionRect:null,collisions:null,droppableRects:he,draggableNodes:M,draggingNode:null,draggingNodeRect:null,droppableContainers:D,over:null,scrollableAncestors:[],scrollAdjustedTranslate:null}),Xe=D.getNodeFor((n=ke.current.over)==null?void 0:n.id),Se=AVs({measure:le.dragOverlay.measure}),Re=(r=Se.nodeRef.current)!=null?r:fe,Ae=T?(a=Se.rect)!=null?a:De:null,Be=!!(Se.nodeRef.current&&Se.rect),qe=_Vs(Be?null:De),Ke=D8t(Re?Gb(Re):null),Ze=wVs(T?Xe??fe:null),Ue=SVs(Ze),et=RVs(p,{transform:{x:I.x-qe.x,y:I.y-qe.y,scaleX:1,scaleY:1},activatorEvent:J,active:W,activeNodeRect:De,containerNodeRect:ze,draggingNodeRect:Ae,over:ke.current.over,overlayNodeRect:Se.rect,scrollableAncestors:Ze,scrollableAncestorRects:Ue,windowRect:Ke}),Qe=je?oB(je,I):null,Ge=jVs(Ze),nt=Sut(Ge),ft=Sut(Ge,[De]),lt=oB(et,nt),Mt=Ae?Hqs(Ae,et):null,Ft=W&&Mt?h({active:W,collisionRect:Mt,droppableRects:he,droppableContainers:ee,pointerCoordinates:Qe}):null,Ts=k8t(Ft,"id"),[js,zt]=j.useState(null),Nt=Be?et:oB(et,ft),Ds=qqs(Nt,(i=js==null?void 0:js.rect)!=null?i:null,De),_t=j.useRef(null),Xs=j.useCallback((Un,In)=>{let{sensor:Ar,options:or}=In;if(V.current==null)return;const qs=M.get(V.current);if(!qs)return;const yr=Un.nativeEvent,fn=new Ar({active:V.current,activeNode:qs,event:yr,options:or,context:ke,onAbort(Xt){if(!M.get(Xt))return;const{onDragAbort:Qn}=ue.current,Sn={id:Xt};Qn==null||Qn(Sn),v({type:"onDragAbort",event:Sn})},onPending(Xt,rr,Qn,Sn){if(!M.get(Xt))return;const{onDragPending:tn}=ue.current,ln={id:Xt,constraint:rr,initialCoordinates:Qn,offset:Sn};tn==null||tn(ln),v({type:"onDragPending",event:ln})},onStart(Xt){const rr=V.current;if(rr==null)return;const Qn=M.get(rr);if(!Qn)return;const{onDragStart:Sn}=ue.current,$n={activatorEvent:yr,active:{id:rr,data:Qn.data,rect:q}};n1.unstable_batchedUpdates(()=>{Sn==null||Sn($n),A(qA.Initializing),b({type:dg.DragStart,initialCoordinates:Xt,active:rr}),v({type:"onDragStart",event:$n}),Q(_t.current),ce(yr)})},onMove(Xt){b({type:dg.DragMove,coordinates:Xt})},onEnd:Zn(dg.DragEnd),onCancel:Zn(dg.DragCancel)});_t.current=fn;function Zn(Xt){return async function(){const{active:Qn,collisions:Sn,over:$n,scrollAdjustedTranslate:tn}=ke.current;let ln=null;if(Qn&&tn){const{cancelDrop:Cr}=ue.current;ln={activatorEvent:yr,active:Qn,collisions:Sn,delta:tn,over:$n},Xt===dg.DragEnd&&typeof Cr=="function"&&await Promise.resolve(Cr(ln))&&(Xt=dg.DragCancel)}V.current=null,n1.unstable_batchedUpdates(()=>{b({type:Xt}),A(qA.Uninitialized),zt(null),Q(null),ce(null),_t.current=null;const Cr=Xt===dg.DragEnd?"onDragEnd":"onDragCancel";if(ln){const ms=ue.current[Cr];ms==null||ms(ln),v({type:Cr,event:ln})}})}}},[M]),rn=j.useCallback((Un,In)=>(Ar,or)=>{const qs=Ar.nativeEvent,yr=M.get(or);if(V.current!==null||!yr||qs.dndKit||qs.defaultPrevented)return;const fn={active:yr};Un(Ar,In.options,fn)===!0&&(qs.dndKit={capturedBy:In.sensor},V.current=or,Xs(Ar,In))},[M,Xs]),Ps=xVs(u,rn);NVs(u),N5(()=>{De&&C===qA.Initializing&&A(qA.Initialized)},[De,C]),j.useEffect(()=>{const{onDragMove:Un}=ue.current,{active:In,activatorEvent:Ar,collisions:or,over:qs}=ke.current;if(!In||!Ar)return;const yr={active:In,activatorEvent:Ar,collisions:or,delta:{x:lt.x,y:lt.y},over:qs};n1.unstable_batchedUpdates(()=>{Un==null||Un(yr),v({type:"onDragMove",event:yr})})},[lt.x,lt.y]),j.useEffect(()=>{const{active:Un,activatorEvent:In,collisions:Ar,droppableContainers:or,scrollAdjustedTranslate:qs}=ke.current;if(!Un||V.current==null||!In||!qs)return;const{onDragOver:yr}=ue.current,fn=or.get(Ts),Zn=fn&&fn.rect.current?{id:fn.id,rect:fn.rect.current,data:fn.data,disabled:fn.disabled}:null,Xt={active:Un,activatorEvent:In,collisions:Ar,delta:{x:qs.x,y:qs.y},over:Zn};n1.unstable_batchedUpdates(()=>{zt(Zn),yr==null||yr(Xt),v({type:"onDragOver",event:Xt})})},[Ts]),N5(()=>{ke.current={activatorEvent:J,active:W,activeNode:fe,collisionRect:Mt,collisions:Ft,droppableRects:he,draggableNodes:M,draggingNode:Re,draggingNodeRect:Ae,droppableContainers:D,over:js,scrollableAncestors:Ze,scrollAdjustedTranslate:lt},q.current={initial:Ae,translated:Mt}},[W,fe,Ft,Mt,M,Re,Ae,he,D,js,Ze,lt]),hVs({...Ee,delta:I,draggingRect:Mt,pointerCoordinates:Qe,scrollableAncestors:Ze,scrollableAncestorRects:Ue});const _n=j.useMemo(()=>({active:W,activeNode:fe,activeNodeRect:De,activatorEvent:J,collisions:Ft,containerNodeRect:ze,dragOverlay:Se,draggableNodes:M,droppableContainers:D,droppableRects:he,over:js,measureDroppableContainers:ve,scrollableAncestors:Ze,scrollableAncestorRects:Ue,measuringConfiguration:le,measuringScheduled:ge,windowRect:Ke}),[W,fe,De,J,Ft,ze,Se,M,D,he,js,ve,Ze,Ue,le,ge,Ke]),Zs=j.useMemo(()=>({activatorEvent:J,activators:Ps,active:W,activeNodeRect:De,ariaDescribedById:{draggable:ne},dispatch:b,draggableNodes:M,over:js,measureDroppableContainers:ve}),[J,Ps,W,De,b,ne,M,js,ve]);return It.createElement(w8t.Provider,{value:N},It.createElement(BAe.Provider,{value:Zs},It.createElement(R8t.Provider,{value:_n},It.createElement(O8t.Provider,{value:Ds},d)),It.createElement(DVs,{disabled:(o==null?void 0:o.restoreFocus)===!1})),It.createElement(Fqs,{...o,hiddenTextDescribedById:ne}));function gr(){const Un=(K==null?void 0:K.autoScrollEnabled)===!1,In=typeof c=="object"?c.enabled===!1:c===!1,Ar=T&&!Un&&!In;return typeof c=="object"?{...c,enabled:Ar}:{enabled:Ar}}}),zVs=j.createContext(null),Aut="button",BVs="Draggable";function $Vs(s){let{id:t,data:n,disabled:r=!1,attributes:a}=s;const i=Fee(BVs),{activators:l,activatorEvent:o,active:c,activeNodeRect:d,ariaDescribedById:u,draggableNodes:h,over:m}=j.useContext(BAe),{role:p=Aut,roleDescription:x="draggable",tabIndex:g=0}=a??{},y=(c==null?void 0:c.id)===t,b=j.useContext(y?O8t:zVs),[v,N]=n5e(),[C,A]=n5e(),T=kVs(l,t),P=mX(n);N5(()=>(h.set(t,{id:t,key:i,node:v,activatorNode:C,data:P}),()=>{const I=h.get(t);I&&I.key===i&&h.delete(t)}),[h,t]);const M=j.useMemo(()=>({role:p,tabIndex:g,"aria-disabled":r,"aria-pressed":y&&p===Aut?!0:void 0,"aria-roledescription":x,"aria-describedby":u.draggable}),[r,p,g,y,x,u.draggable]);return{active:c,activatorEvent:o,activeNodeRect:d,attributes:M,isDragging:y,listeners:r?void 0:T,node:v,over:m,setNodeRef:N,setActivatorNodeRef:A,transform:b}}function UVs(){return j.useContext(R8t)}const qVs="Droppable",VVs={timeout:25};function HVs(s){let{data:t,disabled:n=!1,id:r,resizeObserverConfig:a}=s;const i=Fee(qVs),{active:l,dispatch:o,over:c,measureDroppableContainers:d}=j.useContext(BAe),u=j.useRef({disabled:n}),h=j.useRef(!1),m=j.useRef(null),p=j.useRef(null),{disabled:x,updateMeasurementsFor:g,timeout:y}={...VVs,...a},b=mX(g??r),v=j.useCallback(()=>{if(!h.current){h.current=!0;return}p.current!=null&&clearTimeout(p.current),p.current=setTimeout(()=>{d(Array.isArray(b.current)?b.current:[b.current]),p.current=null},y)},[y]),N=zAe({callback:v,disabled:x||!l}),C=j.useCallback((M,I)=>{N&&(I&&(N.unobserve(I),h.current=!1),M&&N.observe(M))},[N]),[A,T]=n5e(C),P=mX(t);return j.useEffect(()=>{!N||!A.current||(N.disconnect(),h.current=!1,N.observe(A.current))},[A,N]),j.useEffect(()=>(o({type:dg.RegisterDroppable,element:{id:r,key:i,disabled:n,node:A,rect:m,data:P}}),()=>o({type:dg.UnregisterDroppable,key:i,id:r})),[r]),j.useEffect(()=>{n!==u.current.disabled&&(o({type:dg.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 UAe(s,t,n){const r=s.slice();return r.splice(n<0?r.length+n:n,0,r.splice(t,1)[0]),r}function GVs(s,t){return s.reduce((n,r,a)=>{const i=t.get(r);return i&&(n[a]=i),n},Array(s.length))}function gre(s){return s!==null&&s>=0}function WVs(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=YVs(n,l,a);if(l===a){const d=n[i];return d?{x:aa&&l<=i?{x:-o.width-c,y:0,...yre}:l=i?{x:o.width+c,y:0,...yre}:{x:0,y:0,...yre}};function YVs(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=UAe(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}},vre={scaleX:1,scaleY:1},ZVs=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,...vre}:a=l?{x:0,y:o.height+c,...vre}:{x:0,y:0,...vre}};function XVs(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]),x=l!=null,g=l?p.indexOf(l.id):-1,y=d?p.indexOf(d.id):-1,b=j.useRef(p),v=!WVs(p,b.current),N=y!==-1&&g===-1||v,C=KVs(i);N5(()=>{v&&x&&u(p)},[v,p,x,u]),j.useEffect(()=>{b.current=p},[p]);const A=j.useMemo(()=>({activeIndex:g,containerId:h,disabled:C,disableTransforms:N,items:p,overIndex:y,useDragOverlay:m,sortedRects:GVs(p,c),strategy:a}),[g,h,C.draggable,C.droppable,N,p,y,c,m,a]);return It.createElement(z8t.Provider,{value:A},t)}const QVs=s=>{let{id:t,items:n,activeIndex:r,overIndex:a}=s;return UAe(n,r,a).indexOf(t)},JVs=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},eHs={duration:200,easing:"ease"},B8t="transform",tHs=l6.Transition.toString({property:B8t,duration:0,easing:"linear"}),sHs={roleDescription:"sortable"};function nHs(s){let{disabled:t,index:n,node:r,rect:a}=s;const[i,l]=j.useState(null),o=j.useRef(n);return N5(()=>{if(!t&&n!==o.current&&r.current){const c=a.current;if(c){const d=qq(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 VAe(s){let{animateLayoutChanges:t=JVs,attributes:n,disabled:r,data:a,getNewIndex:i=QVs,id:l,strategy:o,resizeObserverConfig:c,transition:d=eHs}=s;const{items:u,containerId:h,activeIndex:m,disabled:p,disableTransforms:x,sortedRects:g,overIndex:y,useDragOverlay:b,strategy:v}=j.useContext(z8t),N=rHs(r,p),C=u.indexOf(l),A=j.useMemo(()=>({sortable:{containerId:h,index:C,items:u},...a}),[h,a,C,u]),T=j.useMemo(()=>u.slice(u.indexOf(l)),[u,l]),{rect:P,node:M,isOver:I,setNodeRef:D}=HVs({id:l,data:A,disabled:N.droppable,resizeObserverConfig:{updateMeasurementsFor:T,...c}}),{active:B,activatorEvent:q,activeNodeRect:W,attributes:V,setNodeRef:K,listeners:Q,isDragging:J,over:ce,setActivatorNodeRef:ue,transform:ne}=$Vs({id:l,data:A,attributes:{...sHs,...n},disabled:N.draggable}),ee=kqs(D,K),le=!!B,he=le&&!x&&gre(m)&&gre(y),ve=!b&&J,ge=ve&&he?ne:null,je=he?ge??(o??v)({rects:g,activeNodeRect:W,activeIndex:m,overIndex:y,index:C}):null,Ee=gre(m)&&gre(y)?i({id:l,items:u,activeIndex:m,overIndex:y}):C,Me=B==null?void 0:B.id,De=j.useRef({activeId:Me,items:u,newIndex:Ee,containerId:h}),ze=u!==De.current.items,ke=t({active:B,containerId:h,isDragging:J,isSorting:le,id:l,index:C,items:u,newIndex:De.current.newIndex,previousItems:De.current.items,previousContainerId:De.current.containerId,transition:d,wasDragging:De.current.activeId!=null}),Xe=nHs({disabled:!ke,index:C,node:M,rect:P});return j.useEffect(()=>{le&&De.current.newIndex!==Ee&&(De.current.newIndex=Ee),h!==De.current.containerId&&(De.current.containerId=h),u!==De.current.items&&(De.current.items=u)},[le,Ee,h,u]),j.useEffect(()=>{if(Me===De.current.activeId)return;if(Me!=null&&De.current.activeId==null){De.current.activeId=Me;return}const Re=setTimeout(()=>{De.current.activeId=Me},50);return()=>clearTimeout(Re)},[Me]),{active:B,activeIndex:m,attributes:V,data:A,rect:P,index:C,newIndex:Ee,items:u,isOver:I,isSorting:le,isDragging:J,listeners:Q,node:M,overIndex:y,over:ce,setNodeRef:ee,setActivatorNodeRef:ue,setDroppableNodeRef:D,setDraggableNodeRef:K,transform:Xe??je,transition:Se()};function Se(){if(Xe||ze&&De.current.newIndex===C)return tHs;if(!(ve&&!ZWe(q)||!d)&&(le||ke))return l6.Transition.toString({...d,property:B8t})}}function rHs(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 i5e(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 aHs=[pd.Down,pd.Right,pd.Up,pd.Left],$8t=(s,t)=>{let{context:{active:n,collisionRect:r,droppableRects:a,droppableContainers:i,over:l,scrollableAncestors:o}}=t;if(aHs.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 pd.Down:r.topm.top&&c.push(h);break;case pd.Left:r.left>m.left&&c.push(h);break;case pd.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,x=m==null?void 0:m.node.current;if(x&&p&&h&&m){const y=OAe(x).some((T,P)=>o[P]!==T),b=U8t(h,m),v=iHs(h,m),N=y||!b?{x:0,y:0}:{x:v?r.width-p.width:0,y:v?r.height-p.height:0},C={x:p.left,y:p.top};return N.x&&N.y?C:pX(C,N)}}}};function U8t(s,t){return!i5e(s)||!i5e(t)?!1:s.data.current.sortable.containerId===t.data.current.sortable.containerId}function iHs(s,t){return!i5e(s)||!i5e(t)||!U8t(s,t)?!1:s.data.current.sortable.indext(s),children:e.jsx(Ya,{className:"h-3.5 w-3.5"})}),e.jsx($,{variant:"destructive",size:"icon",className:"h-7 w-7",onClick:()=>n(s),children:e.jsx(Pn,{className:"h-3.5 w-3.5"})})]}),s.post_date&&e.jsx("div",{className:"absolute bottom-2 left-2",children:e.jsxs($e,{className:"bg-primary/90 text-primary-foreground text-[10px] gap-1 backdrop-blur-sm px-1.5 py-0.5",children:[e.jsx(ia,{className:"h-2.5 w-2.5"}),Hs(new Date(s.post_date+"T00:00:00"),"MMM d")]})})]}),e.jsxs(Oe,{className:"p-3 space-y-2",children:[e.jsx("p",{className:"text-xs text-muted-foreground line-clamp-3",children:s.caption}),e.jsxs(Sc,{children:[e.jsx(Cc,{asChild:!0,children:e.jsxs($,{variant:"outline",size:"sm",className:Tt("w-full h-7 text-[11px] gap-1 justify-start font-normal",!s.post_date&&"text-muted-foreground"),children:[e.jsx(ia,{className:"h-3 w-3"}),s.post_date?Hs(new Date(s.post_date+"T00:00:00"),"MMM d, yyyy"):"Set post date"]})}),e.jsxs(xc,{className:"w-auto p-0",align:"start",children:[e.jsx(y1,{mode:"single",selected:s.post_date?new Date(s.post_date+"T00:00:00"):void 0,onSelect:h=>r(s.id,h?Hs(h,"yyyy-MM-dd"):null),className:"p-3 pointer-events-auto"}),s.post_date&&e.jsx("div",{className:"p-2 border-t",children:e.jsx($,{variant:"ghost",size:"sm",className:"w-full text-xs text-muted-foreground",onClick:()=>r(s.id,null),children:"Clear date"})})]})]})]})]})})}const lHs=()=>{const s=ts(),[t,n]=j.useState("all"),[r,a]=j.useState(!1),[i,l]=j.useState(Hs(new Date,"yyyy-MM")),[o,c]=j.useState([]),[d,u]=j.useState(!1),[h,m]=j.useState(null),[p,x]=j.useState(null),[g,y]=j.useState(""),[b,v]=j.useState(null),[N,C]=j.useState(!1),[A,T]=j.useState(!1),[P,M]=j.useState(Hs(new Date,"yyyy-MM")),[I,D]=j.useState(null),[B,q]=j.useState(""),[W,V]=j.useState(""),[K,Q]=j.useState(""),[J,ce]=j.useState(!1),ue=DAe(pU(Vq,{activationConstraint:{distance:5}}),pU(FAe,{coordinateGetter:$8t})),{data:ne=[],isLoading:ee}=ht({queryKey:["admin-social-swag-2"],queryFn:async()=>{const{data:Qe,error:Ge}=await U.from("social_swag_2").select("*").order("month",{ascending:!1}).order("sort_order");if(Ge)throw Ge;return Qe}}),{data:le=[]}=ht({queryKey:["admin-social-swag-2-months"],queryFn:async()=>{const{data:Qe,error:Ge}=await U.from("social_swag_2_months").select("*").order("month",{ascending:!1});if(Ge)throw Ge;return Qe}}),{data:he=[]}=ht({queryKey:["admin-social-swag-2-reels"],queryFn:async()=>{const{data:Qe,error:Ge}=await U.from("social_swag_2_reels").select("*").order("month",{ascending:!1});if(Ge)throw Ge;return Qe}}),ve=[...new Set(ne.map(Qe=>Qe.month))].sort((Qe,Ge)=>Ge.localeCompare(Qe)),ge=t==="all"?ne:ne.filter(Qe=>Qe.month===t),fe=Qe=>{const Ge=pHe(Qe,"yyyy-MM",new Date);return Hs(Ge,"MMMM yyyy")},je=Qe=>{x(Qe),y(Qe.caption),v(Qe.post_date)},Ee=async()=>{if(p){C(!0);try{const{error:Qe}=await U.from("social_swag_2").update({caption:g,post_date:b}).eq("id",p.id);if(Qe)throw Qe;ae.success("Image updated"),x(null),s.invalidateQueries({queryKey:["admin-social-swag-2"]}),s.invalidateQueries({queryKey:["social-swag-2"]})}catch{ae.error("Failed to update image")}finally{C(!1)}}},Me=async Qe=>{const{active:Ge,over:nt}=Qe;if(!nt||Ge.id===nt.id)return;const ft=ge,lt=ft.findIndex(Ts=>Ts.id===Ge.id),Mt=ft.findIndex(Ts=>Ts.id===nt.id);if(lt===-1||Mt===-1)return;const Ft=UAe(ft,lt,Mt);s.setQueryData(["admin-social-swag-2"],Ts=>{if(!Ts)return Ts;const js={};return Ft.forEach((zt,Nt)=>{js[zt.id]=Nt}),Ts.map(zt=>js[zt.id]!==void 0?{...zt,sort_order:js[zt.id]}:zt).sort((zt,Nt)=>zt.month!==Nt.month?Nt.month.localeCompare(zt.month):zt.sort_order-Nt.sort_order)});try{await Promise.all(Ft.map((Ts,js)=>U.from("social_swag_2").update({sort_order:js}).eq("id",Ts.id)))}catch{ae.error("Failed to save order"),s.invalidateQueries({queryKey:["admin-social-swag-2"]})}},De=Qe=>{const nt=Array.from(Qe.target.files||[]).sort((ft,lt)=>ft.name.localeCompare(lt.name,void 0,{numeric:!0,sensitivity:"base"})).slice(0,16-o.length).map(ft=>({file:ft,preview:URL.createObjectURL(ft),caption:""}));c(ft=>[...ft,...nt].slice(0,16))},ze=Qe=>{c(Ge=>{const nt=[...Ge];return URL.revokeObjectURL(nt[Qe].preview),nt.splice(Qe,1),nt})},ke=(Qe,Ge)=>{c(nt=>{const ft=[...nt];return ft[Qe]={...ft[Qe],caption:Ge},ft})},Xe=async()=>{var Ge;if(o.length===0){ae.error("Please add at least one image");return}if(o.filter(nt=>!nt.caption.trim()).length>0){ae.error("Please add captions to all images");return}u(!0);try{const{data:nt}=await U.from("social_swag_2").select("sort_order").eq("month",i).order("sort_order",{ascending:!1}).limit(1),ft=(((Ge=nt==null?void 0:nt[0])==null?void 0:Ge.sort_order)??-1)+1;for(let lt=0;lt{const Ge=Qe.image_url.split("/social-swag-2/");Ge[1]&&await U.storage.from("social-swag-2").remove([Ge[1]]);const{error:nt}=await U.from("social_swag_2").delete().eq("id",Qe.id);if(nt)throw nt},onSuccess:()=>{ae.success("Image deleted"),s.invalidateQueries({queryKey:["admin-social-swag-2"]})},onError:()=>ae.error("Failed to delete image")}),Re=yt({mutationFn:async({id:Qe,postDate:Ge})=>{const{error:nt}=await U.from("social_swag_2").update({post_date:Ge}).eq("id",Qe);if(nt)throw nt},onSuccess:()=>{ae.success("Post date updated"),s.invalidateQueries({queryKey:["admin-social-swag-2"]}),s.invalidateQueries({queryKey:["social-swag-2"]})},onError:()=>ae.error("Failed to update post date")}),Ae=yt({mutationFn:async({month:Qe,link:Ge})=>{const{error:nt}=await U.from("social_swag_2_months").upsert({month:Qe,canva_link:Ge||null},{onConflict:"month"});if(nt)throw nt},onSuccess:()=>{ae.success("Canva link updated"),m(null),s.invalidateQueries({queryKey:["admin-social-swag-2-months"]})},onError:()=>ae.error("Failed to update Canva link")}),Be=Qe=>{var Ge;return((Ge=le.find(nt=>nt.month===Qe))==null?void 0:Ge.canva_link)||""},qe=Qe=>he.find(Ge=>Ge.month===Qe)||null,Ke=Qe=>{var nt;const Ge=(nt=Qe.target.files)==null?void 0:nt[0];Ge&&(D(Ge),q(URL.createObjectURL(Ge)))},Ze=()=>{B&&URL.revokeObjectURL(B),D(null),q(""),V(""),Q("")},Ue=async()=>{if(!I){ae.error("Please select an image");return}ce(!0);try{const Qe=I.name.split(".").pop(),Ge=`reels/${P}-${Date.now()}.${Qe}`,{error:nt}=await U.storage.from("social-swag-2").upload(Ge,I);if(nt)throw nt;const{data:{publicUrl:ft}}=U.storage.from("social-swag-2").getPublicUrl(Ge),{error:lt}=await U.from("social_swag_2_reels").upsert({month:P,image_url:ft,canva_link:K||null,caption:W||null},{onConflict:"month"});if(lt)throw lt;ae.success("Reel uploaded successfully!"),h9e(`${fe(P)} Reel`,"social-swag-2"),Ze(),T(!1),s.invalidateQueries({queryKey:["admin-social-swag-2-reels"]})}catch(Qe){console.error("Reel upload error:",Qe),ae.error("Failed to upload reel")}finally{ce(!1)}},et=yt({mutationFn:async Qe=>{const Ge=Qe.image_url.split("/social-swag-2/");Ge[1]&&await U.storage.from("social-swag-2").remove([Ge[1]]);const{error:nt}=await U.from("social_swag_2_reels").delete().eq("id",Qe.id);if(nt)throw nt},onSuccess:()=>{ae.success("Reel deleted"),s.invalidateQueries({queryKey:["admin-social-swag-2-reels"]})},onError:()=>ae.error("Failed to delete reel")});return e.jsxs(Ks,{title:"Admin - Social Swag 2.0",children:[e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold",children:"Social Swag 2.0"}),e.jsx("p",{className:"text-muted-foreground",children:"Manage monthly social media images and captions"})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(Os,{open:r,onOpenChange:a,children:[e.jsx(Ko,{asChild:!0,children:e.jsxs($,{className:"gap-2",children:[e.jsx(sn,{className:"h-4 w-4"}),"Upload Images"]})}),e.jsxs(Rs,{className:"max-w-4xl max-h-[90vh] overflow-y-auto",children:[e.jsx(Us,{children:e.jsx(zs,{children:"Upload Social Swag Images"})}),e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Month"}),e.jsx(be,{type:"month",value:i,onChange:Qe=>l(Qe.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(se,{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:De,className:"hidden",id:"swag-upload",disabled:o.length>=16}),e.jsxs("label",{htmlFor:"swag-upload",className:"cursor-pointer",children:[e.jsx(si,{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((Qe,Ge)=>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:Qe.preview,alt:`Upload ${Ge+1}`,className:"w-full h-full object-cover"}),e.jsx($,{variant:"destructive",size:"icon",className:"absolute top-1 right-1 h-6 w-6",onClick:()=>ze(Ge),children:e.jsx(pr,{className:"h-3 w-3"})})]}),e.jsx(Is,{placeholder:"Caption...",value:Qe.caption,onChange:nt=>ke(Ge,nt.target.value),className:"text-xs h-20"})]},Ge))}),e.jsx($,{onClick:Xe,disabled:d||o.length===0,className:"w-full gap-2",children:d?e.jsxs(e.Fragment,{children:[e.jsx(Ht,{className:"h-4 w-4 animate-spin"}),"Uploading..."]}):e.jsxs(e.Fragment,{children:[e.jsx(si,{className:"h-4 w-4"}),"Upload ",o.length," Images"]})})]})]})]}),e.jsxs(Os,{open:A,onOpenChange:Qe=>{T(Qe),Qe||Ze()},children:[e.jsx(Ko,{asChild:!0,children:e.jsxs($,{variant:"outline",className:"gap-2",children:[e.jsx(lh,{className:"h-4 w-4"}),"Upload Reel"]})}),e.jsxs(Rs,{className:"max-w-lg max-h-[85vh] overflow-y-auto",children:[e.jsx(Us,{children:e.jsx(zs,{children:"Upload Monthly Reel"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Month"}),e.jsx(be,{type:"month",value:P,onChange:Qe=>M(Qe.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Reel Preview Image"}),B?e.jsxs("div",{className:"relative aspect-[9/16] max-w-[120px] mx-auto rounded-lg overflow-hidden bg-muted",children:[e.jsx("img",{src:B,alt:"Reel preview",className:"w-full h-full object-cover"}),e.jsx($,{variant:"destructive",size:"icon",className:"absolute top-2 right-2 h-6 w-6",onClick:()=>{URL.revokeObjectURL(B),D(null),q("")},children:e.jsx(pr,{className:"h-3 w-3"})})]}):e.jsxs("div",{className:"border-2 border-dashed rounded-lg p-6 text-center",children:[e.jsx("input",{type:"file",accept:"image/*",onChange:Ke,className:"hidden",id:"reel-upload"}),e.jsxs("label",{htmlFor:"reel-upload",className:"cursor-pointer",children:[e.jsx(lh,{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(se,{children:"Canva Download Link"}),e.jsx(be,{value:K,onChange:Qe=>Q(Qe.target.value),placeholder:"https://www.canva.com/..."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Caption"}),e.jsx(Is,{value:W,onChange:Qe=>V(Qe.target.value),placeholder:"Enter caption for this reel...",className:"h-24"})]}),e.jsx($,{onClick:Ue,disabled:J||!I,className:"w-full gap-2",children:J?e.jsxs(e.Fragment,{children:[e.jsx(Ht,{className:"h-4 w-4 animate-spin"}),"Uploading..."]}):e.jsxs(e.Fragment,{children:[e.jsx(si,{className:"h-4 w-4"}),"Upload Reel"]})})]})]})]})]})]}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[e.jsx(_e,{children:e.jsxs(Oe,{className:"p-4",children:[e.jsx("div",{className:"text-2xl font-bold",children:ne.length}),e.jsx("div",{className:"text-sm text-muted-foreground",children:"Total Images"})]})}),e.jsx(_e,{children:e.jsxs(Oe,{className:"p-4",children:[e.jsx("div",{className:"text-2xl font-bold",children:ve.length}),e.jsx("div",{className:"text-sm text-muted-foreground",children:"Months"})]})})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsx(ua,{value:t,onValueChange:n,children:e.jsxs(ha,{children:[e.jsx(Qt,{value:"all",children:"All"}),ve.map(Qe=>e.jsx(Qt,{value:Qe,children:fe(Qe)},Qe))]})}),t!=="all"&&e.jsx(_e,{children:e.jsx(Oe,{className:"p-4",children:e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx(kc,{className:"h-4 w-4 text-muted-foreground"}),e.jsxs("div",{className:"flex-1",children:[e.jsxs(se,{className:"text-sm text-muted-foreground",children:["Canva Edit Link for ",fe(t)]}),(h==null?void 0:h.month)===t?e.jsxs("div",{className:"flex gap-2 mt-1",children:[e.jsx(be,{value:h.link,onChange:Qe=>m({...h,link:Qe.target.value}),placeholder:"https://www.canva.com/..."}),e.jsx($,{size:"sm",onClick:()=>Ae.mutate(h),children:"Save"}),e.jsx($,{size:"sm",variant:"outline",onClick:()=>m(null),children:"Cancel"})]}):e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[e.jsx("span",{className:"text-sm",children:Be(t)||"No link set"}),e.jsx($,{size:"sm",variant:"outline",onClick:()=>m({month:t,link:Be(t)}),children:"Edit"})]})]})]})})}),t!=="all"&&e.jsx(_e,{children:e.jsx(Oe,{className:"p-4",children:e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsx(lh,{className:"h-4 w-4 text-muted-foreground mt-1"}),e.jsxs("div",{className:"flex-1",children:[e.jsxs(se,{className:"text-sm text-muted-foreground",children:["Reel for ",fe(t)]}),(()=>{const Qe=qe(t);return Qe?e.jsxs("div",{className:"flex items-center gap-4 mt-2",children:[e.jsx("img",{src:Qe.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:Qe.caption||"No caption"}),Qe.canva_link&&e.jsx("a",{href:Qe.canva_link,target:"_blank",rel:"noopener noreferrer",className:"text-primary hover:underline text-xs",children:"View Canva Link"})]}),e.jsx($,{variant:"destructive",size:"sm",onClick:()=>et.mutate(Qe),children:e.jsx(Pn,{className:"h-4 w-4"})})]}):e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:"No reel uploaded for this month"})})()]})]})})})]}),ee?e.jsx("div",{className:"text-center py-12 text-muted-foreground",children:"Loading..."}):ge.length===0?e.jsxs("div",{className:"text-center py-12",children:[e.jsx(Jl,{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($Ae,{sensors:ue,collisionDetection:RAe,onDragEnd:Me,children:e.jsx(qAe,{items:ge.map(Qe=>Qe.id),strategy:zee,children:e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-4 lg:grid-cols-6 gap-4",children:ge.map(Qe=>e.jsx(oHs,{item:Qe,onEdit:je,onDelete:Ge=>Se.mutate(Ge),onDateChange:(Ge,nt)=>Re.mutate({id:Ge,postDate:nt})},Qe.id))})})})]}),e.jsx(Os,{open:!!p,onOpenChange:Qe=>{Qe||x(null)},children:e.jsxs(Rs,{className:"max-w-md",children:[e.jsx(Us,{children:e.jsx(zs,{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(se,{children:"Caption"}),e.jsx(Is,{value:g,onChange:Qe=>y(Qe.target.value),placeholder:"Enter caption...",className:"h-28"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Post Date"}),e.jsxs("div",{className:"flex gap-2 items-center",children:[e.jsxs(Sc,{children:[e.jsx(Cc,{asChild:!0,children:e.jsxs($,{variant:"outline",className:Tt("flex-1 justify-start gap-2 font-normal",!b&&"text-muted-foreground"),children:[e.jsx(ia,{className:"h-4 w-4"}),b?Hs(new Date(b+"T00:00:00"),"MMM d, yyyy"):"Pick a date"]})}),e.jsx(xc,{className:"w-auto p-0",align:"start",children:e.jsx(y1,{mode:"single",selected:b?new Date(b+"T00:00:00"):void 0,onSelect:Qe=>v(Qe?Hs(Qe,"yyyy-MM-dd"):null),className:"p-3 pointer-events-auto"})})]}),b&&e.jsx($,{variant:"ghost",size:"icon",onClick:()=>v(null),children:e.jsx(pr,{className:"h-4 w-4"})})]})]})]}),e.jsxs(kr,{children:[e.jsx($,{variant:"outline",onClick:()=>x(null),children:"Cancel"}),e.jsx($,{onClick:Ee,disabled:N,className:"gap-2",children:N?e.jsxs(e.Fragment,{children:[e.jsx(Ht,{className:"h-4 w-4 animate-spin"}),"Saving..."]}):"Save Changes"})]})]})})]})},cHs=()=>{const{toast:s}=gi(),t=ts(),[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),[x,g]=j.useState({name:"",description:"",icon:""}),[y,b]=j.useState(!1),[v,N]=j.useState(null),[C,A]=j.useState(""),{data:T=[],isLoading:P}=ht({queryKey:["admin-community-categories"],queryFn:async()=>{const{data:Me,error:De}=await U.from("community_categories").select("*").order("sort_order");if(De)throw De;return Me}}),{data:M=[],isLoading:I}=ht({queryKey:["admin-private-groups"],queryFn:async()=>{const{data:Me,error:De}=await U.from("community_private_groups").select("*").order("sort_order");if(De)throw De;return Me}}),{data:D=[]}=ht({queryKey:["admin-group-members",v==null?void 0:v.id],queryFn:async()=>{if(!v)return[];const{data:Me,error:De}=await U.from("community_private_group_members").select("*").eq("group_id",v.id);if(De)throw De;return Me},enabled:!!v}),{data:B=[]}=ht({queryKey:["admin-all-profiles"],queryFn:async()=>{let De=[],ze=0,ke=!0;for(;ke;){const{data:Xe,error:Se}=await U.from("profiles").select("id, name, email, brokerage_id").order("name").range(ze,ze+1e3-1);if(Se)throw Se;Xe&&Xe.length>0?(De=[...De,...Xe],ze+=1e3,ke=Xe.length===1e3):ke=!1}return De}}),{data:q=[]}=ht({queryKey:["admin-all-brokerages"],queryFn:async()=>{const{data:Me,error:De}=await U.from("brokerages").select("*").order("name");if(De)throw De;return Me}}),W=yt({mutationFn:async Me=>{if(Me.id){const{error:De}=await U.from("community_categories").update({name:Me.name,description:Me.description||null,icon:Me.icon||null}).eq("id",Me.id);if(De)throw De}else{const De=Math.max(...T.map(ke=>ke.sort_order),0),{error:ze}=await U.from("community_categories").insert({name:Me.name,description:Me.description||null,icon:Me.icon||null,sort_order:De+1});if(ze)throw ze}},onSuccess:()=>{t.invalidateQueries({queryKey:["admin-community-categories"]}),i(!1),o(null),d({name:"",description:"",icon:""}),s({title:l?"Category updated!":"Category created!"})},onError:Me=>{s({title:"Error",description:Me.message,variant:"destructive"})}}),V=yt({mutationFn:async Me=>{const{error:De}=await U.from("community_categories").delete().eq("id",Me);if(De)throw De},onSuccess:()=>{t.invalidateQueries({queryKey:["admin-community-categories"]}),s({title:"Category deleted"})}}),K=yt({mutationFn:async({id:Me,direction:De})=>{const ze=T.findIndex(ke=>ke.id===Me);if(De==="up"&&ze>0){const ke=T[ze-1],Xe=T[ze];await U.from("community_categories").update({sort_order:Xe.sort_order}).eq("id",ke.id),await U.from("community_categories").update({sort_order:ke.sort_order}).eq("id",Xe.id)}else if(De==="down"&&zet.invalidateQueries({queryKey:["admin-community-categories"]})}),Q=yt({mutationFn:async Me=>{if(Me.id){const{error:De}=await U.from("community_private_groups").update({name:Me.name,description:Me.description||null,icon:Me.icon||null}).eq("id",Me.id);if(De)throw De}else{const De=Math.max(...M.map(ke=>ke.sort_order),0),{error:ze}=await U.from("community_private_groups").insert({name:Me.name,description:Me.description||null,icon:Me.icon||null,sort_order:De+1});if(ze)throw ze}},onSuccess:()=>{t.invalidateQueries({queryKey:["admin-private-groups"]}),h(!1),p(null),g({name:"",description:"",icon:""}),s({title:m?"Private group updated!":"Private group created!"})},onError:Me=>{s({title:"Error",description:Me.message,variant:"destructive"})}}),J=yt({mutationFn:async Me=>{const{error:De}=await U.from("community_private_groups").delete().eq("id",Me);if(De)throw De},onSuccess:()=>{t.invalidateQueries({queryKey:["admin-private-groups"]}),s({title:"Private group deleted"})}}),ce=yt({mutationFn:async({id:Me,direction:De})=>{const ze=M.findIndex(ke=>ke.id===Me);if(De==="up"&&ze>0){const ke=M[ze-1],Xe=M[ze];await U.from("community_private_groups").update({sort_order:Xe.sort_order}).eq("id",ke.id),await U.from("community_private_groups").update({sort_order:ke.sort_order}).eq("id",Xe.id)}else if(De==="down"&&zet.invalidateQueries({queryKey:["admin-private-groups"]})}),ue=yt({mutationFn:async({groupId:Me,userId:De,isMember:ze})=>{if(ze){const{error:ke}=await U.from("community_private_group_members").delete().eq("group_id",Me).eq("user_id",De);if(ke)throw ke}else{const{error:ke}=await U.from("community_private_group_members").insert({group_id:Me,user_id:De});if(ke)throw ke}},onSuccess:()=>{t.invalidateQueries({queryKey:["admin-group-members",v==null?void 0:v.id]})}}),ne=yt({mutationFn:async({groupId:Me,brokerageId:De,isMember:ze})=>{if(ze){const{error:ke}=await U.from("community_private_group_members").delete().eq("group_id",Me).eq("brokerage_id",De);if(ke)throw ke}else{const{error:ke}=await U.from("community_private_group_members").insert({group_id:Me,brokerage_id:De});if(ke)throw ke}},onSuccess:()=>{t.invalidateQueries({queryKey:["admin-group-members",v==null?void 0:v.id]})}}),ee=Me=>{o(Me),d({name:Me.name,description:Me.description||"",icon:Me.icon||""}),i(!0)},le=()=>{o(null),d({name:"",description:"",icon:""}),i(!0)},he=Me=>{p(Me),g({name:Me.name,description:Me.description||"",icon:Me.icon||""}),h(!0)},ve=()=>{p(null),g({name:"",description:"",icon:""}),h(!0)},ge=Me=>{N(Me),A(""),b(!0)},fe=Me=>D.some(De=>De.user_id===Me),je=Me=>D.some(De=>De.brokerage_id===Me),Ee=B.filter(Me=>Me.name.toLowerCase().includes(C.toLowerCase())||Me.email.toLowerCase().includes(C.toLowerCase()));return e.jsx(Ks,{title:"Community Management",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(hh,{title:"Community Management",description:"Manage categories and private groups for community discussions"}),e.jsxs(ua,{value:n,onValueChange:r,children:[e.jsxs(ha,{children:[e.jsx(Qt,{value:"categories",children:"Public Categories"}),e.jsxs(Qt,{value:"private-groups",children:[e.jsx(Ad,{className:"h-4 w-4 mr-1"}),"Private Groups"]})]}),e.jsxs(Jt,{value:"categories",className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Categories visible to all community members"}),e.jsxs($,{onClick:le,children:[e.jsx(sn,{className:"h-4 w-4 mr-2"}),"Add Category"]})]}),e.jsx(_e,{children:e.jsx(Oe,{className:"pt-6",children:e.jsxs(Va,{children:[e.jsx(Ha,{children:e.jsxs(hn,{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(Ga,{children:P?e.jsx(hn,{children:e.jsx(gt,{colSpan:5,className:"text-center py-8",children:"Loading..."})}):T.length===0?e.jsx(hn,{children:e.jsx(gt,{colSpan:5,className:"text-center py-8 text-muted-foreground",children:"No categories yet. Create your first one!"})}):T.map((Me,De)=>e.jsxs(hn,{children:[e.jsx(gt,{children:e.jsxs("div",{className:"flex flex-col gap-1",children:[e.jsx($,{variant:"ghost",size:"icon",className:"h-6 w-6",disabled:De===0,onClick:()=>K.mutate({id:Me.id,direction:"up"}),children:"↑"}),e.jsx($,{variant:"ghost",size:"icon",className:"h-6 w-6",disabled:De===T.length-1,onClick:()=>K.mutate({id:Me.id,direction:"down"}),children:"↓"})]})}),e.jsx(gt,{className:"text-2xl",children:Me.icon||"📁"}),e.jsx(gt,{className:"font-medium",children:Me.name}),e.jsx(gt,{className:"text-muted-foreground",children:Me.description||"—"}),e.jsx(gt,{children:e.jsxs("div",{className:"flex gap-1",children:[e.jsx($,{variant:"ghost",size:"icon",onClick:()=>ee(Me),children:e.jsx(Ya,{className:"h-4 w-4"})}),e.jsx($,{variant:"ghost",size:"icon",className:"text-destructive",onClick:async()=>{await Yi("Delete this category? Posts will be uncategorized.")&&V.mutate(Me.id)},children:e.jsx(Pn,{className:"h-4 w-4"})})]})})]},Me.id))})]})})})]}),e.jsxs(Jt,{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(Ai,{className:"h-3 w-3"}),"Brokerage groups are created automatically and sync with brokerage names"]})]}),e.jsxs($,{onClick:ve,children:[e.jsx(sn,{className:"h-4 w-4 mr-2"}),"Add Private Group"]})]}),e.jsx(_e,{children:e.jsx(Oe,{className:"pt-6",children:e.jsxs(Va,{children:[e.jsx(Ha,{children:e.jsxs(hn,{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(Ga,{children:I?e.jsx(hn,{children:e.jsx(gt,{colSpan:6,className:"text-center py-8",children:"Loading..."})}):M.length===0?e.jsx(hn,{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((Me,De)=>e.jsxs(hn,{children:[e.jsx(gt,{children:e.jsxs("div",{className:"flex flex-col gap-1",children:[e.jsx($,{variant:"ghost",size:"icon",className:"h-6 w-6",disabled:De===0,onClick:()=>ce.mutate({id:Me.id,direction:"up"}),children:"↑"}),e.jsx($,{variant:"ghost",size:"icon",className:"h-6 w-6",disabled:De===M.length-1,onClick:()=>ce.mutate({id:Me.id,direction:"down"}),children:"↓"})]})}),e.jsx(gt,{className:"text-2xl",children:Me.icon||"🔒"}),e.jsx(gt,{className:"font-medium",children:e.jsxs("div",{className:"flex items-center gap-2",children:[Me.name,Me.brokerage_id?e.jsxs($e,{variant:"outline",className:"text-xs bg-blue-50 text-blue-700 border-blue-200",children:[e.jsx(Ai,{className:"h-3 w-3 mr-1"}),"Auto-managed"]}):e.jsxs($e,{variant:"secondary",className:"text-xs",children:[e.jsx(Ad,{className:"h-3 w-3 mr-1"}),"Private"]})]})}),e.jsx(gt,{className:"text-muted-foreground",children:Me.description||"—"}),e.jsx(gt,{children:e.jsxs($,{variant:"outline",size:"sm",onClick:()=>ge(Me),children:[e.jsx(qn,{className:"h-4 w-4 mr-1"}),"Manage"]})}),e.jsx(gt,{children:e.jsxs("div",{className:"flex gap-1",children:[!Me.brokerage_id&&e.jsx($,{variant:"ghost",size:"icon",onClick:()=>he(Me),children:e.jsx(Ya,{className:"h-4 w-4"})}),!Me.brokerage_id&&e.jsx($,{variant:"ghost",size:"icon",className:"text-destructive",onClick:async()=>{await Yi("Delete this private group? All posts in this group will be deleted.")&&J.mutate(Me.id)},children:e.jsx(Pn,{className:"h-4 w-4"})}),Me.brokerage_id&&e.jsx("span",{className:"text-xs text-muted-foreground italic",children:"Managed via brokerage"})]})})]},Me.id))})]})})})]})]}),e.jsx(Os,{open:a,onOpenChange:i,children:e.jsxs(Rs,{children:[e.jsx(Us,{children:e.jsx(zs,{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(be,{value:c.icon,onChange:Me=>d(De=>({...De,icon:Me.target.value})),placeholder:"💬",className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium",children:"Name *"}),e.jsx(be,{value:c.name,onChange:Me=>d(De=>({...De,name:Me.target.value})),placeholder:"Category name",className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium",children:"Description"}),e.jsx(Is,{value:c.description,onChange:Me=>d(De=>({...De,description:Me.target.value})),placeholder:"Brief description of this category",className:"mt-1"})]}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx($,{variant:"outline",onClick:()=>i(!1),children:"Cancel"}),e.jsx($,{onClick:()=>W.mutate({...c,id:l==null?void 0:l.id}),disabled:!c.name.trim(),children:l?"Save Changes":"Create Category"})]})]})]})}),e.jsx(Os,{open:u,onOpenChange:h,children:e.jsxs(Rs,{children:[e.jsx(Us,{children:e.jsx(zs,{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(be,{value:x.icon,onChange:Me=>g(De=>({...De,icon:Me.target.value})),placeholder:"🔒",className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium",children:"Name *"}),e.jsx(be,{value:x.name,onChange:Me=>g(De=>({...De,name:Me.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(Is,{value:x.description,onChange:Me=>g(De=>({...De,description:Me.target.value})),placeholder:"Brief description of this private group",className:"mt-1"})]}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx($,{variant:"outline",onClick:()=>h(!1),children:"Cancel"}),e.jsx($,{onClick:()=>Q.mutate({...x,id:m==null?void 0:m.id}),disabled:!x.name.trim(),children:m?"Save Changes":"Create Private Group"})]})]})]})}),e.jsx(Os,{open:y,onOpenChange:b,children:e.jsxs(Rs,{className:"max-w-2xl",children:[e.jsx(Us,{children:e.jsxs(zs,{children:["Manage Members: ",v==null?void 0:v.name]})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs(ua,{defaultValue:"brokerages",children:[e.jsxs(ha,{className:"w-full",children:[e.jsx(Qt,{value:"brokerages",className:"flex-1",children:"By Brokerage"}),e.jsx(Qt,{value:"users",className:"flex-1",children:"Individual Users"})]}),e.jsxs(Jt,{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(Oi,{className:"h-[300px] border rounded-md p-4",children:e.jsxs("div",{className:"space-y-2",children:[q.map(Me=>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(ui,{checked:je(Me.id),onCheckedChange:()=>{v&&ne.mutate({groupId:v.id,brokerageId:Me.id,isMember:je(Me.id)})}}),e.jsx("span",{className:"font-medium",children:Me.name})]}),e.jsxs($e,{variant:"secondary",children:[B.filter(De=>De.brokerage_id===Me.id).length," agents"]})]},Me.id)),q.length===0&&e.jsx("p",{className:"text-center text-muted-foreground py-4",children:"No brokerages found"})]})})]}),e.jsxs(Jt,{value:"users",className:"space-y-4",children:[e.jsxs("div",{className:"relative",children:[e.jsx(Vr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(be,{placeholder:"Search users...",value:C,onChange:Me=>A(Me.target.value),className:"pl-9"})]}),e.jsx(Oi,{className:"h-[300px] border rounded-md p-4",children:e.jsxs("div",{className:"space-y-2",children:[Ee.map(Me=>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(ui,{checked:fe(Me.id),onCheckedChange:()=>{v&&ue.mutate({groupId:v.id,userId:Me.id,isMember:fe(Me.id)})}}),e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:Me.name}),e.jsx("div",{className:"text-sm text-muted-foreground",children:Me.email})]})]})},Me.id)),Ee.length===0&&e.jsx("p",{className:"text-center text-muted-foreground py-4",children:"No users found"})]})})]})]}),e.jsx("div",{className:"flex justify-end",children:e.jsx($,{onClick:()=>b(!1),children:"Done"})})]})]})})]})})},Eut=s=>{switch(s){case"academy_video":return e.jsx(Td,{className:"h-3 w-3"});case"template":return e.jsx(Wr,{className:"h-3 w-3"});case"toolbox":return e.jsx(Tu,{className:"h-3 w-3"});case"newsletter":return e.jsx(Gj,{className:"h-3 w-3"});case"social_swag":return e.jsx(dn,{className:"h-3 w-3"});default:return e.jsx(Tr,{className:"h-3 w-3"})}},dHs=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}},uHs=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}},hHs=()=>{const{toast:s}=gi(),[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,x]=j.useState([]),[g,y]=j.useState([]);j.useEffect(()=>{b()},[]);const b=async()=>{try{c(!0);const{data:D,error:B}=await U.from("activity_logs").select(` id, user_id, app_name, launched_at, profiles ( name, email, brokerages ( name ) ) `).order("launched_at",{ascending:!1}).limit(5e3);if(B)throw B;const{data:q,error:W}=await U.from("content_engagement_logs").select(` id, user_id, resource_type, resource_id, resource_title, action_type, created_at `).order("created_at",{ascending:!1}).limit(5e3);if(W)throw W;const V=[...new Set((q==null?void 0:q.map(ee=>ee.user_id))||[])],{data:K}=await U.from("profiles").select(` id, name, email, brokerages ( name ) `).in("id",V),Q=new Map((K==null?void 0:K.map(ee=>[ee.id,ee]))||[]),J=(D==null?void 0:D.map(ee=>{var le,he,ve,ge;return{id:ee.id,user_id:ee.user_id,app_name:ee.app_name,launched_at:ee.launched_at,user_name:((le=ee.profiles)==null?void 0:le.name)||"Unknown",user_email:((he=ee.profiles)==null?void 0:he.email)||"Unknown",brokerage_name:((ge=(ve=ee.profiles)==null?void 0:ve.brokerages)==null?void 0:ge.name)||null}}))||[],ce=(q==null?void 0:q.map(ee=>{var he;const le=Q.get(ee.user_id);return{id:ee.id,user_id:ee.user_id,resource_type:ee.resource_type,resource_id:ee.resource_id,resource_title:ee.resource_title,action_type:ee.action_type,created_at:ee.created_at,user_name:(le==null?void 0:le.name)||"Unknown",user_email:(le==null?void 0:le.email)||"Unknown",brokerage_name:((he=le==null?void 0:le.brokerages)==null?void 0:he.name)||null}}))||[];n(J),a(ce);const ue=new Map;J.forEach(ee=>{if(!ue.has(ee.user_id))ue.set(ee.user_id,{user_id:ee.user_id,user_name:ee.user_name,user_email:ee.user_email,brokerage_name:ee.brokerage_name,last_activity_type:"app",last_activity_name:ee.app_name,last_activity_at:ee.launched_at,total_app_launches:1,total_content_views:0});else{const le=ue.get(ee.user_id);le.total_app_launches++,new Date(ee.launched_at)>new Date(le.last_activity_at)&&(le.last_activity_type="app",le.last_activity_name=ee.app_name,le.last_activity_at=ee.launched_at)}}),ce.forEach(ee=>{if(!ue.has(ee.user_id))ue.set(ee.user_id,{user_id:ee.user_id,user_name:ee.user_name,user_email:ee.user_email,brokerage_name:ee.brokerage_name,last_activity_type:ee.resource_type,last_activity_name:ee.resource_title,last_activity_at:ee.created_at,total_app_launches:0,total_content_views:1});else{const le=ue.get(ee.user_id);le.total_content_views++,new Date(ee.created_at)>new Date(le.last_activity_at)&&(le.last_activity_type=ee.resource_type,le.last_activity_name=ee.resource_title,le.last_activity_at=ee.created_at)}});const ne=Array.from(ue.values()).sort((ee,le)=>new Date(le.last_activity_at).getTime()-new Date(ee.last_activity_at).getTime());l(ne)}catch(D){console.error("Error loading activity:",D),s({title:"Error",description:"Failed to load activity logs",variant:"destructive"})}finally{c(!1)}},v=D=>{m({id:D.user_id,name:D.user_name,email:D.user_email});const B=t.filter(W=>W.user_id===D.user_id),q=r.filter(W=>W.user_id===D.user_id);x(B),y(q)},N=()=>{m(null),x([]),y([])},{sortKey:C,sortDirection:A,handleSort:T,sortData:P}=Iee("last_activity_at","desc"),M=i.filter(D=>{var q;if(!d)return!0;const B=d.toLowerCase();return D.user_name.toLowerCase().includes(B)||D.user_email.toLowerCase().includes(B)||((q=D.brokerage_name)==null?void 0:q.toLowerCase().includes(B))}),I=P(M,{user:D=>{var B;return((B=D.user_name)==null?void 0:B.toLowerCase())||""},brokerage:D=>{var B;return((B=D.brokerage_name)==null?void 0:B.toLowerCase())||""},last_activity_at:D=>new Date(D.last_activity_at).getTime(),apps:D=>D.total_app_launches,content:D=>D.total_content_views});return o?e.jsx(_e,{children:e.jsx(Oe,{className:"flex items-center justify-center py-8",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})})}):e.jsxs(e.Fragment,{children:[e.jsxs(_e,{children:[e.jsxs(Bt,{children:[e.jsx(Ut,{children:"User Activity"}),e.jsx(vr,{children:"App launches and content engagement - click to see full history"})]}),e.jsxs(Oe,{children:[e.jsx("div",{className:"mb-4",children:e.jsxs("div",{className:"relative",children:[e.jsx(Vr,{className:"absolute left-3 top-3 h-4 w-4 text-muted-foreground"}),e.jsx(be,{placeholder:"Search by name, email, or brokerage...",value:d,onChange:D=>u(D.target.value),className:"pl-9"})]})}),e.jsx("div",{className:"rounded-md border",children:e.jsxs(Va,{children:[e.jsx(Ha,{children:e.jsxs(hn,{children:[e.jsx(Ku,{sortKey:"user",currentSortKey:C,currentDirection:A,onSort:T,children:"User"}),e.jsx(Ku,{sortKey:"brokerage",currentSortKey:C,currentDirection:A,onSort:T,children:"Brokerage"}),e.jsx(Lt,{children:"Last Activity"}),e.jsx(Ku,{sortKey:"last_activity_at",currentSortKey:C,currentDirection:A,onSort:T,children:"Last Active"}),e.jsx(Ku,{sortKey:"apps",currentSortKey:C,currentDirection:A,onSort:T,className:"text-right",children:"Apps"}),e.jsx(Ku,{sortKey:"content",currentSortKey:C,currentDirection:A,onSort:T,className:"text-right",children:"Content"})]})}),e.jsx(Ga,{children:I.length===0?e.jsx(hn,{children:e.jsx(gt,{colSpan:6,className:"text-center text-muted-foreground",children:"No activity found"})}):I.map(D=>e.jsxs(hn,{className:"cursor-pointer hover:bg-muted/50 transition-colors",onClick:()=>v(D),children:[e.jsx(gt,{children:e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:D.user_name}),e.jsx("div",{className:"text-sm text-muted-foreground",children:D.user_email})]})}),e.jsx(gt,{children:D.brokerage_name?e.jsx($e,{variant:"outline",children:D.brokerage_name}):e.jsx("span",{className:"text-muted-foreground text-sm",children:"-"})}),e.jsx(gt,{children:e.jsx("div",{className:"flex items-center gap-2",children:D.last_activity_type==="app"?e.jsxs($e,{variant:"secondary",children:[e.jsx(Tr,{className:"h-3 w-3 mr-1"}),D.last_activity_name]}):e.jsxs($e,{variant:"outline",className:"flex items-center gap-1",children:[Eut(D.last_activity_type),e.jsx("span",{className:"max-w-32 truncate",children:D.last_activity_name})]})})}),e.jsx(gt,{className:"text-sm text-muted-foreground",children:fc(new Date(D.last_activity_at),{addSuffix:!0})}),e.jsx(gt,{className:"text-right",children:e.jsx($e,{variant:"outline",children:D.total_app_launches})}),e.jsx(gt,{className:"text-right",children:e.jsx($e,{variant:"outline",children:D.total_content_views})})]},D.user_id))})]})})]})]}),e.jsx(Os,{open:!!h,onOpenChange:D=>!D&&N(),children:e.jsxs(Rs,{className:"max-w-3xl max-h-[80vh] overflow-hidden flex flex-col",children:[e.jsxs(Us,{children:[e.jsxs(zs,{children:[h==null?void 0:h.name,"'s Activity"]}),e.jsx(Sr,{children:h==null?void 0:h.email})]}),e.jsxs(ua,{defaultValue:"content",className:"flex-1 overflow-hidden flex flex-col",children:[e.jsxs(ha,{className:"grid w-full grid-cols-2",children:[e.jsxs(Qt,{value:"content",children:["Content (",g.length,")"]}),e.jsxs(Qt,{value:"apps",children:["App Launches (",p.length,")"]})]}),e.jsx(Jt,{value:"content",className:"flex-1 overflow-auto mt-4",children:e.jsx("div",{className:"rounded-md border",children:e.jsxs(Va,{children:[e.jsx(Ha,{children:e.jsxs(hn,{children:[e.jsx(Lt,{children:"Type"}),e.jsx(Lt,{children:"Resource"}),e.jsx(Lt,{children:"Action"}),e.jsx(Lt,{children:"Time"})]})}),e.jsx(Ga,{children:g.length===0?e.jsx(hn,{children:e.jsx(gt,{colSpan:4,className:"text-center text-muted-foreground",children:"No content engagement"})}):g.map(D=>e.jsxs(hn,{children:[e.jsx(gt,{children:e.jsxs($e,{variant:"outline",className:"flex items-center gap-1 w-fit",children:[Eut(D.resource_type),dHs(D.resource_type)]})}),e.jsx(gt,{className:"max-w-48",children:e.jsx("span",{className:"truncate block",children:D.resource_title})}),e.jsx(gt,{children:e.jsx($e,{variant:"secondary",children:uHs(D.action_type)})}),e.jsx(gt,{className:"text-sm text-muted-foreground",children:fc(new Date(D.created_at),{addSuffix:!0})})]},D.id))})]})})}),e.jsx(Jt,{value:"apps",className:"flex-1 overflow-auto mt-4",children:e.jsx("div",{className:"rounded-md border",children:e.jsxs(Va,{children:[e.jsx(Ha,{children:e.jsxs(hn,{children:[e.jsx(Lt,{children:"App"}),e.jsx(Lt,{children:"Time"})]})}),e.jsx(Ga,{children:p.length===0?e.jsx(hn,{children:e.jsx(gt,{colSpan:2,className:"text-center text-muted-foreground",children:"No app launches"})}):p.map(D=>e.jsxs(hn,{children:[e.jsx(gt,{children:e.jsx($e,{variant:"secondary",children:D.app_name})}),e.jsx(gt,{className:"text-sm text-muted-foreground",children:fc(new Date(D.launched_at),{addSuffix:!0})})]},D.id))})]})})})]})]})})]})},mHs=()=>{const{toast:s}=gi(),[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 U.from("profiles").select("*",{count:"exact",head:!0}),{count:o}=await U.from("profiles").select("*",{count:"exact",head:!0}).not("last_login","is",null),c=(l||0)-(o||0),{count:d}=await U.from("brokerages").select("*",{count:"exact",head:!0}),{count:u}=await U.from("activity_logs").select("*",{count:"exact",head:!0}),h=new Date;h.setDate(h.getDate()-7);const{count:m}=await U.from("activity_logs").select("*",{count:"exact",head:!0}).gte("launched_at",h.toISOString()),p=new Date;p.setMonth(p.getMonth()-1);const{count:x}=await U.from("activity_logs").select("*",{count:"exact",head:!0}).gte("launched_at",p.toISOString()),{data:g}=await U.from("activity_logs").select("user_id").gte("launched_at",h.toISOString()),y=new Set(g==null?void 0:g.map(b=>b.user_id)).size;n({totalUsers:l||0,activeUsers:o||0,pendingUsers:c,totalBrokerages:d||0,totalLaunches:u||0,launchesThisWeek:m||0,launchesThisMonth:x||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(_e,{children:e.jsx(Oe,{className:"flex items-center justify-center py-8",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})})}):e.jsxs("div",{className:"grid gap-4 md:grid-cols-2 lg:grid-cols-4",children:[e.jsxs(_e,{children:[e.jsxs(Bt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Ut,{className:"text-sm font-medium",children:"Total Users"}),e.jsx(qn,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Oe,{children:[e.jsx("div",{className:"text-2xl font-bold",children:t.totalUsers}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[t.activeUsers," active, ",t.pendingUsers," pending"]})]})]}),e.jsxs(_e,{children:[e.jsxs(Bt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Ut,{className:"text-sm font-medium",children:"Active Users"}),e.jsx(Ro,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Oe,{children:[e.jsx("div",{className:"text-2xl font-bold",children:t.activeUsers}),e.jsx("p",{className:"text-xs text-muted-foreground",children:t.totalUsers>0?`${Math.round(t.activeUsers/t.totalUsers*100)}% of total`:"0% of total"})]})]}),e.jsxs(_e,{children:[e.jsxs(Bt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Ut,{className:"text-sm font-medium",children:"Pending Invites"}),e.jsx(Hr,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Oe,{children:[e.jsx("div",{className:"text-2xl font-bold",children:t.pendingUsers}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Awaiting setup"})]})]}),e.jsxs(_e,{children:[e.jsxs(Bt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Ut,{className:"text-sm font-medium",children:"Brokerages"}),e.jsx(Ai,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Oe,{children:[e.jsx("div",{className:"text-2xl font-bold",children:t.totalBrokerages}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Total brokerages"})]})]}),e.jsxs(_e,{children:[e.jsxs(Bt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Ut,{className:"text-sm font-medium",children:"Total App Launches"}),e.jsx(zp,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Oe,{children:[e.jsx("div",{className:"text-2xl font-bold",children:t.totalLaunches}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"All time"})]})]}),e.jsxs(_e,{children:[e.jsxs(Bt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Ut,{className:"text-sm font-medium",children:"Launches This Week"}),e.jsx(zp,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Oe,{children:[e.jsx("div",{className:"text-2xl font-bold",children:t.launchesThisWeek}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Last 7 days"})]})]}),e.jsxs(_e,{children:[e.jsxs(Bt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Ut,{className:"text-sm font-medium",children:"Launches This Month"}),e.jsx(zp,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Oe,{children:[e.jsx("div",{className:"text-2xl font-bold",children:t.launchesThisMonth}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Last 30 days"})]})]}),e.jsxs(_e,{children:[e.jsxs(Bt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Ut,{className:"text-sm font-medium",children:"Active This Week"}),e.jsx(Il,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Oe,{children:[e.jsx("div",{className:"text-2xl font-bold",children:t.uniqueActiveThisWeek}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Unique users"})]})]})]})},Tut={event:"Event",template:"Template",academy_video:"Academy Video",resource_kit:"Resource Kit",newsletter:"Newsletter",social_swag:"Social Swag"},Mut={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 q8t({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 U.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 P=U.from("resource_shares").select("*").order("created_at",{ascending:!1});s&&T.length>0&&(P=P.or(`sender_id.in.(${T.join(",")}),recipient_id.in.(${T.join(",")})`));const{data:M,error:I}=await P;if(I)throw I;const D=new Set;M==null||M.forEach(V=>{D.add(V.sender_id),D.add(V.recipient_id)});const{data:B}=await U.from("profiles").select("id, name, email").in("id",Array.from(D)),q=new Map((B==null?void 0:B.map(V=>[V.id,V]))||[]),W=(M==null?void 0:M.map(V=>({...V,sender:q.get(V.sender_id),recipient:q.get(V.recipient_id)})))||[];r(W)}catch(T){console.error("Error loading shares:",T)}finally{i(!1)}},{sortKey:h,sortDirection:m,handleSort:p,sortData:x}=Iee("created_at","desc"),g=n.filter(T=>{var I,D;const P=l===""||T.resource_title.toLowerCase().includes(l.toLowerCase())||((I=T.sender)==null?void 0:I.name.toLowerCase().includes(l.toLowerCase()))||((D=T.recipient)==null?void 0:D.name.toLowerCase().includes(l.toLowerCase())),M=c==="all"||T.resource_type===c;return P&&M}),y=x(g,{resource:T=>{var P;return((P=T.resource_title)==null?void 0:P.toLowerCase())||""},type:T=>T.resource_type,sender:T=>{var P,M;return((M=(P=T.sender)==null?void 0:P.name)==null?void 0:M.toLowerCase())||""},recipient:T=>{var P,M;return((M=(P=T.recipient)==null?void 0:P.name)==null?void 0:M.toLowerCase())||""},status:T=>T.is_read?1:0,created_at:T=>new Date(T.created_at).getTime()}),b=n.length,v=new Set(n.map(T=>T.sender_id)).size,N=new Set(n.map(T=>T.recipient_id)).size,C=n.length>0?Math.round(n.filter(T=>T.is_read).length/n.length*100):0,A=n.reduce((T,P)=>(T[P.resource_type]=(T[P.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,P)=>e.jsxs(_e,{children:[e.jsx(Bt,{className:"pb-2",children:e.jsx(on,{className:"h-4 w-20"})}),e.jsx(Oe,{children:e.jsx(on,{className:"h-8 w-16"})})]},P))}),e.jsx(_e,{children:e.jsx(Oe,{className:"p-6",children:e.jsx(on,{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(_e,{children:[e.jsxs(Bt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Ut,{className:"text-sm font-medium",children:"Total Shares"}),e.jsx(vd,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsx(Oe,{children:e.jsx("div",{className:"text-2xl font-bold",children:b})})]}),e.jsxs(_e,{children:[e.jsxs(Bt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Ut,{className:"text-sm font-medium",children:"Active Sharers"}),e.jsx(qn,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsx(Oe,{children:e.jsx("div",{className:"text-2xl font-bold",children:v})})]}),e.jsxs(_e,{children:[e.jsxs(Bt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Ut,{className:"text-sm font-medium",children:"Recipients Reached"}),e.jsx(Il,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsx(Oe,{children:e.jsx("div",{className:"text-2xl font-bold",children:N})})]}),e.jsxs(_e,{children:[e.jsxs(Bt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Ut,{className:"text-sm font-medium",children:"Read Rate"}),e.jsx(Wr,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsx(Oe,{children:e.jsxs("div",{className:"text-2xl font-bold",children:[C,"%"]})})]})]}),e.jsxs(_e,{children:[e.jsx(Bt,{children:e.jsx(Ut,{className:"text-sm font-medium",children:"Shares by Resource Type"})}),e.jsx(Oe,{children:e.jsxs("div",{className:"flex flex-wrap gap-2",children:[Object.entries(A).map(([T,P])=>e.jsxs($e,{variant:"secondary",className:Mut[T],children:[Tut[T],": ",P]},T)),Object.keys(A).length===0&&e.jsx("span",{className:"text-muted-foreground text-sm",children:"No shares yet"})]})})]}),e.jsxs(_e,{children:[e.jsxs(Bt,{children:[e.jsx(Ut,{children:"Share History"}),e.jsxs(vr,{children:["All resource shares ",s?"in your brokerage":"across the platform"]})]}),e.jsxs(Oe,{children:[e.jsxs("div",{className:"flex flex-col sm:flex-row gap-4 mb-4",children:[e.jsxs("div",{className:"relative flex-1",children:[e.jsx(Vr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(be,{placeholder:"Search by resource, sender, or recipient...",value:l,onChange:T=>o(T.target.value),className:"pl-9"})]}),e.jsxs(vs,{value:c,onValueChange:d,children:[e.jsx(gs,{className:"w-[180px]",children:e.jsx(bs,{placeholder:"Resource type"})}),e.jsxs(ys,{children:[e.jsx(Ye,{value:"all",children:"All Types"}),e.jsx(Ye,{value:"event",children:"Events"}),e.jsx(Ye,{value:"template",children:"Templates"}),e.jsx(Ye,{value:"academy_video",children:"Academy Videos"}),e.jsx(Ye,{value:"resource_kit",children:"Resource Kits"}),e.jsx(Ye,{value:"newsletter",children:"Newsletters"}),e.jsx(Ye,{value:"social_swag",children:"Social Swag"})]})]})]}),e.jsx(Oi,{className:"h-[400px]",children:e.jsxs(Va,{children:[e.jsx(Ha,{children:e.jsxs(hn,{children:[e.jsx(Ku,{sortKey:"resource",currentSortKey:h,currentDirection:m,onSort:p,children:"Resource"}),e.jsx(Ku,{sortKey:"type",currentSortKey:h,currentDirection:m,onSort:p,children:"Type"}),e.jsx(Ku,{sortKey:"sender",currentSortKey:h,currentDirection:m,onSort:p,children:"Sender"}),e.jsx(Ku,{sortKey:"recipient",currentSortKey:h,currentDirection:m,onSort:p,children:"Recipient"}),e.jsx(Ku,{sortKey:"status",currentSortKey:h,currentDirection:m,onSort:p,children:"Status"}),e.jsx(Ku,{sortKey:"created_at",currentSortKey:h,currentDirection:m,onSort:p,children:"Date"})]})}),e.jsx(Ga,{children:y.length===0?e.jsx(hn,{children:e.jsx(gt,{colSpan:6,className:"text-center text-muted-foreground py-8",children:"No shares found"})}):y.map(T=>{var P,M;return e.jsxs(hn,{children:[e.jsx(gt,{className:"font-medium max-w-[200px] truncate",children:T.resource_title}),e.jsx(gt,{children:e.jsx($e,{variant:"secondary",className:Mut[T.resource_type],children:Tut[T.resource_type]})}),e.jsx(gt,{children:((P=T.sender)==null?void 0:P.name)||"Unknown"}),e.jsx(gt,{children:((M=T.recipient)==null?void 0:M.name)||"Unknown"}),e.jsx(gt,{children:e.jsx($e,{variant:T.is_read?"default":"outline",children:T.is_read?"Read":"Unread"})}),e.jsx(gt,{className:"text-muted-foreground",children:Hs(new Date(T.created_at),"MMM d, yyyy")})]},T.id)})})]})})]})]})]})}const EIe={academy_video:{label:"Academy Videos",icon:Xr,color:"bg-purple-100 text-purple-800",actionLabel:"Watched",actionIcon:ga},template:{label:"Templates",icon:Q4,color:"bg-blue-100 text-blue-800",actionLabel:"Accessed",actionIcon:pg},toolbox:{label:"Toolkit",icon:c5,color:"bg-amber-100 text-amber-800",actionLabel:"Downloaded",actionIcon:di},newsletter:{label:"Newsletters",icon:nn,color:"bg-emerald-100 text-emerald-800",actionLabel:"Clicked",actionIcon:pg},social_swag:{label:"Social Swag",icon:Rc,color:"bg-pink-100 text-pink-800",actionLabel:"Accessed",actionIcon:pg},event:{label:"Events",icon:ia,color:"bg-cyan-100 text-cyan-800",actionLabel:"Registered",actionIcon:pg}};function Lut(s){return s.resource_type==="toolbox"?s.total_downloads:s.total_clicks}function pHs(s,t){return s==="toolbox"?t.downloads:t.clicks}function fHs(){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}=Iee("total_views","desc");j.useEffect(()=>{h()},[]);const h=async()=>{try{const{data:P,error:M}=await U.rpc("get_admin_content_engagement");if(M)throw M;t(P||[])}catch(P){console.error("Error loading content engagement:",P)}finally{r(!1)}},m=P=>{i(M=>{const I=M===P?null:P;return requestAnimationFrame(()=>{var D;(D=l.current)==null||D.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((P,M)=>e.jsxs(_e,{children:[e.jsx(Bt,{className:"pb-2",children:e.jsx(on,{className:"h-4 w-20"})}),e.jsx(Oe,{children:e.jsx(on,{className:"h-8 w-16"})})]},M))}),e.jsx(_e,{children:e.jsx(Oe,{className:"py-8",children:e.jsx(on,{className:"h-64 w-full"})})})]});const p=s.reduce((P,M)=>P+M.total_views,0),x=s.reduce((P,M)=>P+M.total_clicks,0),g=s.reduce((P,M)=>P+M.total_downloads,0),y=s.length,b=s.reduce((P,M)=>(P[M.resource_type]||(P[M.resource_type]={views:0,clicks:0,downloads:0,assets:0,uniqueUsers:0}),P[M.resource_type].views+=M.total_views,P[M.resource_type].clicks+=M.total_clicks,P[M.resource_type].downloads+=M.total_downloads,P[M.resource_type].assets+=1,P[M.resource_type].uniqueUsers+=M.unique_users,P),{}),v=a?s.filter(P=>P.resource_type===a):s,N=u(v,{asset:P=>{var M;return((M=P.resource_title)==null?void 0:M.toLowerCase())||""},type:P=>P.resource_type,views:P=>P.total_views,actions:P=>Lut(P),unique_users:P=>P.unique_users,last_activity:P=>P.last_engaged_at?new Date(P.last_engaged_at).getTime():0}),C=a?EIe[a]||{label:a,icon:ga,color:"bg-muted text-muted-foreground",actionLabel:"Actions",actionIcon:pg}:null,A=C==null?void 0:C.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(_e,{children:[e.jsxs(Bt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Ut,{className:"text-sm font-medium",children:"Total Views"}),e.jsx(ga,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Oe,{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(_e,{children:[e.jsxs(Bt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Ut,{className:"text-sm font-medium",children:"Total Clicks"}),e.jsx(pg,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Oe,{children:[e.jsx("div",{className:"text-2xl font-bold",children:x.toLocaleString()}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Link & Canva clicks"})]})]}),e.jsxs(_e,{children:[e.jsxs(Bt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Ut,{className:"text-sm font-medium",children:"Downloads"}),e.jsx(di,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Oe,{children:[e.jsx("div",{className:"text-2xl font-bold",children:g.toLocaleString()}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"PDF downloads"})]})]}),e.jsxs(_e,{children:[e.jsxs(Bt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Ut,{className:"text-sm font-medium",children:"Assets Tracked"}),e.jsx(Il,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Oe,{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(_e,{children:[e.jsxs(Bt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Ut,{className:"text-sm font-medium",children:"Click Rate"}),e.jsx(pg,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Oe,{children:[e.jsxs("div",{className:"text-2xl font-bold",children:[p>0?Math.round((x+g)/p*100):0,"%"]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Of views → actions"})]})]})]}),e.jsxs(_e,{children:[e.jsxs(Bt,{children:[e.jsx(Ut,{className:"text-sm font-medium",children:"Engagement by Content Type"}),e.jsx(vr,{children:"Click a category to see individual asset performance"})]}),e.jsx(Oe,{children:e.jsx("div",{className:"grid gap-3 grid-cols-2 md:grid-cols-3",children:Object.entries(b).map(([P,M])=>{const I=EIe[P]||{label:P,icon:ga,color:"bg-muted text-muted-foreground",actionLabel:"Actions",actionIcon:pg},D=I.icon,B=a===P;return e.jsxs("button",{type:"button",onClick:()=>m(P),className:`flex items-center gap-3 p-3 rounded-lg border text-left transition-colors cursor-pointer ${B?"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(D,{className:"h-4 w-4"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium",children: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(ga,{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"})," ",pHs(P,M)]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(qn,{className:"h-3 w-3"})," ",M.uniqueUsers]})]})]}),e.jsxs($e,{variant:"secondary",className:"text-[10px]",children:[M.assets," items"]})]},P)})})})]}),e.jsx("div",{ref:l,children:e.jsxs(_e,{children:[e.jsx(Bt,{children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(Ut,{className:"text-sm font-medium flex items-center gap-2",children:C&&A?e.jsxs(e.Fragment,{children:[e.jsx(A,{className:"h-4 w-4"}),C.label," — Top Performers"]}):"Top Content by Engagement"}),e.jsx(vr,{children:a?`${v.length} ${((T=C==null?void 0:C.label)==null?void 0:T.toLowerCase())||"items"} ranked by total interactions`:"All tracked assets ranked by total interactions"})]}),a&&e.jsxs($,{variant:"ghost",size:"sm",onClick:()=>i(null),className:"gap-1",children:[e.jsx(ka,{className:"h-3.5 w-3.5"}),"Show All"]})]})}),e.jsx(Oe,{children:v.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(Oi,{className:"h-[400px]",children:e.jsxs(Va,{children:[e.jsx(Ha,{children:e.jsxs(hn,{children:[e.jsx(Lt,{className:"w-[40px]",children:"#"}),e.jsx(Ku,{sortKey:"asset",currentSortKey:o,currentDirection:c,onSort:d,children:"Asset"}),!a&&e.jsx(Ku,{sortKey:"type",currentSortKey:o,currentDirection:c,onSort:d,children:"Type"}),e.jsx(Ku,{sortKey:"views",currentSortKey:o,currentDirection:c,onSort:d,className:"text-right",children:"Views"}),e.jsx(Ku,{sortKey:"actions",currentSortKey:o,currentDirection:c,onSort:d,className:"text-right",children:C?C.actionLabel:"Actions"}),e.jsx(Ku,{sortKey:"unique_users",currentSortKey:o,currentDirection:c,onSort:d,className:"text-right",children:"Unique Users"}),e.jsx(Ku,{sortKey:"last_activity",currentSortKey:o,currentDirection:c,onSort:d,children:"Last Activity"})]})}),e.jsx(Ga,{children:N.map((P,M)=>{const I=EIe[P.resource_type]||{label:P.resource_type,color:"bg-muted text-muted-foreground",actionLabel:"Actions",actionIcon:pg};return e.jsxs(hn,{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:P.resource_title})}),!a&&e.jsx(gt,{children:e.jsx($e,{className:`text-[10px] ${I.color}`,children:I.label})}),e.jsx(gt,{className:"text-right font-medium",children:P.total_views}),e.jsx(gt,{className:"text-right font-medium",children:Lut(P)}),e.jsx(gt,{className:"text-right",children:P.unique_users}),e.jsx(gt,{className:"text-xs text-muted-foreground",children:P.last_engaged_at?fc(new Date(P.last_engaged_at),{addSuffix:!0}):"—"})]},`${P.resource_type}-${P.resource_id}`)})})]})})})]})})]})}var xHs=Array.isArray,Wb=xHs,gHs=typeof Sm=="object"&&Sm&&Sm.Object===Object&&Sm,V8t=gHs,yHs=V8t,vHs=typeof self=="object"&&self&&self.Object===Object&&self,bHs=yHs||vHs||Function("return this")(),R5=bHs,_Hs=R5,wHs=_Hs.Symbol,Bee=wHs,Put=Bee,H8t=Object.prototype,jHs=H8t.hasOwnProperty,NHs=H8t.toString,fG=Put?Put.toStringTag:void 0;function kHs(s){var t=jHs.call(s,fG),n=s[fG];try{s[fG]=void 0;var r=!0}catch{}var a=NHs.call(s);return r&&(t?s[fG]=n:delete s[fG]),a}var SHs=kHs,CHs=Object.prototype,AHs=CHs.toString;function EHs(s){return AHs.call(s)}var THs=EHs,Iut=Bee,MHs=SHs,LHs=THs,PHs="[object Null]",IHs="[object Undefined]",Dut=Iut?Iut.toStringTag:void 0;function DHs(s){return s==null?s===void 0?IHs:PHs:Dut&&Dut in Object(s)?MHs(s):LHs(s)}var AC=DHs;function RHs(s){return s!=null&&typeof s=="object"}var EC=RHs,OHs=AC,FHs=EC,zHs="[object Symbol]";function BHs(s){return typeof s=="symbol"||FHs(s)&&OHs(s)==zHs}var Hq=BHs,$Hs=Wb,UHs=Hq,qHs=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,VHs=/^\w*$/;function HHs(s,t){if($Hs(s))return!1;var n=typeof s;return n=="number"||n=="symbol"||n=="boolean"||s==null||UHs(s)?!0:VHs.test(s)||!qHs.test(s)||t!=null&&s in Object(t)}var JWe=HHs;function GHs(s){var t=typeof s;return s!=null&&(t=="object"||t=="function")}var H6=GHs;const Gq=Uc(H6);var WHs=AC,KHs=H6,YHs="[object AsyncFunction]",ZHs="[object Function]",XHs="[object GeneratorFunction]",QHs="[object Proxy]";function JHs(s){if(!KHs(s))return!1;var t=WHs(s);return t==ZHs||t==XHs||t==YHs||t==QHs}var eKe=JHs;const dl=Uc(eKe);var eGs=R5,tGs=eGs["__core-js_shared__"],sGs=tGs,TIe=sGs,Rut=function(){var s=/[^.]+$/.exec(TIe&&TIe.keys&&TIe.keys.IE_PROTO||"");return s?"Symbol(src)_1."+s:""}();function nGs(s){return!!Rut&&Rut in s}var rGs=nGs,aGs=Function.prototype,iGs=aGs.toString;function oGs(s){if(s!=null){try{return iGs.call(s)}catch{}try{return s+""}catch{}}return""}var G8t=oGs,lGs=eKe,cGs=rGs,dGs=H6,uGs=G8t,hGs=/[\\^$.*+?()[\]{}|]/g,mGs=/^\[object .+?Constructor\]$/,pGs=Function.prototype,fGs=Object.prototype,xGs=pGs.toString,gGs=fGs.hasOwnProperty,yGs=RegExp("^"+xGs.call(gGs).replace(hGs,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function vGs(s){if(!dGs(s)||cGs(s))return!1;var t=lGs(s)?yGs:mGs;return t.test(uGs(s))}var bGs=vGs;function _Gs(s,t){return s==null?void 0:s[t]}var wGs=_Gs,jGs=bGs,NGs=wGs;function kGs(s,t){var n=NGs(s,t);return jGs(n)?n:void 0}var iF=kGs,SGs=iF,CGs=SGs(Object,"create"),HAe=CGs,Out=HAe;function AGs(){this.__data__=Out?Out(null):{},this.size=0}var EGs=AGs;function TGs(s){var t=this.has(s)&&delete this.__data__[s];return this.size-=t?1:0,t}var MGs=TGs,LGs=HAe,PGs="__lodash_hash_undefined__",IGs=Object.prototype,DGs=IGs.hasOwnProperty;function RGs(s){var t=this.__data__;if(LGs){var n=t[s];return n===PGs?void 0:n}return DGs.call(t,s)?t[s]:void 0}var OGs=RGs,FGs=HAe,zGs=Object.prototype,BGs=zGs.hasOwnProperty;function $Gs(s){var t=this.__data__;return FGs?t[s]!==void 0:BGs.call(t,s)}var UGs=$Gs,qGs=HAe,VGs="__lodash_hash_undefined__";function HGs(s,t){var n=this.__data__;return this.size+=this.has(s)?0:1,n[s]=qGs&&t===void 0?VGs:t,this}var GGs=HGs,WGs=EGs,KGs=MGs,YGs=OGs,ZGs=UGs,XGs=GGs;function Wq(s){var t=-1,n=s==null?0:s.length;for(this.clear();++t-1}var pWs=mWs,fWs=GAe;function xWs(s,t){var n=this.__data__,r=fWs(n,s);return r<0?(++this.size,n.push([s,t])):n[r][1]=t,this}var gWs=xWs,yWs=eWs,vWs=lWs,bWs=uWs,_Ws=pWs,wWs=gWs;function Kq(s){var t=-1,n=s==null?0:s.length;for(this.clear();++t0?1:-1},z8=function(t){return _O(t)&&t.indexOf("%")===t.length-1},za=function(t){return VKs(t)&&!Zq(t)},KKs=function(t){return Pl(t)},yg=function(t){return za(t)||_O(t)},YKs=0,oF=function(t){var n=++YKs;return"".concat(t||"").concat(n)},d1=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(!za(t)&&!_O(t))return r;var i;if(z8(t)){var l=t.indexOf("%");i=n*parseFloat(t.slice(0,l))/100}else i=+t;return Zq(i)&&(i=r),a&&i>n&&(i=n),i},nE=function(t){if(!t)return null;var n=Object.keys(t);return n&&n.length?t[n[0]]:null},ZKs=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 nYs(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 v9e(s){"@babel/helpers - typeof";return v9e=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},v9e(s)}var Vut={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"},Z3=function(t){return typeof t=="string"?t:t?t.displayName||t.name||"Component":""},Hut=null,LIe=null,dKe=function s(t){if(t===Hut&&Array.isArray(LIe))return LIe;var n=[];return j.Children.forEach(t,function(r){Pl(r)||(zKs.isFragment(r)?n=n.concat(s(r.props.children)):n.push(r))}),LIe=n,Hut=t,n};function lw(s,t){var n=[],r=[];return Array.isArray(t)?r=t.map(function(a){return Z3(a)}):r=[Z3(t)],dKe(s).forEach(function(a){var i=ow(a,"type.displayName")||ow(a,"type.name");r.indexOf(i)!==-1&&n.push(a)}),n}function B_(s,t){var n=lw(s,t);return n&&n[0]}var Gut=function(t){if(!t||!t.props)return!1;var n=t.props,r=n.width,a=n.height;return!(!za(r)||r<=0||!za(a)||a<=0)},rYs=["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"],aYs=function(t){return t&&t.type&&_O(t.type)&&rYs.indexOf(t.type)>=0},sDt=function(t){return t&&v9e(t)==="object"&&"clipDot"in t},iYs=function(t,n,r,a){var i,l=(i=MIe==null?void 0:MIe[a])!==null&&i!==void 0?i:[];return n.startsWith("data-")||!dl(t)&&(a&&l.includes(n)||JKs.includes(n))||r&&cKe.includes(n)},So=function(t,n,r){if(!t||typeof t=="function"||typeof t=="boolean")return null;var a=t;if(j.isValidElement(t)&&(a=t.props),!Gq(a))return null;var i={};return Object.keys(a).forEach(function(l){var o;iYs((o=a)===null||o===void 0?void 0:o[l],l,n,r)&&(i[l]=a[l])}),i},b9e=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 Wut(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 uYs(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 w9e(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=dYs(s,cYs),u=a||{width:n,height:r,x:0,y:0},h=$l("recharts-surface",i);return It.createElement("svg",_9e({},So(d,!0,"svg"),{className:h,width:n,height:r,style:l,viewBox:"".concat(u.x," ").concat(u.y," ").concat(u.width," ").concat(u.height)}),It.createElement("title",null,o),It.createElement("desc",null,c),t)}var hYs=["children","className"];function j9e(){return j9e=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 pYs(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 Yc=It.forwardRef(function(s,t){var n=s.children,r=s.className,a=mYs(s,hYs),i=$l("recharts-layer",r);return It.createElement("g",j9e({className:i},So(a,!0),{ref:t}),n)}),BN=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:gYs(s,t,n)}var vYs=yYs,bYs="\\ud800-\\udfff",_Ys="\\u0300-\\u036f",wYs="\\ufe20-\\ufe2f",jYs="\\u20d0-\\u20ff",NYs=_Ys+wYs+jYs,kYs="\\ufe0e\\ufe0f",SYs="\\u200d",CYs=RegExp("["+SYs+bYs+NYs+kYs+"]");function AYs(s){return CYs.test(s)}var nDt=AYs;function EYs(s){return s.split("")}var TYs=EYs,rDt="\\ud800-\\udfff",MYs="\\u0300-\\u036f",LYs="\\ufe20-\\ufe2f",PYs="\\u20d0-\\u20ff",IYs=MYs+LYs+PYs,DYs="\\ufe0e\\ufe0f",RYs="["+rDt+"]",N9e="["+IYs+"]",k9e="\\ud83c[\\udffb-\\udfff]",OYs="(?:"+N9e+"|"+k9e+")",aDt="[^"+rDt+"]",iDt="(?:\\ud83c[\\udde6-\\uddff]){2}",oDt="[\\ud800-\\udbff][\\udc00-\\udfff]",FYs="\\u200d",lDt=OYs+"?",cDt="["+DYs+"]?",zYs="(?:"+FYs+"(?:"+[aDt,iDt,oDt].join("|")+")"+cDt+lDt+")*",BYs=cDt+lDt+zYs,$Ys="(?:"+[aDt+N9e+"?",N9e,iDt,oDt,RYs].join("|")+")",UYs=RegExp(k9e+"(?="+k9e+")|"+$Ys+BYs,"g");function qYs(s){return s.match(UYs)||[]}var VYs=qYs,HYs=TYs,GYs=nDt,WYs=VYs;function KYs(s){return GYs(s)?WYs(s):HYs(s)}var YYs=KYs,ZYs=vYs,XYs=nDt,QYs=YYs,JYs=Z8t;function eZs(s){return function(t){t=JYs(t);var n=XYs(t)?QYs(t):void 0,r=n?n[0]:t.charAt(0),a=n?ZYs(n,1).join(""):t.slice(1);return r[s]()+a}}var tZs=eZs,sZs=tZs,nZs=sZs("toUpperCase"),rZs=nZs;const iEe=Uc(rZs);function Wh(s){return function(){return s}}const dDt=Math.cos,c5e=Math.sin,ik=Math.sqrt,d5e=Math.PI,oEe=2*d5e,S9e=Math.PI,C9e=2*S9e,i8=1e-6,aZs=C9e-i8;function uDt(s){this._+=s[0];for(let t=1,n=s.length;t=0))throw new Error(`invalid digits: ${s}`);if(t>15)return uDt;const n=10**t;return function(r){this._+=r[0];for(let a=1,i=r.length;ai8)if(!(Math.abs(h*c-d*u)>i8)||!i)this._append`L${this._x1=t},${this._y1=n}`;else{let p=r-l,x=a-o,g=c*c+d*d,y=p*p+x*x,b=Math.sqrt(g),v=Math.sqrt(m),N=i*Math.tan((S9e-Math.acos((g+m-y)/(2*b*v)))/2),C=N/v,A=N/b;Math.abs(C-1)>i8&&this._append`L${t+C*u},${n+C*h}`,this._append`A${i},${i},0,0,${+(h*p>u*x)},${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)>i8||Math.abs(this._y1-u)>i8)&&this._append`L${d},${u}`,r&&(m<0&&(m=m%C9e+C9e),m>aZs?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>i8&&this._append`A${r},${r},0,${+(m>=S9e)},${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 uKe(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 oZs(t)}function hKe(s){return typeof s=="object"&&"length"in s?s:Array.from(s)}function hDt(s){this._context=s}hDt.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 lEe(s){return new hDt(s)}function mDt(s){return s[0]}function pDt(s){return s[1]}function fDt(s,t){var n=Wh(!0),r=null,a=lEe,i=null,l=uKe(o);s=typeof s=="function"?s:s===void 0?mDt:Wh(s),t=typeof t=="function"?t:t===void 0?pDt:Wh(t);function o(c){var d,u=(c=hKe(c)).length,h,m=!1,p;for(r==null&&(i=a(p=l())),d=0;d<=u;++d)!(d=p;--x)o.point(N[x],C[x]);o.lineEnd(),o.areaEnd()}b&&(N[m]=+s(y,m,h),C[m]=+t(y,m,h),o.point(r?+r(y,m,h):N[m],n?+n(y,m,h):C[m]))}if(v)return o=null,v+""||null}function u(){return fDt().defined(a).curve(l).context(i)}return d.x=function(h){return arguments.length?(s=typeof h=="function"?h:Wh(+h),r=null,d):s},d.x0=function(h){return arguments.length?(s=typeof h=="function"?h:Wh(+h),d):s},d.x1=function(h){return arguments.length?(r=h==null?null:typeof h=="function"?h:Wh(+h),d):r},d.y=function(h){return arguments.length?(t=typeof h=="function"?h:Wh(+h),n=null,d):t},d.y0=function(h){return arguments.length?(t=typeof h=="function"?h:Wh(+h),d):t},d.y1=function(h){return arguments.length?(n=h==null?null:typeof h=="function"?h:Wh(+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:Wh(!!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 xDt{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 lZs(s){return new xDt(s,!0)}function cZs(s){return new xDt(s,!1)}const mKe={draw(s,t){const n=ik(t/d5e);s.moveTo(n,0),s.arc(0,0,n,0,oEe)}},dZs={draw(s,t){const n=ik(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()}},gDt=ik(1/3),uZs=gDt*2,hZs={draw(s,t){const n=ik(t/uZs),r=n*gDt;s.moveTo(0,-n),s.lineTo(r,0),s.lineTo(0,n),s.lineTo(-r,0),s.closePath()}},mZs={draw(s,t){const n=ik(t),r=-n/2;s.rect(r,r,n,n)}},pZs=.8908130915292852,yDt=c5e(d5e/10)/c5e(7*d5e/10),fZs=c5e(oEe/10)*yDt,xZs=-dDt(oEe/10)*yDt,gZs={draw(s,t){const n=ik(t*pZs),r=fZs*n,a=xZs*n;s.moveTo(0,-n),s.lineTo(r,a);for(let i=1;i<5;++i){const l=oEe*i/5,o=dDt(l),c=c5e(l);s.lineTo(c*n,-o*n),s.lineTo(o*r-c*a,c*r+o*a)}s.closePath()}},PIe=ik(3),yZs={draw(s,t){const n=-ik(t/(PIe*3));s.moveTo(0,n*2),s.lineTo(-PIe*n,-n),s.lineTo(PIe*n,-n),s.closePath()}},ej=-.5,tj=ik(3)/2,A9e=1/ik(12),vZs=(A9e/2+1)*3,bZs={draw(s,t){const n=ik(t/vZs),r=n/2,a=n*A9e,i=r,l=n*A9e+n,o=-i,c=l;s.moveTo(r,a),s.lineTo(i,l),s.lineTo(o,c),s.lineTo(ej*r-tj*a,tj*r+ej*a),s.lineTo(ej*i-tj*l,tj*i+ej*l),s.lineTo(ej*o-tj*c,tj*o+ej*c),s.lineTo(ej*r+tj*a,ej*a-tj*r),s.lineTo(ej*i+tj*l,ej*l-tj*i),s.lineTo(ej*o+tj*c,ej*c-tj*o),s.closePath()}};function _Zs(s,t){let n=null,r=uKe(a);s=typeof s=="function"?s:Wh(s||mKe),t=typeof t=="function"?t:Wh(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:Wh(i),a):s},a.size=function(i){return arguments.length?(t=typeof i=="function"?i:Wh(+i),a):t},a.context=function(i){return arguments.length?(n=i??null,a):n},a}function u5e(){}function h5e(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 vDt(s){this._context=s}vDt.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:h5e(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:h5e(this,s,t);break}this._x0=this._x1,this._x1=s,this._y0=this._y1,this._y1=t}};function wZs(s){return new vDt(s)}function bDt(s){this._context=s}bDt.prototype={areaStart:u5e,areaEnd:u5e,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:h5e(this,s,t);break}this._x0=this._x1,this._x1=s,this._y0=this._y1,this._y1=t}};function jZs(s){return new bDt(s)}function _Dt(s){this._context=s}_Dt.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:h5e(this,s,t);break}this._x0=this._x1,this._x1=s,this._y0=this._y1,this._y1=t}};function NZs(s){return new _Dt(s)}function wDt(s){this._context=s}wDt.prototype={areaStart:u5e,areaEnd:u5e,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 kZs(s){return new wDt(s)}function Yut(s){return s<0?-1:1}function Zut(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(Yut(i)+Yut(l))*Math.min(Math.abs(i),Math.abs(l),.5*Math.abs(o))||0}function Xut(s,t){var n=s._x1-s._x0;return n?(3*(s._y1-s._y0)/n-t)/2:t}function IIe(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 m5e(s){this._context=s}m5e.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:IIe(this,this._t0,Xut(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,IIe(this,Xut(this,n=Zut(this,s,t)),n);break;default:IIe(this,this._t0,n=Zut(this,s,t));break}this._x0=this._x1,this._x1=s,this._y0=this._y1,this._y1=t,this._t0=n}}};function jDt(s){this._context=new NDt(s)}(jDt.prototype=Object.create(m5e.prototype)).point=function(s,t){m5e.prototype.point.call(this,t,s)};function NDt(s){this._context=s}NDt.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 SZs(s){return new m5e(s)}function CZs(s){return new jDt(s)}function kDt(s){this._context=s}kDt.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=Qut(s),a=Qut(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 EZs(s){return new cEe(s,.5)}function TZs(s){return new cEe(s,0)}function MZs(s){return new cEe(s,1)}function fU(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 LZs(s,t){return s[t]}function PZs(s){const t=[];return t.key=s,t}function IZs(){var s=Wh([]),t=E9e,n=fU,r=LZs;function a(i){var l=Array.from(s.apply(this,arguments),PZs),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 qZs(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 SDt={symbolCircle:mKe,symbolCross:dZs,symbolDiamond:hZs,symbolSquare:mZs,symbolStar:gZs,symbolTriangle:yZs,symbolWye:bZs},VZs=Math.PI/180,HZs=function(t){var n="symbol".concat(iEe(t));return SDt[n]||mKe},GZs=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*VZs;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}},WZs=function(t,n){SDt["symbol".concat(iEe(t))]=n},pKe=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=UZs(t,FZs),d=eht(eht({},c),{},{type:r,size:i,sizeType:o}),u=function(){var y=HZs(r),b=_Zs().type(y).size(GZs(i,o,r));return b()},h=d.className,m=d.cx,p=d.cy,x=So(d,!0);return m===+m&&p===+p&&i===+i?It.createElement("path",T9e({},x,{className:$l("recharts-symbols",h),transform:"translate(".concat(m,", ").concat(p,")"),d:u()})):null};pKe.registerSymbol=WZs;function xU(s){"@babel/helpers - typeof";return xU=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},xU(s)}function M9e(){return M9e=Object.assign?Object.assign.bind():function(s){for(var t=1;t`);var v=p.inactive?d:p.color;return It.createElement("li",M9e({className:y,style:h,key:"legend-item-".concat(x)},wO(r.props,p,x)),It.createElement(w9e,{width:l,height:l,viewBox:u,style:m},r.renderIcon(p)),It.createElement("span",{className:"recharts-legend-item-text",style:{color:v}},g?g(b,p,x):b))})}},{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 It.createElement("ul",{className:"recharts-default-legend",style:o},this.renderItems())}}])}(j.PureComponent);gX(fKe,"displayName","Legend");gX(fKe,"defaultProps",{iconSize:14,layout:"horizontal",align:"center",verticalAlign:"middle",inactiveColor:"#ccc"});var nXs=WAe;function rXs(){this.__data__=new nXs,this.size=0}var aXs=rXs;function iXs(s){var t=this.__data__,n=t.delete(s);return this.size=t.size,n}var oXs=iXs;function lXs(s){return this.__data__.get(s)}var cXs=lXs;function dXs(s){return this.__data__.has(s)}var uXs=dXs,hXs=WAe,mXs=sKe,pXs=nKe,fXs=200;function xXs(s,t){var n=this.__data__;if(n instanceof hXs){var r=n.__data__;if(!mXs||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&FXs?new IXs:void 0;for(i.set(s,t),i.set(t,s);++h-1&&s%1==0&&s-1&&s%1==0&&s<=UQs}var vKe=qQs,VQs=AC,HQs=vKe,GQs=EC,WQs="[object Arguments]",KQs="[object Array]",YQs="[object Boolean]",ZQs="[object Date]",XQs="[object Error]",QQs="[object Function]",JQs="[object Map]",eJs="[object Number]",tJs="[object Object]",sJs="[object RegExp]",nJs="[object Set]",rJs="[object String]",aJs="[object WeakMap]",iJs="[object ArrayBuffer]",oJs="[object DataView]",lJs="[object Float32Array]",cJs="[object Float64Array]",dJs="[object Int8Array]",uJs="[object Int16Array]",hJs="[object Int32Array]",mJs="[object Uint8Array]",pJs="[object Uint8ClampedArray]",fJs="[object Uint16Array]",xJs="[object Uint32Array]",ym={};ym[lJs]=ym[cJs]=ym[dJs]=ym[uJs]=ym[hJs]=ym[mJs]=ym[pJs]=ym[fJs]=ym[xJs]=!0;ym[WQs]=ym[KQs]=ym[iJs]=ym[YQs]=ym[oJs]=ym[ZQs]=ym[XQs]=ym[QQs]=ym[JQs]=ym[eJs]=ym[tJs]=ym[sJs]=ym[nJs]=ym[rJs]=ym[aJs]=!1;function gJs(s){return GQs(s)&&HQs(s.length)&&!!ym[VQs(s)]}var yJs=gJs;function vJs(s){return function(t){return s(t)}}var ODt=vJs,g5e={exports:{}};g5e.exports;(function(s,t){var n=V8t,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})(g5e,g5e.exports);var bJs=g5e.exports,_Js=yJs,wJs=ODt,oht=bJs,lht=oht&&oht.isTypedArray,jJs=lht?wJs(lht):_Js,FDt=jJs,NJs=CQs,kJs=gKe,SJs=Wb,CJs=RDt,AJs=yKe,EJs=FDt,TJs=Object.prototype,MJs=TJs.hasOwnProperty;function LJs(s,t){var n=SJs(s),r=!n&&kJs(s),a=!n&&!r&&CJs(s),i=!n&&!r&&!a&&EJs(s),l=n||r||a||i,o=l?NJs(s.length,String):[],c=o.length;for(var d in s)(t||MJs.call(s,d))&&!(l&&(d=="length"||a&&(d=="offset"||d=="parent")||i&&(d=="buffer"||d=="byteLength"||d=="byteOffset")||AJs(d,c)))&&o.push(d);return o}var PJs=LJs,IJs=Object.prototype;function DJs(s){var t=s&&s.constructor,n=typeof t=="function"&&t.prototype||IJs;return s===n}var RJs=DJs;function OJs(s,t){return function(n){return s(t(n))}}var zDt=OJs,FJs=zDt,zJs=FJs(Object.keys,Object),BJs=zJs,$Js=RJs,UJs=BJs,qJs=Object.prototype,VJs=qJs.hasOwnProperty;function HJs(s){if(!$Js(s))return UJs(s);var t=[];for(var n in Object(s))VJs.call(s,n)&&n!="constructor"&&t.push(n);return t}var GJs=HJs,WJs=eKe,KJs=vKe;function YJs(s){return s!=null&&KJs(s.length)&&!WJs(s)}var $ee=YJs,ZJs=PJs,XJs=GJs,QJs=$ee;function JJs(s){return QJs(s)?ZJs(s):XJs(s)}var dEe=JJs,een=fQs,ten=kQs,sen=dEe;function nen(s){return een(s,sen,ten)}var ren=nen,cht=ren,aen=1,ien=Object.prototype,oen=ien.hasOwnProperty;function len(s,t,n,r,a,i){var l=n&aen,o=cht(s),c=o.length,d=cht(t),u=d.length;if(c!=u&&!l)return!1;for(var h=c;h--;){var m=o[h];if(!(l?m in t:oen.call(t,m)))return!1}var p=i.get(s),x=i.get(t);if(p&&x)return p==t&&x==s;var g=!0;i.set(s,t),i.set(t,s);for(var y=l;++h-1}var isn=asn;function osn(s,t,n){for(var r=-1,a=s==null?0:s.length;++r=wsn){var d=t?null:bsn(s);if(d)return _sn(d);l=!1,a=vsn,c=new xsn}else c=t?[]:o;e:for(;++r=0)&&Object.prototype.propertyIsEnumerable.call(s,r)&&(n[r]=s[r])}return n}function Fsn(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){return s.value}function Bsn(s,t){if(It.isValidElement(s))return It.cloneElement(s,t);if(typeof s=="function")return It.createElement(s,t);t.ref;var n=Osn(t,Esn);return It.createElement(fKe,n)}var kht=1,FR=function(s){function t(){var n;Tsn(this,t);for(var r=arguments.length,a=new Array(r),i=0;ikht||Math.abs(a.height-this.lastBoundingBox.height)>kht)&&(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?N4({},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 x=this.getBBoxSnapshot();m={top:((u||0)-x.height)/2}}else m=o==="bottom"?{bottom:c&&c.bottom||0}:{top:c&&c.top||0};return N4(N4({},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=N4(N4({position:"absolute",width:l||"auto",height:o||"auto"},this.getDefaultPosition(c)),c);return It.createElement("div",{className:"recharts-legend-wrapper",style:h,ref:function(p){r.wrapperNode=p}},Bsn(i,N4(N4({},this.props),{},{payload:GDt(u,d,zsn)})))}}],[{key:"getWithHeight",value:function(r,a){var i=N4(N4({},this.defaultProps),r.props),l=i.layout;return l==="vertical"&&za(r.props.height)?{height:r.props.height}:l==="horizontal"?{width:r.props.width||a}:null}}])}(j.PureComponent);uEe(FR,"displayName","Legend");uEe(FR,"defaultProps",{iconSize:14,layout:"horizontal",align:"center",verticalAlign:"bottom"});var Sht=Bee,$sn=gKe,Usn=Wb,Cht=Sht?Sht.isConcatSpreadable:void 0;function qsn(s){return Usn(s)||$sn(s)||!!(Cht&&s&&s[Cht])}var Vsn=qsn,Hsn=IDt,Gsn=Vsn;function YDt(s,t,n,r,a){var i=-1,l=s.length;for(n||(n=Gsn),a||(a=[]);++i0&&n(o)?t>1?YDt(o,t-1,n,r,a):Hsn(a,o):r||(a[a.length]=o)}return a}var ZDt=YDt;function Wsn(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 Ksn=Wsn,Ysn=Ksn,Zsn=Ysn(),Xsn=Zsn,Qsn=Xsn,Jsn=dEe;function enn(s,t){return s&&Qsn(s,t,Jsn)}var XDt=enn,tnn=$ee;function snn(s,t){return function(n,r){if(n==null)return n;if(!tnn(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 xnn=fnn,FIe=aKe,gnn=iKe,ynn=O5,vnn=QDt,bnn=unn,_nn=ODt,wnn=xnn,jnn=Jq,Nnn=Wb;function knn(s,t,n){t.length?t=FIe(t,function(i){return Nnn(i)?function(l){return gnn(l,i.length===1?i[0]:i)}:i}):t=[jnn];var r=-1;t=FIe(t,_nn(ynn));var a=vnn(s,function(i,l,o){var c=FIe(t,function(d){return d(i)});return{criteria:c,index:++r,value:i}});return bnn(a,function(i,l){return wnn(i,l,n)})}var Snn=knn;function Cnn(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 Ann=Cnn,Enn=Ann,Eht=Math.max;function Tnn(s,t,n){return t=Eht(t===void 0?s.length-1:t,0),function(){for(var r=arguments,a=-1,i=Eht(r.length-t,0),l=Array(i);++a0){if(++t>=Bnn)return arguments[0]}else t=0;return s.apply(void 0,arguments)}}var Vnn=qnn,Hnn=znn,Gnn=Vnn,Wnn=Gnn(Hnn),Knn=Wnn,Ynn=Jq,Znn=Mnn,Xnn=Knn;function Qnn(s,t){return Xnn(Znn(s,t,Ynn),s+"")}var Jnn=Qnn,ern=tKe,trn=$ee,srn=yKe,nrn=H6;function rrn(s,t,n){if(!nrn(n))return!1;var r=typeof t;return(r=="number"?trn(n)&&srn(t,n.length):r=="string"&&t in n)?ern(n[t],s):!1}var hEe=rrn,arn=ZDt,irn=Snn,orn=Jnn,Mht=hEe,lrn=orn(function(s,t){if(s==null)return[];var n=t.length;return n>1&&Mht(s,t[0],t[1])?t=[]:n>2&&Mht(t[0],t[1],t[2])&&(t=[t[0]]),irn(s,arn(t,1),[])}),crn=lrn;const wKe=Uc(crn);function yX(s){"@babel/helpers - typeof";return yX=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},yX(s)}function z9e(){return z9e=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(xG,"-left"),za(n)&&t&&za(t.x)&&n=t.y),"".concat(xG,"-top"),za(r)&&t&&za(t.y)&&rg?Math.max(u,c[r]):Math.max(h,c[r])}function Nrn(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 krn(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=Iht({allowEscapeViewBox:t,coordinate:n,key:"x",offsetTopLeft:r,position:a,reverseDirection:i,tooltipDimension:l.width,viewBox:c,viewBoxDimension:c.width}),h=Iht({allowEscapeViewBox:t,coordinate:n,key:"y",offsetTopLeft:r,position:a,reverseDirection:i,tooltipDimension:l.height,viewBox:c,viewBoxDimension:c.height}),d=Nrn({translateX:u,translateY:h,useTranslate3d:o})):d=wrn,{cssProperties:d,cssClasses:jrn({translateX:u,translateY:h,coordinate:n})}}function yU(s){"@babel/helpers - typeof";return yU=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},yU(s)}function Dht(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 Rht(s){for(var t=1;tOht||Math.abs(r.height-this.state.lastBoundingBox.height)>Oht)&&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,x=a.position,g=a.reverseDirection,y=a.useTranslate3d,b=a.viewBox,v=a.wrapperStyle,N=krn({allowEscapeViewBox:l,coordinate:u,offsetTopLeft:p,position:x,reverseDirection:g,tooltipBox:this.state.lastBoundingBox,useTranslate3d:y,viewBox:b}),C=N.cssClasses,A=N.cssProperties,T=Rht(Rht({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},v);return It.createElement("div",{tabIndex:-1,className:C,style:T,ref:function(M){r.wrapperNode=M}},d)}}])}(j.PureComponent),Drn=function(){return!(typeof window<"u"&&window.document&&window.document.createElement&&window.setTimeout)},$N={isSsr:Drn(),get:function(t){return $N[t]},set:function(t,n){if(typeof t=="string")$N[t]=n;else{var r=Object.keys(t);r&&r.length&&r.forEach(function(a){$N[a]=t[a]})}}};function vU(s){"@babel/helpers - typeof";return vU=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},vU(s)}function Fht(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 zht(s){for(var t=1;t0;return It.createElement(Irn,{allowEscapeViewBox:l,animationDuration:o,animationEasing:c,isAnimationActive:m,active:i,coordinate:u,hasPayload:T,offset:p,position:y,reverseDirection:b,useTranslate3d:v,viewBox:N,wrapperStyle:C},Hrn(d,zht(zht({},this.props),{},{payload:A})))}}])}(j.PureComponent);jKe(yf,"displayName","Tooltip");jKe(yf,"defaultProps",{accessibilityLayer:!1,allowEscapeViewBox:{x:!1,y:!1},animationDuration:400,animationEasing:"ease",contentStyle:{},coordinate:{x:0,y:0},cursor:!0,cursorStyle:{},filterNull:!0,isAnimationActive:!$N.isSsr,itemStyle:{},labelStyle:{},offset:10,reverseDirection:{x:!1,y:!1},separator:" : ",trigger:"hover",useTranslate3d:!1,viewBox:{x:0,y:0,height:0,width:0},wrapperStyle:{}});var Grn=R5,Wrn=function(){return Grn.Date.now()},Krn=Wrn,Yrn=/\s/;function Zrn(s){for(var t=s.length;t--&&Yrn.test(s.charAt(t)););return t}var Xrn=Zrn,Qrn=Xrn,Jrn=/^\s+/;function ean(s){return s&&s.slice(0,Qrn(s)+1).replace(Jrn,"")}var tan=ean,san=tan,Bht=H6,nan=Hq,$ht=NaN,ran=/^[-+]0x[0-9a-f]+$/i,aan=/^0b[01]+$/i,ian=/^0o[0-7]+$/i,oan=parseInt;function lan(s){if(typeof s=="number")return s;if(nan(s))return $ht;if(Bht(s)){var t=typeof s.valueOf=="function"?s.valueOf():s;s=Bht(t)?t+"":t}if(typeof s!="string")return s===0?s:+s;s=san(s);var n=aan.test(s);return n||ian.test(s)?oan(s.slice(2),n?2:8):ran.test(s)?$ht:+s}var rRt=lan,can=H6,BIe=Krn,Uht=rRt,dan="Expected a function",uan=Math.max,han=Math.min;function man(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(dan);t=Uht(t)||0,can(n)&&(u=!!n.leading,h="maxWait"in n,i=h?uan(Uht(n.maxWait)||0,t):i,m="trailing"in n?!!n.trailing:m);function p(T){var P=r,M=a;return r=a=void 0,d=T,l=s.apply(M,P),l}function x(T){return d=T,o=setTimeout(b,t),u?p(T):l}function g(T){var P=T-c,M=T-d,I=t-P;return h?han(I,i-M):I}function y(T){var P=T-c,M=T-d;return c===void 0||P>=t||P<0||h&&M>=i}function b(){var T=BIe();if(y(T))return v(T);o=setTimeout(b,g(T))}function v(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 C(){return o===void 0?l:v(BIe())}function A(){var T=BIe(),P=y(T);if(r=arguments,a=this,c=T,P){if(o===void 0)return x(c);if(h)return clearTimeout(o),o=setTimeout(b,t),p(c)}return o===void 0&&(o=setTimeout(b,t)),l}return A.cancel=N,A.flush=C,A}var pan=man,fan=pan,xan=H6,gan="Expected a function";function yan(s,t,n){var r=!0,a=!0;if(typeof s!="function")throw new TypeError(gan);return xan(n)&&(r="leading"in n?!!n.leading:r,a="trailing"in n?!!n.trailing:a),fan(s,t,{leading:r,maxWait:t,trailing:a})}var van=yan;const aRt=Uc(van);function bX(s){"@babel/helpers - typeof";return bX=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},bX(s)}function qht(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 jre(s){for(var t=1;ts.length)&&(t=s.length);for(var n=0,r=new Array(t);n0&&(W=aRt(W,g,{trailing:!0,leading:!1}));var V=new ResizeObserver(W),K=A.current.getBoundingClientRect(),Q=K.width,J=K.height;return B(Q,J),V.observe(A.current),function(){V.disconnect()}},[B,g]);var q=j.useMemo(function(){var W=I.containerWidth,V=I.containerHeight;if(W<0||V<0)return null;BN(z8(l)||z8(c),`The width(%s) and height(%s) are both fixed numbers, maybe you don't need to use a ResponsiveContainer.`,l,c),BN(!n||n>0,"The aspect(%s) must be greater than zero.",n);var K=z8(l)?W:l,Q=z8(c)?V:c;n&&n>0&&(K?Q=K/n:Q&&(K=Q*n),m&&Q>m&&(Q=m)),BN(K>0||Q>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,Q,l,c,u,h,n);var J=!Array.isArray(p)&&Z3(p.type).endsWith("Chart");return It.Children.map(p,function(ce){return It.isValidElement(ce)?j.cloneElement(ce,jre({width:K,height:Q},J?{style:jre({height:"100%",width:"100%",maxHeight:Q,maxWidth:K},ce.props.style)}:{})):ce})},[n,p,c,m,h,u,I,l]);return It.createElement("div",{id:y?"".concat(y):void 0,className:$l("recharts-responsive-container",b),style:jre(jre({},C),{},{width:l,height:c,minWidth:u,minHeight:h,maxHeight:m}),ref:A},q)}),eV=function(t){return null};eV.displayName="Cell";function _X(s){"@babel/helpers - typeof";return _X=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},_X(s)}function Hht(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 q9e(s){for(var t=1;t1&&arguments[1]!==void 0?arguments[1]:{};if(t==null||$N.isSsr)return{width:0,height:0};var r=Pan(n),a=JSON.stringify({text:t,copyStyle:r});if(L7.widthCache[a])return L7.widthCache[a];try{var i=document.getElementById(Ght);i||(i=document.createElement("span"),i.setAttribute("id",Ght),i.setAttribute("aria-hidden","true"),document.body.appendChild(i));var l=q9e(q9e({},Lan),r);Object.assign(i.style,l),i.textContent="".concat(t);var o=i.getBoundingClientRect(),c={width:o.width,height:o.height};return L7.widthCache[a]=c,++L7.cacheCount>Man&&(L7.cacheCount=0,L7.widthCache={}),c}catch{return{width:0,height:0}}},Ian=function(t){return{top:t.top+window.scrollY-document.documentElement.clientTop,left:t.left+window.scrollX-document.documentElement.clientLeft}};function wX(s){"@babel/helpers - typeof";return wX=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},wX(s)}function _5e(s,t){return Fan(s)||Oan(s,t)||Ran(s,t)||Dan()}function Dan(){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 Ran(s,t){if(s){if(typeof s=="string")return Wht(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 Wht(s,t)}}function Wht(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 Qan(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 Jht(s,t){return sin(s)||tin(s,t)||ein(s,t)||Jan()}function Jan(){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 ein(s,t){if(s){if(typeof s=="string")return emt(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 emt(s,t)}}function emt(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(Q,J){var ce=J.word,ue=J.width,ne=Q[Q.length-1];if(ne&&(a==null||i||ne.width+ue+rJ.width?Q:J})};if(!u)return p;for(var g="…",y=function(K){var Q=h.slice(0,K),J=cRt({breakAll:d,style:c,children:Q+g}).wordsWithComputedWidth,ce=m(J),ue=ce.length>l||x(ce).width>Number(a);return[ue,ce]},b=0,v=h.length-1,N=0,C;b<=v&&N<=h.length-1;){var A=Math.floor((b+v)/2),T=A-1,P=y(T),M=Jht(P,2),I=M[0],D=M[1],B=y(A),q=Jht(B,1),W=q[0];if(!I&&!W&&(b=A+1),I&&W&&(v=A-1),!I&&W){C=D;break}N++}return C||p},tmt=function(t){var n=Pl(t)?[]:t.toString().split(lRt);return[{words:n}]},rin=function(t){var n=t.width,r=t.scaleToFit,a=t.children,i=t.style,l=t.breakAll,o=t.maxLines;if((n||r)&&!$N.isSsr){var c,d,u=cRt({breakAll:l,children:a,style:i});if(u){var h=u.wordsWithComputedWidth,m=u.spaceWidth;c=h,d=m}else return tmt(a);return nin({breakAll:l,children:a,maxLines:o,style:i},c,d,n,r)}return tmt(a)},smt="#808080",jO=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,x=t.verticalAnchor,g=x===void 0?"end":x,y=t.fill,b=y===void 0?smt:y,v=Qht(t,Zan),N=j.useMemo(function(){return rin({breakAll:v.breakAll,children:v.children,maxLines:v.maxLines,scaleToFit:h,style:v.style,width:v.width})},[v.breakAll,v.children,v.maxLines,h,v.style,v.width]),C=v.dx,A=v.dy,T=v.angle,P=v.className,M=v.breakAll,I=Qht(v,Xan);if(!yg(r)||!yg(i))return null;var D=r+(za(C)?C:0),B=i+(za(A)?A:0),q;switch(g){case"start":q=$Ie("calc(".concat(d,")"));break;case"middle":q=$Ie("calc(".concat((N.length-1)/2," * -").concat(o," + (").concat(d," / 2))"));break;default:q=$Ie("calc(".concat(N.length-1," * -").concat(o,")"));break}var W=[];if(h){var V=N[0].width,K=v.width;W.push("scale(".concat((za(K)?K/V:1)/V,")"))}return T&&W.push("rotate(".concat(T,", ").concat(D,", ").concat(B,")")),W.length&&(I.transform=W.join(" ")),It.createElement("text",V9e({},So(I,!0),{x:D,y:B,className:$l("recharts-text",P),textAnchor:p,fill:b.includes("url")?smt:b}),N.map(function(Q,J){var ce=Q.words.join(M?"":" ");return It.createElement("tspan",{x:D,dy:J===0?q:o,key:"".concat(ce,"-").concat(J)},ce)}))};function qT(s,t){return s==null||t==null?NaN:st?1:s>=t?0:NaN}function ain(s,t){return s==null||t==null?NaN:ts?1:t>=s?0:NaN}function NKe(s){let t,n,r;s.length!==2?(t=qT,n=(o,c)=>qT(s(o),c),r=(o,c)=>s(o)-c):(t=s===qT||s===ain?s:iin,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 iin(){return 0}function dRt(s){return s===null?NaN:+s}function*oin(s,t){for(let n of s)n!=null&&(n=+n)>=n&&(yield n)}const lin=NKe(qT),Uee=lin.right;NKe(dRt).center;class nmt extends Map{constructor(t,n=uin){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(rmt(this,t))}has(t){return super.has(rmt(this,t))}set(t,n){return super.set(cin(this,t),n)}delete(t){return super.delete(din(this,t))}}function rmt({_intern:s,_key:t},n){const r=t(n);return s.has(r)?s.get(r):n}function cin({_intern:s,_key:t},n){const r=t(n);return s.has(r)?s.get(r):(s.set(r,n),n)}function din({_intern:s,_key:t},n){const r=t(n);return s.has(r)&&(n=s.get(r),s.delete(r)),n}function uin(s){return s!==null&&typeof s=="object"?s.valueOf():s}function hin(s=qT){if(s===qT)return uRt;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 uRt(s,t){return(s==null||!(s>=s))-(t==null||!(t>=t))||(st?1:0)}const min=Math.sqrt(50),pin=Math.sqrt(10),fin=Math.sqrt(2);function w5e(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>=min?10:i>=pin?5:i>=fin?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 imt(s,t){let n;for(const r of s)r!=null&&(n>r||n===void 0&&r>=r)&&(n=r);return n}function hRt(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?uRt:hin(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)),x=Math.min(r,Math.floor(t+(c-d)*h/c+m));hRt(s,t,p,x,a)}const i=s[t];let l=n,o=r;for(gG(s,n,t),a(s[r],i)>0&&gG(s,n,r);l0;)--o}a(s[n],i)===0?gG(s,n,o):(++o,gG(s,o,r)),o<=t&&(n=o+1),t<=o&&(r=o-1)}return s}function gG(s,t,n){const r=s[t];s[t]=s[n],s[n]=r}function xin(s,t,n){if(s=Float64Array.from(oin(s)),!(!(r=s.length)||isNaN(t=+t))){if(t<=0||r<2)return imt(s);if(t>=1)return amt(s);var r,a=(r-1)*t,i=Math.floor(a),l=amt(hRt(s,i).subarray(0,i+1)),o=imt(s.subarray(i+1));return l+(o-l)*(a-i)}}function gin(s,t,n=dRt){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 yin(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?kre(t>>24&255,t>>16&255,t>>8&255,(t&255)/255):n===4?kre(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=bin.exec(s))?new jb(t[1],t[2],t[3],1):(t=_in.exec(s))?new jb(t[1]*255/100,t[2]*255/100,t[3]*255/100,1):(t=win.exec(s))?kre(t[1],t[2],t[3],t[4]):(t=jin.exec(s))?kre(t[1]*255/100,t[2]*255/100,t[3]*255/100,t[4]):(t=Nin.exec(s))?mmt(t[1],t[2]/100,t[3]/100,1):(t=kin.exec(s))?mmt(t[1],t[2]/100,t[3]/100,t[4]):omt.hasOwnProperty(s)?dmt(omt[s]):s==="transparent"?new jb(NaN,NaN,NaN,0):null}function dmt(s){return new jb(s>>16&255,s>>8&255,s&255,1)}function kre(s,t,n,r){return r<=0&&(s=t=n=NaN),new jb(s,t,n,r)}function Ain(s){return s instanceof qee||(s=SX(s)),s?(s=s.rgb(),new jb(s.r,s.g,s.b,s.opacity)):new jb}function Y9e(s,t,n,r){return arguments.length===1?Ain(s):new jb(s,t,n,r??1)}function jb(s,t,n,r){this.r=+s,this.g=+t,this.b=+n,this.opacity=+r}SKe(jb,Y9e,pRt(qee,{brighter(s){return s=s==null?j5e:Math.pow(j5e,s),new jb(this.r*s,this.g*s,this.b*s,this.opacity)},darker(s){return s=s==null?NX:Math.pow(NX,s),new jb(this.r*s,this.g*s,this.b*s,this.opacity)},rgb(){return this},clamp(){return new jb(zR(this.r),zR(this.g),zR(this.b),N5e(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:umt,formatHex:umt,formatHex8:Ein,formatRgb:hmt,toString:hmt}));function umt(){return`#${B8(this.r)}${B8(this.g)}${B8(this.b)}`}function Ein(){return`#${B8(this.r)}${B8(this.g)}${B8(this.b)}${B8((isNaN(this.opacity)?1:this.opacity)*255)}`}function hmt(){const s=N5e(this.opacity);return`${s===1?"rgb(":"rgba("}${zR(this.r)}, ${zR(this.g)}, ${zR(this.b)}${s===1?")":`, ${s})`}`}function N5e(s){return isNaN(s)?1:Math.max(0,Math.min(1,s))}function zR(s){return Math.max(0,Math.min(255,Math.round(s)||0))}function B8(s){return s=zR(s),(s<16?"0":"")+s.toString(16)}function mmt(s,t,n,r){return r<=0?s=t=n=NaN:n<=0||n>=1?s=t=NaN:t<=0&&(s=NaN),new SN(s,t,n,r)}function fRt(s){if(s instanceof SN)return new SN(s.h,s.s,s.l,s.opacity);if(s instanceof qee||(s=SX(s)),!s)return new SN;if(s instanceof SN)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 SN(l,o,c,s.opacity)}function Tin(s,t,n,r){return arguments.length===1?fRt(s):new SN(s,t,n,r??1)}function SN(s,t,n,r){this.h=+s,this.s=+t,this.l=+n,this.opacity=+r}SKe(SN,Tin,pRt(qee,{brighter(s){return s=s==null?j5e:Math.pow(j5e,s),new SN(this.h,this.s,this.l*s,this.opacity)},darker(s){return s=s==null?NX:Math.pow(NX,s),new SN(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 jb(UIe(s>=240?s-240:s+120,a,r),UIe(s,a,r),UIe(s<120?s+240:s-120,a,r),this.opacity)},clamp(){return new SN(pmt(this.h),Sre(this.s),Sre(this.l),N5e(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=N5e(this.opacity);return`${s===1?"hsl(":"hsla("}${pmt(this.h)}, ${Sre(this.s)*100}%, ${Sre(this.l)*100}%${s===1?")":`, ${s})`}`}}));function pmt(s){return s=(s||0)%360,s<0?s+360:s}function Sre(s){return Math.max(0,Math.min(1,s||0))}function UIe(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 CKe=s=>()=>s;function Min(s,t){return function(n){return s+n*t}}function Lin(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 Pin(s){return(s=+s)==1?xRt:function(t,n){return n-t?Lin(t,n,s):CKe(isNaN(t)?n:t)}}function xRt(s,t){var n=t-s;return n?Min(s,n):CKe(isNaN(s)?t:s)}const fmt=function s(t){var n=Pin(t);function r(a,i){var l=n((a=Y9e(a)).r,(i=Y9e(i)).r),o=n(a.g,i.g),c=n(a.b,i.b),d=xRt(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 Iin(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:k5e(r,a)})),n=qIe.lastIndex;return nt&&(n=s,s=t,t=n),function(r){return Math.max(s,Math.min(t,r))}}function Hin(s,t,n){var r=s[0],a=s[1],i=t[0],l=t[1];return a2?Gin:Hin,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),k5e)))(m)))},h.domain=function(m){return arguments.length?(s=Array.from(m,S5e),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=AKe,u()},h.clamp=function(m){return arguments.length?(l=m?!0:u1,u()):l!==u1},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 EKe(){return mEe()(u1,u1)}function Win(s){return Math.abs(s=Math.round(s))>=1e21?s.toLocaleString("en").replace(/,/g,""):s.toString(10)}function C5e(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 bU(s){return s=C5e(Math.abs(s)),s?s[1]:NaN}function Kin(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 Yin(s){return function(t){return t.replace(/[0-9]/g,function(n){return s[+n]})}}var Zin=/^(?:(.)?([<>=^]))?([+\-( ])?([$#])?(0)?(\d+)?(,)?(\.\d+)?(~)?([a-z%])?$/i;function CX(s){if(!(t=Zin.exec(s)))throw new Error("invalid format: "+s);var t;return new TKe({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]})}CX.prototype=TKe.prototype;function TKe(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+""}TKe.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 Xin(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 gRt;function Qin(s,t){var n=C5e(s,t);if(!n)return s+"";var r=n[0],a=n[1],i=a-(gRt=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")+C5e(s,Math.max(0,t+i-1))[0]}function gmt(s,t){var n=C5e(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 ymt={"%":(s,t)=>(s*100).toFixed(t),b:s=>Math.round(s).toString(2),c:s=>s+"",d:Win,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)=>gmt(s*100,t),r:gmt,s:Qin,X:s=>Math.round(s).toString(16).toUpperCase(),x:s=>Math.round(s).toString(16)};function vmt(s){return s}var bmt=Array.prototype.map,_mt=["y","z","a","f","p","n","µ","m","","k","M","G","T","P","E","Z","Y"];function Jin(s){var t=s.grouping===void 0||s.thousands===void 0?vmt:Kin(bmt.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?vmt:Yin(bmt.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=CX(h);var m=h.fill,p=h.align,x=h.sign,g=h.symbol,y=h.zero,b=h.width,v=h.comma,N=h.precision,C=h.trim,A=h.type;A==="n"?(v=!0,A="g"):ymt[A]||(N===void 0&&(N=12),C=!0,A="g"),(y||m==="0"&&p==="=")&&(y=!0,m="0",p="=");var T=g==="$"?n:g==="#"&&/[boxX]/.test(A)?"0"+A.toLowerCase():"",P=g==="$"?r:/[%p]/.test(A)?l:"",M=ymt[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 D(B){var q=T,W=P,V,K,Q;if(A==="c")W=M(B)+W,B="";else{B=+B;var J=B<0||1/B<0;if(B=isNaN(B)?c:M(Math.abs(B),N),C&&(B=Xin(B)),J&&+B==0&&x!=="+"&&(J=!1),q=(J?x==="("?x:o:x==="-"||x==="("?"":x)+q,W=(A==="s"?_mt[8+gRt/3]:"")+W+(J&&x==="("?")":""),I){for(V=-1,K=B.length;++VQ||Q>57){W=(Q===46?a+B.slice(V+1):B.slice(V))+W,B=B.slice(0,V);break}}}v&&!y&&(B=t(B,1/0));var ce=q.length+B.length+W.length,ue=ce>1)+q+B+W+ue.slice(ce);break;default:B=ue+q+B+W;break}return i(B)}return D.toString=function(){return h+""},D}function u(h,m){var p=d((h=CX(h),h.type="f",h)),x=Math.max(-8,Math.min(8,Math.floor(bU(m)/3)))*3,g=Math.pow(10,-x),y=_mt[8+x/3];return function(b){return p(g*b)+y}}return{format:d,formatPrefix:u}}var Cre,MKe,yRt;eon({thousands:",",grouping:[3],currency:["$",""]});function eon(s){return Cre=Jin(s),MKe=Cre.format,yRt=Cre.formatPrefix,Cre}function ton(s){return Math.max(0,-bU(Math.abs(s)))}function son(s,t){return Math.max(0,Math.max(-8,Math.min(8,Math.floor(bU(t)/3)))*3-bU(Math.abs(s)))}function non(s,t){return s=Math.abs(s),t=Math.abs(t)-s,Math.max(0,bU(t)-bU(s))+1}function vRt(s,t,n,r){var a=W9e(s,t,n),i;switch(r=CX(r??",f"),r.type){case"s":{var l=Math.max(Math.abs(s),Math.abs(t));return r.precision==null&&!isNaN(i=son(a,l))&&(r.precision=i),yRt(r,l)}case"":case"e":case"g":case"p":case"r":{r.precision==null&&!isNaN(i=non(a,Math.max(Math.abs(s),Math.abs(t))))&&(r.precision=i-(r.type==="e"));break}case"f":case"%":{r.precision==null&&!isNaN(i=ton(a))&&(r.precision=i-(r.type==="%")*2);break}}return MKe(r)}function G6(s){var t=s.domain;return s.ticks=function(n){var r=t();return H9e(r[0],r[r.length-1],n??10)},s.tickFormat=function(n,r){var a=t();return vRt(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=G9e(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 A5e(){var s=EKe();return s.copy=function(){return Vee(s,A5e())},f2.apply(s,arguments),G6(s)}function bRt(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,S5e),n):s.slice()},n.unknown=function(r){return arguments.length?(t=r,n):t},n.copy=function(){return bRt(s).unknown(t)},s=arguments.length?Array.from(s,S5e):[0,1],G6(n)}function _Rt(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 lon(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 Nmt(s){return(t,n)=>-s(-t,n)}function LKe(s){const t=s(wmt,jmt),n=t.domain;let r=10,a,i;function l(){return a=lon(r),i=oon(r),n()[0]<0?(a=Nmt(a),i=Nmt(i),s(ron,aon)):s(wmt,jmt),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(x=1;xu)break;b.push(g)}}else for(;m<=p;++m)for(x=r-1;x>=1;--x)if(g=m>0?x/i(-m):x*i(m),!(gu)break;b.push(g)}b.length*2{if(o==null&&(o=10),c==null&&(c=r===10?"s":","),typeof c!="function"&&(!(r%1)&&(c=CX(c)).precision==null&&(c.trim=!0),c=MKe(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(_Rt(n(),{floor:o=>i(Math.floor(a(o))),ceil:o=>i(Math.ceil(a(o)))})),t}function wRt(){const s=LKe(mEe()).domain([1,10]);return s.copy=()=>Vee(s,wRt()).base(s.base()),f2.apply(s,arguments),s}function kmt(s){return function(t){return Math.sign(t)*Math.log1p(Math.abs(t/s))}}function Smt(s){return function(t){return Math.sign(t)*Math.expm1(Math.abs(t))*s}}function PKe(s){var t=1,n=s(kmt(t),Smt(t));return n.constant=function(r){return arguments.length?s(kmt(t=+r),Smt(t)):t},G6(n)}function jRt(){var s=PKe(mEe());return s.copy=function(){return Vee(s,jRt()).constant(s.constant())},f2.apply(s,arguments)}function Cmt(s){return function(t){return t<0?-Math.pow(-t,s):Math.pow(t,s)}}function con(s){return s<0?-Math.sqrt(-s):Math.sqrt(s)}function don(s){return s<0?-s*s:s*s}function IKe(s){var t=s(u1,u1),n=1;function r(){return n===1?s(u1,u1):n===.5?s(con,don):s(Cmt(n),Cmt(1/n))}return t.exponent=function(a){return arguments.length?(n=+a,r()):n},G6(t)}function DKe(){var s=IKe(mEe());return s.copy=function(){return Vee(s,DKe()).exponent(s.exponent())},f2.apply(s,arguments),s}function uon(){return DKe.apply(null,arguments).exponent(.5)}function Amt(s){return Math.sign(s)*s*s}function hon(s){return Math.sign(s)*Math.sqrt(Math.abs(s))}function NRt(){var s=EKe(),t=[0,1],n=!1,r;function a(i){var l=hon(s(i));return isNaN(l)?r:n?Math.round(l):l}return a.invert=function(i){return s.invert(Amt(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,S5e)).map(Amt)),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 NRt(s.domain(),t).round(n).clamp(s.clamp()).unknown(r)},f2.apply(a,arguments),G6(a)}function kRt(){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 SRt().domain([s,t]).range(a).unknown(i)},f2.apply(G6(l),arguments)}function CRt(){var s=[.5],t=[0,1],n,r=1;function a(i){return i!=null&&i<=i?t[Uee(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 CRt().domain(s).range(t).unknown(n)},f2.apply(a,arguments)}const VIe=new Date,HIe=new Date;function Ig(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(dIg(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)=>(VIe.setTime(+i),HIe.setTime(+l),s(VIe),s(HIe),Math.floor(n(VIe,HIe))),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 E5e=Ig(()=>{},(s,t)=>{s.setTime(+s+t)},(s,t)=>t-s);E5e.every=s=>(s=Math.floor(s),!isFinite(s)||!(s>0)?null:s>1?Ig(t=>{t.setTime(Math.floor(t/s)*s)},(t,n)=>{t.setTime(+t+n*s)},(t,n)=>(n-t)/s):E5e);E5e.range;const R3=1e3,Rj=R3*60,O3=Rj*60,uC=O3*24,RKe=uC*7,Emt=uC*30,GIe=uC*365,$8=Ig(s=>{s.setTime(s-s.getMilliseconds())},(s,t)=>{s.setTime(+s+t*R3)},(s,t)=>(t-s)/R3,s=>s.getUTCSeconds());$8.range;const OKe=Ig(s=>{s.setTime(s-s.getMilliseconds()-s.getSeconds()*R3)},(s,t)=>{s.setTime(+s+t*Rj)},(s,t)=>(t-s)/Rj,s=>s.getMinutes());OKe.range;const FKe=Ig(s=>{s.setUTCSeconds(0,0)},(s,t)=>{s.setTime(+s+t*Rj)},(s,t)=>(t-s)/Rj,s=>s.getUTCMinutes());FKe.range;const zKe=Ig(s=>{s.setTime(s-s.getMilliseconds()-s.getSeconds()*R3-s.getMinutes()*Rj)},(s,t)=>{s.setTime(+s+t*O3)},(s,t)=>(t-s)/O3,s=>s.getHours());zKe.range;const BKe=Ig(s=>{s.setUTCMinutes(0,0,0)},(s,t)=>{s.setTime(+s+t*O3)},(s,t)=>(t-s)/O3,s=>s.getUTCHours());BKe.range;const Hee=Ig(s=>s.setHours(0,0,0,0),(s,t)=>s.setDate(s.getDate()+t),(s,t)=>(t-s-(t.getTimezoneOffset()-s.getTimezoneOffset())*Rj)/uC,s=>s.getDate()-1);Hee.range;const pEe=Ig(s=>{s.setUTCHours(0,0,0,0)},(s,t)=>{s.setUTCDate(s.getUTCDate()+t)},(s,t)=>(t-s)/uC,s=>s.getUTCDate()-1);pEe.range;const ARt=Ig(s=>{s.setUTCHours(0,0,0,0)},(s,t)=>{s.setUTCDate(s.getUTCDate()+t)},(s,t)=>(t-s)/uC,s=>Math.floor(s/uC));ARt.range;function lF(s){return Ig(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())*Rj)/RKe)}const fEe=lF(0),T5e=lF(1),mon=lF(2),pon=lF(3),_U=lF(4),fon=lF(5),xon=lF(6);fEe.range;T5e.range;mon.range;pon.range;_U.range;fon.range;xon.range;function cF(s){return Ig(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)/RKe)}const xEe=cF(0),M5e=cF(1),gon=cF(2),yon=cF(3),wU=cF(4),von=cF(5),bon=cF(6);xEe.range;M5e.range;gon.range;yon.range;wU.range;von.range;bon.range;const $Ke=Ig(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());$Ke.range;const UKe=Ig(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());UKe.range;const hC=Ig(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());hC.every=s=>!isFinite(s=Math.floor(s))||!(s>0)?null:Ig(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)});hC.range;const mC=Ig(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());mC.every=s=>!isFinite(s=Math.floor(s))||!(s>0)?null:Ig(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)});mC.range;function ERt(s,t,n,r,a,i){const l=[[$8,1,R3],[$8,5,5*R3],[$8,15,15*R3],[$8,30,30*R3],[i,1,Rj],[i,5,5*Rj],[i,15,15*Rj],[i,30,30*Rj],[a,1,O3],[a,3,3*O3],[a,6,6*O3],[a,12,12*O3],[r,1,uC],[r,2,2*uC],[n,1,RKe],[t,1,Emt],[t,3,3*Emt],[s,1,GIe]];function o(d,u,h){const m=uy).right(l,m);if(p===l.length)return s.every(W9e(d/GIe,u/GIe,h));if(p===0)return E5e.every(Math.max(W9e(d,u,h),1));const[x,g]=l[m/l[p-1][2]53)return null;"w"in ke||(ke.w=1),"Z"in ke?(Se=KIe(yG(ke.y,0,1)),Re=Se.getUTCDay(),Se=Re>4||Re===0?M5e.ceil(Se):M5e(Se),Se=pEe.offset(Se,(ke.V-1)*7),ke.y=Se.getUTCFullYear(),ke.m=Se.getUTCMonth(),ke.d=Se.getUTCDate()+(ke.w+6)%7):(Se=WIe(yG(ke.y,0,1)),Re=Se.getDay(),Se=Re>4||Re===0?T5e.ceil(Se):T5e(Se),Se=Hee.offset(Se,(ke.V-1)*7),ke.y=Se.getFullYear(),ke.m=Se.getMonth(),ke.d=Se.getDate()+(ke.w+6)%7)}else("W"in ke||"U"in ke)&&("w"in ke||(ke.w="u"in ke?ke.u%7:"W"in ke?1:0),Re="Z"in ke?KIe(yG(ke.y,0,1)).getUTCDay():WIe(yG(ke.y,0,1)).getDay(),ke.m=0,ke.d="W"in ke?(ke.w+6)%7+ke.W*7-(Re+5)%7:ke.w+ke.U*7-(Re+6)%7);return"Z"in ke?(ke.H+=ke.Z/100|0,ke.M+=ke.Z%100,KIe(ke)):WIe(ke)}}function M(Me,De,ze,ke){for(var Xe=0,Se=De.length,Re=ze.length,Ae,Be;Xe=Re)return-1;if(Ae=De.charCodeAt(Xe++),Ae===37){if(Ae=De.charAt(Xe++),Be=A[Ae in Tmt?De.charAt(Xe++):Ae],!Be||(ke=Be(Me,ze,ke))<0)return-1}else if(Ae!=ze.charCodeAt(ke++))return-1}return ke}function I(Me,De,ze){var ke=d.exec(De.slice(ze));return ke?(Me.p=u.get(ke[0].toLowerCase()),ze+ke[0].length):-1}function D(Me,De,ze){var ke=p.exec(De.slice(ze));return ke?(Me.w=x.get(ke[0].toLowerCase()),ze+ke[0].length):-1}function B(Me,De,ze){var ke=h.exec(De.slice(ze));return ke?(Me.w=m.get(ke[0].toLowerCase()),ze+ke[0].length):-1}function q(Me,De,ze){var ke=b.exec(De.slice(ze));return ke?(Me.m=v.get(ke[0].toLowerCase()),ze+ke[0].length):-1}function W(Me,De,ze){var ke=g.exec(De.slice(ze));return ke?(Me.m=y.get(ke[0].toLowerCase()),ze+ke[0].length):-1}function V(Me,De,ze){return M(Me,t,De,ze)}function K(Me,De,ze){return M(Me,n,De,ze)}function Q(Me,De,ze){return M(Me,r,De,ze)}function J(Me){return l[Me.getDay()]}function ce(Me){return i[Me.getDay()]}function ue(Me){return c[Me.getMonth()]}function ne(Me){return o[Me.getMonth()]}function ee(Me){return a[+(Me.getHours()>=12)]}function le(Me){return 1+~~(Me.getMonth()/3)}function he(Me){return l[Me.getUTCDay()]}function ve(Me){return i[Me.getUTCDay()]}function ge(Me){return c[Me.getUTCMonth()]}function fe(Me){return o[Me.getUTCMonth()]}function je(Me){return a[+(Me.getUTCHours()>=12)]}function Ee(Me){return 1+~~(Me.getUTCMonth()/3)}return{format:function(Me){var De=T(Me+="",N);return De.toString=function(){return Me},De},parse:function(Me){var De=P(Me+="",!1);return De.toString=function(){return Me},De},utcFormat:function(Me){var De=T(Me+="",C);return De.toString=function(){return Me},De},utcParse:function(Me){var De=P(Me+="",!0);return De.toString=function(){return Me},De}}}var Tmt={"-":"",_:" ",0:"0"},A0=/^\s*\d+/,Son=/^%/,Con=/[\\^$*+?|[\]().{}]/g;function Jd(s,t,n){var r=s<0?"-":"",a=(r?-s:s)+"",i=a.length;return r+(i[t.toLowerCase(),n]))}function Eon(s,t,n){var r=A0.exec(t.slice(n,n+1));return r?(s.w=+r[0],n+r[0].length):-1}function Ton(s,t,n){var r=A0.exec(t.slice(n,n+1));return r?(s.u=+r[0],n+r[0].length):-1}function Mon(s,t,n){var r=A0.exec(t.slice(n,n+2));return r?(s.U=+r[0],n+r[0].length):-1}function Lon(s,t,n){var r=A0.exec(t.slice(n,n+2));return r?(s.V=+r[0],n+r[0].length):-1}function Pon(s,t,n){var r=A0.exec(t.slice(n,n+2));return r?(s.W=+r[0],n+r[0].length):-1}function Mmt(s,t,n){var r=A0.exec(t.slice(n,n+4));return r?(s.y=+r[0],n+r[0].length):-1}function Lmt(s,t,n){var r=A0.exec(t.slice(n,n+2));return r?(s.y=+r[0]+(+r[0]>68?1900:2e3),n+r[0].length):-1}function Ion(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 Don(s,t,n){var r=A0.exec(t.slice(n,n+1));return r?(s.q=r[0]*3-3,n+r[0].length):-1}function Ron(s,t,n){var r=A0.exec(t.slice(n,n+2));return r?(s.m=r[0]-1,n+r[0].length):-1}function Pmt(s,t,n){var r=A0.exec(t.slice(n,n+2));return r?(s.d=+r[0],n+r[0].length):-1}function Oon(s,t,n){var r=A0.exec(t.slice(n,n+3));return r?(s.m=0,s.d=+r[0],n+r[0].length):-1}function Imt(s,t,n){var r=A0.exec(t.slice(n,n+2));return r?(s.H=+r[0],n+r[0].length):-1}function Fon(s,t,n){var r=A0.exec(t.slice(n,n+2));return r?(s.M=+r[0],n+r[0].length):-1}function zon(s,t,n){var r=A0.exec(t.slice(n,n+2));return r?(s.S=+r[0],n+r[0].length):-1}function Bon(s,t,n){var r=A0.exec(t.slice(n,n+3));return r?(s.L=+r[0],n+r[0].length):-1}function $on(s,t,n){var r=A0.exec(t.slice(n,n+6));return r?(s.L=Math.floor(r[0]/1e3),n+r[0].length):-1}function Uon(s,t,n){var r=Son.exec(t.slice(n,n+1));return r?n+r[0].length:-1}function qon(s,t,n){var r=A0.exec(t.slice(n));return r?(s.Q=+r[0],n+r[0].length):-1}function Von(s,t,n){var r=A0.exec(t.slice(n));return r?(s.s=+r[0],n+r[0].length):-1}function Dmt(s,t){return Jd(s.getDate(),t,2)}function Hon(s,t){return Jd(s.getHours(),t,2)}function Gon(s,t){return Jd(s.getHours()%12||12,t,2)}function Won(s,t){return Jd(1+Hee.count(hC(s),s),t,3)}function TRt(s,t){return Jd(s.getMilliseconds(),t,3)}function Kon(s,t){return TRt(s,t)+"000"}function Yon(s,t){return Jd(s.getMonth()+1,t,2)}function Zon(s,t){return Jd(s.getMinutes(),t,2)}function Xon(s,t){return Jd(s.getSeconds(),t,2)}function Qon(s){var t=s.getDay();return t===0?7:t}function Jon(s,t){return Jd(fEe.count(hC(s)-1,s),t,2)}function MRt(s){var t=s.getDay();return t>=4||t===0?_U(s):_U.ceil(s)}function eln(s,t){return s=MRt(s),Jd(_U.count(hC(s),s)+(hC(s).getDay()===4),t,2)}function tln(s){return s.getDay()}function sln(s,t){return Jd(T5e.count(hC(s)-1,s),t,2)}function nln(s,t){return Jd(s.getFullYear()%100,t,2)}function rln(s,t){return s=MRt(s),Jd(s.getFullYear()%100,t,2)}function aln(s,t){return Jd(s.getFullYear()%1e4,t,4)}function iln(s,t){var n=s.getDay();return s=n>=4||n===0?_U(s):_U.ceil(s),Jd(s.getFullYear()%1e4,t,4)}function oln(s){var t=s.getTimezoneOffset();return(t>0?"-":(t*=-1,"+"))+Jd(t/60|0,"0",2)+Jd(t%60,"0",2)}function Rmt(s,t){return Jd(s.getUTCDate(),t,2)}function lln(s,t){return Jd(s.getUTCHours(),t,2)}function cln(s,t){return Jd(s.getUTCHours()%12||12,t,2)}function dln(s,t){return Jd(1+pEe.count(mC(s),s),t,3)}function LRt(s,t){return Jd(s.getUTCMilliseconds(),t,3)}function uln(s,t){return LRt(s,t)+"000"}function hln(s,t){return Jd(s.getUTCMonth()+1,t,2)}function mln(s,t){return Jd(s.getUTCMinutes(),t,2)}function pln(s,t){return Jd(s.getUTCSeconds(),t,2)}function fln(s){var t=s.getUTCDay();return t===0?7:t}function xln(s,t){return Jd(xEe.count(mC(s)-1,s),t,2)}function PRt(s){var t=s.getUTCDay();return t>=4||t===0?wU(s):wU.ceil(s)}function gln(s,t){return s=PRt(s),Jd(wU.count(mC(s),s)+(mC(s).getUTCDay()===4),t,2)}function yln(s){return s.getUTCDay()}function vln(s,t){return Jd(M5e.count(mC(s)-1,s),t,2)}function bln(s,t){return Jd(s.getUTCFullYear()%100,t,2)}function _ln(s,t){return s=PRt(s),Jd(s.getUTCFullYear()%100,t,2)}function wln(s,t){return Jd(s.getUTCFullYear()%1e4,t,4)}function jln(s,t){var n=s.getUTCDay();return s=n>=4||n===0?wU(s):wU.ceil(s),Jd(s.getUTCFullYear()%1e4,t,4)}function Nln(){return"+0000"}function Omt(){return"%"}function Fmt(s){return+s}function zmt(s){return Math.floor(+s/1e3)}var P7,IRt,DRt;kln({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 kln(s){return P7=kon(s),IRt=P7.format,P7.parse,DRt=P7.utcFormat,P7.utcParse,P7}function Sln(s){return new Date(s)}function Cln(s){return s instanceof Date?+s:+new Date(+s)}function qKe(s,t,n,r,a,i,l,o,c,d){var u=EKe(),h=u.invert,m=u.domain,p=d(".%L"),x=d(":%S"),g=d("%I:%M"),y=d("%I %p"),b=d("%a %d"),v=d("%b %d"),N=d("%B"),C=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)=>xin(s,i/r))},n.copy=function(){return zRt(t).domain(s)},TC.apply(n,arguments)}function yEe(){var s=0,t=.5,n=1,r=1,a,i,l,o,c,d=u1,u,h=!1,m;function p(g){return isNaN(g=+g)?m:(g=.5+((g=+u(g))-i)*(r*gt}var qRt=Iln,Dln=vEe,Rln=qRt,Oln=Jq;function Fln(s){return s&&s.length?Dln(s,Oln,Rln):void 0}var zln=Fln;const JE=Uc(zln);function Bln(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};to.decimalPlaces=to.dp=function(){var s=this,t=s.d.length-1,n=(t-s.e)*_m;if(t=s.d[t],t)for(;t%10==0;t/=10)n--;return n<0?0:n};to.dividedBy=to.div=function(s){return X3(this,new this.constructor(s))};to.dividedToIntegerBy=to.idiv=function(s){var t=this,n=t.constructor;return Mh(X3(t,new n(s),0,1),n.precision)};to.equals=to.eq=function(s){return!this.cmp(s)};to.exponent=function(){return Bx(this)};to.greaterThan=to.gt=function(s){return this.cmp(s)>0};to.greaterThanOrEqualTo=to.gte=function(s){return this.cmp(s)>=0};to.isInteger=to.isint=function(){return this.e>this.d.length-2};to.isNegative=to.isneg=function(){return this.s<0};to.isPositive=to.ispos=function(){return this.s>0};to.isZero=function(){return this.s===0};to.lessThan=to.lt=function(s){return this.cmp(s)<0};to.lessThanOrEqualTo=to.lte=function(s){return this.cmp(s)<1};to.logarithm=to.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(K_))throw Error(a2+"NaN");if(n.s<1)throw Error(a2+(n.s?"NaN":"-Infinity"));return n.eq(K_)?new r(0):(tp=!1,t=X3(AX(n,i),AX(s,i),i),tp=!0,Mh(t,a))};to.minus=to.sub=function(s){var t=this;return s=new t.constructor(s),t.s==s.s?KRt(t,s):GRt(t,(s.s=-s.s,s))};to.modulo=to.mod=function(s){var t,n=this,r=n.constructor,a=r.precision;if(s=new r(s),!s.s)throw Error(a2+"NaN");return n.s?(tp=!1,t=X3(n,s,0,1).times(s),tp=!0,n.minus(t)):Mh(new r(n),a)};to.naturalExponential=to.exp=function(){return WRt(this)};to.naturalLogarithm=to.ln=function(){return AX(this)};to.negated=to.neg=function(){var s=new this.constructor(this);return s.s=-s.s||0,s};to.plus=to.add=function(s){var t=this;return s=new t.constructor(s),t.s==s.s?GRt(t,s):KRt(t,(s.s=-s.s,s))};to.precision=to.sd=function(s){var t,n,r,a=this;if(s!==void 0&&s!==!!s&&s!==1&&s!==0)throw Error(BR+s);if(t=Bx(a)+1,r=a.d.length-1,n=r*_m+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};to.squareRoot=to.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(a2+"NaN")}for(s=Bx(o),tp=!1,a=Math.sqrt(+o),a==0||a==1/0?(t=qS(o.d),(t.length+s)%2==0&&(t+="0"),a=Math.sqrt(t),s=nV((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(X3(o,i,l+2)).times(.5),qS(i.d).slice(0,l)===(t=qS(r.d)).slice(0,l)){if(t=t.slice(l-3,l+1),a==l&&t=="4999"){if(Mh(i,n+1,0),i.times(i).eq(o)){r=i;break}}else if(t!="9999")break;l+=4}return tp=!0,Mh(r,n)};to.times=to.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%c0|0,t=o/c0|0;i[a]=(i[a]+t)%c0|0}for(;!i[--l];)i.pop();return t?++n:i.shift(),s.d=i,s.e=n,tp?Mh(s,h.precision):s};to.toDecimalPlaces=to.todp=function(s,t){var n=this,r=n.constructor;return n=new r(n),s===void 0?n:(k5(s,0,sV),t===void 0?t=r.rounding:k5(t,0,8),Mh(n,s+Bx(n)+1,t))};to.toExponential=function(s,t){var n,r=this,a=r.constructor;return s===void 0?n=kO(r,!0):(k5(s,0,sV),t===void 0?t=a.rounding:k5(t,0,8),r=Mh(new a(r),s+1,t),n=kO(r,!0,s+1)),n};to.toFixed=function(s,t){var n,r,a=this,i=a.constructor;return s===void 0?kO(a):(k5(s,0,sV),t===void 0?t=i.rounding:k5(t,0,8),r=Mh(new i(a),s+Bx(a)+1,t),n=kO(r.abs(),!1,s+Bx(r)+1),a.isneg()&&!a.isZero()?"-"+n:n)};to.toInteger=to.toint=function(){var s=this,t=s.constructor;return Mh(new t(s),Bx(s)+1,t.rounding)};to.toNumber=function(){return+this};to.toPower=to.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(K_);if(o=new c(o),!o.s){if(s.s<1)throw Error(a2+"Infinity");return o}if(o.eq(K_))return o;if(r=c.precision,s.eq(K_))return Mh(o,r);if(t=s.e,n=s.d.length-1,l=t>=n,i=o.s,l){if((n=u<0?-u:u)<=HRt){for(a=new c(K_),t=Math.ceil(r/_m+4),tp=!1;n%2&&(a=a.times(o),Umt(a.d,t)),n=nV(n/2),n!==0;)o=o.times(o),Umt(o.d,t);return tp=!0,s.s<0?new c(K_).div(a):Mh(a,r)}}else if(i<0)throw Error(a2+"NaN");return i=i<0&&s.d[Math.max(t,n)]&1?-1:1,o.s=1,tp=!1,a=s.times(AX(o,r+d)),tp=!0,a=WRt(a),a.s=i,a};to.toPrecision=function(s,t){var n,r,a=this,i=a.constructor;return s===void 0?(n=Bx(a),r=kO(a,n<=i.toExpNeg||n>=i.toExpPos)):(k5(s,1,sV),t===void 0?t=i.rounding:k5(t,0,8),a=Mh(new i(a),s,t),n=Bx(a),r=kO(a,s<=n||n<=i.toExpNeg,s)),r};to.toSignificantDigits=to.tosd=function(s,t){var n=this,r=n.constructor;return s===void 0?(s=r.precision,t=r.rounding):(k5(s,1,sV),t===void 0?t=r.rounding:k5(t,0,8)),Mh(new r(n),s,t)};to.toString=to.valueOf=to.val=to.toJSON=to[Symbol.for("nodejs.util.inspect.custom")]=function(){var s=this,t=Bx(s),n=s.constructor;return kO(s,t<=n.toExpNeg||t>=n.toExpPos)};function GRt(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)),tp?Mh(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/_m),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)/c0|0,c[i]%=c0;for(n&&(c.unshift(n),++a),o=c.length;c[--o]==0;)c.pop();return t.d=c,t.e=a,tp?Mh(t,h):t}function k5(s,t,n){if(s!==~~s||sn)throw Error(BR+s)}function qS(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,x,g,y,b,v,N,C,A,T,P,M,I=r.constructor,D=r.s==a.s?1:-1,B=r.d,q=a.d;if(!r.s)return new I(r);if(!a.s)throw Error(a2+"Division by zero");for(c=r.e-a.e,P=q.length,A=B.length,p=new I(D),x=p.d=[],d=0;q[d]==(B[d]||0);)++d;if(q[d]>(B[d]||0)&&--c,i==null?v=i=I.precision:l?v=i+(Bx(r)-Bx(a))+1:v=i,v<0)return new I(0);if(v=v/_m+2|0,d=0,P==1)for(u=0,q=q[0],v++;(d1&&(q=s(q,u),B=s(B,u),P=q.length,A=B.length),C=P,g=B.slice(0,P),y=g.length;y=c0/2&&++T;do u=0,o=t(q,g,P,y),o<0?(b=g[0],P!=y&&(b=b*c0+(g[1]||0)),u=b/T|0,u>1?(u>=c0&&(u=c0-1),h=s(q,u),m=h.length,y=g.length,o=t(h,g,m,y),o==1&&(u--,n(h,P16)throw Error(GKe+Bx(s));if(!s.s)return new u(K_);for(t==null?(tp=!1,o=h):o=t,l=new u(.03125);s.abs().gte(.1);)s=s.times(l),d+=5;for(r=Math.log(l8(2,d))/Math.LN10*2+5|0,o+=r,n=a=i=new u(K_),u.precision=o;;){if(a=Mh(a.times(s),o),n=n.times(++c),l=i.plus(X3(a,n,o)),qS(l.d).slice(0,o)===qS(i.d).slice(0,o)){for(;d--;)i=Mh(i.times(i),o);return u.precision=h,t==null?(tp=!0,Mh(i,h)):i}i=l}}function Bx(s){for(var t=s.e*_m,n=s.d[0];n>=10;n/=10)t++;return t}function YIe(s,t,n){if(t>s.LN10.sd())throw tp=!0,n&&(s.precision=n),Error(a2+"LN10 precision limit exceeded");return Mh(new s(s.LN10),t)}function VA(s){for(var t="";s--;)t+="0";return t}function AX(s,t){var n,r,a,i,l,o,c,d,u,h=1,m=10,p=s,x=p.d,g=p.constructor,y=g.precision;if(p.s<1)throw Error(a2+(p.s?"NaN":"-Infinity"));if(p.eq(K_))return new g(0);if(t==null?(tp=!1,d=y):d=t,p.eq(10))return t==null&&(tp=!0),YIe(g,d);if(d+=m,g.precision=d,n=qS(x),r=n.charAt(0),i=Bx(p),Math.abs(i)<15e14){for(;r<7&&r!=1||r==1&&n.charAt(1)>3;)p=p.times(s),n=qS(p.d),r=n.charAt(0),h++;i=Bx(p),r>1?(p=new g("0."+n),i++):p=new g(r+"."+n.slice(1))}else return c=YIe(g,d+2,y).times(i+""),p=AX(new g(r+"."+n.slice(1)),d-m).plus(c),g.precision=y,t==null?(tp=!0,Mh(p,y)):p;for(o=l=p=X3(p.minus(K_),p.plus(K_),d),u=Mh(p.times(p),d),a=3;;){if(l=Mh(l.times(u),d),c=o.plus(X3(l,new g(a),d)),qS(c.d).slice(0,d)===qS(o.d).slice(0,d))return o=o.times(2),i!==0&&(o=o.plus(YIe(g,d+2,y).times(i+""))),o=X3(o,new g(h),d),g.precision=y,t==null?(tp=!0,Mh(o,y)):o;o=c,a+=2}}function $mt(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=nV(n/_m),s.d=[],r=(n+1)%_m,n<0&&(r+=_m),rL5e||s.e<-L5e))throw Error(GKe+n)}else s.s=0,s.e=0,s.d=[0];return s}function Mh(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+=_m,a=t,d=h[u=0];else{if(u=Math.ceil((r+1)/_m),i=h.length,u>=i)return s;for(d=i=h[u],l=1;i>=10;i/=10)l++;r%=_m,a=r-_m+l}if(n!==void 0&&(i=l8(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/l8(10,l-a):0:h[u-1])%10&1||n==(s.s<0?8:7))),t<1||!h[0])return c?(i=Bx(s),h.length=1,t=t-i-1,h[0]=l8(10,(_m-t%_m)%_m),s.e=nV(-t/_m)||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=l8(10,_m-r),h[u]=a>0?(d/l8(10,l-a)%l8(10,a)|0)*i:0),c)for(;;)if(u==0){(h[0]+=i)==c0&&(h[0]=1,++s.e);break}else{if(h[u]+=i,h[u]!=c0)break;h[u--]=0,i=1}for(r=h.length;h[--r]===0;)h.pop();if(tp&&(s.e>L5e||s.e<-L5e))throw Error(GKe+Bx(s));return s}function KRt(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),tp?Mh(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/_m),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)+VA(r):l>1&&(i=i.charAt(0)+"."+i.slice(1)),i=i+(a<0?"e":"e+")+a):a<0?(i="0."+VA(-a-1)+i,n&&(r=n-l)>0&&(i+=VA(r))):a>=l?(i+=VA(a+1-l),n&&(r=n-a-1)>0&&(i=i+"."+VA(r))):((r=a+1)0&&(a+1===l&&(i+="."),i+=VA(r))),s.s<0?"-"+i:i}function Umt(s,t){if(s.length>t)return s.length=t,!0}function YRt(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(BR+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 $mt(l,i.toString())}else if(typeof i!="string")throw Error(BR+i);if(i.charCodeAt(0)===45?(i=i.slice(1),l.s=-1):l.s=1,ocn.test(i))$mt(l,i);else throw Error(BR+i)}if(a.prototype=to,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=YRt,a.config=a.set=lcn,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(BR+n+": "+r);if((r=s[n="LN10"])!==void 0)if(r==Math.LN10)this[n]=new this(r);else throw Error(BR+n+": "+r);return this}var WKe=YRt(icn);K_=new WKe(1);const ah=WKe;function ccn(s){return mcn(s)||hcn(s)||ucn(s)||dcn()}function dcn(){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 ucn(s,t){if(s){if(typeof s=="string")return Q9e(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 Q9e(s,t)}}function hcn(s){if(typeof Symbol<"u"&&Symbol.iterator in Object(s))return Array.from(s)}function mcn(s){if(Array.isArray(s))return Q9e(s)}function Q9e(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,qmt(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 Acn(s){if(Array.isArray(s))return s}function eOt(s){var t=EX(s,2),n=t[0],r=t[1],a=n,i=r;return n>r&&(a=r,i=n),[a,i]}function tOt(s,t,n){if(s.lte(0))return new ah(0);var r=wEe.getDigitCount(s.toNumber()),a=new ah(10).pow(r),i=s.div(a),l=r!==1?.05:.1,o=new ah(Math.ceil(i.div(l).toNumber())).add(n).mul(l),c=o.mul(a);return t?c:new ah(Math.ceil(c))}function Ecn(s,t,n){var r=1,a=new ah(s);if(!a.isint()&&n){var i=Math.abs(s);i<1?(r=new ah(10).pow(wEe.getDigitCount(s)-1),a=new ah(Math.floor(a.div(r).toNumber())).mul(r)):i>1&&(a=new ah(Math.floor(s)))}else s===0?a=new ah(Math.floor((t-1)/2)):n||(a=new ah(Math.floor(s)));var l=Math.floor((t-1)/2),o=gcn(xcn(function(c){return a.add(new ah(c-l).mul(r)).toNumber()}),J9e);return o(0,t)}function sOt(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 ah(0),tickMin:new ah(0),tickMax:new ah(0)};var i=tOt(new ah(t).sub(s).div(n-1),r,a),l;s<=0&&t>=0?l=new ah(0):(l=new ah(s).add(t).div(2),l=l.sub(new ah(l).mod(i)));var o=Math.ceil(l.sub(s).div(i).toNumber()),c=Math.ceil(new ah(t).sub(l).div(i).toNumber()),d=o+c+1;return d>n?sOt(s,t,n,r,a+1):(d0?c+(n-d):c,o=t>0?o:o+(n-d)),{step:i,tickMin:l.sub(new ah(o).mul(i)),tickMax:l.add(new ah(c).mul(i))})}function Tcn(s){var t=EX(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=eOt([n,r]),c=EX(o,2),d=c[0],u=c[1];if(d===-1/0||u===1/0){var h=u===1/0?[d].concat(tze(J9e(0,a-1).map(function(){return 1/0}))):[].concat(tze(J9e(0,a-1).map(function(){return-1/0})),[u]);return n>r?eze(h):h}if(d===u)return Ecn(d,a,i);var m=sOt(d,u,l,i),p=m.step,x=m.tickMin,g=m.tickMax,y=wEe.rangeStep(x,g.add(new ah(.1).mul(p)),p);return n>r?eze(y):y}function Mcn(s,t){var n=EX(s,2),r=n[0],a=n[1],i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0,l=eOt([r,a]),o=EX(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=tOt(new ah(d).sub(c).div(u-1),i,0),m=[].concat(tze(wEe.rangeStep(new ah(c),new ah(d).sub(new ah(.99).mul(h)),h)),[d]);return r>a?eze(m):m}var Lcn=QRt(Tcn),Pcn=QRt(Mcn),Icn="Invariant failed";function SO(s,t){throw new Error(Icn)}var Dcn=["offset","layout","width","dataKey","data","dataPointFormatter","xAxis","yAxis"];function jU(s){"@babel/helpers - typeof";return jU=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},jU(s)}function P5e(){return P5e=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 Ucn(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 qcn(s,t){if(!(s instanceof t))throw new TypeError("Cannot call a class as a function")}function Vcn(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(c1(h-u)!==c1(m-h)){var x=[];if(c1(m-h)===c1(c[1]-c[0])){p=m;var g=h+c[1]-c[0];x[0]=Math.min(g,(g+u)/2),x[1]=Math.max(g,(g+u)/2)}else{p=u;var y=m+c[1]-c[0];x[0]=Math.min(h,(y+h)/2),x[1]=Math.max(h,(y+h)/2)}var b=[Math.min(h,(p+h)/2),Math.max(h,(p+h)/2)];if(t>b[0]&&t<=b[1]||t>=x[0]&&t<=x[1]){l=a[d].index;break}}else{var v=Math.min(u,m),N=Math.max(u,m);if(t>(v+h)/2&&t<=(N+h)/2){l=a[d].index;break}}}else for(var C=0;C0&&C(r[C].coordinate+r[C-1].coordinate)/2&&t<=(r[C].coordinate+r[C+1].coordinate)/2||C===o-1&&t>(r[C].coordinate+r[C-1].coordinate)/2){l=r[C].index;break}return l},KKe=function(t){var n,r=t,a=r.type.displayName,i=(n=t.type)!==null&&n!==void 0&&n.defaultProps?ff(ff({},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},odn=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(b&&b.length){var v=b[0].type.defaultProps,N=v!==void 0?ff(ff({},v),b[0].props):b[0].props,C=N.barSize,A=N[y];l[A]||(l[A]=[]);var T=Pl(C)?n:C;l[A].push({item:b[0],stackList:b.slice(1),barSize:Pl(T)?void 0:d1(T,r,0)})}}return l},ldn=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=d1(n,a,0,!0),u,h=[];if(l[0].barSize===+l[0].barSize){var m=!1,p=a/c,x=l.reduce(function(C,A){return C+A.barSize||0},0);x+=(c-1)*d,x>=a&&(x-=(c-1)*d,d=0),x>=a&&p>0&&(m=!0,p*=.9,x=c*p);var g=(a-x)/2>>0,y={offset:g-d,size:0};u=l.reduce(function(C,A){var T={item:A.item,position:{offset:y.offset+y.size+d,size:m?p:A.barSize}},P=[].concat(Gmt(C),[T]);return y=P[P.length-1].position,A.stackList&&A.stackList.length&&A.stackList.forEach(function(M){P.push({item:M,position:y})}),P},h)}else{var b=d1(r,a,0,!0);a-2*b-(c-1)*d<=0&&(d=0);var v=(a-2*b-(c-1)*d)/c;v>1&&(v>>=0);var N=o===+o?Math.min(v,o):v;u=l.reduce(function(C,A,T){var P=[].concat(Gmt(C),[{item:A.item,position:{offset:b+(v+d)*T+(v-N)/2,size:N}}]);return A.stackList&&A.stackList.length&&A.stackList.forEach(function(M){P.push({item:M,position:P[P.length-1].position})}),P},h)}return u},cdn=function(t,n,r,a){var i=r.children,l=r.width,o=r.margin,c=l-(o.left||0)-(o.right||0),d=iOt({children:i,legendWidth:c});if(d){var u=a||{},h=u.width,m=u.height,p=d.align,x=d.verticalAlign,g=d.layout;if((g==="vertical"||g==="horizontal"&&x==="middle")&&p!=="center"&&za(t[p]))return ff(ff({},t),{},dB({},p,t[p]+(h||0)));if((g==="horizontal"||g==="vertical"&&p==="center")&&x!=="middle"&&za(t[x]))return ff(ff({},t),{},dB({},x,t[x]+(m||0)))}return t},ddn=function(t,n,r){return Pl(n)?!0:t==="horizontal"?n==="yAxis":t==="vertical"||r==="x"?n==="xAxis":r==="y"?n==="yAxis":!0},oOt=function(t,n,r,a,i){var l=n.props.children,o=lw(l,Gee).filter(function(d){return ddn(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=ex(u,r);if(Pl(h))return d;var m=Array.isArray(h)?[bEe(h),JE(h)]:[h,h],p=c.reduce(function(x,g){var y=ex(u,g,0),b=m[0]-Math.abs(Array.isArray(y)?y[0]:y),v=m[1]+Math.abs(Array.isArray(y)?y[1]:y);return[Math.min(b,x[0]),Math.max(v,x[1])]},[1/0,-1/0]);return[Math.min(p[0],d[0]),Math.max(p[1],d[1])]},[1/0,-1/0])}return null},udn=function(t,n,r,a,i){var l=n.map(function(o){return oOt(t,o,r,i,a)}).filter(function(o){return!Pl(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},lOt=function(t,n,r,a,i){var l=n.map(function(c){var d=c.props.dataKey;return r==="number"&&d&&oOt(t,c,d,a)||UY(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?c1(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!Zq(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}})},ZIe=new WeakMap,Are=function(t,n){if(typeof n!="function")return t;ZIe.has(t)||ZIe.set(t,new WeakMap);var r=ZIe.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},uOt=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:jX(),realScaleType:"band"}:l==="radial"&&o==="angleAxis"?{scale:A5e(),realScaleType:"linear"}:i==="category"&&n&&(n.indexOf("LineChart")>=0||n.indexOf("AreaChart")>=0||n.indexOf("ComposedChart")>=0&&!r)?{scale:$Y(),realScaleType:"point"}:i==="category"?{scale:jX(),realScaleType:"band"}:{scale:A5e(),realScaleType:"linear"};if(_O(a)){var c="scale".concat(iEe(a));return{scale:(Bmt[c]||$Y)(),realScaleType:Bmt[c]?c:"point"}}return dl(a)?{scale:a}:{scale:$Y(),realScaleType:"point"}},Kmt=1e-4,hOt=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])-Kmt,l=Math.max(a[0],a[1])+Kmt,o=t(n[0]),c=t(n[r-1]);(ol||cl)&&t.domain([n[0],n[r-1]])}},hdn=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])}},fdn=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)}},xdn={sign:pdn,expand:DZs,none:fU,silhouette:RZs,wiggle:OZs,positive:fdn},gdn=function(t,n,r){var a=n.map(function(o){return o.props.dataKey}),i=xdn[r],l=IZs().keys(a).value(function(o,c){return+ex(o,c,0)}).order(E9e).offset(i);return l(t)},ydn=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,x=(p=m.type)!==null&&p!==void 0&&p.defaultProps?ff(ff({},m.type.defaultProps),m.props):m.props,g=x.stackId,y=x.hide;if(y)return h;var b=x[r],v=h[b]||{hasStack:!1,stackGroups:{}};if(yg(g)){var N=v.stackGroups[g]||{numericAxisId:r,cateAxisId:a,items:[]};N.items.push(m),v.hasStack=!0,v.stackGroups[g]=N}else v.stackGroups[oF("_stackId_")]={numericAxisId:r,cateAxisId:a,items:[m]};return ff(ff({},h),{},dB({},b,v))},c),u={};return Object.keys(d).reduce(function(h,m){var p=d[m];if(p.hasStack){var x={};p.stackGroups=Object.keys(p.stackGroups).reduce(function(g,y){var b=p.stackGroups[y];return ff(ff({},g),{},dB({},y,{numericAxisId:r,cateAxisId:a,items:b.items,stackedData:gdn(t,b.items,i)}))},x)}return ff(ff({},h),{},dB({},m,p))},u)},mOt=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=Lcn(d,i,o);return t.domain([bEe(u),JE(u)]),{niceTicks:u}}if(i&&a==="number"){var h=t.domain(),m=Pcn(h,i,o);return{niceTicks:m}}return null};function D5e(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&&!Pl(a[t.dataKey])){var o=o5e(n,"value",a[t.dataKey]);if(o)return o.coordinate+r/2}return n[i]?n[i].coordinate+r/2:null}var c=ex(a,Pl(l)?t.dataKey:l);return Pl(c)?null:t.scale(c)}var Ymt=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=ex(l,n.dataKey,n.domain[o]);return Pl(c)?null:n.scale(c)-i/2+a},vdn=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]},bdn=function(t,n){var r,a=(r=t.type)!==null&&r!==void 0&&r.defaultProps?ff(ff({},t.type.defaultProps),t.props):t.props,i=a.stackId;if(yg(i)){var l=n[i];if(l){var o=l.items.indexOf(t);return o>=0?l.stackedData[o]:null}}return null},_dn=function(t){return t.reduce(function(n,r){return[bEe(r.concat([n[0]]).filter(za)),JE(r.concat([n[1]]).filter(za))]},[1/0,-1/0])},pOt=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=_dn(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})},Zmt=/^dataMin[\s]*-[\s]*([0-9]+([.]{1}[0-9]+){0,1})$/,Xmt=/^dataMax[\s]*\+[\s]*([0-9]+([.]{1}[0-9]+){0,1})$/,aze=function(t,n,r){if(dl(t))return t(n,r);if(!Array.isArray(t))return n;var a=[];if(za(t[0]))a[0]=r?t[0]:Math.min(t[0],n[0]);else if(Zmt.test(t[0])){var i=+Zmt.exec(t[0])[1];a[0]=n[0]-i}else dl(t[0])?a[0]=t[0](n[0]):a[0]=n[0];if(za(t[1]))a[1]=r?t[1]:Math.max(t[1],n[1]);else if(Xmt.test(t[1])){var l=+Xmt.exec(t[1])[1];a[1]=n[1]+l}else dl(t[1])?a[1]=t[1](n[1]):a[1]=n[1];return a},R5e=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=wKe(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},Tdn=function(t,n,r,a,i){var l=t.width,o=t.height,c=t.startAngle,d=t.endAngle,u=d1(t.cx,l,l/2),h=d1(t.cy,o,o/2),m=gOt(l,o,r),p=d1(t.innerRadius,m,0),x=d1(t.outerRadius,m,m*.8),g=Object.keys(n);return g.reduce(function(y,b){var v=n[b],N=v.domain,C=v.reversed,A;if(Pl(v.range))a==="angleAxis"?A=[c,d]:a==="radiusAxis"&&(A=[p,x]),C&&(A=[A[1],A[0]]);else{A=v.range;var T=A,P=Ndn(T,2);c=P[0],d=P[1]}var M=uOt(v,i),I=M.realScaleType,D=M.scale;D.domain(N).range(A),hOt(D);var B=mOt(D,V4(V4({},v),{},{realScaleType:I})),q=V4(V4(V4({},v),B),{},{range:A,radius:x,realScaleType:I,scale:D,cx:u,cy:h,innerRadius:p,outerRadius:x,startAngle:c,endAngle:d});return V4(V4({},y),{},xOt({},b,q))},{})},Mdn=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))},Ldn=function(t,n){var r=t.x,a=t.y,i=n.cx,l=n.cy,o=Mdn({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:Edn(d),angleInRadian:d}},Pdn=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}},Idn=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},tpt=function(t,n){var r=t.x,a=t.y,i=Ldn({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=Pdn(n),h=u.startAngle,m=u.endAngle,p=o,x;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 x?V4(V4({},n),{},{radius:l,angle:Idn(p,n)}):null},yOt=function(t){return!j.isValidElement(t)&&!dl(t)&&typeof t!="boolean"?t.className:""};function PX(s){"@babel/helpers - typeof";return PX=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},PX(s)}var Ddn=["offset"];function Rdn(s){return Bdn(s)||zdn(s)||Fdn(s)||Odn()}function Odn(){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 Fdn(s,t){if(s){if(typeof s=="string")return ize(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 ize(s,t)}}function zdn(s){if(typeof Symbol<"u"&&s[Symbol.iterator]!=null||s["@@iterator"]!=null)return Array.from(s)}function Bdn(s){if(Array.isArray(s))return ize(s)}function ize(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 Udn(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 spt(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 Jx(s){for(var t=1;t=0?1:-1,N,C;a==="insideStart"?(N=p+v*l,C=g):a==="insideEnd"?(N=x-v*l,C=!g):a==="end"&&(N=x+v*l,C=g),C=b<=0?C:!C;var A=Xh(d,u,y,N),T=Xh(d,u,y,N+(C?1:-1)*359),P="M".concat(A.x,",").concat(A.y,` A`).concat(y,",").concat(y,",0,1,").concat(C?0:1,`, `).concat(T.x,",").concat(T.y),M=Pl(t.id)?oF("recharts-radial-line-"):t.id;return It.createElement("text",IX({},r,{dominantBaseline:"central",className:$l("recharts-radial-bar-label",o)}),It.createElement("defs",null,It.createElement("path",{id:M,d:P})),It.createElement("textPath",{xlinkHref:"#".concat(M)},n))},Ydn=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=Xh(l,o,d+r,m),x=p.x,g=p.y;return{x,y:g,textAnchor:x>=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,b=Xh(l,o,y,m),v=b.x,N=b.y;return{x:v,y:N,textAnchor:"middle",verticalAnchor:"middle"}},Zdn=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",x=h>0?"start":"end",g=d>=0?1:-1,y=g*a,b=g>0?"end":"start",v=g>0?"start":"end";if(i==="top"){var N={x:o+d/2,y:c-h*a,textAnchor:"middle",verticalAnchor:p};return Jx(Jx({},N),r?{height:Math.max(c-r.y,0),width:d}:{})}if(i==="bottom"){var C={x:o+d/2,y:c+u+m,textAnchor:"middle",verticalAnchor:x};return Jx(Jx({},C),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:b,verticalAnchor:"middle"};return Jx(Jx({},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:v,verticalAnchor:"middle"};return Jx(Jx({},T),r?{width:Math.max(r.x+r.width-T.x,0),height:u}:{})}var P=r?{width:d,height:u}:{};return i==="insideLeft"?Jx({x:o+y,y:c+u/2,textAnchor:v,verticalAnchor:"middle"},P):i==="insideRight"?Jx({x:o+d-y,y:c+u/2,textAnchor:b,verticalAnchor:"middle"},P):i==="insideTop"?Jx({x:o+d/2,y:c+m,textAnchor:"middle",verticalAnchor:x},P):i==="insideBottom"?Jx({x:o+d/2,y:c+u-m,textAnchor:"middle",verticalAnchor:p},P):i==="insideTopLeft"?Jx({x:o+y,y:c+m,textAnchor:v,verticalAnchor:x},P):i==="insideTopRight"?Jx({x:o+d-y,y:c+m,textAnchor:b,verticalAnchor:x},P):i==="insideBottomLeft"?Jx({x:o+y,y:c+u-m,textAnchor:v,verticalAnchor:p},P):i==="insideBottomRight"?Jx({x:o+d-y,y:c+u-m,textAnchor:b,verticalAnchor:p},P):Gq(i)&&(za(i.x)||z8(i.x))&&(za(i.y)||z8(i.y))?Jx({x:o+d1(i.x,d),y:c+d1(i.y,u),textAnchor:"end",verticalAnchor:"end"},P):Jx({x:o+d/2,y:c+u/2,textAnchor:"middle",verticalAnchor:"middle"},P)},Xdn=function(t){return"cx"in t&&za(t.cx)};function f0(s){var t=s.offset,n=t===void 0?5:t,r=$dn(s,Ddn),a=Jx({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||Pl(o)&&Pl(c)&&!j.isValidElement(d)&&!dl(d))return null;if(j.isValidElement(d))return j.cloneElement(d,a);var p;if(dl(d)){if(p=j.createElement(d,a),j.isValidElement(p))return p}else p=Gdn(a);var x=Xdn(i),g=So(a,!0);if(x&&(l==="insideStart"||l==="insideEnd"||l==="end"))return Kdn(a,p,g);var y=x?Ydn(a):Zdn(a);return It.createElement(jO,IX({className:$l("recharts-label",h)},g,y,{breakAll:m}),p)}f0.displayName="Label";var vOt=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,x=t.left,g=t.width,y=t.height,b=t.clockWise,v=t.labelViewBox;if(v)return v;if(za(g)&&za(y)){if(za(h)&&za(m))return{x:h,y:m,width:g,height:y};if(za(p)&&za(x))return{x:p,y:x,width:g,height:y}}return za(h)&&za(m)?{x:h,y:m,width:0,height:0}:za(n)&&za(r)?{cx:n,cy:r,startAngle:i||a||0,endAngle:l||a||0,innerRadius:d||0,outerRadius:u||c||o||0,clockWise:b}:t.viewBox?t.viewBox:{}},Qdn=function(t,n){return t?t===!0?It.createElement(f0,{key:"label-implicit",viewBox:n}):yg(t)?It.createElement(f0,{key:"label-implicit",viewBox:n,value:t}):j.isValidElement(t)?t.type===f0?j.cloneElement(t,{key:"label-implicit",viewBox:n}):It.createElement(f0,{key:"label-implicit",content:t,viewBox:n}):dl(t)?It.createElement(f0,{key:"label-implicit",content:t,viewBox:n}):Gq(t)?It.createElement(f0,IX({viewBox:n},t,{key:"label-implicit"})):null:null},Jdn=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=vOt(t),l=lw(a,f0).map(function(c,d){return j.cloneElement(c,{viewBox:n||i,key:"label-".concat(d)})});if(!r)return l;var o=Qdn(t.label,n||i);return[o].concat(Rdn(l))};f0.parseViewBox=vOt;f0.renderCallByParent=Jdn;function eun(s){var t=s==null?0:s.length;return t?s[t-1]:void 0}var tun=eun;const sun=Uc(tun);function DX(s){"@babel/helpers - typeof";return DX=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},DX(s)}var nun=["valueAccessor"],run=["data","dataKey","clockWise","id","textBreakAll"];function aun(s){return cun(s)||lun(s)||oun(s)||iun()}function iun(){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 oun(s,t){if(s){if(typeof s=="string")return oze(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 oze(s,t)}}function lun(s){if(typeof Symbol<"u"&&s[Symbol.iterator]!=null||s["@@iterator"]!=null)return Array.from(s)}function cun(s){if(Array.isArray(s))return oze(s)}function oze(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 mun(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 pun=function(t){return Array.isArray(t.value)?sun(t.value):t.value};function m5(s){var t=s.valueAccessor,n=t===void 0?pun:t,r=apt(s,nun),a=r.data,i=r.dataKey,l=r.clockWise,o=r.id,c=r.textBreakAll,d=apt(r,run);return!a||!a.length?null:It.createElement(Yc,{className:"recharts-label-list"},a.map(function(u,h){var m=Pl(i)?n(u,h):ex(u&&u.payload,i),p=Pl(o)?{}:{id:"".concat(o,"-").concat(h)};return It.createElement(f0,F5e({},So(u,!0),d,p,{parentViewBox:u.parentViewBox,value:m,textBreakAll:c,viewBox:f0.parseViewBox(Pl(l)?u:rpt(rpt({},u),{},{clockWise:l})),key:"label-".concat(h),index:h}))}))}m5.displayName="LabelList";function fun(s,t){return s?s===!0?It.createElement(m5,{key:"labelList-implicit",data:t}):It.isValidElement(s)||dl(s)?It.createElement(m5,{key:"labelList-implicit",data:t,content:s}):Gq(s)?It.createElement(m5,F5e({data:t},s,{key:"labelList-implicit"})):null:null}function xun(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=lw(r,m5).map(function(l,o){return j.cloneElement(l,{data:t,key:"labelList-".concat(o)})});if(!n)return a;var i=fun(s.label,t);return[i].concat(aun(a))}m5.renderCallByParent=xun;function RX(s){"@babel/helpers - typeof";return RX=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},RX(s)}function lze(){return lze=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=Xh(n,r,a,l),x=Xh(n,r,a,d);m+="L ".concat(x.x,",").concat(x.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},_un=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=c1(u-d),m=Ere({cx:n,cy:r,radius:i,angle:d,sign:h,cornerRadius:l,cornerIsExternal:c}),p=m.circleTangency,x=m.lineTangency,g=m.theta,y=Ere({cx:n,cy:r,radius:i,angle:u,sign:-h,cornerRadius:l,cornerIsExternal:c}),b=y.circleTangency,v=y.lineTangency,N=y.theta,C=c?Math.abs(d-u):Math.abs(d-u)-g-N;if(C<0)return o?"M ".concat(x.x,",").concat(x.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 `):bOt({cx:n,cy:r,innerRadius:a,outerRadius:i,startAngle:d,endAngle:u});var A="M ".concat(x.x,",").concat(x.y,` A`).concat(l,",").concat(l,",0,0,").concat(+(h<0),",").concat(p.x,",").concat(p.y,` A`).concat(i,",").concat(i,",0,").concat(+(C>180),",").concat(+(h<0),",").concat(b.x,",").concat(b.y,` A`).concat(l,",").concat(l,",0,0,").concat(+(h<0),",").concat(v.x,",").concat(v.y,` `);if(a>0){var T=Ere({cx:n,cy:r,radius:a,angle:d,sign:h,isExternal:!0,cornerRadius:l,cornerIsExternal:c}),P=T.circleTangency,M=T.lineTangency,I=T.theta,D=Ere({cx:n,cy:r,radius:a,angle:u,sign:-h,isExternal:!0,cornerRadius:l,cornerIsExternal:c}),B=D.circleTangency,q=D.lineTangency,W=D.theta,V=c?Math.abs(d-u):Math.abs(d-u)-I-W;if(V<0&&l===0)return"".concat(A,"L").concat(n,",").concat(r,"Z");A+="L".concat(q.x,",").concat(q.y,` A`).concat(l,",").concat(l,",0,0,").concat(+(h<0),",").concat(B.x,",").concat(B.y,` A`).concat(a,",").concat(a,",0,").concat(+(V>180),",").concat(+(h>0),",").concat(P.x,",").concat(P.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},wun={cx:0,cy:0,innerRadius:0,outerRadius:0,startAngle:0,endAngle:0,cornerRadius:0,forceCornerRadius:!1,cornerIsExternal:!1},_Ot=function(t){var n=opt(opt({},wun),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=_un({cx:r,cy:a,innerRadius:i,outerRadius:l,cornerRadius:Math.min(g,x/2),forceCornerRadius:c,cornerIsExternal:d,startAngle:u,endAngle:h}):y=bOt({cx:r,cy:a,innerRadius:i,outerRadius:l,startAngle:u,endAngle:h}),It.createElement("path",lze({},So(n,!0),{className:p,d:y,role:"img"}))};function OX(s){"@babel/helpers - typeof";return OX=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},OX(s)}function cze(){return cze=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 Oun(s,t){return rV(s.getTime(),t.getTime())}function fpt(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],x=o.value,g=x[0],y=x[1];!d&&!r[u]&&(d=n.equals(m,g,i,u,s,t,n)&&n.equals(p,y,m,g,s,t,n))&&(r[u]=!0),u++}if(!d)return!1;i++}return!0}function Fun(s,t,n){var r=ppt(s),a=r.length;if(ppt(t).length!==a)return!1;for(var i;a-- >0;)if(i=r[a],i===SOt&&(s.$$typeof||t.$$typeof)&&s.$$typeof!==t.$$typeof||!kOt(t,i)||!n.equals(s[i],t[i],i,i,s,t,n))return!1;return!0}function jG(s,t,n){var r=hpt(s),a=r.length;if(hpt(t).length!==a)return!1;for(var i,l,o;a-- >0;)if(i=r[a],i===SOt&&(s.$$typeof||t.$$typeof)&&s.$$typeof!==t.$$typeof||!kOt(t,i)||!n.equals(s[i],t[i],i,i,s,t,n)||(l=mpt(s,i),o=mpt(t,i),(l||o)&&(!l||!o||l.configurable!==o.configurable||l.enumerable!==o.enumerable||l.writable!==o.writable)))return!1;return!0}function zun(s,t){return rV(s.valueOf(),t.valueOf())}function Bun(s,t){return s.source===t.source&&s.flags===t.flags}function xpt(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 $un(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 Uun="[object Arguments]",qun="[object Boolean]",Vun="[object Date]",Hun="[object Map]",Gun="[object Number]",Wun="[object Object]",Kun="[object RegExp]",Yun="[object Set]",Zun="[object String]",Xun=Array.isArray,gpt=typeof ArrayBuffer=="function"&&ArrayBuffer.isView?ArrayBuffer.isView:null,ypt=Object.assign,Qun=Object.prototype.toString.call.bind(Object.prototype.toString);function Jun(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(Xun(u))return t(u,h,m);if(gpt!=null&&gpt(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 x=Qun(u);return x===Vun?n(u,h,m):x===Kun?l(u,h,m):x===Hun?r(u,h,m):x===Yun?o(u,h,m):x===Wun?typeof u.then!="function"&&typeof h.then!="function"&&a(u,h,m):x===Uun?a(u,h,m):x===qun||x===Gun||x===Zun?i(u,h,m):!1}}function ehn(s){var t=s.circular,n=s.createCustomConfig,r=s.strict,a={areArraysEqual:r?jG:Run,areDatesEqual:Oun,areMapsEqual:r?upt(fpt,jG):fpt,areObjectsEqual:r?jG:Fun,arePrimitiveWrappersEqual:zun,areRegExpsEqual:Bun,areSetsEqual:r?upt(xpt,jG):xpt,areTypedArraysEqual:r?jG:$un};if(n&&(a=ypt({},a,n(a))),t){var i=Mre(a.areArraysEqual),l=Mre(a.areMapsEqual),o=Mre(a.areObjectsEqual),c=Mre(a.areSetsEqual);a=ypt({},a,{areArraysEqual:i,areMapsEqual:l,areObjectsEqual:o,areSetsEqual:c})}return a}function thn(s){return function(t,n,r,a,i,l,o){return s(t,n,o)}}function shn(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 nhn=K6();K6({strict:!0});K6({circular:!0});K6({circular:!0,strict:!0});K6({createInternalComparator:function(){return rV}});K6({strict:!0,createInternalComparator:function(){return rV}});K6({circular:!0,createInternalComparator:function(){return rV}});K6({circular:!0,createInternalComparator:function(){return rV},strict:!0});function K6(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=ehn(s),c=Jun(o),d=r?r(c):thn(c);return shn({circular:n,comparator:c,createState:a,equals:d,strict:l})}function rhn(s){typeof requestAnimationFrame<"u"&&requestAnimationFrame(s)}function vpt(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):rhn(a)};requestAnimationFrame(r)}function dze(s){"@babel/helpers - typeof";return dze=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},dze(s)}function ahn(s){return chn(s)||lhn(s)||ohn(s)||ihn()}function ihn(){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 ohn(s,t){if(s){if(typeof s=="string")return bpt(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 bpt(s,t)}}function bpt(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:b<0?0:b},g=function(b){for(var v=b>1?1:b,N=v,C=0;C<8;++C){var A=h(N)-v,T=p(N);if(Math.abs(A-v)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,x=m*i,g=m+(p-x)*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 Bhn(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 XIe(s){return Vhn(s)||qhn(s)||Uhn(s)||$hn()}function $hn(){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 Uhn(s,t){if(s){if(typeof s=="string")return fze(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 fze(s,t)}}function qhn(s){if(typeof Symbol<"u"&&s[Symbol.iterator]!=null||s["@@iterator"]!=null)return Array.from(s)}function Vhn(s){if(Array.isArray(s))return fze(s)}function fze(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 $5e(s){return $5e=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(n){return n.__proto__||Object.getPrototypeOf(n)},$5e(s)}var YN=function(s){Yhn(n,s);var t=Zhn(n);function n(r,a){var i;Hhn(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(yze(i)),i.changeStyle=i.changeStyle.bind(yze(i)),!o||p<=0)return i.state={style:{}},typeof m=="function"&&(i.state={style:u}),gze(i);if(h&&h.length)i.state={style:h[0].style};else if(d){if(typeof m=="function")return i.state={style:d},gze(i);i.state={style:c?EW({},c,d):d}}else i.state={style:{}};return i}return Whn(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?EW({},c,u):u};this.state&&m&&(c&&m[c]!==u||!c&&m!==u)&&this.setState(p);return}if(!(nhn(a.to,u)&&a.canBegin&&a.isActive)){var x=!a.canBegin||!a.isActive;this.manager&&this.manager.stop(),this.stopJSAnimation&&this.stopJSAnimation();var g=x||d?h:a.to;if(this.state&&m){var y={style:c?EW({},c,g):g};(c&&m[c]!==g||!c&&m!==g)&&this.setState(y)}this.runAnimation(q2(q2({},this.props),{},{from:g,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=Ohn(l,o,Shn(d),c,this.changeStyle),x=function(){i.stopJSAnimation=p()};this.manager.start([m,u,x,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(g,y,b){if(b===0)return g;var v=y.duration,N=y.easing,C=N===void 0?"ease":N,A=y.style,T=y.properties,P=y.onAnimationEnd,M=b>0?l[b-1]:y,I=T||Object.keys(A);if(typeof C=="function"||C==="spring")return[].concat(XIe(g),[i.runJSAnimation.bind(i,{from:M.style,to:A,duration:v,easing:C}),v]);var D=jpt(I,v,C),B=q2(q2(q2({},M.style),A),{},{transition:D});return[].concat(XIe(g),[B,v,P]).filter(phn)};return this.manager.start([c].concat(XIe(l.reduce(p,[u,Math.max(m,o)])),[a.onAnimationEnd]))}},{key:"runAnimation",value:function(a){this.manager||(this.manager=dhn());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,x=this.manager;if(this.unSubscribe=x.subscribe(this.handleStyleChange),typeof d=="function"||typeof p=="function"||d==="spring"){this.runJSAnimation(a);return}if(m.length>1){this.runStepAnimation(a);return}var g=o?EW({},o,c):c,y=jpt(Object.keys(g),l,d);x.start([u,i,q2(q2({},g),{},{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=zhn(a,Fhn),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 x=p.props,g=x.style,y=g===void 0?{}:g,b=x.className,v=j.cloneElement(p,q2(q2({},c),{},{style:q2(q2({},y),u),className:b}));return v};return d===1?h(j.Children.only(i)):It.createElement("div",null,j.Children.map(i,function(m){return h(m)}))}}]),n}(j.PureComponent);YN.displayName="Animate";YN.defaultProps={begin:0,duration:1e3,from:"",to:"",attributeName:"",easing:"ease",isActive:!0,canBegin:!0,steps:[],onAnimationEnd:function(){},onAnimationStart:function(){}};YN.propTypes={from:Su.oneOfType([Su.object,Su.string]),to:Su.oneOfType([Su.object,Su.string]),attributeName:Su.string,duration:Su.number,begin:Su.number,easing:Su.oneOfType([Su.string,Su.func]),steps:Su.arrayOf(Su.shape({duration:Su.number.isRequired,style:Su.object.isRequired,easing:Su.oneOfType([Su.oneOf(["ease","ease-in","ease-out","ease-in-out","linear"]),Su.func]),properties:Su.arrayOf("string"),onAnimationEnd:Su.func})),children:Su.oneOfType([Su.node,Su.func]),isActive:Su.bool,canBegin:Su.bool,onAnimationEnd:Su.func,shouldReAnimate:Su.bool,onAnimationStart:Su.func,onAnimationReStart:Su.func};function BX(s){"@babel/helpers - typeof";return BX=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},BX(s)}function U5e(){return U5e=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 x=Math.min(l,i);u="M ".concat(t,",").concat(n+o*x,` A `).concat(x,",").concat(x,",0,0,").concat(d,",").concat(t+c*x,",").concat(n,` L `).concat(t+r-c*x,",").concat(n,` A `).concat(x,",").concat(x,",0,0,").concat(d,",").concat(t+r,",").concat(n+o*x,` L `).concat(t+r,",").concat(n+a-o*x,` A `).concat(x,",").concat(x,",0,0,").concat(d,",").concat(t+r-c*x,",").concat(n+a,` L `).concat(t+c*x,",").concat(n+a,` A `).concat(x,",").concat(x,",0,0,").concat(d,",").concat(t,",").concat(n+a-o*x," Z")}else u="M ".concat(t,",").concat(n," h ").concat(r," v ").concat(a," h ").concat(-r," Z");return u},imn=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},omn={x:0,y:0,width:0,height:0,radius:0,isAnimationActive:!1,isUpdateAnimationActive:!1,animationBegin:0,animationDuration:1500,animationEasing:"ease"},YKe=function(t){var n=Mpt(Mpt({},omn),t),r=j.useRef(),a=j.useState(-1),i=Qhn(a,2),l=i[0],o=i[1];j.useEffect(function(){if(r.current&&r.current.getTotalLength)try{var C=r.current.getTotalLength();C&&o(C)}catch{}},[]);var c=n.x,d=n.y,u=n.width,h=n.height,m=n.radius,p=n.className,x=n.animationEasing,g=n.animationDuration,y=n.animationBegin,b=n.isAnimationActive,v=n.isUpdateAnimationActive;if(c!==+c||d!==+d||u!==+u||h!==+h||u===0||h===0)return null;var N=$l("recharts-rectangle",p);return v?It.createElement(YN,{canBegin:l>0,from:{width:u,height:h,x:c,y:d},to:{width:u,height:h,x:c,y:d},duration:g,animationEasing:x,isActive:v},function(C){var A=C.width,T=C.height,P=C.x,M=C.y;return It.createElement(YN,{canBegin:l>0,from:"0px ".concat(l===-1?1:l,"px"),to:"".concat(l,"px 0px"),attributeName:"strokeDasharray",begin:y,duration:g,isActive:b,easing:x},It.createElement("path",U5e({},So(n,!0),{className:N,d:Lpt(P,M,A,T,m),ref:r})))}):It.createElement("path",U5e({},So(n,!0),{className:N,d:Lpt(c,d,u,h,m)}))},lmn=["points","className","baseLinePoints","connectNulls"];function X9(){return X9=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 dmn(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 Ppt(s){return pmn(s)||mmn(s)||hmn(s)||umn()}function umn(){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 hmn(s,t){if(s){if(typeof s=="string")return vze(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 vze(s,t)}}function mmn(s){if(typeof Symbol<"u"&&s[Symbol.iterator]!=null||s["@@iterator"]!=null)return Array.from(s)}function pmn(s){if(Array.isArray(s))return vze(s)}function vze(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){Ipt(r)?n[n.length-1].push(r):n[n.length-1].length>0&&n.push([])}),Ipt(t[0])&&n[n.length-1].push(t[0]),n[n.length-1].length<=0&&(n=n.slice(0,-1)),n},VY=function(t,n){var r=fmn(t);n&&(r=[r.reduce(function(i,l){return[].concat(Ppt(i),Ppt(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},xmn=function(t,n,r){var a=VY(t,r);return"".concat(a.slice(-1)==="Z"?a.slice(0,-1):a,"L").concat(VY(n.reverse(),r).slice(1))},gmn=function(t){var n=t.points,r=t.className,a=t.baseLinePoints,i=t.connectNulls,l=cmn(t,lmn);if(!n||!n.length)return null;var o=$l("recharts-polygon",r);if(a&&a.length){var c=l.stroke&&l.stroke!=="none",d=xmn(n,a,i);return It.createElement("g",{className:o},It.createElement("path",X9({},So(l,!0),{fill:d.slice(-1)==="Z"?l.fill:"none",stroke:"none",d})),c?It.createElement("path",X9({},So(l,!0),{fill:"none",d:VY(n,i)})):null,c?It.createElement("path",X9({},So(l,!0),{fill:"none",d:VY(a,i)})):null)}var u=VY(n,i);return It.createElement("path",X9({},So(l,!0),{fill:u.slice(-1)==="Z"?l.fill:"none",className:o,d:u}))};function bze(){return bze=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 Nmn(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 kmn=function(t,n,r,a,i,l){return"M".concat(t,",").concat(i,"v").concat(a,"M").concat(l,",").concat(n,"h").concat(r)},Smn=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,x=t.className,g=jmn(t,ymn),y=vmn({x:r,y:i,top:o,left:d,width:h,height:p},g);return!za(r)||!za(i)||!za(h)||!za(p)||!za(o)||!za(d)?null:It.createElement("path",_ze({},So(y,!0),{className:$l("recharts-cross",x),d:kmn(r,i,h,p,o,d)}))},Cmn=vEe,Amn=qRt,Emn=O5;function Tmn(s,t){return s&&s.length?Cmn(s,Emn(t),Amn):void 0}var Mmn=Tmn;const Lmn=Uc(Mmn);var Pmn=vEe,Imn=O5,Dmn=VRt;function Rmn(s,t){return s&&s.length?Pmn(s,Imn(t),Dmn):void 0}var Omn=Rmn;const Fmn=Uc(Omn);var zmn=["cx","cy","angle","ticks","axisLine"],Bmn=["ticks","tick","angle","tickFormatter","stroke"];function kU(s){"@babel/helpers - typeof";return kU=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},kU(s)}function HY(){return HY=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 $mn(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 Umn(s,t){if(!(s instanceof t))throw new TypeError("Cannot call a class as a function")}function Fpt(s,t){for(var n=0;n$pt?l=a==="outer"?"start":"end":i<-$pt?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=$M($M({},So(this.props,!1)),{},{fill:"none"},So(o,!1));if(c==="circle")return It.createElement(Wee,_8({className:"recharts-polar-angle-axis-line"},d,{cx:a,cy:i,r:l}));var u=this.props.ticks,h=u.map(function(m){return Xh(a,i,l,m.coordinate)});return It.createElement(gmn,_8({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=So(this.props,!1),h=So(l,!1),m=$M($M({},u),{},{fill:"none"},So(o,!1)),p=i.map(function(x,g){var y=r.getTickLineCoord(x),b=r.getTickTextAnchor(x),v=$M($M($M({textAnchor:b},u),{},{stroke:"none",fill:d},h),{},{index:g,payload:x,x:y.x2,y:y.y2});return It.createElement(Yc,_8({className:$l("recharts-polar-angle-axis-tick",yOt(l)),key:"tick-".concat(x.coordinate)},wO(r.props,x,g)),o&&It.createElement("line",_8({className:"recharts-polar-angle-axis-tick-line"},m,y)),l&&t.renderTickItem(l,v,c?c(x.value,g):x.value))});return It.createElement(Yc,{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:It.createElement(Yc,{className:$l("recharts-polar-angle-axis",this.props.className)},l&&this.renderAxisLine(),this.renderTicks())}}],[{key:"renderTickItem",value:function(r,a,i){var l;return It.isValidElement(r)?l=It.cloneElement(r,a):dl(r)?l=r(a):l=It.createElement(jO,_8({},a,{className:"recharts-polar-angle-axis-tick-value"}),i),l}}])}(j.PureComponent);kEe(SEe,"displayName","PolarAngleAxis");kEe(SEe,"axisType","angleAxis");kEe(SEe,"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 npn=zDt,rpn=npn(Object.getPrototypeOf,Object),apn=rpn,ipn=AC,opn=apn,lpn=EC,cpn="[object Object]",dpn=Function.prototype,upn=Object.prototype,OOt=dpn.toString,hpn=upn.hasOwnProperty,mpn=OOt.call(Object);function ppn(s){if(!lpn(s)||ipn(s)!=cpn)return!1;var t=opn(s);if(t===null)return!0;var n=hpn.call(t,"constructor")&&t.constructor;return typeof n=="function"&&n instanceof n&&OOt.call(n)==mpn}var fpn=ppn;const xpn=Uc(fpn);var gpn=AC,ypn=EC,vpn="[object Boolean]";function bpn(s){return s===!0||s===!1||ypn(s)&&gpn(s)==vpn}var _pn=bpn;const wpn=Uc(_pn);function UX(s){"@babel/helpers - typeof";return UX=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},UX(s)}function H5e(){return H5e=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:g,animationEasing:x,isActive:b},function(N){var C=N.upperWidth,A=N.lowerWidth,T=N.height,P=N.x,M=N.y;return It.createElement(YN,{canBegin:l>0,from:"0px ".concat(l===-1?1:l,"px"),to:"".concat(l,"px 0px"),attributeName:"strokeDasharray",begin:y,duration:g,easing:x},It.createElement("path",H5e({},So(n,!0),{className:v,d:Hpt(P,M,C,A,T),ref:r})))}):It.createElement("g",null,It.createElement("path",H5e({},So(n,!0),{className:v,d:Hpt(c,d,u,h,m)})))},Ppn=["option","shapeType","propTransformer","activeClassName","isActive"];function qX(s){"@babel/helpers - typeof";return qX=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},qX(s)}function Ipn(s,t){if(s==null)return{};var n=Dpn(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 Dpn(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 Gpt(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 G5e(s){for(var t=1;t0?ow(N,"paddingAngle",0):0;if(A){var P=mg(A.endAngle-A.startAngle,N.endAngle-N.startAngle),M=Gh(Gh({},N),{},{startAngle:v+T,endAngle:v+P(g)+T});y.push(M),v=M.endAngle}else{var I=N.endAngle,D=N.startAngle,B=mg(0,I-D),q=B(g),W=Gh(Gh({},N),{},{startAngle:v+T,endAngle:v+q+T});y.push(W),v=W.endAngle}}),It.createElement(Yc,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||!NO(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,x=this.state.isAnimationFinished;if(i||!l||!l.length||!za(d)||!za(u)||!za(h)||!za(m))return null;var g=$l("recharts-pie",o);return It.createElement(Yc,{tabIndex:this.props.rootTabIndex,className:g,ref:function(b){r.pieRef=b}},this.renderSectors(),c&&this.renderLabels(l),f0.renderCallByParent(this.props,null,!1),(!p||x)&&m5.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?v:v-1)*c,C=y-v*p-N,A=a.reduce(function(M,I){var D=ex(I,b,0);return M+(za(D)?D:0)},0),T;if(A>0){var P;T=a.map(function(M,I){var D=ex(M,b,0),B=ex(M,u,I),q=(za(D)?D:0)/A,W;I?W=P.endAngle+c1(g)*c*(D!==0?1:0):W=l;var V=W+c1(g)*((D!==0?p:0)+q*C),K=(W+V)/2,Q=(x.innerRadius+x.outerRadius)/2,J=[{name:B,value:D,payload:M,dataKey:b,type:m}],ce=Xh(x.cx,x.cy,Q,K);return P=Gh(Gh(Gh({percent:q,cornerRadius:i,name:B,tooltipPayload:J,midAngle:K,middleRadius:Q,tooltipPosition:ce},M),x),{},{value:ex(M,b),startAngle:W,endAngle:V,payload:M,paddingAngle:c1(g)*c}),P})}return Gh(Gh({},x),{},{sectors:T,data:a})});var sfn=Math.ceil,nfn=Math.max;function rfn(s,t,n,r){for(var a=-1,i=nfn(sfn((t-s)/(n||1)),0),l=Array(i);i--;)l[r?i:++a]=s,s+=n;return l}var afn=rfn,ifn=rRt,Zpt=1/0,ofn=17976931348623157e292;function lfn(s){if(!s)return s===0?s:0;if(s=ifn(s),s===Zpt||s===-Zpt){var t=s<0?-1:1;return t*ofn}return s===s?s:0}var $Ot=lfn,cfn=afn,dfn=hEe,QIe=$Ot;function ufn(s){return function(t,n,r){return r&&typeof r!="number"&&dfn(t,n,r)&&(n=r=void 0),t=QIe(t),n===void 0?(n=t,t=0):n=QIe(n),r=r===void 0?t0&&r.handleDrag(a.changedTouches[0])}),k_(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()}),k_(r,"handleLeaveWrapper",function(){(r.state.isTravellerMoving||r.state.isSlideMoving)&&(r.leaveTimer=window.setTimeout(r.handleDragEnd,r.props.leaveTimeOut))}),k_(r,"handleEnterSlideOrTraveller",function(){r.setState({isTextActive:!0})}),k_(r,"handleLeaveSlideOrTraveller",function(){r.setState({isTextActive:!1})}),k_(r,"handleSlideDragStart",function(a){var i=tft(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 kfn(t,s),_fn(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),x=t.getIndexInRange(l,m);return{startIndex:p-p%c,endIndex:x===u?u:x-x%c}}},{key:"getTextOfTick",value:function(r){var a=this.props,i=a.data,l=a.tickFormatter,o=a.dataKey,c=ex(i[r],o,r);return dl(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,x=c.onChange,g=r.pageX-i;g>0?g=Math.min(g,d+u-h-o,d+u-h-l):g<0&&(g=Math.max(g,d-l,d-o));var y=this.getIndex({startX:l+g,endX:o+g});(y.startIndex!==m||y.endIndex!==p)&&x&&x(y),this.setState({startX:l+g,endX:o+g,slideMoveStartX:r.pageX})}},{key:"handleTravellerDragStart",value:function(r,a){var i=tft(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,x=u.onChange,g=u.gap,y=u.data,b={startX:this.state.startX,endX:this.state.endX},v=r.pageX-i;v>0?v=Math.min(v,h+m-p-d):v<0&&(v=Math.max(v,h-d)),b[l]=d+v;var N=this.getIndex(b),C=N.startIndex,A=N.endIndex,T=function(){var M=y.length-1;return l==="startX"&&(o>c?C%g===0:A%g===0)||oc?A%g===0:C%g===0)||o>c&&A===M};this.setState(k_(k_({},l,d+v),"brushMoveStartX",r.pageX),function(){x&&T()&&x(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(k_({},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 It.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?It.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,x=c.data,g=c.startIndex,y=c.endIndex,b=Math.max(r,this.props.x),v=JIe(JIe({},So(this.props,!1)),{},{x:b,y:d,width:u,height:h}),N=p||"Min value: ".concat((i=x[g])===null||i===void 0?void 0:i.name,", Max value: ").concat((l=x[y])===null||l===void 0?void 0:l.name);return It.createElement(Yc,{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,v))}},{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 It.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,x={pointerEvents:"none",fill:d};return It.createElement(Yc,{className:"recharts-brush-texts"},It.createElement(jO,Y5e({textAnchor:"end",verticalAnchor:"middle",x:Math.min(h,m)-p,y:l+o/2},x),this.getTextOfTick(a)),It.createElement(jO,Y5e({textAnchor:"start",verticalAnchor:"middle",x:Math.max(h,m)+c+p,y:l+o/2},x),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,x=m.endX,g=m.isTextActive,y=m.isSlideMoving,b=m.isTravellerMoving,v=m.isTravellerFocused;if(!a||!a.length||!za(o)||!za(c)||!za(d)||!za(u)||d<=0||u<=0)return null;var N=$l("recharts-brush",i),C=It.Children.count(l)===1,A=vfn("userSelect","none");return It.createElement(Yc,{className:N,onMouseLeave:this.handleLeaveWrapper,onTouchMove:this.handleTouchMove,style:A},this.renderBackground(),C&&this.renderPanorama(),this.renderSlide(p,x),this.renderTravellerLayer(p,"startX"),this.renderTravellerLayer(x,"endX"),(g||y||b||v||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 It.createElement(It.Fragment,null,It.createElement("rect",{x:a,y:i,width:l,height:o,fill:c,stroke:"none"}),It.createElement("line",{x1:a+1,y1:d,x2:a+l-1,y2:d,fill:"none",stroke:"#fff"}),It.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 It.isValidElement(r)?i=It.cloneElement(r,a):dl(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 JIe({prevData:i,prevTravellerWidth:c,prevUpdateId:d,prevX:o,prevWidth:l},i&&i.length?Cfn({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);k_(EU,"displayName","Brush");k_(EU,"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 Afn=_Ke;function Efn(s,t){var n;return Afn(s,function(r,a,i){return n=t(r,a,i),!n}),!!n}var Tfn=Efn,Mfn=MDt,Lfn=O5,Pfn=Tfn,Ifn=Wb,Dfn=hEe;function Rfn(s,t,n){var r=Ifn(s)?Mfn:Pfn;return n&&Dfn(s,t,n)&&(t=void 0),r(s,Lfn(t))}var Ofn=Rfn;const Ffn=Uc(Ofn);var p5=function(t,n){var r=t.alwaysShow,a=t.ifOverflow;return r&&(a="extendDomain"),a===n},sft=JDt;function zfn(s,t,n){t=="__proto__"&&sft?sft(s,t,{configurable:!0,enumerable:!0,value:n,writable:!0}):s[t]=n}var Bfn=zfn,$fn=Bfn,Ufn=XDt,qfn=O5;function Vfn(s,t){var n={};return t=qfn(t),Ufn(s,function(r,a,i){$fn(n,a,t(r,a,i))}),n}var Hfn=Vfn;const Gfn=Uc(Hfn);function Wfn(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 dxn(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 uxn(s,t){var n=s.x,r=s.y,a=cxn(s,axn),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 NG(NG(NG(NG(NG({},t),a),l?{x:l}:{}),c?{y:c}:{}),{},{height:u,width:m,name:t.name,radius:t.radius})}function rft(s){return It.createElement(FOt,Sze({shapeType:"rectangle",propTransformer:uxn,activeClassName:"recharts-active-bar"},s))}var hxn=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=za(r)||KKs(r);return i?t(r,a):(i||SO(),n)}},mxn=["value","background"],GOt;function TU(s){"@babel/helpers - typeof";return TU=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},TU(s)}function pxn(s,t){if(s==null)return{};var n=fxn(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 fxn(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 X5e(){return X5e=Object.assign?Object.assign.bind():function(s){for(var t=1;t0&&Math.abs(K)0&&Math.abs(V)0&&(W=Math.min((ve||0)-(V[ge-1]||0),W))}),Number.isFinite(W)){var K=W/q,Q=g.layout==="vertical"?r.height:r.width;if(g.padding==="gap"&&(P=K*Q/2),g.padding==="no-gap"){var J=d1(t.barCategoryGap,K*Q),ce=K*Q/2;P=ce-J-(ce-J)/Q*J}}}a==="xAxis"?M=[r.left+(N.left||0)+(P||0),r.left+r.width-(N.right||0)-(P||0)]:a==="yAxis"?M=c==="horizontal"?[r.top+r.height-(N.bottom||0),r.top+(N.top||0)]:[r.top+(N.top||0)+(P||0),r.top+r.height-(N.bottom||0)-(P||0)]:M=g.range,A&&(M=[M[1],M[0]]);var ue=uOt(g,i,m),ne=ue.scale,ee=ue.realScaleType;ne.domain(b).range(M),hOt(ne);var le=mOt(ne,gN(gN({},g),{},{realScaleType:ee}));a==="xAxis"?(B=y==="top"&&!C||y==="bottom"&&C,I=r.left,D=h[T]-B*g.height):a==="yAxis"&&(B=y==="left"&&!C||y==="right"&&C,I=h[T]-B*g.width,D=r.top);var he=gN(gN(gN({},g),le),{},{realScaleType:ee,x:I,y:D,scale:ne,width:a==="xAxis"?r.width:g.width,height:a==="yAxis"?r.height:g.height});return he.bandSize=R5e(he,le),!g.hide&&a==="xAxis"?h[T]+=(B?-1:1)*he.height:g.hide||(h[T]+=(B?-1:1)*he.width),gN(gN({},p),{},EEe({},x,he))},{})},ZOt=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)}},Sxn=function(t){var n=t.x1,r=t.y1,a=t.x2,i=t.y2;return ZOt({x:n,y:r},{x:a,y:i})},XOt=function(){function s(t){jxn(this,s),this.scale=t}return Nxn(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)}}])}();EEe(XOt,"EPS",1e-4);var XKe=function(t){var n=Object.keys(t).reduce(function(r,a){return gN(gN({},r),{},EEe({},a,XOt.create(t[a])))},{});return gN(gN({},n),{},{apply:function(a){var i=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},l=i.bandAware,o=i.position;return Gfn(a,function(c,d){return n[d].apply(c,{bandAware:l,position:o})})},isInRange:function(a){return HOt(a,function(i,l){return n[l].isInRange(i)})}})};function Cxn(s){return(s%180+180)%180}var Axn=function(t){var n=t.width,r=t.height,a=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0,i=Cxn(a),l=i*Math.PI/180,o=Math.atan(r/n),c=l>o&&l-1?a[i?t[l]:l]:void 0}}var Pxn=Lxn,Ixn=$Ot;function Dxn(s){var t=Ixn(s),n=t%1;return t===t?n?t-n:t:0}var Rxn=Dxn,Oxn=HDt,Fxn=O5,zxn=Rxn,Bxn=Math.max;function $xn(s,t,n){var r=s==null?0:s.length;if(!r)return-1;var a=n==null?0:zxn(n);return a<0&&(a=Bxn(r+a,0)),Oxn(s,Fxn(t),a)}var Uxn=$xn,qxn=Pxn,Vxn=Uxn,Hxn=qxn(Vxn),Gxn=Hxn;const Wxn=Uc(Gxn);var Kxn=QWs(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("")}),QKe=j.createContext(void 0),JKe=j.createContext(void 0),QOt=j.createContext(void 0),JOt=j.createContext({}),eFt=j.createContext(void 0),tFt=j.createContext(0),sFt=j.createContext(0),cft=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=Kxn(i);return It.createElement(QKe.Provider,{value:r},It.createElement(JKe.Provider,{value:a},It.createElement(JOt.Provider,{value:i},It.createElement(QOt.Provider,{value:u},It.createElement(eFt.Provider,{value:l},It.createElement(tFt.Provider,{value:d},It.createElement(sFt.Provider,{value:c},o)))))))},Yxn=function(){return j.useContext(eFt)},nFt=function(t){var n=j.useContext(QKe);n==null&&SO();var r=n[t];return r==null&&SO(),r},Zxn=function(){var t=j.useContext(QKe);return nE(t)},Xxn=function(){var t=j.useContext(JKe),n=Wxn(t,function(r){return HOt(r.domain,Number.isFinite)});return n||nE(t)},rFt=function(t){var n=j.useContext(JKe);n==null&&SO();var r=n[t];return r==null&&SO(),r},Qxn=function(){var t=j.useContext(QOt);return t},Jxn=function(){return j.useContext(JOt)},eYe=function(){return j.useContext(sFt)},tYe=function(){return j.useContext(tFt)};function MU(s){"@babel/helpers - typeof";return MU=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},MU(s)}function egn(s,t){if(!(s instanceof t))throw new TypeError("Cannot call a class as a function")}function tgn(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 Rgn(s,t){return uFt(s,t+1)}function Ogn(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 x=r==null?void 0:r[c];if(x===void 0)return{v:uFt(r,d)};var g=c,y,b=function(){return y===void 0&&(y=n(x,g)),y},v=x.coordinate,N=c===0||s4e(s,v,b,u,o);N||(c=0,u=l,d+=1),N&&(u=v+s*(b()/2+a),c+=d)},m;d<=i.length;)if(m=h(),m)return m.v;return[]}function KX(s){"@babel/helpers - typeof";return KX=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},KX(s)}function gft(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 tv(s){for(var t=1;t0?p.coordinate-y*s:p.coordinate})}else i[m]=p=tv(tv({},p),{},{tickCoord:p.coordinate});var b=s4e(s,p.tickCoord,g,o,c);b&&(c=p.tickCoord-s*(g()/2+a),i[m]=tv(tv({},p),{},{isShow:!0}))},u=l-1;u>=0;u--)d(u);return i}function Ugn(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=tv(tv({},u),{},{tickCoord:m>0?u.coordinate-m*s:u.coordinate});var p=s4e(s,u.tickCoord,function(){return h},c,d);p&&(d=u.tickCoord-s*(h/2+a),l[o-1]=tv(tv({},u),{},{isShow:!0}))}for(var x=i?o-1:o,g=function(v){var N=l[v],C,A=function(){return C===void 0&&(C=n(N,v)),C};if(v===0){var T=s*(N.coordinate-s*A()/2-c);l[v]=N=tv(tv({},N),{},{tickCoord:T<0?N.coordinate-T*s:N.coordinate})}else l[v]=N=tv(tv({},N),{},{tickCoord:N.coordinate});var P=s4e(s,N.tickCoord,A,c,d);P&&(c=N.tickCoord+s*(A()/2+a),l[v]=tv(tv({},N),{},{isShow:!0}))},y=0;y=2?c1(a[1].coordinate-a[0].coordinate):1,b=Dgn(i,y,p);return c==="equidistantPreserveStart"?Ogn(y,b,g,a,l):(c==="preserveStart"||c==="preserveStartEnd"?m=Ugn(y,b,g,a,l,c==="preserveStartEnd"):m=$gn(y,b,g,a,l),m.filter(function(v){return v.isShow}))}var qgn=["viewBox"],Vgn=["viewBox"],Hgn=["ticks"];function IU(s){"@babel/helpers - typeof";return IU=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},IU(s)}function J9(){return J9=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 Ggn(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 Wgn(s,t){if(!(s instanceof t))throw new TypeError("Cannot call a class as a function")}function vft(s,t){for(var n=0;n0?c(this.props):c(p)),l<=0||o<=0||!x||!x.length?null:It.createElement(Yc,{className:$l("recharts-cartesian-axis",d),ref:function(y){r.layerReference=y}},i&&this.renderAxisLine(),this.renderTicks(x,this.state.fontSize,this.state.letterSpacing),f0.renderCallByParent(this.props))}}],[{key:"renderTickItem",value:function(r,a,i){var l,o=$l(a.className,"recharts-cartesian-axis-tick-value");return It.isValidElement(r)?l=It.cloneElement(r,Qx(Qx({},a),{},{className:o})):dl(r)?l=r(Qx(Qx({},a),{},{className:o})):l=It.createElement(jO,J9({},a,{className:"recharts-cartesian-axis-tick-value"}),i),l}}])}(j.Component);aYe(aV,"displayName","CartesianAxis");aYe(aV,"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 e0n=["x1","y1","x2","y2","key"],t0n=["offset"];function CO(s){"@babel/helpers - typeof";return CO=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},CO(s)}function bft(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 rv(s){for(var t=1;t=0)&&Object.prototype.propertyIsEnumerable.call(s,r)&&(n[r]=s[r])}return n}function a0n(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 i0n=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 It.createElement("rect",{x:a,y:i,ry:c,width:l,height:o,stroke:"none",fill:n,fillOpacity:r,className:"recharts-cartesian-grid-bg"})};function pFt(s,t){var n;if(It.isValidElement(s))n=It.cloneElement(s,t);else if(dl(s))n=s(t);else{var r=t.x1,a=t.y1,i=t.x2,l=t.y2,o=t.key,c=_ft(t,e0n),d=So(c,!1);d.offset;var u=_ft(d,t0n);n=It.createElement("line",U8({},u,{x1:r,y1:a,x2:i,y2:l,fill:"none",key:o}))}return n}function o0n(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=rv(rv({},s),{},{x1:t,y1:o,x2:t+n,y2:o,key:"line-".concat(c),index:c});return pFt(a,d)});return It.createElement("g",{className:"recharts-cartesian-grid-horizontal"},l)}function l0n(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=rv(rv({},s),{},{x1:o,y1:t,x2:o,y2:t+n,key:"line-".concat(c),index:c});return pFt(a,d)});return It.createElement("g",{className:"recharts-cartesian-grid-vertical"},l)}function c0n(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 x=!u[p+1],g=x?a+l-m:u[p+1]-m;if(g<=0)return null;var y=p%t.length;return It.createElement("rect",{key:"react-".concat(p),y:m,x:r,height:g,width:i,stroke:"none",fill:t[y],fillOpacity:n,className:"recharts-cartesian-grid-bg"})});return It.createElement("g",{className:"recharts-cartesian-gridstripes-horizontal"},h)}function d0n(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 x=!u[p+1],g=x?i+o-m:u[p+1]-m;if(g<=0)return null;var y=p%r.length;return It.createElement("rect",{key:"react-".concat(p),x:m,y:l,width:g,height:c,stroke:"none",fill:r[y],fillOpacity:a,className:"recharts-cartesian-grid-bg"})});return It.createElement("g",{className:"recharts-cartesian-gridstripes-vertical"},h)}var u0n=function(t,n){var r=t.xAxis,a=t.width,i=t.height,l=t.offset;return dOt(rYe(rv(rv(rv({},aV.defaultProps),r),{},{ticks:F3(r,!0),viewBox:{x:0,y:0,width:a,height:i}})),l.left,l.left+l.width,n)},h0n=function(t,n){var r=t.yAxis,a=t.width,i=t.height,l=t.offset;return dOt(rYe(rv(rv(rv({},aV.defaultProps),r),{},{ticks:F3(r,!0),viewBox:{x:0,y:0,width:a,height:i}})),l.top,l.top+l.height,n)},I7={horizontal:!0,vertical:!0,horizontalPoints:[],verticalPoints:[],stroke:"#ccc",fill:"none",verticalFill:[],horizontalFill:[]};function AO(s){var t,n,r,a,i,l,o=eYe(),c=tYe(),d=Jxn(),u=rv(rv({},s),{},{stroke:(t=s.stroke)!==null&&t!==void 0?t:I7.stroke,fill:(n=s.fill)!==null&&n!==void 0?n:I7.fill,horizontal:(r=s.horizontal)!==null&&r!==void 0?r:I7.horizontal,horizontalFill:(a=s.horizontalFill)!==null&&a!==void 0?a:I7.horizontalFill,vertical:(i=s.vertical)!==null&&i!==void 0?i:I7.vertical,verticalFill:(l=s.verticalFill)!==null&&l!==void 0?l:I7.verticalFill,x:za(s.x)?s.x:d.left,y:za(s.y)?s.y:d.top,width:za(s.width)?s.width:d.width,height:za(s.height)?s.height:d.height}),h=u.x,m=u.y,p=u.width,x=u.height,g=u.syncWithTicks,y=u.horizontalValues,b=u.verticalValues,v=Zxn(),N=Xxn();if(!za(p)||p<=0||!za(x)||x<=0||!za(h)||h!==+h||!za(m)||m!==+m)return null;var C=u.verticalCoordinatesGenerator||u0n,A=u.horizontalCoordinatesGenerator||h0n,T=u.horizontalPoints,P=u.verticalPoints;if((!T||!T.length)&&dl(A)){var M=y&&y.length,I=A({yAxis:N?rv(rv({},N),{},{ticks:M?y:N.ticks}):void 0,width:o,height:c,offset:d},M?!0:g);BN(Array.isArray(I),"horizontalCoordinatesGenerator should return Array but instead it returned [".concat(CO(I),"]")),Array.isArray(I)&&(T=I)}if((!P||!P.length)&&dl(C)){var D=b&&b.length,B=C({xAxis:v?rv(rv({},v),{},{ticks:D?b:v.ticks}):void 0,width:o,height:c,offset:d},D?!0:g);BN(Array.isArray(B),"verticalCoordinatesGenerator should return Array but instead it returned [".concat(CO(B),"]")),Array.isArray(B)&&(P=B)}return It.createElement("g",{className:"recharts-cartesian-grid"},It.createElement(i0n,{fill:u.fill,fillOpacity:u.fillOpacity,x:u.x,y:u.y,width:u.width,height:u.height,ry:u.ry}),It.createElement(o0n,U8({},u,{offset:d,horizontalPoints:T,xAxis:v,yAxis:N})),It.createElement(l0n,U8({},u,{offset:d,verticalPoints:P,xAxis:v,yAxis:N})),It.createElement(c0n,U8({},u,{horizontalPoints:T})),It.createElement(d0n,U8({},u,{verticalPoints:P})))}AO.displayName="CartesianGrid";var m0n=["type","layout","connectNulls","ref"],p0n=["key"];function DU(s){"@babel/helpers - typeof";return DU=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},DU(s)}function wft(s,t){if(s==null)return{};var n=f0n(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 f0n(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 GY(){return GY=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(D7(c.slice(0,x)),[h-g]);break}var y=p.length%2===0?[0,m]:[m];return[].concat(D7(t.repeat(c,u)),D7(p),y).map(function(b){return"".concat(b,"px")}).join(", ")}),yN(n,"id",oF("recharts-line-")),yN(n,"pathRef",function(l){n.mainCurve=l}),yN(n,"handleAnimationEnd",function(){n.setState({isAnimationFinished:!0}),n.props.onAnimationEnd&&n.props.onAnimationEnd()}),yN(n,"handleAnimationStart",function(){n.setState({isAnimationFinished:!1}),n.props.onAnimationStart&&n.props.onAnimationStart()}),n}return k0n(t,s),_0n(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=lw(u,Gee);if(!h)return null;var m=function(g,y){return{x:g.x,y:g.y,value:g.value,errorVal:ex(g.payload,y)}},p={clipPath:r?"url(#clipPath-".concat(a,")"):null};return It.createElement(Yc,p,h.map(function(x){return It.cloneElement(x,{key:"bar-".concat(x.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=So(this.props,!1),m=So(c,!0),p=d.map(function(g,y){var b=b_(b_(b_({key:"dot-".concat(y),r:3},h),m),{},{index:y,cx:g.x,cy:g.y,value:g.value,dataKey:u,payload:g.payload,points:d});return t.renderDotItem(c,b)}),x={clipPath:r?"url(#clipPath-".concat(a?"":"dots-").concat(i,")"):null};return It.createElement(Yc,GY({className:"recharts-line-dots",key:"dots"},x),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=wft(o,m0n),m=b_(b_(b_({},So(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 It.createElement($R,GY({},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,x=l.animateNewValues,g=l.width,y=l.height,b=this.state,v=b.prevPoints,N=b.totalLength;return It.createElement(YN,{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(C){var A=C.t;if(v){var T=v.length/o.length,P=o.map(function(q,W){var V=Math.floor(W*T);if(v[V]){var K=v[V],Q=mg(K.x,q.x),J=mg(K.y,q.y);return b_(b_({},q),{},{x:Q(A),y:J(A)})}if(x){var ce=mg(g*2,q.x),ue=mg(y/2,q.y);return b_(b_({},q),{},{x:ce(A),y:ue(A)})}return b_(b_({},q),{},{x:q.x,y:q.y})});return i.renderCurveStatically(P,r,a)}var M=mg(0,N),I=M(A),D;if(c){var B="".concat(c).split(/[,\s]+/gim).map(function(q){return parseFloat(q)});D=i.getStrokeDasharray(I,N,B)}else D=i.generateSimpleStrokeDasharray(N,I);return i.renderCurveStatically(o,r,a,{strokeDasharray:D})})}},{key:"renderCurve",value:function(r,a){var i=this.props,l=i.points,o=i.isAnimationActive,c=this.state,d=c.prevPoints,u=c.totalLength;return o&&l&&l.length&&(!d&&u>0||!NO(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,x=a.height,g=a.isAnimationActive,y=a.id;if(i||!o||!o.length)return null;var b=this.state.isAnimationFinished,v=o.length===1,N=$l("recharts-line",c),C=d&&d.allowDataOverflow,A=u&&u.allowDataOverflow,T=C||A,P=Pl(y)?this.id:y,M=(r=So(l,!1))!==null&&r!==void 0?r:{r:3,strokeWidth:2},I=M.r,D=I===void 0?3:I,B=M.strokeWidth,q=B===void 0?2:B,W=sDt(l)?l:{},V=W.clipDot,K=V===void 0?!0:V,Q=D*2+q;return It.createElement(Yc,{className:N},C||A?It.createElement("defs",null,It.createElement("clipPath",{id:"clipPath-".concat(P)},It.createElement("rect",{x:C?m:m-p/2,y:A?h:h-x/2,width:C?p:p*2,height:A?x:x*2})),!K&&It.createElement("clipPath",{id:"clipPath-dots-".concat(P)},It.createElement("rect",{x:m-Q/2,y:h-Q/2,width:p+Q,height:x+Q}))):null,!v&&this.renderCurve(T,P),this.renderErrorBar(T,P),(v||l)&&this.renderDots(T,K,P),(!g||b)&&m5.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(D7(r),[0]):r,l=[],o=0;o=0)&&Object.prototype.propertyIsEnumerable.call(s,r)&&(n[r]=s[r])}return n}function E0n(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 q8(){return q8=Object.assign?Object.assign.bind():function(s){for(var t=1;t0||!NO(u,l)||!NO(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,x=a.height,g=a.isAnimationActive,y=a.id;if(i||!o||!o.length)return null;var b=this.state.isAnimationFinished,v=o.length===1,N=$l("recharts-area",c),C=h&&h.allowDataOverflow,A=m&&m.allowDataOverflow,T=C||A,P=Pl(y)?this.id:y,M=(r=So(l,!1))!==null&&r!==void 0?r:{r:3,strokeWidth:2},I=M.r,D=I===void 0?3:I,B=M.strokeWidth,q=B===void 0?2:B,W=sDt(l)?l:{},V=W.clipDot,K=V===void 0?!0:V,Q=D*2+q;return It.createElement(Yc,{className:N},C||A?It.createElement("defs",null,It.createElement("clipPath",{id:"clipPath-".concat(P)},It.createElement("rect",{x:C?u:u-p/2,y:A?d:d-x/2,width:C?p:p*2,height:A?x:x*2})),!K&&It.createElement("clipPath",{id:"clipPath-dots-".concat(P)},It.createElement("rect",{x:u-Q/2,y:d-Q/2,width:p+Q,height:x+Q}))):null,v?null:this.renderArea(T,P),(l||v)&&this.renderDots(T,K,P),(!g||b)&&m5.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);gFt=Fb;VS(Fb,"displayName","Area");VS(Fb,"defaultProps",{stroke:"#3182bd",fill:"#3182bd",fillOpacity:.6,xAxisId:0,yAxisId:0,legendType:"line",connectNulls:!1,points:[],dot:!1,activeDot:!0,hide:!1,isAnimationActive:!$N.isSsr,animationBegin:0,animationDuration:1500,animationEasing:"ease"});VS(Fb,"getBaseValue",function(s,t,n,r){var a=s.layout,i=s.baseValue,l=t.props.baseValue,o=l??i;if(za(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]});VS(Fb,"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,x=d&&d.length,g=gFt.getBaseValue(t,n,r,a),y=p==="horizontal",b=!1,v=h.map(function(C,A){var T;x?T=d[u+A]:(T=ex(C,c),Array.isArray(T)?b=!0:T=[g,T]);var P=T[1]==null||x&&ex(C,c)==null;return y?{x:D5e({axis:r,ticks:i,bandSize:o,entry:C,index:A}),y:P?null:a.scale(T[1]),value:T,payload:C}:{x:P?null:r.scale(T[1]),y:D5e({axis:a,ticks:l,bandSize:o,entry:C,index:A}),value:T,payload:C}}),N;return x||b?N=v.map(function(C){var A=Array.isArray(C.value)?C.value[0]:null;return y?{x:C.x,y:A!=null&&C.y!=null?a.scale(A):null}:{x:A!=null?r.scale(A):null,y:C.y}}):N=y?a.scale(g):r.scale(g),TA({points:v,baseLine:N,layout:p,isRange:b},m)});VS(Fb,"renderDotItem",function(s,t){var n;if(It.isValidElement(s))n=It.cloneElement(s,t);else if(dl(s))n=s(t);else{var r=$l("recharts-area-dot",typeof s!="boolean"?s.className:""),a=t.key,i=yFt(t,A0n);n=It.createElement(Wee,q8({},i,{key:a,className:r}))}return n});function OU(s){"@babel/helpers - typeof";return OU=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},OU(s)}function O0n(s,t){if(!(s instanceof t))throw new TypeError("Cannot call a class as a function")}function F0n(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 Nyn(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 kyn(s,t){if(!(s instanceof t))throw new TypeError("Cannot call a class as a function")}function Syn(s,t){for(var n=0;ns.length)&&(t=s.length);for(var n=0,r=new Array(t);n0?l:t&&t.length&&za(a)&&za(i)?t.slice(a,i+1):[]};function IFt(s){return s==="number"?[0,"auto"]:void 0}var Gze=function(t,n,r,a){var i=t.graphicalItems,l=t.tooltipAxis,o=IEe(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=o5e(p,l.dataKey,a)}else m=h&&h[r]||o[r];return m?[].concat(BU(c),[fOt(d,m)]):c},[])},Lft=function(t,n,r,a){var i=a||{x:t.chartX,y:t.chartY},l=Fyn(i,r),o=t.orderedTooltipTicks,c=t.tooltipAxis,d=t.tooltipTicks,u=idn(l,o,d,c);if(u>=0&&d){var h=d[u]&&d[u].value,m=Gze(t,n,u,h),p=zyn(r,o,u,i);return{activeTooltipIndex:u,activeLabel:h,activePayload:m,activeCoordinate:p}}return null},Byn=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=cOt(u,i);return r.reduce(function(x,g){var y,b=g.type.defaultProps!==void 0?Qr(Qr({},g.type.defaultProps),g.props):g.props,v=b.type,N=b.dataKey,C=b.allowDataOverflow,A=b.allowDuplicatedCategory,T=b.scale,P=b.ticks,M=b.includeHidden,I=b[l];if(x[I])return x;var D=IEe(t.data,{graphicalItems:a.filter(function(le){var he,ve=l in le.props?le.props[l]:(he=le.type.defaultProps)===null||he===void 0?void 0:he[l];return ve===I}),dataStartIndex:c,dataEndIndex:d}),B=D.length,q,W,V;hyn(b.domain,C,v)&&(q=aze(b.domain,null,C),p&&(v==="number"||T!=="auto")&&(V=UY(D,N,"category")));var K=IFt(v);if(!q||q.length===0){var Q,J=(Q=b.domain)!==null&&Q!==void 0?Q:K;if(N){if(q=UY(D,N,v),v==="category"&&p){var ce=ZKs(q);A&&ce?(W=q,q=K5e(0,B)):A||(q=Qmt(J,q,g).reduce(function(le,he){return le.indexOf(he)>=0?le:[].concat(BU(le),[he])},[]))}else if(v==="category")A?q=q.filter(function(le){return le!==""&&!Pl(le)}):q=Qmt(J,q,g).reduce(function(le,he){return le.indexOf(he)>=0||he===""||Pl(he)?le:[].concat(BU(le),[he])},[]);else if(v==="number"){var ue=udn(D,a.filter(function(le){var he,ve,ge=l in le.props?le.props[l]:(he=le.type.defaultProps)===null||he===void 0?void 0:he[l],fe="hide"in le.props?le.props.hide:(ve=le.type.defaultProps)===null||ve===void 0?void 0:ve.hide;return ge===I&&(M||!fe)}),N,i,u);ue&&(q=ue)}p&&(v==="number"||T!=="auto")&&(V=UY(D,N,"category"))}else p?q=K5e(0,B):o&&o[I]&&o[I].hasStack&&v==="number"?q=m==="expand"?[0,1]:pOt(o[I].stackGroups,c,d):q=lOt(D,a.filter(function(le){var he=l in le.props?le.props[l]:le.type.defaultProps[l],ve="hide"in le.props?le.props.hide:le.type.defaultProps.hide;return he===I&&(M||!ve)}),v,u,!0);if(v==="number")q=qze(h,q,I,i,P),J&&(q=aze(J,q,C));else if(v==="category"&&J){var ne=J,ee=q.every(function(le){return ne.indexOf(le)>=0});ee&&(q=ne)}}return Qr(Qr({},x),{},cl({},I,Qr(Qr({},b),{},{axisType:i,domain:q,categoricalDomain:V,duplicateDomain:W,originalDomain:(y=b.domain)!==null&&y!==void 0?y:K,isCategorical:p,layout:u})))},{})},$yn=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=IEe(t.data,{graphicalItems:r,dataStartIndex:c,dataEndIndex:d}),p=m.length,x=cOt(u,i),g=-1;return r.reduce(function(y,b){var v=b.type.defaultProps!==void 0?Qr(Qr({},b.type.defaultProps),b.props):b.props,N=v[l],C=IFt("number");if(!y[N]){g++;var A;return x?A=K5e(0,p):o&&o[N]&&o[N].hasStack?(A=pOt(o[N].stackGroups,c,d),A=qze(h,A,N,i)):(A=aze(C,lOt(m,r.filter(function(T){var P,M,I=l in T.props?T.props[l]:(P=T.type.defaultProps)===null||P===void 0?void 0:P[l],D="hide"in T.props?T.props.hide:(M=T.type.defaultProps)===null||M===void 0?void 0:M.hide;return I===N&&!D}),"number",u),a.defaultProps.allowDataOverflow),A=qze(h,A,N,i)),Qr(Qr({},y),{},cl({},N,Qr(Qr({axisType:i},a.defaultProps),{},{hide:!0,orientation:ow(Ryn,"".concat(i,".").concat(g%2),null),domain:A,originalDomain:C,isCategorical:x,layout:u})))}return y},{})},Uyn=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=lw(u,i),p={};return m&&m.length?p=Byn(t,{axes:m,graphicalItems:l,axisType:a,axisIdKey:h,stackGroups:o,dataStartIndex:c,dataEndIndex:d}):l&&l.length&&(p=$yn(t,{Axis:i,graphicalItems:l,axisType:a,axisIdKey:h,stackGroups:o,dataStartIndex:c,dataEndIndex:d})),p},qyn=function(t){var n=nE(t),r=F3(n,!1,!0);return{tooltipTicks:r,orderedTooltipTicks:wKe(r,function(a){return a.coordinate}),tooltipAxis:n,tooltipAxisBandSize:R5e(n,r)}},Pft=function(t){var n=t.children,r=t.defaultShowTooltip,a=B_(n,EU),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}},Vyn=function(t){return!t||!t.length?!1:t.some(function(n){var r=Z3(n&&n.type);return r&&r.indexOf("Bar")>=0})},Ift=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"}},Hyn=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=B_(h,EU),x=B_(h,FR),g=Object.keys(c).reduce(function(A,T){var P=c[T],M=P.orientation;return!P.mirror&&!P.hide?Qr(Qr({},A),{},cl({},M,A[M]+P.width)):A},{left:m.left||0,right:m.right||0}),y=Object.keys(l).reduce(function(A,T){var P=l[T],M=P.orientation;return!P.mirror&&!P.hide?Qr(Qr({},A),{},cl({},M,ow(A,"".concat(M))+P.height)):A},{top:m.top||0,bottom:m.bottom||0}),b=Qr(Qr({},y),g),v=b.bottom;p&&(b.bottom+=p.props.height||EU.defaultProps.height),x&&n&&(b=cdn(b,a,r,n));var N=d-b.left-b.right,C=u-b.top-b.bottom;return Qr(Qr({brushBottom:v},b),{},{width:Math.max(N,0),height:Math.max(C,0)})},Gyn=function(t,n){if(n==="xAxis")return t[n].width;if(n==="yAxis")return t[n].height},DEe=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(b,v){var N=v.graphicalItems,C=v.stackGroups,A=v.offset,T=v.updateId,P=v.dataStartIndex,M=v.dataEndIndex,I=b.barSize,D=b.layout,B=b.barGap,q=b.barCategoryGap,W=b.maxBarSize,V=Ift(D),K=V.numericAxisName,Q=V.cateAxisName,J=Vyn(N),ce=[];return N.forEach(function(ue,ne){var ee=IEe(b.data,{graphicalItems:[ue],dataStartIndex:P,dataEndIndex:M}),le=ue.type.defaultProps!==void 0?Qr(Qr({},ue.type.defaultProps),ue.props):ue.props,he=le.dataKey,ve=le.maxBarSize,ge=le["".concat(K,"Id")],fe=le["".concat(Q,"Id")],je={},Ee=c.reduce(function(Ue,et){var Qe=v["".concat(et.axisType,"Map")],Ge=le["".concat(et.axisType,"Id")];Qe&&Qe[Ge]||et.axisType==="zAxis"||SO();var nt=Qe[Ge];return Qr(Qr({},Ue),{},cl(cl({},et.axisType,nt),"".concat(et.axisType,"Ticks"),F3(nt)))},je),Me=Ee[Q],De=Ee["".concat(Q,"Ticks")],ze=C&&C[ge]&&C[ge].hasStack&&bdn(ue,C[ge].stackGroups),ke=Z3(ue.type).indexOf("Bar")>=0,Xe=R5e(Me,De),Se=[],Re=J&&odn({barSize:I,stackGroups:C,totalSize:Gyn(Ee,Q)});if(ke){var Ae,Be,qe=Pl(ve)?W:ve,Ke=(Ae=(Be=R5e(Me,De,!0))!==null&&Be!==void 0?Be:qe)!==null&&Ae!==void 0?Ae:0;Se=ldn({barGap:B,barCategoryGap:q,bandSize:Ke!==Xe?Ke:Xe,sizeList:Re[fe],maxBarSize:qe}),Ke!==Xe&&(Se=Se.map(function(Ue){return Qr(Qr({},Ue),{},{position:Qr(Qr({},Ue.position),{},{offset:Ue.position.offset-Ke/2})})}))}var Ze=ue&&ue.type&&ue.type.getComposedData;Ze&&ce.push({props:Qr(Qr({},Ze(Qr(Qr({},Ee),{},{displayedData:ee,props:b,dataKey:he,item:ue,bandSize:Xe,barPosition:Se,offset:A,stackedData:ze,layout:D,dataStartIndex:P,dataEndIndex:M}))),{},cl(cl(cl({key:ue.key||"item-".concat(ne)},K,Ee[K]),Q,Ee[Q]),"animationId",T)),childIndex:lYs(ue,b.children),item:ue})}),ce},p=function(b,v){var N=b.props,C=b.dataStartIndex,A=b.dataEndIndex,T=b.updateId;if(!Gut({props:N}))return null;var P=N.children,M=N.layout,I=N.stackOffset,D=N.data,B=N.reverseStackOrder,q=Ift(M),W=q.numericAxisName,V=q.cateAxisName,K=lw(P,r),Q=ydn(D,K,"".concat(W,"Id"),"".concat(V,"Id"),I,B),J=c.reduce(function(le,he){var ve="".concat(he.axisType,"Map");return Qr(Qr({},le),{},cl({},ve,Uyn(N,Qr(Qr({},he),{},{graphicalItems:K,stackGroups:he.axisType===W&&Q,dataStartIndex:C,dataEndIndex:A}))))},{}),ce=Hyn(Qr(Qr({},J),{},{props:N,graphicalItems:K}),v==null?void 0:v.legendBBox);Object.keys(J).forEach(function(le){J[le]=u(N,J[le],ce,le.replace("Map",""),n)});var ue=J["".concat(V,"Map")],ne=qyn(ue),ee=m(N,Qr(Qr({},J),{},{dataStartIndex:C,dataEndIndex:A,updateId:T,graphicalItems:K,stackGroups:Q,offset:ce}));return Qr(Qr({formattedGraphicalItems:ee,graphicalItems:K,offset:ce,stackGroups:Q},ne),J)},x=function(y){function b(v){var N,C,A;return kyn(this,b),A=Ayn(this,b,[v]),cl(A,"eventEmitterSymbol",Symbol("rechartsEventEmitter")),cl(A,"accessibilityManager",new uyn),cl(A,"handleLegendBBoxUpdate",function(T){if(T){var P=A.state,M=P.dataStartIndex,I=P.dataEndIndex,D=P.updateId;A.setState(Qr({legendBBox:T},p({props:A.props,dataStartIndex:M,dataEndIndex:I,updateId:D},Qr(Qr({},A.state),{},{legendBBox:T}))))}}),cl(A,"handleReceiveSyncEvent",function(T,P,M){if(A.props.syncId===T){if(M===A.eventEmitterSymbol&&typeof A.props.syncMethod!="function")return;A.applySyncEvent(P)}}),cl(A,"handleBrushChange",function(T){var P=T.startIndex,M=T.endIndex;if(P!==A.state.dataStartIndex||M!==A.state.dataEndIndex){var I=A.state.updateId;A.setState(function(){return Qr({dataStartIndex:P,dataEndIndex:M},p({props:A.props,dataStartIndex:P,dataEndIndex:M,updateId:I},A.state))}),A.triggerSyncEvent({dataStartIndex:P,dataEndIndex:M})}}),cl(A,"handleMouseEnter",function(T){var P=A.getMouseInfo(T);if(P){var M=Qr(Qr({},P),{},{isTooltipActive:!0});A.setState(M),A.triggerSyncEvent(M);var I=A.props.onMouseEnter;dl(I)&&I(M,T)}}),cl(A,"triggeredAfterMouseMove",function(T){var P=A.getMouseInfo(T),M=P?Qr(Qr({},P),{},{isTooltipActive:!0}):{isTooltipActive:!1};A.setState(M),A.triggerSyncEvent(M);var I=A.props.onMouseMove;dl(I)&&I(M,T)}),cl(A,"handleItemMouseEnter",function(T){A.setState(function(){return{isTooltipActive:!0,activeItem:T,activePayload:T.tooltipPayload,activeCoordinate:T.tooltipPosition||{x:T.cx,y:T.cy}}})}),cl(A,"handleItemMouseLeave",function(){A.setState(function(){return{isTooltipActive:!1}})}),cl(A,"handleMouseMove",function(T){T.persist(),A.throttleTriggeredAfterMouseMove(T)}),cl(A,"handleMouseLeave",function(T){A.throttleTriggeredAfterMouseMove.cancel();var P={isTooltipActive:!1};A.setState(P),A.triggerSyncEvent(P);var M=A.props.onMouseLeave;dl(M)&&M(P,T)}),cl(A,"handleOuterEvent",function(T){var P=oYs(T),M=ow(A.props,"".concat(P));if(P&&dl(M)){var I,D;/.*touch.*/i.test(P)?D=A.getMouseInfo(T.changedTouches[0]):D=A.getMouseInfo(T),M((I=D)!==null&&I!==void 0?I:{},T)}}),cl(A,"handleClick",function(T){var P=A.getMouseInfo(T);if(P){var M=Qr(Qr({},P),{},{isTooltipActive:!0});A.setState(M),A.triggerSyncEvent(M);var I=A.props.onClick;dl(I)&&I(M,T)}}),cl(A,"handleMouseDown",function(T){var P=A.props.onMouseDown;if(dl(P)){var M=A.getMouseInfo(T);P(M,T)}}),cl(A,"handleMouseUp",function(T){var P=A.props.onMouseUp;if(dl(P)){var M=A.getMouseInfo(T);P(M,T)}}),cl(A,"handleTouchMove",function(T){T.changedTouches!=null&&T.changedTouches.length>0&&A.throttleTriggeredAfterMouseMove(T.changedTouches[0])}),cl(A,"handleTouchStart",function(T){T.changedTouches!=null&&T.changedTouches.length>0&&A.handleMouseDown(T.changedTouches[0])}),cl(A,"handleTouchEnd",function(T){T.changedTouches!=null&&T.changedTouches.length>0&&A.handleMouseUp(T.changedTouches[0])}),cl(A,"handleDoubleClick",function(T){var P=A.props.onDoubleClick;if(dl(P)){var M=A.getMouseInfo(T);P(M,T)}}),cl(A,"handleContextMenu",function(T){var P=A.props.onContextMenu;if(dl(P)){var M=A.getMouseInfo(T);P(M,T)}}),cl(A,"triggerSyncEvent",function(T){A.props.syncId!==void 0&&t8e.emit(s8e,A.props.syncId,T,A.eventEmitterSymbol)}),cl(A,"applySyncEvent",function(T){var P=A.props,M=P.layout,I=P.syncMethod,D=A.state.updateId,B=T.dataStartIndex,q=T.dataEndIndex;if(T.dataStartIndex!==void 0||T.dataEndIndex!==void 0)A.setState(Qr({dataStartIndex:B,dataEndIndex:q},p({props:A.props,dataStartIndex:B,dataEndIndex:q,updateId:D},A.state)));else if(T.activeTooltipIndex!==void 0){var W=T.chartX,V=T.chartY,K=T.activeTooltipIndex,Q=A.state,J=Q.offset,ce=Q.tooltipTicks;if(!J)return;if(typeof I=="function")K=I(ce,T);else if(I==="value"){K=-1;for(var ue=0;ue=0){var ze,ke;if(W.dataKey&&!W.allowDuplicatedCategory){var Xe=typeof W.dataKey=="function"?De:"payload.".concat(W.dataKey.toString());ze=o5e(ue,Xe,K),ke=ne&&ee&&o5e(ee,Xe,K)}else ze=ue==null?void 0:ue[V],ke=ne&&ee&&ee[V];if(fe||ge){var Se=T.props.activeIndex!==void 0?T.props.activeIndex:V;return[j.cloneElement(T,Qr(Qr(Qr({},I.props),Ee),{},{activeIndex:Se})),null,null]}if(!Pl(ze))return[Me].concat(BU(A.renderActivePoints({item:I,activePoint:ze,basePoint:ke,childIndex:V,isRange:ne})))}else{var Re,Ae=(Re=A.getItemByXY(A.state.activeCoordinate))!==null&&Re!==void 0?Re:{graphicalItem:Me},Be=Ae.graphicalItem,qe=Be.item,Ke=qe===void 0?T:qe,Ze=Be.childIndex,Ue=Qr(Qr(Qr({},I.props),Ee),{},{activeIndex:Ze});return[j.cloneElement(Ke,Ue),null,null]}return ne?[Me,null,null]:[Me,null]}),cl(A,"renderCustomized",function(T,P,M){return j.cloneElement(T,Qr(Qr({key:"recharts-customized-".concat(M)},A.props),A.state))}),cl(A,"renderMap",{CartesianGrid:{handler:Pre,once:!0},ReferenceArea:{handler:A.renderReferenceElement},ReferenceLine:{handler:Pre},ReferenceDot:{handler:A.renderReferenceElement},XAxis:{handler:Pre},YAxis:{handler:Pre},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=v.id)!==null&&N!==void 0?N:oF("recharts"),"-clip"),A.throttleTriggeredAfterMouseMove=aRt(A.triggeredAfterMouseMove,(C=v.throttleDelay)!==null&&C!==void 0?C:1e3/60),A.state={},A}return Myn(b,y),Cyn(b,[{key:"componentDidMount",value:function(){var N,C;this.addListener(),this.accessibilityManager.setDetails({container:this.container,offset:{left:(N=this.props.margin.left)!==null&&N!==void 0?N:0,top:(C=this.props.margin.top)!==null&&C!==void 0?C:0},coordinateList:this.state.tooltipTicks,mouseHandlerCallback:this.triggeredAfterMouseMove,layout:this.props.layout}),this.displayDefaultTooltip()}},{key:"displayDefaultTooltip",value:function(){var N=this.props,C=N.children,A=N.data,T=N.height,P=N.layout,M=B_(C,yf);if(M){var I=M.props.defaultIndex;if(!(typeof I!="number"||I<0||I>this.state.tooltipTicks.length-1)){var D=this.state.tooltipTicks[I]&&this.state.tooltipTicks[I].value,B=Gze(this.state,A,I,D),q=this.state.tooltipTicks[I].coordinate,W=(this.state.offset.top+T)/2,V=P==="horizontal",K=V?{x:q,y:W}:{y:q,x:W},Q=this.state.formattedGraphicalItems.find(function(ce){var ue=ce.item;return ue.type.name==="Scatter"});Q&&(K=Qr(Qr({},K),Q.props.points[I].tooltipPosition),B=Q.props.points[I].tooltipPayload);var J={activeTooltipIndex:I,isTooltipActive:!0,activeLabel:D,activePayload:B,activeCoordinate:K};this.setState(J),this.renderCursor(M),this.accessibilityManager.setIndex(I)}}}},{key:"getSnapshotBeforeUpdate",value:function(N,C){if(!this.props.accessibilityLayer)return null;if(this.state.tooltipTicks!==C.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){b9e([B_(N.children,yf)],[B_(this.props.children,yf)])||this.displayDefaultTooltip()}},{key:"componentWillUnmount",value:function(){this.removeListener(),this.throttleTriggeredAfterMouseMove.cancel()}},{key:"getTooltipEventType",value:function(){var N=B_(this.props.children,yf);if(N&&typeof N.props.shared=="boolean"){var C=N.props.shared?"axis":"item";return o.indexOf(C)>=0?C:i}return i}},{key:"getMouseInfo",value:function(N){if(!this.container)return null;var C=this.container,A=C.getBoundingClientRect(),T=Ian(A),P={chartX:Math.round(N.pageX-T.left),chartY:Math.round(N.pageY-T.top)},M=A.width/C.offsetWidth||1,I=this.inRange(P.chartX,P.chartY,M);if(!I)return null;var D=this.state,B=D.xAxisMap,q=D.yAxisMap,W=this.getTooltipEventType(),V=Lft(this.state,this.props.data,this.props.layout,I);if(W!=="axis"&&B&&q){var K=nE(B).scale,Q=nE(q).scale,J=K&&K.invert?K.invert(P.chartX):null,ce=Q&&Q.invert?Q.invert(P.chartY):null;return Qr(Qr({},P),{},{xValue:J,yValue:ce},V)}return V?Qr(Qr({},P),V):null}},{key:"inRange",value:function(N,C){var A=arguments.length>2&&arguments[2]!==void 0?arguments[2]:1,T=this.props.layout,P=N/A,M=C/A;if(T==="horizontal"||T==="vertical"){var I=this.state.offset,D=P>=I.left&&P<=I.left+I.width&&M>=I.top&&M<=I.top+I.height;return D?{x:P,y:M}:null}var B=this.state,q=B.angleAxisMap,W=B.radiusAxisMap;if(q&&W){var V=nE(q);return tpt({x:P,y:M},V)}return null}},{key:"parseEventsOfWrapper",value:function(){var N=this.props.children,C=this.getTooltipEventType(),A=B_(N,yf),T={};A&&C==="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 P=l5e(this.props,this.handleOuterEvent);return Qr(Qr({},P),T)}},{key:"addListener",value:function(){t8e.on(s8e,this.handleReceiveSyncEvent)}},{key:"removeListener",value:function(){t8e.removeListener(s8e,this.handleReceiveSyncEvent)}},{key:"filterFormatItem",value:function(N,C,A){for(var T=this.state.formattedGraphicalItems,P=0,M=T.length;P{const{data:v,error:N}=await U.from("email_campaigns").select("*").eq("status","sent").order("sent_at",{ascending:!0});if(N)throw N;return v}}),{data:r}=ht({queryKey:["campaign-agent-profiles"],queryFn:async()=>{const{data:v,error:N}=await U.from("profiles").select("id, name, email");if(N)throw N;return v}});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(v=>[v.id,v])),l=a.reduce((v,N)=>v+(N.sent_count||0),0),o=a.reduce((v,N)=>v+(N.open_count||0),0),c=a.reduce((v,N)=>v+(N.click_count||0),0),d=a.reduce((v,N)=>v+(N.bounce_count||0),0),u=a.reduce((v,N)=>v+(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:Br,color:"text-foreground"},{label:"Total Emails Sent",value:l,icon:qn,color:"text-green-600"},{label:"Avg Open Rate",value:`${h}%`,icon:ga,color:"text-blue-600"},{label:"Avg Click Rate",value:`${m}%`,icon:pg,color:"text-purple-600"},{label:"Total Bounces",value:d,icon:mc,color:"text-orange-600"},{label:"Complaints",value:u,icon:Il,color:"text-destructive"}],x=new Map;a.forEach(v=>{var A,T;const N=v.user_id,C=x.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};C.campaigns++,C.sent+=v.sent_count||0,C.opens+=v.open_count||0,C.clicks+=v.click_count||0,x.set(N,C)});const g=[...x.entries()].map(([v,N])=>({id:v,...N,openRate:N.sent>0?+(N.opens/N.sent*100).toFixed(1):0})).sort((v,N)=>N.sent-v.sent),y=g.slice(0,6).map(v=>({name:v.name,value:v.sent})),b=a.map(v=>{var N;return{name:v.name.length>20?v.name.slice(0,20)+"…":v.name,agent:((N=i.get(v.user_id))==null?void 0:N.name)||"Unknown",openRate:v.sent_count>0?+(v.open_count/v.sent_count*100).toFixed(1):0,clickRate:v.sent_count>0?+(v.click_count/v.sent_count*100).toFixed(1):0,sent:v.sent_count,date:v.sent_at?Hs(new Date(v.sent_at),"MMM d"):""}});return e.jsx("div",{className:"space-y-6",children:a.length===0?e.jsx(_e,{children:e.jsxs(Oe,{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(Br,{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(v=>e.jsx(_e,{children:e.jsxs(Oe,{className:"p-4 text-center",children:[e.jsx(v.icon,{className:`h-5 w-5 mx-auto mb-1 ${v.color}`}),e.jsx("p",{className:"text-2xl font-bold",children:v.value}),e.jsx("p",{className:"text-xs text-muted-foreground",children:v.label})]})},v.label))}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs(_e,{children:[e.jsx(Bt,{children:e.jsx(Ut,{className:"text-base",children:"Open & Click Rates by Campaign"})}),e.jsx(Oe,{children:e.jsx("div",{className:"h-[280px]",children:e.jsx(Ob,{width:"100%",height:"100%",children:e.jsxs(REe,{data:b,children:[e.jsx(k1,{dataKey:"date",fontSize:11}),e.jsx(S1,{fontSize:11,unit:"%"}),e.jsx(yf,{formatter:v=>`${v}%`}),e.jsx(i2,{dataKey:"openRate",fill:"hsl(220, 70%, 50%)",name:"Open Rate",radius:[2,2,0,0]}),e.jsx(i2,{dataKey:"clickRate",fill:"hsl(270, 70%, 50%)",name:"Click Rate",radius:[2,2,0,0]})]})})})})]}),e.jsxs(_e,{children:[e.jsx(Bt,{children:e.jsx(Ut,{className:"text-base",children:"Send Volume by Agent"})}),e.jsx(Oe,{children:e.jsx("div",{className:"h-[280px]",children:e.jsx(Ob,{width:"100%",height:"100%",children:e.jsxs(oYe,{children:[e.jsx(ok,{data:y,dataKey:"value",nameKey:"name",cx:"50%",cy:"50%",outerRadius:100,label:({name:v,percent:N})=>`${v} (${(N*100).toFixed(0)}%)`,fontSize:11,children:y.map((v,N)=>e.jsx(eV,{fill:Dft[N%Dft.length]},N))}),e.jsx(yf,{})]})})})})]})]}),e.jsxs(_e,{children:[e.jsx(Bt,{children:e.jsx(Ut,{className:"text-base",children:"Send Volume Trend"})}),e.jsx(Oe,{children:e.jsx("div",{className:"h-[240px]",children:e.jsx(Ob,{width:"100%",height:"100%",children:e.jsxs(iYe,{data:b,children:[e.jsx(k1,{dataKey:"date",fontSize:11}),e.jsx(S1,{fontSize:11}),e.jsx(yf,{}),e.jsx(dF,{type:"monotone",dataKey:"sent",stroke:"hsl(142, 71%, 45%)",strokeWidth:2,name:"Emails Sent",dot:{r:4}})]})})})})]}),e.jsxs(_e,{children:[e.jsx(Bt,{children:e.jsx(Ut,{className:"text-base",children:"Agent Performance"})}),e.jsx(Oe,{children:e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b text-left text-muted-foreground",children:[e.jsx("th",{className:"pb-2 font-medium",children:"Agent"}),e.jsx("th",{className:"pb-2 font-medium text-center",children:"Campaigns"}),e.jsx("th",{className:"pb-2 font-medium text-center",children:"Sent"}),e.jsx("th",{className:"pb-2 font-medium text-center",children:"Opens"}),e.jsx("th",{className:"pb-2 font-medium text-center",children:"Clicks"}),e.jsx("th",{className:"pb-2 font-medium text-center",children:"Open Rate"})]})}),e.jsx("tbody",{children:g.map(v=>e.jsxs("tr",{className:"border-b last:border-0 hover:bg-muted/30",children:[e.jsx("td",{className:"py-2.5 font-medium",children:v.name}),e.jsx("td",{className:"py-2.5 text-center",children:v.campaigns}),e.jsx("td",{className:"py-2.5 text-center",children:v.sent}),e.jsx("td",{className:"py-2.5 text-center",children:v.opens}),e.jsx("td",{className:"py-2.5 text-center",children:v.clicks}),e.jsx("td",{className:"py-2.5 text-center",children:e.jsxs($e,{variant:"outline",children:[v.openRate,"%"]})})]},v.id))})]})})})]}),e.jsxs(_e,{children:[e.jsx(Bt,{children:e.jsx(Ut,{className:"text-base",children:"Campaign Leaderboard"})}),e.jsx(Oe,{children:e.jsx("div",{className:"space-y-2",children:[...a].sort((v,N)=>{const C=v.sent_count>0?v.open_count/v.sent_count:0;return(N.sent_count>0?N.open_count/N.sent_count:0)-C}).slice(0,10).map((v,N)=>{const C=v.sent_count>0?(v.open_count/v.sent_count*100).toFixed(1):"0.0",A=v.sent_count>0?(v.click_count/v.sent_count*100).toFixed(1):"0.0",T=i.get(v.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/${v.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:v.name}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[(T==null?void 0:T.name)||"Unknown"," · ",v.sent_at?Hs(new Date(v.sent_at),"MMM d, yyyy"):""," · ",v.sent_count," sent"]})]}),e.jsxs("div",{className:"flex gap-3 text-xs",children:[e.jsxs($e,{variant:"outline",className:"gap-1",children:[e.jsx(ga,{className:"h-3 w-3"})," ",C,"%"]}),e.jsxs($e,{variant:"outline",className:"gap-1",children:[e.jsx(pg,{className:"h-3 w-3"})," ",A,"%"]})]})]},v.id)})})})]})]})})}const Kyn=()=>{const{toast:s}=gi(),[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 U.from("website_apps").select("slug, name").order("sort_order"),p=[];let x=0;for(;;){const{data:A,error:T}=await U.from("agent_website_app_installs").select("user_id, app_slug, enabled").range(x,x+999);if(T)throw T;if(p.push(...A||[]),!A||A.length<1e3)break;x+=1e3}const g=[];for(x=0;;){const{data:A,error:T}=await U.from("widget_events").select("user_id, app_slug, event_type, created_at").gte("created_at",h).order("created_at",{ascending:!1}).range(x,x+999);if(T)throw T;if(g.push(...A||[]),!A||A.length<1e3||(x+=1e3,x>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 g){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 b=new Map;for(const A of p){if(!A.enabled)continue;const T=b.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),b.set(A.user_id,T)}for(const A of g){const T=b.get(A.user_id);T&&(T.events_30d+=1,A.event_type==="lead_capture"&&(T.leads_30d+=1))}const v=Array.from(b.keys());if(v.length>0){const{data:A}=await U.from("profiles").select("id, name, email").in("id",v);for(const T of A||[]){const P=b.get(T.id);P&&(P.name=T.name,P.email=T.email)}}const N=Array.from(y.values()),C=Array.from(b.values()).sort((A,T)=>T.events_30d-A.events_30d);a(N),l(C),c({installs:N.reduce((A,T)=>A+T.enabled,0),activeAgents:C.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(_e,{children:e.jsx(Oe,{className:"flex items-center justify-center py-8",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})})}):e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"grid gap-4 md:grid-cols-2 lg:grid-cols-4",children:[e.jsxs(_e,{children:[e.jsxs(Bt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Ut,{className:"text-sm font-medium",children:"Active Installs"}),e.jsx(Gl,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Oe,{children:[e.jsx("div",{className:"text-2xl font-bold",children:o.installs}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Apps turned on across all agents"})]})]}),e.jsxs(_e,{children:[e.jsxs(Bt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Ut,{className:"text-sm font-medium",children:"Agents Using Apps"}),e.jsx(qn,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Oe,{children:[e.jsx("div",{className:"text-2xl font-bold",children:o.activeAgents}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"At least one app enabled"})]})]}),e.jsxs(_e,{children:[e.jsxs(Bt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Ut,{className:"text-sm font-medium",children:"Impressions (30d)"}),e.jsx(ga,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Oe,{children:[e.jsx("div",{className:"text-2xl font-bold",children:o.impressions30d}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Widget views on lead sites"})]})]}),e.jsxs(_e,{children:[e.jsxs(Bt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Ut,{className:"text-sm font-medium",children:"Leads Captured (30d)"}),e.jsx(nn,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Oe,{children:[e.jsx("div",{className:"text-2xl font-bold",children:o.leads30d}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Total submissions"})]})]})]}),e.jsxs(_e,{children:[e.jsx(Bt,{children:e.jsx(Ut,{children:"App Performance (last 30 days)"})}),e.jsx(Oe,{children:e.jsxs(Va,{children:[e.jsx(Ha,{children:e.jsxs(hn,{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(Ga,{children:[r.map(u=>{const h=u.impressions>0?(u.lead_captures/u.impressions*100).toFixed(1):"—";return e.jsxs(hn,{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(hn,{children:e.jsx(gt,{colSpan:8,className:"text-center text-muted-foreground py-6",children:"No data yet"})})]})]})})]}),e.jsxs(_e,{children:[e.jsx(Bt,{children:e.jsx(Ut,{children:"Agent Usage (last 30 days)"})}),e.jsxs(Oe,{children:[e.jsxs(Va,{children:[e.jsx(Ha,{children:e.jsxs(hn,{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(Ga,{children:[i.slice(0,100).map(u=>e.jsxs(hn,{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($e,{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(hn,{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."]})]})]})]})},Yyn=()=>{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([U.rpc("get_extension_usage_summary"),U.from("extension_usage_events").select("id, user_id, action, metadata, created_at").order("created_at",{ascending:!1}).limit(50)]),p=h||[],x=m||[];t(p),r(x);const g=Array.from(new Set(x.map(y=>y.user_id)));if(g.length){const{data:y}=await U.from("profiles").select("id, name, email").in("id",g),b={};(y||[]).forEach(v=>{b[v.id]={name:v.name,email:v.email}}),i(b)}}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(_e,{children:e.jsx(Oe,{className:"flex items-center justify-center py-8",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})})});const 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(_e,{children:[e.jsxs(Bt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Ut,{className:"text-sm font-medium",children:"Active Users"}),e.jsx(qn,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Oe,{children:[e.jsx("div",{className:"text-2xl font-bold",children:d.users}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Using extension"})]})]}),e.jsxs(_e,{children:[e.jsxs(Bt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Ut,{className:"text-sm font-medium",children:"Total Actions"}),e.jsx(dR,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Oe,{children:[e.jsx("div",{className:"text-2xl font-bold",children:d.events}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"All events"})]})]}),e.jsxs(_e,{children:[e.jsxs(Bt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Ut,{className:"text-sm font-medium",children:"Contacts Saved"}),e.jsx(il,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsx(Oe,{children:e.jsx("div",{className:"text-2xl font-bold",children:d.contacts})})]}),e.jsxs(_e,{children:[e.jsxs(Bt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Ut,{className:"text-sm font-medium",children:"Listings Imported"}),e.jsx(sa,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsx(Oe,{children:e.jsx("div",{className:"text-2xl font-bold",children:d.listings})})]}),e.jsxs(_e,{children:[e.jsxs(Bt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Ut,{className:"text-sm font-medium",children:"Activities Logged"}),e.jsx(Ji,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsx(Oe,{children:e.jsx("div",{className:"text-2xl font-bold",children:d.activities})})]})]}),e.jsxs(_e,{children:[e.jsx(Bt,{children:e.jsx(Ut,{children:"Users by Extension Activity"})}),e.jsx(Oe,{children:s.length===0?e.jsx("p",{className:"text-sm text-muted-foreground py-8 text-center",children:"No extension usage yet. Once agents install and use the Chrome Extension, their activity will appear here."}):e.jsx("div",{className:"overflow-x-auto",children:e.jsxs(Va,{children:[e.jsx(Ha,{children:e.jsxs(hn,{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(Ga,{children:s.map(h=>e.jsxs(hn,{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?Hs(new Date(h.first_event_at),"MMM d, yyyy"):"—"}),e.jsx(gt,{className:"text-xs text-muted-foreground",children:h.last_event_at?Hs(new Date(h.last_event_at),"MMM d, h:mm a"):"—"})]},h.user_id))})]})})})]}),e.jsxs(_e,{children:[e.jsx(Bt,{children:e.jsx(Ut,{children:"Recent Activity"})}),e.jsx(Oe,{children:n.length===0?e.jsx("p",{className:"text-sm text-muted-foreground py-4 text-center",children:"No recent events."}):e.jsx("div",{className:"space-y-2",children:n.map(h=>{const m=a[h.user_id];return e.jsxs("div",{className:"flex items-center justify-between border-b pb-2 last:border-0",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx($e,{variant:"secondary",children:u(h.action)}),e.jsxs("div",{children:[e.jsx("div",{className:"text-sm font-medium",children:(m==null?void 0:m.name)||(m==null?void 0:m.email)||h.user_id.slice(0,8)}),h.metadata&&Object.keys(h.metadata).length>0&&e.jsx("div",{className:"text-xs text-muted-foreground truncate max-w-md",children:JSON.stringify(h.metadata)})]})]}),e.jsx("div",{className:"text-xs text-muted-foreground",children:Hs(new Date(h.created_at),"MMM d, h:mm a")})]},h.id)})})})]})]})},Zyn=()=>e.jsx(Ks,{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(ua,{defaultValue:"analytics",className:"space-y-4",children:[e.jsxs(ha,{children:[e.jsx(Qt,{value:"analytics",children:"Analytics"}),e.jsx(Qt,{value:"website-apps",children:"Website Apps"}),e.jsx(Qt,{value:"extension",children:"Chrome Extension"}),e.jsx(Qt,{value:"content",children:"Content"}),e.jsx(Qt,{value:"email-campaigns",children:"Email Campaigns"}),e.jsx(Qt,{value:"activity",children:"Activity"}),e.jsx(Qt,{value:"shares",children:"Shares"})]}),e.jsx(Jt,{value:"analytics",className:"space-y-4",children:e.jsx(mHs,{})}),e.jsx(Jt,{value:"website-apps",className:"space-y-4",children:e.jsx(Kyn,{})}),e.jsx(Jt,{value:"extension",className:"space-y-4",children:e.jsx(Yyn,{})}),e.jsx(Jt,{value:"content",className:"space-y-4",children:e.jsx(fHs,{})}),e.jsx(Jt,{value:"email-campaigns",className:"space-y-4",children:e.jsx(Wyn,{})}),e.jsx(Jt,{value:"activity",className:"space-y-4",children:e.jsx(hHs,{})}),e.jsx(Jt,{value:"shares",className:"space-y-4",children:e.jsx(q8t,{})})]})]})});function Xyn(){const s=ts(),[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,x]=j.useState([]),[g,y]=j.useState([]),[b,v]=j.useState(!1),[N,C]=j.useState(null),[A,T]=j.useState(""),{data:P,isLoading:M}=ht({queryKey:["brokerage-resources"],queryFn:async()=>{const{data:ke,error:Xe}=await U.from("brokerage_resources").select("*").order("publish_date",{ascending:!1});if(Xe)throw Xe;return ke}}),{data:I}=ht({queryKey:["brokerage-resource-pdfs"],queryFn:async()=>{const{data:ke,error:Xe}=await U.from("brokerage_resource_pdfs").select("*").order("sort_order",{ascending:!0});if(Xe)throw Xe;return ke}}),{data:D}=ht({queryKey:["brokerage-resource-videos"],queryFn:async()=>{const{data:ke,error:Xe}=await U.from("brokerage_resource_videos").select("*").order("sort_order",{ascending:!0});if(Xe)throw Xe;return ke}}),{data:B}=ht({queryKey:["brokerage-resource-links"],queryFn:async()=>{const{data:ke,error:Xe}=await U.from("brokerage_resource_links").select("*").order("sort_order",{ascending:!0});if(Xe)throw Xe;return ke}}),{data:q,isLoading:W}=ht({queryKey:["brokerage-resource-categories"],queryFn:async()=>{const{data:ke,error:Xe}=await U.from("brokerage_resource_categories").select("*").order("sort_order",{ascending:!0});if(Xe)throw Xe;return ke}}),V=()=>{l({title:"",description:"",publish_date:new Date().toISOString().split("T")[0],is_published:!1,category_id:""}),c(null),u(""),m([]),x([]),y([]),a(null),T("")},K=ke=>{a(ke),l({title:ke.title,description:ke.description||"",publish_date:ke.publish_date.split("T")[0],is_published:ke.is_published,category_id:ke.category_id||""}),u(ke.preview_image_url||""),T("");const Xe=(I==null?void 0:I.filter(Ae=>Ae.resource_id===ke.id))||[];m(Xe.map(Ae=>({id:Ae.id,name:Ae.name,file_url:Ae.file_url,file_size:Ae.file_size,sort_order:Ae.sort_order})));const Se=(D==null?void 0:D.filter(Ae=>Ae.resource_id===ke.id))||[];x(Se.map(Ae=>({id:Ae.id,title:Ae.title,video_url:Ae.video_url,sort_order:Ae.sort_order})));const Re=(B==null?void 0:B.filter(Ae=>Ae.resource_id===ke.id))||[];y(Re.map(Ae=>({id:Ae.id,title:Ae.title,canva_share_link:Ae.canva_share_link,sort_order:Ae.sort_order}))),n(!0)},Q=ke=>{var Se;const Xe=(Se=ke.target.files)==null?void 0:Se[0];Xe&&(c(Xe),u(URL.createObjectURL(Xe)))},J=()=>{m([...h,{name:"",file_url:"",sort_order:h.length}])},ce=ke=>{m(h.filter((Xe,Se)=>Se!==ke))},ue=(ke,Xe,Se)=>{const Re=[...h];if(Xe==="file"&&Se instanceof File){const Ae=Se.name.replace(/\.[^/.]+$/,"");Re[ke]={...Re[ke],file:Se,file_size:Se.size,name:Re[ke].name||Ae}}else Re[ke]={...Re[ke],[Xe]:Se};m(Re)},ne=()=>{x([...p,{title:"",video_url:"",sort_order:p.length}])},ee=ke=>{x(p.filter((Xe,Se)=>Se!==ke))},le=(ke,Xe,Se)=>{const Re=[...p];Xe==="file"&&Se instanceof File?Re[ke]={...Re[ke],file:Se}:Re[ke]={...Re[ke],[Xe]:Se},x(Re)},he=()=>{y([...g,{title:"",canva_share_link:"",sort_order:g.length}])},ve=ke=>{y(g.filter((Xe,Se)=>Se!==ke))},ge=(ke,Xe,Se)=>{const Re=[...g];Re[ke]={...Re[ke],[Xe]:Se},y(Re)},fe=async(ke,Xe)=>{try{const Se=await U.functions.invoke("bunny-upload",{body:{action:"create",title:ke.name}});if(Se.error)throw Se.error;const{videoId:Re,uploadUrl:Ae,libraryId:Be}=Se.data,qe=await U.functions.invoke("bunny-upload",{body:{action:"upload-url",videoId:Re,libraryId:Be}});if(qe.error)throw qe.error;const{uploadUrl:Ke,apiKey:Ze}=qe.data,Ue=new XMLHttpRequest;return Ue.open("PUT",Ke,!0),Ue.setRequestHeader("AccessKey",Ze),Ue.upload.onprogress=et=>{if(et.lengthComputable){const Qe=Math.round(et.loaded/et.total*100),Ge=[...p];Ge[Xe]={...Ge[Xe],uploadProgress:Qe},x(Ge)}},await new Promise((et,Qe)=>{Ue.onload=()=>Ue.status>=200&&Ue.status<300?et():Qe(new Error("Upload failed")),Ue.onerror=()=>Qe(new Error("Upload failed")),Ue.send(ke)}),`https://iframe.mediadelivery.net/embed/${Be}/${Re}`}catch(Se){throw console.error("Bunny upload error:",Se),Se}},je=yt({mutationFn:async ke=>{const{data:Xe,error:Se}=await U.from("brokerage_resource_categories").insert({name:ke,sort_order:(q==null?void 0:q.length)||0}).select().single();if(Se)throw Se;return Xe},onSuccess:ke=>{s.invalidateQueries({queryKey:["brokerage-resource-categories"]}),l({...i,category_id:ke.id}),T(""),ae.success("Category created")},onError:ke=>{ae.error("Failed to create category: "+ke.message)}}),Ee=yt({mutationFn:async()=>{v(!0);let ke=(r==null?void 0:r.preview_image_url)||null;if(o){const Re=o.name.split(".").pop(),Ae=`${Date.now()}.${Re}`,{error:Be}=await U.storage.from("brokerage-resources").upload(`previews/${Ae}`,o);if(Be)throw Be;const{data:qe}=U.storage.from("brokerage-resources").getPublicUrl(`previews/${Ae}`);ke=qe.publicUrl}const Xe={title:i.title,description:i.description||null,preview_image_url:ke,publish_date:i.publish_date,is_published:i.is_published,category_id:i.category_id||null};let Se;if(r){const{error:Re}=await U.from("brokerage_resources").update(Xe).eq("id",r.id);if(Re)throw Re;Se=r.id;const Ae=(I==null?void 0:I.filter(nt=>nt.resource_id===r.id).map(nt=>nt.id))||[],Be=h.filter(nt=>nt.id).map(nt=>nt.id),qe=Ae.filter(nt=>!Be.includes(nt));qe.length>0&&await U.from("brokerage_resource_pdfs").delete().in("id",qe);const Ke=(D==null?void 0:D.filter(nt=>nt.resource_id===r.id).map(nt=>nt.id))||[],Ze=p.filter(nt=>nt.id).map(nt=>nt.id),Ue=Ke.filter(nt=>!Ze.includes(nt));Ue.length>0&&await U.from("brokerage_resource_videos").delete().in("id",Ue);const et=(B==null?void 0:B.filter(nt=>nt.resource_id===r.id).map(nt=>nt.id))||[],Qe=g.filter(nt=>nt.id).map(nt=>nt.id),Ge=et.filter(nt=>!Qe.includes(nt));Ge.length>0&&await U.from("brokerage_resource_links").delete().in("id",Ge)}else{const{data:Re,error:Ae}=await U.from("brokerage_resources").insert(Xe).select().single();if(Ae)throw Ae;Se=Re.id}for(let Re=0;Re{s.invalidateQueries({queryKey:["brokerage-resources"]}),s.invalidateQueries({queryKey:["brokerage-resource-pdfs"]}),s.invalidateQueries({queryKey:["brokerage-resource-videos"]}),s.invalidateQueries({queryKey:["brokerage-resource-links"]}),ae.success(r?"Resource updated":"Resource created"),n(!1),V(),v(!1)},onError:ke=>{ae.error("Failed to save resource: "+ke.message),v(!1)}}),Me=yt({mutationFn:async ke=>{const{error:Xe}=await U.from("brokerage_resources").delete().eq("id",ke);if(Xe)throw Xe},onSuccess:()=>{s.invalidateQueries({queryKey:["brokerage-resources"]}),s.invalidateQueries({queryKey:["brokerage-resource-pdfs"]}),s.invalidateQueries({queryKey:["brokerage-resource-videos"]}),s.invalidateQueries({queryKey:["brokerage-resource-links"]}),ae.success("Resource deleted")},onError:ke=>{ae.error("Failed to delete: "+ke.message)}}),De=ke=>{if(ke.preventDefault(),!i.title){ae.error("Please enter a title");return}Ee.mutate()},ze=ke=>{const Xe=(I==null?void 0:I.filter(Ae=>Ae.resource_id===ke).length)||0,Se=(D==null?void 0:D.filter(Ae=>Ae.resource_id===ke).length)||0,Re=(B==null?void 0:B.filter(Ae=>Ae.resource_id===ke).length)||0;return{pdfCount:Xe,videoCount:Se,linkCount:Re}};return e.jsx(Ks,{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(_e,{children:[e.jsx(Bt,{className:"pb-2",children:e.jsx(Ut,{className:"text-sm font-medium text-muted-foreground",children:"Total Resources"})}),e.jsx(Oe,{children:e.jsx("div",{className:"text-2xl font-bold",children:(P==null?void 0:P.length)||0})})]}),e.jsxs(_e,{children:[e.jsx(Bt,{className:"pb-2",children:e.jsx(Ut,{className:"text-sm font-medium text-muted-foreground",children:"Published"})}),e.jsx(Oe,{children:e.jsx("div",{className:"text-2xl font-bold",children:(P==null?void 0:P.filter(ke=>ke.is_published).length)||0})})]})]}),e.jsxs($,{onClick:()=>{V(),n(!0)},children:[e.jsx(sn,{className:"h-4 w-4 mr-2"}),"Add Resource"]})]}),e.jsx(_e,{children:e.jsx(Oe,{className:"p-0",children:e.jsxs(Va,{children:[e.jsx(Ha,{children:e.jsxs(hn,{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(Ga,{children:M?e.jsx(hn,{children:e.jsx(gt,{colSpan:6,className:"text-center py-8",children:"Loading..."})}):(P==null?void 0:P.length)===0?e.jsx(hn,{children:e.jsx(gt,{colSpan:6,className:"text-center py-8 text-muted-foreground",children:"No brokerage resources yet. Create your first one!"})}):P==null?void 0:P.map(ke=>{const{pdfCount:Xe,videoCount:Se,linkCount:Re}=ze(ke.id),Ae=q==null?void 0:q.find(Be=>Be.id===ke.category_id);return e.jsxs(hn,{children:[e.jsx(gt,{children:e.jsxs("div",{className:"flex items-center gap-3",children:[ke.preview_image_url?e.jsx("img",{src:ke.preview_image_url,alt:ke.title,className:"w-10 h-10 rounded object-cover"}):e.jsx("div",{className:"w-10 h-10 rounded bg-muted flex items-center justify-center",children:e.jsx(ix,{className:"h-5 w-5 text-muted-foreground"})}),e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:ke.title}),ke.description&&e.jsx("div",{className:"text-sm text-muted-foreground line-clamp-1",children:ke.description})]})]})}),e.jsx(gt,{children:Ae?e.jsx("span",{className:"inline-flex items-center px-2 py-1 rounded-full text-xs font-medium bg-muted",children:Ae.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(Wr,{className:"h-3.5 w-3.5"}),Xe]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Xr,{className:"h-3.5 w-3.5"}),Se]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(kc,{className:"h-3.5 w-3.5"}),Re]})]})}),e.jsx(gt,{children:Hs(new Date(ke.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 ${ke.is_published?"bg-green-100 text-green-800":"bg-yellow-100 text-yellow-800"}`,children:ke.is_published?"Published":"Draft"})}),e.jsx(gt,{className:"text-right",children:e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx($,{variant:"ghost",size:"icon",onClick:()=>{const Be=(I==null?void 0:I.filter(Ze=>Ze.resource_id===ke.id))||[],qe=(D==null?void 0:D.filter(Ze=>Ze.resource_id===ke.id))||[],Ke=(B==null?void 0:B.filter(Ze=>Ze.resource_id===ke.id))||[];C({...ke,pdfs:Be,videos:qe,links:Ke})},children:e.jsx(ga,{className:"h-4 w-4"})}),e.jsx($,{variant:"ghost",size:"icon",onClick:()=>K(ke),children:e.jsx(Ya,{className:"h-4 w-4"})}),e.jsx($,{variant:"ghost",size:"icon",onClick:async()=>{await Yi("Delete this resource?")&&Me.mutate(ke.id)},children:e.jsx(Pn,{className:"h-4 w-4 text-destructive"})})]})})]},ke.id)})})]})})}),e.jsx(Os,{open:t,onOpenChange:n,children:e.jsxs(Rs,{className:"max-w-3xl max-h-[90vh] overflow-y-auto",children:[e.jsx(Us,{children:e.jsx(zs,{children:r?"Edit Brokerage Resource":"Add Brokerage Resource"})}),e.jsxs("form",{onSubmit:De,className:"space-y-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{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(ix,{className:"h-8 w-8 text-muted-foreground"})}),e.jsx(be,{type:"file",accept:"image/*",onChange:Q})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"title",children:"Title *"}),e.jsx(be,{id:"title",value:i.title,onChange:ke=>l({...i,title:ke.target.value}),placeholder:"Resource Title"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(se,{className:"flex items-center gap-2",children:[e.jsx(Up,{className:"h-4 w-4"}),"Category"]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(vs,{value:i.category_id,onValueChange:ke=>l({...i,category_id:ke}),children:[e.jsx(gs,{className:"flex-1",children:e.jsx(bs,{placeholder:"Select a category"})}),e.jsx(ys,{children:q==null?void 0:q.map(ke=>e.jsx(Ye,{value:ke.id,children:ke.name},ke.id))})]}),i.category_id&&e.jsx($,{type:"button",variant:"ghost",size:"icon",onClick:()=>l({...i,category_id:""}),children:e.jsx(pr,{className:"h-4 w-4"})})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(be,{placeholder:"Or create new category...",value:A,onChange:ke=>T(ke.target.value),className:"flex-1"}),e.jsxs($,{type:"button",variant:"outline",size:"sm",disabled:!A.trim()||je.isPending,onClick:()=>je.mutate(A.trim()),children:[e.jsx(sn,{className:"h-4 w-4 mr-1"}),"Add"]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Description"}),e.jsx(m2,{content:i.description,onChange:ke=>l({...i,description:ke}),placeholder:"Brief description of this resource",minHeight:"120px"})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"publish_date",children:"Publish Date"}),e.jsx(be,{id:"publish_date",type:"date",value:i.publish_date,onChange:ke=>l({...i,publish_date:ke.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Published"}),e.jsxs("div",{className:"flex items-center space-x-2 pt-2",children:[e.jsx(Tn,{checked:i.is_published,onCheckedChange:ke=>l({...i,is_published:ke})}),e.jsx("span",{className:"text-sm text-muted-foreground",children:i.is_published?"Visible to brokerage managers":"Hidden from brokerage managers"})]})]})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(se,{className:"flex items-center gap-2",children:[e.jsx(Wr,{className:"h-4 w-4"}),"PDF Documents (",h.length,")"]}),e.jsxs($,{type:"button",variant:"outline",size:"sm",onClick:J,children:[e.jsx(sn,{className:"h-4 w-4 mr-1"}),"Add PDF"]})]}),h.map((ke,Xe)=>e.jsxs("div",{className:"flex items-center gap-2 p-3 border rounded-lg bg-muted/50",children:[e.jsx(be,{placeholder:"PDF Name",value:ke.name,onChange:Se=>ue(Xe,"name",Se.target.value),className:"flex-1"}),e.jsx(be,{type:"file",accept:".pdf",onChange:Se=>{var Ae;const Re=(Ae=Se.target.files)==null?void 0:Ae[0];Re&&ue(Xe,"file",Re)},className:"flex-1"}),ke.file_url&&!ke.file&&e.jsx("span",{className:"text-xs text-muted-foreground",children:"Uploaded"}),e.jsx($,{type:"button",variant:"ghost",size:"icon",onClick:()=>ce(Xe),children:e.jsx(pr,{className:"h-4 w-4"})})]},Xe))]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(se,{className:"flex items-center gap-2",children:[e.jsx(Xr,{className:"h-4 w-4"}),"Videos (",p.length,")"]}),e.jsxs($,{type:"button",variant:"outline",size:"sm",onClick:ne,children:[e.jsx(sn,{className:"h-4 w-4 mr-1"}),"Add Video"]})]}),p.map((ke,Xe)=>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(be,{placeholder:"Video Title",value:ke.title,onChange:Se=>le(Xe,"title",Se.target.value),className:"flex-1"}),e.jsx($,{type:"button",variant:"ghost",size:"icon",onClick:()=>ee(Xe),children:e.jsx(pr,{className:"h-4 w-4"})})]}),e.jsx(be,{type:"file",accept:"video/*",onChange:Se=>{var Ae;const Re=(Ae=Se.target.files)==null?void 0:Ae[0];Re&&le(Xe,"file",Re)}}),ke.uploadProgress!==void 0&&ke.uploadProgress>0&&e.jsx("div",{className:"w-full bg-muted rounded-full h-2",children:e.jsx("div",{className:"bg-primary h-2 rounded-full transition-all",style:{width:`${ke.uploadProgress}%`}})}),ke.video_url&&!ke.file&&e.jsx("span",{className:"text-xs text-muted-foreground",children:"Video uploaded"})]},Xe))]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(se,{className:"flex items-center gap-2",children:[e.jsx(kc,{className:"h-4 w-4"}),"Canva Links (",g.length,")"]}),e.jsxs($,{type:"button",variant:"outline",size:"sm",onClick:he,children:[e.jsx(sn,{className:"h-4 w-4 mr-1"}),"Add Link"]})]}),g.map((ke,Xe)=>e.jsxs("div",{className:"flex items-center gap-2 p-3 border rounded-lg bg-muted/50",children:[e.jsx(be,{placeholder:"Link Title",value:ke.title,onChange:Se=>ge(Xe,"title",Se.target.value),className:"flex-1"}),e.jsx(be,{placeholder:"Canva Share Link",value:ke.canva_share_link,onChange:Se=>ge(Xe,"canva_share_link",Se.target.value),className:"flex-1"}),e.jsx($,{type:"button",variant:"ghost",size:"icon",onClick:()=>ve(Xe),children:e.jsx(pr,{className:"h-4 w-4"})})]},Xe))]}),e.jsxs("div",{className:"flex justify-end gap-2 pt-4",children:[e.jsx($,{type:"button",variant:"outline",onClick:()=>n(!1),children:"Cancel"}),e.jsx($,{type:"submit",disabled:Ee.isPending||b,children:Ee.isPending||b?"Saving...":r?"Update":"Create"})]})]})]})}),e.jsx(Os,{open:!!N,onOpenChange:()=>C(null),children:e.jsxs(Rs,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsx(Us,{children:e.jsx(zs,{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(Wr,{className:"h-4 w-4"}),"PDF Documents (",N.pdfs.length,")"]}),e.jsx("div",{className:"space-y-1",children:N.pdfs.map(ke=>e.jsx("a",{href:ke.file_url,target:"_blank",rel:"noopener noreferrer",className:"block p-2 border rounded hover:bg-muted",children:ke.name},ke.id))})]}),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(Xr,{className:"h-4 w-4"}),"Videos (",N.videos.length,")"]}),e.jsx("div",{className:"space-y-2",children:N.videos.map(ke=>e.jsx("div",{className:"p-2 border rounded",children:e.jsx("p",{className:"font-medium text-sm",children:ke.title})},ke.id))})]}),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(kc,{className:"h-4 w-4"}),"Canva Links (",N.links.length,")"]}),e.jsx("div",{className:"space-y-1",children:N.links.map(ke=>e.jsx("a",{href:ke.canva_share_link,target:"_blank",rel:"noopener noreferrer",className:"block p-2 border rounded hover:bg-muted",children:ke.title},ke.id))})]})]})]})})]})})}const DFt=[{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 Qyn(){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),[x,g]=j.useState(""),[y,b]=j.useState(""),[v,N]=j.useState(""),[C,A]=j.useState(""),[T,P]=j.useState("Learn More"),[M,I]=j.useState("top"),[D,B]=j.useState(""),[q,W]=j.useState(!0),[V,K]=j.useState(""),[Q,J]=j.useState("");j.useEffect(()=>{ce()},[]);const ce=async()=>{try{const{data:je,error:Ee}=await U.from("dashboard_banners").select("*").order("placement").order("sort_order");if(Ee)throw Ee;t(je||[])}catch(je){ae.error("Failed to load banners: "+je.message)}finally{r(!1)}},ue=()=>{g(""),b(""),N(""),A(""),P("Learn More"),I("top"),B(""),W(!0),K(""),J(""),d(null)},ne=je=>{d(je),g(je.title),b(je.description||""),N(je.image_url),A(je.link_url||""),P(je.link_text||"Learn More"),I(je.placement),B(je.section_after||""),W(je.is_active),K(je.start_date?Hs(new Date(je.start_date),"yyyy-MM-dd'T'HH:mm"):""),J(je.end_date?Hs(new Date(je.end_date),"yyyy-MM-dd'T'HH:mm"):""),i(!0)},ee=async je=>{var Me;const Ee=(Me=je.target.files)==null?void 0:Me[0];if(Ee){h(!0);try{const De=Ee.name.split(".").pop(),ze=`${Date.now()}.${De}`,{error:ke}=await U.storage.from("banner-images").upload(ze,Ee);if(ke)throw ke;const{data:{publicUrl:Xe}}=U.storage.from("banner-images").getPublicUrl(ze);N(Xe),ae.success("Image uploaded successfully")}catch(De){ae.error("Failed to upload image: "+De.message)}finally{h(!1)}}},le=async()=>{if(!x.trim()||!v){ae.error("Please fill in required fields (title and image)");return}p(!0);try{const je={title:x.trim(),description:y.trim()||null,image_url:v,link_url:C.trim()||null,link_text:T.trim()||"Learn More",placement:M,section_after:M==="between"?D:null,is_active:q,start_date:V?new Date(V).toISOString():null,end_date:Q?new Date(Q).toISOString():null};if(c){const{error:Ee}=await U.from("dashboard_banners").update(je).eq("id",c.id);if(Ee)throw Ee;ae.success("Banner updated successfully")}else{const Ee=s.filter(De=>De.placement===M).length,{error:Me}=await U.from("dashboard_banners").insert({...je,sort_order:Ee});if(Me)throw Me;ae.success("Banner created successfully")}i(!1),ue(),ce()}catch(je){ae.error("Failed to save banner: "+je.message)}finally{p(!1)}},he=async()=>{if(c)try{const{error:je}=await U.from("dashboard_banners").delete().eq("id",c.id);if(je)throw je;ae.success("Banner deleted successfully"),o(!1),d(null),ce()}catch(je){ae.error("Failed to delete banner: "+je.message)}},ve=async je=>{try{const{error:Ee}=await U.from("dashboard_banners").update({is_active:!je.is_active}).eq("id",je.id);if(Ee)throw Ee;ae.success(je.is_active?"Banner deactivated":"Banner activated"),ce()}catch(Ee){ae.error("Failed to update banner: "+Ee.message)}},ge=s.filter(je=>je.placement==="top"),fe=s.filter(je=>je.placement==="between");return n?e.jsx(Ks,{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(Ks,{title:"Dashboard Management",description:"Configure dashboard modules and banners",children:[e.jsxs("div",{className:"space-y-8",children:[e.jsxs(_e,{children:[e.jsxs(Bt,{className:"flex flex-row items-center justify-between",children:[e.jsxs("div",{children:[e.jsxs(Ut,{className:"flex items-center gap-2",children:[e.jsx(Jl,{className:"h-5 w-5"}),"Hero Banners (Top of Dashboard)"]}),e.jsx(vr,{children:"These banners appear in a rotating carousel at the top of the dashboard"})]}),e.jsxs(Os,{open:a&&M==="top",onOpenChange:je=>{je||ue(),i(je),je&&I("top")},children:[e.jsx(Ko,{asChild:!0,children:e.jsxs($,{onClick:()=>{ue(),I("top")},children:[e.jsx(sn,{className:"mr-2 h-4 w-4"}),"Add Hero Banner"]})}),e.jsxs(Rs,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsxs(Us,{children:[e.jsxs(zs,{children:[c?"Edit":"Create"," Banner"]}),e.jsx(Sr,{children:"Configure the banner's content and display settings"})]}),e.jsx(Rft,{title:x,setTitle:g,description:y,setDescription:b,imageUrl:v,linkUrl:C,setLinkUrl:A,linkText:T,setLinkText:P,placement:M,setPlacement:I,sectionAfter:D,setSectionAfter:B,isActive:q,setIsActive:W,startDate:V,setStartDate:K,endDate:Q,setEndDate:J,handleImageUpload:ee,uploading:u,showPlacementOptions:!1}),e.jsxs(kr,{children:[e.jsx($,{variant:"outline",onClick:()=>{i(!1),ue()},children:"Cancel"}),e.jsx($,{onClick:le,disabled:m,children:m?"Saving...":c?"Update Banner":"Create Banner"})]})]})]})]}),e.jsx(Oe,{children:ge.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:ge.map(je=>e.jsx(Oft,{banner:je,onEdit:()=>ne(je),onDelete:()=>{d(je),o(!0)},onToggleActive:()=>ve(je)},je.id))})})]}),e.jsxs(_e,{children:[e.jsxs(Bt,{className:"flex flex-row items-center justify-between",children:[e.jsxs("div",{children:[e.jsxs(Ut,{className:"flex items-center gap-2",children:[e.jsx(Jl,{className:"h-5 w-5"}),"Section Banners"]}),e.jsx(vr,{children:"These banners appear between dashboard content sections"})]}),e.jsxs(Os,{open:a&&M==="between",onOpenChange:je=>{je||ue(),i(je),je&&I("between")},children:[e.jsx(Ko,{asChild:!0,children:e.jsxs($,{onClick:()=>{ue(),I("between")},children:[e.jsx(sn,{className:"mr-2 h-4 w-4"}),"Add Section Banner"]})}),e.jsxs(Rs,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsxs(Us,{children:[e.jsxs(zs,{children:[c?"Edit":"Create"," Section Banner"]}),e.jsx(Sr,{children:"Configure where this banner appears between sections"})]}),e.jsx(Rft,{title:x,setTitle:g,description:y,setDescription:b,imageUrl:v,linkUrl:C,setLinkUrl:A,linkText:T,setLinkText:P,placement:M,setPlacement:I,sectionAfter:D,setSectionAfter:B,isActive:q,setIsActive:W,startDate:V,setStartDate:K,endDate:Q,setEndDate:J,handleImageUpload:ee,uploading:u,showPlacementOptions:!0}),e.jsxs(kr,{children:[e.jsx($,{variant:"outline",onClick:()=>{i(!1),ue()},children:"Cancel"}),e.jsx($,{onClick:le,disabled:m,children:m?"Saving...":c?"Update Banner":"Create Banner"})]})]})]})]}),e.jsx(Oe,{children:fe.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:fe.map(je=>e.jsx(Oft,{banner:je,onEdit:()=>ne(je),onDelete:()=>{d(je),o(!0)},onToggleActive:()=>ve(je),showSection:!0},je.id))})})]})]}),e.jsx(Os,{open:l,onOpenChange:o,children:e.jsxs(Rs,{children:[e.jsxs(Us,{children:[e.jsx(zs,{children:"Delete Banner"}),e.jsxs(Sr,{children:['Are you sure you want to delete "',c==null?void 0:c.title,'"? This action cannot be undone.']})]}),e.jsxs(kr,{children:[e.jsx($,{variant:"outline",onClick:()=>o(!1),children:"Cancel"}),e.jsx($,{variant:"destructive",onClick:he,children:"Delete"})]})]})})]})}function Rft({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:x,startDate:g,setStartDate:y,endDate:b,setEndDate:v,handleImageUpload:N,uploading:C,showPlacementOptions:A}){return e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"title",children:"Title *"}),e.jsx(be,{id:"title",placeholder:"Banner headline...",value:s,onChange:T=>t(T.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"description",children:"Description"}),e.jsx(Is,{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(se,{children:"Banner Image *"}),e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx(be,{type:"file",accept:"image/*",onChange:N,disabled:C,className:"flex-1"}),C&&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(se,{htmlFor:"linkUrl",children:"Link URL (optional)"}),e.jsx(be,{id:"linkUrl",placeholder:"https://...",value:i,onChange:T=>l(T.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"linkText",children:"Button Text"}),e.jsx(be,{id:"linkText",placeholder:"Learn More",value:o,onChange:T=>c(T.target.value)})]})]}),A&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Placement"}),e.jsxs(vs,{value:h,onValueChange:m,children:[e.jsx(gs,{children:e.jsx(bs,{placeholder:"Select section placement..."})}),e.jsx(ys,{children:DFt.map(T=>e.jsx(Ye,{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(se,{htmlFor:"startDate",className:"flex items-center gap-2",children:[e.jsx(ia,{className:"h-4 w-4"}),"Start Date (optional)"]}),e.jsx(be,{id:"startDate",type:"datetime-local",value:g,onChange:T=>y(T.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(se,{htmlFor:"endDate",className:"flex items-center gap-2",children:[e.jsx(ia,{className:"h-4 w-4"}),"End Date (optional)"]}),e.jsx(be,{id:"endDate",type:"datetime-local",value:b,onChange:T=>v(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(Tn,{id:"isActive",checked:p,onCheckedChange:x}),e.jsx(se,{htmlFor:"isActive",children:"Active"})]})})]})}function Oft({banner:s,onEdit:t,onDelete:n,onToggleActive:r,showSection:a=!1}){var c;const i=(c=DFt.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 U.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($p,{className:"h-5 w-5 text-muted-foreground cursor-grab"}),e.jsx("img",{src:s.image_url,alt:s.title,className:"w-24 h-14 object-cover rounded"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("h4",{className:"font-medium truncate",children:s.title}),!s.is_active&&e.jsx($e,{variant:"secondary",children:"Inactive"}),s.start_date&&new Date(s.start_date)>new Date&&e.jsx($e,{variant:"outline",children:"Scheduled"})]}),s.description&&e.jsx("p",{className:"text-sm text-muted-foreground truncate",children:s.description}),a&&i&&e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:i})]}),l!==null&&e.jsxs("div",{className:"flex items-center gap-1 text-destructive",title:"Button clicks",children:[e.jsx(uu,{className:"h-4 w-4"}),e.jsx("span",{className:"text-sm font-semibold",children:l})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[s.link_url&&e.jsx("a",{href:s.link_url,target:"_blank",rel:"noopener noreferrer",children:e.jsx($,{variant:"ghost",size:"icon",children:e.jsx(Tr,{className:"h-4 w-4"})})}),e.jsx($,{variant:"ghost",size:"icon",onClick:r,children:s.is_active?e.jsx(ga,{className:"h-4 w-4"}):e.jsx(b0,{className:"h-4 w-4"})}),e.jsx($,{variant:"ghost",size:"icon",onClick:t,children:e.jsx(Ya,{className:"h-4 w-4"})}),e.jsx($,{variant:"ghost",size:"icon",onClick:n,children:e.jsx(Pn,{className:"h-4 w-4 text-destructive"})})]})]})}const Ire={open:{label:"Open",icon:Hr,color:"bg-yellow-500"},in_progress:{label:"In Progress",icon:Ed,color:"bg-blue-500"},resolved:{label:"Resolved",icon:Ro,color:"bg-green-500"},closed:{label:"Closed",icon:$d,color:"bg-muted-foreground"}},Fft={general:"General Support",technology:"Technology Support",crm:"CRM Support",marketing:"Marketing Support"};function Jyn(){var M,I;const{user:s}=_s(),t=ts(),[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:x=[],isLoading:g}=ht({queryKey:["admin-support-tickets",c,u],queryFn:async()=>{let D=U.from("support_tickets").select("*, profiles!support_tickets_user_id_fkey(name, email)").order("created_at",{ascending:!1});c!=="all"&&(D=D.eq("status",c)),u!=="all"&&(D=D.eq("category",u));const{data:B,error:q}=await D;if(q)throw q;return B}}),{data:y=[]}=ht({queryKey:["admin-users-notifications"],queryFn:async()=>{const{data:D,error:B}=await U.from("user_roles").select("user_id").eq("role","admin");if(B)throw B;const q=D.map(ce=>ce.user_id),{data:W,error:V}=await U.from("profiles").select("id, name, email").in("id",q);if(V)throw V;const{data:K,error:Q}=await U.from("support_notification_settings").select("user_id, receive_notifications");if(Q)throw Q;const J=new Map((K==null?void 0:K.map(ce=>[ce.user_id,ce.receive_notifications]))||[]);return W.map(ce=>({...ce,receives_notifications:J.get(ce.id)||!1}))}}),{data:b=[]}=ht({queryKey:["admin-ticket-replies",n==null?void 0:n.id],queryFn:async()=>{if(!n)return[];const{data:D,error:B}=await U.from("support_ticket_replies").select("*, profiles(name)").eq("ticket_id",n.id).order("created_at",{ascending:!0});if(B)throw B;return D},enabled:!!n}),v=yt({mutationFn:async({userId:D,enabled:B})=>{const{data:q}=await U.from("support_notification_settings").select("id").eq("user_id",D).maybeSingle();if(q){const{error:W}=await U.from("support_notification_settings").update({receive_notifications:B}).eq("user_id",D);if(W)throw W}else{const{error:W}=await U.from("support_notification_settings").insert({user_id:D,receive_notifications:B});if(W)throw W}},onSuccess:()=>{t.invalidateQueries({queryKey:["admin-users-notifications"]}),ae.success("Notification settings updated")},onError:()=>{ae.error("Failed to update settings")}}),N=yt({mutationFn:async({ticketId:D,status:B})=>{const{error:q}=await U.from("support_tickets").update({status:B}).eq("id",D);if(q)throw q},onSuccess:()=>{t.invalidateQueries({queryKey:["admin-support-tickets"]}),n&&r({...n,status:n.status}),ae.success("Status updated")},onError:()=>{ae.error("Failed to update status")}}),C=yt({mutationFn:async({ticketId:D,assignedTo:B})=>{const{error:q}=await U.from("support_tickets").update({assigned_to:B}).eq("id",D);if(q)throw q},onSuccess:()=>{t.invalidateQueries({queryKey:["admin-support-tickets"]}),ae.success("Ticket assigned")},onError:()=>{ae.error("Failed to assign ticket")}}),A=yt({mutationFn:async({content:D,attachments:B})=>{var W,V;if(!n||!s)throw new Error("Missing data");const{error:q}=await U.from("support_ticket_replies").insert({ticket_id:n.id,user_id:s.id,content:D,is_admin_reply:!0,attachments:B});if(q)throw q;try{await U.functions.invoke("support-reply-notify",{body:{ticketId:n.id,ticketSubject:n.subject,replyContent:D,userEmail:(W=n.profiles)==null?void 0:W.email,userName:(V=n.profiles)==null?void 0:V.name}})}catch(K){console.error("Failed to send reply notification:",K)}},onSuccess:()=>{t.invalidateQueries({queryKey:["admin-ticket-replies",n==null?void 0:n.id]}),i(""),o([]),ae.success("Reply sent!")},onError:()=>{ae.error("Failed to send reply")}}),T=()=>{!a.trim()&&l.length===0||A.mutate({content:a,attachments:l})};j.useEffect(()=>{const D=U.channel("admin-tickets").on("postgres_changes",{event:"*",schema:"public",table:"support_tickets"},()=>{t.invalidateQueries({queryKey:["admin-support-tickets"]})}).subscribe();return()=>{U.removeChannel(D)}},[t]);const P=x.filter(D=>D.status==="open").length;return n?(Ire[n.status].icon,e.jsx(Ks,{children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx($,{variant:"ghost",size:"icon",onClick:()=>r(null),children:e.jsx(ka,{className:"h-5 w-5"})}),e.jsxs("div",{className:"flex-1",children:[e.jsx("h1",{className:"text-2xl font-bold",children:n.subject}),e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[e.jsx($e,{variant:"secondary",children:Fft[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(_e,{children:[e.jsx(Bt,{className:"pb-2",children:e.jsx(Ut,{className:"text-sm",children:"Status"})}),e.jsx(Oe,{children:e.jsxs(vs,{value:n.status,onValueChange:D=>{N.mutate({ticketId:n.id,status:D}),r({...n,status:D})},children:[e.jsx(gs,{children:e.jsx(bs,{})}),e.jsxs(ys,{children:[e.jsx(Ye,{value:"open",children:"Open"}),e.jsx(Ye,{value:"in_progress",children:"In Progress"}),e.jsx(Ye,{value:"resolved",children:"Resolved"}),e.jsx(Ye,{value:"closed",children:"Closed"})]})]})})]}),e.jsxs(_e,{children:[e.jsx(Bt,{className:"pb-2",children:e.jsx(Ut,{className:"text-sm",children:"Assigned To"})}),e.jsx(Oe,{children:e.jsxs(vs,{value:n.assigned_to||"unassigned",onValueChange:D=>{const B=D==="unassigned"?null:D;C.mutate({ticketId:n.id,assignedTo:B}),r({...n,assigned_to:B})},children:[e.jsx(gs,{children:e.jsx(bs,{placeholder:"Unassigned"})}),e.jsxs(ys,{children:[e.jsx(Ye,{value:"unassigned",children:"Unassigned"}),y.map(D=>e.jsx(Ye,{value:D.id,children:D.name},D.id))]})]})})]})]}),e.jsxs(_e,{children:[e.jsx(Bt,{children:e.jsxs(vr,{children:["Created on ",Hs(new Date(n.created_at),"MMM d, yyyy 'at' h:mm a")]})}),e.jsx(Oe,{children:e.jsx("p",{className:"text-muted-foreground whitespace-pre-wrap",children:n.description})})]}),e.jsxs(_e,{children:[e.jsx(Bt,{children:e.jsx(Ut,{className:"text-lg",children:"Conversation"})}),e.jsxs(Oe,{children:[e.jsx(Oi,{className:"h-[300px] pr-4",children:b.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:b.map(D=>{var B,q;return e.jsxs("div",{className:`p-4 rounded-lg ${D.is_admin_reply?"bg-primary/10 ml-4":"bg-muted mr-4"}`,children:[e.jsxs("div",{className:"flex justify-between items-start mb-2",children:[e.jsx("span",{className:"font-medium text-sm",children:D.is_admin_reply?`${((B=D.profiles)==null?void 0:B.name)||"Admin"} (Support)`:((q=D.profiles)==null?void 0:q.name)||"User"}),e.jsx("span",{className:"text-xs text-muted-foreground",children:Hs(new Date(D.created_at),"MMM d, h:mm a")})]}),e.jsx("p",{className:"text-sm whitespace-pre-wrap",children:D.content}),D.attachments&&D.attachments.length>0&&e.jsx(d8t,{attachments:D.attachments})]},D.id)})})}),e.jsx(Hl,{className:"my-4"}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex gap-2",children:[e.jsx(Is,{placeholder:"Type your reply...",value:a,onChange:D=>i(D.target.value),className:"min-h-[80px]"}),e.jsx($,{onClick:T,disabled:!a.trim()&&l.length===0||A.isPending,className:"self-end",children:e.jsx(Br,{className:"h-4 w-4"})})]}),e.jsx(c8t,{value:l,onChange:o,disabled:A.isPending})]})]})]})]})})):e.jsx(Ks,{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",P>0&&e.jsxs($e,{variant:"destructive",className:"ml-2",children:[P," open"]})]})]}),e.jsxs(Os,{open:m,onOpenChange:p,children:[e.jsx(Ko,{asChild:!0,children:e.jsxs($,{variant:"outline",children:[e.jsx(pc,{className:"h-4 w-4 mr-2"}),"Notification Settings"]})}),e.jsxs(Rs,{children:[e.jsxs(Us,{children:[e.jsx(zs,{children:"Email Notification Settings"}),e.jsx(Sr,{children:"Choose which admins receive email notifications for new support tickets."})]}),e.jsx("div",{className:"space-y-4 mt-4",children:y.map(D=>e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(Lo,{className:"h-4 w-4 text-muted-foreground"}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:D.name}),e.jsx("p",{className:"text-sm text-muted-foreground",children:D.email})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[D.receives_notifications?e.jsx(Dx,{className:"h-4 w-4 text-primary"}):e.jsx(e5,{className:"h-4 w-4 text-muted-foreground"}),e.jsx(Tn,{checked:D.receives_notifications,onCheckedChange:B=>v.mutate({userId:D.id,enabled:B})})]})]},D.id))})]})]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex flex-wrap gap-4 items-center",children:[e.jsx(ua,{value:c,onValueChange:d,className:"w-auto",children:e.jsxs(ha,{children:[e.jsx(Qt,{value:"all",children:"All"}),e.jsx(Qt,{value:"open",children:"Open"}),e.jsx(Qt,{value:"in_progress",children:"In Progress"}),e.jsx(Qt,{value:"resolved",children:"Resolved"}),e.jsx(Qt,{value:"closed",children:"Closed"})]})}),e.jsxs(vs,{value:u,onValueChange:h,children:[e.jsx(gs,{className:"w-[180px]",children:e.jsx(bs,{placeholder:"All Categories"})}),e.jsxs(ys,{children:[e.jsx(Ye,{value:"all",children:"All Categories"}),e.jsx(Ye,{value:"general",children:"General Support"}),e.jsx(Ye,{value:"technology",children:"Technology Support"}),e.jsx(Ye,{value:"crm",children:"CRM Support"}),e.jsx(Ye,{value:"marketing",children:"Marketing Support"})]})]})]}),e.jsx("div",{className:"mt-4",children:g?e.jsx("div",{className:"text-center py-12 text-muted-foreground",children:"Loading tickets..."}):x.length===0?e.jsx(_e,{children:e.jsxs(Oe,{className:"text-center py-12",children:[e.jsx(Ed,{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:x.map(D=>{var q,W;const B=Ire[D.status].icon;return e.jsx(_e,{className:"cursor-pointer hover:bg-muted/50 transition-colors",onClick:()=>r(D),children:e.jsx(Oe,{className:"p-4",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("h3",{className:"font-medium truncate",children:D.subject}),e.jsxs("div",{className:"flex items-center gap-2 mt-1 flex-wrap",children:[e.jsx($e,{variant:"outline",className:"text-xs",children:Fft[D.category]}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:[(q=D.profiles)==null?void 0:q.name," • ",Hs(new Date(D.created_at),"MMM d, yyyy")]}),D.assigned_to&&e.jsxs($e,{variant:"secondary",className:"text-xs gap-1",children:[e.jsx(Lo,{className:"h-3 w-3"}),((W=y.find(V=>V.id===D.assigned_to))==null?void 0:W.name)||"Assigned"]})]})]}),e.jsxs($e,{className:Ire[D.status].color,children:[e.jsx(B,{className:"h-3 w-3 mr-1"}),Ire[D.status].label]})]})})},D.id)})})})]})]})})}const RFt=ky.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 evn({content:s,onChange:t,variables:n}){const r=GGe({extensions:[KGe,rWe.configure({openOnClick:!1,HTMLAttributes:{class:"text-primary underline"}}),aWe.configure({types:["heading","paragraph"]}),iWe,RFt],content:s,onUpdate:({editor:l})=>{t(l.getHTML())}});j.useEffect(()=>{r&&s!==r.getHTML()&&r.commands.setContent(s)},[s,r]);const a=l=>{r&&r.chain().focus().insertContent(`{{${l.key}}}`).run()},i=()=>{if(!r)return;const l=r.getAttributes("link").href,o=window.prompt("URL",l);if(o!==null){if(o===""){r.chain().focus().extendMarkRange("link").unsetLink().run();return}r.chain().focus().extendMarkRange("link").setLink({href:o}).run()}};return r?e.jsxs("div",{className:"border rounded-lg overflow-hidden",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-1 p-2 border-b bg-muted/30",children:[e.jsx($,{type:"button",variant:"ghost",size:"sm",onClick:()=>r.chain().focus().toggleBold().run(),className:r.isActive("bold")?"bg-muted":"",children:e.jsx(pT,{className:"h-4 w-4"})}),e.jsx($,{type:"button",variant:"ghost",size:"sm",onClick:()=>r.chain().focus().toggleItalic().run(),className:r.isActive("italic")?"bg-muted":"",children:e.jsx(_T,{className:"h-4 w-4"})}),e.jsx("div",{className:"w-px h-6 bg-border mx-1"}),e.jsx($,{type:"button",variant:"ghost",size:"sm",onClick:()=>r.chain().focus().toggleBulletList().run(),className:r.isActive("bulletList")?"bg-muted":"",children:e.jsx(Sg,{className:"h-4 w-4"})}),e.jsx($,{type:"button",variant:"ghost",size:"sm",onClick:()=>r.chain().focus().toggleOrderedList().run(),className:r.isActive("orderedList")?"bg-muted":"",children:e.jsx(qj,{className:"h-4 w-4"})}),e.jsx("div",{className:"w-px h-6 bg-border mx-1"}),e.jsx($,{type:"button",variant:"ghost",size:"sm",onClick:()=>r.chain().focus().setTextAlign("left").run(),className:r.isActive({textAlign:"left"})?"bg-muted":"",children:e.jsx(iR,{className:"h-4 w-4"})}),e.jsx($,{type:"button",variant:"ghost",size:"sm",onClick:()=>r.chain().focus().setTextAlign("center").run(),className:r.isActive({textAlign:"center"})?"bg-muted":"",children:e.jsx(aR,{className:"h-4 w-4"})}),e.jsx($,{type:"button",variant:"ghost",size:"sm",onClick:()=>r.chain().focus().setTextAlign("right").run(),className:r.isActive({textAlign:"right"})?"bg-muted":"",children:e.jsx(oR,{className:"h-4 w-4"})}),e.jsx("div",{className:"w-px h-6 bg-border mx-1"}),e.jsx($,{type:"button",variant:"ghost",size:"sm",onClick:i,className:r.isActive("link")?"bg-muted":"",children:e.jsx(kc,{className:"h-4 w-4"})}),e.jsx($,{type:"button",variant:"ghost",size:"sm",onClick:()=>r.chain().focus().toggleCodeBlock().run(),className:r.isActive("codeBlock")?"bg-muted":"",children:e.jsx(xT,{className:"h-4 w-4"})}),e.jsx("div",{className:"w-px h-6 bg-border mx-1"}),e.jsx($,{type:"button",variant:"ghost",size:"sm",onClick:()=>r.chain().focus().undo().run(),disabled:!r.can().undo(),children:e.jsx(PT,{className:"h-4 w-4"})}),e.jsx($,{type:"button",variant:"ghost",size:"sm",onClick:()=>r.chain().focus().redo().run(),disabled:!r.can().redo(),children:e.jsx(ET,{className:"h-4 w-4"})}),e.jsx("div",{className:"flex-1"}),n.length>0&&e.jsxs(Hd,{children:[e.jsx(Gd,{asChild:!0,children:e.jsxs($,{type:"button",variant:"outline",size:"sm",className:"gap-2",children:[e.jsx(Gz,{className:"h-4 w-4"}),"Insert Variable"]})}),e.jsx(Md,{align:"end",className:"w-64",children:n.map(l=>e.jsxs(Na,{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(VGe,{editor:r,className:"prose prose-sm max-w-none p-4 min-h-[300px] focus:outline-none [&_.ProseMirror]:outline-none [&_.ProseMirror]:min-h-[280px]"}),n.length>0&&e.jsxs("div",{className:"border-t p-3 bg-muted/20",children:[e.jsx("p",{className:"text-xs text-muted-foreground mb-2",children:"Available variables (click to copy):"}),e.jsx("div",{className:"flex flex-wrap gap-2",children:n.map(l=>e.jsx($e,{variant:"secondary",className:"cursor-pointer hover:bg-secondary/80 font-mono text-xs",onClick:()=>{navigator.clipboard.writeText(`{{${l.key}}}`)},children:`{{${l.key}}}`},l.key))})]})]}):null}function tvn(){const s=ts(),[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,x]=j.useState("visual"),{data:g,isLoading:y}=ht({queryKey:["email-templates"],queryFn:async()=>{const{data:A,error:T}=await U.from("email_templates").select("*").order("name");if(T)throw T;return A.map(P=>({...P,available_variables:P.available_variables||[]}))}}),b=yt({mutationFn:async A=>{const{error:T}=await U.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"]}),ae.success("Email template updated successfully"),n(null)},onError:A=>{ae.error("Failed to update template: "+A.message)}}),v=A=>{n(A),l(A.subject),c(A.body_html),u(A.description||""),m(A.is_active),x("visual")},N=()=>{t&&b.mutate({id:t.id,subject:i,body_html:o,description:d,is_active:h})},C=(A,T)=>{let P=A;return T.forEach(M=>{const I=`{{${M.key}}}`,D=`[${M.label}]`;P=P.replace(new RegExp(I.replace(/[{}]/g,"\\$&"),"g"),D)}),P};return t?e.jsxs(Ks,{title:"Edit Email Template",children:[e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsxs($,{variant:"ghost",onClick:()=>n(null),children:[e.jsx(ka,{className:"h-4 w-4 mr-2"}),"Back to Templates"]}),e.jsx("div",{className:"flex-1"}),e.jsxs($,{variant:"outline",onClick:()=>a(t),children:[e.jsx(ga,{className:"h-4 w-4 mr-2"}),"Preview"]}),e.jsxs($,{onClick:N,disabled:b.isPending,children:[e.jsx(Jo,{className:"h-4 w-4 mr-2"}),b.isPending?"Saving...":"Save Changes"]})]}),e.jsxs(_e,{children:[e.jsx(Bt,{children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsxs(Ut,{className:"flex items-center gap-2",children:[e.jsx(nn,{className:"h-5 w-5"}),t.name]}),e.jsxs(vr,{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(se,{htmlFor:"active-toggle",children:"Active"}),e.jsx(Tn,{id:"active-toggle",checked:h,onCheckedChange:m})]})]})}),e.jsxs(Oe,{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"description",children:"Description"}),e.jsx(Is,{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(se,{htmlFor:"subject",children:"Email Subject"}),e.jsx(be,{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(se,{children:"Email Body"}),e.jsx(ua,{value:p,onValueChange:A=>x(A),children:e.jsxs(ha,{className:"h-8",children:[e.jsxs(Qt,{value:"visual",className:"text-xs px-3 h-6",children:[e.jsx(Hj,{className:"h-3 w-3 mr-1"}),"Visual"]}),e.jsxs(Qt,{value:"html",className:"text-xs px-3 h-6",children:[e.jsx(xT,{className:"h-3 w-3 mr-1"}),"HTML"]})]})})]}),p==="visual"?e.jsx(evn,{content:o,onChange:c,variables:t.available_variables}):e.jsx(Is,{value:o,onChange:A=>c(A.target.value),className:"font-mono text-sm min-h-[400px]",placeholder:"HTML email body"})]})]})]})]}),e.jsx(Os,{open:!!r,onOpenChange:()=>a(null),children:e.jsxs(Rs,{className:"max-w-3xl max-h-[90vh] overflow-auto",children:[e.jsxs(Us,{children:[e.jsx(zs,{children:"Email Preview"}),e.jsxs(Sr,{children:["Subject: ",i.replace(/\{\{(\w+)\}\}/g,"[$1]")]})]}),e.jsx("div",{className:"border rounded-lg p-4 bg-white",children:e.jsx("div",{dangerouslySetInnerHTML:{__html:C(o,t.available_variables)}})})]})})]}):e.jsx(Ks,{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(_e,{children:e.jsxs(Bt,{children:[e.jsx(on,{className:"h-5 w-48"}),e.jsx(on,{className:"h-4 w-96"})]})},T))}):e.jsx("div",{className:"grid gap-4",children:g==null?void 0:g.map(A=>e.jsxs(_e,{className:"hover:shadow-md transition-shadow",children:[e.jsx(Bt,{children:e.jsxs("div",{className:"flex items-start justify-between",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsxs(Ut,{className:"flex items-center gap-2 text-lg",children:[e.jsx(nn,{className:"h-5 w-5 text-muted-foreground"}),A.name,!A.is_active&&e.jsx($e,{variant:"secondary",children:"Inactive"})]}),e.jsx(vr,{children:A.description})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs($,{variant:"outline",size:"sm",onClick:()=>a(A),children:[e.jsx(ga,{className:"h-4 w-4 mr-2"}),"Preview"]}),e.jsxs($,{size:"sm",onClick:()=>v(A),children:[e.jsx(bm,{className:"h-4 w-4 mr-2"}),"Edit"]})]})]})}),e.jsx(Oe,{children:e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[e.jsx("span",{className:"text-muted-foreground",children:"Subject:"}),e.jsx("code",{className:"bg-muted px-2 py-0.5 rounded text-sm",children:A.subject})]}),e.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[e.jsx("span",{className:"text-muted-foreground",children:"Variables:"}),e.jsx("div",{className:"flex flex-wrap gap-1",children:A.available_variables.map(T=>e.jsx($e,{variant:"outline",className:"font-mono text-xs",children:`{{${T.key}}}`},T.key))})]})]})})]},A.id))}),e.jsx(Os,{open:!!r&&!t,onOpenChange:()=>a(null),children:e.jsxs(Rs,{className:"max-w-3xl max-h-[90vh] overflow-auto",children:[e.jsxs(Us,{children:[e.jsxs(zs,{children:["Email Preview: ",r==null?void 0:r.name]}),e.jsxs(Sr,{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:C(r.body_html,r.available_variables)}})})]})})]})})}function svn(){const s=ts(),[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,x]=j.useState({name:"",description:"",icon:"📧"}),{data:g=[]}=ht({queryKey:["agent-email-template-categories"],queryFn:async()=>{const{data:D,error:B}=await U.from("email_template_categories").select("*").order("sort_order");if(B)throw B;return D}}),{data:y=[],isLoading:b}=ht({queryKey:["agent-email-templates-admin"],queryFn:async()=>{const{data:D,error:B}=await U.from("agent_email_templates").select("*, category:email_template_categories(*)").order("sort_order");if(B)throw B;return D}}),v=yt({mutationFn:async D=>{const B={title:D.title,subject:D.subject,body:D.body,description:D.description||null,tone:D.tone||null,category_id:D.category_id||null,is_active:D.is_active};if(D.id){const{error:q}=await U.from("agent_email_templates").update(B).eq("id",D.id);if(q)throw q}else{const{error:q}=await U.from("agent_email_templates").insert(B);if(q)throw q}},onSuccess:()=>{s.invalidateQueries({queryKey:["agent-email-templates-admin"]}),c(!1),ae.success(r?"Template updated":"Template created")},onError:()=>ae.error("Failed to save template")}),N=yt({mutationFn:async D=>{const{error:B}=await U.from("agent_email_templates").delete().eq("id",D);if(B)throw B},onSuccess:()=>{s.invalidateQueries({queryKey:["agent-email-templates-admin"]}),ae.success("Template deleted")}}),C=yt({mutationFn:async D=>{const B={name:D.name,description:D.description||null,icon:D.icon};if(D.id){const{error:q}=await U.from("email_template_categories").update(B).eq("id",D.id);if(q)throw q}else{const q=g.length>0?Math.max(...g.map(V=>V.sort_order))+1:0,{error:W}=await U.from("email_template_categories").insert({...B,sort_order:q});if(W)throw W}},onSuccess:()=>{s.invalidateQueries({queryKey:["agent-email-template-categories"]}),u(!1),ae.success(i?"Category updated":"Category created")},onError:()=>ae.error("Failed to save category")}),A=yt({mutationFn:async D=>{const{error:B}=await U.from("email_template_categories").delete().eq("id",D);if(B)throw B},onSuccess:()=>{s.invalidateQueries({queryKey:["agent-email-template-categories"]}),ae.success("Category deleted")}}),T=()=>{a(null),m({title:"",subject:"",body:"",description:"",tone:"",category_id:"",is_active:!0}),c(!0)},P=D=>{a(D),m({title:D.title,subject:D.subject,body:D.body,description:D.description||"",tone:D.tone||"",category_id:D.category_id||"",is_active:D.is_active}),c(!0)},M=()=>{l(null),x({name:"",description:"",icon:"📧"}),u(!0)},I=D=>{l(D),x({name:D.name,description:D.description||"",icon:D.icon}),u(!0)};return e.jsx(Ks,{children:e.jsxs("div",{className:"space-y-6 animate-fade-in",children:[e.jsx(hh,{title:"Agent Email Templates",description:"Manage email templates that agents use when composing emails from Mission Control."}),e.jsxs(ua,{value:t,onValueChange:n,children:[e.jsxs(ha,{children:[e.jsxs(Qt,{value:"templates",className:"gap-2",children:[e.jsx(nn,{className:"h-4 w-4"})," Templates"]}),e.jsxs(Qt,{value:"categories",className:"gap-2",children:[e.jsx(cv,{className:"h-4 w-4"})," Categories"]})]}),e.jsxs(Jt,{value:"templates",className:"space-y-4",children:[e.jsx("div",{className:"flex justify-end",children:e.jsxs($,{onClick:T,className:"gap-2",children:[e.jsx(sn,{className:"h-4 w-4"})," Add Template"]})}),e.jsx(_e,{children:e.jsx(Oe,{className:"p-0",children:e.jsxs(Va,{children:[e.jsx(Ha,{children:e.jsxs(hn,{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(Ga,{children:b?e.jsx(hn,{children:e.jsx(gt,{colSpan:5,className:"text-center py-8",children:e.jsx(Ht,{className:"h-6 w-6 animate-spin mx-auto"})})}):y.length===0?e.jsx(hn,{children:e.jsx(gt,{colSpan:5,className:"text-center py-8 text-muted-foreground",children:"No templates yet. Create your first one!"})}):y.map(D=>e.jsxs(hn,{children:[e.jsx(gt,{children:e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:D.title}),e.jsx("p",{className:"text-xs text-muted-foreground truncate max-w-[300px]",children:D.subject})]})}),e.jsx(gt,{className:"hidden md:table-cell",children:D.category?e.jsxs($e,{variant:"outline",className:"gap-1",children:[D.category.icon," ",D.category.name]}):e.jsx("span",{className:"text-muted-foreground text-sm",children:"—"})}),e.jsx(gt,{className:"hidden md:table-cell",children:D.tone?e.jsx($e,{variant:"secondary",children:D.tone}):"—"}),e.jsx(gt,{children:e.jsx($e,{variant:D.is_active?"default":"secondary",children:D.is_active?"Active":"Inactive"})}),e.jsx(gt,{className:"text-right",children:e.jsxs("div",{className:"flex justify-end gap-1",children:[e.jsx($,{variant:"ghost",size:"icon",onClick:()=>P(D),children:e.jsx(Ya,{className:"h-4 w-4"})}),e.jsx($,{variant:"ghost",size:"icon",className:"text-destructive hover:text-destructive",onClick:async()=>{await Yi("Delete this template?")&&N.mutate(D.id)},children:e.jsx(Pn,{className:"h-4 w-4"})})]})})]},D.id))})]})})})]}),e.jsxs(Jt,{value:"categories",className:"space-y-4",children:[e.jsx("div",{className:"flex justify-end",children:e.jsxs($,{onClick:M,className:"gap-2",children:[e.jsx(sn,{className:"h-4 w-4"})," Add Category"]})}),e.jsx("div",{className:"grid gap-3 sm:grid-cols-2 lg:grid-cols-3",children:g.map(D=>e.jsxs(_e,{children:[e.jsx(Bt,{className:"pb-2",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(Ut,{className:"text-base flex items-center gap-2",children:[e.jsx("span",{className:"text-lg",children:D.icon})," ",D.name]}),e.jsxs("div",{className:"flex gap-1",children:[e.jsx($,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:()=>I(D),children:e.jsx(Ya,{className:"h-3.5 w-3.5"})}),e.jsx($,{variant:"ghost",size:"icon",className:"h-8 w-8 text-destructive",onClick:async()=>{await Yi("Delete this category?")&&A.mutate(D.id)},children:e.jsx(Pn,{className:"h-3.5 w-3.5"})})]})]})}),e.jsxs(Oe,{children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:D.description||"No description"}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-2",children:[y.filter(B=>B.category_id===D.id).length," templates"]})]})]},D.id))})]})]}),e.jsx(Os,{open:o,onOpenChange:c,children:e.jsxs(Rs,{className:"sm:max-w-[700px] max-h-[90vh] overflow-y-auto",children:[e.jsx(Us,{children:e.jsx(zs,{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(se,{children:"Title"}),e.jsx(be,{value:h.title,onChange:D=>m(B=>({...B,title:D.target.value})),placeholder:"e.g. Quick Check-in"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:"Category"}),e.jsxs(vs,{value:h.category_id,onValueChange:D=>m(B=>({...B,category_id:D})),children:[e.jsx(gs,{children:e.jsx(bs,{placeholder:"Select category"})}),e.jsx(ys,{children:g.map(D=>e.jsxs(Ye,{value:D.id,children:[D.icon," ",D.name]},D.id))})]})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:"Subject Line"}),e.jsx(be,{value:h.subject,onChange:D=>m(B=>({...B,subject:D.target.value})),placeholder:"e.g. Hey {{first_name}}, just checking in!"}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Use ","{{first_name}}",", ","{{last_name}}",", ","{{full_name}}"," for merge variables"]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:"Email Body"}),e.jsx(Is,{value:h.body,onChange:D=>m(B=>({...B,body:D.target.value})),rows:12,placeholder:"Write your email template...",className:"resize-y"})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:"Description (internal)"}),e.jsx(be,{value:h.description,onChange:D=>m(B=>({...B,description:D.target.value})),placeholder:"Short description for admin reference"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:"Tone"}),e.jsx(be,{value:h.tone,onChange:D=>m(B=>({...B,tone:D.target.value})),placeholder:"e.g. Warm & Casual"})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Tn,{checked:h.is_active,onCheckedChange:D=>m(B=>({...B,is_active:D}))}),e.jsx(se,{children:"Active"})]})]}),e.jsxs(kr,{children:[e.jsx($,{variant:"outline",onClick:()=>c(!1),children:"Cancel"}),e.jsxs($,{onClick:()=>v.mutate({...h,id:r==null?void 0:r.id}),disabled:v.isPending||!h.title||!h.subject||!h.body,children:[v.isPending&&e.jsx(Ht,{className:"h-4 w-4 mr-2 animate-spin"}),r?"Save Changes":"Create Template"]})]})]})}),e.jsx(Os,{open:d,onOpenChange:u,children:e.jsxs(Rs,{className:"sm:max-w-[450px]",children:[e.jsx(Us,{children:e.jsx(zs,{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(se,{children:"Icon"}),e.jsx(be,{value:p.icon,onChange:D=>x(B=>({...B,icon:D.target.value})),className:"text-center text-lg"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:"Name"}),e.jsx(be,{value:p.name,onChange:D=>x(B=>({...B,name:D.target.value})),placeholder:"e.g. Check-in & Stay in Touch"})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:"Description"}),e.jsx(be,{value:p.description,onChange:D=>x(B=>({...B,description:D.target.value})),placeholder:"Brief description of this category"})]})]}),e.jsxs(kr,{children:[e.jsx($,{variant:"outline",onClick:()=>u(!1),children:"Cancel"}),e.jsxs($,{onClick:()=>C.mutate({...p,id:i==null?void 0:i.id}),disabled:C.isPending||!p.name,children:[C.isPending&&e.jsx(Ht,{className:"h-4 w-4 mr-2 animate-spin"}),i?"Save Changes":"Create Category"]})]})]})})]})})}const nvn=({brokerageId:s})=>{var as,Ls,cs;const{toast:t}=gi(),n=Vn(),[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,x]=j.useState(!1),[g,y]=j.useState({}),[b,v]=j.useState(!1),[N,C]=j.useState(!1),[A,T]=j.useState({email:"",name:"",password:"",phone:""}),[P,M]=j.useState(null),[I,D]=j.useState([]),[B,q]=j.useState("none"),[W,V]=j.useState(!1),[K,Q]=j.useState(null),[J,ce]=j.useState(!1),[ue,ne]=j.useState(!1),[ee,le]=j.useState(!1),[he,ve]=j.useState(""),[ge,fe]=j.useState(!1),[je,Ee]=j.useState([]),[Me,De]=j.useState(!1),[ze,ke]=j.useState(!1),[Xe,Se]=j.useState(null),[Re,Ae]=j.useState({name:"",phone:"",email:""}),[Be,qe]=j.useState(!1),[Ke,Ze]=j.useState(!1),[Ue,et]=j.useState(null),[Qe,Ge]=j.useState("asc"),[nt,ft]=j.useState(!1),[lt,Mt]=j.useState(null),[Ft,Ts]=j.useState(!1),[js,zt]=j.useState(null),[Nt,Ds]=j.useState(""),[_t,Xs]=j.useState(!1),[rn,Ps]=j.useState(null);j.useEffect(()=>{gr(),Zs(),_n()},[s]);const _n=async()=>{try{const{data:qt}=await U.from("partnership_programs").select("id, name, enabled").eq("brokerage_id",s).maybeSingle();if(!qt||!qt.enabled){M(null),D([]);return}const{data:Gs}=await U.from("partnership_packages").select("id, name, description, sort_order").eq("program_id",qt.id).order("sort_order",{ascending:!0});M({id:qt.id,name:qt.name}),D(Gs||[]),Gs&&Gs.length>0&&q(Gs[0].id)}catch(qt){console.error("Error loading partnership packages:",qt)}},Zs=async()=>{try{const{data:qt,error:Gs}=await U.from("brokerage_manager_assignments").select("user_id").eq("brokerage_id",s);if(Gs)throw Gs;Ee((qt==null?void 0:qt.map(Vs=>Vs.user_id))||[])}catch(qt){console.error("Error loading brokerage managers:",qt)}},gr=async()=>{try{l(!0);const{data:qt,error:Gs}=await U.functions.invoke("get-brokerage-agents",{body:{brokerageId:s}});if(Gs)throw Gs;const Vs=qt.agents||[];if(a(Vs),Vs.length>0){const Hn=Vs.map(ma=>ma.id),{data:Kr}=await U.from("agent_assistant_assignments").select("agent_id, assistant_id").in("agent_id",Hn);if(Kr&&Kr.length>0){const ma=Kr.map(da=>da.assistant_id),{data:Or}=await U.from("profiles").select("id, name, email").in("id",ma),ta={};for(const da of Kr){const va=Or==null?void 0:Or.find(hi=>hi.id===da.assistant_id);va&&(ta[da.agent_id]={name:va.name||"",email:va.email||""})}y(ta)}else y({})}}catch(qt){console.error("Error loading agents:",qt),t({title:"Error",description:"Failed to load agents",variant:"destructive"})}finally{l(!1)}},Un=async()=>{var qt;if(!A.email||!A.name||!A.password){t({title:"Error",description:"Please fill in all fields",variant:"destructive"});return}C(!0);try{const{data:{session:Gs}}=await U.auth.getSession(),Vs=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/create-user",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${Gs==null?void 0:Gs.access_token}`},body:JSON.stringify({...A,brokerageId:s,partnershipPackageId:P&&B!=="none"?B:void 0})}),Hn=await Vs.json();if(!Vs.ok)throw new Error(Hn.error||"Failed to create agent");t({title:"Success",description:`Agent ${A.email} created successfully`}),T({email:"",name:"",password:"",phone:""}),q(((qt=I[0])==null?void 0:qt.id)||"none"),v(!1),gr()}catch(Gs){console.error("Error creating agent:",Gs),t({title:"Error",description:Gs.message||"Failed to create agent",variant:"destructive"})}finally{C(!1)}},In=async qt=>{try{const{data:{session:Gs}}=await U.auth.getSession(),Vs=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/resend-welcome-email",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${Gs==null?void 0:Gs.access_token}`},body:JSON.stringify({userId:qt})}),Hn=await Vs.json();if(!Vs.ok)throw new Error(Hn.error||"Failed to resend welcome email");t({title:"Success",description:"Welcome email sent successfully"})}catch(Gs){console.error("Error resending welcome email:",Gs),t({title:"Error",description:Gs.message||"Failed to resend welcome email",variant:"destructive"})}},Ar=async(qt,Gs)=>{try{const{error:Vs}=await U.functions.invoke("send-password-reset",{body:{email:qt,redirectTo:window.location.origin}});if(Vs)throw Vs;t({title:"Password Reset Sent",description:`Password reset email sent to ${Gs}`})}catch(Vs){console.error("Error sending password reset:",Vs),t({title:"Error",description:Vs.message||"Failed to send password reset email",variant:"destructive"})}},or=qt=>{Q(qt),V(!0)},qs=qt=>{Se(qt),Ae({name:qt.name,phone:qt.phone||"",email:qt.email}),ke(!0)},yr=async()=>{if(!Xe)return;if(!Re.name.trim()){t({title:"Error",description:"Name is required",variant:"destructive"});return}const qt=Re.email.trim().toLowerCase()!==Xe.email.toLowerCase();qe(!0);try{if(qt){if(!Re.email.trim())throw new Error("Email is required");Ze(!0);const{data:{session:Vs}}=await U.auth.getSession(),Hn=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/update-agent-email",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${Vs==null?void 0:Vs.access_token}`},body:JSON.stringify({agentId:Xe.id,newEmail:Re.email.trim(),brokerageId:s})}),Kr=await Hn.json();if(Ze(!1),!Hn.ok)throw new Error(Kr.error||"Failed to update email")}const{error:Gs}=await U.from("profiles").update({name:Re.name.trim(),phone:Re.phone.trim()||null}).eq("id",Xe.id);if(Gs)throw Gs;t({title:"Success",description:"Agent profile updated successfully"}),ke(!1),Se(null),gr()}catch(Gs){console.error("Error updating agent:",Gs),t({title:"Error",description:Gs.message||"Failed to update agent",variant:"destructive"})}finally{qe(!1),Ze(!1)}},fn=async()=>{if(!he){t({title:"Error",description:"Please select an agent to promote",variant:"destructive"});return}fe(!0);try{const{data:{session:qt}}=await U.auth.getSession(),Gs=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/manage-user-roles",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${qt==null?void 0:qt.access_token}`},body:JSON.stringify({userId:he,role:"brokerage_manager",action:"add",brokerageId:s})}),Vs=await Gs.json();if(!Gs.ok)throw new Error(Vs.error||"Failed to add brokerage manager");t({title:"Success",description:"Brokerage manager added successfully"}),le(!1),ve(""),Zs()}catch(qt){console.error("Error adding brokerage manager:",qt),t({title:"Error",description:qt.message||"Failed to add brokerage manager",variant:"destructive"})}finally{fe(!1)}},Zn=async qt=>{try{const{data:{session:Gs}}=await U.auth.getSession(),Vs=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/manage-user-roles",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${Gs==null?void 0:Gs.access_token}`},body:JSON.stringify({userId:qt,role:"brokerage_manager",action:"remove",brokerageId:s})}),Hn=await Vs.json();if(!Vs.ok)throw new Error(Hn.error||"Failed to remove brokerage manager");t({title:"Success",description:"Brokerage manager role removed"}),Zs()}catch(Gs){console.error("Error removing brokerage manager:",Gs),t({title:"Error",description:Gs.message||"Failed to remove brokerage manager",variant:"destructive"})}},Xt=qt=>je.includes(qt),rr=qt=>{zt(qt),Ds(""),Ts(!0)},Qn=async()=>{if(!(!js||!Nt)){if(Nt.length<6){t({title:"Error",description:"Password must be at least 6 characters",variant:"destructive"});return}Xs(!0);try{const{data:{session:qt}}=await U.auth.getSession(),Gs=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/update-agent-email",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${qt==null?void 0:qt.access_token}`},body:JSON.stringify({agentId:js.id,brokerageId:s,action:"set_password",newPassword:Nt})}),Vs=await Gs.json();if(!Gs.ok)throw new Error(Vs.error||"Failed to set password");t({title:"Success",description:`Password set for ${js.name}`}),Ts(!1),zt(null),Ds("")}catch(qt){console.error("Error setting password:",qt),t({title:"Error",description:qt.message||"Failed to set password",variant:"destructive"})}finally{Xs(!1)}}},Sn=async qt=>{Ps(qt.id);try{const{data:{session:Gs}}=await U.auth.getSession(),Vs=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/update-agent-email",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${Gs==null?void 0:Gs.access_token}`},body:JSON.stringify({agentId:qt.id,brokerageId:s,action:"claim_account"})}),Hn=await Vs.json();if(!Vs.ok)throw new Error(Hn.error||"Failed to claim account");t({title:"Success",description:`Account claimed for ${qt.name}`}),gr()}catch(Gs){console.error("Error claiming account:",Gs),t({title:"Error",description:Gs.message||"Failed to claim account",variant:"destructive"})}finally{Ps(null)}},$n=async()=>{if(K){ce(!0);try{const{data:{session:qt}}=await U.auth.getSession(),Gs=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/remove-agent",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${qt==null?void 0:qt.access_token}`},body:JSON.stringify({userId:K.id,brokerageId:s})}),Vs=await Gs.json();if(!Gs.ok)throw new Error(Vs.error||"Failed to remove agent");t({title:"Success",description:`${K.name} has been removed from your brokerage`}),V(!1),Q(null),gr()}catch(qt){console.error("Error removing agent:",qt),t({title:"Error",description:qt.message||"Failed to remove agent",variant:"destructive"})}finally{ce(!1)}}},tn=qt=>{const Gs=qt.trim().split(" ");return Gs.length>1?Gs[Gs.length-1].toLowerCase():qt.toLowerCase()},ln=qt=>{Ue===qt?Ge(Qe==="asc"?"desc":"asc"):(et(qt),Ge("asc"))},Cr=qt=>Ue!==qt?e.jsx(Tx,{className:"ml-1 h-4 w-4"}):Qe==="asc"?e.jsx(sp,{className:"ml-1 h-4 w-4"}):e.jsx(ax,{className:"ml-1 h-4 w-4"}),ms=r.filter(qt=>{if(d==="active"&&!qt.claimed||d==="pending"&&qt.claimed)return!1;if(!o)return!0;const Gs=o.toLowerCase();return qt.name.toLowerCase().includes(Gs)||qt.email.toLowerCase().includes(Gs)}),ot=[...ms].sort((qt,Gs)=>{if(!Ue)return 0;let Vs=0;return Ue==="name"?Vs=tn(qt.name).localeCompare(tn(Gs.name)):Ue==="status"&&(Vs=qt.claimed===Gs.claimed?0:qt.claimed?-1:1),Qe==="asc"?Vs:-Vs});ms.filter(qt=>qt.claimed&&!Xt(qt.id));const pt=qt=>{m(Gs=>{const Vs=new Set(Gs);return Vs.has(qt)?Vs.delete(qt):Vs.add(qt),Vs})},vt=()=>{h.size===ot.length?m(new Set):m(new Set(ot.map(qt=>qt.id)))},At=()=>{m(new Set)},Zt=async()=>{const qt=Array.from(h);if(qt.length===0)return;x(!0);let Gs=0,Vs=0;try{const{data:{session:Hn}}=await U.auth.getSession();for(const Kr of qt)try{(await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/resend-welcome-email",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${Hn==null?void 0:Hn.access_token}`},body:JSON.stringify({userId:Kr})})).ok?Gs++:Vs++}catch{Vs++}Gs>0?t({title:"Success",description:`Welcome emails sent to ${Gs} agent${Gs>1?"s":""}${Vs>0?` (${Vs} failed)`:""}`}):t({title:"Error",description:"Failed to send welcome emails",variant:"destructive"}),At()}catch(Hn){console.error("Error bulk sending welcome emails:",Hn),t({title:"Error",description:Hn.message||"Failed to send welcome emails",variant:"destructive"})}finally{x(!1)}};return i?e.jsx(_e,{children:e.jsx(Oe,{className:"flex items-center justify-center py-8",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})})}):e.jsxs(e.Fragment,{children:[e.jsxs(_e,{children:[e.jsx(Bt,{children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(Ut,{children:"Agents"}),e.jsx(vr,{children:"Manage your brokerage's agents"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs($,{variant:"outline",onClick:()=>le(!0),children:[e.jsx(kf,{className:"mr-2 h-4 w-4"}),"Add Brokerage Manager"]}),e.jsxs($,{variant:"outline",onClick:()=>ne(!0),children:[e.jsx(PN,{className:"mr-2 h-4 w-4"}),"Import CSV"]}),e.jsxs($,{onClick:()=>v(!0),children:[e.jsx(il,{className:"mr-2 h-4 w-4"}),"Add Agent"]})]})]})}),e.jsxs(Oe,{children:[e.jsxs("div",{className:"mb-4 flex flex-col gap-4 sm:flex-row sm:items-center",children:[e.jsxs("div",{className:"relative flex-1",children:[e.jsx(Vr,{className:"absolute left-3 top-3 h-4 w-4 text-muted-foreground"}),e.jsx(be,{placeholder:"Search agents...",value:o,onChange:qt=>c(qt.target.value),className:"pl-9"})]}),e.jsxs(vs,{value:d,onValueChange:qt=>u(qt),children:[e.jsx(gs,{className:"w-[160px]",children:e.jsx(bs,{placeholder:"Filter by status"})}),e.jsxs(ys,{children:[e.jsx(Ye,{value:"all",children:"All Agents"}),e.jsx(Ye,{value:"active",children:"Active"}),e.jsx(Ye,{value:"pending",children:"Pending"})]})]})]}),h.size>0&&e.jsxs("div",{className:"mb-4 flex items-center gap-3 rounded-lg border bg-muted/50 p-3",children:[e.jsxs("span",{className:"text-sm font-medium",children:[h.size," agent",h.size>1?"s":""," selected"]}),e.jsx("div",{className:"flex-1"}),e.jsxs($,{size:"sm",variant:"outline",onClick:()=>{const Gs=r.filter(Vs=>h.has(Vs.id)&&Vs.email).map(Vs=>({email:Vs.email,name:Vs.name}));sessionStorage.setItem("campaign_direct_recipients",JSON.stringify(Gs)),n("/admin/email-campaigns/new?directMode=1",{state:{directRecipients:Gs}})},disabled:p,children:[e.jsx(Eh,{className:"mr-2 h-4 w-4"}),"Email Agents (",h.size,")"]}),e.jsxs($,{size:"sm",variant:"outline",onClick:Zt,disabled:p,children:[e.jsx(nn,{className:"mr-2 h-4 w-4"}),p?"Sending...":"Resend Welcome Email"]}),e.jsx($,{size:"sm",variant:"ghost",onClick:At,children:"Clear"})]}),e.jsx("div",{className:"rounded-md border",children:e.jsxs(Va,{children:[e.jsx(Ha,{children:e.jsxs(hn,{children:[e.jsx(Lt,{className:"w-[40px]",children:e.jsx(ui,{checked:ot.length>0&&h.size===ot.length,onCheckedChange:vt,"aria-label":"Select all"})}),e.jsx(Lt,{children:e.jsxs($,{variant:"ghost",size:"sm",className:"-ml-3 h-8 hover:bg-transparent",onClick:()=>ln("name"),children:["Name (Last)",Cr("name")]})}),e.jsx(Lt,{children:"Email"}),e.jsx(Lt,{children:e.jsxs($,{variant:"ghost",size:"sm",className:"-ml-3 h-8 hover:bg-transparent",onClick:()=>ln("status"),children:["Status",Cr("status")]})}),e.jsx(Lt,{children:"Actions"})]})}),e.jsx(Ga,{children:ot.length===0?e.jsx(hn,{children:e.jsx(gt,{colSpan:5,className:"text-center text-muted-foreground",children:"No agents found"})}):ot.map(qt=>e.jsxs(hn,{children:[e.jsx(gt,{children:e.jsx(ui,{checked:h.has(qt.id),onCheckedChange:()=>pt(qt.id),"aria-label":`Select ${qt.name}`})}),e.jsx(gt,{className:"font-medium",children:qt.name}),e.jsx(gt,{children:qt.email}),e.jsx(gt,{children:e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[qt.claimed?e.jsx($e,{variant:"default",children:"Active"}):e.jsx($e,{variant:"secondary",children:"Pending"}),Xt(qt.id)&&e.jsxs($e,{variant:"outline",className:"border-primary text-primary",children:[e.jsx(j0,{className:"mr-1 h-3 w-3"}),"Manager"]}),g[qt.id]&&e.jsxs($e,{variant:"outline",className:"text-xs",children:[e.jsx(qn,{className:"mr-1 h-3 w-3"}),"Asst: ",g[qt.id].name||g[qt.id].email]})]})}),e.jsx(gt,{children:e.jsxs("div",{className:"flex items-center gap-1 flex-wrap",children:[e.jsx($,{size:"sm",variant:"ghost",onClick:()=>{Mt(qt),ft(!0)},title:"Send celebration",className:"text-yellow-500 hover:text-yellow-600 hover:bg-yellow-50",children:e.jsx(Nf,{className:"h-4 w-4"})}),e.jsx($,{size:"sm",variant:"ghost",onClick:()=>qs(qt),title:"Edit agent",children:e.jsx(Ya,{className:"h-4 w-4"})}),!qt.claimed&&e.jsxs(e.Fragment,{children:[e.jsx($,{size:"sm",variant:"ghost",onClick:()=>In(qt.id),title:"Resend welcome email",children:e.jsx(nn,{className:"h-4 w-4"})}),e.jsx($,{size:"sm",variant:"ghost",onClick:()=>Sn(qt),title:"Claim account for agent",disabled:rn===qt.id,className:"text-green-600 hover:text-green-700 hover:bg-green-50",children:e.jsx(Yj,{className:"h-4 w-4"})})]}),e.jsx($,{size:"sm",variant:"ghost",onClick:()=>rr(qt),title:"Set password",className:"text-blue-600 hover:text-blue-700 hover:bg-blue-50",children:e.jsx(Ad,{className:"h-4 w-4"})}),e.jsx($,{size:"sm",variant:"ghost",onClick:()=>Ar(qt.email,qt.name),title:"Send password reset email",children:e.jsx(q3,{className:"h-4 w-4"})}),Xt(qt.id)&&e.jsx($,{size:"sm",variant:"ghost",onClick:()=>Zn(qt.id),title:"Remove manager role",className:"text-orange-500 hover:text-orange-600",children:e.jsx(kf,{className:"h-4 w-4"})}),e.jsx($,{size:"sm",variant:"ghost",onClick:()=>or(qt),className:"text-destructive hover:text-destructive",title:"Remove agent",children:e.jsx(Pn,{className:"h-4 w-4"})})]})})]},qt.id))})]})})]})]}),e.jsx(Os,{open:b,onOpenChange:v,children:e.jsxs(Rs,{children:[e.jsxs(Us,{children:[e.jsx(zs,{children:"Add New Agent"}),e.jsx(Sr,{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(se,{htmlFor:"name",children:"Name"}),e.jsx(be,{id:"name",value:A.name,onChange:qt=>T({...A,name:qt.target.value}),placeholder:"John Doe"})]}),e.jsxs("div",{children:[e.jsx(se,{htmlFor:"email",children:"Email"}),e.jsx(be,{id:"email",type:"email",value:A.email,onChange:qt=>T({...A,email:qt.target.value}),placeholder:"john@example.com"})]}),e.jsxs("div",{children:[e.jsx(se,{htmlFor:"phone",children:"Phone (optional)"}),e.jsx(be,{id:"phone",type:"tel",value:A.phone,onChange:qt=>T({...A,phone:qt.target.value}),placeholder:"555-123-4567"})]}),e.jsxs("div",{children:[e.jsx(se,{htmlFor:"password",children:"Temporary Password"}),e.jsx(be,{id:"password",type:"password",value:A.password,onChange:qt=>T({...A,password:qt.target.value}),placeholder:"Temporary password"})]}),P&&I.length>0&&e.jsxs("div",{children:[e.jsxs(se,{htmlFor:"package",children:[P.name," Package"]}),e.jsxs(vs,{value:B,onValueChange:q,children:[e.jsx(gs,{id:"package",children:e.jsx(bs,{placeholder:"Choose a package"})}),e.jsxs(ys,{children:[I.map(qt=>e.jsx(Ye,{value:qt.id,children:qt.name},qt.id)),e.jsx(Ye,{value:"none",children:"No package (full access)"})]})]}),e.jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:B==="none"?"Agent gets unrestricted LevelUp access.":((as=I.find(qt=>qt.id===B))==null?void 0:as.description)||"Their welcome email will list what is included in this package."})]})]}),e.jsxs(kr,{children:[e.jsx($,{variant:"outline",onClick:()=>v(!1),children:"Cancel"}),e.jsx($,{onClick:Un,disabled:N,children:N?"Creating...":"Create Agent"})]})]})}),e.jsx(Os,{open:W,onOpenChange:V,children:e.jsxs(Rs,{children:[e.jsxs(Us,{children:[e.jsx(zs,{children:"Remove Agent"}),e.jsxs(Sr,{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(kr,{children:[e.jsx($,{variant:"outline",onClick:()=>V(!1),children:"Cancel"}),e.jsx($,{variant:"destructive",onClick:$n,disabled:J,children:J?"Removing...":"Remove Agent"})]})]})}),e.jsx(u8t,{open:ue,onOpenChange:ne,fixedBrokerageId:s,onSuccess:gr}),e.jsx(Os,{open:ee,onOpenChange:le,children:e.jsxs(Rs,{children:[e.jsxs(Us,{children:[e.jsx(zs,{children:"Add Brokerage Manager"}),e.jsx(Sr,{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(se,{children:"Select Agent"}),e.jsxs(Sc,{open:Me,onOpenChange:De,children:[e.jsx(Cc,{asChild:!0,children:e.jsxs($,{variant:"outline",role:"combobox","aria-expanded":Me,className:"w-full justify-between",children:[he?((Ls=r.find(qt=>qt.id===he))==null?void 0:Ls.name)+" ("+((cs=r.find(qt=>qt.id===he))==null?void 0:cs.email)+")":"Select an agent to promote...",e.jsx(sw,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(xc,{className:"w-full p-0",align:"start",children:e.jsxs(pw,{children:[e.jsx(fw,{placeholder:"Search by name or email..."}),e.jsxs(xw,{className:"max-h-[200px]",children:[e.jsx(gw,{children:"No eligible agents found."}),e.jsx($b,{children:r.filter(qt=>!Xt(qt.id)).map(qt=>e.jsxs(iv,{value:`${qt.name} ${qt.email}`,onSelect:()=>{ve(qt.id),De(!1)},children:[e.jsx(oa,{className:`mr-2 h-4 w-4 ${he===qt.id?"opacity-100":"opacity-0"}`}),qt.name," (",qt.email,")"]},qt.id))})]})]})})]}),r.filter(qt=>!Xt(qt.id)).length===0&&e.jsx("p",{className:"mt-2 text-sm text-muted-foreground",children:"All agents are already brokerage managers."})]})}),e.jsxs(kr,{children:[e.jsx($,{variant:"outline",onClick:()=>le(!1),children:"Cancel"}),e.jsx($,{onClick:fn,disabled:ge||!he,children:ge?"Adding...":"Add as Manager"})]})]})}),e.jsx(Os,{open:ze,onOpenChange:ke,children:e.jsxs(Rs,{children:[e.jsxs(Us,{children:[e.jsx(zs,{children:"Edit Agent"}),e.jsxs(Sr,{children:["Update profile information for ",Xe==null?void 0:Xe.name]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(se,{htmlFor:"edit-name",children:"Name"}),e.jsx(be,{id:"edit-name",value:Re.name,onChange:qt=>Ae({...Re,name:qt.target.value}),placeholder:"Agent name"})]}),e.jsxs("div",{children:[e.jsx(se,{htmlFor:"edit-email",children:"Email"}),e.jsx(be,{id:"edit-email",type:"email",value:Re.email,onChange:qt=>Ae({...Re,email:qt.target.value}),placeholder:"agent@example.com"}),Re.email.trim().toLowerCase()!==(Xe==null?void 0:Xe.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(se,{htmlFor:"edit-phone",children:"Phone"}),e.jsx(be,{id:"edit-phone",type:"tel",value:Re.phone,onChange:qt=>Ae({...Re,phone:qt.target.value}),placeholder:"555-123-4567"})]})]}),e.jsxs(kr,{children:[e.jsx($,{variant:"outline",onClick:()=>ke(!1),children:"Cancel"}),e.jsx($,{onClick:yr,disabled:Be||Ke,children:Ke?"Updating email...":Be?"Saving...":"Save Changes"})]})]})}),lt&&e.jsx(h8t,{open:nt,onOpenChange:qt=>{ft(qt),qt||Mt(null)},userId:lt.id,userName:lt.name}),e.jsx(Os,{open:Ft,onOpenChange:Ts,children:e.jsxs(Rs,{children:[e.jsxs(Us,{children:[e.jsx(zs,{children:"Set Password"}),e.jsxs(Sr,{children:["Set a new password for ",js==null?void 0:js.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(se,{htmlFor:"new-password",children:"New Password"}),e.jsx(be,{id:"new-password",type:"password",value:Nt,onChange:qt=>Ds(qt.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(kr,{children:[e.jsx($,{variant:"outline",onClick:()=>Ts(!1),children:"Cancel"}),e.jsx($,{onClick:Qn,disabled:_t||!Nt||Nt.length<6,children:_t?"Setting...":"Set Password"})]})]})})]})},rvn={academy_video:"Academy Video",template:"Template",toolbox:"Toolbox Resource",newsletter:"Newsletter",social_swag:"Social Swag",event:"Event"},avn={view:"Viewed",click_canva:"Opened Canva",click_pdf:"Downloaded PDF",click_video:"Watched Video",click_link:"Clicked Link",register:"Registered"},ivn=s=>{switch(s){case"academy_video":return e.jsx(Xr,{className:"h-4 w-4"});case"template":return e.jsx(Wr,{className:"h-4 w-4"});case"toolbox":return e.jsx(Wr,{className:"h-4 w-4"});case"newsletter":return e.jsx(Gj,{className:"h-4 w-4"});case"social_swag":return e.jsx(dn,{className:"h-4 w-4"});case"event":return e.jsx(ia,{className:"h-4 w-4"});default:return e.jsx(Tr,{className:"h-4 w-4"})}},ovn=({brokerageId:s})=>{const{toast:t}=gi(),[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:g,error:y}=await U.from("profiles").select("id, name, email").eq("brokerage_id",s);if(y)throw y;const b=g.map(B=>B.id),v=new Map(g.map(B=>[B.id,B]));if(b.length===0){r([]),i([]),o([]);return}const{data:N,error:C}=await U.from("activity_logs").select("*").in("user_id",b).order("launched_at",{ascending:!1});if(C)throw C;const A=N.map(B=>{var q,W;return{id:B.id,user_id:B.user_id,app_name:B.app_name,launched_at:B.launched_at,user_name:((q=v.get(B.user_id))==null?void 0:q.name)||"Unknown",user_email:((W=v.get(B.user_id))==null?void 0:W.email)||"Unknown"}});r(A);const{data:T,error:P}=await U.from("content_engagement_logs").select("*").in("user_id",b).order("created_at",{ascending:!1});if(P)throw P;const M=(T||[]).map(B=>{var q,W;return{id:B.id,user_id:B.user_id,resource_type:B.resource_type,resource_id:B.resource_id,resource_title:B.resource_title,action_type:B.action_type,created_at:B.created_at,user_name:((q=v.get(B.user_id))==null?void 0:q.name)||"Unknown",user_email:((W=v.get(B.user_id))==null?void 0:W.email)||"Unknown"}});i(M);const I=new Map;g.forEach(B=>{I.set(B.id,{user_id:B.id,user_name:B.name,user_email:B.email,app_launches:0,content_views:0,last_activity:""})}),A.forEach(B=>{const q=I.get(B.user_id);q&&(q.app_launches++,(!q.last_activity||new Date(B.launched_at)>new Date(q.last_activity))&&(q.last_activity=B.launched_at))}),M.forEach(B=>{const q=I.get(B.user_id);q&&(q.content_views++,(!q.last_activity||new Date(B.created_at)>new Date(q.last_activity))&&(q.last_activity=B.created_at))});const D=Array.from(I.values()).filter(B=>B.app_launches>0||B.content_views>0).sort((B,q)=>new Date(q.last_activity).getTime()-new Date(B.last_activity).getTime());o(D)}catch(g){console.error("Error loading activity:",g),t({title:"Error",description:"Failed to load activity logs",variant:"destructive"})}finally{d(!1)}},p=g=>n.filter(y=>y.user_id===g),x=g=>a.filter(y=>y.user_id===g);return c?e.jsx(_e,{children:e.jsx(Oe,{className:"flex items-center justify-center py-8",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})})}):e.jsxs(e.Fragment,{children:[e.jsxs(_e,{children:[e.jsxs(Bt,{children:[e.jsx(Ut,{children:"Agent Activity"}),e.jsx(vr,{children:"Track app usage and content engagement - click an agent for details"})]}),e.jsx(Oe,{children:e.jsx("div",{className:"rounded-md border",children:e.jsxs(Va,{children:[e.jsx(Ha,{children:e.jsxs(hn,{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(Ga,{children:l.length===0?e.jsx(hn,{children:e.jsx(gt,{colSpan:4,className:"text-center text-muted-foreground",children:"No activity yet"})}):l.map(g=>e.jsxs(hn,{className:"cursor-pointer hover:bg-muted/50 transition-colors",onClick:()=>h({id:g.user_id,name:g.user_name,email:g.user_email}),children:[e.jsx(gt,{children:e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:g.user_name}),e.jsx("div",{className:"text-sm text-muted-foreground",children:g.user_email})]})}),e.jsx(gt,{className:"text-center",children:e.jsxs($e,{variant:"outline",className:"gap-1",children:[e.jsx(Td,{className:"h-3 w-3"}),g.app_launches]})}),e.jsx(gt,{className:"text-center",children:e.jsxs($e,{variant:"secondary",className:"gap-1",children:[e.jsx(Wr,{className:"h-3 w-3"}),g.content_views]})}),e.jsx(gt,{className:"text-sm text-muted-foreground",children:g.last_activity&&fc(new Date(g.last_activity),{addSuffix:!0})})]},g.user_id))})]})})})]}),e.jsx(Os,{open:!!u,onOpenChange:g=>!g&&h(null),children:e.jsxs(Rs,{className:"max-w-3xl max-h-[80vh] overflow-hidden flex flex-col",children:[e.jsxs(Us,{children:[e.jsxs(zs,{children:[u==null?void 0:u.name,"'s Activity"]}),e.jsx(Sr,{children:u==null?void 0:u.email})]}),e.jsxs(ua,{defaultValue:"content",className:"flex-1 overflow-hidden flex flex-col",children:[e.jsxs(ha,{className:"grid w-full grid-cols-2",children:[e.jsx(Qt,{value:"content",children:"Content Engagement"}),e.jsx(Qt,{value:"apps",children:"App Launches"})]}),e.jsx(Jt,{value:"content",className:"flex-1 overflow-auto",children:e.jsx("div",{className:"rounded-md border",children:e.jsxs(Va,{children:[e.jsx(Ha,{children:e.jsxs(hn,{children:[e.jsx(Lt,{children:"Resource"}),e.jsx(Lt,{children:"Type"}),e.jsx(Lt,{children:"Action"}),e.jsx(Lt,{children:"Time"})]})}),e.jsx(Ga,{children:u&&x(u.id).length===0?e.jsx(hn,{children:e.jsx(gt,{colSpan:4,className:"text-center text-muted-foreground",children:"No content engagement yet"})}):u&&x(u.id).map(g=>e.jsxs(hn,{children:[e.jsx(gt,{className:"max-w-[200px] truncate font-medium",children:g.resource_title}),e.jsx(gt,{children:e.jsxs($e,{variant:"outline",className:"gap-1",children:[ivn(g.resource_type),rvn[g.resource_type]||g.resource_type]})}),e.jsx(gt,{children:e.jsx("span",{className:"text-sm text-muted-foreground",children:avn[g.action_type]||g.action_type})}),e.jsx(gt,{className:"text-sm text-muted-foreground",children:fc(new Date(g.created_at),{addSuffix:!0})})]},g.id))})]})})}),e.jsx(Jt,{value:"apps",className:"flex-1 overflow-auto",children:e.jsx("div",{className:"rounded-md border",children:e.jsxs(Va,{children:[e.jsx(Ha,{children:e.jsxs(hn,{children:[e.jsx(Lt,{children:"App"}),e.jsx(Lt,{children:"Time"})]})}),e.jsx(Ga,{children:u&&p(u.id).length===0?e.jsx(hn,{children:e.jsx(gt,{colSpan:2,className:"text-center text-muted-foreground",children:"No app launches yet"})}):u&&p(u.id).map(g=>e.jsxs(hn,{children:[e.jsx(gt,{children:e.jsx($e,{variant:"outline",children:g.app_name})}),e.jsx(gt,{className:"text-sm text-muted-foreground",children:fc(new Date(g.launched_at),{addSuffix:!0})})]},g.id))})]})})})]})]})})]})},lvn=({brokerageId:s})=>{const{toast:t}=gi(),[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 U.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 U.from("profiles").select("id, email").in("id",d);if(m)throw m;const{count:p}=await U.from("profiles").select("*",{count:"exact",head:!0}).eq("brokerage_id",s).not("last_login","is",null),x=p||0,g=u-x,{count:y}=await U.from("activity_logs").select("*",{count:"exact",head:!0}).in("user_id",d),b=new Date;b.setDate(b.getDate()-7);const{count:v}=await U.from("activity_logs").select("*",{count:"exact",head:!0}).in("user_id",d).gte("launched_at",b.toISOString()),N=new Date;N.setMonth(N.getMonth()-1);const{count:C}=await U.from("activity_logs").select("*",{count:"exact",head:!0}).in("user_id",d).gte("launched_at",N.toISOString());r({totalAgents:u,activeAgents:x,pendingAgents:g,totalLaunches:y||0,launchesThisWeek:v||0,launchesThisMonth:C||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(_e,{children:e.jsx(Oe,{className:"flex items-center justify-center py-8",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})})}):e.jsxs("div",{className:"grid gap-4 md:grid-cols-2 lg:grid-cols-3",children:[e.jsxs(_e,{children:[e.jsxs(Bt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Ut,{className:"text-sm font-medium",children:"Total Agents"}),e.jsx(qn,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Oe,{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(_e,{children:[e.jsxs(Bt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Ut,{className:"text-sm font-medium",children:"Active Agents"}),e.jsx(Ro,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Oe,{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(_e,{children:[e.jsxs(Bt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Ut,{className:"text-sm font-medium",children:"Pending Invites"}),e.jsx(Hr,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Oe,{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(_e,{children:[e.jsxs(Bt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Ut,{className:"text-sm font-medium",children:"Total App Launches"}),e.jsx(zp,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Oe,{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(_e,{children:[e.jsxs(Bt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Ut,{className:"text-sm font-medium",children:"This Week"}),e.jsx(zp,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Oe,{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(_e,{children:[e.jsxs(Bt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Ut,{className:"text-sm font-medium",children:"This Month"}),e.jsx(zp,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Oe,{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"})]})]})]})},cvn=({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:b,error:v}=await U.from("invite_codes").select("*").eq("brokerage_id",s).order("created_at",{ascending:!1});if(v)throw v;n(b||[])}catch(b){console.error("Error loading invite codes:",b),ae.error("Failed to load invite links")}finally{a(!1)}},m=()=>Math.random().toString(36).substring(2,8).toUpperCase(),p=async()=>{l(!0);try{const b=m(),{error:v}=await U.from("invite_codes").insert({code:b,description:d.description||null,max_uses:d.maxUses?parseInt(d.maxUses):null,brokerage_id:s,is_active:!0});if(v)throw v;ae.success("Invite link created!"),c(!1),u({description:"",maxUses:""}),h()}catch(b){console.error("Error creating invite code:",b),ae.error("Failed to create invite link")}finally{l(!1)}},x=async b=>{try{const{error:v}=await U.from("invite_codes").delete().eq("id",b);if(v)throw v;ae.success("Invite link deleted"),n(t.filter(N=>N.id!==b))}catch(v){console.error("Error deleting invite code:",v),ae.error("Failed to delete invite link")}},g=async(b,v)=>{try{const{error:N}=await U.from("invite_codes").update({is_active:!v}).eq("id",b);if(N)throw N;n(t.map(C=>C.id===b?{...C,is_active:!v}:C)),ae.success(`Invite link ${v?"deactivated":"activated"}`)}catch(N){console.error("Error toggling invite code:",N),ae.error("Failed to update invite link")}},y=b=>{const v=`${window.location.origin}/join?code=${b}`;navigator.clipboard.writeText(v),ae.success("Link copied to clipboard!")};return r?e.jsx(_e,{children:e.jsx(Oe,{className:"flex items-center justify-center py-8",children:e.jsx(Ht,{className:"h-6 w-6 animate-spin text-muted-foreground"})})}):e.jsxs(_e,{children:[e.jsxs(Bt,{className:"flex flex-row items-center justify-between",children:[e.jsxs("div",{children:[e.jsxs(Ut,{className:"flex items-center gap-2",children:[e.jsx(kc,{className:"h-5 w-5"}),"Agent Invite Links"]}),e.jsx(vr,{children:"Create shareable links for agents to join your brokerage"})]}),e.jsxs(Os,{open:o,onOpenChange:c,children:[e.jsx(Ko,{asChild:!0,children:e.jsxs($,{size:"sm",children:[e.jsx(sn,{className:"mr-2 h-4 w-4"}),"Create Link"]})}),e.jsxs(Rs,{children:[e.jsxs(Us,{children:[e.jsx(zs,{children:"Create Invite Link"}),e.jsx(Sr,{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(se,{htmlFor:"description",children:"Description (optional)"}),e.jsx(be,{id:"description",placeholder:"e.g., New agent recruiting campaign",value:d.description,onChange:b=>u({...d,description:b.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"maxUses",children:"Max Uses (optional)"}),e.jsx(be,{id:"maxUses",type:"number",placeholder:"Leave empty for unlimited",value:d.maxUses,onChange:b=>u({...d,maxUses:b.target.value})})]}),e.jsx($,{onClick:p,disabled:i,className:"w-full",children:i?e.jsxs(e.Fragment,{children:[e.jsx(Ht,{className:"mr-2 h-4 w-4 animate-spin"}),"Creating..."]}):"Create Invite Link"})]})]})]})]}),e.jsx(Oe,{children:t.length===0?e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(kc,{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(b=>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:b.code}),e.jsx($e,{variant:b.is_active?"default":"secondary",children:b.is_active?"Active":"Inactive"})]}),b.description&&e.jsx("p",{className:"text-sm text-muted-foreground mt-1 truncate",children:b.description}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-1",children:[b.uses_count," uses",b.max_uses&&` / ${b.max_uses} max`]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx($,{variant:"ghost",size:"sm",onClick:()=>y(b.code),title:"Copy link",children:e.jsx(Ca,{className:"h-4 w-4"})}),e.jsx($,{variant:"ghost",size:"sm",onClick:()=>g(b.id,b.is_active),title:b.is_active?"Deactivate":"Activate",children:b.is_active?"Disable":"Enable"}),e.jsx($,{variant:"ghost",size:"sm",onClick:()=>x(b.id),className:"text-destructive hover:text-destructive",title:"Delete",children:e.jsx(Pn,{className:"h-4 w-4"})})]})]},b.id))})})]})},dvn=({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,x]=j.useState(!1),g=C=>/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(C),y=()=>{const C=o.trim().toLowerCase();if(C&&g(C)&&!d.includes(C)){if(d.length>=10){ae.error("Maximum 10 emails per invite");return}u([...d,C]),c("")}else C&&!g(C)?ae.error("Please enter a valid email address"):d.includes(C)&&ae.error("Email already added")},b=C=>{u(d.filter(A=>A!==C))},v=C=>{(C.key==="Enter"||C.key===",")&&(C.preventDefault(),y())},N=async()=>{if(d.length===0){ae.error("Please add at least one email address");return}x(!0);try{const{data:C,error:A}=await U.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;C.successCount===C.totalCount?ae.success(`${C.successCount} invite${C.successCount>1?"s":""} sent successfully!`):ae.warning(`${C.successCount} of ${C.totalCount} invites sent. Some failed.`),u([]),m(""),t(!1),l==null||l()}catch(C){console.error("Error sending invites:",C),ae.error("Failed to send invites. Please try again.")}finally{x(!1)}};return e.jsx(Os,{open:s,onOpenChange:t,children:e.jsxs(Rs,{className:"sm:max-w-[550px]",children:[e.jsxs(Us,{children:[e.jsxs(zs,{className:"flex items-center gap-2",children:[e.jsx(nn,{className:"h-5 w-5 text-primary"}),"Invite Broker Friends"]}),e.jsx(Sr,{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(Co,{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(se,{htmlFor:"email",children:"Email Addresses (up to 10)"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(be,{id:"email",type:"email",placeholder:"Enter email and press Enter",value:o,onChange:C=>c(C.target.value),onKeyDown:v,onBlur:y}),e.jsx($,{type:"button",variant:"secondary",onClick:y,children:"Add"})]}),d.length>0&&e.jsx("div",{className:"flex flex-wrap gap-2 mt-2",children:d.map(C=>e.jsxs($e,{variant:"secondary",className:"flex items-center gap-1 pr-1",children:[C,e.jsx("button",{type:"button",onClick:()=>b(C),className:"ml-1 rounded-full p-0.5 hover:bg-muted",children:e.jsx(pr,{className:"h-3 w-3"})})]},C))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"message",children:"Personal Message (optional)"}),e.jsx(Is,{id:"message",placeholder:"Add a personal note that will appear at the top of the email...",value:h,onChange:C=>m(C.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(dn,{className:"h-4 w-4 text-primary"}),"What they'll receive:"]}),e.jsxs("ul",{className:"text-xs text-muted-foreground space-y-1",children:[e.jsxs("li",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"w-1 h-1 rounded-full bg-primary"}),"Beautiful branded email from you"]}),e.jsxs("li",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"w-1 h-1 rounded-full bg-primary"}),"Your personal message (if added)"]}),e.jsxs("li",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"w-1 h-1 rounded-full bg-primary"}),"Key LevelUp features for brokerages"]}),e.jsxs("li",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"w-1 h-1 rounded-full bg-primary"}),"Direct signup link with your referral code"]})]})]})]}),e.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[e.jsx($,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsx($,{onClick: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(Br,{className:"h-4 w-4 mr-2"}),"Send ",d.length>0&&`(${d.length})`," Invite",d.length!==1?"s":""]})})]})]})})},uvn=({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 U.from("referral_invites").select("*").eq("referrer_brokerage_id",s).order("sent_at",{ascending:!1}).limit(20);if(d)throw d;r(c||[])}catch(c){console.error("Error fetching invites:",c)}finally{i(!1)}},o=c=>{switch(c){case"signed_up":return e.jsxs($e,{className:"bg-green-100 text-green-800 gap-1",children:[e.jsx(Ro,{className:"h-3 w-3"}),"Signed Up"]});case"expired":return e.jsxs($e,{variant:"outline",className:"text-muted-foreground gap-1",children:[e.jsx($d,{className:"h-3 w-3"}),"Expired"]});default:return e.jsxs($e,{variant:"secondary",className:"gap-1",children:[e.jsx(Hr,{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(nn,{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 ",Hs(new Date(c.sent_at),"MMM d, yyyy")]})]}),o(c.status)]},c.id))]})},hvn=()=>{const{brokerageId:s,user:t}=_s(),[n,r]=j.useState(null),[a,i]=j.useState(""),[l,o]=j.useState(""),[c,d]=j.useState([]),[u,h]=j.useState(!0),[m,p]=j.useState(!1),[x,g]=j.useState(0);j.useEffect(()=>{s&&y()},[s]);const y=async()=>{try{const[T,P]=await Promise.all([U.from("brokerages").select("name").eq("id",s).single(),t?U.from("profiles").select("name").eq("id",t.id).single():Promise.resolve({data:null})]);T.data&&i(T.data.name),P.data&&o(P.data.name||"A LevelUp Member");const{data:M}=await U.from("referral_codes").select("code").eq("brokerage_id",s).single();if(M)r(M.code);else{const D=`REF${s==null?void 0:s.slice(0,8).toUpperCase()}`;await U.from("referral_codes").insert({brokerage_id:s,code:D}),r(D)}const{data:I}=await U.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)}},b=()=>{const T=`https://dashboard.relevelup.com/?ref=${n}`;navigator.clipboard.writeText(T),ae.success("Referral link copied to clipboard!")},v=c.filter(T=>T.status==="qualified").length,N=c.filter(T=>T.status==="pending").length,C=v*25,A=Math.max(0,Math.ceil((299-C)/25));return u?null:e.jsxs(e.Fragment,{children:[e.jsxs(_e,{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(Co,{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:["$",C]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Monthly Savings"})]}),C>0&&e.jsxs("div",{className:"flex items-center gap-1 text-green-600",children:[e.jsx(Ro,{className:"h-4 w-4"}),e.jsx("span",{className:"text-sm font-medium",children:"Active"})]})]}),A>0&&C<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"})]}),C>=299&&e.jsxs("div",{className:"flex items-center gap-2 text-primary",children:[e.jsx(dn,{className:"h-5 w-5"}),e.jsx("span",{className:"font-bold",children:"FREE Membership Unlocked!"})]})]})})]})}),e.jsxs(Oe,{className:"pt-6 space-y-6",children:[e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-3",children:[e.jsxs($,{onClick:()=>p(!0),className:"w-full",size:"lg",children:[e.jsx(nn,{className:"h-4 w-4 mr-2"}),"Invite Broker Friends"]}),e.jsxs($,{onClick:b,variant:"outline",className:"w-full",size:"lg",children:[e.jsx(Ca,{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(qd,{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:["$",C]}),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(qn,{className:"h-5 w-5 mx-auto text-primary mb-1"}),e.jsx("p",{className:"text-2xl font-bold",children:v}),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(Hr,{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(uvn,{brokerageId:s,refreshTrigger:x}),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 P,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:((P=T.referred_brokerage)==null?void 0:P.name)||((M=T.referred_user)==null?void 0:M.email)||"Pending setup"}),e.jsxs($e,{variant:T.status==="qualified"?"default":T.status==="pending"?"secondary":"destructive",className:T.status==="qualified"?"bg-green-600":"",children:[T.status==="qualified"&&e.jsx(Ro,{className:"h-3 w-3 mr-1"}),T.status]})]},T.id)})]})]})]}),e.jsx(dvn,{open:m,onOpenChange:p,referralCode:n||"",brokerageId:s||"",senderName:l||"A LevelUp Member",brokerageName:a,onInvitesSent:()=>g(T=>T+1)})]})},mvn=({brokerageId:s})=>{const t=Vn(),{teams:n,isLoading:r}=CC(s),{data:a,isLoading:i}=ht({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 U.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:x}=await U.from("profiles").select("id, name, avatar_url").in("id",p),g=new Map((x||[]).map(T=>[T.id,T])),{data:y}=await U.from("innercircle_contacts").select("owner_user_id").in("owner_user_id",m),{data:b}=await U.from("deal_pipeline").select("owner_user_id").in("owner_user_id",m),{data:v}=await U.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 C=new Map;(b||[]).forEach(T=>{C.set(T.owner_user_id,(C.get(T.owner_user_id)||0)+1)});const A=new Map;return(v||[]).forEach(T=>{A.set(T.owner_user_id,(A.get(T.owner_user_id)||0)+1)}),n.map(T=>{const P=h.filter(V=>V.team_id===T.id),M=P.find(V=>V.role==="team_leader"),I=M?g.get(M.user_id):null,D=P.map(V=>V.user_id),B=D.reduce((V,K)=>V+(N.get(K)||0),0),q=D.reduce((V,K)=>V+(C.get(K)||0),0),W=D.reduce((V,K)=>V+(A.get(K)||0),0);return{team_id:T.id,team_name:T.name,member_count:P.length,leader_name:(I==null?void 0:I.name)||null,leader_avatar:(I==null?void 0:I.avatar_url)||null,total_contacts:B,total_deals:q,total_videos:W}})},enabled:n.length>0});if(r||i)return e.jsx("div",{className:"grid gap-4 md:grid-cols-2 lg:grid-cols-3",children:[1,2,3].map(u=>e.jsxs(_e,{children:[e.jsx(Bt,{children:e.jsx(on,{className:"h-5 w-32"})}),e.jsx(Oe,{children:e.jsx(on,{className:"h-24 w-full"})})]},u))});if(n.length===0)return e.jsx(_e,{children:e.jsxs(Oe,{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(qn,{className:"h-12 w-12 text-muted-foreground mb-4"}),e.jsx("h3",{className:"text-lg font-semibold mb-2",children:"No Teams Yet"}),e.jsx("p",{className:"text-muted-foreground mb-4",children:"Create teams to organize your agents and track their performance."}),e.jsx($,{onClick:()=>t("/brokerage/teams"),children:"Manage Teams"})]})});const o=(a||[]).reduce((u,h)=>u+h.member_count,0),c=(a||[]).reduce((u,h)=>u+h.total_contacts,0),d=(a||[]).reduce((u,h)=>u+h.total_deals,0);return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"grid gap-4 grid-cols-2 md:grid-cols-4",children:[e.jsx(_e,{children:e.jsxs(Oe,{className:"pt-6",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground mb-1",children:[e.jsx(qn,{className:"h-4 w-4"})," Teams"]}),e.jsx("p",{className:"text-2xl font-bold",children:n.length})]})}),e.jsx(_e,{children:e.jsxs(Oe,{className:"pt-6",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground mb-1",children:[e.jsx(qn,{className:"h-4 w-4"})," Total Members"]}),e.jsx("p",{className:"text-2xl font-bold",children:o})]})}),e.jsx(_e,{children:e.jsxs(Oe,{className:"pt-6",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground mb-1",children:[e.jsx(hR,{className:"h-4 w-4"})," Total Contacts"]}),e.jsx("p",{className:"text-2xl font-bold",children:c.toLocaleString()})]})}),e.jsx(_e,{children:e.jsxs(Oe,{className:"pt-6",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground mb-1",children:[e.jsx(ix,{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(_e,{className:"hover:shadow-md transition-shadow",children:[e.jsxs(Bt,{className:"pb-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(Ut,{className:"text-lg",children:u.team_name}),e.jsxs($e,{variant:"secondary",children:[u.member_count," members"]})]}),u.leader_name&&e.jsxs("div",{className:"flex items-center gap-2 mt-2",children:[e.jsxs(Ea,{className:"h-6 w-6",children:[e.jsx(ki,{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(Ng,{className:"h-3 w-3 text-amber-500"}),u.leader_name]})]})]}),e.jsx(Oe,{children:e.jsxs("div",{className:"grid grid-cols-3 gap-3 text-center",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-lg font-semibold",children:u.total_contacts.toLocaleString()}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Contacts"})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-lg font-semibold",children:u.total_deals.toLocaleString()}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Deals"})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-lg font-semibold",children:u.total_videos.toLocaleString()}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Videos"})]})]})})]},u.team_id))}),e.jsx("div",{className:"flex justify-end",children:e.jsx($,{variant:"outline",onClick:()=>t("/brokerage/teams"),children:"Manage Teams →"})})]})},pvn=()=>{const{user:s,isBrokerageManager:t,brokerageId:n,isAdmin:r,managedBrokerages:a,selectedBrokerageId:i,setSelectedBrokerageId:l}=_s(),o=Vn(),{toast:c}=gi(),[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?x():a.length===0&&!n&&m(!1)},[s,t,r,p,o,a,i]);const x=async()=>{if(!p){m(!1);return}try{const{data:g,error:y}=await U.from("brokerages").select("name").eq("id",p).single();if(y)throw y;u(g.name)}catch(g){console.error("Error loading brokerage info:",g),c({title:"Error",description:"Failed to load brokerage information",variant:"destructive"})}finally{m(!1)}};return h?e.jsx(Ks,{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(Ks,{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(vs,{value:i||"",onValueChange:l,children:[e.jsxs(gs,{className:"w-[280px]",children:[e.jsx(Ai,{className:"mr-2 h-4 w-4"}),e.jsx(bs,{placeholder:"Select brokerage"})]}),e.jsx(ys,{children:a.map(g=>e.jsx(Ye,{value:g.id,children:g.name},g.id))})]})]}),e.jsxs(ua,{defaultValue:"agents",className:"space-y-4",children:[e.jsxs(ha,{className:"grid w-full grid-cols-4 md:grid-cols-8",children:[e.jsx(Qt,{value:"agents",children:"Agents"}),e.jsx(Qt,{value:"teams",children:"Teams"}),e.jsx(Qt,{value:"invite",children:"Invite Links"}),e.jsx(Qt,{value:"referrals",children:"Referrals"}),e.jsx(Qt,{value:"leaderboard",children:"Leaderboard"}),e.jsx(Qt,{value:"activity",children:"Activity"}),e.jsx(Qt,{value:"analytics",children:"Analytics"}),e.jsx(Qt,{value:"shares",children:"Shares"})]}),e.jsx(Jt,{value:"agents",className:"space-y-4",children:e.jsx(nvn,{brokerageId:p})}),e.jsx(Jt,{value:"teams",className:"space-y-4",children:e.jsx(mvn,{brokerageId:p})}),e.jsx(Jt,{value:"invite",className:"space-y-4",children:e.jsx(cvn,{brokerageId:p})}),e.jsx(Jt,{value:"referrals",className:"space-y-4",children:e.jsx(hvn,{})}),e.jsx(Jt,{value:"leaderboard",className:"space-y-4",children:e.jsx(GLt,{brokerageId:p,title:`${d} Event Leaderboard`,showUserStats:!1})}),e.jsx(Jt,{value:"activity",className:"space-y-4",children:e.jsx(ovn,{brokerageId:p})}),e.jsx(Jt,{value:"analytics",className:"space-y-4",children:e.jsx(lvn,{brokerageId:p})}),e.jsx(Jt,{value:"shares",className:"space-y-4",children:e.jsx(q8t,{brokerageOnly:!0,brokerageId:p})})]})]})}):e.jsx(Ks,{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(Ai,{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 fvn({brokerageId:s,canManage:t}){const{user:n}=_s(),[r,a]=j.useState([]),[i,l]=j.useState(!0),[o,c]=j.useState(!1),[d,u]=j.useState(null),[h,m]=j.useState(null),[p,x]=j.useState(!1),[g,y]=j.useState(""),[b,v]=j.useState(""),[N,C]=j.useState(!1),A=async()=>{try{const{data:D,error:B}=await U.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(B)throw B;const q=D;if(q&&q.length>0){const W=[...new Set(q.map(J=>J.created_by))],{data:V}=await U.from("profiles").select("id, name, avatar_url").in("id",W),K=new Map((V==null?void 0:V.map(J=>[J.id,J]))||[]),Q=q.map(J=>({...J,author:K.get(J.created_by)||{name:"Unknown",avatar_url:null}}));a(Q)}else a([])}catch(D){console.error("Error fetching announcements:",D)}finally{l(!1)}};j.useEffect(()=>{A()},[s]);const T=()=>{y(""),v(""),C(!1),u(null)},P=D=>{D?(u(D),y(D.title),v(D.content),C(D.is_pinned)):T(),c(!0)},M=async()=>{if(!g.trim()||!b.trim()){ae.error("Please fill in all fields");return}x(!0);try{if(d){const{error:D}=await U.from("brokerage_announcements").update({title:g.trim(),content:b.trim(),is_pinned:N,pinned_at:N?new Date().toISOString():null}).eq("id",d.id);if(D)throw D;ae.success("Announcement updated")}else{const{error:D}=await U.from("brokerage_announcements").insert({brokerage_id:s,created_by:n==null?void 0:n.id,title:g.trim(),content:b.trim(),is_pinned:N,pinned_at:N?new Date().toISOString():null});if(D)throw D;ae.success("Announcement created")}c(!1),T(),A()}catch(D){console.error("Error saving announcement:",D),ae.error("Failed to save announcement")}finally{x(!1)}},I=async()=>{if(h)try{const{error:D}=await U.from("brokerage_announcements").delete().eq("id",h);if(D)throw D;ae.success("Announcement deleted"),A()}catch(D){console.error("Error deleting announcement:",D),ae.error("Failed to delete announcement")}finally{m(null)}};return i?e.jsxs(_e,{children:[e.jsx(Bt,{children:e.jsxs(Ut,{className:"flex items-center gap-2",children:[e.jsx(Eh,{className:"h-5 w-5"}),"Announcements"]})}),e.jsx(Oe,{children:e.jsx("div",{className:"animate-pulse space-y-3",children:e.jsx("div",{className:"h-20 bg-muted rounded"})})})]}):e.jsxs(e.Fragment,{children:[e.jsxs(_e,{children:[e.jsxs(Bt,{className:"flex flex-row items-center justify-between space-y-0 pb-4",children:[e.jsxs(Ut,{className:"flex items-center gap-2",children:[e.jsx(Eh,{className:"h-5 w-5 text-primary"}),"Announcements"]}),t&&e.jsxs($,{size:"sm",onClick:()=>P(),className:"gap-1",children:[e.jsx(sn,{className:"h-4 w-4"}),"New"]})]}),e.jsx(Oe,{children:r.length===0?e.jsx("p",{className:"text-sm text-muted-foreground text-center py-4",children:"No announcements yet"}):e.jsx("div",{className:"space-y-4",children:r.map(D=>{var B,q,W,V;return e.jsx("div",{className:`p-4 rounded-lg border ${D.is_pinned?"bg-primary/5 border-primary/20":"bg-muted/30"}`,children:e.jsxs("div",{className:"flex items-start justify-between gap-2",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[D.is_pinned&&e.jsx(CT,{className:"h-3.5 w-3.5 text-primary shrink-0"}),e.jsx("h4",{className:"font-semibold truncate",children:D.title})]}),e.jsx("p",{className:"text-sm text-muted-foreground whitespace-pre-wrap",children:D.content}),e.jsxs("div",{className:"flex items-center gap-2 mt-3 text-xs text-muted-foreground",children:[e.jsxs(Ea,{className:"h-5 w-5",children:[e.jsx(ki,{src:((B=D.author)==null?void 0:B.avatar_url)||void 0}),e.jsx(Ta,{className:"text-[10px]",children:((W=(q=D.author)==null?void 0:q.name)==null?void 0:W.charAt(0))||"?"})]}),e.jsx("span",{children:(V=D.author)==null?void 0:V.name}),e.jsx("span",{children:"•"}),e.jsx("span",{children:Hs(new Date(D.created_at),"MMM d, yyyy")})]})]}),t&&e.jsxs("div",{className:"flex items-center gap-1 shrink-0",children:[e.jsx($,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:()=>P(D),children:e.jsx(Ya,{className:"h-4 w-4"})}),e.jsx($,{variant:"ghost",size:"icon",className:"h-8 w-8 text-destructive hover:text-destructive",onClick:()=>m(D.id),children:e.jsx(Pn,{className:"h-4 w-4"})})]})]})},D.id)})})})]}),e.jsx(Os,{open:o,onOpenChange:c,children:e.jsxs(Rs,{children:[e.jsx(Us,{children:e.jsx(zs,{children:d?"Edit Announcement":"New Announcement"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"title",children:"Title"}),e.jsx(be,{id:"title",value:g,onChange:D=>y(D.target.value),placeholder:"Announcement title..."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"content",children:"Content"}),e.jsx(Is,{id:"content",value:b,onChange:D=>v(D.target.value),placeholder:"Write your announcement...",rows:4})]}),e.jsx("div",{className:"flex items-center justify-between",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Tn,{id:"pinned",checked:N,onCheckedChange:C}),e.jsxs(se,{htmlFor:"pinned",className:"flex items-center gap-1 cursor-pointer",children:[e.jsx(CT,{className:"h-4 w-4"}),"Pin to top"]})]})}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx($,{variant:"outline",onClick:()=>c(!1),children:"Cancel"}),e.jsx($,{onClick:M,disabled:p,children:p?"Saving...":d?"Update":"Create"})]})]})]})}),e.jsx(Ll,{open:!!h,onOpenChange:()=>m(null),children:e.jsxs(yl,{children:[e.jsxs(vl,{children:[e.jsx(_l,{children:"Delete Announcement"}),e.jsx(wl,{children:"Are you sure you want to delete this announcement? This action cannot be undone."})]}),e.jsxs(bl,{children:[e.jsx(jl,{children:"Cancel"}),e.jsx(fl,{onClick:I,className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Delete"})]})]})})]})}function xvn({brokerageId:s,canManage:t=!1}){const{startImpersonation:n,isLoading:r}=aCe(),{user:a}=_s(),[i,l]=j.useState([]),[o,c]=j.useState(!0),[d,u]=j.useState(""),[h,m]=j.useState(new Set);j.useEffect(()=>{(async()=>{try{const{data:g,error:y}=await U.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(g||[]),g&&g.length>0){const b=g.map(N=>N.id),{data:v}=await U.from("agent_assistant_assignments").select("agent_id").in("agent_id",b);v&&m(new Set(v.map(N=>N.agent_id)))}}catch(g){console.error("Error fetching agents:",g)}finally{c(!1)}})()},[s]);const p=i.filter(x=>{var g,y;return x.name.toLowerCase().includes(d.toLowerCase())||x.email.toLowerCase().includes(d.toLowerCase())||((g=x.title)==null?void 0:g.toLowerCase().includes(d.toLowerCase()))||((y=x.areas_served)==null?void 0:y.toLowerCase().includes(d.toLowerCase()))});return o?e.jsxs(_e,{children:[e.jsx(Bt,{children:e.jsxs(Ut,{className:"flex items-center gap-2",children:[e.jsx(qn,{className:"h-5 w-5"}),"Agent Roster"]})}),e.jsx(Oe,{children:e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-4",children:[1,2,3,4].map(x=>e.jsx("div",{className:"animate-pulse",children:e.jsx("div",{className:"h-48 bg-muted rounded-lg"})},x))})})]}):e.jsxs(_e,{children:[e.jsxs(Bt,{className:"flex flex-col sm:flex-row sm:items-center justify-between gap-4 space-y-0",children:[e.jsxs(Ut,{className:"flex items-center gap-2",children:[e.jsx(qn,{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(Vr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(be,{placeholder:"Search agents...",value:d,onChange:x=>u(x.target.value),className:"pl-9"})]})]}),e.jsx(Oe,{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(x=>e.jsx(gvn,{agent:x,hasAssistant:h.has(x.id),canImpersonate:t&&x.id!==(a==null?void 0:a.id),onImpersonate:()=>n(x.id,"/my-brokerage"),impersonationLoading:r},x.id))})})]})}function gvn({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(ki,{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($e,{variant:"outline",className:"text-[10px] mt-1",children:"Has Assistant"})]}),s.bio&&e.jsx("p",{className:"text-xs text-muted-foreground text-center line-clamp-2 mb-3",children:s.bio}),e.jsxs("div",{className:"space-y-1.5 mb-3",children:[s.areas_served&&e.jsxs("div",{className:"flex items-center gap-1.5 text-xs text-muted-foreground",children:[e.jsx(ai,{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(Mx,{children:[e.jsx(Lx,{asChild:!0,children:e.jsx($,{variant:"outline",size:"icon",className:"h-8 w-8 text-blue-600 hover:text-blue-700 hover:bg-blue-50",onClick:r,disabled:a,children:e.jsx(yR,{className:"h-4 w-4"})})}),e.jsxs(tx,{children:["Login as ",s.name]})]}),s.phone&&e.jsx($,{variant:"outline",size:"icon",className:"h-8 w-8",asChild:!0,children:e.jsx("a",{href:`tel:${s.phone}`,title:`Call ${s.name}`,children:e.jsx(ya,{className:"h-4 w-4"})})}),e.jsx($,{variant:"outline",size:"icon",className:"h-8 w-8",asChild:!0,children:e.jsx("a",{href:`mailto:${s.email}`,title:`Email ${s.name}`,children:e.jsx(nn,{className:"h-4 w-4"})})}),s.linkedin_url&&e.jsx($,{variant:"outline",size:"icon",className:"h-8 w-8",asChild:!0,children:e.jsx("a",{href:s.linkedin_url,target:"_blank",rel:"noopener noreferrer",title:"LinkedIn",children:e.jsx(kg,{className:"h-4 w-4"})})}),s.instagram_url&&e.jsx($,{variant:"outline",size:"icon",className:"h-8 w-8",asChild:!0,children:e.jsx("a",{href:s.instagram_url,target:"_blank",rel:"noopener noreferrer",title:"Instagram",children:e.jsx(Qh,{className:"h-4 w-4"})})})]})]})}function yvn({brokerageId:s}){const[t,n]=j.useState([]),[r,a]=j.useState(!0);if(j.useEffect(()=>{(async()=>{try{const{data:c,error:d}=await U.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(g=>g.id),{data:h,error:m}=await U.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(g=>[g.id,g])),x=(h||[]).filter(g=>g.total_points>0).map(g=>{const y=p.get(g.user_id);return{user_id:g.user_id,total_points:g.total_points,name:(y==null?void 0:y.name)||"Unknown",avatar_url:(y==null?void 0:y.avatar_url)||null}});n(x)}catch(c){console.error("Error fetching leaderboard:",c)}finally{a(!1)}})()},[s]),r)return e.jsxs(_e,{children:[e.jsx(Bt,{children:e.jsxs(Ut,{className:"flex items-center gap-2",children:[e.jsx(pl,{className:"h-5 w-5"}),"Team Leaderboard"]})}),e.jsx(Oe,{children:e.jsx("div",{className:"animate-pulse space-y-3",children:[1,2,3].map(o=>e.jsx("div",{className:"h-12 bg-muted rounded"},o))})})]});const i=o=>o===1?"text-yellow-500":o===2?"text-gray-400":o===3?"text-amber-600":"text-muted-foreground",l=o=>o<=3?e.jsx(V3,{className:Tt("h-5 w-5",i(o))}):e.jsx("span",{className:"w-5 text-center text-sm text-muted-foreground",children:o});return e.jsxs(_e,{children:[e.jsx(Bt,{children:e.jsxs(Ut,{className:"flex items-center gap-2",children:[e.jsx(pl,{className:"h-5 w-5 text-primary"}),"Team Leaderboard"]})}),e.jsx(Oe,{children:t.length===0?e.jsx("p",{className:"text-sm text-muted-foreground text-center py-4",children:"No points earned yet. Attend events to earn points!"}):e.jsx("div",{className:"space-y-2",children:t.slice(0,10).map((o,c)=>{const d=o.name.split(" ").map(h=>h[0]).join("").toUpperCase().slice(0,2),u=c+1;return e.jsxs("div",{className:Tt("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(ki,{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 vvn({brokerageId:s}){const t=Vn(),[n,r]=j.useState([]),[a,i]=j.useState(!0);j.useEffect(()=>{(async()=>{try{const{data:c,error:d}=await U.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(g=>g.id),h=new Map(c.map(g=>[g.id,g])),{data:m,error:p}=await U.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 x=(m||[]).map(g=>({id:g.id,slug:g.slug,property_address:g.property_address,city:g.city,price:g.price,property_type:g.property_type,agent_id:g.agent_id,agent:h.get(g.agent_id)||null,photos:g.listing_photos||[]}));r(x)}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(_e,{children:[e.jsx(Bt,{children:e.jsxs(Ut,{className:"flex items-center gap-2",children:[e.jsx(sa,{className:"h-5 w-5"}),"Brokerage Listings"]})}),e.jsx(Oe,{children:e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[1,2].map(o=>e.jsx("div",{className:"animate-pulse",children:e.jsx("div",{className:"h-32 bg-muted rounded-lg"})},o))})})]}):e.jsxs(_e,{children:[e.jsxs(Bt,{className:"flex flex-row items-center justify-between space-y-0 pb-4",children:[e.jsxs(Ut,{className:"flex items-center gap-2",children:[e.jsx(sa,{className:"h-5 w-5 text-primary"}),"Brokerage Listings"]}),e.jsxs($,{size:"sm",variant:"outline",onClick:()=>t("/mission-control/listings"),className:"gap-1",children:[e.jsx(sn,{className:"h-4 w-4"}),"Add Listing"]})]}),e.jsxs(Oe,{children:[n.length===0?e.jsxs("div",{className:"text-center py-8",children:[e.jsx(sa,{className:"h-10 w-10 text-muted-foreground mx-auto mb-2"}),e.jsx("p",{className:"text-sm text-muted-foreground mb-3",children:"No active listings from your brokerage yet"}),e.jsxs($,{size:"sm",onClick:()=>t("/mission-control/listings/new"),className:"gap-1",children:[e.jsx(sn,{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(sa,{className:"h-8 w-8 text-muted-foreground"})}),e.jsx("div",{className:"absolute top-2 left-2",children:e.jsx("span",{className:"text-[10px] font-medium bg-primary text-primary-foreground px-1.5 py-0.5 rounded uppercase",children:o.property_type.replace("_"," ")})})]}),e.jsxs("div",{className:"p-2.5",children:[e.jsx("p",{className:"font-semibold text-sm text-primary",children:l(o.price)}),e.jsx("p",{className:"text-xs text-muted-foreground truncate mt-0.5",children:o.property_address||"Address not available"}),e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:o.city}),o.agent&&e.jsxs("p",{className:"text-[10px] text-muted-foreground mt-1.5 truncate",children:["Listed by ",o.agent.name]})]})]},o.id))}),n.length>0&&e.jsxs($,{variant:"ghost",size:"sm",className:"w-full mt-3",onClick:()=>t("/mission-control/listings"),children:["View All Listings",e.jsx(Tr,{className:"h-3 w-3 ml-1"})]})]})]})}const bvn={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 _vn({brokerageId:s,canManage:t}){const{user:n}=_s(),{toast:r}=gi(),{data:a,isLoading:i}=mDs(s),l=pDs(s),[o,c]=j.useState({...bvn}),[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 x=(v,N)=>c(C=>({...C,[v]:N})),g=async(v,N)=>{if(n){m(v);try{const C=await VLt(n.id,N,`brokerage-${v}`);x(v,C),r({title:"Image uploaded"})}catch(C){r({title:"Upload failed",description:C.message,variant:"destructive"})}finally{m(null)}}},y=async()=>{try{await l.mutateAsync({...Object.fromEntries(Object.entries(o).map(([v,N])=>[v,N||null])),...d}),r({title:"Brokerage brand saved",description:"Agents in this brokerage now inherit these settings."})}catch(v){r({title:"Could not save",description:v.message,variant:"destructive"})}},b=(v,N)=>e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:N}),e.jsxs("div",{className:"flex items-center gap-3",children:[o[v]&&e.jsx("img",{src:o[v],alt:N,className:"h-12 w-auto rounded border bg-background p-1"}),e.jsx("input",{ref:p[v],type:"file",accept:"image/*",className:"hidden",onChange:C=>{var A;return((A=C.target.files)==null?void 0:A[0])&&g(v,C.target.files[0])}}),e.jsxs($,{type:"button",variant:"outline",disabled:!t||h===v,onClick:()=>{var C;return(C=p[v].current)==null?void 0:C.click()},children:[h===v?e.jsx(Ht,{className:"h-4 w-4 animate-spin"}):e.jsx(si,{className:"h-4 w-4"}),e.jsx("span",{className:"ml-2",children:"Upload"})]}),o[v]&&t&&e.jsx($,{type:"button",variant:"ghost",onClick:()=>x(v,""),children:"Remove"})]})]});return e.jsxs(_e,{children:[e.jsxs(Bt,{children:[e.jsxs(Ut,{className:"flex items-center gap-2",children:[e.jsx(Ai,{className:"h-5 w-5"}),"Brokerage Brand"]}),e.jsx(vr,{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(Oe,{className:"space-y-6",children:i?e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground text-sm",children:[e.jsx(Ht,{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(([v,N,C])=>e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:N}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(be,{type:"color",className:"h-10 w-14 p-1",disabled:!t,value:o[v]||C,onChange:A=>x(v,A.target.value)}),e.jsx(be,{disabled:!t,value:o[v],placeholder:C,onChange:A=>x(v,A.target.value)})]})]},v))}),e.jsxs("div",{className:"grid gap-4 sm:grid-cols-3",children:[b("logo_url","Logo (light background)"),b("logo_dark_url","Logo (dark background)"),b("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(se,{children:"Heading font"}),e.jsx(be,{disabled:!t,value:o.heading_font,placeholder:"Playfair Display",onChange:v=>x("heading_font",v.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Body font"}),e.jsx(be,{disabled:!t,value:o.body_font,placeholder:"Inter",onChange:v=>x("body_font",v.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Legal brokerage name"}),e.jsx(be,{disabled:!t,value:o.legal_name,placeholder:"Acme Realty, Inc.",onChange:v=>x("legal_name",v.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Brokerage license #"}),e.jsx(be,{disabled:!t,value:o.license_number,placeholder:"DRE #01234567",onChange:v=>x("license_number",v.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"License state"}),e.jsx(be,{disabled:!t,value:o.license_state,placeholder:"CA",onChange:v=>x("license_state",v.target.value)})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Required disclaimer / compliance line"}),e.jsx(Is,{disabled:!t,rows:2,value:o.compliance_line,placeholder:"Each office independently owned and operated. Information deemed reliable but not guaranteed.",onChange:v=>x("compliance_line",v.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(([v,N])=>e.jsxs("div",{className:"flex items-center justify-between rounded-md border p-3",children:[e.jsx(se,{className:"text-sm font-normal",children:N}),e.jsx(Tn,{disabled:!t,checked:d[v],onCheckedChange:C=>u(A=>({...A,[v]:C}))})]},v))}),t&&e.jsxs($,{onClick:y,disabled:l.isPending,children:[l.isPending?e.jsx(Ht,{className:"mr-2 h-4 w-4 animate-spin"}):e.jsx(Jo,{className:"mr-2 h-4 w-4"}),"Save brokerage brand"]})]})})]})}function wvn(){const{user:s,isAdmin:t,isBrokerageManager:n}=_s(),r=Vn(),[a,i]=j.useState(!0),[l,o]=j.useState(null),[c,d]=j.useState(""),[u,h]=j.useState(0),[m,p]=j.useState(!1),[x,g]=j.useState(!1);return j.useEffect(()=>{(async()=>{if(s)try{const{data:b}=await U.from("profiles").select("brokerage_id").eq("id",s.id).maybeSingle();if(!(b!=null&&b.brokerage_id)){i(!1);return}o(b.brokerage_id);const{data:v}=await U.from("brokerages").select("name").eq("id",b.brokerage_id).maybeSingle();v&&d(v.name);const{count:N}=await U.from("profiles").select("id",{count:"exact",head:!0}).eq("brokerage_id",b.brokerage_id);if(h(N||0),t)p(!0),g(!0);else if(n){const{data:C}=await U.from("brokerage_manager_assignments").select("id").eq("user_id",s.id).eq("brokerage_id",b.brokerage_id).maybeSingle();p(!!C),g(!!C)}}catch(b){console.error("Error fetching brokerage info:",b)}finally{i(!1)}})()},[s,t,n]),a?e.jsx(Ks,{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(Ks,{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(qn,{className:"h-5 w-5 text-primary"}),e.jsxs("span",{className:"font-medium",children:[u," ",u===1?"Agent":"Agents"]})]}),x&&e.jsxs("div",{className:"flex gap-2",children:[e.jsxs($,{variant:"outline",onClick:()=>r("/brokerage-content"),children:[e.jsx(wf,{className:"h-4 w-4 mr-2"}),"Brokerage Content"]}),e.jsxs($,{onClick:()=>r(`/mission-control/listings/new?brokerage=${l}`),children:[e.jsx(sa,{className:"h-4 w-4 mr-2"}),"Add Listing"]})]})]}),e.jsx(_vn,{brokerageId:l,canManage:m}),e.jsx(fvn,{brokerageId:l,canManage:m}),e.jsx(xvn,{brokerageId:l,canManage:m}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-8",children:[e.jsx(yvn,{brokerageId:l}),e.jsx(vvn,{brokerageId:l})]})]})}):e.jsx(Ks,{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(Ai,{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 jvn(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 Nvn(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 zft={video:{icon:Td,label:"Video",color:"bg-red-500/10 text-red-600 dark:text-red-400"},pdf:{icon:Wr,label:"Document",color:"bg-blue-500/10 text-blue-600 dark:text-blue-400"},link:{icon:Dc,label:"Link",color:"bg-green-500/10 text-green-600 dark:text-green-400"},event:{icon:ia,label:"Event",color:"bg-purple-500/10 text-purple-600 dark:text-purple-400"},graphic:{icon:Rc,label:"Graphic",color:"bg-amber-500/10 text-amber-600 dark:text-amber-400"}};function kvn({item:s,canManage:t}){const[n,r]=j.useState(!1),[a,i]=j.useState(null),l=SCs(),o=Vn(),c=zft[s.content_type]||zft.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"?jvn(s.url):null,[s]);j.useEffect(()=>{u||!s.url||s.content_type!=="video"||!Nvn(s.url)||fetch(`https://www.youtube.com/oembed?url=${encodeURIComponent(s.url)}&format=json`).then(x=>x.ok?x.json():null).then(x=>{x!=null&&x.thumbnail_url&&i(x.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),ae.success("Content deleted")}catch{ae.error("Failed to delete")}r(!1)};return e.jsxs(e.Fragment,{children:[e.jsxs(_e,{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(Oe,{className:"p-4",children:e.jsxs("div",{className:"flex items-start justify-between gap-2",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsxs($e,{variant:"secondary",className:`text-[10px] px-1.5 py-0 ${c.color}`,children:[e.jsx(d,{className:"h-3 w-3 mr-1"}),c.label]}),s.category&&e.jsxs($e,{variant:"outline",className:"text-[10px] px-1.5 py-0",children:[s.category.icon," ",s.category.name]})]}),e.jsx("h3",{className:"font-semibold text-sm text-foreground group-hover:text-primary transition-colors truncate",children:s.title}),s.description&&e.jsx("p",{className:"text-xs text-muted-foreground mt-1 line-clamp-2",children:s.description}),s.content_type==="event"&&s.event_date&&e.jsxs("p",{className:"text-xs text-primary mt-2 font-medium",children:["📅 ",Hs(new Date(s.event_date),"MMM d, yyyy · h:mm a")]}),e.jsxs("p",{className:"text-[10px] text-muted-foreground mt-2",children:["Added ",Hs(new Date(s.created_at),"MMM d, yyyy")]})]}),t&&e.jsxs(Hd,{children:[e.jsx(Gd,{asChild:!0,onClick:x=>x.stopPropagation(),children:e.jsx($,{variant:"ghost",size:"icon",className:"h-7 w-7 shrink-0",children:e.jsx(cy,{className:"h-4 w-4"})})}),e.jsx(Md,{align:"end",children:e.jsxs(Na,{onClick:x=>{x.stopPropagation(),r(!0)},className:"text-destructive",children:[e.jsx(Pn,{className:"h-4 w-4 mr-2"}),"Delete"]})})]})]})})]}),e.jsx(Ll,{open:n,onOpenChange:r,children:e.jsxs(yl,{children:[e.jsxs(vl,{children:[e.jsx(_l,{children:"Delete Content"}),e.jsxs(wl,{children:['Are you sure you want to delete "',s.title,'"? This cannot be undone.']})]}),e.jsxs(bl,{children:[e.jsx(jl,{children:"Cancel"}),e.jsx(fl,{onClick:p,className:"bg-destructive text-destructive-foreground",children:"Delete"})]})]})})]})}function Svn(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 Bft=[{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 Cvn({brokerageId:s,categories:t}){var le;const{user:n}=_s(),[r,a]=j.useState(!1),[i,l]=j.useState(!1),[o,c]=j.useState(""),[d,u]=j.useState("📁"),[h,m]=j.useState(!1);j.useRef(null);const[p,x]=j.useState("video"),[g,y]=j.useState(""),[b,v]=j.useState(""),[N,C]=j.useState(""),[A,T]=j.useState(""),[P,M]=j.useState(""),[I,D]=j.useState(""),[B,q]=j.useState(""),W=kCs(),V=CCs(s),K=ACs(),Q=ECs(s),J=()=>{x("video"),y(""),v(""),C(""),T(""),M(""),D(""),q("")},ce=async(he,ve)=>{var fe;const ge=(fe=he.target.files)==null?void 0:fe[0];if(ge){m(!0);try{const je=ge.name.split(".").pop(),Ee=`${s}/${Date.now()}-${Math.random().toString(36).slice(2)}.${je}`,{error:Me}=await U.storage.from("brokerage-content").upload(Ee,ge);if(Me)throw Me;const{data:{publicUrl:De}}=U.storage.from("brokerage-content").getPublicUrl(Ee);ve==="file"?(T(De),p==="graphic"&&!P&&M(De)):M(De),ae.success("File uploaded")}catch(je){ae.error(je.message||"Upload failed")}finally{m(!1)}}},ue=async()=>{if(!g.trim()){ae.error("Title is required");return}if(n)try{await W.mutateAsync({brokerage_id:s,category_id:B||null,content_type:p,title:g.trim(),description:b.trim()||null,url:N.trim()||null,file_url:A.trim()||null,thumbnail_url:P.trim()||null,event_date:I?new Date(I).toISOString():null,created_by:n.id}),ae.success("Content added!"),J(),a(!1)}catch(he){ae.error(he.message||"Failed to add content")}},ne=async()=>{if(o.trim())try{await V.mutateAsync({name:o.trim(),icon:d,sort_order:t.length}),c(""),u("📁"),ae.success("Category created")}catch(he){ae.error(he.message||"Failed to create category")}},ee=async()=>{try{await Q.mutateAsync(),ae.success("Default categories created")}catch{ae.error("Failed to create defaults")}};return e.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[e.jsxs(Os,{open:r,onOpenChange:a,children:[e.jsx(Ko,{asChild:!0,children:e.jsxs($,{children:[e.jsx(sn,{className:"h-4 w-4 mr-2"}),"Add Content"]})}),e.jsxs(Rs,{className:"max-w-lg max-h-[90vh] overflow-y-auto",children:[e.jsx(Us,{children:e.jsx(zs,{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(se,{children:"Content Type"}),e.jsxs(vs,{value:p,onValueChange:x,children:[e.jsx(gs,{children:e.jsx(bs,{})}),e.jsx(ys,{children:Bft.map(he=>e.jsx(Ye,{value:he.value,children:he.label},he.value))})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:(le=Bft.find(he=>he.value===p))==null?void 0:le.hint})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:"Category"}),e.jsxs(vs,{value:B,onValueChange:q,children:[e.jsx(gs,{children:e.jsx(bs,{placeholder:"Select category (optional)"})}),e.jsx(ys,{children:t.map(he=>e.jsxs(Ye,{value:he.id,children:[he.icon," ",he.name]},he.id))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:"Title *"}),e.jsx(be,{value:g,onChange:he=>y(he.target.value),placeholder:"Content title"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:"Description"}),e.jsx(Is,{value:b,onChange:he=>v(he.target.value),placeholder:"Brief description...",rows:2})]}),["video","link","graphic","event"].includes(p)&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:p==="video"?"Video URL":p==="graphic"?"Canva / Image URL":p==="event"?"Event Link (Zoom, etc.)":"URL"}),e.jsx(be,{value:N,onChange:he=>{const ve=he.target.value;if(C(ve),p==="video"&&!P){const ge=Svn(ve);ge&&M(ge)}},placeholder:"https://..."})]}),["pdf","graphic"].includes(p)&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:p==="pdf"?"Upload PDF":"Upload Image"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(be,{type:"file",accept:p==="pdf"?".pdf,.doc,.docx":"image/*",onChange:he=>ce(he,"file"),disabled:h}),h&&e.jsx(Ht,{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(se,{children:"Thumbnail Image (optional)"}),e.jsx(be,{type:"file",accept:"image/*",onChange:he=>ce(he,"thumbnail"),disabled:h}),P&&e.jsxs("div",{className:"relative w-20 h-20 rounded overflow-hidden",children:[e.jsx("img",{src:P,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(pr,{className:"h-3 w-3"})})]})]}),p==="event"&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:"Event Date & Time"}),e.jsx(be,{type:"datetime-local",value:I,onChange:he=>D(he.target.value)})]}),e.jsxs($,{onClick:ue,disabled:W.isPending||!g.trim(),className:"w-full",children:[W.isPending?e.jsx(Ht,{className:"h-4 w-4 animate-spin mr-2"}):e.jsx(sn,{className:"h-4 w-4 mr-2"}),"Add Content"]})]})]})]}),e.jsxs(Os,{open:i,onOpenChange:l,children:[e.jsx(Ko,{asChild:!0,children:e.jsxs($,{variant:"outline",size:"sm",children:[e.jsx(pc,{className:"h-4 w-4 mr-2"}),"Categories"]})}),e.jsxs(Rs,{className:"max-w-md",children:[e.jsx(Us,{children:e.jsx(zs,{children:"Manage Categories"})}),e.jsxs("div",{className:"space-y-4 mt-2",children:[t.length===0&&e.jsxs("div",{className:"text-center py-4",children:[e.jsx("p",{className:"text-sm text-muted-foreground mb-3",children:"No categories yet"}),e.jsxs($,{variant:"outline",size:"sm",onClick:ee,disabled:Q.isPending,children:[Q.isPending?e.jsx(Ht,{className:"h-4 w-4 animate-spin mr-2"}):null,"Create Default Categories"]})]}),t.map(he=>e.jsxs("div",{className:"flex items-center justify-between p-2 rounded-lg border",children:[e.jsxs("span",{className:"text-sm",children:[he.icon," ",he.name]}),!he.is_default&&e.jsx($,{variant:"ghost",size:"icon",className:"h-7 w-7 text-destructive",onClick:async()=>{await K.mutateAsync(he.id),ae.success("Category deleted")},children:e.jsx(pr,{className:"h-4 w-4"})})]},he.id)),e.jsxs("div",{className:"flex gap-2 pt-2 border-t",children:[e.jsx(be,{value:d,onChange:he=>u(he.target.value),className:"w-14 text-center",maxLength:2}),e.jsx(be,{value:o,onChange:he=>c(he.target.value),placeholder:"New category name",className:"flex-1",onKeyDown:he=>he.key==="Enter"&&ne()}),e.jsx($,{size:"sm",onClick:ne,disabled:!o.trim(),children:"Add"})]})]})]})]})]})}function Avn(){const{user:s,isAdmin:t,isBrokerageManager:n}=_s(),[r,a]=j.useState(!0),[i,l]=j.useState(null),[o,c]=j.useState(""),[d,u]=j.useState(!1),[h,m]=j.useState(null),[p,x]=j.useState("");j.useEffect(()=>{(async()=>{if(s)try{const{data:C}=await U.from("profiles").select("brokerage_id").eq("id",s.id).maybeSingle();if(!(C!=null&&C.brokerage_id)){a(!1);return}l(C.brokerage_id);const{data:A}=await U.from("brokerages").select("name").eq("id",C.brokerage_id).maybeSingle();if(A&&c(A.name),t)u(!0);else if(n){const{data:T}=await U.from("brokerage_manager_assignments").select("id").eq("user_id",s.id).eq("brokerage_id",C.brokerage_id).maybeSingle();u(!!T)}}catch(C){console.error("Error fetching brokerage info:",C)}finally{a(!1)}})()},[s,t,n]);const{data:g=[]}=wCs(i),{data:y=[],isLoading:b}=jCs(i,h),v=j.useMemo(()=>{if(!p.trim())return y;const N=p.toLowerCase();return y.filter(C=>{var A;return C.title.toLowerCase().includes(N)||((A=C.description)==null?void 0:A.toLowerCase().includes(N))||C.content_type.toLowerCase().includes(N)})},[y,p]);return r?e.jsx(Ks,{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(Ks,{title:`${o} Content`,description:"Brokerage Content Hub",children:e.jsxs("div",{className:"space-y-6",children:[d&&i&&e.jsx(Cvn,{brokerageId:i,categories:g}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"relative max-w-sm",children:[e.jsx(Vr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(be,{placeholder:"Search content...",value:p,onChange:N=>x(N.target.value),className:"pl-9"})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx($,{variant:h===null?"default":"outline",size:"sm",onClick:()=>m(null),children:"All"}),g.map(N=>e.jsxs($,{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))]})]}),b?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"})}):v.length===0?e.jsx(_e,{className:"bg-muted/30 border-dashed",children:e.jsxs(Oe,{className:"flex flex-col items-center justify-center py-12",children:[e.jsx(cv,{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:v.map(N=>e.jsx(kvn,{item:N,canManage:d},N.id))})]})}):e.jsx(Ks,{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(Ai,{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 $ft={video:{icon:Td,label:"Video",color:"bg-red-500/10 text-red-600 dark:text-red-400"},pdf:{icon:Wr,label:"Document",color:"bg-blue-500/10 text-blue-600 dark:text-blue-400"},link:{icon:Dc,label:"Link",color:"bg-green-500/10 text-green-600 dark:text-green-400"},event:{icon:ia,label:"Event",color:"bg-purple-500/10 text-purple-600 dark:text-purple-400"},graphic:{icon:Rc,label:"Graphic",color:"bg-amber-500/10 text-amber-600 dark:text-amber-400"}};function Evn(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 Tvn(s){try{const t=new URL(s).hostname.replace("www.","");return["youtube.com","youtu.be","m.youtube.com"].includes(t)}catch{return!1}}function Mvn(s){try{return new URL(s).hostname.includes("vimeo.com")}catch{return!1}}function Lvn(s){try{const t=s.match(/vimeo\.com\/(\d+)/);if(t)return`https://player.vimeo.com/video/${t[1]}`}catch{}return null}function Pvn(){const{contentId:s}=Vi(),{data:t,isLoading:n}=ht({queryKey:["brokerage-content-detail",s],queryFn:async()=>{const{data:d,error:u}=await U.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(Ks,{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(Ks,{title:"Brokerage Content",children:e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(Ai,{className:"h-12 w-12 text-muted-foreground mb-4"}),e.jsx("h3",{className:"text-lg font-semibold",children:"Content not found"}),e.jsx("p",{className:"text-muted-foreground mt-1",children:"This content may have been removed."}),e.jsx($,{asChild:!0,className:"mt-4",children:e.jsx(Wn,{to:"/brokerage-content",children:"Back to Content"})})]})});const r=$ft[t.content_type]||$ft.link,a=r.icon,i=t.url||t.file_url,l=i&&Tvn(i)?Evn(i):null,o=i&&Mvn(i)?Lvn(i):null,c=l||o;return e.jsx(Ks,{title:t.title,children:e.jsxs("div",{className:"space-y-6 max-w-4xl mx-auto",children:[e.jsx($,{variant:"ghost",size:"sm",asChild:!0,className:"gap-2",children:e.jsxs(Wn,{to:"/brokerage-content",children:[e.jsx(ka,{className:"h-4 w-4"}),"Back to Content"]})}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs($e,{variant:"secondary",className:`text-xs px-2 py-0.5 ${r.color}`,children:[e.jsx(a,{className:"h-3 w-3 mr-1"}),r.label]}),t.category&&e.jsxs($e,{variant:"outline",className:"text-xs px-2 py-0.5",children:[t.category.icon," ",t.category.name]}),e.jsxs("span",{className:"text-xs text-muted-foreground ml-auto",children:["Added ",Hs(new Date(t.created_at),"MMMM d, yyyy")]})]}),e.jsx("h1",{className:"text-2xl font-bold text-foreground",children:t.title}),c&&e.jsx(_e,{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(_e,{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(_e,{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(_e,{children:e.jsx(Oe,{className:"pt-6",children:e.jsx("p",{className:"text-muted-foreground whitespace-pre-wrap",children:t.description})})}),t.content_type==="event"&&t.event_date&&e.jsx(_e,{children:e.jsxs(Oe,{className:"pt-6 flex items-center gap-3",children:[e.jsx("div",{className:"p-2 rounded-md bg-primary/10",children:e.jsx(ia,{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:Hs(new Date(t.event_date),"EEEE, MMMM d, yyyy · h:mm a")})]})]})}),e.jsxs("div",{className:"flex flex-wrap gap-3",children:[t.file_url&&e.jsx($,{asChild:!0,size:"lg",children:e.jsxs("a",{href:t.file_url,target:"_blank",rel:"noopener noreferrer",children:[e.jsx(di,{className:"h-4 w-4 mr-2"}),t.content_type==="pdf"?"Download Document":"Download File"]})}),t.url&&e.jsx($,{variant:t.file_url?"outline":"default",asChild:!0,size:"lg",children:e.jsxs("a",{href:t.url,target:"_blank",rel:"noopener noreferrer",children:[e.jsx(Tr,{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 c4e={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 Ivn(s="open"){const{user:t}=_s();return ht({queryKey:["brokerage-help-requests",s,t==null?void 0:t.id],queryFn:async()=>{if(!t)return[];let n=U.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 U.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 Dvn(s){return ht({queryKey:["brokerage-help-request",s],queryFn:async()=>{if(!s)return null;const{data:t,error:n}=await U.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 Rvn(s){return ht({queryKey:["brokerage-help-claims",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await U.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 Ovn(){const s=ts(),{user:t,brokerageId:n}=_s();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 U.from("brokerage_help_requests").insert({...r,brokerage_id:n,requester_user_id:t.id}).select().single();if(i)throw i;try{await U.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 Fvn(){const s=ts(),{user:t}=_s();return yt({mutationFn:async({request_id:n,note:r})=>{if(!t)throw new Error("Not signed in");const{data:a,error:i}=await U.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 zvn(){const s=ts();return yt({mutationFn:async({claim_id:t,request_id:n,claimant_user_id:r})=>{const{error:a}=await U.from("brokerage_help_claims").update({status:"accepted",responded_at:new Date().toISOString()}).eq("id",t);if(a)throw a;const{error:i}=await U.from("brokerage_help_requests").update({status:"filled",assigned_user_id:r}).eq("id",n);if(i)throw i;try{await U.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 Bvn(){const s=ts();return yt({mutationFn:async({claim_id:t})=>{const{error:n}=await U.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 $vn(){const s=ts();return yt({mutationFn:async t=>{const{error:n}=await U.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 Uvn(){const s=ts();return yt({mutationFn:async t=>{const{error:n}=await U.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 qvn(){const{user:s,brokerageId:t}=_s(),n=ts(),r=ht({queryKey:["brokerage-help-prefs",s==null?void 0:s.id,t],queryFn:async()=>{if(!s||!t)return null;const{data:i,error:l}=await U.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 U.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 Vvn(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 Hvn(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 Gvn({req:s,onClick:t}){var i;const n=c4e[s.request_type],r=Vvn(s.event_start_at,s.event_end_at),a=[s.address,s.city,s.state].filter(Boolean).join(", ");return e.jsx(_e,{className:"cursor-pointer hover:shadow-md transition group",onClick:t,children:e.jsxs(Oe,{className:"p-5",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3 mb-3",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsxs($e,{variant:"secondary",className:"text-xs",children:[n.emoji," ",n.label]}),s.status!=="open"&&e.jsx($e,{variant:"outline",className:"text-xs capitalize",children:s.status})]}),e.jsx(Ja,{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(Hr,{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(ai,{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(qd,{className:"h-3.5 w-3.5 shrink-0"}),e.jsx("span",{children:Hvn(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 Wvn(){var c;const s=Vn(),{brokerageId:t}=_s(),[n,r]=j.useState("open"),{data:a=[],isLoading:i}=Ivn(n),l=qvn(),o=((c=l.data)==null?void 0:c.email_enabled)??!0;return t?e.jsx(Ks,{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(ua,{value:n,onValueChange:d=>r(d),children:e.jsxs(ha,{children:[e.jsx(Qt,{value:"open",children:"Open"}),e.jsx(Qt,{value:"mine",children:"My Posts"}),e.jsx(Qt,{value:"my_claims",children:"My Claims"}),e.jsx(Qt,{value:"filled",children:"Filled"})]})}),e.jsxs($,{onClick:()=>s("/brokerage/help-board/new"),className:"gap-2",children:[e.jsx(sn,{className:"h-4 w-4"})," Post Request"]})]}),e.jsx(_e,{className:"bg-muted/30 border-dashed",children:e.jsxs(Oe,{className:"flex items-center justify-between py-3 px-5",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[o?e.jsx(Dx,{className:"h-4 w-4 text-primary"}):e.jsx(e5,{className:"h-4 w-4 text-muted-foreground"}),e.jsxs("div",{children:[e.jsx(se,{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(Tn,{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(_e,{className:"bg-muted/30 border-dashed",children:e.jsxs(Oe,{className:"flex flex-col items-center justify-center py-12",children:[e.jsx(ES,{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(Gvn,{req:d,onClick:()=>s(`/brokerage/help-board/${d.id}`)},d.id))})]})}):e.jsx(Ks,{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(ES,{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 Kvn(){const s=Vn(),{toast:t}=gi(),n=Ovn(),[r,a]=j.useState("open_house"),[i,l]=j.useState(""),[o,c]=j.useState(""),[d,u]=j.useState(""),[h,m]=j.useState(""),[p,x]=j.useState(""),[g,y]=j.useState(""),[b,v]=j.useState(""),[N,C]=j.useState(""),[A,T]=j.useState(""),[P,M]=j.useState(""),[I,D]=j.useState("goodwill"),[B,q]=j.useState(""),[W,V]=j.useState(""),K=r==="open_house"||r==="showing_coverage",Q=r!=="general",J=(ue,ne)=>!ue||!ne?null:`${ue}T${ne}:00`,ce=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 ne=J(d,h),ee=J(d,p);await n.mutateAsync({request_type:r,title:i.trim(),description:o.trim()||null,event_start_at:ne,event_end_at:ee,address:K&&g.trim()||null,city:K&&b.trim()||null,state:K&&N.trim()||null,zip:K&&A.trim()||null,mls_number:P.trim()||null,compensation_type:I,compensation_amount:B?Number(B):null,compensation_notes:W.trim()||null}),t({title:"Posted!",description:"Your teammates have been notified."}),s("/brokerage/help-board")}catch(ne){t({title:"Could not post",description:(ne==null?void 0:ne.message)??"Something went wrong.",variant:"destructive"})}};return e.jsx(Ks,{title:"Post a Help Request",description:"Ask a teammate to cover for you",children:e.jsxs("div",{className:"max-w-2xl mx-auto",children:[e.jsxs($,{variant:"ghost",size:"sm",onClick:()=>s("/brokerage/help-board"),className:"mb-4 gap-2",children:[e.jsx(ka,{className:"h-4 w-4"})," Back to board"]}),e.jsx("form",{onSubmit:ce,children:e.jsx(_e,{children:e.jsxs(Oe,{className:"p-6 space-y-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"What do you need help with?"}),e.jsx("div",{className:"grid grid-cols-2 gap-2",children:Object.keys(c4e).map(ue=>{const ne=c4e[ue],ee=ue===r;return e.jsxs("button",{type:"button",onClick:()=>a(ue),className:`text-left p-3 rounded-lg border-2 transition ${ee?"border-primary bg-primary/5":"border-border hover:border-primary/40"}`,children:[e.jsx("div",{className:"text-lg",children:ne.emoji}),e.jsx("div",{className:"font-medium text-sm mt-1",children:ne.label}),e.jsx("div",{className:"text-xs text-muted-foreground line-clamp-1",children:ne.description})]},ue)})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"title",children:"Title *"}),e.jsx(be,{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(se,{htmlFor:"description",children:"Details"}),e.jsx(Is,{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})]}),Q&&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(se,{htmlFor:"date",children:"Date"}),e.jsx(be,{id:"date",type:"date",value:d,onChange:ue=>u(ue.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"start",children:"Start"}),e.jsx(be,{id:"start",type:"time",value:h,onChange:ue=>m(ue.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"end",children:"End"}),e.jsx(be,{id:"end",type:"time",value:p,onChange:ue=>x(ue.target.value)})]})]}),K&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"address",children:"Address"}),e.jsx(be,{id:"address",value:g,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(se,{htmlFor:"city",children:"City"}),e.jsx(be,{id:"city",value:b,onChange:ue=>v(ue.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"state",children:"State"}),e.jsx(be,{id:"state",value:N,onChange:ue=>C(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(se,{htmlFor:"zip",children:"Zip"}),e.jsx(be,{id:"zip",value:A,onChange:ue=>T(ue.target.value),maxLength:10})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"mls",children:"MLS # (optional)"}),e.jsx(be,{id:"mls",value:P,onChange:ue=>M(ue.target.value)})]})]})]}),e.jsxs("div",{className:"space-y-3 pt-2 border-t",children:[e.jsx(se,{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 ne=I===ue.val;return e.jsxs("button",{type:"button",onClick:()=>D(ue.val),className:`text-left p-3 rounded-lg border-2 transition ${ne?"border-primary bg-primary/5":"border-border hover:border-primary/40"}`,children:[e.jsx("div",{className:"font-medium text-sm",children: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(se,{htmlFor:"amount",children:I==="flat_fee"?"Amount ($)":"Percent (%)"}),e.jsx(be,{id:"amount",type:"number",min:"0",step:I==="referral_percent"?"1":"5",value:B,onChange:ue=>q(ue.target.value),placeholder:I==="flat_fee"?"100":"25"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"comp-notes",children:"Compensation notes"}),e.jsx(be,{id:"comp-notes",value:W,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($,{type:"button",variant:"ghost",onClick:()=>s("/brokerage/help-board"),children:"Cancel"}),e.jsxs($,{type:"submit",disabled:n.isPending,className:"gap-2",children:[n.isPending&&e.jsx(Ht,{className:"h-4 w-4 animate-spin"}),"Post & Notify Brokerage"]})]})]})})})]})})}function Yvn(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 r8e(s){return s?s.split(" ").map(t=>t[0]).slice(0,2).join("").toUpperCase():"?"}function Zvn(){var P,M,I,D,B,q,W,V;const{id:s}=Vi(),t=Vn(),{user:n}=_s(),{toast:r}=gi(),{data:a,isLoading:i}=Dvn(s),{data:l=[]}=Rvn(s),o=Fvn(),c=zvn(),d=Bvn(),u=$vn(),h=Uvn(),[m,p]=j.useState("");if(i)return e.jsx(Ks,{title:"Loading...",description:"",children:e.jsx("div",{className:"flex items-center justify-center py-16",children:e.jsx(Ht,{className:"h-8 w-8 animate-spin text-primary"})})});if(!a)return e.jsxs(Ks,{title:"Not Found",description:"",children:[e.jsxs($,{variant:"ghost",onClick:()=>t("/brokerage/help-board"),className:"gap-2",children:[e.jsx(ka,{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 x=c4e[a.request_type],g=Yvn(a.event_start_at,a.event_end_at),y=[a.address,a.city,a.state,a.zip].filter(Boolean).join(", "),b=(n==null?void 0:n.id)===a.requester_user_id,v=l.find(K=>K.claimant_user_id===(n==null?void 0:n.id)),N=l.find(K=>K.status==="accepted"),C=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(Ks,{title:a.title,description:`${x.emoji} ${x.label}`,children:e.jsxs("div",{className:"max-w-3xl mx-auto space-y-4",children:[e.jsxs($,{variant:"ghost",size:"sm",onClick:()=>t("/brokerage/help-board"),className:"gap-2",children:[e.jsx(ka,{className:"h-4 w-4"})," Back to board"]}),e.jsx(_e,{children:e.jsxs(Oe,{className:"p-6 space-y-4",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3 flex-wrap",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsxs($e,{variant:"secondary",children:[x.emoji," ",x.label]}),e.jsx($e,{variant:C?"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(ki,{src:((P=a.requester)==null?void 0:P.avatar_url)||void 0}),e.jsx(Ta,{children:r8e((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:[g&&e.jsxs("div",{className:"flex items-start gap-2 text-sm",children:[e.jsx(Hr,{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:g})]})]}),y&&e.jsxs("div",{className:"flex items-start gap-2 text-sm",children:[e.jsx(ai,{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(qd,{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(vT,{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]})]})}),!b&&C&&!v&&e.jsx(_e,{children:e.jsxs(Oe,{className:"p-6 space-y-3",children:[e.jsx("h3",{className:"font-semibold",children:"Offer to cover this"}),e.jsx(Is,{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($,{onClick:T,disabled:o.isPending,className:"gap-2",children:[o.isPending&&e.jsx(Ht,{className:"h-4 w-4 animate-spin"}),"I can cover this"]})]})}),!b&&v&&e.jsx(_e,{className:"border-primary/30 bg-primary/5",children:e.jsxs(Oe,{className:"p-4 flex items-center gap-3",children:[e.jsx(oa,{className:"h-5 w-5 text-primary"}),e.jsxs("div",{className:"text-sm",children:[e.jsxs("div",{className:"font-medium capitalize",children:["Your offer: ",v.status]}),e.jsxs("div",{className:"text-muted-foreground",children:[v.status==="pending"&&"Waiting for the requester to pick.",v.status==="accepted"&&"You're confirmed — see contact info below.",v.status==="declined"&&"They went with someone else this time."]})]})]})}),N&&(b||N.claimant_user_id===(n==null?void 0:n.id))&&e.jsx(_e,{className:"border-primary/30",children:e.jsxs(Oe,{className:"p-6",children:[e.jsx("h3",{className:"font-semibold mb-3",children:"Confirmed coverage"}),e.jsxs("div",{className:"flex items-center gap-3 mb-3",children:[e.jsxs(Ea,{className:"h-10 w-10",children:[e.jsx(ki,{src:((D=N.claimant)==null?void 0:D.avatar_url)||void 0}),e.jsx(Ta,{children:r8e((B=N.claimant)==null?void 0:B.name)})]}),e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:(q=N.claimant)==null?void 0:q.name}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Covering this request"})]})]}),e.jsxs("div",{className:"space-y-1.5 text-sm",children:[((W=N.claimant)==null?void 0:W.email)&&e.jsxs("a",{href:`mailto:${N.claimant.email}`,className:"flex items-center gap-2 text-primary hover:underline",children:[e.jsx(nn,{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(ya,{className:"h-4 w-4"})," ",N.claimant.phone]})]})]})}),b&&e.jsx(_e,{children:e.jsxs(Oe,{className:"p-6 space-y-3",children:[e.jsxs("h3",{className:"font-semibold",children:["Interested agents (",l.length,")"]}),l.length===0&&e.jsx("p",{className:"text-sm text-muted-foreground",children:"No claims yet. Hang tight — your teammates were just notified."}),l.map(K=>{var Q,J,ce,ue,ne;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(ki,{src:((Q=K.claimant)==null?void 0:Q.avatar_url)||void 0}),e.jsx(Ta,{children:r8e((J=K.claimant)==null?void 0:J.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:((ce=K.claimant)==null?void 0:ce.name)||"Teammate"}),e.jsx($e,{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"&&C&&e.jsxs("div",{className:"flex gap-2 mt-2",children:[e.jsxs($,{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(oa,{className:"h-3.5 w-3.5"})," Pick ",((ne=(ue=K.claimant)==null?void 0:ue.name)==null?void 0:ne.split(" ")[0])||"them"]}),e.jsxs($,{size:"sm",variant:"ghost",onClick:()=>d.mutate({claim_id:K.id,request_id:a.id}),disabled:d.isPending,className:"gap-1",children:[e.jsx(pr,{className:"h-3.5 w-3.5"})," Pass"]})]})]})]},K.id)}),b&&C&&e.jsx("div",{className:"pt-3 border-t flex justify-end",children:e.jsx($,{variant:"ghost",size:"sm",onClick:()=>u.mutate(a.id),disabled:u.isPending,children:"Cancel request"})}),b&&a.status==="filled"&&e.jsx("div",{className:"pt-3 border-t flex justify-end",children:e.jsx($,{size:"sm",onClick:()=>h.mutate(a.id),disabled:h.isPending,children:"Mark complete"})})]})})]})})}function OFt({onSelect:s,maxHeight:t="460px"}){const[n,r]=j.useState(""),[a,i]=j.useState("all"),{data:l=[],isLoading:o}=ht({queryKey:["newsletter-graphics-picker"],queryFn:async()=>{const{data:u,error:h}=await U.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(Vr,{className:"absolute left-2.5 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-muted-foreground"}),e.jsx(be,{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(Oi,{style:{maxHeight:t},className:"rounded-md border",children:o?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx(Ht,{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(Jl,{className:"h-8 w-8 text-muted-foreground/50 mb-2"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:l.length===0?"No graphics available yet":"No graphics match your search"})]}):e.jsx("div",{className:"grid grid-cols-2 sm:grid-cols-3 gap-2 p-2",children:d.map(u=>e.jsxs("button",{onClick:()=>s(u),className:"group relative rounded-md overflow-hidden border bg-muted/30 hover:ring-2 hover:ring-primary hover:border-primary transition-all text-left",title:u.title,children:[e.jsx("div",{className:"aspect-video bg-muted overflow-hidden",children:e.jsx("img",{src:u.thumbnail_url||u.image_url,alt:u.title,loading:"lazy",className:"w-full h-full object-cover group-hover:scale-105 transition-transform duration-200"})}),u.is_featured&&e.jsxs($e,{className:"absolute top-1 left-1 h-5 px-1.5 gap-0.5 text-[10px] bg-amber-500 hover:bg-amber-500 text-white border-0",children:[e.jsx(Qa,{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 Xvn=[{key:"search",label:"Search for Properties",icon:Vr,defaultText:"Search for Properties",placeholder:"https://your-website.com/search",helper:"Link to your home search page"},{key:"call",label:"Call Agent",icon:ya,defaultText:"Call Me",hrefPrefix:"tel:",placeholder:"+15555551234",helper:"Your phone number"},{key:"email",label:"Email Agent",icon:nn,defaultText:"Email Me",hrefPrefix:"mailto:",placeholder:"you@email.com",helper:"Your email address"},{key:"schedule",label:"Schedule a Call",icon:ia,defaultText:"Schedule a Call",placeholder:"https://calendly.com/you",helper:"Link to your booking page"},{key:"listings",label:"View My Listings",icon:sa,defaultText:"View My Listings",placeholder:"https://your-website.com/listings",helper:"Link to your listings page"},{key:"valuation",label:"Get Home Value",icon:qd,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:ai,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:vd,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:uu,defaultText:"Learn More",placeholder:"https://...",helper:"Any link you want"}];function Uft(s){const t=s.match(/(?:youtube\.com\/(?:watch\?v=|embed\/|v\/)|youtu\.be\/)([A-Za-z0-9_-]{11})/);return t?t[1]:null}function Qvn(s){const t=s.match(/vimeo\.com\/(?:video\/)?(\d+)/);return t?t[1]:null}function FFt({html:s,onChange:t}){const{user:n}=_s(),r=j.useRef(null),a=j.useRef(""),i=j.useRef(t);i.current=t;const[l,o]=j.useState("desktop"),c=j.useRef(null),[d,u]=j.useState(!1),[h,m]=j.useState(""),[p,x]=j.useState(""),g=j.useRef(null),y=()=>{var _t;const Nt=(_t=r.current)==null?void 0:_t.contentDocument,Ds=Nt==null?void 0:Nt.getSelection();Ds&&Ds.rangeCount>0&&(Nt!=null&&Nt.body.contains(Ds.anchorNode))&&(g.current=Ds.getRangeAt(0).cloneRange())},b=()=>{var Ps;const Nt=c.current,Ds=(Ps=r.current)==null?void 0:Ps.contentDocument;if(!Nt||!Ds)return;let _t=h.trim();_t&&!/^(https?:|mailto:|tel:|#|\/)/i.test(_t)&&(_t="https://"+_t),Nt.setAttribute("href",_t),Nt.setAttribute("target","_blank");const Xs=p.trim();Xs&&Xs!==(Nt.textContent||"").trim()&&(Nt.textContent=Xs);const rn=` `+Ds.documentElement.outerHTML;a.current=rn,i.current(rn),u(!1)};j.useEffect(()=>{var _t,Xs;const Nt=r.current;if(!Nt||a.current===s)return;const Ds=()=>{const rn=Nt.contentDocument;if(!rn)return;rn.open(),rn.write(s||""),rn.close(),a.current=s;const Ps=rn.body;if(!Ps)return;Ps.setAttribute("contenteditable","true"),Ps.style.outline="none",Ps.style.minHeight="400px",Ps.style.cursor="text";const _n=()=>{const gr=` `+rn.documentElement.outerHTML;a.current=gr,i.current(gr)};Ps.addEventListener("input",_n),Ps.addEventListener("blur",_n),Ps.addEventListener("mouseup",y),Ps.addEventListener("keyup",y),rn.addEventListener("selectionchange",y);const Zs=gr=>{var yr;const Un=gr.target,In=Un==null?void 0:Un.closest("a");if(In){if(gr.metaKey||gr.ctrlKey||gr.shiftKey)return;gr.preventDefault(),gr.stopPropagation(),c.current=In,m(In.getAttribute("href")||""),x((In.textContent||"").trim()),u(!0);return}const Ar=rn.getSelection();if(!Ar)return;const or=(yr=rn.caretRangeFromPoint)==null?void 0:yr.call(rn,gr.clientX,gr.clientY),qs=or==null?void 0:or.startContainer;if(qs&&qs.nodeType===Node.TEXT_NODE){const fn=qs.textContent||"",Zn=or.startOffset,Xt=fn.lastIndexOf("[",Zn),rr=fn.indexOf("]",Zn);if(Xt!==-1&&rr!==-1&&rr>Xt){const Qn=rn.createRange();Qn.setStart(qs,Xt),Qn.setEnd(qs,rr+1),Ar.removeAllRanges(),Ar.addRange(Qn),g.current=Qn.cloneRange()}}};Ps.addEventListener("click",Zs,!0)};((_t=Nt.contentDocument)==null?void 0:_t.readyState)==="complete"||(Xs=Nt.contentDocument)!=null&&Xs.body?Ds():Nt.addEventListener("load",Ds,{once:!0})},[s]);const v=(Nt,Ds)=>{var rn;const _t=(rn=r.current)==null?void 0:rn.contentDocument;if(!_t)return;_t.body.focus(),_t.execCommand(Nt,!1,Ds);const Xs=` `+_t.documentElement.outerHTML;a.current=Xs,i.current(Xs)},N=()=>{const Nt=window.prompt("Enter URL (https://...)");Nt&&v("createLink",Nt)},C=(Nt,Ds)=>{var rn;const _t=(rn=r.current)==null?void 0:rn.contentDocument;if(!_t)return;if(_t.body.focus(),Ds==="cursor"&&g.current&&_t.body.contains(g.current.startContainer)){const Ps=_t.getSelection();if(Ps){Ps.removeAllRanges(),Ps.addRange(g.current),_t.execCommand("insertHTML",!1,Nt);const _n=` `+_t.documentElement.outerHTML;a.current=_n,i.current(_n);return}}Ds==="top"?_t.body.insertAdjacentHTML("afterbegin",Nt):_t.body.insertAdjacentHTML("beforeend",Nt);const Xs=` `+_t.documentElement.outerHTML;a.current=Xs,i.current(Xs)},[A,T]=j.useState(!1),[P,M]=j.useState(null),[I,D]=j.useState(""),[B,q]=j.useState(""),[W,V]=j.useState("#406E71"),[K,Q]=j.useState("cursor"),J=Nt=>{M(Nt),D(Nt.defaultText),q(""),T(!0)},ce=()=>{if(!P)return;const Nt=B.trim();if(!P.isForward&&!Nt)return;let Ds=Nt;if(P.isForward){const Ps=Nt||"",_n=encodeURIComponent("You should see this newsletter"),Zs=encodeURIComponent(Ps?`I thought you'd like this — take a look: ${Ps} `:`I thought you'd like this newsletter — take a look! `);Ds=`mailto:?subject=${_n}&body=${Zs}`}else P.hrefPrefix==="tel:"?Ds="tel:"+Nt.replace(/[^0-9+]/g,""):P.hrefPrefix==="mailto:"?Ds="mailto:"+Nt:/^https?:\/\//i.test(Nt)||(Ds="https://"+Nt);const _t=(I||P.defaultText).replace(/[<>]/g,""),Xs=W||"#406E71",rn=`
${_t}

 

`;C(rn,K),T(!1)},[ue,ne]=j.useState(!1),[ee,le]=j.useState(""),[he,ve]=j.useState(""),[ge,fe]=j.useState(""),[je,Ee]=j.useState("cursor"),Me=(()=>{if(he.trim())return he.trim();const Nt=Uft(ee);return Nt?`https://i.ytimg.com/vi/${Nt}/hqdefault.jpg`:""})(),De=()=>{le(""),ve(""),fe(""),ne(!0)},ze=()=>{const Nt=ee.trim();if(!Nt)return;let Ds=Nt;/^https?:\/\//i.test(Ds)||(Ds="https://"+Ds);const _t=Uft(Ds),Xs=_t?null:Qvn(Ds);let rn=he.trim();!rn&&_t&&(rn=`https://i.ytimg.com/vi/${_t}/hqdefault.jpg`),!rn&&Xs&&(rn=`https://vumbnail.com/${Xs}.jpg`),rn||(rn="https://placehold.co/600x340/406E71/ffffff?text=Watch+Video");const Ps=(ge||"Watch the video").replace(/[<>]/g,""),_n=`
${Ps}
▶ ${Ps}

 

`.trim();C(_n,je),ne(!1)},[ke,Xe]=j.useState(!1),[Se,Re]=j.useState(""),[Ae,Be]=j.useState(""),[qe,Ke]=j.useState("full"),[Ze,Ue]=j.useState("cursor"),[et,Qe]=j.useState(!1),Ge=j.useRef(null),nt=()=>{Re(""),Be(""),Ke("full"),Xe(!0)},ft=async Nt=>{var Ds;if(!n){ae.error("You must be signed in to upload images");return}if(Nt.size>10*1024*1024){ae.error("Image must be under 10MB");return}Qe(!0);try{const _t=((Ds=Nt.name.split(".").pop())==null?void 0:Ds.toLowerCase())||"png",Xs=`${n.id}/newsletters/${Date.now()}-${Math.random().toString(36).slice(2,8)}.${_t}`,{error:rn}=await U.storage.from("email-assets").upload(Xs,Nt,{cacheControl:"3600",upsert:!1,contentType:Nt.type});if(rn)throw rn;const{data:Ps}=U.storage.from("email-assets").getPublicUrl(Xs);Re(Ps.publicUrl),ae.success("Image uploaded")}catch(_t){ae.error(_t.message||"Upload failed")}finally{Qe(!1)}},lt=()=>{if(!Se.trim())return;const Nt=(Ae||"").replace(/[<>"]/g,""),Ds=qe==="half"?280:560,_t=`
${Nt}

 

`.trim();C(_t,Ze),Xe(!1)},{data:Mt,isLoading:Ft}=ht({queryKey:["newsletter-editor-videos",n==null?void 0:n.id],enabled:!!(n!=null&&n.id)&&ue,queryFn:async()=>{const{data:Nt,error:Ds}=await U.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(Ds)throw Ds;return Nt||[]}}),Ts=Nt=>{Nt.share_token&&(le(`https://video.relevelup.com/share/video/${Nt.share_token}`),ve(`https://video.relevelup.com/thumb/${Nt.share_token}`),fe(Nt.title||"Watch the video"))},js=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($,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:()=>v("bold"),title:"Bold",children:e.jsx(pT,{className:"h-3.5 w-3.5"})}),e.jsx($,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:()=>v("italic"),title:"Italic",children:e.jsx(_T,{className:"h-3.5 w-3.5"})}),e.jsx($,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:()=>v("underline"),title:"Underline",children:e.jsx(Vz,{className:"h-3.5 w-3.5"})}),e.jsx("div",{className:"w-px h-5 bg-border mx-1"}),e.jsx($,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:()=>v("insertUnorderedList"),title:"Bullet list",children:e.jsx(Sg,{className:"h-3.5 w-3.5"})}),e.jsx($,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:()=>v("insertOrderedList"),title:"Numbered list",children:e.jsx(qj,{className:"h-3.5 w-3.5"})}),e.jsx($,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:N,title:"Insert link",children:e.jsx(kc,{className:"h-3.5 w-3.5"})}),e.jsx("div",{className:"w-px h-5 bg-border mx-1"}),e.jsx($,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:()=>v("undo"),title:"Undo",children:e.jsx(PT,{className:"h-3.5 w-3.5"})}),e.jsx($,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:()=>v("redo"),title:"Redo",children:e.jsx(ET,{className:"h-3.5 w-3.5"})}),e.jsx("div",{className:"w-px h-5 bg-border mx-1"}),e.jsxs(Hd,{children:[e.jsx(Gd,{asChild:!0,children:e.jsxs($,{type:"button",variant:"ghost",size:"sm",className:"h-7 px-2 gap-1.5",title:"Insert CTA Button",children:[e.jsx(uu,{className:"h-3.5 w-3.5"}),e.jsx("span",{className:"text-xs font-medium",children:"CTA Button"})]})}),e.jsxs(Md,{align:"start",className:"w-56 bg-popover z-50",children:[e.jsx(iO,{children:"Insert a call-to-action"}),e.jsx(S0,{}),Xvn.map(Nt=>{const Ds=Nt.icon;return e.jsxs(Na,{onClick:()=>J(Nt),children:[e.jsx(Ds,{className:"h-4 w-4 mr-2"}),Nt.label]},Nt.key)})]})]}),e.jsxs($,{type:"button",variant:"ghost",size:"sm",className:"h-7 px-2 gap-1.5",title:"Insert image",onClick:nt,children:[e.jsx(Jl,{className:"h-3.5 w-3.5"}),e.jsx("span",{className:"text-xs font-medium",children:"Image"})]}),e.jsxs($,{type:"button",variant:"ghost",size:"sm",className:"h-7 px-2 gap-1.5",title:"Insert video block",onClick:De,children:[e.jsx(Xr,{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(iB,{type:"single",value:l,onValueChange:Nt=>Nt&&o(Nt),size:"sm",className:"h-7",children:[e.jsx(OR,{value:"desktop",className:"h-7 px-2",title:"Desktop preview",children:e.jsx(Hj,{className:"h-3.5 w-3.5"})}),e.jsx(OR,{value:"mobile",className:"h-7 px-2",title:"Mobile preview",children:e.jsx(dv,{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(uu,{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:js,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(Os,{open:d,onOpenChange:u,children:e.jsxs(Rs,{className:"sm:max-w-md",children:[e.jsx(Us,{children:e.jsx(zs,{children:"Edit link"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"link-edit-text",children:"Button / link text"}),e.jsx(be,{id:"link-edit-text",value:p,onChange:Nt=>x(Nt.target.value),placeholder:"Click here"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"link-edit-href",children:"Where should this link go?"}),e.jsx(be,{id:"link-edit-href",value:h,onChange:Nt=>m(Nt.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(kr,{children:[e.jsx($,{type:"button",variant:"outline",onClick:()=>u(!1),children:"Cancel"}),e.jsx($,{type:"button",onClick:b,disabled:!h.trim(),children:"Save link"})]})]})}),e.jsx(Os,{open:A,onOpenChange:T,children:e.jsxs(Rs,{className:"sm:max-w-md",children:[e.jsx(Us,{children:e.jsxs(zs,{children:["Insert ",(P==null?void 0:P.label)||"CTA Button"]})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"cta-text",children:"Button text"}),e.jsx(be,{id:"cta-text",value:I,onChange:Nt=>D(Nt.target.value),placeholder:P==null?void 0:P.defaultText})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"cta-value",children:P==null?void 0:P.helper}),e.jsx(be,{id:"cta-value",value:B,onChange:Nt=>q(Nt.target.value),placeholder:P==null?void 0:P.placeholder,autoFocus:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"cta-color",children:"Button color"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(be,{id:"cta-color",type:"color",value:W,onChange:Nt=>V(Nt.target.value),className:"h-9 w-16 p-1 cursor-pointer"}),e.jsx(be,{value:W,onChange:Nt=>V(Nt.target.value),className:"flex-1"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Position"}),e.jsxs(wb,{value:K,onValueChange:Nt=>Q(Nt),className:"flex gap-4 flex-wrap",children:[e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(rh,{value:"cursor",id:"cta-cursor"}),e.jsxs(se,{htmlFor:"cta-cursor",className:"flex items-center gap-1.5 cursor-pointer font-normal",children:[e.jsx(uu,{className:"h-3.5 w-3.5"}),"At cursor"]})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(rh,{value:"top",id:"cta-top"}),e.jsxs(se,{htmlFor:"cta-top",className:"flex items-center gap-1.5 cursor-pointer font-normal",children:[e.jsx(sp,{className:"h-3.5 w-3.5"}),"Top of newsletter"]})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(rh,{value:"bottom",id:"cta-bottom"}),e.jsxs(se,{htmlFor:"cta-bottom",className:"flex items-center gap-1.5 cursor-pointer font-normal",children:[e.jsx(ax,{className:"h-3.5 w-3.5"}),"Bottom of newsletter"]})]})]})]}),e.jsx("div",{className:"rounded-md border bg-muted/30 p-4 flex justify-center",children:e.jsx("div",{style:{backgroundColor:W,color:"#ffffff",borderRadius:6,padding:"14px 28px",fontFamily:"Arial, sans-serif",fontWeight:600,fontSize:16},children:I||(P==null?void 0:P.defaultText)})})]}),e.jsxs(kr,{children:[e.jsx($,{type:"button",variant:"outline",onClick:()=>T(!1),children:"Cancel"}),e.jsx($,{type:"button",onClick:ce,disabled:!(P!=null&&P.isForward)&&!B.trim(),children:"Insert Button"})]})]})}),e.jsx(Os,{open:ue,onOpenChange:ne,children:e.jsxs(Rs,{className:"sm:max-w-lg max-h-[90vh] overflow-y-auto",children:[e.jsx(Us,{children:e.jsx(zs,{children:"Insert Video Block"})}),e.jsxs(ua,{defaultValue:"library",className:"space-y-3",children:[e.jsxs(ha,{className:"grid w-full grid-cols-3",children:[e.jsx(Qt,{value:"library",children:"My Library"}),e.jsx(Qt,{value:"url",children:"From URL"}),e.jsx(Qt,{value:"record",children:"Record New"})]}),e.jsxs(Jt,{value:"library",className:"space-y-3 mt-2",children:[Ft?e.jsxs("div",{className:"text-center py-8 text-sm text-muted-foreground",children:[e.jsx(Ht,{className:"h-5 w-5 animate-spin mx-auto mb-2"}),"Loading your videos..."]}):!Mt||Mt.length===0?e.jsxs("div",{className:"text-center py-8 text-sm text-muted-foreground border rounded-md",children:[e.jsx(Xr,{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:Mt.map(Nt=>{const Ds=ee.includes(Nt.share_token||"___"),_t=Nt.share_token?`https://video.relevelup.com/thumb/${Nt.share_token}`:Nt.thumbnail_url||"";return e.jsxs("button",{type:"button",onClick:()=>Ts(Nt),className:`group text-left rounded-md border-2 overflow-hidden transition-all ${Ds?"border-primary ring-2 ring-primary/30":"border-transparent hover:border-primary/40"}`,children:[e.jsxs("div",{className:"aspect-video bg-muted relative",children:[_t?e.jsx("img",{src:_t,alt:Nt.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(Xr,{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(Td,{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:Nt.title||"Untitled"})})]},Nt.id)})}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{htmlFor:"vid-title-lib",className:"text-xs",children:"Caption (optional)"}),e.jsx(be,{id:"vid-title-lib",value:ge,onChange:Nt=>fe(Nt.target.value),placeholder:"Watch the video"})]})]}),e.jsxs(Jt,{value:"url",className:"space-y-3 mt-2",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{htmlFor:"vid-url",children:"Video URL"}),e.jsx(be,{id:"vid-url",value:ee,onChange:Nt=>le(Nt.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(se,{htmlFor:"vid-title",children:"Caption (optional)"}),e.jsx(be,{id:"vid-title",value:ge,onChange:Nt=>fe(Nt.target.value),placeholder:"Watch the video"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{htmlFor:"vid-thumb",children:"Custom thumbnail URL (optional)"}),e.jsx(be,{id:"vid-thumb",value:he,onChange:Nt=>ve(Nt.target.value),placeholder:"https://... (only if not YouTube/Vimeo)"})]})]}),e.jsx(Jt,{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(Xr,{className:"h-10 w-10 mx-auto text-primary"}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:"Record a quick video"}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:`Record a personal intro, market update, or property tour. When you're done, it'll show up in "My Library" and you can pick it from there.`})]}),e.jsx($,{type:"button",onClick:()=>{window.open("/mission-control/video/record","_blank")},children:"Open Video Recorder"}),e.jsx("p",{className:"text-[11px] text-muted-foreground",children:"Opens in a new tab — come back here when you're done."})]})})]}),e.jsxs("div",{className:"space-y-2 pt-2 border-t",children:[e.jsx(se,{children:"Position"}),e.jsxs(wb,{value:je,onValueChange:Nt=>Ee(Nt),className:"flex gap-4 flex-wrap",children:[e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(rh,{value:"cursor",id:"vid-cursor"}),e.jsxs(se,{htmlFor:"vid-cursor",className:"flex items-center gap-1.5 cursor-pointer font-normal",children:[e.jsx(uu,{className:"h-3.5 w-3.5"}),"At cursor"]})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(rh,{value:"top",id:"vid-top"}),e.jsxs(se,{htmlFor:"vid-top",className:"flex items-center gap-1.5 cursor-pointer font-normal",children:[e.jsx(sp,{className:"h-3.5 w-3.5"}),"Top"]})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(rh,{value:"bottom",id:"vid-bottom"}),e.jsxs(se,{htmlFor:"vid-bottom",className:"flex items-center gap-1.5 cursor-pointer font-normal",children:[e.jsx(ax,{className:"h-3.5 w-3.5"}),"Bottom"]})]})]})]}),Me&&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:Me,alt:"thumbnail",className:"w-full rounded-md",style:{maxHeight:180,objectFit:"cover"},onError:Nt=>{Nt.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(kr,{children:[e.jsx($,{type:"button",variant:"outline",onClick:()=>ne(!1),children:"Cancel"}),e.jsx($,{type:"button",onClick:ze,disabled:!ee.trim(),children:"Insert Video"})]})]})}),e.jsx(Os,{open:ke,onOpenChange:Xe,children:e.jsxs(Rs,{className:"sm:max-w-md max-h-[90vh] overflow-y-auto",children:[e.jsx(Us,{children:e.jsx(zs,{children:"Insert Image"})}),e.jsxs(ua,{defaultValue:"library",className:"space-y-3",children:[e.jsxs(ha,{className:"grid w-full grid-cols-3",children:[e.jsx(Qt,{value:"library",children:"Library"}),e.jsx(Qt,{value:"upload",children:"Upload"}),e.jsx(Qt,{value:"url",children:"From URL"})]}),e.jsx(Jt,{value:"library",className:"mt-2",children:e.jsx(OFt,{maxHeight:"380px",onSelect:Nt=>{Re(Nt.image_url),Ae||Be(Nt.title)}})}),e.jsxs(Jt,{value:"upload",className:"space-y-3 mt-2",children:[e.jsx("input",{ref:Ge,type:"file",accept:"image/png,image/jpeg,image/webp,image/gif",className:"hidden",onChange:Nt=>{var _t;const Ds=(_t=Nt.target.files)==null?void 0:_t[0];Ds&&ft(Ds),Nt.target.value=""}}),Se?e.jsxs("div",{className:"rounded-md border overflow-hidden bg-muted/30",children:[e.jsx("img",{src:Se,alt:"Preview",className:"w-full max-h-48 object-contain"}),e.jsxs("div",{className:"flex justify-between items-center p-2 text-xs",children:[e.jsx("span",{className:"text-muted-foreground truncate",children:"Uploaded ✓"}),e.jsx($,{type:"button",variant:"ghost",size:"sm",onClick:()=>Re(""),children:"Replace"})]})]}):e.jsx("button",{type:"button",onClick:()=>{var Nt;return(Nt=Ge.current)==null?void 0:Nt.click()},disabled:et,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:et?e.jsxs(e.Fragment,{children:[e.jsx(Ht,{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(si,{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(Jt,{value:"url",className:"space-y-3 mt-2",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{htmlFor:"img-url",children:"Image URL"}),e.jsx(be,{id:"img-url",value:Se,onChange:Nt=>Re(Nt.target.value),placeholder:"https://..."})]}),Se&&/^https?:\/\//i.test(Se)&&e.jsx("div",{className:"rounded-md border overflow-hidden bg-muted/30",children:e.jsx("img",{src:Se,alt:"Preview",className:"w-full max-h-48 object-contain",onError:Nt=>{Nt.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(se,{htmlFor:"img-alt",children:"Alt text (for accessibility)"}),e.jsx(be,{id:"img-alt",value:Ae,onChange:Nt=>Be(Nt.target.value),placeholder:"Describe the image"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:"Size"}),e.jsxs(wb,{value:qe,onValueChange:Nt=>Ke(Nt),className:"flex gap-4",children:[e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(rh,{value:"full",id:"img-full"}),e.jsx(se,{htmlFor:"img-full",className:"cursor-pointer font-normal",children:"Full width"})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(rh,{value:"half",id:"img-half"}),e.jsx(se,{htmlFor:"img-half",className:"cursor-pointer font-normal",children:"Half width"})]})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:"Position"}),e.jsxs(wb,{value:Ze,onValueChange:Nt=>Ue(Nt),className:"flex gap-4 flex-wrap",children:[e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(rh,{value:"cursor",id:"img-cursor"}),e.jsxs(se,{htmlFor:"img-cursor",className:"flex items-center gap-1.5 cursor-pointer font-normal",children:[e.jsx(uu,{className:"h-3.5 w-3.5"}),"At cursor"]})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(rh,{value:"top",id:"img-top"}),e.jsxs(se,{htmlFor:"img-top",className:"flex items-center gap-1.5 cursor-pointer font-normal",children:[e.jsx(sp,{className:"h-3.5 w-3.5"}),"Top"]})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(rh,{value:"bottom",id:"img-bottom"}),e.jsxs(se,{htmlFor:"img-bottom",className:"flex items-center gap-1.5 cursor-pointer font-normal",children:[e.jsx(ax,{className:"h-3.5 w-3.5"}),"Bottom"]})]})]})]})]}),e.jsxs(kr,{children:[e.jsx($,{type:"button",variant:"outline",onClick:()=>Xe(!1),children:"Cancel"}),e.jsx($,{type:"button",onClick:lt,disabled:!Se.trim()||et,children:"Insert Image"})]})]})})]})}const qft="newsletter-content",Jvn="inline-images";function e1n(s,t){const n=atob(s),r=new Array(n.length);for(let a=0;a{const{data:M}=await U.from("team_members").select("team_id, role").eq("user_id",a.id).maybeSingle();return M}}),A=(C==null?void 0:C.role)==="team_leader",T=(C==null?void 0:C.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)??n1n()),g((n==null?void 0:n.is_template)??!1),b((n==null?void 0:n.share_scope)??"private"))},[s,n]);const P=async()=>{if(a){if(!c.trim()){ae.error("Please enter a title");return}if(!m.trim()){ae.error("Newsletter content is empty");return}N(!0);try{const M=await t1n(m);M!==m&&p(M);const I={user_id:a.id,title:c.trim(),description:u.trim()||null,html_content:M,is_template:x,share_scope:y,shared_team_id:y==="team"?T:null,shared_brokerage_id:y==="brokerage"?o:null};if(y==="team"&&!T){ae.error("You must be a team leader to share with a team"),N(!1);return}if(y==="brokerage"&&!l){ae.error("Only brokerage managers can share to a brokerage"),N(!1);return}if(y==="global"&&!i){ae.error("Only admins can publish global starter templates"),N(!1);return}let D;if(n!=null&&n.id?{error:D}=await U.from("agent_custom_newsletters").update(I).eq("id",n.id):{error:D}=await U.from("agent_custom_newsletters").insert(I),D)throw D;ae.success(n!=null&&n.id?"Saved":"Newsletter created"),r==null||r(),t(!1)}catch(M){ae.error(M.message||"Failed to save")}finally{N(!1)}}};return e.jsx(Os,{open:s,onOpenChange:t,children:e.jsxs(Rs,{className:"max-w-6xl h-[92vh] flex flex-col p-0",children:[e.jsx(Us,{className:"px-6 pt-6 pb-3 border-b",children:e.jsx(zs,{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(se,{htmlFor:"acn-title",children:"Title *"}),e.jsx(be,{id:"acn-title",value:c,onChange:M=>d(M.target.value),placeholder:"e.g. June Market Update"})]}),e.jsxs("div",{children:[e.jsx(se,{htmlFor:"acn-desc",children:"Description (optional)"}),e.jsx(be,{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(Tn,{id:"acn-template",checked:x,onCheckedChange:g}),e.jsx(se,{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(se,{className:"text-sm font-semibold",children:"Sharing"}),e.jsxs(wb,{value:y,onValueChange:M=>b(M),className:"space-y-2",children:[e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx(rh,{value:"private",id:"s-private",className:"mt-0.5"}),e.jsxs(se,{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(rh,{value:"team",id:"s-team",className:"mt-0.5"}),e.jsxs(se,{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(rh,{value:"brokerage",id:"s-brokerage",className:"mt-0.5"}),e.jsxs(se,{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(rh,{value:"global",id:"s-global",className:"mt-0.5"}),e.jsxs(se,{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(se,{className:"mb-2 block",children:"Content"}),e.jsx(FFt,{html:m,onChange:p})]})]}),e.jsxs(kr,{className:"px-6 py-3 border-t",children:[e.jsx($,{variant:"outline",onClick:()=>t(!1),disabled:v,children:"Cancel"}),e.jsxs($,{onClick:P,disabled:v,children:[v?e.jsx(Ht,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(Jo,{className:"h-4 w-4 mr-2"}),n!=null&&n.id?"Save Changes":"Create"]})]})]})})}function n1n(){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 cYe=/\[[^\]\[<>]{2,80}\]/g,r1n=/^\[\s*(?:\/?\s*if\b[^\]]*|endif|else|x-apple-[\w-]*|data-[\w-]*|object [^\]]*|cdata[^\]]*)\s*\]$/i;function dYe(s){return!r1n.test(s)}function a1n(s){return(s.match(cYe)||[]).filter(dYe)}function Vft(s){const t=s.toLowerCase();return t.charAt(0).toUpperCase()+t.slice(1)}function i1n(s){const t=[],n=new RegExp(cYe.source,"g");let r;for(;(r=n.exec(s))!==null;)dYe(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 · ${Vft(h)}`:`Date ${i[l.token]}`:(m=Vft(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 o1n({html:s,onChange:t,originalHtml:n}){const r=j.useMemo(()=>i1n(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 b=new RegExp(cYe.source,"g");let v=0;const N=s.replace(b,C=>{if(!dYe(C))return C;const A=(a[v]||"").trim();return v+=1,A||C});N!==s&&(o(C=>[...C,{html:s,values:a}]),d.current=!0,i({}),t(N))},h=()=>{const b=l[l.length-1];b&&(o(v=>v.slice(0,-1)),d.current=!0,i(b.values),t(b.html))},m=()=>{const b=c.current;!b||b===s||(o([]),d.current=!0,i({}),t(b))},p=l.length>0,x=!!c.current&&c.current!==s,g=e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs($,{type:"button",size:"sm",variant:"outline",onClick:h,disabled:!p,children:[e.jsx(eY,{className:"h-3.5 w-3.5 mr-1"}),"Undo last fill"]}),e.jsxs($,{type:"button",size:"sm",variant:"ghost",onClick:m,disabled:!x,children:[e.jsx(Ih,{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(Fr,{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||x)&&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?"}),g]})]});const y=r.filter(b=>(a[b.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(mc,{className:"h-4 w-4 text-amber-600 mt-0.5 shrink-0"}),e.jsxs("div",{children:[e.jsx("div",{className:"text-sm font-semibold",children:"Customize before you send"}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["This template has ",r.length," field",r.length===1?"":"s"," that only you can fill in (local dates, events, favorite spots). Sending is locked until they're done."]})]})]}),e.jsxs($e,{variant:"secondary",className:"shrink-0",children:[y,"/",r.length," ready"]})]}),e.jsx("div",{className:"grid grid-cols-1 gap-4",children:r.map(b=>e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{className:"text-[11px] uppercase tracking-wide text-muted-foreground",children:b.label}),e.jsx(be,{value:a[b.index]||"",placeholder:b.hint,className:"h-10 text-sm",onChange:v=>i(N=>({...N,[b.index]:v.target.value})),onKeyDown:v=>{v.key==="Enter"&&(v.preventDefault(),u())}})]},b.index))}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs($,{type:"button",size:"sm",onClick:u,children:[e.jsx(Iz,{className:"h-3.5 w-3.5 mr-1"}),"Apply to email"]}),g]}),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 iV(){var a;const{user:s}=_s(),{data:t,isLoading:n}=ht({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([U.from("mass_email_settings").select("reply_to_email, display_name").eq("user_id",s.id).maybeSingle(),U.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 Kee(){const{user:s}=_s();return ht({queryKey:["verified-sender-check",s==null?void 0:s.id],enabled:!!s,staleTime:3e4,queryFn:async()=>{const[t,n]=await Promise.all([U.from("user_verified_senders").select("id, email, status").eq("user_id",s.id),U.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 OEe({open:s,onOpenChange:t,hasPending:n,pendingEmails:r}){const a=Vn();return e.jsx(Os,{open:s,onOpenChange:t,children:e.jsxs(Rs,{className:"sm:max-w-md",children:[e.jsxs(Us,{children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx("div",{className:"h-9 w-9 rounded-full bg-amber-500/10 text-amber-600 flex items-center justify-center",children:e.jsx(xo,{className:"h-5 w-5"})}),e.jsx(zs,{children:"Verify your sending email first"})]}),e.jsx(Sr,{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(Hr,{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(nn,{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(kr,{className:"gap-2 sm:gap-2",children:[e.jsx($,{variant:"outline",onClick:()=>t(!1),children:"Not now"}),e.jsxs($,{onClick:()=>{t(!1),a("/mission-control/integrations")},children:[e.jsx(Tr,{className:"h-4 w-4 mr-1"}),n?"Manage senders":"Verify my email"]})]})]})})}function oV(){const s=Za();return ht({queryKey:["custom-tags",s],queryFn:async()=>{const{data:t,error:n}=await U.from("contact_custom_tags").select("*").eq("owner_user_id",s).order("name");if(n)throw n;return t},enabled:!!s})}function l1n(s){return ht({queryKey:["contact-custom-tags",s],queryFn:async()=>{const{data:t,error:n}=await U.from("contact_custom_tag_assignments").select("*, tag:contact_custom_tags(*)").eq("contact_id",s);if(n)throw n;return t},enabled:!!s})}function uYe(){const s=ts(),t=Za();return yt({mutationFn:async({name:n,color:r})=>{const{data:a,error:i}=await U.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 c1n(){const s=ts();return yt({mutationFn:async t=>{const{error:n}=await U.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 d1n(){const s=ts();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 U.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 zFt(){const s=ts();return yt({mutationFn:async({contactId:t,tagId:n})=>{const{error:r}=await U.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 u1n(){const s=ts();return yt({mutationFn:async({contactId:t,tagId:n})=>{const{error:r}=await U.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 FEe(){const s=Za();return ht({queryKey:["all-contact-custom-tags",s],queryFn:async()=>{const{data:t,error:n}=await U.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 hYe(){const{user:s}=_s();return ht({queryKey:["contact-smart-lists",s==null?void 0:s.id],queryFn:async()=>{const{data:t,error:n}=await U.from("contact_smart_lists").select("*").order("created_at",{ascending:!1});if(n)throw n;return t},enabled:!!s})}function BFt(){const s=ts(),{user:t}=_s();return yt({mutationFn:async({name:n,filters:r,sort_by:a})=>{const{data:i,error:l}=await U.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"]}),ja({title:"Smart filter saved"})},onError:n=>{ja({title:"Error saving smart filter",description:n.message,variant:"destructive"})}})}function $Ft(){const s=ts();return yt({mutationFn:async t=>{const{error:n}=await U.from("contact_smart_lists").delete().eq("id",t);if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["contact-smart-lists"]}),ja({title:"Smart filter deleted"})}})}const Hft=s=>s.replace(/&/g,"&").replace(//g,">").replace(/"/g,""");function Gft(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,x)=>m[x]??`{{${x}}}`)}function h1n(s,t,n,r){const a=t.trim()?`
${Hft(t).replace(/\n/g,"
")}
`:"",i=n.trim()?`
${Hft(n).replace(/\n/g,"
")}
`:"",l=r?`
${r}
`:"";return`${a} ${s} ${i} ${l}`}function m1n(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 p1n=["free","act now","click here","limited time","urgent","$$$","100% free","guarantee","no obligation","risk-free","winner","cash bonus","make money","earn extra","amazing"];function f1n(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=p1n.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 mYe({open:s,onOpenChange:t,newsletterId:n,newsletterTitle:r,htmlCode:a}){const{user:i}=_s();ux();const{isReady:l,settings:o}=iV(),{data:c}=Kee(),[d,u]=j.useState(!1),h=Za(),{data:m}=ht({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:tn}=await U.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 tn}}),[p,x]=j.useState("visual"),[g,y]=j.useState("all"),[b,v]=j.useState(""),[N,C]=j.useState(""),[A,T]=j.useState(""),[P,M]=j.useState(""),[I,D]=j.useState(!0),[B,q]=j.useState([]),[W,V]=j.useState(null),[K,Q]=j.useState(new Set),[J,ce]=j.useState(""),[ue,ne]=j.useState(!1),[ee,le]=j.useState(!1),[he,ve]=j.useState(!1),[ge,fe]=j.useState({sent:0,failed:0,total:0,currentName:""}),[je,Ee]=j.useState(!0),[Me,De]=j.useState(!1),[ze,ke]=j.useState([]),[Xe,Se]=j.useState(!1),[Re,Ae]=j.useState(new Set),[Be,qe]=j.useState("now"),[Ke,Ze]=j.useState(""),{data:Ue=[]}=oV(),{data:et=[]}=FEe(),{data:Qe=[]}=hYe(),{data:Ge=[],isLoading:nt}=ht({queryKey:["newsletter-send-contacts",h],enabled:!!h&&s,queryFn:async()=>{const tn=[];let ln=0;const Cr=1e3;for(;;){const{data:ms,error:ot}=await U.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(ln,ln+Cr-1);if(ot)throw ot;if(!ms||ms.length===0||(tn.push(...ms),ms.length{const{data:tn}=await U.from("ses_suppressed_emails").select("email");return(tn||[]).map(ln=>ln.email.toLowerCase())}}),{data:lt}=ht({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:tn}=await U.from("profiles").select("brokerage_id").eq("id",i.id).maybeSingle();if(!(tn!=null&&tn.brokerage_id))return null;const{data:ln}=await U.from("brokerages").select("name, city, state").eq("id",tn.brokerage_id).maybeSingle();return ln}}),{data:Mt}=ht({queryKey:["newsletter-active-lead-site",h],enabled:!!h&&s,staleTime:5*60*1e3,queryFn:async()=>{if(!h)return null;const{data:tn}=await U.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 tn}}),Ft=!!(Mt!=null&&Mt.mls_provider_id),Ts=(Mt==null?void 0:Mt.mls_agent_id)||(Mt==null?void 0:Mt.mls_agent_key)||null,{data:js=[],isLoading:zt}=ht({queryKey:["newsletter-agent-listings",h,Ts],enabled:!!h&&!!Ts&&Xe,staleTime:60*1e3,queryFn:async()=>{if(!Ts)return[];const{data:tn}=await U.from("mlsgrid_listings").select("listing_key, address, city, state, list_price, bedrooms, bathrooms_total, living_area, photos, standard_status, modification_timestamp").eq("list_agent_mls_id",Ts).eq("standard_status","Active").order("modification_timestamp",{ascending:!1}).limit(30);return tn||[]}}),{data:Nt=[],isLoading:Ds}=ht({queryKey:["newsletter-exchange-listings",h],enabled:!!h&&Xe,staleTime:60*1e3,queryFn:async()=>{const{data:tn}=await U.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),ln=tn||[];if(ln.length===0)return[];const Cr=ln.map(vt=>vt.id),{data:ms}=await U.from("listing_photos").select("listing_id, photo_url, is_primary, sort_order").in("listing_id",Cr),ot=new Map,pt=new Map;for(const vt of ms||[])vt.is_primary&&!ot.has(vt.listing_id)&&ot.set(vt.listing_id,vt.photo_url),pt.has(vt.listing_id)||pt.set(vt.listing_id,vt.photo_url);return ln.map(vt=>({...vt,_photo:ot.get(vt.id)||pt.get(vt.id)||""}))}}),{data:_t=!1}=ht({queryKey:["newsletter-exchange-listings-exists",h],enabled:!!h&&s,staleTime:5*60*1e3,queryFn:async()=>{const{count:tn}=await U.from("listings").select("id",{count:"exact",head:!0}).eq("agent_id",h).in("status",["active","coming_soon","office_exclusive","pre_market"]);return(tn||0)>0}}),Xs=j.useMemo(()=>{const tn=new Set(ft);return Ge.filter(ln=>ln.email&&ln.email.includes("@")&&!tn.has(ln.email.toLowerCase()))},[Ge,ft]),rn=j.useMemo(()=>{if(B.length===0)return null;const tn=new Set;for(const ln of et)B.includes(ln.tag_id)&&tn.add(ln.contact_id);return tn},[et,B]),Ps=j.useMemo(()=>Qe.find(tn=>tn.id===W)||null,[Qe,W]),_n=j.useMemo(()=>{var tn;if(g==="all")return Xs;if(g==="tags")return rn?Xs.filter(ln=>rn.has(ln.id)):[];if(g==="smartlists"){if(!Ps)return[];const ln=(((tn=Ps.filters)==null?void 0:tn.search)||"").toLowerCase().trim();return ln?Xs.filter(Cr=>`${Cr.first_name||""} ${Cr.last_name||""}`.toLowerCase().includes(ln)||(Cr.email||"").toLowerCase().includes(ln)):Xs}return Xs.filter(ln=>K.has(ln.id))},[g,Xs,rn,Ps,K]),Zs=j.useMemo(()=>{if(!J.trim())return Xs;const tn=J.toLowerCase();return Xs.filter(ln=>`${ln.first_name||""} ${ln.last_name||""}`.toLowerCase().includes(tn))},[Xs,J]);j.useEffect(()=>{s&&(v(""),C(`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||""),x("light"),y("all"),q([]),V(null),Q(new Set),ce(""),ne(!1),D(!0),Ee(!0),ke([]),qe("now"),Ze(""),fe({sent:0,failed:0,total:0,currentName:""}))},[s,r,a]);const gr=l,Un=j.useMemo(()=>a1n(P||a||""),[P,a]),In=!!(b.trim()&&gr&&_n.length>0&&!ee&&Un.length===0),Ar=tn=>{const ln=P||a,Cr=I&&(m!=null&&m.email_signature)?m.email_signature:null;let ms;return p==="light"?ms=h1n(ln,N,A,Cr):ms=Cr?`${ln}
${Cr}
`:ln,je&&(ms+=m1n(m??null,lt??null,tn.email)),Gft(ms,tn,m??null,(lt==null?void 0:lt.name)??null)},or=j.useMemo(()=>Ar({first_name:"Friend",last_name:"",email:"preview@example.com",phone:"",address:"",city:"",state:"",zip:""}),[p,N,A,P,a,I,m,je,lt]),qs=j.useMemo(()=>f1n(b,p==="advanced"||p==="visual"?P:a),[b,p,P,a]),yr=async()=>{De(!0),ke([]);try{const tn=p==="advanced"||p==="visual"?P:a,{data:ln,error:Cr}=await U.functions.invoke("generate-newsletter-subjects",{body:{newsletterTitle:r,bodyHtml:tn,currentSubject:b}});if(Cr)throw Cr;const ms=ln==null?void 0:ln.subjects;if(!Array.isArray(ms)||ms.length===0)throw new Error("No subjects returned");ke(ms)}catch(tn){const ln=(tn==null?void 0:tn.message)||"Failed to generate subjects";ln.includes("credits exhausted")||ln.includes("402")?ae.error("AI credits exhausted. Please add credits to your workspace."):ln.includes("Rate limit")||ln.includes("429")?ae.error("Rate limit hit — try again in a moment."):ae.error(ln)}finally{De(!1)}},fn=tn=>tn?"$"+Number(tn).toLocaleString("en-US"):"",Zn=()=>{var pt,vt;if(Re.size===0){ae.error("Pick at least one listing first.");return}const tn=(Mt==null?void 0:Mt.subdomain_slug)||"",ln=tn?`https://${tn}.relevelup.com`:"https://relevelup.com",Cr=[];for(const At of js){const Zt=`mls:${At.listing_key}`;if(!Re.has(Zt))continue;const as=Array.isArray(At.photos)&&At.photos.length>0?typeof At.photos[0]=="string"?At.photos[0]:((pt=At.photos[0])==null?void 0:pt.MediaURL)||((vt=At.photos[0])==null?void 0:vt.url)||"":"",Ls=At.bedrooms?`${At.bedrooms} bd`:"",cs=At.bathrooms_total?`${At.bathrooms_total} ba`:"",qt=At.living_area?`${Number(At.living_area).toLocaleString()} sqft`:"";Cr.push({url:`${ln}/listings/${At.listing_key}`,photo:as,price:fn(At.list_price),addr:`${At.address||""}${At.city?", "+At.city:""}`,stats:[Ls,cs,qt].filter(Boolean).join(" • ")})}for(const At of Nt){const Zt=`ex:${At.id}`;if(!Re.has(Zt))continue;const as=At.bedrooms?`${At.bedrooms} bd`:"",Ls=At.bathrooms?`${At.bathrooms} ba`:"",cs=At.square_footage?`${Number(At.square_footage).toLocaleString()} sqft`:"";Cr.push({url:`https://listings.relevelup.com/${At.slug||At.id}`,photo:At._photo||"",price:fn(At.price),addr:`${At.property_address||""}${At.city?", "+At.city:""}`,stats:[as,Ls,cs].filter(Boolean).join(" • ")})}const ot=`

Featured Listings

${Cr.map(At=>`
${At.photo?`${At.addr}`:""}
${At.price}
${At.addr}
${At.stats}
`.trim()).join(` `)}
`.trim();M(At=>(At||a||"")+` `+ot),x("visual"),Ae(new Set),Se(!1),ae.success(`Added ${Cr.length} listing${Cr.length===1?"":"s"} to your newsletter.`)},Xt=()=>Ar({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}}"),rr=()=>Gft(b,{first_name:"__FN__",last_name:"__LN__",email:"__EM__",name:"__NAME__",phone:"__PHONE__",address:"__ADDR__",city:"__CITY__",state:"__STATE__",zip:"__ZIP__"},m??null,(lt==null?void 0:lt.name)??null).replace(/__FN__/g,"{{first_name}}").replace(/__LN__/g,"{{last_name}}").replace(/__EM__/g,"{{email}}").replace(/__NAME__/g,"{{name}}").replace(/__PHONE__/g,"{{phone}}").replace(/__ADDR__/g,"{{address}}").replace(/__CITY__/g,"{{city}}").replace(/__STATE__/g,"{{state}}").replace(/__ZIP__/g,"{{zip}}"),Qn=()=>{if(Un.length>0){ae.error(`Fill in ${Un.length} template field${Un.length===1?"":"s"} before sending.`);return}if(In){if(Be==="later"){if(!Ke){ae.error("Pick a date and time to schedule.");return}const tn=new Date(Ke).getTime();if(Number.isNaN(tn)||tn{if(!(!In||!i)){ve(!1),le(!0),fe({sent:0,failed:0,total:_n.length,currentName:"Preparing campaign…"});try{const ln=`${((o==null?void 0:o.display_name)||"ReLevelUp").toLowerCase().replace(/[^a-z]/g,".")}@send.relevelup.com`,Cr=Xt(),ms=rr(),ot=Be==="later",{data:pt,error:vt}=await U.from("email_campaigns").insert({user_id:h||i.id,name:`Newsletter: ${r}`,subject:ms,body_html:Cr,from_email:ln,reply_to_email:(o==null?void 0:o.reply_to_email)||null,total_recipients:_n.length,status:ot?"scheduled":"draft",scheduled_at:ot?new Date(Ke).toISOString():null}).select("id").single();if(vt)throw vt;fe(Zt=>({...Zt,currentName:"Adding recipients…"}));const At=_n.map(Zt=>({campaign_id:pt.id,contact_id:Zt.id,email:Zt.email,name:[Zt.first_name,Zt.last_name].filter(Boolean).join(" ")||null,status:"pending"}));for(let Zt=0;Zt({...cs,sent:Math.min(Zt+as.length,At.length)}))}if(ot){const{error:Zt}=await U.functions.invoke("ses-schedule-campaign",{body:{action:"schedule",campaign_id:pt.id}});if(Zt)throw Zt;ae.success(`Newsletter scheduled for ${new Date(Ke).toLocaleString()}.`)}else{const{error:Zt}=await U.functions.invoke("ses-send-campaign",{body:{action:"send_campaign",campaign_id:pt.id}});if(Zt)throw Zt;ae.success(`Sending to ${_n.length} contact${_n.length===1?"":"s"}! Open & click tracking will appear in Sent Emails.`)}t(!1)}catch(tn){console.error("Newsletter send failed:",tn),ae.error(`Failed to send: ${tn.message||"Unknown error"}`)}finally{le(!1)}}},$n=tn=>{Q(ln=>{const Cr=new Set(ln);return Cr.has(tn)?Cr.delete(tn):Cr.add(tn),Cr})};return e.jsxs(Os,{open:s,onOpenChange:tn=>!ee&&t(tn),children:[e.jsxs(Rs,{className:"max-w-5xl max-h-[92vh] overflow-y-auto",children:[e.jsx(Us,{children:e.jsxs(zs,{className:"flex items-center gap-2",children:[e.jsx(Br,{className:"h-5 w-5"})," Send Newsletter"]})}),!gr&&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(xo,{className:"h-5 w-5 text-destructive shrink-0 mt-0.5"}),e.jsxs("div",{className:"flex-1",children:[e.jsx("div",{className:"font-semibold text-destructive",children:"Set up Mass Email first"}),e.jsx("p",{className:"text-muted-foreground mt-1",children:"You need to verify your sender email before you can send newsletters. It only takes a minute — we'll send a verification email to confirm you own the address."}),e.jsx($,{size:"sm",className:"mt-3",onClick:()=>{window.open("/mission-control/integrations#mass-email","_blank")},children:"Set up Mass Email →"})]})]}),e.jsxs("div",{className:"grid lg:grid-cols-2 gap-6",children:[e.jsxs("div",{className:"space-y-5",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(se,{children:"Subject"}),e.jsxs($,{type:"button",variant:"ghost",size:"sm",className:"h-7 gap-1 text-xs",onClick:yr,disabled:Me,title:"Generate subject lines with AI",children:[Me?e.jsx(Ht,{className:"h-3 w-3 animate-spin"}):e.jsx(dn,{className:"h-3 w-3"}),"AI Suggestions"]})]}),e.jsx(be,{value:b,onChange:tn=>v(tn.target.value),placeholder:"Newsletter subject"}),ze.length>0&&e.jsxs("div",{className:"rounded-md border bg-primary/5 p-2 space-y-1",children:[e.jsx("p",{className:"text-[11px] font-medium text-muted-foreground px-1",children:"Click to use:"}),ze.map((tn,ln)=>e.jsxs("button",{type:"button",onClick:()=>{v(tn),ke([])},className:"w-full text-left text-sm px-2 py-1.5 rounded hover:bg-primary/10 transition-colors",children:[e.jsx(dn,{className:"h-3 w-3 inline-block mr-1.5 text-primary"}),tn]},ln))]}),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}}"})]})]}),qs.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(zz,{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:qs.map((tn,ln)=>e.jsx("li",{children:tn},ln))})]}),(Ft||_t)&&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(sa,{className:"h-3.5 w-3.5 text-primary"}),"Insert your active listings"]}),e.jsx("p",{className:"text-muted-foreground mt-0.5",children:Ft&&_t?"Pick from your live MLS listings or your Listing Exchange listings.":Ft?"Pick from your live MLS listings and drop them into the email.":"Pick from your Listing Exchange listings and drop them into the email."})]}),e.jsx($,{type:"button",size:"sm",variant:"outline",onClick:()=>Se(!0),children:"Choose listings"})]}),e.jsx(o1n,{html:P||a||"",originalHtml:a||"",onChange:M}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Editing"}),e.jsxs(ua,{value:p,onValueChange:tn=>x(tn),children:[e.jsxs(ha,{className:"grid grid-cols-3 w-full",children:[e.jsxs(Qt,{value:"visual",children:[e.jsx(wm,{className:"h-3 w-3 mr-1"}),"Visual"]}),e.jsxs(Qt,{value:"light",children:[e.jsx(Wr,{className:"h-3 w-3 mr-1"}),"Quick edit"]}),e.jsxs(Qt,{value:"advanced",children:[e.jsx(X4,{className:"h-3 w-3 mr-1"}),"HTML"]})]}),e.jsx(Jt,{value:"visual",className:"mt-3",children:e.jsx(FFt,{html:P,onChange:M})}),e.jsxs(Jt,{value:"light",className:"space-y-3 mt-3",children:[e.jsxs("div",{children:[e.jsx(se,{className:"text-xs text-muted-foreground",children:"Personal intro (above newsletter)"}),e.jsx(Is,{value:N,onChange:tn=>C(tn.target.value),rows:4,placeholder:"Hi {{first_name}}, ..."})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-xs text-muted-foreground",children:"Personal outro (below newsletter)"}),e.jsx(Is,{value:A,onChange:tn=>T(tn.target.value),rows:3,placeholder:"Talk soon!"})]})]}),e.jsxs(Jt,{value:"advanced",className:"mt-3",children:[e.jsx(se,{className:"text-xs text-muted-foreground",children:"Edit full HTML"}),e.jsx(Is,{value:P,onChange:tn=>M(tn.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(Tn,{checked:I&&!!(m!=null&&m.email_signature),disabled:!(m!=null&&m.email_signature),onCheckedChange:D})]}),e.jsxs("div",{className:"flex items-center justify-between rounded-lg border p-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-sm font-medium",children:"Include unsubscribe footer"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Adds your brokerage info and a one-click unsubscribe link. Strongly recommended for deliverability."})]}),e.jsx(Tn,{checked:je,onCheckedChange:Ee})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Recipients"}),e.jsxs(ua,{value:g,onValueChange:tn=>y(tn),children:[e.jsxs(ha,{className:"grid grid-cols-4 w-full",children:[e.jsxs(Qt,{value:"all",children:[e.jsx(qn,{className:"h-3 w-3 mr-1"}),"All"]}),e.jsxs(Qt,{value:"tags",children:[e.jsx(Up,{className:"h-3 w-3 mr-1"}),"Tags"]}),e.jsxs(Qt,{value:"smartlists",children:[e.jsx(MK,{className:"h-3 w-3 mr-1"}),"Lists"]}),e.jsxs(Qt,{value:"individual",children:[e.jsx(Lo,{className:"h-3 w-3 mr-1"}),"Pick"]})]}),e.jsx(Jt,{value:"all",className:"mt-3",children:e.jsxs("div",{className:"rounded-lg border bg-muted/30 p-4 text-sm",children:["Send to ",e.jsx("strong",{children:Xs.length})," contact",Xs.length===1?"":"s"," with a valid, non-suppressed email."]})}),e.jsxs(Jt,{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(Oi,{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(tn=>e.jsxs("label",{className:"flex items-center gap-2 p-1.5 hover:bg-muted rounded cursor-pointer",children:[e.jsx(ui,{checked:B.includes(tn.id),onCheckedChange:ln=>q(Cr=>ln?[...Cr,tn.id]:Cr.filter(ms=>ms!==tn.id))}),e.jsx("span",{className:"inline-block h-2 w-2 rounded-full",style:{background:tn.color||"#406E71"}}),e.jsx("span",{className:"text-sm",children:tn.name})]},tn.id))})]}),e.jsxs(Jt,{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(Oi,{className:"h-40 rounded-lg border p-2",children:Qe.length===0?e.jsx("p",{className:"text-xs text-muted-foreground p-2",children:"No smart lists yet. Save one from the contacts page."}):Qe.map(tn=>e.jsxs("label",{className:"flex items-center gap-2 p-1.5 hover:bg-muted rounded cursor-pointer",children:[e.jsx("input",{type:"radio",name:"smartlist",checked:W===tn.id,onChange:()=>V(tn.id)}),e.jsx("span",{className:"text-sm",children:tn.name})]},tn.id))})]}),e.jsxs(Jt,{value:"individual",className:"mt-3 space-y-2",children:[e.jsx(be,{placeholder:"Search contacts...",value:J,onChange:tn=>ce(tn.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:()=>Q(new Set),children:"Clear"})]}),e.jsxs(Oi,{className:"h-48 rounded-lg border p-2",children:[nt&&e.jsx("p",{className:"text-xs text-muted-foreground p-2",children:"Loading contacts…"}),!nt&&Zs.length===0&&e.jsx("p",{className:"text-xs text-muted-foreground p-2",children:"No matching contacts."}),Zs.slice(0,200).map(tn=>e.jsxs("label",{className:"flex items-center gap-2 p-1.5 hover:bg-muted rounded cursor-pointer",children:[e.jsx(ui,{checked:K.has(tn.id),onCheckedChange:()=>$n(tn.id)}),e.jsxs("div",{className:"text-sm flex-1 min-w-0",children:[e.jsxs("div",{className:"truncate",children:[tn.first_name," ",tn.last_name||""]}),e.jsx("div",{className:"text-xs text-muted-foreground truncate",children:tn.email})]})]},tn.id)),Zs.length>200&&e.jsx("p",{className:"text-xs text-muted-foreground p-2",children:"Showing first 200 — refine search to see more."})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2 pt-1",children:[e.jsxs($e,{variant:"secondary",className:"gap-1",children:[e.jsx(Fr,{className:"h-3 w-3"})," ",_n.length," recipient",_n.length===1?"":"s"]}),gr&&e.jsxs($e,{variant:"outline",className:"gap-1 text-xs",children:["via Mass Email",o!=null&&o.reply_to_email?` (${o.reply_to_email})`:""]})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(se,{children:"Preview"}),e.jsx($,{variant:"ghost",size:"sm",onClick:()=>ne(tn=>!tn),children:ue?e.jsxs(e.Fragment,{children:[e.jsx(b0,{className:"h-3 w-3 mr-1"}),"Hide"]}):e.jsxs(e.Fragment,{children:[e.jsx(ga,{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:or,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)."]})]})]}),ee&&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(Ht,{className:"h-4 w-4 animate-spin"}),"Sending to ",ge.currentName||"..."]}),e.jsxs("span",{className:"text-muted-foreground",children:[ge.sent+ge.failed," / ",ge.total]})]}),e.jsx(Ki,{value:ge.total?(ge.sent+ge.failed)/ge.total*100:0}),ge.failed>0&&e.jsxs("p",{className:"text-xs text-destructive",children:[ge.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(Hr,{className:"h-4 w-4"})," When to send"]}),e.jsxs(wb,{value:Be,onValueChange:tn=>qe(tn),className:"flex flex-col sm:flex-row gap-3",children:[e.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",children:[e.jsx(rh,{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(rh,{value:"later",id:"send-later"}),e.jsxs("span",{className:"text-sm flex items-center gap-1",children:[e.jsx(Xu,{className:"h-3.5 w-3.5"})," Schedule for later"]})]}),Be==="later"&&e.jsx(be,{type:"datetime-local",value:Ke,onChange:tn=>Ze(tn.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:Un.length>0?`${Un.length} template field${Un.length===1?"":"s"} still need${Un.length===1?"s":""} your input before this can go out.`:"Suppressed/unsubscribed contacts are skipped automatically. Open & click tracking is included."}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx($,{variant:"outline",onClick:()=>t(!1),disabled:ee,children:"Cancel"}),e.jsx($,{onClick:Qn,disabled:!In,children:ee?e.jsxs(e.Fragment,{children:[e.jsx(Ht,{className:"h-4 w-4 mr-1 animate-spin"}),"Working…"]}):Be==="later"?e.jsxs(e.Fragment,{children:[e.jsx(Xu,{className:"h-4 w-4 mr-1"}),"Schedule for ",_n.length]}):e.jsxs(e.Fragment,{children:[e.jsx(Br,{className:"h-4 w-4 mr-1"}),"Send to ",_n.length]})})]})]})]})]}),e.jsx(Ll,{open:he,onOpenChange:ve,children:e.jsxs(yl,{children:[e.jsxs(vl,{children:[e.jsx(_l,{children:Be==="later"?"Schedule newsletter?":"Send newsletter?"}),e.jsxs(wl,{children:[Be==="later"?"Schedule ":"Send ",e.jsxs("span",{className:"font-medium text-foreground",children:['"',b,'"']})," to"," ",e.jsxs("span",{className:"font-medium text-foreground",children:[_n.length," contact",_n.length===1?"":"s"]}),Be==="later"&&Ke?` for ${new Date(Ke).toLocaleString()}`:"","? Suppressed and unsubscribed contacts are skipped automatically."]})]}),e.jsxs(bl,{children:[e.jsx(jl,{children:"Cancel"}),e.jsx(fl,{onClick:Sn,children:Be==="later"?e.jsxs(e.Fragment,{children:[e.jsx(Xu,{className:"h-4 w-4 mr-1"}),"Schedule"]}):e.jsxs(e.Fragment,{children:[e.jsx(Br,{className:"h-4 w-4 mr-1"}),"Send to ",_n.length]})})]})]})}),e.jsx(Os,{open:Xe,onOpenChange:Se,children:e.jsxs(Rs,{className:"max-w-2xl max-h-[85vh] overflow-y-auto",children:[e.jsx(Us,{children:e.jsxs(zs,{className:"flex items-center gap-2",children:[e.jsx(sa,{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||Ds)&&e.jsxs("div",{className:"text-sm text-muted-foreground p-6 text-center",children:[e.jsx(Ht,{className:"h-4 w-4 animate-spin inline-block mr-2"}),"Loading your listings…"]}),!zt&&!Ds&&js.length===0&&Nt.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."}),js.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:js.map(tn=>{var ot,pt;const ln=`mls:${tn.listing_key}`,Cr=Re.has(ln),ms=Array.isArray(tn.photos)&&tn.photos.length>0?typeof tn.photos[0]=="string"?tn.photos[0]:((ot=tn.photos[0])==null?void 0:ot.MediaURL)||((pt=tn.photos[0])==null?void 0:pt.url)||"":"";return e.jsxs("button",{type:"button",onClick:()=>{Ae(vt=>{const At=new Set(vt);return At.has(ln)?At.delete(ln):At.size<6?At.add(ln):ae.error("Max 6 listings per newsletter"),At})},className:`relative rounded-lg border-2 overflow-hidden text-left transition-all ${Cr?"border-primary ring-2 ring-primary/30":"border-border hover:border-primary/50"}`,children:[ms&&e.jsx("img",{src:ms,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:tn.list_price?`$${Number(tn.list_price).toLocaleString()}`:""}),e.jsx("div",{className:"text-xs truncate",children:tn.address}),e.jsxs("div",{className:"text-[11px] text-muted-foreground truncate",children:[tn.city,tn.state?`, ${tn.state}`:""]})]}),Cr&&e.jsx("div",{className:"absolute top-1 right-1 bg-primary text-primary-foreground rounded-full p-0.5",children:e.jsx(Fr,{className:"h-4 w-4"})})]},ln)})})]}),Nt.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:Nt.map(tn=>{const ln=`ex:${tn.id}`,Cr=Re.has(ln);return e.jsxs("button",{type:"button",onClick:()=>{Ae(ms=>{const ot=new Set(ms);return ot.has(ln)?ot.delete(ln):ot.size<6?ot.add(ln):ae.error("Max 6 listings per newsletter"),ot})},className:`relative rounded-lg border-2 overflow-hidden text-left transition-all ${Cr?"border-primary ring-2 ring-primary/30":"border-border hover:border-primary/50"}`,children:[tn._photo&&e.jsx("img",{src:tn._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:tn.price?`$${Number(tn.price).toLocaleString()}`:""}),e.jsx("div",{className:"text-xs truncate",children:tn.property_address}),e.jsxs("div",{className:"text-[11px] text-muted-foreground truncate",children:[tn.city,tn.state?`, ${tn.state}`:""]})]}),Cr&&e.jsx("div",{className:"absolute top-1 right-1 bg-primary text-primary-foreground rounded-full p-0.5",children:e.jsx(Fr,{className:"h-4 w-4"})})]},ln)})})]})]}),e.jsxs(kr,{children:[e.jsx($,{variant:"outline",onClick:()=>Se(!1),children:"Cancel"}),e.jsxs($,{onClick:Zn,disabled:Re.size===0,children:["Insert ",Re.size>0?Re.size:""," listing",Re.size===1?"":"s"]})]})]})}),e.jsx(OEe,{open:d,onOpenChange:u,hasPending:!!(c!=null&&c.hasPendingSes),pendingEmails:c==null?void 0:c.pendingEmails})]})}function x1n(){const{user:s}=_s(),t=ts(),[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}=ht({queryKey:["agent-custom-newsletters",s==null?void 0:s.id],enabled:!!(s!=null&&s.id),queryFn:async()=>{const{data:P,error:M}=await U.from("agent_custom_newsletters").select("*").order("updated_at",{ascending:!1});if(M)throw M;return P||[]}}),x=()=>t.invalidateQueries({queryKey:["agent-custom-newsletters"]}),g=(m==null?void 0:m.filter(P=>P.user_id===(s==null?void 0:s.id)&&!P.is_template))??[],y=(m==null?void 0:m.filter(P=>P.user_id===(s==null?void 0:s.id)&&P.is_template))??[],b=(m==null?void 0:m.filter(P=>P.user_id!==(s==null?void 0:s.id)&&P.is_template&&(P.share_scope==="team"||P.share_scope==="brokerage"||P.share_scope==="global")))??[],v=(m==null?void 0:m.filter(P=>P.share_scope==="global"&&P.is_template))??[],N=n==="starters"?v:n==="mine"?g:n==="templates"?y:b.filter(P=>P.share_scope!=="global"),C=async P=>{if(!s)return;const{error:M}=await U.from("agent_custom_newsletters").insert({user_id:s.id,title:`${P.title} (Copy)`,description:P.description,html_content:P.html_content,is_template:!1,share_scope:"private"});if(M){ae.error(M.message);return}ae.success('Duplicated to "My Newsletters"'),x(),r("mine")},A=async P=>{const{error:M}=await U.from("agent_custom_newsletters").delete().eq("id",P);if(M){ae.error(M.message);return}ae.success("Deleted"),h(null),x()},T=P=>P.share_scope==="global"?e.jsxs($e,{variant:"secondary",className:"gap-1",children:[e.jsx(dn,{className:"h-3 w-3"}),"Starter"]}):P.share_scope==="brokerage"?e.jsxs($e,{variant:"secondary",className:"gap-1",children:[e.jsx(Ai,{className:"h-3 w-3"}),"Brokerage"]}):P.share_scope==="team"?e.jsxs($e,{variant:"secondary",className:"gap-1",children:[e.jsx(qn,{className:"h-3 w-3"}),"Team"]}):e.jsxs($e,{variant:"outline",className:"gap-1 text-muted-foreground",children:[e.jsx(Ad,{className:"h-3 w-3"}),"Private"]});return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[e.jsxs("div",{className:"flex gap-2 flex-wrap",children:[e.jsxs($,{variant:n==="starters"?"default":"outline",size:"sm",onClick:()=>r("starters"),className:"gap-1.5",children:[e.jsx(dn,{className:"h-3.5 w-3.5"}),"Starter Templates (",v.length,")"]}),e.jsxs($,{variant:n==="mine"?"default":"outline",size:"sm",onClick:()=>r("mine"),children:["My Newsletters (",g.length,")"]}),e.jsxs($,{variant:n==="templates"?"default":"outline",size:"sm",onClick:()=>r("templates"),children:["My Templates (",y.length,")"]}),e.jsxs($,{variant:n==="shared"?"default":"outline",size:"sm",onClick:()=>r("shared"),children:["Shared with Me (",b.filter(P=>P.share_scope!=="global").length,")"]})]}),e.jsxs($,{onClick:()=>{o(null),i(!0)},children:[e.jsx(sn,{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((P,M)=>e.jsx(on,{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(dn,{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(_e,{children:e.jsxs(Oe,{className:"py-12 text-center text-muted-foreground",children:[e.jsx(Wr,{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(P=>{const M=P.user_id===(s==null?void 0:s.id);return e.jsxs(_e,{className:"overflow-hidden hover:shadow-md transition-shadow",children:[e.jsxs("div",{className:"aspect-[3/2] bg-muted relative overflow-hidden",children:[P.thumbnail_url?e.jsx("img",{src:P.thumbnail_url,alt:P.title,className:"w-full h-full object-cover"}):e.jsx("div",{className:"w-full h-full p-3 overflow-hidden pointer-events-none",dangerouslySetInnerHTML:{__html:`
${P.html_content}
`}}),e.jsxs("div",{className:"absolute top-2 right-2 flex gap-1",children:[P.is_template&&e.jsx($e,{className:"bg-primary/90",children:"Template"}),T(P)]})]}),e.jsxs(Oe,{className:"p-3 space-y-2",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"font-semibold line-clamp-1",children:P.title}),P.description&&e.jsx("p",{className:"text-xs text-muted-foreground line-clamp-1",children:P.description}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-0.5",children:["Updated ",Hs(new Date(P.updated_at||P.created_at),"MMM d, yyyy")]})]}),e.jsxs("div",{className:"flex gap-1.5 flex-wrap",children:[e.jsxs($,{size:"sm",onClick:()=>d(P),className:"flex-1 min-w-[80px]",children:[e.jsx(Br,{className:"h-3.5 w-3.5 mr-1"})," Send"]}),M?e.jsxs(e.Fragment,{children:[e.jsx($,{size:"sm",variant:"outline",onClick:()=>{o(P),i(!0)},children:e.jsx(Ya,{className:"h-3.5 w-3.5"})}),e.jsx($,{size:"sm",variant:"outline",onClick:()=>C(P),children:e.jsx(Ca,{className:"h-3.5 w-3.5"})}),e.jsx($,{size:"sm",variant:"outline",onClick:()=>h(P.id),children:e.jsx(Pn,{className:"h-3.5 w-3.5"})})]}):e.jsxs($,{size:"sm",variant:"outline",onClick:()=>C(P),children:[e.jsx(Ca,{className:"h-3.5 w-3.5 mr-1"})," Use"]})]})]})]},P.id)})}),e.jsx(s1n,{open:a,onOpenChange:i,initial:l,onSaved:x}),c&&e.jsx(mYe,{open:!!c,onOpenChange:P=>!P&&d(null),newsletterId:c.id,newsletterTitle:c.title,htmlCode:c.html_content}),e.jsx(Ll,{open:!!u,onOpenChange:P=>!P&&h(null),children:e.jsxs(yl,{children:[e.jsxs(vl,{children:[e.jsx(_l,{children:"Delete this newsletter?"}),e.jsx(wl,{children:"This cannot be undone."})]}),e.jsxs(bl,{children:[e.jsx(jl,{children:"Cancel"}),e.jsx(fl,{onClick:()=>u&&A(u),children:"Delete"})]})]})})]})}function g1n(){const s=Vn(),[t,n]=j.useState(""),[r,a]=j.useState("grid"),[i,l]=j.useState(null),{data:o,isLoading:c}=ht({queryKey:["newsletters"],queryFn:async()=>{const{data:A,error:T}=await U.from("newsletter_content").select("*").eq("is_published",!0).order("publish_date",{ascending:!1});if(T)throw T;return A}}),{data:d}=ht({queryKey:["newsletter-likes-all"],queryFn:async()=>{const{data:A}=await U.from("newsletter_likes").select("newsletter_id");return A||[]}}),{data:u}=ht({queryKey:["newsletter-comments-all"],queryFn:async()=>{const{data:A}=await U.from("newsletter_comments").select("newsletter_id");return A||[]}}),{data:h}=ht({queryKey:["newsletter-resource-counts"],queryFn:async()=>{const[A,T,P,M]=await Promise.all([U.from("newsletter_canva_links").select("newsletter_id"),U.from("newsletter_pdfs").select("newsletter_id"),U.from("newsletter_videos").select("newsletter_id"),U.from("newsletter_drive_links").select("newsletter_id")]);return{canva:A.data||[],pdfs:T.data||[],videos:P.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,x=A=>{var T;return((T=h==null?void 0:h.canva)==null?void 0:T.filter(P=>P.newsletter_id===A).length)||0},g=A=>{var T;return((T=h==null?void 0:h.pdfs)==null?void 0:T.filter(P=>P.newsletter_id===A).length)||0},y=A=>{var T;return((T=h==null?void 0:h.videos)==null?void 0:T.filter(P=>P.newsletter_id===A).length)||0},b=A=>{var T;return((T=h==null?void 0:h.drives)==null?void 0:T.filter(P=>P.newsletter_id===A).length)||0},v=A=>x(A)+g(A)+y(A)+b(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()))}),C=A=>{s(`/newsletters/${A}`)};return e.jsx(Ks,{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(ua,{defaultValue:"custom",className:"space-y-4",children:[e.jsxs(ha,{children:[e.jsx(Qt,{value:"custom",children:"Build & Send"}),e.jsx(Qt,{value:"curated",children:"Curated Monthly"})]}),e.jsx(Jt,{value:"custom",className:"mt-2",children:e.jsx(x1n,{})}),e.jsxs(Jt,{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(Vr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(be,{placeholder:"Search newsletters...",value:t,onChange:A=>n(A.target.value),className:"pl-9"})]}),e.jsxs("div",{className:"flex gap-2",children:[t&&e.jsx($,{variant:"outline",size:"sm",onClick:()=>n(""),children:"Clear"}),e.jsxs("div",{className:"flex gap-1",children:[e.jsx($,{variant:r==="grid"?"secondary":"outline",size:"icon",onClick:()=>a("grid"),className:"rounded-full",children:e.jsx(_0,{className:"h-4 w-4"})}),e.jsx($,{variant:r==="list"?"secondary":"outline",size:"icon",onClick:()=>a("list"),className:"rounded-full",children:e.jsx(Sg,{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(_e,{children:e.jsxs(Oe,{className:"p-0",children:[e.jsx(on,{className:"aspect-[3/2] w-full"}),e.jsxs("div",{className:"p-4 space-y-2",children:[e.jsx(on,{className:"h-5 w-3/4"}),e.jsx(on,{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(Wr,{className:"h-12 w-12 mx-auto text-muted-foreground mb-4"}),e.jsx("div",{className:"text-muted-foreground mb-4",children:t?"No newsletters match your search":"No newsletters available yet"}),t&&e.jsx($,{variant:"outline",onClick:()=>n(""),children:"Clear Search"})]}),!c&&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=v(A.id),P=x(A.id),M=g(A.id),I=y(A.id);return r==="grid"?e.jsxs(_e,{className:"group overflow-hidden hover:shadow-lg transition-all duration-200 cursor-pointer border-border/50",onClick:()=>C(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(Wr,{className:"h-16 w-16"})})}),e.jsxs(Oe,{className:"p-4 space-y-3",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"font-semibold text-foreground line-clamp-1",children:A.title}),e.jsxs("div",{className:"flex items-center gap-1.5 mt-1 text-xs text-muted-foreground",children:[e.jsx(ia,{className:"h-3 w-3"}),Hs(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:[P>0&&e.jsxs($e,{variant:"secondary",className:"text-xs gap-1 font-normal",children:[e.jsx(Rc,{className:"h-3 w-3"})," ",P," Template",P>1?"s":""]}),M>0&&e.jsxs($e,{variant:"secondary",className:"text-xs gap-1 font-normal",children:[e.jsx(di,{className:"h-3 w-3"})," ",M," PDF",M>1?"s":""]}),I>0&&e.jsxs($e,{variant:"secondary",className:"text-xs gap-1 font-normal",children:[e.jsx(Td,{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(Ox,{className:"h-3 w-3"})," ",m(A.id)]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Ed,{className:"h-3 w-3"})," ",p(A.id)]})]}),A.html_code&&e.jsxs($,{size:"sm",className:"w-full bg-gradient-to-r from-[#2a4c64] to-[#406E71] text-white hover:opacity-90",onClick:D=>{D.stopPropagation(),l(A)},children:[e.jsx(Br,{className:"h-4 w-4 mr-1.5"}),"Send Newsletter"]})]})]},A.id):e.jsx(_e,{className:"group overflow-hidden hover:shadow-md transition-all duration-200 cursor-pointer border-border/50",onClick:()=>C(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(Wr,{className:"h-10 w-10"})})}),e.jsxs(Oe,{className:"p-4 flex-1 flex flex-col justify-center gap-2",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"font-semibold text-foreground line-clamp-1",children:A.title}),e.jsxs("div",{className:"flex items-center gap-1.5 mt-0.5 text-xs text-muted-foreground",children:[e.jsx(ia,{className:"h-3 w-3"}),Hs(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(Ox,{className:"h-3 w-3"})," ",m(A.id)]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Ed,{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($,{size:"sm",className:"bg-gradient-to-r from-[#2a4c64] to-[#406E71] text-white hover:opacity-90",onClick:D=>{D.stopPropagation(),l(A)},children:[e.jsx(Br,{className:"h-4 w-4 mr-1.5"}),"Send"]})})]})},A.id)})})]})]}),(i==null?void 0:i.html_code)&&e.jsx(mYe,{open:!!i,onOpenChange:A=>!A&&l(null),newsletterId:i.id,newsletterTitle:i.title,htmlCode:i.html_code})]})})}function y1n({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(_e,{className:"overflow-hidden border-border/50",children:[i.image_url&&e.jsx("img",{src:i.image_url,alt:i.title||"",className:"w-full h-40 object-cover"}),e.jsxs(Oe,{className:"p-4 space-y-2",children:[i.title&&e.jsx("h4",{className:"font-semibold text-foreground",children:i.title}),i.description&&e.jsx("p",{className:"text-sm text-muted-foreground",children:i.description})]})]},l))},r)})})}function v1n(){const{id:s}=Vi(),t=Vn(),{user:n}=_s(),{toast:r}=gi(),a=ts(),{trackEngagement:i}=Iq(),[l,o]=j.useState(""),[c,d]=j.useState(!1),{data:u,isLoading:h}=ht({queryKey:["newsletter",s],queryFn:async()=>{const{data:P,error:M}=await U.from("newsletter_content").select("*").eq("id",s).single();if(M)throw M;return P},enabled:!!s});j.useEffect(()=>{u&&i("newsletter",u.id,u.title,"view")},[u==null?void 0:u.id]);const{data:m}=ht({queryKey:["newsletter-drives",s],queryFn:async()=>{const{data:P}=await U.from("newsletter_drive_links").select("*").eq("newsletter_id",s).order("sort_order");return P||[]},enabled:!!s}),{data:p}=ht({queryKey:["newsletter-pdfs",s],queryFn:async()=>{const{data:P}=await U.from("newsletter_pdfs").select("*").eq("newsletter_id",s).order("sort_order");return P||[]},enabled:!!s}),{data:x}=ht({queryKey:["newsletter-videos",s],queryFn:async()=>{const{data:P}=await U.from("newsletter_videos").select("*").eq("newsletter_id",s).order("sort_order");return P||[]},enabled:!!s}),{data:g}=ht({queryKey:["newsletter-canva-links",s],queryFn:async()=>{const{data:P}=await U.from("newsletter_canva_links").select("*").eq("newsletter_id",s).order("sort_order");return P||[]},enabled:!!s}),{data:y}=ht({queryKey:["newsletter-likes",s],queryFn:async()=>{const{data:P}=await U.from("newsletter_likes").select("*").eq("newsletter_id",s);return P||[]},enabled:!!s}),{data:b}=ht({queryKey:["newsletter-comments",s],queryFn:async()=>{const{data:P}=await U.from("newsletter_comments").select("*, profiles:user_id(name)").eq("newsletter_id",s).order("created_at",{ascending:!1});return P||[]},enabled:!!s}),v=y==null?void 0:y.some(P=>P.user_id===(n==null?void 0:n.id)),N=yt({mutationFn:async()=>{v?await U.from("newsletter_likes").delete().eq("newsletter_id",s).eq("user_id",n==null?void 0:n.id):await U.from("newsletter_likes").insert({newsletter_id:s,user_id:n==null?void 0:n.id})},onSuccess:()=>{a.invalidateQueries({queryKey:["newsletter-likes",s]})}}),C=yt({mutationFn:async P=>{const{error:M}=await U.from("newsletter_comments").insert({newsletter_id:s,user_id:n==null?void 0:n.id,content:P});if(M)throw M},onSuccess:()=>{a.invalidateQueries({queryKey:["newsletter-comments",s]}),o(""),r({title:"Comment added"})}}),A=yt({mutationFn:async P=>{const{error:M}=await U.from("newsletter_comments").delete().eq("id",P);if(M)throw M},onSuccess:()=>{a.invalidateQueries({queryKey:["newsletter-comments",s]}),r({title:"Comment deleted"})}}),T=P=>{if(P.includes("player.mediadelivery.net")||P.includes("iframe.mediadelivery.net")){const M=P.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(P.includes("youtube.com")||P.includes("youtu.be")){const M=P.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:P,target:"_blank",rel:"noopener noreferrer",className:"flex items-center gap-2 text-primary hover:underline",children:[e.jsx(Td,{className:"h-4 w-4"})," Watch Video"]})};return h?e.jsx(Ks,{title:"",description:"",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(on,{className:"h-8 w-32"}),e.jsx(on,{className:"h-64 w-full"}),e.jsx(on,{className:"h-32 w-full"})]})}):u?e.jsx(Ks,{title:"",description:"",children:e.jsxs("div",{className:"max-w-4xl mx-auto space-y-6",children:[e.jsxs($,{variant:"ghost",onClick:()=>t("/newsletters"),className:"mb-4",children:[e.jsx(ka,{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:Hs(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(y1n,{rows:u.content_blocks||[]}),e.jsxs("div",{className:"flex items-center gap-4 flex-wrap",children:[e.jsx(Fq,{resourceType:"newsletter",resourceId:u.id,resourceTitle:u.title}),e.jsxs($,{variant:v?"default":"outline",size:"sm",onClick:()=>N.mutate(),children:[e.jsx(fo,{className:`h-4 w-4 mr-1 ${v?"fill-current":""}`}),(y==null?void 0:y.length)||0," ",(y==null?void 0:y.length)===1?"Like":"Likes"]}),u.html_code&&e.jsxs($,{size:"sm",className:"bg-gradient-to-r from-[#2a4c64] to-[#406E71] text-white hover:opacity-90",onClick:()=>d(!0),children:[e.jsx(Br,{className:"h-4 w-4 mr-1"}),"Send Newsletter"]})]}),u.html_code&&e.jsx(mYe,{open:c,onOpenChange:d,newsletterId:u.id,newsletterTitle:u.title,htmlCode:u.html_code}),g&&g.length>0&&e.jsxs(_e,{children:[e.jsx(Bt,{children:e.jsx(Ut,{className:"text-lg",children:"Canva Templates"})}),e.jsx(Oe,{className:"space-y-2",children:g.map(P=>e.jsxs("a",{href:P.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(Rc,{className:"h-5 w-5 text-purple-500"}),e.jsx("span",{className:"font-medium",children:P.title}),e.jsx(Tr,{className:"h-4 w-4 text-muted-foreground ml-auto"})]},P.id))})]}),m&&m.length>0&&e.jsxs(_e,{children:[e.jsx(Bt,{children:e.jsx(Ut,{className:"text-lg",children:"Google Drive Files"})}),e.jsx(Oe,{className:"space-y-2",children:m.map(P=>e.jsxs("a",{href:P.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(Tr,{className:"h-5 w-5 text-primary"}),e.jsx("span",{className:"font-medium",children:P.title})]},P.id))})]}),p&&p.length>0&&e.jsxs(_e,{children:[e.jsx(Bt,{children:e.jsx(Ut,{className:"text-lg",children:"PDF Downloads"})}),e.jsx(Oe,{className:"space-y-2",children:p.map(P=>e.jsxs("a",{href:P.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(Wr,{className:"h-5 w-5 text-red-500"}),e.jsx("span",{className:"font-medium flex-1",children:P.name}),e.jsx(di,{className:"h-4 w-4 text-muted-foreground"})]},P.id))})]}),x&&x.length>0&&e.jsxs(_e,{children:[e.jsx(Bt,{children:e.jsx(Ut,{className:"text-lg",children:"Videos"})}),e.jsx(Oe,{className:"space-y-6",children:x.map(P=>e.jsxs("div",{className:"space-y-2",children:[e.jsx("h4",{className:"font-medium",children:P.title}),T(P.video_url)]},P.id))})]}),e.jsxs(_e,{children:[e.jsx(Bt,{children:e.jsxs(Ut,{className:"text-lg",children:["Comments (",(b==null?void 0:b.length)||0,")"]})}),e.jsxs(Oe,{className:"space-y-4",children:[e.jsxs("div",{className:"flex gap-3",children:[e.jsx(Is,{placeholder:"Write a comment...",value:l,onChange:P=>o(P.target.value),className:"flex-1"}),e.jsx($,{onClick:()=>l.trim()&&C.mutate(l),disabled:!l.trim()||C.isPending,children:e.jsx(Br,{className:"h-4 w-4"})})]}),e.jsx("div",{className:"space-y-4",children:b==null?void 0:b.map(P=>{var M,I,D;return e.jsxs("div",{className:"flex gap-3",children:[e.jsx(Ea,{className:"h-8 w-8",children:e.jsx(Ta,{children:((I=(M=P.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:((D=P.profiles)==null?void 0:D.name)||"User"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:Hs(new Date(P.created_at),"MMM d, yyyy")}),P.user_id===(n==null?void 0:n.id)&&e.jsx($,{variant:"ghost",size:"icon",className:"h-6 w-6",onClick:()=>A.mutate(P.id),children:e.jsx(Pn,{className:"h-3 w-3"})})]})]}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:P.content})]})]},P.id)})})]})]})]})}):e.jsx(Ks,{title:"Not Found",description:"",children:e.jsxs("div",{className:"text-center py-12",children:[e.jsx("p",{className:"text-muted-foreground",children:"Newsletter not found"}),e.jsx($,{variant:"link",onClick:()=>t("/newsletters"),children:"Back to Newsletters"})]})})}function b1n({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,x)=>{const g=[...s];g[h]={...g[h],columns:g[h].columns.map((y,b)=>b===m?{...y,[p]:x}:y)},t(g)},d=async(h,m,p)=>{var y;const x=(y=p.target.files)==null?void 0:y[0];if(!x)return;const g=`${h}-${m}`;r(g);try{const b=`content-blocks/${Date.now()}-${x.name}`,{error:v}=await U.storage.from("newsletter-content").upload(b,x);if(!v){const{data:N}=U.storage.from("newsletter-content").getPublicUrl(b);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(se,{className:"text-base font-medium",children:"Content Blocks (3-Column Rows)"}),e.jsxs($,{type:"button",variant:"outline",size:"sm",onClick:l,children:[e.jsx(sn,{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(_e,{className:"relative",children:[e.jsx($,{type:"button",variant:"ghost",size:"icon",className:"absolute top-2 right-2 h-6 w-6 text-muted-foreground hover:text-destructive",onClick:()=>o(m),children:e.jsx(pr,{className:"h-4 w-4"})}),e.jsxs(Oe,{className:"p-4 pt-3",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[e.jsx($p,{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,x)=>{const g=`${m}-${x}`;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 ",x+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($,{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,x),children:e.jsx(pr,{className:"h-3 w-3"})})]}):e.jsxs("div",{className:"grid grid-cols-2 gap-1.5",children:[e.jsx(be,{type:"file",accept:"image/*",className:"hidden",id:`block-img-${g}`,onChange:y=>d(m,x,y)}),e.jsx($,{type:"button",variant:"outline",size:"sm",className:"text-xs h-8",disabled:n===g,asChild:!0,children:e.jsx("label",{htmlFor:`block-img-${g}`,className:"cursor-pointer",children:n===g?"...":e.jsxs(e.Fragment,{children:[e.jsx(Jl,{className:"h-3 w-3 mr-1"})," Upload"]})})}),e.jsxs($,{type:"button",variant:"outline",size:"sm",className:"text-xs h-8",onClick:()=>i({row:m,col:x}),children:[e.jsx(g1,{className:"h-3 w-3 mr-1"})," Library"]})]}),e.jsx(be,{placeholder:"Title",value:p.title,onChange:y=>c(m,x,"title",y.target.value),className:"h-8 text-sm"}),e.jsx(Is,{placeholder:"Description",value:p.description,onChange:y=>c(m,x,"description",y.target.value),className:"text-sm min-h-[60px] resize-none"})]},x)})})]})]},m)),e.jsx(Os,{open:!!a,onOpenChange:h=>!h&&i(null),children:e.jsxs(Rs,{className:"sm:max-w-2xl",children:[e.jsx(Us,{children:e.jsx(zs,{children:"Choose a Graphic"})}),e.jsx(OFt,{onSelect:h=>{a&&(c(a.row,a.col,"image_url",h.image_url),i(null))}})]})})]})}function _1n(){const{toast:s}=gi(),t=ts(),[n,r]=j.useState(!1),[a,i]=j.useState(null),[l,o]=j.useState({title:"",description:"",publish_date:Hs(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([]),[x,g]=j.useState([]),[y,b]=j.useState([]),[v,N]=j.useState([]),[C,A]=j.useState([]),[T,P]=j.useState(""),[M,I]=j.useState([]),[D,B]=j.useState(!1),{data:q,isLoading:W}=ht({queryKey:["admin-newsletters"],queryFn:async()=>{const{data:je,error:Ee}=await U.from("newsletter_content").select("*").order("publish_date",{ascending:!1});if(Ee)throw Ee;return je}}),V=yt({mutationFn:async je=>{const{data:Ee,error:Me}=await U.from("newsletter_content").insert({title:je.title,description:je.description||null,preview_image_url:je.preview_image_url,publish_date:je.publish_date,is_published:je.is_published,content_blocks:je.content_blocks,html_code:je.html_code}).select().single();if(Me)throw Me;return Ee},onSuccess:async je=>{await J(je.id),t.invalidateQueries({queryKey:["admin-newsletters"]}),s({title:"Newsletter created successfully"}),je.is_published&&hqs(je.title,je.id),ne()},onError:je=>{s({title:"Error creating newsletter",description:je.message,variant:"destructive"})}}),K=yt({mutationFn:async je=>{const{error:Ee}=await U.from("newsletter_content").update({title:je.title,description:je.description||null,preview_image_url:je.preview_image_url,publish_date:je.publish_date,is_published:je.is_published,content_blocks:je.content_blocks,html_code:je.html_code}).eq("id",je.id);if(Ee)throw Ee;return je.id},onSuccess:async je=>{await J(je),t.invalidateQueries({queryKey:["admin-newsletters"]}),s({title:"Newsletter updated successfully"}),ne()},onError:je=>{s({title:"Error updating newsletter",description:je.message,variant:"destructive"})}}),Q=yt({mutationFn:async je=>{const{error:Ee}=await U.from("newsletter_content").delete().eq("id",je);if(Ee)throw Ee},onSuccess:()=>{t.invalidateQueries({queryKey:["admin-newsletters"]}),s({title:"Newsletter deleted successfully"})},onError:je=>{s({title:"Error deleting newsletter",description:je.message,variant:"destructive"})}}),J=async je=>{await U.from("newsletter_drive_links").delete().eq("newsletter_id",je),await U.from("newsletter_pdfs").delete().eq("newsletter_id",je),await U.from("newsletter_videos").delete().eq("newsletter_id",je),await U.from("newsletter_canva_links").delete().eq("newsletter_id",je);for(const Ee of M){const Me=`${je}/${Date.now()}-${Ee.file.name}`,{error:De}=await U.storage.from("newsletter-content").upload(Me,Ee.file);if(!De){const{data:ze}=U.storage.from("newsletter-content").getPublicUrl(Me);x.push({name:Ee.name,file_url:ze.publicUrl,file_size:Ee.file.size,sort_order:x.length})}}m.length>0&&await U.from("newsletter_drive_links").insert(m.map((Ee,Me)=>({newsletter_id:je,title:Ee.title,drive_url:Ee.drive_url,sort_order:Me}))),x.length>0&&await U.from("newsletter_pdfs").insert(x.map((Ee,Me)=>({newsletter_id:je,name:Ee.name,file_url:Ee.file_url,file_size:Ee.file_size||null,sort_order:Me}))),y.length>0&&await U.from("newsletter_videos").insert(y.map((Ee,Me)=>({newsletter_id:je,title:Ee.title,video_url:Ee.video_url,sort_order:Me}))),v.length>0&&await U.from("newsletter_canva_links").insert(v.map((Ee,Me)=>({newsletter_id:je,title:Ee.title,canva_share_link:Ee.canva_share_link,sort_order:Me})))},ce=async je=>{i(je),o({title:je.title,description:je.description||"",publish_date:Hs(new Date(je.publish_date),"yyyy-MM-dd'T'HH:mm"),is_published:je.is_published}),h(je.preview_image_url),A(je.content_blocks||[]),P(je.html_code||"");const[Ee,Me,De,ze]=await Promise.all([U.from("newsletter_drive_links").select("*").eq("newsletter_id",je.id).order("sort_order"),U.from("newsletter_pdfs").select("*").eq("newsletter_id",je.id).order("sort_order"),U.from("newsletter_videos").select("*").eq("newsletter_id",je.id).order("sort_order"),U.from("newsletter_canva_links").select("*").eq("newsletter_id",je.id).order("sort_order")]);p(Ee.data||[]),g(Me.data||[]),b(De.data||[]),N(ze.data||[]),I([]),r(!0)},ue=async je=>{const[Ee,Me,De,ze]=await Promise.all([U.from("newsletter_drive_links").select("*").eq("newsletter_id",je.id).order("sort_order"),U.from("newsletter_pdfs").select("*").eq("newsletter_id",je.id).order("sort_order"),U.from("newsletter_videos").select("*").eq("newsletter_id",je.id).order("sort_order"),U.from("newsletter_canva_links").select("*").eq("newsletter_id",je.id).order("sort_order")]);i(null),o({title:`${je.title} (Copy)`,description:je.description||"",publish_date:Hs(new Date,"yyyy-MM-dd'T'HH:mm"),is_published:!1}),h(je.preview_image_url),A(je.content_blocks||[]),P(je.html_code||""),p((Ee.data||[]).map(({id:ke,...Xe})=>Xe)),g((Me.data||[]).map(({id:ke,...Xe})=>Xe)),b((De.data||[]).map(({id:ke,...Xe})=>Xe)),N((ze.data||[]).map(({id:ke,...Xe})=>Xe)),I([]),r(!0)},ne=()=>{r(!1),i(null),o({title:"",description:"",publish_date:Hs(new Date,"yyyy-MM-dd'T'HH:mm"),is_published:!1}),d(null),h(null),p([]),g([]),b([]),N([]),A([]),P(""),I([])},ee=async je=>{var Me;const Ee=(Me=je.target.files)==null?void 0:Me[0];Ee&&(d(Ee),h(URL.createObjectURL(Ee)))},le=async()=>{if(!l.title){s({title:"Title is required",variant:"destructive"});return}B(!0);let je=u;if(c){const Ee=`previews/${Date.now()}-${c.name}`,{error:Me}=await U.storage.from("newsletter-content").upload(Ee,c);if(!Me){const{data:De}=U.storage.from("newsletter-content").getPublicUrl(Ee);je=De.publicUrl}}a?K.mutate({id:a.id,...l,preview_image_url:je,content_blocks:C,html_code:T||null}):V.mutate({...l,preview_image_url:je,content_blocks:C,html_code:T||null}),B(!1)},he=()=>p([...m,{title:"",drive_url:"",sort_order:m.length}]),ve=()=>b([...y,{title:"",video_url:"",sort_order:y.length}]),ge=()=>N([...v,{title:"",canva_share_link:"",sort_order:v.length}]),fe=je=>{const Ee=je.target.files;if(!Ee)return;const Me=Array.from(Ee).map(De=>({file:De,name:De.name.replace(/\.[^/.]+$/,"")}));I([...M,...Me])};return e.jsx(Ks,{title:"Newsletter Content",description:"Manage monthly newsletter templates and resources",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(hh,{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(_e,{children:[e.jsx(Bt,{className:"pb-2",children:e.jsx(Ut,{className:"text-sm font-medium text-muted-foreground",children:"Total"})}),e.jsx(Oe,{children:e.jsx("div",{className:"text-2xl font-bold",children:(q==null?void 0:q.length)||0})})]}),e.jsxs(_e,{children:[e.jsx(Bt,{className:"pb-2",children:e.jsx(Ut,{className:"text-sm font-medium text-muted-foreground",children:"Published"})}),e.jsx(Oe,{children:e.jsx("div",{className:"text-2xl font-bold",children:(q==null?void 0:q.filter(je=>je.is_published).length)||0})})]})]}),e.jsxs(Os,{open:n,onOpenChange:je=>!je&&ne(),children:[e.jsx(Ko,{asChild:!0,children:e.jsxs($,{onClick:()=>r(!0),children:[e.jsx(sn,{className:"mr-2 h-4 w-4"})," Add Newsletter"]})}),e.jsxs(Rs,{className:"max-w-4xl max-h-[90vh] overflow-y-auto",children:[e.jsx(Us,{children:e.jsx(zs,{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(se,{children:"Title *"}),e.jsx(be,{value:l.title,onChange:je=>o({...l,title:je.target.value}),placeholder:"Newsletter title"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Publish Date"}),e.jsx(be,{type:"datetime-local",value:l.publish_date,onChange:je=>o({...l,publish_date:je.target.value})})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Description"}),e.jsx(m2,{content:l.description,onChange:je=>o({...l,description:je}),placeholder:"Newsletter description",minHeight:"120px"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Preview Image"}),e.jsxs("div",{className:"flex items-center gap-4",children:[u&&e.jsxs("div",{className:"relative group",children:[e.jsx("img",{src:u,alt:"Preview",className:"h-20 w-32 object-cover rounded-md"}),e.jsx($,{type:"button",variant:"destructive",size:"icon",className:"absolute -top-2 -right-2 h-5 w-5 opacity-0 group-hover:opacity-100 transition-opacity",onClick:()=>{d(null),h(null)},children:e.jsx(pr,{className:"h-3 w-3"})})]}),e.jsxs("div",{children:[e.jsx(be,{type:"file",accept:"image/*",onChange:ee,className:"hidden",id:"preview-upload"}),e.jsx($,{variant:"outline",asChild:!0,children:e.jsxs("label",{htmlFor:"preview-upload",className:"cursor-pointer",children:[e.jsx(si,{className:"mr-2 h-4 w-4"})," Upload Image"]})})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Tn,{checked:l.is_published,onCheckedChange:je=>o({...l,is_published:je})}),e.jsx(se,{children:"Published"})]}),e.jsx(b1n,{rows:C,onChange:A}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(se,{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:je=>P(je.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(se,{className:"text-base font-medium",children:"Canva Links"}),e.jsxs($,{type:"button",variant:"outline",size:"sm",onClick:ge,children:[e.jsx(sn,{className:"mr-1 h-3 w-3"})," Add Canva Link"]})]}),v.map((je,Ee)=>e.jsxs("div",{className:"flex gap-2 items-center",children:[e.jsx(be,{placeholder:"Link title",value:je.title,onChange:Me=>{const De=[...v];De[Ee].title=Me.target.value,N(De)},className:"w-1/3"}),e.jsx(be,{placeholder:"Canva share link",value:je.canva_share_link,onChange:Me=>{const De=[...v];De[Ee].canva_share_link=Me.target.value,N(De)},className:"flex-1"}),e.jsx($,{type:"button",variant:"ghost",size:"icon",onClick:()=>N(v.filter((Me,De)=>De!==Ee)),children:e.jsx(pr,{className:"h-4 w-4"})})]},Ee))]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(se,{className:"text-base font-medium",children:"Google Drive Links"}),e.jsxs($,{type:"button",variant:"outline",size:"sm",onClick:he,children:[e.jsx(sn,{className:"mr-1 h-3 w-3"})," Add Link"]})]}),m.map((je,Ee)=>e.jsxs("div",{className:"flex gap-2 items-center",children:[e.jsx(be,{placeholder:"Link title",value:je.title,onChange:Me=>{const De=[...m];De[Ee].title=Me.target.value,p(De)},className:"w-1/3"}),e.jsx(be,{placeholder:"Google Drive URL",value:je.drive_url,onChange:Me=>{const De=[...m];De[Ee].drive_url=Me.target.value,p(De)},className:"flex-1"}),e.jsx($,{type:"button",variant:"ghost",size:"icon",onClick:()=>p(m.filter((Me,De)=>De!==Ee)),children:e.jsx(pr,{className:"h-4 w-4"})})]},Ee))]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(se,{className:"text-base font-medium",children:"PDF Files"}),e.jsxs("div",{children:[e.jsx(be,{type:"file",accept:".pdf",multiple:!0,onChange:fe,className:"hidden",id:"pdf-upload"}),e.jsx($,{variant:"outline",size:"sm",asChild:!0,children:e.jsxs("label",{htmlFor:"pdf-upload",className:"cursor-pointer",children:[e.jsx(si,{className:"mr-1 h-3 w-3"})," Upload PDF"]})})]})]}),x.map((je,Ee)=>e.jsxs("div",{className:"flex gap-2 items-center bg-muted/50 p-2 rounded",children:[e.jsx(Wr,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"flex-1 text-sm",children:je.name}),e.jsx($,{type:"button",variant:"ghost",size:"icon",onClick:()=>g(x.filter((Me,De)=>De!==Ee)),children:e.jsx(pr,{className:"h-4 w-4"})})]},`existing-${Ee}`)),M.map((je,Ee)=>e.jsxs("div",{className:"flex gap-2 items-center bg-muted/50 p-2 rounded",children:[e.jsx(Wr,{className:"h-4 w-4 text-muted-foreground"}),e.jsx(be,{value:je.name,onChange:Me=>{const De=[...M];De[Ee].name=Me.target.value,I(De)},className:"flex-1 h-8",placeholder:"PDF name"}),e.jsx("span",{className:"text-xs text-muted-foreground",children:"(new)"}),e.jsx($,{type:"button",variant:"ghost",size:"icon",onClick:()=>I(M.filter((Me,De)=>De!==Ee)),children:e.jsx(pr,{className:"h-4 w-4"})})]},`pending-${Ee}`))]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(se,{className:"text-base font-medium",children:"Video Links"}),e.jsxs($,{type:"button",variant:"outline",size:"sm",onClick:ve,children:[e.jsx(sn,{className:"mr-1 h-3 w-3"})," Add Video"]})]}),y.map((je,Ee)=>e.jsxs("div",{className:"flex gap-2 items-center",children:[e.jsx(be,{placeholder:"Video title",value:je.title,onChange:Me=>{const De=[...y];De[Ee].title=Me.target.value,b(De)},className:"w-1/3"}),e.jsx(be,{placeholder:"Video URL",value:je.video_url,onChange:Me=>{const De=[...y];De[Ee].video_url=Me.target.value,b(De)},className:"flex-1"}),e.jsx($,{type:"button",variant:"ghost",size:"icon",onClick:()=>b(y.filter((Me,De)=>De!==Ee)),children:e.jsx(pr,{className:"h-4 w-4"})})]},Ee))]}),e.jsxs("div",{className:"flex justify-end gap-2 pt-4 border-t",children:[e.jsx($,{variant:"outline",onClick:ne,children:"Cancel"}),e.jsx($,{onClick:le,disabled:D||V.isPending||K.isPending,children:D?"Uploading...":a?"Update":"Create"})]})]})]})]})]}),e.jsx(_e,{children:e.jsx(Oe,{className:"p-0",children:e.jsxs(Va,{children:[e.jsx(Ha,{children:e.jsxs(hn,{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(Ga,{children:W?e.jsx(hn,{children:e.jsx(gt,{colSpan:4,className:"text-center py-8",children:"Loading..."})}):(q==null?void 0:q.length)===0?e.jsx(hn,{children:e.jsx(gt,{colSpan:4,className:"text-center py-8 text-muted-foreground",children:"No newsletters yet. Create your first one!"})}):q==null?void 0:q.map(je=>e.jsxs(hn,{children:[e.jsx(gt,{children:e.jsxs("div",{className:"flex items-center gap-3",children:[je.preview_image_url?e.jsx("img",{src:je.preview_image_url,alt:je.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(Wr,{className:"h-5 w-5 text-muted-foreground"})}),e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:je.title}),je.description&&e.jsx("div",{className:"text-sm text-muted-foreground line-clamp-1",children:je.description.replace(/<[^>]*>/g,"")})]})]})}),e.jsx(gt,{children:Hs(new Date(je.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 ${je.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:je.is_published?"Published":"Draft"})}),e.jsx(gt,{className:"text-right",children:e.jsxs("div",{className:"flex justify-end gap-1",children:[e.jsx($,{variant:"ghost",size:"icon",onClick:()=>ce(je),title:"Edit",children:e.jsx(Ya,{className:"h-4 w-4"})}),e.jsx($,{variant:"ghost",size:"icon",onClick:()=>ue(je),title:"Duplicate",children:e.jsx(Ca,{className:"h-4 w-4"})}),e.jsx($,{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?")&&Q.mutate(je.id)},children:e.jsx(Pn,{className:"h-4 w-4"})})]})})]},je.id))})]})})})]})})}const w1n={status:"all",billing:"all",role:"all",brokerage:"all",joinedWithinDays:null};function j1n({brokerages:s}){var A;const{toast:t}=gi(),[n,r]=j.useState(w1n),[a,i]=j.useState(""),[l,o]=j.useState(""),[c,d]=j.useState(""),[u,h]=j.useState(null),[m,p]=j.useState(!1),[x,g]=j.useState(!1),[y,b]=j.useState(null),v=(T,P)=>r(M=>({...M,[T]:P}));j.useEffect(()=>{const T=setTimeout(async()=>{p(!0);try{const{data:P,error:M}=await U.functions.invoke("admin-broadcast-sms",{body:{action:"preview",filters:n,sms_body:a||"Sample message"}});if(M)throw M;h(P)}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}g(!0);const{data:T,error:P}=await U.functions.invoke("admin-broadcast-sms",{body:{action:"test",to:c,sms_body:a}});if(g(!1),P||T!=null&&T.error){t({title:"Test failed",description:(T==null?void 0:T.error)||(P==null?void 0:P.message),variant:"destructive"});return}t({title:"Test text sent",description:`Sent to ${c}`})},C=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"}))){g(!0),b({total:T,sent:0,failed:0});try{const{data:M,error:I}=await U.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 D=0,B=0,q=M.total,W=0;for(;q>0&&W++<400;){const{data:V,error:K}=await U.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}D+=V.sent||0,B+=V.failed||0,q=V.remaining||0,b({total:T,sent:D,failed:B})}t({title:"Broadcast complete",description:`${D} sent${B?`, ${B} failed`:""}.`})}catch(M){t({title:"Broadcast failed",description:M.message,variant:"destructive"})}finally{g(!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(_e,{children:[e.jsxs(Bt,{className:"pb-3",children:[e.jsxs(Ut,{className:"flex items-center gap-2 text-base",children:[e.jsx(j0,{className:"h-4 w-4"})," SMS Audience"]}),e.jsx(vr,{children:"Only members with a recorded consent date and source are included. Opted-out and undeliverable numbers are always excluded."})]}),e.jsxs(Oe,{className:"space-y-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{className:"text-xs",children:"Account status"}),e.jsxs(vs,{value:n.status,onValueChange:T=>v("status",T),children:[e.jsx(gs,{children:e.jsx(bs,{})}),e.jsxs(ys,{children:[e.jsx(Ye,{value:"all",children:"All members"}),e.jsx(Ye,{value:"active",children:"Signed in before"}),e.jsx(Ye,{value:"pending",children:"Never signed in"})]})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{className:"text-xs",children:"Billing"}),e.jsxs(vs,{value:n.billing,onValueChange:T=>v("billing",T),children:[e.jsx(gs,{children:e.jsx(bs,{})}),e.jsxs(ys,{children:[e.jsx(Ye,{value:"all",children:"All"}),e.jsx(Ye,{value:"trial",children:"On trial"}),e.jsx(Ye,{value:"paid",children:"Paid"}),e.jsx(Ye,{value:"grandfathered",children:"Grandfathered"}),e.jsx(Ye,{value:"canceled",children:"Canceled / past due"})]})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{className:"text-xs",children:"Role"}),e.jsxs(vs,{value:n.role,onValueChange:T=>v("role",T),children:[e.jsx(gs,{children:e.jsx(bs,{})}),e.jsxs(ys,{children:[e.jsx(Ye,{value:"all",children:"All roles"}),e.jsx(Ye,{value:"user",children:"Agents"}),e.jsx(Ye,{value:"brokerage_manager",children:"Brokerage managers"}),e.jsx(Ye,{value:"coach",children:"Coaches"}),e.jsx(Ye,{value:"admin",children:"Admins"})]})]})]}),!!(s!=null&&s.length)&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{className:"text-xs",children:"Brokerage"}),e.jsxs(vs,{value:n.brokerage,onValueChange:T=>v("brokerage",T),children:[e.jsx(gs,{children:e.jsx(bs,{})}),e.jsxs(ys,{children:[e.jsx(Ye,{value:"all",children:"All brokerages"}),e.jsx(Ye,{value:"none",children:"No brokerage"}),s.map(T=>e.jsx(Ye,{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(Ht,{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(Hr,{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(_e,{children:[e.jsxs(Bt,{className:"pb-3",children:[e.jsxs(Ut,{className:"flex items-center gap-2 text-base",children:[e.jsx(Ji,{className:"h-4 w-4"})," Text message"]}),e.jsxs(vr,{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(Oe,{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{htmlFor:"sms-broadcast-name",className:"text-xs",children:"Internal name"}),e.jsx(be,{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(se,{htmlFor:"sms-broadcast-body",className:"text-xs",children:"Message"}),e.jsx(Is,{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($e,{variant:((u==null?void 0:u.segments)??1)>2?"destructive":"secondary",children:[(u==null?void 0:u.segments)??1," segment",((u==null?void 0:u.segments)??1)===1?"":"s"]})]})]}),(u==null?void 0:u.composed)&&e.jsxs("div",{className:"rounded-lg border bg-muted/30 p-3",children:[e.jsx("p",{className:"mb-1 text-xs font-medium text-muted-foreground",children:"Preview as delivered"}),e.jsx("p",{className:"whitespace-pre-wrap text-sm",children:u.composed})]}),e.jsxs("div",{className:"flex flex-wrap items-end gap-2",children:[e.jsxs("div",{className:"flex-1 space-y-1.5",style:{minWidth:200},children:[e.jsx(se,{htmlFor:"sms-test-phone",className:"text-xs",children:"Send a test to"}),e.jsx(be,{id:"sms-test-phone",value:c,onChange:T=>d(T.target.value),placeholder:"(555) 123-4567",type:"tel"})]}),e.jsxs($,{variant:"outline",onClick:N,disabled:x,children:[x&&e.jsx(Ht,{className:"mr-2 h-4 w-4 animate-spin"})," Send test"]})]}),y&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(Ki,{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(Fr,{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(xo,{className:"h-3 w-3"})," ",y.failed," failed"]}),e.jsxs("span",{children:["of ",y.total]})]})]}),e.jsxs($,{onClick:C,disabled:x||!a.trim()||!(u!=null&&u.count),className:"w-full",children:[x?e.jsx(Ht,{className:"mr-2 h-4 w-4 animate-spin"}):e.jsx(Br,{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 a8e={status:"all",billing:"all",role:"all",brokerage:"all",joinedWithinDays:null,respectOptOut:!0,program:"all",programStatus:"active"},N1n=["{{first_name}}","{{name}}","{{email}}"];function k1n(s){return`${s||'

Your email preview will appear here…

'}`}function S1n(){var Ge;const{toast:s}=gi(),{user:t}=_s(),n=ts(),[r,a]=j.useState("filters"),[i,l]=j.useState([]),[o,c]=j.useState(""),[d,u]=j.useState([]),[h,m]=j.useState(!1),[p,x]=j.useState(""),[g,y]=j.useState(!1),[b,v]=j.useState(a8e),[N,C]=j.useState(null),[A,T]=j.useState(!1),[P,M]=j.useState(""),[I,D]=j.useState(""),[B,q]=j.useState(""),[W,V]=j.useState(""),[K,Q]=j.useState("rich"),[J,ce]=j.useState(""),[ue,ne]=j.useState(""),[ee,le]=j.useState(""),[he,ve]=j.useState(!1),[ge,fe]=j.useState(null),je=K==="rich"?J:ue;j.useEffect(()=>{t!=null&&t.email&&(q(nt=>nt||t.email),V(nt=>nt||t.email),le(nt=>nt||t.email))},[t==null?void 0:t.email]);const{data:Ee}=ht({queryKey:["broadcast-brokerages"],queryFn:async()=>{const{data:nt}=await U.from("brokerages").select("id, name").order("name");return nt||[]}}),{data:Me}=ht({queryKey:["broadcast-programs"],queryFn:async()=>{const{data:nt}=await U.from("programs").select("id, name").order("created_at",{ascending:!1});return nt||[]}}),{data:De}=ht({queryKey:["admin-broadcasts"],queryFn:async()=>{const{data:nt,error:ft}=await U.from("admin_broadcasts").select("*").order("created_at",{ascending:!1}).limit(30);if(ft)throw ft;return nt}}),{data:ze}=ht({queryKey:["admin-broadcast-templates"],queryFn:async()=>{const{data:nt,error:ft}=await U.from("admin_broadcast_templates").select("*").order("updated_at",{ascending:!1});if(ft)throw ft;return nt}}),ke=async nt=>{T(!0);try{const{data:ft,error:lt}=await U.functions.invoke("admin-broadcast",{body:{action:"preview",filters:nt}});if(lt)throw lt;if(ft!=null&&ft.error)throw new Error(ft.error);C(ft)}catch(ft){s({title:"Could not load audience",description:ft.message,variant:"destructive"})}finally{T(!1)}};j.useEffect(()=>{if(r!=="filters")return;const nt=setTimeout(()=>ke(b),400);return()=>clearTimeout(nt)},[b,r]),j.useEffect(()=>{if(r!=="manual")return;const nt=setTimeout(async()=>{m(!0);try{const{data:ft,error:lt}=await U.functions.invoke("admin-broadcast",{body:{action:"search_members",query:o}});if(lt)throw lt;u((ft==null?void 0:ft.members)||[])}catch{u([])}finally{m(!1)}},350);return()=>clearTimeout(nt)},[o,r]);const Xe=(nt,ft)=>v(lt=>({...lt,[nt]:ft})),Se=r==="manual"?i.length:(N==null?void 0:N.count)||0,Re=()=>r==="manual"?{recipient_mode:"manual",manual_emails:i.map(nt=>nt.email)}:{recipient_mode:"filters",filters:b},Ae=nt=>l(ft=>ft.some(lt=>lt.email.toLowerCase()===nt.email.toLowerCase())?ft.filter(lt=>lt.email.toLowerCase()!==nt.email.toLowerCase()):[...ft,nt]),Be=async()=>{const nt=(p||P||I).trim();if(!nt||!je.trim()){s({title:"Add a template name and content first",variant:"destructive"});return}y(!0);try{const{error:ft}=await U.from("admin_broadcast_templates").insert({created_by:t.id,name:nt,subject:I,body_html:je,editor_mode:K,from_email:B||null,reply_to_email:W||null,filters:b});if(ft)throw ft;x(""),s({title:"Template saved",description:`"${nt}" is available for future sends.`}),n.invalidateQueries({queryKey:["admin-broadcast-templates"]})}catch(ft){s({title:"Could not save template",description:ft.message,variant:"destructive"})}finally{y(!1)}},qe=nt=>{M(nt.name||""),D(nt.subject||""),nt.from_email&&q(nt.from_email),nt.reply_to_email&&V(nt.reply_to_email);const ft=nt.editor_mode==="html"?"html":"rich";Q(ft),ft==="html"?ne(nt.body_html||""):ce(nt.body_html||""),nt.filters&&Object.keys(nt.filters).length&&v({...a8e,...nt.filters}),s({title:"Template loaded",description:"Edit and send when ready."})},Ke=async nt=>{if(!await Yi(`Delete template "${nt.name}"?`))return;const{error:ft}=await U.from("admin_broadcast_templates").delete().eq("id",nt.id);if(ft){s({title:"Delete failed",description:ft.message,variant:"destructive"});return}n.invalidateQueries({queryKey:["admin-broadcast-templates"]})},Ze=j.useMemo(()=>!!I.trim()&&!!je.trim()&&!!B.trim()&&Se>0,[I,je,B,Se]),Ue=async()=>{if(!ee||!I.trim()||!je.trim()){s({title:"Add a subject, content and test address first",variant:"destructive"});return}try{const{data:nt,error:ft}=await U.functions.invoke("admin-broadcast",{body:{action:"test",to:ee,subject:I,html:je,from_email:B,reply_to:W||void 0}});if(ft)throw ft;if(nt!=null&&nt.error)throw new Error(nt.error);s({title:"Test sent",description:`Check ${ee}`})}catch(nt){s({title:"Test failed",description:nt.message,variant:"destructive"})}},et=async()=>{const nt=Se;if(await Yi({title:"Send this broadcast?",description:`"${I}" will be emailed to ${nt} member${nt===1?"":"s"}. Sent emails can't be recalled.`,confirmText:"Send broadcast",cancelText:"Cancel",destructive:!1})){ve(!0),fe({total:nt,sent:0,failed:0});try{const{data:lt,error:Mt}=await U.functions.invoke("admin-broadcast",{body:{action:"queue",name:P||I,subject:I,html:je,from_email:B,reply_to:W||void 0,...Re()}});if(Mt)throw Mt;if(lt!=null&<.error)throw new Error(lt.error);let Ft=0,Ts=0,js=lt.total,zt=0;for(;js>0;){const{data:Nt,error:Ds}=await U.functions.invoke("admin-broadcast",{body:{action:"process",broadcast_id:lt.broadcast_id,limit:40}});if(Ds)throw Ds;if(Nt!=null&&Nt.error)throw new Error(Nt.error);if(Ft+=Nt.sent,Ts+=Nt.failed,js=Nt.remaining,fe({total:lt.total,sent:Ft,failed:Ts}),Nt.throttled){const _t=Math.min(Math.max(Number(Nt.retry_after_ms)||15e3,5e3),45e3);await new Promise(Xs=>setTimeout(Xs,_t));continue}if(Nt.sent===0&&Nt.failed===0){if(++zt>=3)break;await new Promise(_t=>setTimeout(_t,5e3))}else zt=0}s({title:"Broadcast complete",description:`${Ft} sent${Ts?`, ${Ts} failed`:""}`}),n.invalidateQueries({queryKey:["admin-broadcasts"]})}catch(lt){s({title:"Send failed",description:lt.message,variant:"destructive"})}finally{ve(!1)}}},Qe=async nt=>{ve(!0);try{const{data:ft,error:lt}=await U.functions.invoke("admin-broadcast",{body:{action:"retry_failed",broadcast_id:nt}});if(lt)throw lt;if(ft!=null&&ft.error)throw new Error(ft.error);let Mt=0,Ft=0,Ts=ft.requeued,js=0;for(fe({total:Ts,sent:0,failed:0});Ts>0;){const{data:zt,error:Nt}=await U.functions.invoke("admin-broadcast",{body:{action:"process",broadcast_id:nt,limit:25}});if(Nt)throw Nt;if(zt!=null&&zt.error)throw new Error(zt.error);if(Mt+=zt.sent,Ft+=zt.failed,Ts=zt.remaining,fe({total:ft.requeued,sent:Mt,failed:Ft}),zt.throttled){await new Promise(Ds=>setTimeout(Ds,Math.min(Math.max(Number(zt.retry_after_ms)||15e3,5e3),45e3)));continue}if(zt.sent===0&&zt.failed===0){if(++js>=3)break;await new Promise(Ds=>setTimeout(Ds,5e3))}else js=0}s({title:"Retry complete",description:`${Mt} sent${Ft?`, ${Ft} still failed`:""}`}),n.invalidateQueries({queryKey:["admin-broadcasts"]})}catch(ft){s({title:"Retry failed",description:ft.message,variant:"destructive"})}finally{ve(!1)}};return e.jsx(Ks,{children:e.jsxs("div",{className:"space-y-6 p-4 md:p-8",children:[e.jsx(hh,{title:"Member Broadcasts",description:"Send a one-off email to a filtered slice of LevelUp members"}),e.jsxs(ua,{defaultValue:"compose",className:"space-y-6",children:[e.jsxs(ha,{children:[e.jsxs(Qt,{value:"compose",className:"gap-2",children:[e.jsx(nn,{className:"h-4 w-4"})," Compose"]}),e.jsxs(Qt,{value:"sms",className:"gap-2",children:[e.jsx(Ji,{className:"h-4 w-4"})," Text (SMS)"]}),e.jsxs(Qt,{value:"templates",className:"gap-2",children:[e.jsx(nw,{className:"h-4 w-4"})," Templates"]}),e.jsxs(Qt,{value:"history",className:"gap-2",children:[e.jsx(Uj,{className:"h-4 w-4"})," History"]})]}),e.jsx(Jt,{value:"sms",className:"space-y-6",children:e.jsx(j1n,{brokerages:Ee})}),e.jsx(Jt,{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(_e,{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(qn,{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(Oe,{className:"space-y-4 pt-5",children:[e.jsx(ua,{value:r,onValueChange:nt=>a(nt),children:e.jsxs(ha,{className:"grid w-full grid-cols-2",children:[e.jsxs(Qt,{value:"filters",className:"gap-1.5 text-xs",children:[e.jsx(qn,{className:"h-3.5 w-3.5"})," Filters"]}),e.jsxs(Qt,{value:"manual",className:"gap-1.5 text-xs",children:[e.jsx(il,{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(se,{children:"Find members"}),e.jsxs("div",{className:"relative",children:[e.jsx(Vr,{className:"pointer-events-none absolute left-2.5 top-2.5 h-4 w-4 text-muted-foreground"}),e.jsx(be,{value:o,onChange:nt=>c(nt.target.value),placeholder:"Search by name or email",className:"pl-8"})]})]}),i.length>0&&e.jsx("div",{className:"flex flex-wrap gap-1.5",children:i.map(nt=>e.jsxs($e,{variant:"secondary",className:"gap-1",children:[e.jsx("span",{className:"max-w-[150px] truncate",children:nt.name||nt.email}),e.jsx("button",{type:"button",onClick:()=>Ae(nt),"aria-label":`Remove ${nt.email}`,children:e.jsx(pr,{className:"h-3 w-3"})})]},nt.email))}),e.jsx("div",{className:"max-h-72 space-y-1 overflow-y-auto rounded-lg border p-1",children:h?e.jsx("p",{className:"p-3 text-xs text-muted-foreground",children:"Searching…"}):d.length===0?e.jsx("p",{className:"p-3 text-xs text-muted-foreground",children:"No members found."}):d.map(nt=>{const ft=i.some(lt=>lt.email.toLowerCase()===nt.email.toLowerCase());return e.jsxs("button",{type:"button",onClick:()=>Ae(nt),className:`flex w-full items-center justify-between rounded-md px-2.5 py-2 text-left text-xs hover:bg-muted ${ft?"bg-muted":""}`,children:[e.jsxs("span",{className:"min-w-0",children:[e.jsx("span",{className:"block truncate font-medium",children:nt.name||"Member"}),e.jsx("span",{className:"block truncate text-muted-foreground",children:nt.email})]}),ft&&e.jsx(Fr,{className:"h-4 w-4 shrink-0 text-primary"})]},nt.id)})})]}),r==="filters"&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:"Account status"}),e.jsxs(vs,{value:b.status,onValueChange:nt=>Xe("status",nt),children:[e.jsx(gs,{children:e.jsx(bs,{})}),e.jsxs(ys,{children:[e.jsx(Ye,{value:"all",children:"All members"}),e.jsx(Ye,{value:"active",children:"Active (signed in)"}),e.jsx(Ye,{value:"pending",children:"Pending (never signed in)"})]})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:"Membership"}),e.jsxs(vs,{value:b.billing,onValueChange:nt=>Xe("billing",nt),children:[e.jsx(gs,{children:e.jsx(bs,{})}),e.jsxs(ys,{children:[e.jsx(Ye,{value:"all",children:"Any membership"}),e.jsx(Ye,{value:"trial",children:"On trial"}),e.jsx(Ye,{value:"paid",children:"Paid subscribers"}),e.jsx(Ye,{value:"grandfathered",children:"Grandfathered"}),e.jsx(Ye,{value:"canceled",children:"Canceled / past due"})]})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:"Role"}),e.jsxs(vs,{value:b.role,onValueChange:nt=>Xe("role",nt),children:[e.jsx(gs,{children:e.jsx(bs,{})}),e.jsxs(ys,{children:[e.jsx(Ye,{value:"all",children:"Any role"}),e.jsx(Ye,{value:"user",children:"Members"}),e.jsx(Ye,{value:"brokerage_manager",children:"Brokerage managers"}),e.jsx(Ye,{value:"coach",children:"Coaches"}),e.jsx(Ye,{value:"assistant",children:"Assistants"}),e.jsx(Ye,{value:"admin",children:"Admins"})]})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:"Brokerage"}),e.jsxs(vs,{value:b.brokerage,onValueChange:nt=>Xe("brokerage",nt),children:[e.jsx(gs,{children:e.jsx(bs,{})}),e.jsxs(ys,{className:"max-h-72",children:[e.jsx(Ye,{value:"all",children:"All brokerages"}),e.jsx(Ye,{value:"none",children:"No brokerage"}),(Ee||[]).map(nt=>e.jsx(Ye,{value:nt.id,children:nt.name},nt.id))]})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:"Program enrollment"}),e.jsxs(vs,{value:b.program,onValueChange:nt=>Xe("program",nt),children:[e.jsx(gs,{children:e.jsx(bs,{})}),e.jsxs(ys,{className:"max-h-72",children:[e.jsx(Ye,{value:"all",children:"Not filtered by program"}),e.jsx(Ye,{value:"any",children:"Enrolled in any program"}),(Me||[]).map(nt=>e.jsx(Ye,{value:nt.id,children:nt.name},nt.id))]})]})]}),b.program!=="all"&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:"Enrollment status"}),e.jsxs(vs,{value:b.programStatus,onValueChange:nt=>Xe("programStatus",nt),children:[e.jsx(gs,{children:e.jsx(bs,{})}),e.jsxs(ys,{children:[e.jsx(Ye,{value:"active",children:"Active enrollees (paid, reserved, completed)"}),e.jsx(Ye,{value:"any",children:"Any enrollment status"}),e.jsx(Ye,{value:"paid",children:"Paid"}),e.jsx(Ye,{value:"reserved",children:"Reserved"}),e.jsx(Ye,{value:"scheduled_for_charge",children:"Scheduled for charge"}),e.jsx(Ye,{value:"pending_payment_method",children:"Pending payment method"}),e.jsx(Ye,{value:"payment_failed",children:"Payment failed"}),e.jsx(Ye,{value:"completed",children:"Completed"}),e.jsx(Ye,{value:"canceled",children:"Canceled"}),e.jsx(Ye,{value:"refunded",children:"Refunded"})]})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:"Joined within"}),e.jsxs(vs,{value:b.joinedWithinDays?String(b.joinedWithinDays):"all",onValueChange:nt=>Xe("joinedWithinDays",nt==="all"?null:Number(nt)),children:[e.jsx(gs,{children:e.jsx(bs,{})}),e.jsxs(ys,{children:[e.jsx(Ye,{value:"all",children:"Any time"}),e.jsx(Ye,{value:"30",children:"Last 30 days"}),e.jsx(Ye,{value:"60",children:"Last 60 days"}),e.jsx(Ye,{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(Tn,{checked:b.respectOptOut,onCheckedChange:nt=>Xe("respectOptOut",nt)})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx($,{variant:"ghost",size:"sm",onClick:()=>v(a8e),children:"Reset"}),e.jsxs($,{variant:"outline",size:"sm",className:"gap-2",onClick:()=>ke(b),disabled:A,children:[A?e.jsx(Ht,{className:"h-3.5 w-3.5 animate-spin"}):e.jsx(Wi,{className:"h-3.5 w-3.5"}),"Refresh"]})]}),(Ge=N==null?void 0:N.sample)!=null&&Ge.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(nt=>e.jsxs("p",{className:"truncate text-xs",children:[e.jsx("span",{className:"font-medium",children:nt.name||"Member"})," ",e.jsx("span",{className:"text-muted-foreground",children:nt.email})]},nt.email))})]}):null]})]})]})}),e.jsxs("div",{className:"space-y-6",children:[e.jsxs(_e,{children:[e.jsxs(Bt,{className:"pb-4",children:[e.jsx(Ut,{className:"text-base",children:"Message"}),e.jsxs(vr,{children:["Personalize with merge tags: ",N1n.join(" ")]})]}),e.jsxs(Oe,{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(se,{children:"Internal name"}),e.jsx(be,{value:P,onChange:nt=>M(nt.target.value),placeholder:"August product update"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:"Subject line"}),e.jsx(be,{value:I,onChange:nt=>D(nt.target.value),placeholder:"Big news for LevelUp members"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:"From (must be a verified sender)"}),e.jsx(be,{value:B,onChange:nt=>q(nt.target.value),placeholder:"hello@relevelup.com"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:"Reply-to"}),e.jsx(be,{value:W,onChange:nt=>V(nt.target.value),placeholder:"support@relevelup.com"})]})]}),e.jsxs(ua,{value:K,onValueChange:nt=>Q(nt),children:[e.jsxs(ha,{children:[e.jsxs(Qt,{value:"rich",className:"gap-2",children:[e.jsx(dn,{className:"h-3.5 w-3.5"})," Rich text"]}),e.jsxs(Qt,{value:"html",className:"gap-2",children:[e.jsx(xT,{className:"h-3.5 w-3.5"})," Paste HTML"]})]}),e.jsx(Jt,{value:"rich",className:"mt-3",children:e.jsx(m2,{content:J,onChange:ce,minHeight:"320px",placeholder:"Write your message…"})}),e.jsxs(Jt,{value:"html",className:"mt-3 space-y-2",children:[e.jsx(Is,{value:ue,onChange:nt=>ne(nt.target.value),placeholder:"…paste your full email HTML here…",className:"min-h-[320px] font-mono text-xs"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Paste full HTML from Canva, Beefree, Mailchimp, etc. It is sent exactly as written (merge tags still work)."})]})]})]})]}),e.jsxs(_e,{children:[e.jsxs(Bt,{className:"flex flex-row items-center justify-between space-y-0 pb-3",children:[e.jsxs(Ut,{className:"flex items-center gap-2 text-base",children:[e.jsx(ga,{className:"h-4 w-4"})," Preview"]}),e.jsx($e,{variant:"secondary",children:K==="html"?"Raw HTML":"Rich text"})]}),e.jsx(Oe,{children:e.jsx("iframe",{title:"Email preview",srcDoc:k1n(je),className:"h-[420px] w-full rounded-lg border bg-white"})})]}),e.jsx(_e,{children:e.jsxs(Oe,{className:"space-y-4 pt-6",children:[ge&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex justify-between text-sm",children:[e.jsxs("span",{children:[ge.sent+ge.failed," of ",ge.total," processed"]}),e.jsxs("span",{className:"text-muted-foreground",children:[ge.sent," sent",ge.failed?` • ${ge.failed} failed`:""]})]}),e.jsx(Ki,{value:ge.total?(ge.sent+ge.failed)/ge.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(se,{children:"Send a test to"}),e.jsx(be,{value:ee,onChange:nt=>le(nt.target.value),className:"w-64"})]}),e.jsx($,{variant:"outline",onClick:Ue,disabled:he,children:"Send test"}),e.jsx("div",{className:"flex-1"}),e.jsxs($,{onClick:et,disabled:!Ze||he,size:"lg",className:"gap-2",children:[he?e.jsx(Ht,{className:"h-4 w-4 animate-spin"}):e.jsx(Br,{className:"h-4 w-4"}),he?"Sending…":`Send to ${Se} member${Se===1?"":"s"}`]})]}),e.jsxs("div",{className:"flex flex-wrap items-end gap-3 border-t pt-4",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:"Save as template"}),e.jsx(be,{value:p,onChange:nt=>x(nt.target.value),placeholder:P||I||"Template name",className:"w-64"})]}),e.jsxs($,{variant:"outline",className:"gap-2",onClick:Be,disabled:g,children:[g?e.jsx(Ht,{className:"h-4 w-4 animate-spin"}):e.jsx(fT,{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(Jt,{value:"templates",className:"space-y-3",children:(ze||[]).length===0?e.jsx(_e,{children:e.jsxs(Oe,{className:"flex flex-col items-center py-14 text-center",children:[e.jsx(nw,{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.'})]})}):(ze||[]).map(nt=>e.jsx(_e,{children:e.jsxs(Oe,{className:"flex flex-wrap items-center justify-between gap-4 py-4",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("h3",{className:"truncate text-sm font-semibold",children:nt.name}),e.jsx($e,{variant:"secondary",className:"text-xs",children:nt.editor_mode==="html"?"Raw HTML":"Rich text"})]}),e.jsxs("p",{className:"truncate text-xs text-muted-foreground",children:["Subject: ",nt.subject||"—"]}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Updated ",Hs(new Date(nt.updated_at),"MMM d, yyyy h:mm a")]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs($,{size:"sm",className:"gap-2",onClick:()=>qe(nt),children:[e.jsx(Jo,{className:"h-3.5 w-3.5"})," Use template"]}),e.jsx($,{size:"sm",variant:"ghost",onClick:()=>Ke(nt),children:e.jsx(Pn,{className:"h-3.5 w-3.5"})})]})]})},nt.id))}),e.jsx(Jt,{value:"history",className:"space-y-3",children:(De||[]).length===0?e.jsx(_e,{children:e.jsxs(Oe,{className:"flex flex-col items-center py-14 text-center",children:[e.jsx(nn,{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."})]})}):(De||[]).map(nt=>e.jsx(_e,{children:e.jsxs(Oe,{className:"flex flex-wrap items-center justify-between gap-4 py-4",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("h3",{className:"truncate text-sm font-semibold",children:nt.name}),e.jsxs($e,{variant:nt.status==="sent"?"default":nt.status==="sending"?"secondary":"outline",className:"gap-1 text-xs",children:[nt.status==="sent"?e.jsx(Fr,{className:"h-3 w-3"}):e.jsx(xo,{className:"h-3 w-3"}),nt.status]})]}),e.jsxs("p",{className:"truncate text-xs text-muted-foreground",children:["Subject: ",nt.subject]}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[Hs(new Date(nt.created_at),"MMM d, yyyy h:mm a")," • from ",nt.from_email]})]}),e.jsxs("div",{className:"flex gap-6 text-center",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-lg font-bold",children:nt.total_recipients}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Recipients"})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-lg font-bold",children:nt.sent_count}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Sent"})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-lg font-bold",children:nt.failed_count}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Failed"})]}),e.jsxs("div",{children:[e.jsxs("p",{className:"text-lg font-bold",children:[nt.open_count??0,nt.sent_count>0&&e.jsxs("span",{className:"ml-1 text-xs font-medium text-muted-foreground",children:[Math.round((nt.open_count??0)/nt.sent_count*100),"%"]})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Opens"})]}),e.jsxs("div",{children:[e.jsxs("p",{className:"text-lg font-bold",children:[nt.click_count??0,nt.sent_count>0&&e.jsxs("span",{className:"ml-1 text-xs font-medium text-muted-foreground",children:[Math.round((nt.click_count??0)/nt.sent_count*100),"%"]})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Clicks"})]}),nt.failed_count>0&&e.jsx("div",{className:"flex items-center",children:e.jsx($,{size:"sm",variant:"outline",disabled:he,onClick:()=>Qe(nt.id),children:"Retry failed"})})]})]})},nt.id))})]})]})})}const C1n=["Headers","Footers","Seasonal","Holidays","Market Updates","Just Sold","Just Listed","Open House","Buyer Tips","Seller Tips","Testimonials","CTAs & Buttons","Dividers","General"];function A1n(){const s=ts(),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:x=[],isLoading:g}=ht({queryKey:["admin-newsletter-graphics"],queryFn:async()=>{const{data:B,error:q}=await U.from("newsletter_graphics").select("*").order("is_featured",{ascending:!1}).order("created_at",{ascending:!1});if(q)throw q;return B||[]}}),y=j.useMemo(()=>{const B=new Set(C1n);return x.forEach(q=>B.add(q.category)),Array.from(B).sort()},[x]),b=j.useMemo(()=>{const B=n.trim().toLowerCase();return x.filter(q=>a!=="all"&&q.category!==a?!1:B?q.title.toLowerCase().includes(B)||(q.description||"").toLowerCase().includes(B)||q.tags.some(W=>W.toLowerCase().includes(B)):!0)},[x,n,a]),v=()=>{p({title:"",description:"",image_url:"",category:"General",tags:"",is_active:!0,is_featured:!1}),o(null)},N=()=>{v(),d(!0)},C=B=>{o(B),p({title:B.title,description:B.description||"",image_url:B.image_url,category:B.category,tags:B.tags.join(", "),is_active:B.is_active,is_featured:B.is_featured}),d(!0)},A=async B=>{var q;if(!B.type.startsWith("image/")){ae.error("Please choose an image file");return}if(B.size>15*1024*1024){ae.error("Image must be under 15MB");return}h(!0);try{const W=((q=B.name.split(".").pop())==null?void 0:q.toLowerCase())||"png",V=`graphics-library/${Date.now()}-${Math.random().toString(36).slice(2,8)}.${W}`,{error:K}=await U.storage.from("newsletter-content").upload(V,B,{cacheControl:"31536000",upsert:!1,contentType:B.type});if(K)throw K;const{data:Q}=U.storage.from("newsletter-content").getPublicUrl(V);p(J=>({...J,image_url:Q.publicUrl,title:J.title||B.name.replace(/\.[^.]+$/,"").replace(/[-_]/g," ")})),ae.success("Uploaded")}catch(W){ae.error(W.message||"Upload failed")}finally{h(!1),t.current&&(t.current.value="")}},T=yt({mutationFn:async()=>{var W;if(!m.image_url)throw new Error("Please upload an image");if(!m.title.trim())throw new Error("Please add a title");const B=m.tags.split(",").map(V=>V.trim()).filter(Boolean),q={title:m.title.trim(),description:m.description.trim()||null,image_url:m.image_url,category:m.category||"General",tags:B,is_active:m.is_active,is_featured:m.is_featured};if(l){const{error:V}=await U.from("newsletter_graphics").update(q).eq("id",l.id);if(V)throw V}else{const{data:V}=await U.auth.getUser(),{error:K}=await U.from("newsletter_graphics").insert({...q,created_by:(W=V.user)==null?void 0:W.id});if(K)throw K}},onSuccess:()=>{ae.success(l?"Updated":"Graphic added to library"),s.invalidateQueries({queryKey:["admin-newsletter-graphics"]}),s.invalidateQueries({queryKey:["newsletter-graphics-picker"]}),d(!1),v()},onError:B=>ae.error(B.message||"Save failed")}),P=yt({mutationFn:async B=>{const{error:q}=await U.from("newsletter_graphics").delete().eq("id",B);if(q)throw q},onSuccess:()=>{ae.success("Deleted"),s.invalidateQueries({queryKey:["admin-newsletter-graphics"]}),s.invalidateQueries({queryKey:["newsletter-graphics-picker"]})},onError:B=>ae.error(B.message||"Delete failed")}),M=async B=>{const{error:q}=await U.from("newsletter_graphics").update({is_active:!B.is_active}).eq("id",B.id);q?ae.error(q.message):(s.invalidateQueries({queryKey:["admin-newsletter-graphics"]}),s.invalidateQueries({queryKey:["newsletter-graphics-picker"]}))},I=async B=>{const{error:q}=await U.from("newsletter_graphics").update({is_featured:!B.is_featured}).eq("id",B.id);q?ae.error(q.message):(s.invalidateQueries({queryKey:["admin-newsletter-graphics"]}),s.invalidateQueries({queryKey:["newsletter-graphics-picker"]}))},D=B=>{navigator.clipboard.writeText(B),ae.success("URL copied")};return e.jsxs(Ks,{children:[e.jsxs("div",{className:"p-4 md:p-6 max-w-7xl mx-auto space-y-5",children:[e.jsx(hh,{title:"Newsletter Graphics Library",description:"Upload branded graphics agents can drop into their newsletters and email campaigns."}),e.jsx(_e,{children:e.jsxs(Oe,{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(Vr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(be,{value:n,onChange:B=>r(B.target.value),placeholder:"Search graphics by title, tag, description...",className:"pl-9"})]}),e.jsxs(vs,{value:a,onValueChange:i,children:[e.jsx(gs,{className:"w-full md:w-56",children:e.jsx(bs,{})}),e.jsxs(ys,{children:[e.jsx(Ye,{value:"all",children:"All categories"}),y.map(B=>e.jsx(Ye,{value:B,children:B},B))]})]}),e.jsxs($,{onClick:N,className:"gap-1.5 whitespace-nowrap",children:[e.jsx(x1,{className:"h-4 w-4"})," Add Graphic"]})]})}),g?e.jsx("div",{className:"flex justify-center py-16",children:e.jsx(Ht,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):b.length===0?e.jsx(_e,{children:e.jsxs(Oe,{className:"py-16 text-center",children:[e.jsx(Jl,{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:x.length===0?"No graphics uploaded yet — add your first one to get started.":"No graphics match your filters."}),x.length===0&&e.jsxs($,{onClick:N,className:"gap-1.5",children:[e.jsx(x1,{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:b.map(B=>e.jsxs(_e,{className:`overflow-hidden group ${B.is_active?"":"opacity-60"}`,children:[e.jsxs("div",{className:"aspect-video bg-muted relative overflow-hidden",children:[e.jsx("img",{src:B.image_url,alt:B.title,loading:"lazy",className:"w-full h-full object-cover"}),B.is_featured&&e.jsxs($e,{className:"absolute top-2 left-2 gap-0.5 bg-amber-500 hover:bg-amber-500 text-white border-0",children:[e.jsx(Qa,{className:"h-3 w-3 fill-current"})," Featured"]}),!B.is_active&&e.jsx($e,{variant:"secondary",className:"absolute top-2 right-2",children:"Hidden"})]}),e.jsxs(Oe,{className:"p-3 space-y-2",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-sm truncate",children:B.title}),e.jsx("p",{className:"text-xs text-muted-foreground",children:B.category})]}),B.tags.length>0&&e.jsx("div",{className:"flex flex-wrap gap-1",children:B.tags.slice(0,3).map(q=>e.jsx($e,{variant:"outline",className:"text-[10px] px-1.5 py-0",children:q},q))}),e.jsxs("div",{className:"flex items-center justify-between pt-1 border-t",children:[e.jsxs("div",{className:"flex gap-1",children:[e.jsx($,{size:"icon",variant:"ghost",className:"h-7 w-7",onClick:()=>C(B),title:"Edit",children:e.jsx(Ya,{className:"h-3.5 w-3.5"})}),e.jsx($,{size:"icon",variant:"ghost",className:"h-7 w-7",onClick:()=>I(B),title:B.is_featured?"Unfeature":"Feature",children:e.jsx(Qa,{className:`h-3.5 w-3.5 ${B.is_featured?"fill-amber-500 text-amber-500":""}`})}),e.jsx($,{size:"icon",variant:"ghost",className:"h-7 w-7",onClick:()=>D(B.image_url),title:"Copy URL",children:e.jsx(Ca,{className:"h-3.5 w-3.5"})})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Tn,{checked:B.is_active,onCheckedChange:()=>M(B)}),e.jsx($,{size:"icon",variant:"ghost",className:"h-7 w-7 text-destructive hover:text-destructive",onClick:async()=>{await Yi(`Delete "${B.title}"?`)&&P.mutate(B.id)},children:e.jsx(Pn,{className:"h-3.5 w-3.5"})})]})]})]})]},B.id))})]}),e.jsx(Os,{open:c,onOpenChange:d,children:e.jsxs(Rs,{className:"sm:max-w-lg max-h-[90vh] overflow-y-auto",children:[e.jsx(Us,{children:e.jsx(zs,{children:l?"Edit Graphic":"Add New Graphic"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(se,{children:"Image"}),e.jsx("input",{ref:t,type:"file",accept:"image/*",className:"hidden",onChange:B=>{var W;const q=(W=B.target.files)==null?void 0:W[0];q&&A(q)}}),m.image_url?e.jsxs("div",{className:"relative rounded-lg overflow-hidden border bg-muted/30 mt-1.5",children:[e.jsx("img",{src:m.image_url,alt:"Preview",className:"w-full max-h-64 object-contain"}),e.jsx($,{type:"button",variant:"destructive",size:"icon",className:"absolute top-2 right-2 h-7 w-7",onClick:()=>p(B=>({...B,image_url:""})),children:e.jsx(pr,{className:"h-3.5 w-3.5"})})]}):e.jsx("button",{type:"button",onClick:()=>{var B;return(B=t.current)==null?void 0:B.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(Ht,{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(si,{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(se,{htmlFor:"g-title",children:"Title *"}),e.jsx(be,{id:"g-title",value:m.title,onChange:B=>p(q=>({...q,title:B.target.value})),placeholder:"e.g. Fall Market Update Banner"})]}),e.jsxs("div",{children:[e.jsx(se,{htmlFor:"g-desc",children:"Description"}),e.jsx(Is,{id:"g-desc",value:m.description,onChange:B=>p(q=>({...q,description:B.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(se,{children:"Category"}),e.jsxs(vs,{value:m.category,onValueChange:B=>p(q=>({...q,category:B})),children:[e.jsx(gs,{children:e.jsx(bs,{})}),e.jsx(ys,{children:y.map(B=>e.jsx(Ye,{value:B,children:B},B))})]})]}),e.jsxs("div",{children:[e.jsx(se,{htmlFor:"g-tags",children:"Tags (comma-separated)"}),e.jsx(be,{id:"g-tags",value:m.tags,onChange:B=>p(q=>({...q,tags:B.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(Tn,{checked:m.is_featured,onCheckedChange:B=>p(q=>({...q,is_featured:B}))})]}),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(Tn,{checked:m.is_active,onCheckedChange:B=>p(q=>({...q,is_active:B}))})]})]}),e.jsxs(kr,{children:[e.jsx($,{variant:"outline",onClick:()=>d(!1),children:"Cancel"}),e.jsxs($,{onClick:()=>T.mutate(),disabled:T.isPending,children:[T.isPending&&e.jsx(Ht,{className:"h-3.5 w-3.5 mr-1.5 animate-spin"}),l?"Save Changes":"Add to Library"]})]})]})})]})}const Wft={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 E1n(){const{user:s}=_s(),{toast:t}=gi(),n=Vn(),r=ts(),[a,i]=j.useState(""),[l,o]=j.useState("popular"),[c,d]=j.useState(!1),[u,h]=j.useState(""),[m,p]=j.useState(""),[x,g]=j.useState(!1),{data:y=[],isLoading:b}=ht({queryKey:["wishlist-items",l,x],queryFn:async()=>{let T=U.from("wishlist_items").select("*");x&&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:P,error:M}=await T;if(M)throw M;const I=[...new Set((P==null?void 0:P.map(Q=>Q.user_id))||[])],{data:D}=await U.from("profiles").select("id, name").in("id",I),B=new Map((D==null?void 0:D.map(Q=>[Q.id,Q]))||[]);let q=[];if(s){const{data:Q}=await U.from("wishlist_votes").select("item_id").eq("user_id",s.id);q=(Q==null?void 0:Q.map(J=>J.item_id))||[]}const W=(P==null?void 0:P.map(Q=>Q.id))||[],{data:V}=await U.from("wishlist_comments").select("item_id").in("item_id",W),K=new Map;return V==null||V.forEach(Q=>{K.set(Q.item_id,(K.get(Q.item_id)||0)+1)}),P==null?void 0:P.map(Q=>{const J=B.get(Q.user_id),ce=(J==null?void 0:J.name)||"Unknown";return{...Q,user_name:ce,user_initials:ce.split(" ").map(ue=>ue[0]).join("").toUpperCase().slice(0,2),has_voted:q.includes(Q.id),comment_count:K.get(Q.id)||0}})}}),v=yt({mutationFn:async({title:T,description:P})=>{const{error:M}=await U.from("wishlist_items").insert({user_id:s.id,title:T,description:P});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:P})=>{if(P){const{error:M}=await U.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 U.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 P=y.find(I=>I.id===T.itemId),M=((P==null?void 0:P.vote_count)||0)+1;U.functions.invoke("wishlist-notify",{body:{itemId:T.itemId,voteCount:M}}).catch(console.error)}},onError:T=>{t({title:"Error",description:T.message,variant:"destructive"})}}),C=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}v.mutate({title:u.trim(),description:m.trim()})};return e.jsx(Ks,{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(i5,{className:"h-6 w-6 text-primary"})}),e.jsxs("div",{children:[e.jsx("h1",{className:"text-5xl font-bold",children:"Wishlist"}),e.jsx("p",{className:"text-muted-foreground text-sm",children:"Share ideas and vote on what we build next"})]})]}),e.jsxs(Os,{open:c,onOpenChange:d,children:[e.jsx(Ko,{asChild:!0,children:e.jsxs($,{className:"gap-2",children:[e.jsx(sn,{className:"h-4 w-4"}),"Add Idea"]})}),e.jsxs(Rs,{children:[e.jsx(Us,{children:e.jsx(zs,{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(se,{htmlFor:"title",children:"Title"}),e.jsx(be,{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(se,{htmlFor:"description",children:"Description"}),e.jsx(Is,{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($,{onClick:A,className:"w-full",disabled:v.isPending,children:v.isPending?e.jsxs(e.Fragment,{children:[e.jsx(Ht,{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(Vr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(be,{placeholder:"Search ideas...",value:a,onChange:T=>i(T.target.value),className:"pl-10"})]}),e.jsx("div",{className:"flex gap-2",children:e.jsx(ua,{value:l,onValueChange:T=>o(T),children:e.jsxs(ha,{children:[e.jsx(Qt,{value:"popular",children:"Most Popular"}),e.jsx(Qt,{value:"latest",children:"Latest"}),e.jsx(Qt,{value:"trending",children:"Trending"})]})})})]}),e.jsx("div",{className:"flex items-center gap-2 mb-4",children:e.jsx($,{variant:x?"default":"outline",size:"sm",onClick:()=>g(!x),children:x?"Show All Ideas":"My Ideas"})}),b?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx(Ht,{className:"h-8 w-8 animate-spin text-muted-foreground"})}):C.length===0?e.jsxs("div",{className:"text-center py-12 bg-muted/30 rounded-lg",children:[e.jsx(i5,{className:"h-12 w-12 text-muted-foreground mx-auto mb-4"}),e.jsx("h3",{className:"text-lg font-medium mb-2",children:"No ideas yet"}),e.jsx("p",{className:"text-muted-foreground mb-4",children:"Be the first to submit an idea!"}),e.jsxs($,{onClick:()=>d(!0),children:[e.jsx(sn,{className:"h-4 w-4 mr-2"}),"Add Idea"]})]}):e.jsx("div",{className:"space-y-3",children:C.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:P=>{P.stopPropagation(),N.mutate({itemId:T.id,hasVoted:T.has_voted||!1})},className:Tt("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(sp,{className:Tt("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($e,{className:Tt("text-xs",Wft[T.status].color),children:Wft[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(Ji,{className:"h-4 w-4"}),e.jsx("span",{className:"text-sm",children:T.comment_count})]})]})},T.id))})]})})}const Kft={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 T1n(){const{itemId:s}=Vi(),t=Vn(),{user:n}=_s(),{toast:r}=gi(),a=ts(),[i,l]=j.useState(""),{data:o=!1}=ht({queryKey:["user-is-admin",n==null?void 0:n.id],queryFn:async()=>{if(!n)return!1;const{data:y,error:b}=await U.from("user_roles").select("role").eq("user_id",n.id).eq("role","admin").maybeSingle();return!b&&!!y},enabled:!!n}),{data:c,isLoading:d}=ht({queryKey:["wishlist-item",s],queryFn:async()=>{const{data:y,error:b}=await U.from("wishlist_items").select("*").eq("id",s).single();if(b)throw b;const{data:v}=await U.from("profiles").select("name").eq("id",y.user_id).single();let N=!1;if(n){const{data:C}=await U.from("wishlist_votes").select("id").eq("item_id",s).eq("user_id",n.id).maybeSingle();N=!!C}return{...y,user_name:(v==null?void 0:v.name)||"Unknown",user_initials:((v==null?void 0:v.name)||"U").split(" ").map(C=>C[0]).join("").toUpperCase().slice(0,2),has_voted:N}}}),{data:u=[],isLoading:h}=ht({queryKey:["wishlist-comments",s],queryFn:async()=>{const{data:y,error:b}=await U.from("wishlist_comments").select("*").eq("item_id",s).order("created_at",{ascending:!0});if(b)throw b;const v=[...new Set((y==null?void 0:y.map(A=>A.user_id))||[])],{data:N}=await U.from("profiles").select("id, name").in("id",v),C=new Map((N==null?void 0:N.map(A=>[A.id,A]))||[]);return y==null?void 0:y.map(A=>{const T=C.get(A.user_id),P=(T==null?void 0:T.name)||"Unknown";return{...A,user_name:P,user_initials:P.split(" ").map(M=>M[0]).join("").toUpperCase().slice(0,2)}})}}),m=yt({mutationFn:async y=>{if(y){const{error:b}=await U.from("wishlist_votes").delete().eq("item_id",s).eq("user_id",n.id);if(b)throw b;return{wasAdded:!1}}else{const{error:b}=await U.from("wishlist_votes").insert({item_id:s,user_id:n.id});if(b)throw b;return{wasAdded:!0}}},onSuccess:async y=>{if(a.invalidateQueries({queryKey:["wishlist-item",s]}),a.invalidateQueries({queryKey:["wishlist-items"]}),y!=null&&y.wasAdded&&c){const b=(c.vote_count||0)+1;U.functions.invoke("wishlist-notify",{body:{itemId:s,voteCount:b}}).catch(console.error)}},onError:y=>{r({title:"Error",description:y.message,variant:"destructive"})}}),p=yt({mutationFn:async y=>{const{error:b}=await U.from("wishlist_comments").insert({item_id:s,user_id:n.id,content:y});if(b)throw b},onSuccess:()=>{a.invalidateQueries({queryKey:["wishlist-comments",s]}),l(""),r({title:"Comment added!"})},onError:y=>{r({title:"Error",description:y.message,variant:"destructive"})}}),x=yt({mutationFn:async y=>{const{error:b}=await U.from("wishlist_comments").delete().eq("id",y);if(b)throw b},onSuccess:()=>{a.invalidateQueries({queryKey:["wishlist-comments",s]}),r({title:"Comment deleted"})},onError:y=>{r({title:"Error",description:y.message,variant:"destructive"})}}),g=()=>{i.trim()&&p.mutate(i.trim())};return d?e.jsx(Ks,{title:"Wishlist",children:e.jsxs("div",{className:"max-w-3xl mx-auto",children:[e.jsx(on,{className:"h-8 w-32 mb-6"}),e.jsx(on,{className:"h-48 w-full mb-6"}),e.jsx(on,{className:"h-32 w-full"})]})}):c?e.jsx(Ks,{title:"Wishlist",children:e.jsxs("div",{className:"max-w-3xl mx-auto",children:[e.jsxs($,{variant:"ghost",size:"sm",onClick:()=>t("/wishlist"),className:"mb-4",children:[e.jsx(ka,{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:Tt("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(sp,{className:Tt("h-5 w-5",c.has_voted&&"fill-current")}),e.jsx("span",{className:"text-lg font-bold",children:c.vote_count}),e.jsx("span",{className:"text-xs",children:"votes"})]}),e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx("h1",{className:"text-xl font-bold",children:c.title}),e.jsx($e,{className:Tt("text-xs",Kft[c.status].color),children:Kft[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(s5e,{placeholder:o?"Share your thoughts... Use # to link templates":"Share your thoughts on this idea...",value:i,onChange:l,minHeight:"60px",mentionFormat:"encoded",enableTemplateMentions:o}),e.jsx($,{onClick:g,disabled:!i.trim()||p.isPending,size:"icon",className:"h-auto",children:p.isPending?e.jsx(Ht,{className:"h-4 w-4 animate-spin"}):e.jsx(Br,{className:"h-4 w-4"})})]}),h?e.jsx("div",{className:"space-y-4",children:[1,2].map(y=>e.jsx(on,{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(qWe,{content:y.content,className:"text-sm text-foreground"})]}),(n==null?void 0:n.id)===y.user_id&&e.jsx($,{variant:"ghost",size:"icon",className:"h-8 w-8 text-muted-foreground hover:text-destructive",onClick:()=>x.mutate(y.id),children:e.jsx(Pn,{className:"h-4 w-4"})})]},y.id))})]})]})}):e.jsx(Ks,{title:"Wishlist",children:e.jsxs("div",{className:"max-w-3xl mx-auto text-center py-12",children:[e.jsx("p",{className:"text-muted-foreground",children:"Item not found"}),e.jsx($,{variant:"link",onClick:()=>t("/wishlist"),children:"Go back to Wishlist"})]})})}const Yft={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"}},Zft=["open","under_review","planned","in_progress","launched","declined"];function M1n(){const{toast:s}=gi(),t=Vn(),n=ts(),[r,a]=j.useState(""),[i,l]=j.useState("all"),[o,c]=j.useState(!1),[d,u]=j.useState(null),{data:h=[],isLoading:m}=ht({queryKey:["admin-wishlist-items"],queryFn:async()=>{const{data:b,error:v}=await U.from("wishlist_items").select("*").order("vote_count",{ascending:!1});if(v)throw v;const N=[...new Set((b==null?void 0:b.map(I=>I.user_id))||[])],{data:C}=await U.from("profiles").select("id, name, email").in("id",N),A=new Map((C==null?void 0:C.map(I=>[I.id,I]))||[]),T=(b==null?void 0:b.map(I=>I.id))||[],{data:P}=await U.from("wishlist_comments").select("item_id").in("item_id",T),M=new Map;return P==null||P.forEach(I=>{M.set(I.item_id,(M.get(I.item_id)||0)+1)}),b==null?void 0:b.map(I=>{const D=A.get(I.user_id);return{...I,user_name:(D==null?void 0:D.name)||"Unknown",user_email:(D==null?void 0:D.email)||"",comment_count:M.get(I.id)||0}})}}),p=yt({mutationFn:async({itemId:b,status:v})=>{const{error:N}=await U.from("wishlist_items").update({status:v}).eq("id",b);if(N)throw N},onSuccess:()=>{n.invalidateQueries({queryKey:["admin-wishlist-items"]}),s({title:"Status updated!"})},onError:b=>{s({title:"Error",description:b.message,variant:"destructive"})}}),x=yt({mutationFn:async b=>{const{error:v}=await U.from("wishlist_items").delete().eq("id",b);if(v)throw v},onSuccess:()=>{n.invalidateQueries({queryKey:["admin-wishlist-items"]}),c(!1),u(null),s({title:"Item deleted!"})},onError:b=>{s({title:"Error",description:b.message,variant:"destructive"})}}),g=h.filter(b=>{const v=b.title.toLowerCase().includes(r.toLowerCase())||b.description.toLowerCase().includes(r.toLowerCase())||b.user_name.toLowerCase().includes(r.toLowerCase()),N=i==="all"||b.status===i;return v&&N}),y={total:h.length,open:h.filter(b=>b.status==="open").length,inProgress:h.filter(b=>b.status==="in_progress").length,launched:h.filter(b=>b.status==="launched").length,highVotes:h.filter(b=>b.vote_count>=10).length};return e.jsx(Ks,{title:"Admin - Wishlist",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx($,{variant:"ghost",size:"icon",onClick:()=>t("/admin"),children:e.jsx(ka,{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(Vr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(be,{placeholder:"Search ideas, users...",value:r,onChange:b=>a(b.target.value),className:"pl-10"})]}),e.jsxs(vs,{value:i,onValueChange:b=>l(b),children:[e.jsx(gs,{className:"w-[180px]",children:e.jsx(bs,{placeholder:"Filter by status"})}),e.jsxs(ys,{children:[e.jsx(Ye,{value:"all",children:"All Statuses"}),Zft.map(b=>e.jsx(Ye,{value:b,children:Yft[b].label},b))]})]})]}),m?e.jsx("div",{className:"space-y-2",children:[1,2,3,4,5].map(b=>e.jsx(on,{className:"h-16 w-full"},b))}):e.jsx("div",{className:"bg-card border rounded-lg overflow-hidden",children:e.jsxs(Va,{children:[e.jsx(Ha,{children:e.jsxs(hn,{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(Ga,{children:g.length===0?e.jsx(hn,{children:e.jsx(gt,{colSpan:6,className:"text-center py-8 text-muted-foreground",children:"No items found"})}):g.map(b=>e.jsxs(hn,{className:Tt(b.vote_count>=10&&"bg-primary/5"),children:[e.jsx(gt,{children:e.jsx($e,{variant:b.vote_count>=10?"default":"secondary",children:b.vote_count})}),e.jsx(gt,{children:e.jsxs("div",{children:[e.jsx("p",{className:"font-medium line-clamp-1",children:b.title}),e.jsx("p",{className:"text-sm text-muted-foreground line-clamp-1",children:b.description})]})}),e.jsx(gt,{className:"hidden md:table-cell",children:e.jsxs("div",{children:[e.jsx("p",{className:"text-sm",children:b.user_name}),e.jsx("p",{className:"text-xs text-muted-foreground",children:b.user_email})]})}),e.jsx(gt,{className:"hidden sm:table-cell",children:b.comment_count}),e.jsx(gt,{children:e.jsxs(vs,{value:b.status,onValueChange:v=>p.mutate({itemId:b.id,status:v}),children:[e.jsx(gs,{className:"w-[140px] h-8",children:e.jsx(bs,{})}),e.jsx(ys,{children:Zft.map(v=>e.jsx(Ye,{value:v,children:Yft[v].label},v))})]})}),e.jsx(gt,{children:e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx($,{variant:"ghost",size:"icon",onClick:()=>window.open(`/wishlist/${b.id}`,"_blank"),children:e.jsx(Tr,{className:"h-4 w-4"})}),e.jsx($,{variant:"ghost",size:"icon",className:"text-destructive",onClick:()=>{u(b.id),c(!0)},children:e.jsx(Pn,{className:"h-4 w-4"})})]})})]},b.id))})]})}),e.jsx(Os,{open:o,onOpenChange:c,children:e.jsxs(Rs,{children:[e.jsx(Us,{children:e.jsx(zs,{children:"Delete Wishlist Item"})}),e.jsx("p",{className:"text-muted-foreground",children:"Are you sure you want to delete this idea? This will also delete all votes and comments."}),e.jsxs("div",{className:"flex justify-end gap-2 mt-4",children:[e.jsx($,{variant:"outline",onClick:()=>c(!1),children:"Cancel"}),e.jsx($,{variant:"destructive",onClick:()=>d&&x.mutate(d),disabled:x.isPending,children:x.isPending?e.jsxs(e.Fragment,{children:[e.jsx(Ht,{className:"h-4 w-4 mr-2 animate-spin"}),"Deleting..."]}):"Delete"})]})]})})]})})}function L1n(){const{user:s}=_s(),[t,n]=j.useState([]),[r,a]=j.useState(!0),[i,l]=j.useState(!1),[o,c]=j.useState(null),[d,u]=j.useState(!1),[h,m]=j.useState(null),[p,x]=j.useState(""),[g,y]=j.useState(""),[b,v]=j.useState(""),[N,C]=j.useState(""),[A,T]=j.useState(""),[P,M]=j.useState(!1),[I,D]=j.useState(""),[B,q]=j.useState("once"),[W,V]=j.useState([]),[K,Q]=j.useState([]),[J,ce]=j.useState(!1),[ue,ne]=j.useState(!1),[ee,le]=j.useState([]),[he,ve]=j.useState({total:0,dismissed:0});j.useEffect(()=>{ge()},[]);const ge=async()=>{const{data:Qe,error:Ge}=await U.from("levelup_briefs").select("*").order("created_at",{ascending:!1});Ge?(ae.error("Failed to fetch briefs"),console.error(Ge)):n(Qe||[]),a(!1)},fe=()=>{x(""),y(""),v(""),C(""),T(""),M(!1),D(new Date().toISOString().slice(0,16)),q("once"),V([]),Q([]),c(null)},je=()=>{fe(),l(!0)},Ee=async Qe=>{c(Qe),x(Qe.title),y(Qe.description||""),v(Qe.video_url||""),C(Qe.graphic_url||""),T(Qe.graphic_link_url||""),M(Qe.is_published),D(Qe.publish_date.slice(0,16)),q(Qe.show_frequency);const{data:Ge}=await U.from("levelup_brief_links").select("*").eq("brief_id",Qe.id).order("sort_order");V((Ge==null?void 0:Ge.map(ft=>({title:ft.title,url:ft.url})))||[]);const{data:nt}=await U.from("levelup_brief_polls").select("*").eq("brief_id",Qe.id).order("sort_order");if(nt){const ft=[];for(const lt of nt){const{data:Mt}=await U.from("levelup_brief_poll_options").select("*").eq("poll_id",lt.id).order("sort_order");ft.push({question:lt.question,poll_type:lt.poll_type,options:(Mt==null?void 0:Mt.map(Ft=>Ft.option_text))||[]})}Q(ft)}l(!0)},Me=async Qe=>{var nt;const Ge=(nt=Qe.target.files)==null?void 0:nt[0];if(Ge){ce(!0);try{const ft=await U.functions.invoke("bunny-upload",{body:{action:"create",title:Ge.name.replace(/\.[^/.]+$/,"")}});if(ft.error)throw ft.error;const{videoId:lt,libraryId:Mt}=ft.data,Ft=await U.functions.invoke("bunny-upload",{body:{action:"upload-url",videoId:lt}});if(Ft.error)throw Ft.error;const{uploadUrl:Ts,apiKey:js}=Ft.data,zt=new XMLHttpRequest;await new Promise((Ds,_t)=>{zt.upload.addEventListener("progress",Xs=>{if(Xs.lengthComputable){const rn=Math.round(Xs.loaded/Xs.total*100);console.log("Upload progress:",rn)}}),zt.addEventListener("load",()=>{zt.status>=200&&zt.status<300?Ds():_t(new Error(`Upload failed with status ${zt.status}`))}),zt.addEventListener("error",()=>_t(new Error("Upload failed"))),zt.open("PUT",Ts),zt.setRequestHeader("AccessKey",js),zt.send(Ge)});const Nt=`https://player.mediadelivery.net/embed/${Mt}/${lt}`;v(Nt),ae.success("Video uploaded successfully! It may take a few minutes to process.")}catch(ft){console.error("Upload error:",ft),ae.error("Failed to upload video")}finally{ce(!1)}}},De=async()=>{if(!p.trim()){ae.error("Title is required");return}try{let Qe;if(o){const{error:Ge}=await U.from("levelup_briefs").update({title:p,description:g||null,video_url:b||null,graphic_url:N||null,graphic_link_url:A||null,is_published:P,publish_date:I,show_frequency:B}).eq("id",o.id);if(Ge)throw Ge;Qe=o.id,await U.from("levelup_brief_links").delete().eq("brief_id",Qe);const{data:nt}=await U.from("levelup_brief_polls").select("id").eq("brief_id",Qe);if(nt)for(const ft of nt)await U.from("levelup_brief_poll_options").delete().eq("poll_id",ft.id);await U.from("levelup_brief_polls").delete().eq("brief_id",Qe)}else{const{data:Ge,error:nt}=await U.from("levelup_briefs").insert({title:p,description:g||null,video_url:b||null,graphic_url:N||null,graphic_link_url:A||null,is_published:P,publish_date:I,show_frequency:B,created_by:s==null?void 0:s.id}).select().single();if(nt)throw nt;Qe=Ge.id}if(W.length>0){const Ge=W.map((nt,ft)=>({brief_id:Qe,title:nt.title,url:nt.url,sort_order:ft}));await U.from("levelup_brief_links").insert(Ge)}for(let Ge=0;Ge0){const Mt=nt.options.map((Ft,Ts)=>({poll_id:ft.id,option_text:Ft,sort_order:Ts}));await U.from("levelup_brief_poll_options").insert(Mt)}}ae.success(o?"Brief updated":"Brief created"),l(!1),fe(),ge()}catch(Qe){console.error("Error saving brief:",Qe),ae.error("Failed to save brief")}},ze=async Qe=>{if(await Yi("Are you sure you want to delete this brief?"))try{const{error:Ge}=await U.from("levelup_briefs").delete().eq("id",Qe);if(Ge)throw Ge;ae.success("Brief deleted"),ge()}catch(Ge){console.error("Error deleting brief:",Ge),ae.error("Failed to delete brief")}},ke=async Qe=>{m(Qe);const{count:Ge}=await U.from("levelup_brief_views").select("*",{count:"exact",head:!0}).eq("brief_id",Qe.id),{count:nt}=await U.from("levelup_brief_views").select("*",{count:"exact",head:!0}).eq("brief_id",Qe.id).not("dismissed_at","is",null);ve({total:Ge||0,dismissed:nt||0});const{data:ft}=await U.from("levelup_brief_polls").select("*").eq("brief_id",Qe.id).order("sort_order");if(ft){const lt=[];for(const Mt of ft){const{data:Ft}=await U.from("levelup_brief_poll_options").select("*").eq("poll_id",Mt.id).order("sort_order"),{data:Ts}=await U.from("levelup_brief_poll_responses").select("option_id, user_id").eq("poll_id",Mt.id),js=[...new Set((Ts==null?void 0:Ts.map(Xs=>Xs.user_id))||[])];let zt={};if(js.length>0){const{data:Xs}=await U.from("profiles").select("id, name, email").in("id",js);Xs&&Xs.forEach(rn=>{zt[rn.id]=rn.name||rn.email||"Unknown"})}const Nt=(Ts||[]).map(Xs=>({optionId:Xs.option_id,userName:zt[Xs.user_id]||"Unknown",userId:Xs.user_id})),Ds={};let _t=0;Ft&&Ft.forEach(Xs=>{const rn=(Ts==null?void 0:Ts.filter(Ps=>Ps.option_id===Xs.id).length)||0;Ds[Xs.id]=rn,_t+=rn}),lt.push({...Mt,options:Ft||[],results:Ds,respondents:Nt,totalResponses:Mt.poll_type==="single"?new Set(Ts==null?void 0:Ts.map(Xs=>Xs.user_id)).size:_t})}le(lt)}u(!0)},Xe=()=>{V([...W,{title:"",url:""}])},Se=(Qe,Ge,nt)=>{const ft=[...W];ft[Qe][Ge]=nt,V(ft)},Re=Qe=>{V(W.filter((Ge,nt)=>nt!==Qe))},Ae=()=>{Q([...K,{question:"",poll_type:"single",options:["",""]}])},Be=(Qe,Ge)=>{const nt=[...K];nt[Qe].question=Ge,Q(nt)},qe=(Qe,Ge)=>{const nt=[...K];nt[Qe].poll_type=Ge,Q(nt)},Ke=Qe=>{const Ge=[...K];Ge[Qe].options.push(""),Q(Ge)},Ze=(Qe,Ge,nt)=>{const ft=[...K];ft[Qe].options[Ge]=nt,Q(ft)},Ue=(Qe,Ge)=>{const nt=[...K];nt[Qe].options=nt[Qe].options.filter((ft,lt)=>lt!==Ge),Q(nt)},et=Qe=>{Q(K.filter((Ge,nt)=>nt!==Qe))};return e.jsxs(Ks,{title:"The LevelUp Brief",children:[e.jsxs("div",{className:"space-y-6",children:[e.jsx(hh,{title:"The LevelUp Brief",description:"Create engaging popup briefs for your agents",children:e.jsxs($,{onClick:je,children:[e.jsx(sn,{className:"h-4 w-4 mr-2"}),"Create Brief"]})}),e.jsx(_e,{children:e.jsx(Oe,{className:"p-0",children:e.jsxs(Va,{children:[e.jsx(Ha,{children:e.jsxs(hn,{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(Ga,{children:r?e.jsx(hn,{children:e.jsx(gt,{colSpan:5,className:"text-center py-8",children:"Loading..."})}):t.length===0?e.jsx(hn,{children:e.jsx(gt,{colSpan:5,className:"text-center py-8 text-muted-foreground",children:"No briefs created yet"})}):t.map(Qe=>e.jsxs(hn,{children:[e.jsx(gt,{className:"font-medium",children:Qe.title}),e.jsx(gt,{children:e.jsx($e,{variant:Qe.is_published?"default":"secondary",children:Qe.is_published?"Published":"Draft"})}),e.jsx(gt,{className:"capitalize",children:Qe.show_frequency.replace("_"," ")}),e.jsx(gt,{children:Hs(new Date(Qe.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($,{variant:"ghost",size:"icon",onClick:()=>ke(Qe),children:e.jsx(ml,{className:"h-4 w-4"})}),e.jsx($,{variant:"ghost",size:"icon",onClick:()=>Ee(Qe),children:e.jsx(bm,{className:"h-4 w-4"})}),e.jsx($,{variant:"ghost",size:"icon",onClick:()=>ze(Qe.id),children:e.jsx(Pn,{className:"h-4 w-4 text-destructive"})})]})})]},Qe.id))})]})})})]}),e.jsx(Os,{open:i,onOpenChange:l,children:e.jsxs(Rs,{className:"max-w-3xl max-h-[90vh] overflow-y-auto",children:[e.jsx(Us,{children:e.jsx(zs,{children:o?"Edit Brief":"Create New Brief"})}),e.jsxs(ua,{defaultValue:"content",className:"w-full",children:[e.jsxs(ha,{className:"grid w-full grid-cols-4",children:[e.jsx(Qt,{value:"content",children:"Content"}),e.jsx(Qt,{value:"media",children:"Media"}),e.jsx(Qt,{value:"links",children:"Links"}),e.jsx(Qt,{value:"polls",children:"Polls"})]}),e.jsxs(Jt,{value:"content",className:"space-y-4 mt-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Title *"}),e.jsx(be,{value:p,onChange:Qe=>x(Qe.target.value),placeholder:"What's happening at LevelUp..."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Description"}),e.jsx(m2,{content:g,onChange:Qe=>y(Qe),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(se,{children:"Publish Date"}),e.jsx(be,{type:"datetime-local",value:I,onChange:Qe=>D(Qe.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Show Frequency"}),e.jsxs(vs,{value:B,onValueChange:q,children:[e.jsx(gs,{children:e.jsx(bs,{})}),e.jsxs(ys,{children:[e.jsx(Ye,{value:"once",children:"Once (until dismissed)"}),e.jsx(Ye,{value:"every_login",children:"Every login"}),e.jsx(Ye,{value:"daily",children:"Daily"})]})]})]})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(Tn,{checked:P,onCheckedChange:M}),e.jsx(se,{children:"Publish immediately"})]})]}),e.jsxs(Jt,{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(se,{children:"Upload Video to Bunny.net"}),e.jsx("div",{className:"flex gap-2",children:e.jsx(be,{type:"file",accept:"video/*",onChange:Me,disabled:J})}),J&&e.jsx("p",{className:"text-sm text-muted-foreground",children:"Uploading..."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Or paste embed URL"}),e.jsx(be,{value:b,onChange:Qe=>v(Qe.target.value),placeholder:"https://iframe.mediadelivery.net/embed/..."})]}),b&&e.jsx("div",{className:"aspect-video rounded-lg overflow-hidden bg-muted",children:e.jsx("iframe",{src:b,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(se,{children:"Upload Image"}),e.jsx("div",{className:"flex gap-2",children:e.jsx(be,{type:"file",accept:"image/*",onChange:async Qe=>{var nt;const Ge=(nt=Qe.target.files)==null?void 0:nt[0];if(Ge){ne(!0);try{const ft=Ge.name.split(".").pop(),lt=`brief-graphics/${Date.now()}.${ft}`,{error:Mt}=await U.storage.from("banner-images").upload(lt,Ge,{upsert:!0});if(Mt)throw Mt;const{data:Ft}=U.storage.from("banner-images").getPublicUrl(lt);C(Ft.publicUrl),ae.success("Image uploaded!")}catch(ft){console.error(ft),ae.error("Failed to upload image")}finally{ne(!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(se,{children:"Or paste Image URL"}),e.jsx(be,{value:N,onChange:Qe=>C(Qe.target.value),placeholder:"https://example.com/image.png"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Click-through Link (optional)"}),e.jsx(be,{value:A,onChange:Qe=>T(Qe.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(Jt,{value:"links",className:"space-y-4 mt-4",children:[e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsx(se,{children:"Quick Links"}),e.jsxs($,{variant:"outline",size:"sm",onClick:Xe,children:[e.jsx(sn,{className:"h-4 w-4 mr-1"}),"Add Link"]})]}),W.map((Qe,Ge)=>e.jsxs("div",{className:"flex gap-2 items-start",children:[e.jsx(be,{value:Qe.title,onChange:nt=>Se(Ge,"title",nt.target.value),placeholder:"Link title",className:"flex-1"}),e.jsx(be,{value:Qe.url,onChange:nt=>Se(Ge,"url",nt.target.value),placeholder:"https://...",className:"flex-[2]"}),e.jsx($,{variant:"ghost",size:"icon",onClick:()=>Re(Ge),children:e.jsx(Pn,{className:"h-4 w-4 text-destructive"})})]},Ge)),W.length===0&&e.jsx("p",{className:"text-muted-foreground text-center py-4",children:"No links added yet"})]}),e.jsxs(Jt,{value:"polls",className:"space-y-4 mt-4",children:[e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsx(se,{children:"Polls"}),e.jsxs($,{variant:"outline",size:"sm",onClick:Ae,children:[e.jsx(sn,{className:"h-4 w-4 mr-1"}),"Add Poll"]})]}),K.map((Qe,Ge)=>e.jsx(_e,{className:"p-4",children:e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsx(be,{value:Qe.question,onChange:nt=>Be(Ge,nt.target.value),placeholder:"Poll question...",className:"flex-1 mr-2"}),e.jsxs(vs,{value:Qe.poll_type,onValueChange:nt=>qe(Ge,nt),children:[e.jsx(gs,{className:"w-32",children:e.jsx(bs,{})}),e.jsxs(ys,{children:[e.jsx(Ye,{value:"single",children:"Single"}),e.jsx(Ye,{value:"multi",children:"Multi-select"})]})]}),e.jsx($,{variant:"ghost",size:"icon",onClick:()=>et(Ge),children:e.jsx(Pn,{className:"h-4 w-4 text-destructive"})})]}),e.jsxs("div",{className:"space-y-2 pl-4",children:[Qe.options.map((nt,ft)=>e.jsxs("div",{className:"flex gap-2",children:[e.jsx(be,{value:nt,onChange:lt=>Ze(Ge,ft,lt.target.value),placeholder:`Option ${ft+1}`}),Qe.options.length>2&&e.jsx($,{variant:"ghost",size:"icon",onClick:()=>Ue(Ge,ft),children:e.jsx(Pn,{className:"h-4 w-4 text-muted-foreground"})})]},ft)),e.jsxs($,{variant:"ghost",size:"sm",onClick:()=>Ke(Ge),children:[e.jsx(sn,{className:"h-4 w-4 mr-1"}),"Add Option"]})]})]})},Ge)),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($,{variant:"outline",onClick:()=>l(!1),children:"Cancel"}),e.jsx($,{onClick:De,children:o?"Update Brief":"Create Brief"})]})]})}),e.jsx(Os,{open:d,onOpenChange:u,children:e.jsxs(Rs,{className:"max-w-2xl",children:[e.jsx(Us,{children:e.jsxs(zs,{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(_e,{children:[e.jsx(Bt,{className:"pb-2",children:e.jsx(Ut,{className:"text-sm font-medium text-muted-foreground",children:"Total Views"})}),e.jsx(Oe,{children:e.jsx("p",{className:"text-2xl font-bold",children:he.total})})]}),e.jsxs(_e,{children:[e.jsx(Bt,{className:"pb-2",children:e.jsx(Ut,{className:"text-sm font-medium text-muted-foreground",children:"Dismissed"})}),e.jsx(Oe,{children:e.jsx("p",{className:"text-2xl font-bold",children:he.dismissed})})]})]}),ee.length>0?e.jsxs("div",{className:"space-y-4",children:[e.jsx("h3",{className:"font-semibold",children:"Poll Results"}),ee.map(Qe=>e.jsxs(_e,{className:"p-4",children:[e.jsx("h4",{className:"font-medium mb-3",children:Qe.question}),e.jsx("div",{className:"space-y-2",children:Qe.options.map(Ge=>{const nt=Qe.results[Ge.id]||0,ft=Qe.totalResponses>0?Math.round(nt/Qe.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:Ge.option_text}),e.jsxs("span",{className:"text-muted-foreground",children:[nt," (",ft,"%)"]})]}),e.jsx("div",{className:"h-2 bg-muted rounded-full overflow-hidden",children:e.jsx("div",{className:"h-full bg-primary transition-all",style:{width:`${ft}%`}})}),nt>0&&e.jsx("div",{className:"flex flex-wrap gap-1 pt-1",children:(Qe.respondents||[]).filter(lt=>lt.optionId===Ge.id).map((lt,Mt)=>e.jsx($e,{variant:"secondary",className:"text-xs font-normal",children:lt.userName},Mt))})]},Ge.id)})})]},Qe.id))]}):e.jsx("p",{className:"text-muted-foreground text-center py-4",children:"No polls in this brief"})]})]})})]})}const P1n=()=>{const{user:s}=_s(),{toast:t}=gi(),n=ts(),[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:x}=ht({queryKey:["additional-services-admin"],queryFn:async()=>{const{data:A,error:T}=await U.from("additional_services").select("*").order("publish_date",{ascending:!1});if(T)throw T;return A}}),g=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:D}=await U.storage.from("service-images").upload(I,A.image);if(D)throw D;const{data:B}=U.storage.from("service-images").getPublicUrl(I);T=B.publicUrl}const P={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 U.from("additional_services").update(P).eq("id",A.itemId);if(M)throw M}else{const{error:M}=await U.from("additional_services").insert(P);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),b()},onError:A=>{t({title:"Error saving service",description:A.message,variant:"destructive"})}}),y=yt({mutationFn:async A=>{const{error:T}=await U.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"})}}),b=()=>{c({name:"",description:"",signup_link_url:"",publish_date:new Date().toISOString().split("T")[0],is_published:!1}),u(null),m(""),l(null)},v=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 P;const T=(P=A.target.files)==null?void 0:P[0];T&&(u(T),m(URL.createObjectURL(T)))},C=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}g.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(Ks,{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(_e,{children:[e.jsx(Bt,{className:"pb-2",children:e.jsx(Ut,{className:"text-sm font-medium text-muted-foreground",children:"Total Services"})}),e.jsx(Oe,{children:e.jsx("div",{className:"text-2xl font-bold",children:p.length})})]}),e.jsxs(_e,{children:[e.jsx(Bt,{className:"pb-2",children:e.jsx(Ut,{className:"text-sm font-medium text-muted-foreground",children:"Published"})}),e.jsx(Oe,{children:e.jsx("div",{className:"text-2xl font-bold",children:p.filter(A=>A.is_published).length})})]})]}),e.jsxs(Os,{open:r,onOpenChange:A=>{a(A),A||b()},children:[e.jsx(Ko,{asChild:!0,children:e.jsxs($,{className:"gap-2",children:[e.jsx(sn,{className:"h-4 w-4"}),"Add Service"]})}),e.jsxs(Rs,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsx(Us,{children:e.jsx(zs,{children:i?"Edit Service":"Add New Service"})}),e.jsxs("form",{onSubmit:C,className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"name",children:"Name *"}),e.jsx(be,{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(se,{children:"Description"}),e.jsx(m2,{content:o.description,onChange:A=>c({...o,description:A}),placeholder:"Enter description",minHeight:"120px"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"signup_link_url",children:"Signup Link URL *"}),e.jsx(be,{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(se,{htmlFor:"publish_date",children:"Publish Date"}),e.jsx(be,{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(Tn,{id:"is_published",checked:o.is_published,onCheckedChange:A=>c({...o,is_published:A})}),e.jsx(se,{htmlFor:"is_published",children:"Published"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Preview Image"}),h?e.jsxs("div",{className:"relative",children:[e.jsx("img",{src:h,alt:"Preview",className:"w-full max-h-48 object-contain rounded-lg border"}),e.jsx($,{type:"button",variant:"destructive",size:"icon",className:"absolute top-2 right-2 h-6 w-6",onClick:()=>{u(null),m("")},children:e.jsx(pr,{className:"h-3 w-3"})})]}):e.jsxs("div",{className:"border-2 border-dashed rounded-lg p-4 text-center",children:[e.jsx(Jl,{className:"h-8 w-8 mx-auto text-muted-foreground mb-2"}),e.jsx(be,{type:"file",accept:"image/*",onChange:N,className:"cursor-pointer"})]})]}),e.jsxs("div",{className:"flex justify-end gap-2 pt-4",children:[e.jsx($,{type:"button",variant:"outline",onClick:()=>a(!1),children:"Cancel"}),e.jsx($,{type:"submit",disabled:g.isPending,children:g.isPending?"Saving...":i?"Update":"Create"})]})]})]})]})]}),e.jsx(_e,{children:e.jsx(Oe,{className:"p-0",children:x?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(Va,{children:[e.jsx(Ha,{children:e.jsxs(hn,{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(Ga,{children:p.map(A=>e.jsxs(hn,{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(Jl,{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(Tr,{className:"h-3 w-3"}),"Link"]})}),e.jsx(gt,{children:new Date(A.publish_date).toLocaleDateString()}),e.jsx(gt,{children:e.jsx($e,{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($,{variant:"ghost",size:"icon",onClick:()=>v(A),children:e.jsx(Ya,{className:"h-4 w-4"})}),e.jsx($,{variant:"ghost",size:"icon",onClick:async()=>{await Yi("Are you sure you want to delete this service?")&&y.mutate(A.id)},children:e.jsx(Pn,{className:"h-4 w-4 text-destructive"})})]})})]},A.id))})]})})})]})})};function I1n(){const{toast:s}=gi(),[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:b}=await U.functions.invoke("stripe-manage-coupons",{body:{action:"list"}});if(b)throw b;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:b,error:v}=await U.functions.invoke("stripe-manage-coupons",{body:y});if(v)throw v;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:b}=await U.functions.invoke("stripe-manage-coupons",{body:{action:"delete",couponId:y}});if(b)throw b;s({title:"Success",description:"Coupon deleted successfully"}),h()}catch(b){console.error("Error deleting coupon:",b),s({title:"Error",description:b.message||"Failed to delete coupon",variant:"destructive"})}},x=y=>y.percent_off?`${y.percent_off}% off`:y.amount_off?`$${(y.amount_off/100).toFixed(2)} off`:"N/A",g=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(Ks,{title:"Subscription Discounts",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(hh,{title:"Subscription Discounts",description:"Create and manage discount coupons for subscriptions",children:e.jsxs(Os,{open:o,onOpenChange:c,children:[e.jsx(Ko,{asChild:!0,children:e.jsxs($,{children:[e.jsx(sn,{className:"mr-2 h-4 w-4"}),"Create Coupon"]})}),e.jsxs(Rs,{children:[e.jsxs(Us,{children:[e.jsx(zs,{children:"Create New Coupon"}),e.jsx(Sr,{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(se,{children:"Promotion Code (what users will type)"}),e.jsx(be,{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(se,{children:"Coupon Name (internal label)"}),e.jsx(be,{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(se,{children:"Discount Type"}),e.jsxs(vs,{value:d.discountType,onValueChange:y=>{const b=y==="amount"&&d.duration==="forever"?"once":d.duration;u({...d,discountType:y,duration:b})},children:[e.jsx(gs,{children:e.jsx(bs,{})}),e.jsxs(ys,{children:[e.jsx(Ye,{value:"percent",children:e.jsxs("span",{className:"flex items-center",children:[e.jsx(ST,{className:"mr-2 h-4 w-4"}),"Percentage Off"]})}),e.jsx(Ye,{value:"amount",children:e.jsxs("span",{className:"flex items-center",children:[e.jsx(qd,{className:"mr-2 h-4 w-4"}),"Fixed Amount Off"]})})]})]})]}),d.discountType==="percent"?e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Percent Off"}),e.jsxs("div",{className:"relative",children:[e.jsx(be,{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(se,{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(be,{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(se,{children:"Duration"}),e.jsxs(vs,{value:d.duration,onValueChange:y=>u({...d,duration:y}),children:[e.jsx(gs,{children:e.jsx(bs,{})}),e.jsxs(ys,{children:[e.jsx(Ye,{value:"once",children:"Once (first payment only)"}),e.jsx(Ye,{value:"repeating",children:"Multiple months"}),e.jsxs(Ye,{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(se,{children:"Number of Months"}),e.jsx(be,{type:"number",min:"1",placeholder:"3",value:d.durationInMonths,onChange:y=>u({...d,durationInMonths:y.target.value})})]}),e.jsx($,{onClick:m,disabled:i,className:"w-full",children:i?e.jsxs(e.Fragment,{children:[e.jsx(Ht,{className:"mr-2 h-4 w-4 animate-spin"}),"Creating..."]}):"Create Coupon"})]})]})]})}),e.jsxs(_e,{children:[e.jsxs(Bt,{children:[e.jsx(Ut,{children:"Active Coupons"}),e.jsx(vr,{children:"Share coupon codes with users to give them discounts on subscriptions"})]}),e.jsx(Oe,{children:r?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx(Ht,{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(Va,{children:[e.jsx(Ha,{children:e.jsxs(hn,{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(Ga,{children:t.map(y=>{var b;return e.jsxs(hn,{children:[e.jsx(gt,{className:"font-mono font-medium",children:((b=y.promotion_codes)==null?void 0:b.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:x(y)}),e.jsx(gt,{children:g(y)}),e.jsx(gt,{children:y.times_redeemed}),e.jsx(gt,{children:e.jsx($e,{variant:y.valid?"default":"secondary",children:y.valid?"Active":"Inactive"})}),e.jsx(gt,{className:"text-right",children:e.jsx($,{variant:"ghost",size:"sm",onClick:()=>p(y.id),children:e.jsx(Pn,{className:"h-4 w-4 text-destructive"})})})]},y.id)})})]})})]}),e.jsxs(_e,{children:[e.jsx(Bt,{children:e.jsx(Ut,{children:"How to Use Coupons"})}),e.jsxs(Oe,{className:"text-sm text-muted-foreground space-y-2",children:[e.jsx("p",{children:"1. Create a coupon above with your desired discount."}),e.jsx("p",{children:'2. Share the coupon code (shown in the "Code" column) with users.'}),e.jsx("p",{children:"3. Users can enter the code during checkout to receive the discount."}),e.jsx("p",{children:"4. Alternatively, you can create a promotion code in Stripe dashboard for public-facing promotions."})]})]})]})})}const i8e={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 D1n(){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}=ht({queryKey:["admin-subscriptions"],queryFn:async()=>{const{data:b,error:v}=await U.from("profiles").select(` *, brokerages:brokerage_id (id, name) `).order("created_at",{ascending:!1});if(v)throw v;return b}}),{data:h}=ht({queryKey:["admin-brokerages-subscriptions"],queryFn:async()=>{const{data:b,error:v}=await U.from("brokerages").select("*").order("name");if(v)throw v;return await Promise.all((b||[]).map(async C=>{const{data:A}=await U.from("profiles").select("id, name, email, subscription_status, subscription_product_id").eq("brokerage_id",C.id),{data:T}=await U.from("user_roles").select("user_id").eq("role","brokerage_manager"),P=(T==null?void 0:T.map(D=>D.user_id))||[],M=(A==null?void 0:A.filter(D=>P.includes(D.id)))||[],I=(A==null?void 0:A.length)||0;return{...C,managers:M,agentCount:I}}))}}),{data:m}=ht({queryKey:["admin-website-subscriptions"],queryFn:async()=>{const{data:b,error:v}=await U.from("local_move_subscriptions").select("*").order("created_at",{ascending:!1});if(v)throw v;return b}}),p=b=>{if(b.is_grandfathered)return{status:"Grandfathered",badge:"Legacy",variant:"secondary"};if(b.brokerage_id&&!b.subscription_product_id)return{status:"Brokerage",badge:"Team Member",variant:"outline"};if(b.is_trial&&b.trial_expires_at)return new Date(b.trial_expires_at)>new Date?{status:"Trial",badge:"Active Trial",variant:"default"}:{status:"Trial Expired",badge:"Expired",variant:"destructive"};if(b.subscription_status==="active"||b.subscription_status==="trialing"){const v=i8e[b.subscription_product_id];return{status:(v==null?void 0:v.name)||"Active",badge:b.subscription_status==="trialing"?"Trial":"Active",variant:"default"}}return b.subscription_status==="canceled"||b.subscription_status==="past_due"?{status:"Canceled",badge:"Inactive",variant:"destructive"}:{status:"None",badge:"No Subscription",variant:"outline"}},x=c==null?void 0:c.filter(b=>{var N,C;if(!(((N=b.name)==null?void 0:N.toLowerCase().includes(s.toLowerCase()))||((C=b.email)==null?void 0:C.toLowerCase().includes(s.toLowerCase()))))return!1;if(a!=="all"){const A=b.subscription_source||"platform";if(a==="platform"&&A==="local_move_website"||a==="local_move_website"&&A!=="local_move_website")return!1}switch(p(b),n){case"active":return b.subscription_status==="active";case"trialing":return b.subscription_status==="trialing"||b.is_trial&&new Date(b.trial_expires_at)>new Date;case"grandfathered":return b.is_grandfathered;case"brokerage":return b.brokerage_id&&!b.subscription_product_id&&!b.is_grandfathered;case"expired":return b.subscription_status==="canceled"||b.subscription_status==="past_due"||b.is_trial&&new Date(b.trial_expires_at)<=new Date;case"none":return!b.subscription_status||b.subscription_status==="none";default:return!0}}),g={totalUsers:(c==null?void 0:c.length)||0,activeSubscriptions:(c==null?void 0:c.filter(b=>b.subscription_status==="active").length)||0,trials:(c==null?void 0:c.filter(b=>b.subscription_status==="trialing"||b.is_trial&&new Date(b.trial_expires_at)>new Date).length)||0,grandfathered:(c==null?void 0:c.filter(b=>b.is_grandfathered).length)||0,brokerageMembers:(c==null?void 0:c.filter(b=>b.brokerage_id&&!b.subscription_product_id&&!b.is_grandfathered).length)||0,individualSubscribers:(c==null?void 0:c.filter(b=>b.subscription_status==="active"&&b.subscription_product_id==="prod_Tc07cYplXUGNkm").length)||0,brokerageSubscribers:(c==null?void 0:c.filter(b=>b.subscription_status==="active"&&(b.subscription_product_id==="prod_Tc08MupgoVySDG"||b.subscription_product_id==="prod_Tc09N1tJ4RrAFn")).length)||0},y=b=>{window.open(`https://dashboard.stripe.com/customers/${b}`,"_blank")};return e.jsx(Ks,{title:"Subscription Management",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(hh,{title:"Subscription Management",description:"Track and manage all subscriptions",children:e.jsxs($,{onClick:()=>u(),variant:"outline",size:"sm",children:[e.jsx(Wi,{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(_e,{children:e.jsxs(Oe,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(qn,{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:g.totalUsers})]})}),e.jsx(_e,{className:"border-green-500/50",children:e.jsxs(Oe,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(yy,{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:g.activeSubscriptions})]})}),e.jsx(_e,{className:"border-blue-500/50",children:e.jsxs(Oe,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Hr,{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:g.trials})]})}),e.jsx(_e,{className:"border-purple-500/50",children:e.jsxs(Oe,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ng,{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:g.grandfathered})]})}),e.jsx(_e,{className:"border-orange-500/50",children:e.jsxs(Oe,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ai,{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:g.brokerageMembers})]})}),e.jsx(_e,{children:e.jsxs(Oe,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Yj,{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:g.individualSubscribers})]})}),e.jsx(_e,{children:e.jsxs(Oe,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ai,{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:g.brokerageSubscribers})]})})]}),e.jsxs(ua,{defaultValue:"users",className:"space-y-4",children:[e.jsxs(ha,{children:[e.jsx(Qt,{value:"users",children:"All Users"}),e.jsx(Qt,{value:"brokerages",children:"Brokerages"}),e.jsxs(Qt,{value:"websites",className:"gap-2",children:[e.jsx(Gl,{className:"h-4 w-4"}),"Website Subscriptions",m&&m.length>0&&e.jsx($e,{variant:"secondary",className:"ml-1",children:m.length})]})]}),e.jsxs(Jt,{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(Vr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(be,{placeholder:"Search by name or email...",value:s,onChange:b=>t(b.target.value),className:"pl-9"})]}),e.jsxs(vs,{value:a,onValueChange:b=>i(b),children:[e.jsx(gs,{className:"w-[200px]",children:e.jsx(bs,{placeholder:"Source"})}),e.jsxs(ys,{children:[e.jsx(Ye,{value:"all",children:"All Sources"}),e.jsx(Ye,{value:"platform",children:"Platform"}),e.jsx(Ye,{value:"local_move_website",children:"Local Move Website"})]})]}),e.jsxs(vs,{value:n,onValueChange:b=>r(b),children:[e.jsx(gs,{className:"w-[200px]",children:e.jsx(bs,{placeholder:"Filter by status"})}),e.jsxs(ys,{children:[e.jsx(Ye,{value:"all",children:"All Statuses"}),e.jsx(Ye,{value:"active",children:"Active Subscriptions"}),e.jsx(Ye,{value:"trialing",children:"Trials"}),e.jsx(Ye,{value:"grandfathered",children:"Grandfathered"}),e.jsx(Ye,{value:"brokerage",children:"Brokerage Members"}),e.jsx(Ye,{value:"expired",children:"Expired/Canceled"}),e.jsx(Ye,{value:"none",children:"No Subscription"})]})]})]}),e.jsx(_e,{children:e.jsx(Oe,{className:"p-0",children:e.jsxs(Va,{children:[e.jsx(Ha,{children:e.jsxs(hn,{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(Ga,{children:d?e.jsx(hn,{children:e.jsx(gt,{colSpan:6,className:"text-center py-8",children:"Loading subscriptions..."})}):(x==null?void 0:x.length)===0?e.jsx(hn,{children:e.jsx(gt,{colSpan:6,className:"text-center py-8 text-muted-foreground",children:"No users found"})}):x==null?void 0:x.map(b=>{var C,A;const v=p(b),N=i8e[b.subscription_product_id];return e.jsxs(hn,{children:[e.jsx(gt,{children:e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:b.name}),e.jsx("p",{className:"text-sm text-muted-foreground",children:b.email})]})}),e.jsx(gt,{children:e.jsx($e,{variant:v.variant,children:v.badge})}),e.jsx(gt,{children:e.jsx("span",{className:"text-sm",children:b.is_grandfathered?"Legacy Access":b.brokerage_id&&!b.subscription_product_id?"Brokerage Subscription":(N==null?void 0:N.name)||v.status})}),e.jsx(gt,{children:(C=b.brokerages)!=null&&C.name?e.jsx("span",{className:"text-sm",children:b.brokerages.name}):e.jsx("span",{className:"text-sm text-muted-foreground",children:"—"})}),e.jsx(gt,{children:b.subscription_end_date?e.jsx("span",{className:"text-sm",children:Hs(new Date(b.subscription_end_date),"MMM d, yyyy")}):b.trial_expires_at?e.jsxs("span",{className:"text-sm text-blue-600",children:["Trial: ",Hs(new Date(b.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:[b.stripe_customer_id&&e.jsx($,{variant:"ghost",size:"sm",onClick:()=>y(b.stripe_customer_id),children:e.jsx(Tr,{className:"h-4 w-4"})}),e.jsxs(Os,{children:[e.jsx(Ko,{asChild:!0,children:e.jsx($,{variant:"outline",size:"sm",onClick:()=>o(b),children:"Details"})}),e.jsxs(Rs,{children:[e.jsxs(Us,{children:[e.jsx(zs,{children:"Subscription Details"}),e.jsxs(Sr,{children:[b.name," (",b.email,")"]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Status"}),e.jsx($e,{variant:v.variant,className:"mt-1",children:v.badge})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Plan"}),e.jsx("p",{className:"font-medium",children:b.is_grandfathered?"Grandfathered (Legacy)":b.brokerage_id&&!b.subscription_product_id?"Brokerage Subscription":(N==null?void 0:N.name)||"None"})]}),b.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=b.brokerages)==null?void 0:A.name)||"Unknown"})]}),b.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:Hs(new Date(b.subscription_end_date),"MMMM d, yyyy")})]}),b.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:Hs(new Date(b.trial_expires_at),"MMMM d, yyyy")})]}),b.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:b.stripe_customer_id})]})]}),b.stripe_customer_id&&e.jsxs($,{className:"w-full",onClick:()=>y(b.stripe_customer_id),children:[e.jsx(Tr,{className:"h-4 w-4 mr-2"}),"View in Stripe Dashboard"]})]})]})]})]})})]},b.id)})})]})})})]}),e.jsx(Jt,{value:"brokerages",className:"space-y-4",children:e.jsx("div",{className:"grid gap-4",children:h==null?void 0:h.map(b=>{var N,C;const v=(N=b.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(_e,{children:[e.jsx(Bt,{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(Ai,{className:"h-5 w-5 text-primary"})}),e.jsxs("div",{children:[e.jsx(Ut,{className:"text-lg",children:b.name}),e.jsxs(vr,{children:[b.agentCount," agents"]})]})]}),e.jsx($e,{variant:v?"default":"outline",children:v?"Active Subscription":"No Active Subscription"})]})}),e.jsx(Oe,{children:((C=b.managers)==null?void 0:C.length)>0?e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{className:"text-sm font-medium text-muted-foreground",children:"Managers:"}),b.managers.map(A=>{const T=i8e[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($e,{variant:"default",children:T.name}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:T.price})]}):e.jsx($e,{variant:"outline",children:"No Subscription"})})]},A.id)})]}):e.jsx("p",{className:"text-sm text-muted-foreground",children:"No managers assigned"})})]},b.id)})})}),e.jsx(Jt,{value:"websites",className:"space-y-4",children:e.jsxs(_e,{children:[e.jsxs(Bt,{children:[e.jsxs(Ut,{className:"flex items-center gap-2",children:[e.jsx(Gl,{className:"h-5 w-5 text-primary"}),"Local Move Website Subscriptions"]}),e.jsx(vr,{children:"$249 setup fee + $99/mo subscriptions from TheLocalMove.com agent websites"})]}),e.jsx(Oe,{className:"p-0",children:e.jsxs(Va,{children:[e.jsx(Ha,{children:e.jsxs(hn,{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(Ga,{children:m?m.length===0?e.jsx(hn,{children:e.jsx(gt,{colSpan:7,className:"text-center py-8 text-muted-foreground",children:"No website subscriptions yet"})}):m.map(b=>e.jsxs(hn,{children:[e.jsx(gt,{children:e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:b.agent_name||"—"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:b.agent_email})]})}),e.jsx(gt,{children:e.jsx($e,{variant:b.status==="active"?"default":b.status==="canceled"?"destructive":"outline",children:b.status})}),e.jsx(gt,{children:b.setup_fee_paid?e.jsxs($e,{variant:"secondary",children:["Paid · $",(b.setup_fee_amount_cents/100).toFixed(0)]}):e.jsx($e,{variant:"outline",children:"Unpaid"})}),e.jsxs(gt,{className:"font-medium",children:["$",(b.monthly_amount_cents/100).toFixed(0),"/mo"]}),e.jsx(gt,{children:b.current_period_end?e.jsx("span",{className:"text-sm",children:Hs(new Date(b.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:Hs(new Date(b.created_at),"MMM d, yyyy")})}),e.jsx(gt,{className:"text-right",children:b.stripe_customer_id&&e.jsx($,{variant:"ghost",size:"sm",onClick:()=>y(b.stripe_customer_id),children:e.jsx(Tr,{className:"h-4 w-4"})})})]},b.id)):e.jsx(hn,{children:e.jsx(gt,{colSpan:7,className:"text-center py-8",children:"Loading…"})})})]})})]})})]})]})})}function R1n(){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:x,error:g}=await U.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(g)throw g;t(x||[]);const y=(x==null?void 0:x.filter(N=>N.status==="qualified").length)||0,b=(x==null?void 0:x.filter(N=>N.status==="pending").length)||0,v=(x==null?void 0:x.filter(N=>N.status==="cancelled").length)||0;d({total:(x==null?void 0:x.length)||0,qualified:y,pending:b,cancelled:v,totalDiscounts:y*25})}catch(x){console.error("Error fetching referrals:",x),ae.error("Failed to load referrals")}finally{r(!1)}},h=async()=>{try{ae.loading("Processing qualifications...");const{error:x}=await U.functions.invoke("process-referral-qualifications");if(x)throw x;ae.dismiss(),ae.success("Qualifications processed successfully"),u()}catch(x){ae.dismiss(),console.error("Error processing qualifications:",x),ae.error("Failed to process qualifications")}},m=s.filter(x=>{var b,v,N,C,A,T;const g=((v=(b=x.referrer_brokerage)==null?void 0:b.name)==null?void 0:v.toLowerCase().includes(a.toLowerCase()))||((C=(N=x.referred_brokerage)==null?void 0:N.name)==null?void 0:C.toLowerCase().includes(a.toLowerCase()))||((T=(A=x.referred_user)==null?void 0:A.email)==null?void 0:T.toLowerCase().includes(a.toLowerCase())),y=l==="all"||x.status===l;return g&&y}),p=x=>{switch(x){case"qualified":return e.jsxs($e,{className:"bg-green-100 text-green-800",children:[e.jsx(Ro,{className:"h-3 w-3 mr-1"}),"Qualified"]});case"pending":return e.jsxs($e,{variant:"secondary",children:[e.jsx(Hr,{className:"h-3 w-3 mr-1"}),"Pending"]});case"cancelled":return e.jsxs($e,{variant:"destructive",children:[e.jsx($d,{className:"h-3 w-3 mr-1"}),"Cancelled"]});default:return e.jsx($e,{children:x})}};return e.jsx(Ks,{title:"Referral Program",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(hh,{title:"Referral Program",description:"Track and manage brokerage referrals",children:e.jsxs($,{onClick:h,variant:"outline",children:[e.jsx(Wi,{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(_e,{children:e.jsx(Oe,{className:"pt-6",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(qn,{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(_e,{children:e.jsx(Oe,{className:"pt-6",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ro,{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(_e,{children:e.jsx(Oe,{className:"pt-6",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Hr,{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(_e,{children:e.jsx(Oe,{className:"pt-6",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx($d,{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(_e,{children:e.jsx(Oe,{className:"pt-6",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(qd,{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(_e,{children:[e.jsxs(Bt,{children:[e.jsx(Ut,{children:"All Referrals"}),e.jsx(vr,{children:"View and manage all referral relationships"})]}),e.jsxs(Oe,{children:[e.jsxs("div",{className:"flex gap-4 mb-4",children:[e.jsxs("div",{className:"relative flex-1",children:[e.jsx(Vr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(be,{placeholder:"Search by brokerage or email...",value:a,onChange:x=>i(x.target.value),className:"pl-10"})]}),e.jsxs(vs,{value:l,onValueChange:o,children:[e.jsx(gs,{className:"w-[180px]",children:e.jsx(bs,{placeholder:"Filter by status"})}),e.jsxs(ys,{children:[e.jsx(Ye,{value:"all",children:"All Statuses"}),e.jsx(Ye,{value:"pending",children:"Pending"}),e.jsx(Ye,{value:"qualified",children:"Qualified"}),e.jsx(Ye,{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(Va,{children:[e.jsx(Ha,{children:e.jsxs(hn,{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(Ga,{children:m.length===0?e.jsx(hn,{children:e.jsx(gt,{colSpan:6,className:"text-center text-muted-foreground py-8",children:"No referrals found"})}):m.map(x=>{var g,y,b,v;return e.jsxs(hn,{children:[e.jsx(gt,{className:"font-medium",children:((g=x.referrer_brokerage)==null?void 0:g.name)||"Unknown"}),e.jsx(gt,{children:e.jsxs("div",{children:[e.jsx("p",{children:((y=x.referred_brokerage)==null?void 0:y.name)||((b=x.referred_user)==null?void 0:b.name)||"Pending setup"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:(v=x.referred_user)==null?void 0:v.email})]})}),e.jsx(gt,{children:Hs(new Date(x.signup_date),"MMM d, yyyy")}),e.jsx(gt,{children:p(x.status)}),e.jsx(gt,{children:x.qualified_date?Hs(new Date(x.qualified_date),"MMM d, yyyy"):"-"}),e.jsx(gt,{children:x.discount_applied?e.jsx($e,{variant:"outline",className:"text-green-600",children:"$25/mo applied"}):e.jsx("span",{className:"text-muted-foreground",children:"-"})})]},x.id)})})]})]})]})]})})}const o8e=[{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"}],O1n=[{value:"brokerage_manager",label:"Brokerage Manager"},{value:"agent",label:"Agent"}];function F1n(){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:v,error:N}=await U.from("onboarding_checklist_items").select("*").order("target_role").order("sort_order");if(N)throw N;t(v||[])}catch(v){console.error("Error fetching checklist items:",v),ae.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=v=>{o(v),d({title:v.title,description:v.description||"",action_type:v.action_type,target_role:v.target_role,is_active:v.is_active}),i(!0)},p=async()=>{if(!c.title.trim()){ae.error("Title is required");return}try{if(l){const{error:v}=await U.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(v)throw v;ae.success("Checklist item updated")}else{const v=s.filter(C=>C.target_role===c.target_role).reduce((C,A)=>Math.max(C,A.sort_order),-1),{error:N}=await U.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:v+1});if(N)throw N;ae.success("Checklist item created")}i(!1),u()}catch(v){console.error("Error saving checklist item:",v),ae.error("Failed to save checklist item")}},x=async v=>{if(await Yi("Are you sure you want to delete this checklist item?"))try{const{error:N}=await U.from("onboarding_checklist_items").delete().eq("id",v);if(N)throw N;ae.success("Checklist item deleted"),u()}catch(N){console.error("Error deleting checklist item:",N),ae.error("Failed to delete checklist item")}},g=async v=>{try{const{error:N}=await U.from("onboarding_checklist_items").update({is_active:!v.is_active}).eq("id",v.id);if(N)throw N;ae.success(v.is_active?"Item deactivated":"Item activated"),u()}catch(N){console.error("Error toggling item:",N),ae.error("Failed to update item")}},y=s.filter(v=>v.target_role==="brokerage_manager"),b=s.filter(v=>v.target_role==="agent");return e.jsxs(Ks,{title:"Onboarding Checklist",children:[e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-2xl font-bold",children:"Onboarding Checklist"}),e.jsx("p",{className:"text-muted-foreground",children:"Manage checklist items shown to new users on their dashboard"})]}),e.jsxs($,{onClick:h,className:"gap-2",children:[e.jsx(sn,{className:"h-4 w-4"}),"Add Item"]})]}),e.jsxs(_e,{children:[e.jsx(Bt,{children:e.jsxs(Ut,{className:"flex items-center gap-2",children:[e.jsx($e,{variant:"secondary",children:"Brokerage Manager"}),"Checklist Items"]})}),e.jsx(Oe,{children:y.length===0?e.jsx("p",{className:"text-muted-foreground text-center py-4",children:"No checklist items for brokerage managers"}):e.jsxs(Va,{children:[e.jsx(Ha,{children:e.jsxs(hn,{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(Ga,{children:y.map((v,N)=>{var C;return e.jsxs(hn,{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:v.title}),v.description&&e.jsx("p",{className:"text-sm text-muted-foreground line-clamp-1",children:v.description})]})}),e.jsx(gt,{children:e.jsx($e,{variant:"outline",children:((C=o8e.find(A=>A.value===v.action_type))==null?void 0:C.label)||v.action_type})}),e.jsx(gt,{children:e.jsx(Tn,{checked:v.is_active,onCheckedChange:()=>g(v)})}),e.jsx(gt,{className:"text-right",children:e.jsxs("div",{className:"flex items-center justify-end gap-2",children:[e.jsx($,{variant:"ghost",size:"icon",onClick:()=>m(v),children:e.jsx(Ya,{className:"h-4 w-4"})}),e.jsx($,{variant:"ghost",size:"icon",onClick:()=>x(v.id),children:e.jsx(Pn,{className:"h-4 w-4 text-destructive"})})]})})]},v.id)})})]})})]}),e.jsxs(_e,{children:[e.jsx(Bt,{children:e.jsxs(Ut,{className:"flex items-center gap-2",children:[e.jsx($e,{variant:"secondary",children:"Agent"}),"Checklist Items"]})}),e.jsx(Oe,{children:b.length===0?e.jsx("p",{className:"text-muted-foreground text-center py-4",children:"No checklist items for agents"}):e.jsxs(Va,{children:[e.jsx(Ha,{children:e.jsxs(hn,{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(Ga,{children:b.map((v,N)=>{var C;return e.jsxs(hn,{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:v.title}),v.description&&e.jsx("p",{className:"text-sm text-muted-foreground line-clamp-1",children:v.description})]})}),e.jsx(gt,{children:e.jsx($e,{variant:"outline",children:((C=o8e.find(A=>A.value===v.action_type))==null?void 0:C.label)||v.action_type})}),e.jsx(gt,{children:e.jsx(Tn,{checked:v.is_active,onCheckedChange:()=>g(v)})}),e.jsx(gt,{className:"text-right",children:e.jsxs("div",{className:"flex items-center justify-end gap-2",children:[e.jsx($,{variant:"ghost",size:"icon",onClick:()=>m(v),children:e.jsx(Ya,{className:"h-4 w-4"})}),e.jsx($,{variant:"ghost",size:"icon",onClick:()=>x(v.id),children:e.jsx(Pn,{className:"h-4 w-4 text-destructive"})})]})})]},v.id)})})]})})]})]}),e.jsx(Os,{open:a,onOpenChange:i,children:e.jsxs(Rs,{children:[e.jsx(Us,{children:e.jsx(zs,{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(se,{htmlFor:"title",children:"Title *"}),e.jsx(be,{id:"title",value:c.title,onChange:v=>d({...c,title:v.target.value}),placeholder:"e.g., Watch your first academy video"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"description",children:"Description"}),e.jsx(Is,{id:"description",value:c.description,onChange:v=>d({...c,description:v.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(se,{children:"Target Role"}),e.jsxs(vs,{value:c.target_role,onValueChange:v=>d({...c,target_role:v}),children:[e.jsx(gs,{children:e.jsx(bs,{})}),e.jsx(ys,{children:O1n.map(v=>e.jsx(Ye,{value:v.value,children:v.label},v.value))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Action Type"}),e.jsxs(vs,{value:c.action_type,onValueChange:v=>d({...c,action_type:v}),children:[e.jsx(gs,{children:e.jsx(bs,{})}),e.jsx(ys,{children:o8e.map(v=>e.jsx(Ye,{value:v.value,children:v.label},v.value))})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Tn,{id:"is_active",checked:c.is_active,onCheckedChange:v=>d({...c,is_active:v})}),e.jsx(se,{htmlFor:"is_active",children:"Active"})]})]}),e.jsxs(kr,{children:[e.jsx($,{variant:"outline",onClick:()=>i(!1),children:"Cancel"}),e.jsx($,{onClick:p,children:l?"Save Changes":"Create Item"})]})]})})]})}function z1n(){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(""),[x,g]=j.useState(""),{data:y}=ht({queryKey:["admin-brokerages"],queryFn:async()=>{const{data:D,error:B}=await U.from("brokerages").select("id, name").order("name");if(B)throw B;return D}}),b=async D=>{let q=[],W=0,V=!0;for(;V;){const{data:K,error:Q}=await D(W,W+1e3-1);if(Q)throw Q;K&&K.length>0?(q=[...q,...K],W+=1e3,V=K.length===1e3):V=!1}return q},{data:v,isLoading:N}=ht({queryKey:["admin-agent-os-user-stats"],queryFn:async()=>{const D=await b((Ee,Me)=>U.from("profiles").select("id, name, email, brokerage_id, created_at").range(Ee,Me)),{data:B}=await U.from("brokerages").select("id, name"),q=new Map((B==null?void 0:B.map(Ee=>[Ee.id,Ee.name]))||[]),[{data:W},{data:V},{data:K},{data:Q},{data:J},{data:ce},{data:ue}]=await Promise.all([U.rpc("get_admin_contact_counts"),U.rpc("get_admin_video_counts"),U.rpc("get_admin_popby_counts"),U.rpc("get_admin_listing_counts"),U.rpc("get_admin_deal_counts"),U.rpc("get_admin_portal_counts"),U.rpc("get_admin_sendable_card_counts")]),ne=new Map;W==null||W.forEach(Ee=>ne.set(Ee.owner_user_id,Ee.contact_count));const ee=new Map;V==null||V.forEach(Ee=>ee.set(Ee.owner_user_id,Ee.video_count));const le=new Map;K==null||K.forEach(Ee=>le.set(Ee.owner_user_id,Ee.popby_count));const he=new Map;Q==null||Q.forEach(Ee=>he.set(Ee.agent_id,Ee.listing_count));const ve=new Map;J==null||J.forEach(Ee=>ve.set(Ee.owner_user_id,Ee.deal_count));const ge=new Map;ce==null||ce.forEach(Ee=>ge.set(Ee.owner_user_id,{total:Ee.portal_count,active:Ee.active_portal_count}));const fe=new Map;return ue==null||ue.forEach(Ee=>fe.set(Ee.owner_user_id,{total:Ee.card_count,sent:Ee.sent_card_count,views:Ee.total_card_views})),D.map(Ee=>{const Me=ge.get(Ee.id),De=fe.get(Ee.id);return{id:Ee.id,name:Ee.name||"Unknown",email:Ee.email||"",brokerage_id:Ee.brokerage_id,brokerage_name:Ee.brokerage_id&&q.get(Ee.brokerage_id)||null,contact_count:ne.get(Ee.id)||0,video_count:ee.get(Ee.id)||0,popby_count:le.get(Ee.id)||0,listing_count:he.get(Ee.id)||0,deal_count:ve.get(Ee.id)||0,portal_count:(Me==null?void 0:Me.total)||0,active_portal_count:(Me==null?void 0:Me.active)||0,card_count:(De==null?void 0:De.total)||0,sent_card_count:(De==null?void 0:De.sent)||0,total_card_views:(De==null?void 0:De.views)||0,created_at:Ee.created_at}})}}),C=j.useMemo(()=>{if(!v)return[];let D=v.filter(B=>{const q=s.toLowerCase(),W=!s||B.name.toLowerCase().includes(q)||B.email.toLowerCase().includes(q),V=n==="all"||n==="none"&&!B.brokerage_id||B.brokerage_id===n,K=parseInt(c)||0,Q=parseInt(u)||0,J=parseInt(m)||0,ce=parseInt(x)||0,ue=B.contact_count>=K&&B.video_count>=Q&&B.popby_count>=J&&B.listing_count>=ce;return W&&V&&ue});return D.sort((B,q)=>{let W=0;return a==="name"?W=B.name.localeCompare(q.name):W=B[a]-q[a],l==="asc"?W:-W}),D},[v,s,n,a,l,c,u,m,x]),A=D=>{a===D?o(l==="asc"?"desc":"asc"):(i(D),o("desc"))},T=()=>{const D=["Name","Email","Brokerage","Contacts","Videos","Popbys","Listings","Deals","Portals (Active)","Cards Created","Cards Sent","Card Views"],B=C.map(Q=>[Q.name,Q.email,Q.brokerage_name||"None",Q.contact_count,Q.video_count,Q.popby_count,Q.listing_count,Q.deal_count,`${Q.portal_count} (${Q.active_portal_count})`,Q.card_count,Q.sent_card_count,Q.total_card_views]),q=[D.join(","),...B.map(Q=>Q.map(J=>`"${J}"`).join(","))].join(` `),W=new Blob([q],{type:"text/csv"}),V=URL.createObjectURL(W),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)},P=j.useMemo(()=>C.length?C.reduce((D,B)=>({contacts:D.contacts+B.contact_count,videos:D.videos+B.video_count,popbys:D.popbys+B.popby_count,listings:D.listings+B.listing_count,deals:D.deals+B.deal_count,portals:D.portals+B.portal_count,activePortals:D.activePortals+B.active_portal_count,cards:D.cards+B.card_count,sentCards:D.sentCards+B.sent_card_count,cardViews:D.cardViews+B.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},[C]),M=j.useMemo(()=>C.length?{portals:C.filter(D=>D.portal_count>0).length,cards:C.filter(D=>D.card_count>0).length}:{portals:0,cards:0},[C]),I=({field:D,children:B})=>e.jsx(Lt,{className:"cursor-pointer hover:bg-muted/50 select-none",onClick:()=>A(D),children:e.jsxs("div",{className:"flex items-center gap-1",children:[B,e.jsx(Tx,{className:`h-3 w-3 ${a===D?"text-primary":"text-muted-foreground"}`})]})});return e.jsx(JN,{children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"grid gap-4 md:grid-cols-2",children:[e.jsxs(_e,{className:"border-blue-500/20 bg-gradient-to-br from-blue-500/5 to-transparent",children:[e.jsx(Bt,{className:"pb-2",children:e.jsxs(Ut,{className:"text-sm font-medium flex items-center gap-2",children:[e.jsx(zj,{className:"h-4 w-4 text-blue-500"}),"Client Portals"]})}),e.jsx(Oe,{children:e.jsxs("div",{className:"grid grid-cols-3 gap-4 text-center",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-2xl font-bold",children: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:P.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:P.activePortals}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Active Portals"})]})]})})]}),e.jsxs(_e,{className:"border-violet-500/20 bg-gradient-to-br from-violet-500/5 to-transparent",children:[e.jsx(Bt,{className:"pb-2",children:e.jsxs(Ut,{className:"text-sm font-medium flex items-center gap-2",children:[e.jsx(nn,{className:"h-4 w-4 text-violet-500"}),"Card Studio"]})}),e.jsx(Oe,{children:e.jsxs("div",{className:"grid grid-cols-4 gap-3 text-center",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-2xl font-bold",children: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:P.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:P.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:P.cardViews}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Total Views"})]})]})})]})]}),e.jsxs(_e,{children:[e.jsx(Bt,{children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsxs(Ut,{className:"flex items-center gap-2",children:[e.jsx(qn,{className:"h-5 w-5"}),"User Activity Analytics"]}),e.jsx(vr,{children:"View all users and their Agent OS usage metrics"})]}),e.jsxs($,{variant:"outline",size:"sm",onClick:T,children:[e.jsx(di,{className:"h-4 w-4 mr-2"}),"Export CSV"]})]})}),e.jsxs(Oe,{className:"space-y-4",children:[e.jsxs("div",{className:"grid gap-4 md:grid-cols-6",children:[e.jsx("div",{className:"md:col-span-2",children:e.jsxs("div",{className:"relative",children:[e.jsx(Vr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(be,{placeholder:"Search by name or email...",value:s,onChange:D=>t(D.target.value),className:"pl-9"})]})}),e.jsx("div",{children:e.jsxs(vs,{value:n,onValueChange:r,children:[e.jsxs(gs,{children:[e.jsx(Ai,{className:"h-4 w-4 mr-2 text-muted-foreground"}),e.jsx(bs,{placeholder:"Brokerage"})]}),e.jsxs(ys,{children:[e.jsx(Ye,{value:"all",children:"All Brokerages"}),e.jsx(Ye,{value:"none",children:"No Brokerage"}),y==null?void 0:y.map(D=>e.jsx(Ye,{value:D.id,children:D.name},D.id))]})]})}),e.jsx("div",{children:e.jsx(be,{type:"number",placeholder:"Min contacts",value:c,onChange:D=>d(D.target.value),min:"0"})}),e.jsx("div",{children:e.jsx(be,{type:"number",placeholder:"Min videos",value:u,onChange:D=>h(D.target.value),min:"0"})}),e.jsx("div",{children:e.jsx(be,{type:"number",placeholder:"Min popbys",value:m,onChange:D=>p(D.target.value),min:"0"})})]}),e.jsxs("div",{className:"grid gap-4 md:grid-cols-8 text-sm",children:[e.jsxs("div",{className:"bg-muted/50 rounded-lg p-3 text-center",children:[e.jsx("div",{className:"text-2xl font-bold",children:C.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:P.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:P.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:P.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:P.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:P.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:P.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:P.cards.toLocaleString()}),e.jsx("div",{className:"text-muted-foreground",children:"Cards"})]})]}),N?e.jsx("div",{className:"flex justify-center py-12",children:e.jsx(Ht,{className:"h-8 w-8 animate-spin text-muted-foreground"})}):e.jsx("div",{className:"rounded-md border overflow-x-auto",children:e.jsxs(Va,{children:[e.jsx(Ha,{children:e.jsxs(hn,{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(zj,{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(nn,{className:"h-3 w-3 text-violet-500"}),"Cards"]})})]})}),e.jsx(Ga,{children:C.length===0?e.jsx(hn,{children:e.jsx(gt,{colSpan:10,className:"text-center py-8 text-muted-foreground",children:"No users found matching your filters"})}):C.map(D=>e.jsxs(hn,{children:[e.jsx(gt,{className:"font-medium",children:D.name}),e.jsx(gt,{className:"text-muted-foreground",children:D.email}),e.jsx(gt,{children:D.brokerage_name?e.jsx($e,{variant:"secondary",children:D.brokerage_name}):e.jsx("span",{className:"text-muted-foreground",children:"—"})}),e.jsx(gt,{children:e.jsx($e,{variant:D.contact_count>0?"default":"outline",children:D.contact_count})}),e.jsx(gt,{children:e.jsx($e,{variant:D.video_count>0?"default":"outline",children:D.video_count})}),e.jsx(gt,{children:e.jsx($e,{variant:D.popby_count>0?"default":"outline",children:D.popby_count})}),e.jsx(gt,{children:e.jsx($e,{variant:D.listing_count>0?"default":"outline",children:D.listing_count})}),e.jsx(gt,{children:e.jsx($e,{variant:D.deal_count>0?"default":"outline",children:D.deal_count})}),e.jsx(gt,{children:D.portal_count>0?e.jsxs(Mx,{children:[e.jsx(Lx,{children:e.jsxs($e,{variant:"default",className:"bg-blue-600 hover:bg-blue-700",children:[D.portal_count,D.active_portal_count>0&&e.jsxs("span",{className:"ml-1 opacity-75",children:["(",D.active_portal_count," active)"]})]})}),e.jsxs(tx,{children:[e.jsxs("p",{children:[D.portal_count," total portals"]}),e.jsxs("p",{children:[D.active_portal_count," currently active"]})]})]}):e.jsx($e,{variant:"outline",children:"0"})}),e.jsx(gt,{children:D.card_count>0?e.jsxs(Mx,{children:[e.jsx(Lx,{children:e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx($e,{variant:"default",className:"bg-violet-600 hover:bg-violet-700",children:D.card_count}),D.sent_card_count>0&&e.jsxs("span",{className:"flex items-center gap-0.5 text-xs text-emerald-600",children:[e.jsx(Br,{className:"h-3 w-3"}),D.sent_card_count]}),D.total_card_views>0&&e.jsxs("span",{className:"flex items-center gap-0.5 text-xs text-muted-foreground",children:[e.jsx(ga,{className:"h-3 w-3"}),D.total_card_views]})]})}),e.jsxs(tx,{children:[e.jsxs("p",{children:[D.card_count," cards created"]}),e.jsxs("p",{children:[D.sent_card_count," sent"]}),e.jsxs("p",{children:[D.total_card_views," total views"]})]})]}):e.jsx($e,{variant:"outline",children:"0"})})]},D.id))})]})})]})]})]})})}function B1n(){gi(),ts();const[s,t]=j.useState("user-analytics"),{data:n}=ht({queryKey:["admin-feature-flags"],queryFn:async()=>{const{data:p,error:x}=await U.from("feature_flags").select("*").order("key");if(x)throw x;return p}}),{data:r,isLoading:a}=ht({queryKey:["admin-relationship-types"],queryFn:async()=>{const{data:p,error:x}=await U.from("relationship_types").select("*").order("sort_order");if(x)throw x;return p}}),{data:i,isLoading:l}=ht({queryKey:["admin-action-types"],queryFn:async()=>{const{data:p,error:x}=await U.from("action_types").select("*").order("sort_order");if(x)throw x;return p}}),{data:o,isLoading:c}=ht({queryKey:["admin-action-scripts"],queryFn:async()=>{const{data:p,error:x}=await U.from("action_scripts").select("*, action_type:action_types(*)");if(x)throw x;return p}}),{data:d,isLoading:u}=ht({queryKey:["admin-touchpoint-plans"],queryFn:async()=>{const{data:p,error:x}=await U.from("touchpoint_plans").select("*").order("name");if(x)throw x;return p}}),{data:h,isLoading:m}=ht({queryKey:["admin-popby-items"],queryFn:async()=>{const{data:p,error:x}=await U.from("popby_items").select("*").is("owner_user_id",null).order("name");if(x)throw x;return p}});return e.jsx(Ks,{title:"Agent OS Control Center",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(hh,{title:"Agent OS Control Center",description:"Manage InnerCircle settings, scripts, and touchpoint plans"}),e.jsxs(ua,{value:s,onValueChange:t,children:[e.jsxs(ha,{className:"grid w-full grid-cols-9",children:[e.jsxs(Qt,{value:"user-analytics",className:"gap-2",children:[e.jsx(ml,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Users"})]}),e.jsxs(Qt,{value:"relationship-types",className:"gap-2",children:[e.jsx(qn,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Relationships"})]}),e.jsxs(Qt,{value:"action-types",className:"gap-2",children:[e.jsx(ya,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Actions"})]}),e.jsxs(Qt,{value:"scripts",className:"gap-2",children:[e.jsx(Wr,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Scripts"})]}),e.jsxs(Qt,{value:"video-scripts",className:"gap-2",children:[e.jsx(lh,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Video Scripts"})]}),e.jsxs(Qt,{value:"plans",className:"gap-2",children:[e.jsx(ia,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Plans"})]}),e.jsxs(Qt,{value:"popbys",className:"gap-2",children:[e.jsx(Co,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Popbys"})]}),e.jsxs(Qt,{value:"settings",className:"gap-2",children:[e.jsx(pc,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Settings"})]}),e.jsxs(Qt,{value:"feature-flags",className:"gap-2",children:[e.jsx(U3,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Flags"})]})]}),e.jsx(Jt,{value:"user-analytics",className:"mt-6",children:e.jsx(z1n,{})}),e.jsx(Jt,{value:"relationship-types",className:"mt-6",children:e.jsx($1n,{types:r||[],isLoading:a})}),e.jsx(Jt,{value:"action-types",className:"mt-6",children:e.jsx(U1n,{types:i||[],isLoading:l})}),e.jsx(Jt,{value:"scripts",className:"mt-6",children:e.jsx(q1n,{scripts:o||[],actionTypes:i||[],isLoading:c})}),e.jsx(Jt,{value:"video-scripts",className:"mt-6",children:e.jsx(W1n,{})}),e.jsx(Jt,{value:"plans",className:"mt-6",children:e.jsx(V1n,{plans:d||[],actionTypes:i||[],scripts:o||[],isLoading:u})}),e.jsx(Jt,{value:"popbys",className:"mt-6",children:e.jsx(G1n,{items:h||[],isLoading:m})}),e.jsx(Jt,{value:"settings",className:"mt-6",children:e.jsx(K1n,{})}),e.jsx(Jt,{value:"feature-flags",className:"mt-6",children:e.jsx(H1n,{flags:n||[]})})]})]})})}function $1n({types:s,isLoading:t}){const{toast:n}=gi(),r=ts(),[a,i]=j.useState(null),[l,o]=j.useState(!1),c=yt({mutationFn:async u=>{if(u.id){const{error:h}=await U.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 U.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 U.from("relationship_types").update({active:!u.active}).eq("id",u.id),r.invalidateQueries({queryKey:["admin-relationship-types"]})};return e.jsxs(_e,{children:[e.jsxs(Bt,{className:"flex flex-row items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(Ut,{children:"Relationship Types"}),e.jsx(vr,{children:"Define the relationship categories for InnerCircle contacts"})]}),e.jsxs($,{onClick:()=>{i(null),o(!0)},children:[e.jsx(sn,{className:"h-4 w-4 mr-2"}),"Add Type"]})]}),e.jsx(Oe,{children:t?e.jsx("div",{className:"flex justify-center py-8",children:e.jsx(Ht,{className:"h-8 w-8 animate-spin text-muted-foreground"})}):e.jsxs(Va,{children:[e.jsx(Ha,{children:e.jsxs(hn,{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(Ga,{children:s.map(u=>e.jsxs(hn,{children:[e.jsx(gt,{children:e.jsx($p,{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(Tn,{checked:u.active,onCheckedChange:()=>d(u)})}),e.jsx(gt,{children:e.jsx($,{variant:"ghost",size:"icon",onClick:()=>{i(u),o(!0)},children:e.jsx(Ya,{className:"h-4 w-4"})})})]},u.id))})]})}),e.jsx(Os,{open:l,onOpenChange:o,children:e.jsxs(Rs,{children:[e.jsx(Us,{children:e.jsxs(zs,{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(se,{htmlFor:"name",children:"Name"}),e.jsx(be,{id:"name",name:"name",defaultValue:a==null?void 0:a.name,required:!0})]}),e.jsxs("div",{children:[e.jsx(se,{htmlFor:"description",children:"Description"}),e.jsx(Is,{id:"description",name:"description",defaultValue:(a==null?void 0:a.description)||""})]}),e.jsxs("div",{children:[e.jsx(se,{htmlFor:"icon",children:"Icon"}),e.jsx(be,{id:"icon",name:"icon",defaultValue:(a==null?void 0:a.icon)||"",placeholder:"e.g., star, heart, user"})]})]}),e.jsxs(kr,{className:"mt-4",children:[e.jsx($,{type:"button",variant:"outline",onClick:()=>o(!1),children:"Cancel"}),e.jsxs($,{type:"submit",disabled:c.isPending,children:[c.isPending&&e.jsx(Ht,{className:"h-4 w-4 mr-2 animate-spin"}),"Save"]})]})]})]})})]})}function U1n({types:s,isLoading:t}){const{toast:n}=gi(),r=ts(),[a,i]=j.useState(null),[l,o]=j.useState(!1),c=yt({mutationFn:async u=>{if(u.id){const{error:h}=await U.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 U.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 U.from("action_types").update({active:!u.active}).eq("id",u.id),r.invalidateQueries({queryKey:["admin-action-types"]})};return e.jsxs(_e,{children:[e.jsxs(Bt,{className:"flex flex-row items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(Ut,{children:"Action Types"}),e.jsx(vr,{children:"Define the types of touchpoint actions agents can take"})]}),e.jsxs($,{onClick:()=>{i(null),o(!0)},children:[e.jsx(sn,{className:"h-4 w-4 mr-2"}),"Add Action"]})]}),e.jsx(Oe,{children:t?e.jsx("div",{className:"flex justify-center py-8",children:e.jsx(Ht,{className:"h-8 w-8 animate-spin text-muted-foreground"})}):e.jsxs(Va,{children:[e.jsx(Ha,{children:e.jsxs(hn,{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(Ga,{children:s.map(u=>e.jsxs(hn,{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(Tn,{checked:u.active,onCheckedChange:()=>d(u)})}),e.jsx(gt,{children:e.jsx($,{variant:"ghost",size:"icon",onClick:()=>{i(u),o(!0)},children:e.jsx(Ya,{className:"h-4 w-4"})})})]},u.id))})]})}),e.jsx(Os,{open:l,onOpenChange:o,children:e.jsxs(Rs,{children:[e.jsx(Us,{children:e.jsxs(zs,{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(se,{htmlFor:"name",children:"Name"}),e.jsx(be,{id:"name",name:"name",defaultValue:a==null?void 0:a.name,required:!0})]}),e.jsxs("div",{children:[e.jsx(se,{htmlFor:"description",children:"Description"}),e.jsx(Is,{id:"description",name:"description",defaultValue:(a==null?void 0:a.description)||""})]}),e.jsxs("div",{children:[e.jsx(se,{htmlFor:"icon",children:"Icon"}),e.jsx(be,{id:"icon",name:"icon",defaultValue:(a==null?void 0:a.icon)||"",placeholder:"e.g., phone, message"})]}),e.jsxs("div",{children:[e.jsx(se,{htmlFor:"color",children:"Color"}),e.jsx(be,{id:"color",name:"color",type:"color",defaultValue:(a==null?void 0:a.color)||"#6366f1"})]})]}),e.jsxs(kr,{className:"mt-4",children:[e.jsx($,{type:"button",variant:"outline",onClick:()=>o(!1),children:"Cancel"}),e.jsxs($,{type:"submit",disabled:c.isPending,children:[c.isPending&&e.jsx(Ht,{className:"h-4 w-4 mr-2 animate-spin"}),"Save"]})]})]})]})})]})}function q1n({scripts:s,actionTypes:t,isLoading:n}){const{toast:r}=gi(),a=ts(),[i,l]=j.useState(null),[o,c]=j.useState(!1),d=yt({mutationFn:async h=>{if(h.id){const{error:m}=await U.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 U.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 U.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(_e,{children:[e.jsxs(Bt,{className:"flex flex-row items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(Ut,{children:"Script Library"}),e.jsx(vr,{children:"Create and manage scripts for each action type"})]}),e.jsxs($,{onClick:()=>{l(null),c(!0)},children:[e.jsx(sn,{className:"h-4 w-4 mr-2"}),"Add Script"]})]}),e.jsx(Oe,{children:n?e.jsx("div",{className:"flex justify-center py-8",children:e.jsx(Ht,{className:"h-8 w-8 animate-spin text-muted-foreground"})}):e.jsxs(Va,{children:[e.jsx(Ha,{children:e.jsxs(hn,{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(Ga,{children:s.map(h=>{var m;return e.jsxs(hn,{children:[e.jsx(gt,{className:"font-medium",children:h.title}),e.jsx(gt,{children:e.jsx($e,{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($e,{variant:h.active?"default":"secondary",children:h.active?"Active":"Inactive"})}),e.jsxs(gt,{className:"flex gap-1",children:[e.jsx($,{variant:"ghost",size:"icon",onClick:()=>{l(h),c(!0)},children:e.jsx(Ya,{className:"h-4 w-4"})}),e.jsx($,{variant:"ghost",size:"icon",onClick:()=>u.mutate(h.id),children:e.jsx(Pn,{className:"h-4 w-4 text-destructive"})})]})]},h.id)})})]})}),e.jsx(Os,{open:o,onOpenChange:c,children:e.jsxs(Rs,{className:"max-w-2xl",children:[e.jsx(Us,{children:e.jsxs(zs,{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(se,{htmlFor:"title",children:"Title"}),e.jsx(be,{id:"title",name:"title",defaultValue:i==null?void 0:i.title,required:!0})]}),e.jsxs("div",{children:[e.jsx(se,{htmlFor:"action_type_id",children:"Action Type"}),e.jsxs(vs,{name:"action_type_id",defaultValue:i==null?void 0:i.action_type_id,children:[e.jsx(gs,{children:e.jsx(bs,{placeholder:"Select action type"})}),e.jsx(ys,{children:t.map(h=>e.jsx(Ye,{value:h.id,children:h.name},h.id))})]})]})]}),e.jsxs("div",{children:[e.jsx(se,{htmlFor:"tone",children:"Tone (optional)"}),e.jsx(be,{id:"tone",name:"tone",defaultValue:(i==null?void 0:i.tone)||"",placeholder:"e.g., Friendly, Professional, Casual"})]}),e.jsxs("div",{children:[e.jsx(se,{htmlFor:"script_body",children:"Script Body"}),e.jsx(Is,{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(kr,{className:"mt-4",children:[e.jsx($,{type:"button",variant:"outline",onClick:()=>c(!1),children:"Cancel"}),e.jsxs($,{type:"submit",disabled:d.isPending,children:[d.isPending&&e.jsx(Ht,{className:"h-4 w-4 mr-2 animate-spin"}),"Save"]})]})]})]})})]})}function V1n({plans:s,actionTypes:t,scripts:n,isLoading:r}){const{toast:a}=gi(),i=ts(),[l,o]=j.useState(null),[c,d]=j.useState(!1),[u,h]=j.useState(null),[m,p]=j.useState(!1),[x,g]=j.useState(null),[y,b]=j.useState(null),{data:v}=ht({queryKey:["plan-items",u],queryFn:async()=>{if(!u)return[];const{data:I,error:D}=await U.from("touchpoint_plan_items").select("*").eq("plan_id",u).order("month_number");if(D)throw D;return I},enabled:!!u}),N=yt({mutationFn:async I=>{if(I.id){const{error:D}=await U.from("touchpoint_plans").update({name:I.name,description:I.description,active:I.active}).eq("id",I.id);if(D)throw D}else{const{error:D}=await U.from("touchpoint_plans").insert([{name:I.name,description:I.description,active:!0}]);if(D)throw D}},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"})}}),C=yt({mutationFn:async I=>{if(I.id){const{error:D}=await U.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(D)throw D}else{const{error:D}=await U.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(D)throw D}},onSuccess:()=>{i.invalidateQueries({queryKey:["plan-items",u]}),a({title:"Item saved"})}}),A=yt({mutationFn:async I=>{const{error:D}=await U.from("touchpoint_plan_items").delete().eq("id",I);if(D)throw D},onSuccess:()=>{i.invalidateQueries({queryKey:["plan-items",u]})}}),T=yt({mutationFn:async I=>{const{data:D,error:B}=await U.from("action_scripts").insert([{...I,active:!0}]).select().single();if(B)throw B;return D},onSuccess:async I=>{i.invalidateQueries({queryKey:["admin-action-scripts"]}),x&&await C.mutateAsync({id:x.itemId,plan_id:u,month_number:x.month,action_type_id:x.actionTypeId,default_script_id:I.id}),p(!1),g(null),a({title:"Script created and assigned"})},onError:I=>{a({title:"Error",description:I.message,variant:"destructive"})}}),P=(I,D,B)=>{g({month:I,actionTypeId:D,itemId:B}),p(!0)},M=I=>n.find(D=>D.id===I);return e.jsxs("div",{className:"space-y-6",children:[e.jsxs(_e,{children:[e.jsxs(Bt,{className:"flex flex-row items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(Ut,{children:"Touchpoint Plans"}),e.jsx(vr,{children:"Create annual touchpoint plans that agents can apply to their contacts"})]}),e.jsxs($,{onClick:()=>{o(null),d(!0)},children:[e.jsx(sn,{className:"h-4 w-4 mr-2"}),"Add Plan"]})]}),e.jsx(Oe,{children:r?e.jsx("div",{className:"flex justify-center py-8",children:e.jsx(Ht,{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(_e,{className:`cursor-pointer transition-colors ${u===I.id?"border-primary":""}`,onClick:()=>h(I.id),children:[e.jsx(Bt,{className:"pb-2",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(Ut,{className:"text-base",children:I.name}),e.jsx($,{variant:"ghost",size:"icon",onClick:D=>{D.stopPropagation(),o(I),d(!0)},children:e.jsx(Ya,{className:"h-4 w-4"})})]})}),e.jsxs(Oe,{children:[e.jsx("p",{className:"text-sm text-muted-foreground line-clamp-2",children:I.description}),e.jsx($e,{variant:I.active?"default":"secondary",className:"mt-2",children:I.active?"Active":"Inactive"})]})]},I.id))})})]}),u&&e.jsxs(_e,{children:[e.jsxs(Bt,{children:[e.jsx(Ut,{children:"Plan Schedule"}),e.jsx(vr,{children:"Configure the monthly touchpoint schedule. Select an action type for each month, then assign or create a script."})]}),e.jsx(Oe,{children:e.jsx("div",{className:"grid gap-3",children:Array.from({length:12},(I,D)=>D+1).map(I=>{const D=v==null?void 0:v.find(W=>W.month_number===I),B=D!=null&&D.default_script_id?M(D.default_script_id):null,q=n.filter(W=>W.action_type_id===(D==null?void 0:D.action_type_id)&&W.active);return e.jsxs("div",{className:"p-4 border rounded-lg space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsxs("div",{className:"w-20 font-medium text-sm",children:["Month ",I]}),e.jsxs(vs,{value:(D==null?void 0:D.action_type_id)||"none",onValueChange:W=>{W==="none"&&D?A.mutate(D.id):W!=="none"&&C.mutate({id:D==null?void 0:D.id,plan_id:u,month_number:I,action_type_id:W,default_script_id:null})},children:[e.jsx(gs,{className:"w-40",children:e.jsx(bs,{placeholder:"No action"})}),e.jsxs(ys,{children:[e.jsx(Ye,{value:"none",children:"No action"}),t.filter(W=>W.active).map(W=>e.jsx(Ye,{value:W.id,children:e.jsxs("span",{className:"flex items-center gap-2",children:[W.color&&e.jsx("span",{className:"w-3 h-3 rounded-full",style:{backgroundColor:W.color}}),W.name]})},W.id))]})]}),D&&e.jsxs(e.Fragment,{children:[e.jsxs(vs,{value:D.default_script_id||"none",onValueChange:W=>{b(null),C.mutate({id:D.id,default_script_id:W==="none"?null:W})},children:[e.jsx(gs,{className:"w-56",children:e.jsx(bs,{placeholder:"Select script"})}),e.jsxs(ys,{children:[e.jsx(Ye,{value:"none",children:"No default script"}),q.map(W=>e.jsxs(Ye,{value:W.id,children:[W.title," ",W.tone&&`(${W.tone})`]},W.id))]})]}),e.jsxs($,{variant:"outline",size:"sm",onClick:()=>P(I,D.action_type_id,D.id),children:[e.jsx(sn,{className:"h-3 w-3 mr-1"}),"New Script"]}),B&&e.jsx($,{variant:"ghost",size:"sm",onClick:()=>b((y==null?void 0:y.id)===B.id?null:B),children:(y==null?void 0:y.id)===B.id?"Hide":"Preview"})]})]}),y&&(D==null?void 0:D.default_script_id)===y.id&&e.jsxs("div",{className:"ml-24 p-3 bg-muted rounded-lg text-sm",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx($e,{variant:"outline",children:y.title}),y.tone&&e.jsx($e,{variant:"secondary",children:y.tone})]}),e.jsx("p",{className:"text-muted-foreground whitespace-pre-wrap",children:y.script_body})]})]},I)})})})]}),e.jsx(Os,{open:c,onOpenChange:d,children:e.jsxs(Rs,{children:[e.jsx(Us,{children:e.jsxs(zs,{children:[l?"Edit":"Add"," Touchpoint Plan"]})}),e.jsxs("form",{onSubmit:I=>{I.preventDefault();const D=new FormData(I.currentTarget);N.mutate({id:l==null?void 0:l.id,name:D.get("name"),description:D.get("description"),active:!0})},children:[e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(se,{htmlFor:"name",children:"Name"}),e.jsx(be,{id:"name",name:"name",defaultValue:l==null?void 0:l.name,required:!0})]}),e.jsxs("div",{children:[e.jsx(se,{htmlFor:"description",children:"Description"}),e.jsx(Is,{id:"description",name:"description",defaultValue:(l==null?void 0:l.description)||"",rows:3})]})]}),e.jsxs(kr,{className:"mt-4",children:[e.jsx($,{type:"button",variant:"outline",onClick:()=>d(!1),children:"Cancel"}),e.jsxs($,{type:"submit",disabled:N.isPending,children:[N.isPending&&e.jsx(Ht,{className:"h-4 w-4 mr-2 animate-spin"}),"Save"]})]})]})]})}),e.jsx(Os,{open:m,onOpenChange:p,children:e.jsxs(Rs,{className:"max-w-2xl",children:[e.jsxs(Us,{children:[e.jsx(zs,{children:"Create New Script"}),e.jsxs(Sr,{children:["Create a script for Month ",x==null?void 0:x.month,". Use ","{{FirstName}}",", ","{{LastName}}",", and ","{{AgentName}}"," as placeholders."]})]}),e.jsxs("form",{onSubmit:I=>{I.preventDefault();const D=new FormData(I.currentTarget);T.mutate({title:D.get("title"),action_type_id:x.actionTypeId,tone:D.get("tone"),script_body:D.get("script_body")})},children:[e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx(se,{htmlFor:"script_title",children:"Title"}),e.jsx(be,{id:"script_title",name:"title",placeholder:"e.g., Warm Check-In",required:!0})]}),e.jsxs("div",{children:[e.jsx(se,{htmlFor:"script_tone",children:"Tone"}),e.jsx(be,{id:"script_tone",name:"tone",placeholder:"e.g., Friendly, Professional"})]})]}),e.jsxs("div",{children:[e.jsx(se,{htmlFor:"script_body",children:"Script Body"}),e.jsx(Is,{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(kr,{className:"mt-4",children:[e.jsx($,{type:"button",variant:"outline",onClick:()=>p(!1),children:"Cancel"}),e.jsxs($,{type:"submit",disabled:T.isPending,children:[T.isPending&&e.jsx(Ht,{className:"h-4 w-4 mr-2 animate-spin"}),"Create & Assign"]})]})]})]})})]})}function H1n({flags:s}){const{toast:t}=gi(),n=ts(),r=async(a,i)=>{const{error:l}=await U.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(_e,{children:[e.jsxs(Bt,{children:[e.jsx(Ut,{children:"Feature Flags"}),e.jsx(vr,{children:"Control which features are enabled for members"})]}),e.jsx(Oe,{children:e.jsxs(Va,{children:[e.jsx(Ha,{children:e.jsxs(hn,{children:[e.jsx(Lt,{children:"Flag"}),e.jsx(Lt,{children:"Status"}),e.jsx(Lt,{children:"Notes"}),e.jsx(Lt,{children:"Last Updated"})]})}),e.jsx(Ga,{children:s.map(a=>e.jsxs(hn,{children:[e.jsx(gt,{className:"font-mono text-sm",children:a.key}),e.jsx(gt,{children:e.jsx(Tn,{checked:a.enabled,onCheckedChange:i=>r(a,{enabled:i})})}),e.jsx(gt,{children:e.jsx(be,{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 G1n({items:s,isLoading:t}){const{toast:n}=gi(),r=ts(),[a,i]=j.useState(null),[l,o]=j.useState(!1),c=yt({mutationFn:async h=>{if(h.id){const{error:m}=await U.from("popby_items").update({name:h.name,description:h.description}).eq("id",h.id);if(m)throw m}else{const{error:m}=await U.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 U.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 U.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(_e,{children:[e.jsxs(Bt,{className:"flex flex-row items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(Ut,{children:"Popby Ideas"}),e.jsx(vr,{children:"Manage global popby ideas that all agents can see"})]}),e.jsxs($,{onClick:()=>{i(null),o(!0)},children:[e.jsx(sn,{className:"h-4 w-4 mr-2"}),"Add Popby Idea"]})]}),e.jsx(Oe,{children:t?e.jsx("div",{className:"flex justify-center py-8",children:e.jsx(Ht,{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(Co,{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(Va,{children:[e.jsx(Ha,{children:e.jsxs(hn,{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(Ga,{children:s.map(h=>e.jsxs(hn,{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(Tn,{checked:h.is_active,onCheckedChange:()=>d(h)})}),e.jsx(gt,{children:e.jsxs("div",{className:"flex gap-1",children:[e.jsx($,{variant:"ghost",size:"icon",onClick:()=>{i(h),o(!0)},children:e.jsx(Ya,{className:"h-4 w-4"})}),e.jsx($,{variant:"ghost",size:"icon",onClick:()=>u(h.id),children:e.jsx(Pn,{className:"h-4 w-4 text-destructive"})})]})})]},h.id))})]})}),e.jsx(Os,{open:l,onOpenChange:o,children:e.jsxs(Rs,{children:[e.jsx(Us,{children:e.jsxs(zs,{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(se,{htmlFor:"name",children:"Name"}),e.jsx(be,{id:"name",name:"name",defaultValue:a==null?void 0:a.name,required:!0,placeholder:"e.g., Homemade Cookies"})]}),e.jsxs("div",{children:[e.jsx(se,{htmlFor:"description",children:"Description"}),e.jsx(Is,{id:"description",name:"description",defaultValue:(a==null?void 0:a.description)||"",placeholder:"Brief description of the popby idea..."})]})]}),e.jsxs(kr,{className:"mt-4",children:[e.jsx($,{type:"button",variant:"outline",onClick:()=>o(!1),children:"Cancel"}),e.jsxs($,{type:"submit",disabled:c.isPending,children:[c.isPending&&e.jsx(Ht,{className:"h-4 w-4 mr-2 animate-spin"}),"Save"]})]})]})]})})]})}function W1n(){var p;const{toast:s}=gi(),t=ts(),[n,r]=j.useState(null),[a,i]=j.useState(!1),{data:l,isLoading:o}=ht({queryKey:["admin-video-script-categories"],queryFn:async()=>{const{data:x,error:g}=await U.from("video_script_categories").select("*").order("sort_order");if(g)throw g;return x}}),{data:c,isLoading:d}=ht({queryKey:["admin-video-scripts"],queryFn:async()=>{const{data:x,error:g}=await U.from("video_scripts").select("*, category:video_script_categories(*)").order("title");if(g)throw g;return x}}),u=yt({mutationFn:async x=>{var g,y;if(x.id){const{error:b}=await U.from("video_scripts").update({title:x.title,script_text:x.script_text,category_id:x.category_id,tags:((g=x.tags)==null?void 0:g.split(",").map(v=>v.trim()).filter(Boolean))||[]}).eq("id",x.id);if(b)throw b}else{const{error:b}=await U.from("video_scripts").insert([{title:x.title,script_text:x.script_text,category_id:x.category_id||null,tags:((y=x.tags)==null?void 0:y.split(",").map(v=>v.trim()).filter(Boolean))||[]}]);if(b)throw b}},onSuccess:()=>{t.invalidateQueries({queryKey:["admin-video-scripts"]}),i(!1),r(null),s({title:"Video script saved!"})},onError:x=>s({title:"Error",description:x.message,variant:"destructive"})}),h=async x=>{await U.from("video_scripts").update({is_active:!x.is_active}).eq("id",x.id),t.invalidateQueries({queryKey:["admin-video-scripts"]})},m=async x=>{await Yi("Delete this video script?")&&(await U.from("video_scripts").delete().eq("id",x),t.invalidateQueries({queryKey:["admin-video-scripts"]}),s({title:"Script deleted"}))};return e.jsxs(_e,{children:[e.jsxs(Bt,{className:"flex flex-row items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(Ut,{children:"Video Scripts"}),e.jsx(vr,{children:"Manage teleprompter scripts for Quick Video Touch"})]}),e.jsxs($,{onClick:()=>{r(null),i(!0)},children:[e.jsx(sn,{className:"h-4 w-4 mr-2"}),"Add Script"]})]}),e.jsx(Oe,{children:d?e.jsx("div",{className:"flex justify-center py-8",children:e.jsx(Ht,{className:"h-8 w-8 animate-spin text-muted-foreground"})}):e.jsxs(Va,{children:[e.jsx(Ha,{children:e.jsxs(hn,{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(Ga,{children:c==null?void 0:c.map(x=>{var g;return e.jsxs(hn,{children:[e.jsx(gt,{className:"font-medium",children:x.title}),e.jsx(gt,{className:"text-muted-foreground",children:((g=x.category)==null?void 0:g.name)||"Uncategorized"}),e.jsx(gt,{children:e.jsx(Tn,{checked:x.is_active,onCheckedChange:()=>h(x)})}),e.jsxs(gt,{className:"flex gap-1",children:[e.jsx($,{variant:"ghost",size:"icon",onClick:()=>{r(x),i(!0)},children:e.jsx(Ya,{className:"h-4 w-4"})}),e.jsx($,{variant:"ghost",size:"icon",onClick:()=>m(x.id),children:e.jsx(Pn,{className:"h-4 w-4"})})]})]},x.id)})})]})}),e.jsx(Os,{open:a,onOpenChange:i,children:e.jsxs(Rs,{className:"max-w-2xl",children:[e.jsx(Us,{children:e.jsxs(zs,{children:[n?"Edit":"Add"," Video Script"]})}),e.jsxs("form",{onSubmit:x=>{x.preventDefault();const g=new FormData(x.currentTarget);u.mutate({id:n==null?void 0:n.id,title:g.get("title"),script_text:g.get("script_text"),category_id:g.get("category_id")||null,tags:g.get("tags")})},children:[e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(se,{htmlFor:"title",children:"Title"}),e.jsx(be,{id:"title",name:"title",defaultValue:n==null?void 0:n.title,required:!0})]}),e.jsxs("div",{children:[e.jsx(se,{htmlFor:"category_id",children:"Category"}),e.jsxs(vs,{name:"category_id",defaultValue:(n==null?void 0:n.category_id)||"",children:[e.jsx(gs,{children:e.jsx(bs,{placeholder:"Select category"})}),e.jsx(ys,{children:l==null?void 0:l.map(x=>e.jsx(Ye,{value:x.id,children:x.name},x.id))})]})]}),e.jsxs("div",{children:[e.jsx(se,{htmlFor:"script_text",children:"Script Text"}),e.jsx(Is,{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(se,{htmlFor:"tags",children:"Tags (comma-separated)"}),e.jsx(be,{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(kr,{className:"mt-4",children:[e.jsx($,{type:"button",variant:"outline",onClick:()=>i(!1),children:"Cancel"}),e.jsxs($,{type:"submit",disabled:u.isPending,children:[u.isPending&&e.jsx(Ht,{className:"h-4 w-4 mr-2 animate-spin"}),"Save"]})]})]})]})})]})}function K1n(){const{toast:s}=gi(),[t,n]=j.useState(""),[r,a]=j.useState(!0),[i,l]=j.useState(!1);j.useEffect(()=>{(async()=>{a(!0);try{const{data:d}=await U.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 U.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(_e,{children:e.jsx(Oe,{className:"flex justify-center py-8",children:e.jsx(Ht,{className:"h-8 w-8 animate-spin text-muted-foreground"})})}):e.jsx("div",{className:"space-y-6",children:e.jsxs(_e,{children:[e.jsxs(Bt,{children:[e.jsxs(Ut,{className:"flex items-center gap-2",children:[e.jsx(ai,{className:"h-5 w-5"}),"Popby Map Settings"]}),e.jsx(vr,{children:"Configure the map feature for popbys"})]}),e.jsxs(Oe,{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"mapbox-token",children:"Mapbox Public Token"}),e.jsx(be,{id:"mapbox-token",placeholder:"pk.eyJ1I...",value:t,onChange:c=>n(c.target.value)}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Get your token at"," ",e.jsx("a",{href:"https://mapbox.com/",target:"_blank",rel:"noopener noreferrer",className:"text-primary hover:underline",children:"mapbox.com"}),". This token will be used by all agents for the popby map feature."]})]}),e.jsxs($,{onClick:o,disabled:i,children:[i&&e.jsx(Ht,{className:"h-4 w-4 mr-2 animate-spin"}),"Save Token"]}),t&&e.jsx($e,{variant:"secondary",className:"ml-2",children:"Token configured"})]})]})})}const Y1n=()=>{const[s,t]=j.useState(""),[n,r]=j.useState("grid"),a=Vn(),{data:i=[],isLoading:l}=ht({queryKey:["additional-services"],queryFn:async()=>{const{data:c,error:d}=await U.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(Ks,{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(Vr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(be,{placeholder:"Search services...",value:s,onChange:c=>t(c.target.value),className:"pl-9"})]}),e.jsxs("div",{className:"flex gap-2",children:[s&&e.jsx($,{variant:"outline",size:"sm",onClick:()=>t(""),children:"Clear"}),e.jsxs("div",{className:"flex gap-1",children:[e.jsx($,{variant:n==="grid"?"secondary":"outline",size:"icon",onClick:()=>r("grid"),className:"rounded-full",children:e.jsx(_0,{className:"h-4 w-4"})}),e.jsx($,{variant:n==="list"?"secondary":"outline",size:"icon",onClick:()=>r("list"),className:"rounded-full",children:e.jsx(Sg,{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(_e,{children:e.jsxs(Oe,{className:"p-4",children:[e.jsx(on,{className:"aspect-[3/2] w-full rounded-lg mb-4"}),e.jsx(on,{className:"h-5 w-3/4 mb-2"}),e.jsx(on,{className:"h-4 w-full mb-4"})]})},d))}),!l&&o.length===0&&e.jsxs("div",{className:"text-center py-12",children:[e.jsx("div",{className:"text-muted-foreground mb-4",children:s?"No services match your search":"No additional services available yet"}),s&&e.jsx($,{variant:"outline",onClick:()=>t(""),children:"Clear Search"})]}),!l&&o.length>0&&e.jsx("div",{className:n==="grid"?"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6":"space-y-4",children:o.map(c=>e.jsxs(_e,{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(dn,{className:"h-8 w-8"})})}),e.jsxs(Oe,{className:`p-4 flex flex-col ${n==="list"?"flex-1":""}`,children:[e.jsx("h3",{className:"font-semibold text-foreground line-clamp-1 mb-1",children:c.name}),c.description&&e.jsx("p",{className:"text-sm text-muted-foreground line-clamp-2 flex-1",children:EZ(c.description)})]})]},c.id))})]})})},Z1n=()=>{const{serviceId:s}=Vi(),t=Vn(),{data:n,isLoading:r}=ht({queryKey:["additional-service",s],queryFn:async()=>{const{data:a,error:i}=await U.from("additional_services").select("*").eq("id",s).eq("is_published",!0).single();if(i)throw i;return a},enabled:!!s});return r?e.jsx(Ks,{title:"Loading...",children:e.jsxs("div",{className:"max-w-4xl mx-auto space-y-6",children:[e.jsx(on,{className:"h-8 w-48"}),e.jsx(on,{className:"h-64 w-full rounded-lg"}),e.jsx(on,{className:"h-24 w-full"})]})}):n?e.jsx(Ks,{title:n.name,children:e.jsxs("div",{className:"max-w-4xl mx-auto space-y-6",children:[e.jsxs($,{variant:"ghost",onClick:()=>t("/additional-services"),className:"gap-2",children:[e.jsx(ka,{className:"h-4 w-4"}),"Back to Services"]}),e.jsx(_e,{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(dn,{className:"h-16 w-16"})})})}),e.jsx(_e,{children:e.jsxs(Oe,{className:"p-6 space-y-6",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold text-foreground mb-2",children:n.name}),e.jsxs("div",{className:"flex items-center text-sm text-muted-foreground",children:[e.jsx(ia,{className:"h-4 w-4 mr-1"}),"Published ",Hs(new Date(n.publish_date),"MMMM d, yyyy")]})]}),n.description&&e.jsx("div",{className:"prose prose-sm max-w-none text-muted-foreground [&_a]:text-primary [&_a]:underline",dangerouslySetInnerHTML:{__html:n.description}}),e.jsx("div",{className:"pt-4 border-t",children:e.jsxs($,{size:"lg",className:"gap-2",onClick:()=>window.open(n.signup_link_url,"_blank"),children:[e.jsx(Tr,{className:"h-5 w-5"}),"Sign Up Now"]})})]})})]})}):e.jsx(Ks,{title:"Not Found",children:e.jsxs("div",{className:"max-w-4xl mx-auto text-center py-12",children:[e.jsx("h2",{className:"text-2xl font-bold text-foreground mb-4",children:"Service Not Found"}),e.jsx("p",{className:"text-muted-foreground mb-6",children:"The service you're looking for doesn't exist or has been removed."}),e.jsxs($,{onClick:()=>t("/additional-services"),children:[e.jsx(ka,{className:"h-4 w-4 mr-2"}),"Back to Services"]})]})})},kG=[{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 X1n(){const[s,t]=j.useState(kG[0].id),n=kG.find(r=>r.id===s)||kG[0];return e.jsx(Ks,{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(t5,{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(vs,{value:s,onValueChange:t,children:[e.jsx(gs,{className:"w-full",children:e.jsx(bs,{placeholder:"Select a tool"})}),e.jsx(ys,{children:kG.map(r=>e.jsx(Ye,{value:r.id,children:r.name},r.id))})]})}),e.jsx("div",{className:"hidden md:block",children:e.jsx(ua,{value:s,onValueChange:t,className:"w-full",children:e.jsx(ha,{className:"w-full flex-wrap h-auto gap-1 bg-muted p-1",children:kG.map(r=>e.jsx(Qt,{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 Q1n(s,t){const n={};return(s[s.length-1]===""?[...s,""]:s).join((n.padRight?" ":"")+","+(n.padLeft===!1?"":" ")).trim()}const J1n=/^[$_\p{ID_Start}][$_\u{200C}\u{200D}\p{ID_Continue}]*$/u,ebn=/^[$_\p{ID_Start}][-$_\u{200C}\u{200D}\p{ID_Continue}]*$/u,tbn={};function Xft(s,t){return(tbn.jsx?ebn:J1n).test(s)}const sbn=/[ \t\n\f\r]/g;function nbn(s){return typeof s=="object"?s.type==="text"?Qft(s.value):!1:Qft(s)}function Qft(s){return s.replace(sbn,"")===""}class Yee{constructor(t,n,r){this.normal=n,this.property=t,r&&(this.space=r)}}Yee.prototype.normal={};Yee.prototype.property={};Yee.prototype.space=void 0;function UFt(s,t){const n={},r={};for(const a of s)Object.assign(n,a.property),Object.assign(r,a.normal);return new Yee(n,r,t)}function Wze(s){return s.toLowerCase()}class Kb{constructor(t,n){this.attribute=n,this.property=t}}Kb.prototype.attribute="";Kb.prototype.booleanish=!1;Kb.prototype.boolean=!1;Kb.prototype.commaOrSpaceSeparated=!1;Kb.prototype.commaSeparated=!1;Kb.prototype.defined=!1;Kb.prototype.mustUseProperty=!1;Kb.prototype.number=!1;Kb.prototype.overloadedBoolean=!1;Kb.prototype.property="";Kb.prototype.spaceSeparated=!1;Kb.prototype.space=void 0;let rbn=0;const Fl=uF(),Nx=uF(),Kze=uF(),qa=uF(),Nh=uF(),UR=uF(),__=uF();function uF(){return 2**++rbn}const Yze=Object.freeze(Object.defineProperty({__proto__:null,boolean:Fl,booleanish:Nx,commaOrSpaceSeparated:__,commaSeparated:UR,number:qa,overloadedBoolean:Kze,spaceSeparated:Nh},Symbol.toStringTag,{value:"Module"})),l8e=Object.keys(Yze);class pYe extends Kb{constructor(t,n,r,a){let i=-1;if(super(t,n),Jft(this,"space",a),typeof r=="number")for(;++i4&&n.slice(0,4)==="data"&&cbn.test(t)){if(t.charAt(4)==="-"){const i=t.slice(5).replace(ext,hbn);r="data"+i.charAt(0).toUpperCase()+i.slice(1)}else{const i=t.slice(4);if(!ext.test(i)){let l=i.replace(lbn,ubn);l.charAt(0)!=="-"&&(l="-"+l),t="data"+l}}a=pYe}return new a(r,t)}function ubn(s){return"-"+s.toLowerCase()}function hbn(s){return s.charAt(1).toUpperCase()}const mbn=UFt([qFt,abn,GFt,WFt,KFt],"html"),fYe=UFt([qFt,ibn,GFt,WFt,KFt],"svg");function pbn(s){return s.join(" ").trim()}var xYe={},txt=/\/\*[^*]*\*+([^/*][^*]*\*+)*\//g,fbn=/\n/g,xbn=/^\s*/,gbn=/^(\*?[-#/*\\\w]+(\[[0-9a-z_-]+\])?)\s*/,ybn=/^:\s*/,vbn=/^((?:'(?:\\'|.)*?'|"(?:\\"|.)*?"|\([^)]*?\)|[^};])+)/,bbn=/^[;\s]*/,_bn=/^\s+|\s+$/g,wbn=` `,sxt="/",nxt="*",w8="",jbn="comment",Nbn="declaration";function kbn(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(x){var g=x.match(fbn);g&&(n+=g.length);var y=x.lastIndexOf(wbn);r=~y?x.length-y:r+x.length}function i(){var x={line:n,column:r};return function(g){return g.position=new l(x),d(),g}}function l(x){this.start=x,this.end={line:n,column:r},this.source=t.source}l.prototype.content=s;function o(x){var g=new Error(t.source+":"+n+":"+r+": "+x);if(g.reason=x,g.filename=t.source,g.line=n,g.column=r,g.source=s,!t.silent)throw g}function c(x){var g=x.exec(s);if(g){var y=g[0];return a(y),s=s.slice(y.length),g}}function d(){c(xbn)}function u(x){var g;for(x=x||[];g=h();)g!==!1&&x.push(g);return x}function h(){var x=i();if(!(sxt!=s.charAt(0)||nxt!=s.charAt(1))){for(var g=2;w8!=s.charAt(g)&&(nxt!=s.charAt(g)||sxt!=s.charAt(g+1));)++g;if(g+=2,w8===s.charAt(g-1))return o("End of comment missing");var y=s.slice(2,g-2);return r+=2,a(y),s=s.slice(g),r+=2,x({type:jbn,comment:y})}}function m(){var x=i(),g=c(gbn);if(g){if(h(),!c(ybn))return o("property missing ':'");var y=c(vbn),b=x({type:Nbn,property:rxt(g[0].replace(txt,w8)),value:y?rxt(y[0].replace(txt,w8)):w8});return c(bbn),b}}function p(){var x=[];u(x);for(var g;g=m();)g!==!1&&(x.push(g),u(x));return x}return d(),p()}function rxt(s){return s?s.replace(_bn,w8):w8}var Sbn=kbn,Cbn=Sm&&Sm.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(xYe,"__esModule",{value:!0});xYe.default=Ebn;const Abn=Cbn(Sbn);function Ebn(s,t){let n=null;if(!s||typeof s!="string")return n;const r=(0,Abn.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 zEe={};Object.defineProperty(zEe,"__esModule",{value:!0});zEe.camelCase=void 0;var Tbn=/^--[a-zA-Z0-9_-]+$/,Mbn=/-([a-z])/g,Lbn=/^[^-]+$/,Pbn=/^-(webkit|moz|ms|o|khtml)-/,Ibn=/^-(ms)-/,Dbn=function(s){return!s||Lbn.test(s)||Tbn.test(s)},Rbn=function(s,t){return t.toUpperCase()},axt=function(s,t){return"".concat(t,"-")},Obn=function(s,t){return t===void 0&&(t={}),Dbn(s)?s:(s=s.toLowerCase(),t.reactCompat?s=s.replace(Ibn,axt):s=s.replace(Pbn,axt),s.replace(Mbn,Rbn))};zEe.camelCase=Obn;var Fbn=Sm&&Sm.__importDefault||function(s){return s&&s.__esModule?s:{default:s}},zbn=Fbn(xYe),Bbn=zEe;function Zze(s,t){var n={};return!s||typeof s!="string"||(0,zbn.default)(s,function(r,a){r&&a&&(n[(0,Bbn.camelCase)(r,t)]=a)}),n}Zze.default=Zze;var $bn=Zze;const Ubn=Uc($bn),YFt=ZFt("end"),gYe=ZFt("start");function ZFt(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 qbn(s){const t=gYe(s),n=YFt(s);if(t&&n)return{start:t,end:n}}function WY(s){return!s||typeof s!="object"?"":"position"in s||"type"in s?ixt(s.position):"start"in s||"end"in s?ixt(s):"line"in s||"column"in s?Xze(s):""}function Xze(s){return oxt(s&&s.line)+":"+oxt(s&&s.column)}function ixt(s){return Xze(s&&s.start)+"-"+Xze(s&&s.end)}function oxt(s){return s&&typeof s=="number"?s:1}class _v 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=WY(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}}_v.prototype.file="";_v.prototype.name="";_v.prototype.reason="";_v.prototype.message="";_v.prototype.stack="";_v.prototype.column=void 0;_v.prototype.line=void 0;_v.prototype.ancestors=void 0;_v.prototype.cause=void 0;_v.prototype.fatal=void 0;_v.prototype.place=void 0;_v.prototype.ruleId=void 0;_v.prototype.source=void 0;const yYe={}.hasOwnProperty,Vbn=new Map,Hbn=/[A-Z]/g,Gbn=new Set(["table","tbody","thead","tfoot","tr"]),Wbn=new Set(["td","th"]),XFt="https://github.com/syntax-tree/hast-util-to-jsx-runtime";function Kbn(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=s_n(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=t_n(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"?fYe:mbn,stylePropertyNameCase:t.stylePropertyNameCase||"dom",tableCellAlignToStyle:t.tableCellAlignToStyle!==!1},i=QFt(a,s,void 0);return i&&typeof i!="string"?i:a.create(s,a.Fragment,{children:i||void 0},void 0)}function QFt(s,t,n){if(t.type==="element")return Ybn(s,t,n);if(t.type==="mdxFlowExpression"||t.type==="mdxTextExpression")return Zbn(s,t);if(t.type==="mdxJsxFlowElement"||t.type==="mdxJsxTextElement")return Qbn(s,t,n);if(t.type==="mdxjsEsm")return Xbn(s,t);if(t.type==="root")return Jbn(s,t,n);if(t.type==="text")return e_n(s,t)}function Ybn(s,t,n){const r=s.schema;let a=r;t.tagName.toLowerCase()==="svg"&&r.space==="html"&&(a=fYe,s.schema=a),s.ancestors.push(t);const i=e7t(s,t.tagName,!1),l=n_n(s,t);let o=bYe(s,t);return Gbn.has(t.tagName)&&(o=o.filter(function(c){return typeof c=="string"?!nbn(c):!0})),JFt(s,l,i,t),vYe(l,o),s.ancestors.pop(),s.schema=r,s.create(t,i,l,n)}function Zbn(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)}XX(s,t.position)}function Xbn(s,t){if(t.data&&t.data.estree&&s.evaluater)return s.evaluater.evaluateProgram(t.data.estree);XX(s,t.position)}function Qbn(s,t,n){const r=s.schema;let a=r;t.name==="svg"&&r.space==="html"&&(a=fYe,s.schema=a),s.ancestors.push(t);const i=t.name===null?s.Fragment:e7t(s,t.name,!0),l=r_n(s,t),o=bYe(s,t);return JFt(s,l,i,t),vYe(l,o),s.ancestors.pop(),s.schema=r,s.create(t,i,l,n)}function Jbn(s,t,n){const r={};return vYe(r,bYe(s,t)),s.create(t,s.Fragment,r,n)}function e_n(s,t){return t.value}function JFt(s,t,n,r){typeof n!="string"&&n!==s.Fragment&&s.passNode&&(t.node=r)}function vYe(s,t){if(t.length>0){const n=t.length>1?t:t[0];n&&(s.children=n)}}function t_n(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 s_n(s,t){return n;function n(r,a,i,l){const o=Array.isArray(i.children),c=gYe(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 n_n(s,t){const n={};let r,a;for(a in t.properties)if(a!=="children"&&yYe.call(t.properties,a)){const i=a_n(s,a,t.properties[a]);if(i){const[l,o]=i;s.tableCellAlignToStyle&&l==="align"&&typeof o=="string"&&Wbn.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 r_n(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 XX(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 XX(s,t.position);else i=r.value===null?!0:r.value;n[a]=i}return n}function bYe(s,t){const n=[];let r=-1;const a=s.passKeys?new Map:Vbn;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?(S5(s,s.length,0,t),s):t}const dxt={}.hasOwnProperty;function m_n(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 uB(s){return s.replace(/[\t\n\r ]+/g," ").replace(/^ | $/g,"").toLowerCase().toUpperCase()}const OS=Y6(/[A-Za-z]/),X_=Y6(/[\dA-Za-z]/),x_n=Y6(/[#-'*+\--9=?A-Z^-~]/);function Qze(s){return s!==null&&(s<32||s===127)}const Jze=Y6(/\d/),g_n=Y6(/[\dA-Fa-f]/),y_n=Y6(/[!-/:-@[-`{-~]/);function Ml(s){return s!==null&&s<-2}function zb(s){return s!==null&&(s<0||s===32)}function du(s){return s===-2||s===-1||s===32}const v_n=Y6(new RegExp("\\p{P}|\\p{S}","u")),b_n=Y6(/\s/);function Y6(s){return t;function t(n){return n!==null&&n>-1&&s.test(String.fromCharCode(n))}}function cV(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 Zh(s,t,n,r){const a=r?r-1:Number.POSITIVE_INFINITY;let i=0;return l;function l(c){return du(c)?(s.enter(n),o(c)):t(c)}function o(c){return du(c)&&i++l))return;const P=t.events.length;let M=P,I,D;for(;M--;)if(t.events[M][0]==="exit"&&t.events[M][1].type==="chunkFlow"){if(I){D=t.events[M][1].end;break}I=!0}for(b(r),T=P;TN;){const A=n[C];t.containerState=A[1],A[0].exit.call(t,s)}n.length=N}function v(){a.write([null]),i=void 0,a=void 0,t.containerState._closeFlow=void 0}}function k_n(s,t,n){return Zh(s,s.attempt(this.parser.constructs.document,t,n),"linePrefix",this.parser.constructs.disable.null.includes("codeIndented")?void 0:4)}function hxt(s){if(s===null||zb(s)||b_n(s))return 1;if(v_n(s))return 2}function wYe(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};mxt(h,-c),mxt(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=Sj(d,[["enter",s[r][1],t],["exit",s[r][1],t]])),d=Sj(d,[["enter",a,t],["enter",l,t],["exit",l,t],["enter",i,t]]),d=Sj(d,wYe(t.parser.constructs.insideSpan.null,s.slice(r+1,n),t)),d=Sj(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=Sj(d,[["enter",s[n][1],t],["exit",s[n][1],t]])):u=0,S5(s,r-1,n-r+3,d),n=r+d.length-u-2;break}}for(n=-1;++n0&&du(T)?Zh(s,v,"linePrefix",i+1)(T):v(T)}function v(T){return T===null||Ml(T)?s.check(pxt,g,C)(T):(s.enter("codeFlowValue"),N(T))}function N(T){return T===null||Ml(T)?(s.exit("codeFlowValue"),v(T)):(s.consume(T),N)}function C(T){return s.exit("codeFenced"),t(T)}function A(T,P,M){let I=0;return D;function D(K){return T.enter("lineEnding"),T.consume(K),T.exit("lineEnding"),B}function B(K){return T.enter("codeFencedFence"),du(K)?Zh(T,q,"linePrefix",r.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(K):q(K)}function q(K){return K===o?(T.enter("codeFencedFenceSequence"),W(K)):M(K)}function W(K){return K===o?(I++,T.consume(K),W):I>=l?(T.exit("codeFencedFenceSequence"),du(K)?Zh(T,V,"whitespace")(K):V(K)):M(K)}function V(K){return K===null||Ml(K)?(T.exit("codeFencedFence"),P(K)):M(K)}}}function O_n(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 d8e={name:"codeIndented",tokenize:z_n},F_n={partial:!0,tokenize:B_n};function z_n(s,t,n){const r=this;return a;function a(d){return s.enter("codeIndented"),Zh(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):Ml(d)?s.attempt(F_n,l,c)(d):(s.enter("codeFlowValue"),o(d))}function o(d){return d===null||Ml(d)?(s.exit("codeFlowValue"),l(d)):(s.consume(d),o)}function c(d){return s.exit("codeIndented"),t(d)}}function B_n(s,t,n){const r=this;return a;function a(l){return r.parser.lazy[r.now().line]?n(l):Ml(l)?(s.enter("lineEnding"),s.consume(l),s.exit("lineEnding"),a):Zh(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):Ml(l)?a(l):n(l)}}const $_n={name:"codeText",previous:q_n,resolve:U_n,tokenize:V_n};function U_n(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&&SG(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),SG(this.left,t)}unshift(t){this.setCursor(0),this.right.push(t)}unshiftMany(t){this.setCursor(0),SG(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 o7t(s,t,n,r,a,i,l,o,c){const d=c||Number.POSITIVE_INFINITY;let u=0;return h;function h(b){return b===60?(s.enter(r),s.enter(a),s.enter(i),s.consume(b),s.exit(i),m):b===null||b===32||b===41||Qze(b)?n(b):(s.enter(r),s.enter(l),s.enter(o),s.enter("chunkString",{contentType:"string"}),g(b))}function m(b){return b===62?(s.enter(i),s.consume(b),s.exit(i),s.exit(a),s.exit(r),t):(s.enter(o),s.enter("chunkString",{contentType:"string"}),p(b))}function p(b){return b===62?(s.exit("chunkString"),s.exit(o),m(b)):b===null||b===60||Ml(b)?n(b):(s.consume(b),b===92?x:p)}function x(b){return b===60||b===62||b===92?(s.consume(b),p):p(b)}function g(b){return!u&&(b===null||b===41||zb(b))?(s.exit("chunkString"),s.exit(o),s.exit(l),s.exit(r),t(b)):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):Ml(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||Ml(p)||o++>999?(s.exit("chunkString"),u(p)):(s.consume(p),c||(c=!du(p)),p===92?m:h)}function m(p){return p===91||p===92||p===93?(s.consume(p),o++,h):h(p)}}function c7t(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):Ml(m)?(s.enter("lineEnding"),s.consume(m),s.exit("lineEnding"),Zh(s,d,"linePrefix")):(s.enter("chunkString",{contentType:"string"}),u(m))}function u(m){return m===l||m===null||Ml(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 KY(s,t){let n;return r;function r(a){return Ml(a)?(s.enter("lineEnding"),s.consume(a),s.exit("lineEnding"),n=!0,r):du(a)?Zh(s,r,n?"linePrefix":"lineSuffix")(a):t(a)}}const Q_n={name:"definition",tokenize:ewn},J_n={partial:!0,tokenize:twn};function ewn(s,t,n){const r=this;let a;return i;function i(p){return s.enter("definition"),l(p)}function l(p){return l7t.call(r,s,o,n,"definitionLabel","definitionLabelMarker","definitionLabelString")(p)}function o(p){return a=uB(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 zb(p)?KY(s,d)(p):d(p)}function d(p){return o7t(s,u,n,"definitionDestination","definitionDestinationLiteral","definitionDestinationLiteralMarker","definitionDestinationRaw","definitionDestinationString")(p)}function u(p){return s.attempt(J_n,h,h)(p)}function h(p){return du(p)?Zh(s,m,"whitespace")(p):m(p)}function m(p){return p===null||Ml(p)?(s.exit("definition"),r.parser.defined.push(a),t(p)):n(p)}}function twn(s,t,n){return r;function r(o){return zb(o)?KY(s,a)(o):n(o)}function a(o){return c7t(s,i,n,"definitionTitle","definitionTitleMarker","definitionTitleString")(o)}function i(o){return du(o)?Zh(s,l,"whitespace")(o):l(o)}function l(o){return o===null||Ml(o)?t(o):n(o)}}const swn={name:"hardBreakEscape",tokenize:nwn};function nwn(s,t,n){return r;function r(i){return s.enter("hardBreakEscape"),s.consume(i),a}function a(i){return Ml(i)?(s.exit("hardBreakEscape"),t(i)):n(i)}}const rwn={name:"headingAtx",resolve:awn,tokenize:iwn};function awn(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"},S5(s,r,n-r+1,[["enter",a,t],["enter",i,t],["exit",i,t],["exit",a,t]])),s}function iwn(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||zb(u)?(s.exit("atxHeadingSequence"),o(u)):n(u)}function o(u){return u===35?(s.enter("atxHeadingSequence"),c(u)):u===null||Ml(u)?(s.exit("atxHeading"),t(u)):du(u)?Zh(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||zb(u)?(s.exit("atxHeadingText"),o(u)):(s.consume(u),d)}}const own=["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"],xxt=["pre","script","style","textarea"],lwn={concrete:!0,name:"htmlFlow",resolveTo:uwn,tokenize:hwn},cwn={partial:!0,tokenize:pwn},dwn={partial:!0,tokenize:mwn};function uwn(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 hwn(s,t,n){const r=this;let a,i,l,o,c;return d;function d(he){return u(he)}function u(he){return s.enter("htmlFlow"),s.enter("htmlFlowData"),s.consume(he),h}function h(he){return he===33?(s.consume(he),m):he===47?(s.consume(he),i=!0,g):he===63?(s.consume(he),a=3,r.interrupt?t:ne):OS(he)?(s.consume(he),l=String.fromCharCode(he),y):n(he)}function m(he){return he===45?(s.consume(he),a=2,p):he===91?(s.consume(he),a=5,o=0,x):OS(he)?(s.consume(he),a=4,r.interrupt?t:ne):n(he)}function p(he){return he===45?(s.consume(he),r.interrupt?t:ne):n(he)}function x(he){const ve="CDATA[";return he===ve.charCodeAt(o++)?(s.consume(he),o===ve.length?r.interrupt?t:q:x):n(he)}function g(he){return OS(he)?(s.consume(he),l=String.fromCharCode(he),y):n(he)}function y(he){if(he===null||he===47||he===62||zb(he)){const ve=he===47,ge=l.toLowerCase();return!ve&&!i&&xxt.includes(ge)?(a=1,r.interrupt?t(he):q(he)):own.includes(l.toLowerCase())?(a=6,ve?(s.consume(he),b):r.interrupt?t(he):q(he)):(a=7,r.interrupt&&!r.parser.lazy[r.now().line]?n(he):i?v(he):N(he))}return he===45||X_(he)?(s.consume(he),l+=String.fromCharCode(he),y):n(he)}function b(he){return he===62?(s.consume(he),r.interrupt?t:q):n(he)}function v(he){return du(he)?(s.consume(he),v):D(he)}function N(he){return he===47?(s.consume(he),D):he===58||he===95||OS(he)?(s.consume(he),C):du(he)?(s.consume(he),N):D(he)}function C(he){return he===45||he===46||he===58||he===95||X_(he)?(s.consume(he),C):A(he)}function A(he){return he===61?(s.consume(he),T):du(he)?(s.consume(he),A):N(he)}function T(he){return he===null||he===60||he===61||he===62||he===96?n(he):he===34||he===39?(s.consume(he),c=he,P):du(he)?(s.consume(he),T):M(he)}function P(he){return he===c?(s.consume(he),c=null,I):he===null||Ml(he)?n(he):(s.consume(he),P)}function M(he){return he===null||he===34||he===39||he===47||he===60||he===61||he===62||he===96||zb(he)?A(he):(s.consume(he),M)}function I(he){return he===47||he===62||du(he)?N(he):n(he)}function D(he){return he===62?(s.consume(he),B):n(he)}function B(he){return he===null||Ml(he)?q(he):du(he)?(s.consume(he),B):n(he)}function q(he){return he===45&&a===2?(s.consume(he),Q):he===60&&a===1?(s.consume(he),J):he===62&&a===4?(s.consume(he),ee):he===63&&a===3?(s.consume(he),ne):he===93&&a===5?(s.consume(he),ue):Ml(he)&&(a===6||a===7)?(s.exit("htmlFlowData"),s.check(cwn,le,W)(he)):he===null||Ml(he)?(s.exit("htmlFlowData"),W(he)):(s.consume(he),q)}function W(he){return s.check(dwn,V,le)(he)}function V(he){return s.enter("lineEnding"),s.consume(he),s.exit("lineEnding"),K}function K(he){return he===null||Ml(he)?W(he):(s.enter("htmlFlowData"),q(he))}function Q(he){return he===45?(s.consume(he),ne):q(he)}function J(he){return he===47?(s.consume(he),l="",ce):q(he)}function ce(he){if(he===62){const ve=l.toLowerCase();return xxt.includes(ve)?(s.consume(he),ee):q(he)}return OS(he)&&l.length<8?(s.consume(he),l+=String.fromCharCode(he),ce):q(he)}function ue(he){return he===93?(s.consume(he),ne):q(he)}function ne(he){return he===62?(s.consume(he),ee):he===45&&a===2?(s.consume(he),ne):q(he)}function ee(he){return he===null||Ml(he)?(s.exit("htmlFlowData"),le(he)):(s.consume(he),ee)}function le(he){return s.exit("htmlFlow"),t(he)}}function mwn(s,t,n){const r=this;return a;function a(l){return Ml(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 pwn(s,t,n){return r;function r(a){return s.enter("lineEnding"),s.consume(a),s.exit("lineEnding"),s.attempt(BEe,t,n)}}const fwn={name:"htmlText",tokenize:xwn};function xwn(s,t,n){const r=this;let a,i,l;return o;function o(ne){return s.enter("htmlText"),s.enter("htmlTextData"),s.consume(ne),c}function c(ne){return ne===33?(s.consume(ne),d):ne===47?(s.consume(ne),A):ne===63?(s.consume(ne),N):OS(ne)?(s.consume(ne),M):n(ne)}function d(ne){return ne===45?(s.consume(ne),u):ne===91?(s.consume(ne),i=0,x):OS(ne)?(s.consume(ne),v):n(ne)}function u(ne){return ne===45?(s.consume(ne),p):n(ne)}function h(ne){return ne===null?n(ne):ne===45?(s.consume(ne),m):Ml(ne)?(l=h,J(ne)):(s.consume(ne),h)}function m(ne){return ne===45?(s.consume(ne),p):h(ne)}function p(ne){return ne===62?Q(ne):ne===45?m(ne):h(ne)}function x(ne){const ee="CDATA[";return ne===ee.charCodeAt(i++)?(s.consume(ne),i===ee.length?g:x):n(ne)}function g(ne){return ne===null?n(ne):ne===93?(s.consume(ne),y):Ml(ne)?(l=g,J(ne)):(s.consume(ne),g)}function y(ne){return ne===93?(s.consume(ne),b):g(ne)}function b(ne){return ne===62?Q(ne):ne===93?(s.consume(ne),b):g(ne)}function v(ne){return ne===null||ne===62?Q(ne):Ml(ne)?(l=v,J(ne)):(s.consume(ne),v)}function N(ne){return ne===null?n(ne):ne===63?(s.consume(ne),C):Ml(ne)?(l=N,J(ne)):(s.consume(ne),N)}function C(ne){return ne===62?Q(ne):N(ne)}function A(ne){return OS(ne)?(s.consume(ne),T):n(ne)}function T(ne){return ne===45||X_(ne)?(s.consume(ne),T):P(ne)}function P(ne){return Ml(ne)?(l=P,J(ne)):du(ne)?(s.consume(ne),P):Q(ne)}function M(ne){return ne===45||X_(ne)?(s.consume(ne),M):ne===47||ne===62||zb(ne)?I(ne):n(ne)}function I(ne){return ne===47?(s.consume(ne),Q):ne===58||ne===95||OS(ne)?(s.consume(ne),D):Ml(ne)?(l=I,J(ne)):du(ne)?(s.consume(ne),I):Q(ne)}function D(ne){return ne===45||ne===46||ne===58||ne===95||X_(ne)?(s.consume(ne),D):B(ne)}function B(ne){return ne===61?(s.consume(ne),q):Ml(ne)?(l=B,J(ne)):du(ne)?(s.consume(ne),B):I(ne)}function q(ne){return ne===null||ne===60||ne===61||ne===62||ne===96?n(ne):ne===34||ne===39?(s.consume(ne),a=ne,W):Ml(ne)?(l=q,J(ne)):du(ne)?(s.consume(ne),q):(s.consume(ne),V)}function W(ne){return ne===a?(s.consume(ne),a=void 0,K):ne===null?n(ne):Ml(ne)?(l=W,J(ne)):(s.consume(ne),W)}function V(ne){return ne===null||ne===34||ne===39||ne===60||ne===61||ne===96?n(ne):ne===47||ne===62||zb(ne)?I(ne):(s.consume(ne),V)}function K(ne){return ne===47||ne===62||zb(ne)?I(ne):n(ne)}function Q(ne){return ne===62?(s.consume(ne),s.exit("htmlTextData"),s.exit("htmlText"),t):n(ne)}function J(ne){return s.exit("htmlTextData"),s.enter("lineEnding"),s.consume(ne),s.exit("lineEnding"),ce}function ce(ne){return du(ne)?Zh(s,ue,"linePrefix",r.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(ne):ue(ne)}function ue(ne){return s.enter("htmlTextData"),l(ne)}}const jYe={name:"labelEnd",resolveAll:bwn,resolveTo:_wn,tokenize:wwn},gwn={tokenize:jwn},ywn={tokenize:Nwn},vwn={tokenize:kwn};function bwn(s){let t=-1;const n=[];for(;++t=3&&(d===null||Ml(d))?(s.exit("thematicBreak"),t(d)):n(d)}function c(d){return d===a?(s.consume(d),r++,c):(s.exit("thematicBreakSequence"),du(d)?Zh(s,o,"whitespace")(d):o(d))}}const ab={continuation:{tokenize:Dwn},exit:Own,name:"list",tokenize:Iwn},Lwn={partial:!0,tokenize:Fwn},Pwn={partial:!0,tokenize:Rwn};function Iwn(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 x=r.containerState.type||(p===42||p===43||p===45?"listUnordered":"listOrdered");if(x==="listUnordered"?!r.containerState.marker||p===r.containerState.marker:Jze(p)){if(r.containerState.type||(r.containerState.type=x,s.enter(x,{_container:!0})),x==="listUnordered")return s.enter("listItemPrefix"),p===42||p===45?s.check(q2e,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 Jze(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(BEe,r.interrupt?n:u,s.attempt(Lwn,m,h))}function u(p){return r.containerState.initialBlankLine=!0,i++,m(p)}function h(p){return du(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 Dwn(s,t,n){const r=this;return r.containerState._closeFlow=void 0,s.check(BEe,a,i);function a(o){return r.containerState.furtherBlankLines=r.containerState.furtherBlankLines||r.containerState.initialBlankLine,Zh(s,t,"listItemIndent",r.containerState.size+1)(o)}function i(o){return r.containerState.furtherBlankLines||!du(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(Pwn,t,l)(o))}function l(o){return r.containerState._closeFlow=!0,r.interrupt=void 0,Zh(s,s.attempt(ab,t,n),"linePrefix",r.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(o)}}function Rwn(s,t,n){const r=this;return Zh(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 Own(s){s.exit(this.containerState.type)}function Fwn(s,t,n){const r=this;return Zh(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!du(i)&&l&&l[1].type==="listItemPrefixWhitespace"?t(i):n(i)}}const gxt={name:"setextUnderline",resolveTo:zwn,tokenize:Bwn};function zwn(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 Bwn(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"),du(d)?Zh(s,c,"lineSuffix")(d):c(d))}function c(d){return d===null||Ml(d)?(s.exit("setextHeadingLine"),t(d)):n(d)}}const $wn={tokenize:Uwn};function Uwn(s){const t=this,n=s.attempt(BEe,r,s.attempt(this.parser.constructs.flowInitial,a,Zh(s,s.attempt(this.parser.constructs.flow,a,s.attempt(W_n,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 qwn={resolveAll:u7t()},Vwn=d7t("string"),Hwn=d7t("text");function d7t(s){return{resolveAll:u7t(s==="text"?Gwn: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 ajn(s,t){let n=-1;const r=[];let a;for(;++n0){const js=Mt.tokenStack[Mt.tokenStack.length-1];(js[1]||vxt).call(Mt,void 0,js[0])}for(lt.position={start:oA(ft.length>0?ft[0][1].start:{line:1,column:1,offset:0}),end:oA(ft.length>0?ft[ft.length-2][1].end:{line:1,column:1,offset:0})},Ts=-1;++Ts0&&(r.className=["language-"+a[0]]);let i={type:"element",tagName:"code",properties:r,children:[{type:"text",value:n}]};return t.meta&&(i.data={meta:t.meta}),s.patch(t,i),i=s.applyData(t,i),i={type:"element",tagName:"pre",properties:{},children:[i]},s.patch(t,i),i}function vjn(s,t){const n={type:"element",tagName:"del",properties:{},children:s.all(t)};return s.patch(t,n),s.applyData(t,n)}function bjn(s,t){const n={type:"element",tagName:"em",properties:{},children:s.all(t)};return s.patch(t,n),s.applyData(t,n)}function _jn(s,t){const n=typeof s.options.clobberPrefix=="string"?s.options.clobberPrefix:"user-content-",r=String(t.identifier).toUpperCase(),a=cV(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 wjn(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 jjn(s,t){if(s.options.allowDangerousHtml){const n={type:"raw",value:t.value};return s.patch(t,n),s.applyData(t,n)}}function p7t(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 Njn(s,t){const n=String(t.identifier).toUpperCase(),r=s.definitionById.get(n);if(!r)return p7t(s,t);const a={src:cV(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 kjn(s,t){const n={src:cV(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 Sjn(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 Cjn(s,t){const n=String(t.identifier).toUpperCase(),r=s.definitionById.get(n);if(!r)return p7t(s,t);const a={href:cV(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 Ajn(s,t){const n={href:cV(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 Ejn(s,t,n){const r=s.all(t),a=n?Tjn(n):f7t(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 Mjn(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=gYe(t.children[1]),c=YFt(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 Rjn(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(wxt(t.slice(a),a>0,!1)),i.join("")}function wxt(s,t,n){let r=0,a=s.length;if(t){let i=s.codePointAt(r);for(;i===bxt||i===_xt;)r++,i=s.codePointAt(r)}if(n){let i=s.codePointAt(a-1);for(;i===bxt||i===_xt;)a--,i=s.codePointAt(a-1)}return a>r?s.slice(r,a):""}function zjn(s,t){const n={type:"text",value:Fjn(String(t.value))};return s.patch(t,n),s.applyData(t,n)}function Bjn(s,t){const n={type:"element",tagName:"hr",properties:{},children:[]};return s.patch(t,n),s.applyData(t,n)}const $jn={blockquote:xjn,break:gjn,code:yjn,delete:vjn,emphasis:bjn,footnoteReference:_jn,heading:wjn,html:jjn,imageReference:Njn,image:kjn,inlineCode:Sjn,linkReference:Cjn,link:Ajn,listItem:Ejn,list:Mjn,paragraph:Ljn,root:Pjn,strong:Ijn,table:Djn,tableCell:Ojn,tableRow:Rjn,text:zjn,thematicBreak:Bjn,toml:Dre,yaml:Dre,definition:Dre,footnoteDefinition:Dre};function Dre(){}const x7t=-1,$Ee=0,YY=1,d4e=2,NYe=3,kYe=4,SYe=5,CYe=6,g7t=7,y7t=8,v7t=typeof self=="object"?self:globalThis,jxt=(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 v7t[s](t)},Ujn=(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 $Ee:case x7t:return n(l,a);case YY:{const o=n([],a);for(const c of l)o.push(r(c));return o}case d4e:{const o=n({},a);for(const[c,d]of l)o[r(c)]=r(d);return o}case NYe:return n(new Date(l),a);case kYe:{const{source:o,flags:c}=l;return n(new RegExp(o,c),a)}case SYe:{const o=n(new Map,a);for(const[c,d]of l)o.set(r(c),r(d));return o}case CYe:{const o=n(new Set,a);for(const c of l)o.add(r(c));return o}case g7t:{const{name:o,message:c}=l;return n(typeof v7t[o]=="function"?jxt(o,c):new Error(c),a)}case y7t: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(jxt(i,l),a)};return r},Nxt=s=>Ujn(new Map,s)(0),c8="",{toString:qjn}={},{keys:Vjn}=Object,CG=s=>{const t=typeof s;if(t!=="object"||!s)return[$Ee,t];const n=qjn.call(s).slice(8,-1);switch(n){case"Array":return[YY,c8];case"Object":return[d4e,c8];case"Date":return[NYe,c8];case"RegExp":return[kYe,c8];case"Map":return[SYe,c8];case"Set":return[CYe,c8];case"DataView":return[YY,n]}return n.includes("Array")?[YY,n]:s instanceof Error?[g7t,s.name||"Error"]:[d4e,n]},Rre=([s,t])=>s===$Ee&&(t==="function"||t==="symbol"),Hjn=(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]=CG(l);switch(o){case $Ee:{let u=l;switch(c){case"bigint":o=y7t,u=l.toString();break;case"function":case"symbol":if(s)throw new TypeError("unable to serialize "+c);u=null;break;case"undefined":return a([x7t],l)}return a([o,u],l)}case YY:{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 d4e:{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 Vjn(l))(s||!Rre(CG(l[m])))&&u.push([i(m),i(l[m])]);return h}case NYe:return a([o,isNaN(l.getTime())?c8:l.toISOString()],l);case kYe:{const{source:u,flags:h}=l;return a([o,{source:u,flags:h}],l)}case SYe:{const u=[],h=a([o,u],l);for(const[m,p]of l)(s||!(Rre(CG(m))||Rre(CG(p))))&&u.push([i(m),i(p)]);return h}case CYe:{const u=[],h=a([o,u],l);for(const m of l)(s||!Rre(CG(m)))&&u.push(i(m));return h}}const{message:d}=l;return a([o,{name:c,message:d}],l)};return i},kxt=(s,{json:t,lossy:n}={})=>{const r=[];return Hjn(!(t||n),!!t,new Map,r)(s),r},u4e=typeof structuredClone=="function"?(s,t)=>t&&("json"in t||"lossy"in t)?Nxt(kxt(s,t)):structuredClone(s):(s,t)=>Nxt(kxt(s,t));function Gjn(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 Wjn(s,t){return"Back to reference "+(s+1)+(t>1?"-"+t:"")}function Kjn(s){const t=typeof s.options.clobberPrefix=="string"?s.options.clobberPrefix:"user-content-",n=s.options.footnoteBackContent||Gjn,r=s.options.footnoteBackLabel||Wjn,a=s.options.footnoteLabel||"Footnotes",i=s.options.footnoteLabelTagName||"h2",l=s.options.footnoteLabelProperties||{className:["sr-only"]},o=[];let c=-1;for(;++c0&&x.push({type:"text",value:" "});let v=typeof n=="string"?n:n(c,p);typeof v=="string"&&(v={type:"text",value:v}),x.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(v)?v:[v]})}const y=u[u.length-1];if(y&&y.type==="element"&&y.tagName==="p"){const v=y.children[y.children.length-1];v&&v.type==="text"?v.value+=" ":y.children.push({type:"text",value:" "}),y.children.push(...x)}else u.push(...x);const b={type:"element",tagName:"li",properties:{id:t+"fn-"+m},children:s.wrap(u,!0)};s.patch(d,b),o.push(b)}if(o.length!==0)return{type:"element",tagName:"section",properties:{dataFootnotes:!0,className:["footnotes"]},children:[{type:"element",tagName:i,properties:{...u4e(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 b7t=function(s){if(s==null)return Qjn;if(typeof s=="function")return UEe(s);if(typeof s=="object")return Array.isArray(s)?Yjn(s):Zjn(s);if(typeof s=="string")return Xjn(s);throw new Error("Expected function, string, or object as test")};function Yjn(s){const t=[];let n=-1;for(;++n":""))+")"})}return m;function m(){let p=_7t,x,g,y;if((!t||i(c,d,u[u.length-1]||void 0))&&(p=n2n(n(c,u)),p[0]===Sxt))return p;if("children"in c&&c.children){const b=c;if(b.children&&p[0]!==t2n)for(g=(r?b.children.length:-1)+l,y=u.concat(b);g>-1&&g0&&n.push({type:"text",value:` `}),n}function Cxt(s){let t=0,n=s.charCodeAt(t);for(;n===9||n===32;)t++,n=s.charCodeAt(t);return s.slice(t)}function Axt(s,t){const n=a2n(s,t),r=n.one(s,void 0),a=Kjn(n),i=Array.isArray(r)?{type:"root",children:r}:r||{type:"root",children:[]};return a&&i.children.push({type:"text",value:` `},a),i}function d2n(s,t){return s&&"run"in s?async function(n,r){const a=Axt(n,{file:r,...t});await s.run(a,r)}:function(n,r){return Axt(n,{file:r,...s||t})}}function Ext(s){if(s)throw s}var V2e=Object.prototype.hasOwnProperty,j7t=Object.prototype.toString,Txt=Object.defineProperty,Mxt=Object.getOwnPropertyDescriptor,Lxt=function(t){return typeof Array.isArray=="function"?Array.isArray(t):j7t.call(t)==="[object Array]"},Pxt=function(t){if(!t||j7t.call(t)!=="[object Object]")return!1;var n=V2e.call(t,"constructor"),r=t.constructor&&t.constructor.prototype&&V2e.call(t.constructor.prototype,"isPrototypeOf");if(t.constructor&&!n&&!r)return!1;var a;for(a in t);return typeof a>"u"||V2e.call(t,a)},Ixt=function(t,n){Txt&&n.name==="__proto__"?Txt(t,n.name,{enumerable:!0,configurable:!0,value:n.newValue,writable:!0}):t[n.name]=n.newValue},Dxt=function(t,n){if(n==="__proto__")if(V2e.call(t,n)){if(Mxt)return Mxt(t,n).value}else return;return t[n]},u2n=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 rS={basename:p2n,dirname:f2n,extname:x2n,join:g2n,sep:"/"};function p2n(s,t){if(t!==void 0&&typeof t!="string")throw new TypeError('"ext" argument must be a string');Zee(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 f2n(s){if(Zee(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 x2n(s){Zee(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 g2n(...s){let t=-1,n;for(;++t0&&s.codePointAt(s.length-1)===47&&(n+="/"),t?"/"+n:n}function v2n(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 Zee(s){if(typeof s!="string")throw new TypeError("Path must be a string. Received "+JSON.stringify(s))}const b2n={cwd:_2n};function _2n(){return"/"}function nBe(s){return!!(s!==null&&typeof s=="object"&&"href"in s&&s.href&&"protocol"in s&&s.protocol&&s.auth===void 0)}function w2n(s){if(typeof s=="string")s=new URL(s);else if(!nBe(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 j2n(s)}function j2n(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,...x]=u;const g=r[m][1];sBe(g)&&sBe(p)&&(p=h8e(!0,g,p)),r[m]=[d,p,...x]}}}}const C2n=new AYe().freeze();function x8e(s,t){if(typeof t!="function")throw new TypeError("Cannot `"+s+"` without `parser`")}function g8e(s,t){if(typeof t!="function")throw new TypeError("Cannot `"+s+"` without `compiler`")}function y8e(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 Oxt(s){if(!sBe(s)||typeof s.type!="string")throw new TypeError("Expected node, got `"+s+"`")}function Fxt(s,t,n){if(!n)throw new Error("`"+s+"` finished async. Use `"+t+"` instead")}function Ore(s){return A2n(s)?s:new N7t(s)}function A2n(s){return!!(s&&typeof s=="object"&&"message"in s&&"messages"in s)}function E2n(s){return typeof s=="string"||T2n(s)}function T2n(s){return!!(s&&typeof s=="object"&&"byteLength"in s&&"byteOffset"in s)}const M2n="https://github.com/remarkjs/react-markdown/blob/main/changelog.md",zxt=[],Bxt={allowDangerousHtml:!0},L2n=/^(https?|ircs?|mailto|xmpp)$/i,P2n=[{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 I2n(s){const t=D2n(s),n=R2n(s);return O2n(t.runSync(t.parse(n),n),s)}function D2n(s){const t=s.rehypePlugins||zxt,n=s.remarkPlugins||zxt,r=s.remarkRehypeOptions?{...s.remarkRehypeOptions,...Bxt}:Bxt;return C2n().use(fjn).use(n).use(d2n,r).use(t)}function R2n(s){const t=s.children||"",n=new N7t;return typeof t=="string"&&(n.value=t),n}function O2n(s,t){const n=t.allowedElements,r=t.allowElement,a=t.components,i=t.disallowedElements,l=t.skipHtml,o=t.unwrapDisallowed,c=t.urlTransform||F2n;for(const u of P2n)Object.hasOwn(t,u.from)&&(""+u.from+(u.to?"use `"+u.to+"` instead":"remove it")+M2n+u.id,void 0);return w7t(s,d),Kbn(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 c8e)if(Object.hasOwn(c8e,p)&&Object.hasOwn(u.properties,p)){const x=u.properties[p],g=c8e[p];(g===null||g.includes(u.tagName))&&(u.properties[p]=c(String(x||""),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 F2n(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||L2n.test(s.slice(0,t))?s:""}const z2n={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(Wn,{to:n,className:a,children:[t,e.jsx(mT,{className:"h-3 w-3"})]}):e.jsxs("a",{href:n,target:"_blank",rel:"noopener noreferrer",className:a,children:[t,e.jsx(mT,{className:"h-3 w-3"})]})}},B2n=["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 $2n(){var h,m,p;const{user:s}=_s(),[t,n]=j.useState([]),[r,a]=j.useState(""),[i,l]=j.useState(!1),o=j.useRef(null),c=j.useRef(null),d=((h=s==null?void 0:s.user_metadata)==null?void 0:h.first_name)||((p=(m=s==null?void 0:s.user_metadata)==null?void 0:m.full_name)==null?void 0:p.split(" ")[0])||"";j.useEffect(()=>{var x;(x=c.current)==null||x.scrollTo({top:c.current.scrollHeight,behavior:"smooth"})},[t,i]);const u=async x=>{var v;const g=x.trim();if(!g||i)return;const y=[...t,{role:"user",content:g}];n([...y,{role:"assistant",content:""}]),a(""),l(!0);const b=new AbortController;o.current=b;try{const{data:N}=await U.auth.getSession(),C=(v=N.session)==null?void 0:v.access_token,A=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/levelup-assistant",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${C}`,apikey:"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6InJlbHplamlzd25vdGlramd2amh6Iiwicm9sZSI6ImFub24iLCJpYXQiOjE3NjE5NTAzNDQsImV4cCI6MjA3NzUyNjM0NH0.dzIkIr_oFSbFE3oWS0ktIr83iKHHkZxt40Gc7SpC_mM"},body:JSON.stringify({messages:y,agentName:d}),signal:b.signal});if(!A.ok||!A.body){const D=await A.json().catch(()=>({error:"Something went wrong."}));throw new Error(D.error||"Something went wrong.")}const T=A.body.getReader(),P=new TextDecoder;let M="",I="";for(;;){const{done:D,value:B}=await T.read();if(D)break;M+=P.decode(B,{stream:!0});const q=M.split(` `);M=q.pop()||"";for(const W of q){const V=W.trim();if(!V.startsWith("data:"))continue;const K=V.slice(5).trim();if(!(!K||K==="[DONE]"))try{const Q=JSON.parse(K);Q.delta&&(I+=Q.delta,n(J=>{const ce=[...J];return ce[ce.length-1]={role:"assistant",content:I},ce}))}catch{}}}I||n(D=>{const B=[...D];return B[B.length-1]={role:"assistant",content:"I didn't catch that — mind asking again?"},B})}catch(N){N.name==="AbortError"?n(C=>C.filter((A,T)=>!(T===C.length-1&&!A.content))):(ae.error(N.message||"The assistant is unavailable right now."),n(C=>C.slice(0,-1)))}finally{l(!1),o.current=null}};return e.jsx(Ks,{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(t5,{className:"h-5 w-5 text-primary"})}),e.jsxs("div",{children:[e.jsx("h1",{className:"text-xl font-bold tracking-tight",children:"Ask LevelUp AI"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Your in-app guide to the platform and your business."})]})]}),t.length>0&&e.jsxs($,{variant:"ghost",size:"sm",className:"gap-1",onClick:()=>n([]),children:[e.jsx(Ih,{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(t5,{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:B2n.map(x=>e.jsx("button",{onClick:()=>u(x),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:x},x))})]}):t.map((x,g)=>e.jsx("div",{className:Tt("flex",x.role==="user"?"justify-end":"justify-start"),children:x.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:x.content})}):e.jsx("div",{className:"max-w-full text-sm leading-relaxed text-foreground",children:x.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(I2n,{components:z2n,children:x.content})}):e.jsx("span",{className:"animate-pulse text-muted-foreground",children:"Thinking…"})})},g))}),e.jsxs("div",{className:"mt-3 flex items-end gap-2 rounded-2xl border bg-background p-2",children:[e.jsx(Is,{value:r,onChange:x=>a(x.target.value),onKeyDown:x=>{x.key==="Enter"&&!x.shiftKey&&(x.preventDefault(),u(r))},rows:1,placeholder:"Ask anything about LevelUp or your business…",className:"min-h-[44px] resize-none border-0 bg-transparent shadow-none focus-visible:ring-0"}),i?e.jsx($,{size:"icon",variant:"secondary",onClick:()=>{var x;return(x=o.current)==null?void 0:x.abort()},children:e.jsx(Lb,{className:"h-4 w-4"})}):e.jsx($,{size:"icon",disabled:!r.trim(),onClick:()=>u(r),children:e.jsx(Br,{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 U2n({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 Fre({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:Tt("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(Ja,{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 q2n({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",x=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(dn,{className:"mt-0.5 h-3.5 w-3.5 shrink-0 text-primary"}),e.jsx("span",{children:r})]})]}),e.jsx(U2n,{done:t,total:n})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsx(Fre,{icon:e.jsx(Mu,{className:"h-3.5 w-3.5"}),label:"Weekly goal",value:`${a}/${i}`,hint:`${x}% 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(pc,{className:"h-3.5 w-3.5"})})}),e.jsx(Fre,{icon:e.jsx(yd,{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(Fre,{icon:e.jsx(Hr,{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(Fre,{icon:e.jsx(qn,{className:"h-3.5 w-3.5"}),label:"Your sphere",value:String(c),hint:"People in your database",onClick:h})]})]})}const $xt="agent-os-onboarding-completed",zre=[{icon:w0,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:ox,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:qn,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:Nl,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:Co,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:ml,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"]}],V2n=()=>{const[s,t]=j.useState(!1),[n,r]=j.useState(0),[a,i]=j.useState(!1);j.useEffect(()=>{if(!localStorage.getItem($xt)){const x=setTimeout(()=>t(!0),500);return()=>clearTimeout(x)}},[]);const l=()=>{n{r(n+1),i(!1)},150)):c()},o=()=>{c()},c=()=>{localStorage.setItem($xt,"true"),t(!1)},d=zre[n],u=d.icon,h=n===zre.length-1,m=p=>{p||c(),t(p)};return e.jsx(Os,{open:s,onOpenChange:m,children:e.jsxs(Rs,{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(dn,{className:"h-3 w-3"}),"Beta"]})]}),e.jsxs("div",{className:"p-6 pt-4",children:[e.jsxs(Us,{className:"text-center sm:text-center pb-2",children:[e.jsx(zs,{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(Sr,{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,x)=>e.jsxs("div",{className:"flex items-center gap-3 group",style:{transitionDelay:`${150+x*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(oa,{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})]},x))}),e.jsx("div",{className:"flex justify-center gap-2 py-4",children:zre.map((p,x)=>e.jsx("button",{onClick:()=>{x!==n&&(i(!0),setTimeout(()=>{r(x),i(!1)},150))},className:`h-2 rounded-full transition-all duration-300 ${x===n?"w-8 bg-gradient-to-r "+d.bgGradient:x{const{user:s}=_s();return ht({queryKey:["contact-snoozes",s==null?void 0:s.id],queryFn:async()=>{const{data:t,error:n}=await U.from("contact_snoozes").select("*").gte("snoozed_until",new Date().toISOString());if(n)throw n;return t},enabled:!!s})},G2n=()=>{const s=ts(),{user:t}=_s();return yt({mutationFn:async({contactId:n,days:r})=>{if(!(t!=null&&t.id))throw new Error("Not authenticated");const a=Bd(new Date,r);await U.from("contact_snoozes").delete().eq("contact_id",n);const{error:i}=await U.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"]}),ja({title:"Touch snoozed!",description:"Contact has been snoozed."})},onError:n=>{ja({title:"Error snoozing contact",description:n.message,variant:"destructive"})}})},W2n=()=>{const s=ts();return yt({mutationFn:async t=>{const{error:n}=await U.from("contact_snoozes").delete().eq("contact_id",t);if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["contact-snoozes"]}),ja({title:"Snooze cancelled"})},onError:t=>{ja({title:"Error cancelling snooze",description:t.message,variant:"destructive"})}})},K2n=[{label:"1 week",days:7},{label:"2 weeks",days:14},{label:"1 month",days:30}];function qEe({open:s,onOpenChange:t,contactId:n,contactName:r}){const[a,i]=j.useState(null),l=G2n(),o=async()=>{a&&(await l.mutateAsync({contactId:n,days:a}),i(null),t(!1))},c=d=>Hs(Bd(new Date,d),"MMM d, yyyy");return e.jsx(Os,{open:s,onOpenChange:t,children:e.jsxs(Rs,{className:"sm:max-w-md",children:[e.jsxs(Us,{children:[e.jsxs(zs,{className:"flex items-center gap-2",children:[e.jsx(Hr,{className:"h-5 w-5"}),"Snooze Touch"]}),e.jsxs(Sr,{children:["Postpone the next scheduled touch for ",r,". Select how long to snooze."]})]}),e.jsx("div",{className:"space-y-3 py-4",children:K2n.map(d=>e.jsxs("button",{type:"button",onClick:()=>i(d.days),className:Tt("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(ia,{className:"h-3.5 w-3.5"}),"Until ",c(d.days)]})]},d.days))}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx($,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsx($,{onClick:o,disabled:!a||l.isPending,children:l.isPending?"Snoozing...":"Snooze Touch"})]})]})})}const Y2n={Crown:Ng,FileText:Wr,Users:qn,Globe:Gl,Star:Qa,Phone:ya,MessageSquare:Ji,PenTool:kT,Video:Xr,Gift:Co};function Z2n({actions:s,onMarkComplete:t,onViewScript:n,isLoading:r,buildSmsLink:a,buildEmailLink:i,onGmailCompose:l}){const o=Vn(),[c,d]=j.useState("name"),[u,h]=j.useState("asc"),[m,p]=j.useState(null),[x,g]=j.useState(""),y=A=>{c===A?h(T=>T==="asc"?"desc":"asc"):(d(A),h("asc"))},b=j.useMemo(()=>[...s].sort((A,T)=>{var M,I;let P=0;switch(c){case"name":{const D=`${A.contact.first_name} ${A.contact.last_name||""}`.toLowerCase(),B=`${T.contact.first_name} ${T.contact.last_name||""}`.toLowerCase();P=D.localeCompare(B);break}case"relationship_type":P=(A.relationshipTypeName||"").localeCompare(T.relationshipTypeName||"");break;case"action_type":P=(((M=A.actionType)==null?void 0:M.name)||"").localeCompare(((I=T.actionType)==null?void 0:I.name)||"");break;case"last_touch":P=(A.monthNumber||0)-(T.monthNumber||0);break}return u==="asc"?P:-P}),[s,c,u]),v=A=>Y2n[A||"Phone"]||ya,N=({field:A,children:T})=>e.jsxs($,{variant:"ghost",size:"sm",className:"h-8 -ml-3 font-medium",onClick:()=>y(A),children:[T,c===A?u==="asc"?e.jsx(sp,{className:"ml-2 h-4 w-4"}):e.jsx(ax,{className:"ml-2 h-4 w-4"}):e.jsx(Tx,{className:"ml-2 h-4 w-4 opacity-50"})]}),C=(A,T,P)=>{p(A),g(`${T} ${P||""}`.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(Va,{children:[e.jsx(Ha,{children:e.jsxs(hn,{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(Ga,{children:b.map((A,T)=>{var q,W,V,K,Q,J;const P=A.isSpecialDate,M=A.specialDateType,I=P?M==="birthday"?np:sa:v(((q=A.actionType)==null?void 0:q.icon)||null),D=A.contact.phone,B=A.contact.email;return e.jsxs(hn,{className:Tt("hover:bg-muted/50 transition-colors",P&&M==="birthday"&&"bg-pink-50/50 dark:bg-pink-950/20",P&&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($e,{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:P?e.jsx($e,{className:Tt("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(np,{className:"h-3 w-3"})," Birthday"]}):e.jsxs(e.Fragment,{children:[e.jsx(sa,{className:"h-3 w-3"})," Anniversary"]})}):e.jsxs($e,{variant:"outline",className:"gap-1",children:[e.jsx(I,{className:"h-3 w-3"}),(W=A.actionType)==null?void 0:W.name]})})}),e.jsx(gt,{children:D?e.jsx("span",{className:"text-sm font-mono",children:A.contact.phone}):e.jsx("span",{className:"text-muted-foreground text-sm",children:"—"})}),e.jsx(gt,{children:e.jsxs("div",{className:"flex items-center gap-1",children:[D&&e.jsx("a",{href:`tel:${A.contact.phone}`,className:"p-1.5 rounded bg-primary/10 hover:bg-primary/20 text-primary transition-colors",title:"Call",children:e.jsx(ya,{className:"h-3.5 w-3.5"})}),D&&e.jsx("a",{href:a(A.contact.phone,(V=A.script)==null?void 0:V.script_body,A.contact),className:"p-1.5 rounded bg-emerald-500/10 hover:bg-emerald-500/20 text-emerald-600 dark:text-emerald-400 transition-colors",title:"Text",children:e.jsx(Ji,{className:"h-3.5 w-3.5"})}),B&&(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(nn,{className:"h-3.5 w-3.5"})}):e.jsx("a",{href:i(A.contact.email,(K=A.script)==null?void 0:K.script_body,(Q=A.script)==null?void 0:Q.email_subject,(J=A.actionType)==null?void 0:J.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(nn,{className:"h-3.5 w-3.5"})})),P&&e.jsxs("button",{onClick:()=>{const ce=`${A.contact.first_name}${A.contact.last_name?" "+A.contact.last_name:""}`,ue=M==="birthday"?"birthday":"home_anniversary",ne=new URLSearchParams({cardType:ue,contactId:A.contact.id,name:ce,...A.contact.address?{address:A.contact.address}:{},...M==="anniversary"&&A.contact.home_anniversary?{date:A.contact.home_anniversary}:{}});o(`/mission-control/card-studio?${ne.toString()}`)},className:Tt("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(nn,{className:"h-3.5 w-3.5"}),"Send Card"]}),e.jsx($,{variant:"ghost",size:"icon",className:"h-7 w-7 text-muted-foreground hover:text-foreground",onClick:()=>C(A.contact.id,A.contact.first_name,A.contact.last_name),title:"Snooze",children:e.jsx(vy,{className:"h-3.5 w-3.5"})}),e.jsxs($,{variant:"default",size:"sm",className:"h-7 px-2 text-xs ml-1",onClick:()=>{var ce;return t(A.contact.id,A.actionType.id,(ce=A.script)==null?void 0:ce.id)},disabled:r,children:[e.jsx(Fr,{className:"h-3.5 w-3.5 mr-1"}),"Done"]})]})})]},`${A.contact.id}-${T}`)})})]})}),e.jsx(qEe,{open:!!m,onOpenChange:A=>!A&&p(null),contactId:m||"",contactName:x})]})}function X2n(){const{user:s}=_s(),{limitFor:t,isRestricted:n}=ek(),r=n?t("mass_email"):null,{data:a=0,refetch:i}=ht({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 U.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 Q2n({onSelect:s}){const{user:t}=_s(),[n,r]=j.useState("root"),[a,i]=j.useState(null),{data:l=[],isLoading:o}=ht({queryKey:["agent-email-template-categories"],queryFn:async()=>{const{data:b,error:v}=await U.from("email_template_categories").select("*").order("sort_order");if(v)throw v;return b}}),{data:c=[],isLoading:d}=ht({queryKey:["agent-email-templates",a],enabled:n==="category"&&!!a,queryFn:async()=>{const{data:b,error:v}=await U.from("agent_email_templates").select("*").eq("is_active",!0).eq("category_id",a).order("sort_order");if(v)throw v;return b}}),{data:u=[],isLoading:h}=ht({queryKey:["picker-campaign-templates",t==null?void 0:t.id],enabled:!!t,queryFn:async()=>{const{data:b,error:v}=await U.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(v)throw v;return b}}),m=u.filter(b=>b.user_id===(t==null?void 0:t.id)&&!b.is_shared),p=u.filter(b=>b.is_shared),x=l.find(b=>b.id===a);if(o)return e.jsx("div",{className:"flex items-center justify-center py-6",children:e.jsx(Ht,{className:"h-5 w-5 animate-spin text-muted-foreground"})});const g=b=>{s({title:b.name,subject:b.subject,body:b.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(Lo,{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(Ja,{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(Gl,{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(Ja,{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(b=>e.jsxs("button",{onClick:()=>{i(b.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:b.icon}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-sm",children:b.name}),b.description&&e.jsx("p",{className:"text-xs text-muted-foreground line-clamp-1",children:b.description})]})]}),e.jsx(Ja,{className:"h-4 w-4 text-muted-foreground shrink-0"})]},b.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(Ic,{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(Lo,{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(Ht,{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(dn,{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(Oi,{className:"max-h-[280px]",children:e.jsx("div",{className:"space-y-1",children:m.map(b=>e.jsxs("button",{onClick:()=>g(b),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:b.name}),e.jsx("p",{className:"text-xs text-muted-foreground mt-0.5 line-clamp-1",children:b.subject||"(no subject)"})]},b.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(Gl,{className:"h-3.5 w-3.5"})," Shared Library"]}),h?e.jsx("div",{className:"flex items-center justify-center py-6",children:e.jsx(Ht,{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(Oi,{className:"max-h-[280px]",children:e.jsx("div",{className:"space-y-1",children:p.map(b=>e.jsxs("button",{onClick:()=>g(b),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:b.name}),e.jsx($e,{variant:"secondary",className:"text-[10px] shrink-0",children:"Shared"})]}),e.jsx("p",{className:"text-xs text-muted-foreground mt-0.5 line-clamp-1",children:b.subject||"(no subject)"})]},b.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:x==null?void 0:x.icon})," ",x==null?void 0:x.name]}),d?e.jsx("div",{className:"flex items-center justify-center py-6",children:e.jsx(Ht,{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(Oi,{className:"max-h-[280px]",children:e.jsx("div",{className:"space-y-1",children:c.map(b=>e.jsxs("button",{onClick:()=>s(b),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:b.title}),b.tone&&e.jsx($e,{variant:"secondary",className:"text-[10px] shrink-0",children:b.tone})]}),e.jsx("p",{className:"text-xs text-muted-foreground mt-0.5 line-clamp-1",children:b.subject})]},b.id))})})]})}function VEe(){const{user:s}=_s(),t=ts(),{data:n,isLoading:r}=ht({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 U.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 U.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"]}),ae.success("Connect page created!")},onError:d=>{var u;(u=d.message)!=null&&u.includes("duplicate")?ae.error("That slug is already taken. Try another."):ae.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 U.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"]}),ae.success("Page updated!")},onError:()=>ae.error("Failed to update page")}),{data:l=[],isLoading:o}=ht({queryKey:["contact-intake-submissions",s==null?void 0:s.id],queryFn:async()=>{if(!(s!=null&&s.id))return[];const{data:d,error:u}=await U.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 U.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 k7t({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 g=y=>{m.current&&!m.current.contains(y.target)&&i(!1)};return document.addEventListener("mousedown",g),()=>document.removeEventListener("mousedown",g)},[]),j.useEffect(()=>{p.current&&clearTimeout(p.current);const g=s.trim();if(!n||g.length<1||g.includes("@")&&g.indexOf("@")>0&&/\S+@\S+\.\S+/.test(g)){o([]);return}return p.current=setTimeout(async()=>{d(!0);const y=`%${g}%`,b=U,{data:v,error:N}=await b.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&&v&&(o(v),h(0),i(v.length>0))},180),()=>{p.current&&clearTimeout(p.current)}},[s,n]);const x=g=>{g.email&&(t(g.email),i(!1))};return e.jsxs("div",{ref:m,className:"relative",children:[e.jsx(be,{id:"gmail-to",value:s,onChange:g=>t(g.target.value),onFocus:()=>l.length>0&&i(!0),onKeyDown:g=>{!a||l.length===0||(g.key==="ArrowDown"?(g.preventDefault(),h(y=>Math.min(y+1,l.length-1))):g.key==="ArrowUp"?(g.preventDefault(),h(y=>Math.max(y-1,0))):g.key==="Enter"?(g.preventDefault(),x(l[u])):g.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(Ht,{className:"h-3 w-3 animate-spin"})," Searching..."]}):l.map((g,y)=>{const b=[g.first_name,g.last_name].filter(Boolean).join(" ")||"(No name)";return e.jsxs("button",{type:"button",onMouseEnter:()=>h(y),onClick:()=>x(g),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(Lo,{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:b}),e.jsx("div",{className:"text-xs text-muted-foreground truncate",children:g.email})]})]},g.id)})})]})}function J2n(){const{user:s}=_s(),{data:t,isLoading:n}=ht({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 U.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 eNn(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 tNn(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 v8e=25*1024*1024,Uxt=Math.floor(6.5*1024*1024),sNn=750*1024,nj=50,nNn=["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 Bre(s){return s<1024?s+" B":s<1024*1024?(s/1024).toFixed(1)+" KB":(s/(1024*1024)).toFixed(1)+" MB"}function rNn(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 aNn(s){if(!s)return"";const t=s.trim();return t.split(/\s+/)[0]||t}function rj(s,t){const n=aNn(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 x2({open:s,onOpenChange:t,contact:n,bulkContacts:r,defaultSubject:a="",defaultBody:i="",gmailEmail:l,onSendComplete:o,sendSource:c,logTouchpoint:d=!0}){const{user:u}=_s(),h=ts(),{isReady:m,settings:p}=iV(),{data:x}=Kee(),[g,y]=j.useState(!1),{intakePage:b}=VEe(),v=b?`https://contacts.relevelup.com/${b.slug}`:null,N=!!r&&r.length>0,C=X2n(),A=m,T=N?r:n?[n]:[],P=T[0],M=N?Math.ceil(T.length/nj):1,I=N&&T.length>nj,[D,B]=j.useState((P==null?void 0:P.email)||""),[q,W]=j.useState(a),[V,K]=j.useState(i),[Q,J]=j.useState(!1),[ce,ue]=j.useState(!1),[ne,ee]=j.useState([]),le=j.useRef(new Map),[he,ve]=j.useState(a),[ge,fe]=j.useState(i),[je,Ee]=j.useState(!1),[Me,De]=j.useState("composing"),[ze,ke]=j.useState(0),[Xe,Se]=j.useState(0),[Re,Ae]=j.useState(0),[Be,qe]=j.useState(0),Ke=j.useRef(!1),Ze=j.useRef(0),[Ue,et]=j.useState(!0),{signatureHtml:Qe,hasSignature:Ge,signatureEnabledByDefault:nt}=J2n(),[ft,lt]=j.useState(!0),[Mt,Ft]=j.useState(null);j.useEffect(()=>{s&<(Ge)},[s,Ge]),j.useEffect(()=>{if(s){const fn=/<[a-z][\s\S]*>/i.test(i),Zn=fn?tNn(i):i;Ds.current=fn?{plain:Zn,html:i}:null,B((P==null?void 0:P.email)||""),ve(a),fe(Zn),W(rj(a,P||{first_name:""})),K(rj(Zn,P||{first_name:""})),ue(!a&&!i),Ee(!1),ee([]),le.current=new Map,De("composing"),ke(0),Se(0),Ae(0),qe(0),Ke.current=!1,Ze.current=0,Ft(null)}},[s,P,a,i]);const Ts=async fn=>{const Zn=fn.target.files;if(!Zn)return;const Xt=ne.reduce((Sn,$n)=>Sn+$n.size,0),rr=[];let Qn=Xt;for(const Sn of Array.from(Zn)){if(!nNn.includes(Sn.type)){ae.error(`${Sn.name}: Unsupported file type`);continue}if(Qn+Sn.size>v8e){ae.error(`Total attachments exceed ${Bre(v8e)} limit`);break}try{const $n=await rNn(Sn);rr.push({name:Sn.name,type:Sn.type,size:Sn.size,data:$n}),Qn+=Sn.size}catch{ae.error(`Failed to read ${Sn.name}`)}}ee(Sn=>[...Sn,...rr]),fn.target.value=""},js=fn=>{const Zn=ne[fn];Zn&&le.current.delete(`${Zn.name}::${Zn.size}`),ee(Xt=>Xt.filter((rr,Qn)=>Qn!==fn))},zt=async()=>{if(ne.length===0||!u)return{inline:[],paths:[]};const fn=[],Zn=[];for(const Xt of ne){const rr=`${Xt.name}::${Xt.size}`,Qn=le.current.get(rr);if(Qn){Zn.push(Qn);continue}if(Xt.size<=sNn){fn.push(Xt);continue}const Sn=Xt.name.replace(/[^a-zA-Z0-9._-]/g,"_"),$n=`${u.id}/${Date.now()}-${Sn}`,tn=atob(Xt.data),ln=new Uint8Array(tn.length);for(let ms=0;ms{if(!/<[a-z][\s\S]*>/i.test(fn)||typeof window>"u")return fn;const Zn=fn.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,""),Xt=document.createElement("div");return Xt.innerHTML=Zn,(Xt.textContent||Xt.innerText||"").replace(/\u00a0/g," ").replace(/\n{3,}/g,` `).trim()},Ds=j.useRef(null),_t=Ds.current&&ge===Ds.current.plain?Ds.current.html:null,Xs=fn=>{const Zn=/<[a-z][\s\S]*>/i.test(fn.body),Xt=Zn?Nt(fn.body):fn.body;Ds.current=Zn?{plain:Xt,html:fn.body}:null,ve(fn.subject),fe(Xt),W(rj(fn.subject,P||{first_name:""})),K(rj(Xt,P||{first_name:""})),ue(!1)},rn=fn=>/<\s*(p|div|span|table|tr|td|img|br|h[1-6]|a|body|html|section|article|ul|ol|li)\b/i.test(fn)?fn:fn.split(/\n\n+/).map(Zn=>`

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

`).join(""),Ps=(fn,Zn)=>{const Xt="https://relzejiswnotikjgvjhz.supabase.co/functions/v1/bulk-email-track";let rr=fn.replace(/]*?)href=(["'])(.*?)\2([^>]*)>/gi,(Sn,$n,tn,ln,Cr)=>{if(!ln||/^(mailto:|tel:|#)/i.test(ln)||ln.includes("/bulk-email-track")||ln.includes("/ses-campaign-track"))return Sn;const ms=`${Xt}?s=${Zn}&t=click&u=${encodeURIComponent(ln)}`;return``});const Qn=``;return/<\/body>/i.test(rr)?rr=rr.replace(/<\/body>/i,`${Qn}`):rr=`${rr}${Qn}`,rr},_n=async fn=>{if(!(fn!=null&&fn.email))return ae.error("Please enter a recipient email"),!1;const Zn=fn||{first_name:""},Xt=rj(he,Zn),rr=Ds.current,Qn=rr&&ge===rr.plain,Sn=rj(Qn?rr.html:ge,Zn);let $n=Qn?Sn:rn(Sn);ft&&Qe&&($n=eNn($n,rj(Qe,Zn)));const tn=u&&fn.id?crypto.randomUUID():null;tn&&($n=Ps($n,tn));try{if(u&&fn.email){const ms=new Date(Date.now()-6e5).toISOString(),{data:ot}=await U.from("bulk_email_sends").select("id").eq("user_id",u.id).eq("contact_email",fn.email).eq("subject",Xt).gte("sent_at",ms).limit(1);if(ot&&ot.length>0)return console.log(`Skipping duplicate send to ${fn.email} (same subject within 10 min)`),ae.info(`Skipped ${fn.first_name||fn.email} — already sent this in the last 10 min`),!0}const{inline:ln,paths:Cr}=await zt();if(A){const ms=(p==null?void 0:p.display_name)||"ReLevelUp",ot=`${ms.toLowerCase().replace(/[^a-z]/g,".")}@send.relevelup.com`,pt=`${ms} <${ot}>`;let vt=Cr[0];if(!vt&&ln.length>0&&u){const as=ln[0],Ls=as.name.replace(/[^a-zA-Z0-9._-]/g,"_"),cs=`${u.id}/${Date.now()}-${Ls}`,qt=atob(as.data),Gs=new Uint8Array(qt.length);for(let Hn=0;Hn({name:pt,type:vt,data:At})),attachment_paths:Cr,skip_signature:!0}});if(ot)throw ot;if(!(ms!=null&&ms.success))throw new Error((ms==null?void 0:ms.error)||"Failed to send")}if(u&&fn.id&&tn&&(await U.from("bulk_email_sends").insert({id:tn,user_id:u.id,contact_id:fn.id,contact_email:fn.email,subject:Xt,source:c||(A?"ses_bulk":"sphere_gaps")}),d))try{await U.from("contact_touch_logs").insert({owner_user_id:u.id,contact_id:fn.id,action_type_id:"9a88a47c-cb2a-4401-a2b5-111a76b19f9d",notes:`Mass Email: ${Xt}`,completed_at:new Date().toISOString()})}catch(ms){console.warn("touch log insert failed",ms)}return!0}catch(ln){return console.error("Send error:",ln),ae.error("Failed to send to "+fn.first_name+": "+(ln instanceof Error?ln.message:"Unknown error")),!1}},Zs=()=>{const fn=ze*nj;return T.slice(fn,fn+nj)},gr=async(fn=0,Zn=Ue)=>{if(!q||!V){ae.error("Please fill in subject and message");return}J(!0),De("sending");let Xt=Math.max(0,Math.min(fn,T.length)),rr=!1;for(;XtCr+1):Ae(Cr=>Cr+1),tn<$n-1&&await new Promise(Cr=>setTimeout(Cr,150))}if(h.invalidateQueries({queryKey:["bulk-email-sends"]}),h.invalidateQueries({queryKey:["contact-touch-logs"]}),h.invalidateQueries({queryKey:["contacts-last-touch"]}),rr||Ke.current||Xt>=T.length)break;if(!Zn){J(!1),De("batch_complete");return}if(qe(0),await new Promise(tn=>setTimeout(tn,1500)),Ke.current){rr=!0;break}}J(!1),De(rr||Ke.current?"batch_complete":"all_done")},Un=async()=>{var Zn;if(!q||!V){ae.error("Please fill in subject and message");return}const fn=N?(r==null?void 0:r.length)||0:1;if(C.wouldExceed(fn)){ae.error(`Your package includes ${(Zn=C.limit)==null?void 0:Zn.toLocaleString()} emails per month. You have ${C.remaining.toLocaleString()} left — request an upgrade for unlimited sending.`);return}if(A&&x&&!x.hasVerifiedSes&&!x.hasGmail){y(!0);return}if(!N){const Xt=P||{id:"",first_name:"",last_name:"",email:D.trim()};if(!Xt.email){ae.error("Please enter a recipient email");return}J(!0);try{await _n(Xt)&&(h.invalidateQueries({queryKey:["bulk-email-sends"]}),ae.success("Email sent successfully!"),t(!1),o==null||o())}finally{J(!1)}return}Ke.current=!1,Ze.current=0,await gr(0)},In=async()=>{Ke.current=!1,qe(0),await gr(Ze.current,!1)},Ar=async()=>{Ke.current=!1,et(!0),qe(0),await gr(Ze.current,!0)},or=()=>{if(Q){Ke.current=!0;return}t(!1),o==null||o()},qs=ze*nj;Math.min(qs+nj,T.length);const yr=N&&T.length>0?Math.round((Xe+Re)/T.length*100):0;return e.jsxs(Os,{open:s,onOpenChange:or,children:[e.jsxs(Rs,{className:"sm:max-w-[600px] max-h-[90vh] overflow-y-auto",children:[e.jsxs(Us,{children:[e.jsxs(zs,{className:"flex items-center gap-2",children:[e.jsx(nn,{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&&Me==="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."]})]}),Me==="sending"&&e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{className:"text-center space-y-2",children:[e.jsx(Ht,{className:"h-8 w-8 animate-spin mx-auto text-primary"}),e.jsxs("p",{className:"font-medium",children:["Sending batch ",ze+1," of ",M,"..."]}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[Be," of ",Zs().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(Ki,{value:Be/Math.max(Zs().length,1)*100,className:"h-2"}),e.jsxs("div",{className:"flex justify-between text-xs text-muted-foreground",children:[e.jsxs("span",{children:["Overall: ",Xe+Re," / ",T.length]}),e.jsxs("span",{children:[Xe," sent • ",Re," failed"]})]}),e.jsx($,{variant:"outline",size:"sm",className:"w-full",onClick:()=>{Ke.current=!0},children:"Stop Sending"})]}),Me==="batch_complete"&&e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{className:"text-center space-y-2",children:[e.jsx(Fr,{className:"h-8 w-8 text-emerald-500 mx-auto"}),e.jsxs("p",{className:"font-medium",children:["Sending paused after batch ",ze+1]}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[Xe," sent, ",Re," failed so far"]})]}),e.jsx(Ki,{value:yr,className:"h-2"}),e.jsxs("p",{className:"text-xs text-center text-muted-foreground",children:[T.length-Xe-Re," contacts remaining (",Math.max(M-ze-1,0)," batches left)"]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx($,{variant:"outline",className:"flex-1",onClick:or,children:"Done for Now"}),e.jsxs($,{className:"flex-1 gap-2",onClick:Ar,children:[e.jsx(Br,{className:"h-4 w-4"}),"Resume Sending"]})]}),e.jsxs($,{variant:"ghost",size:"sm",className:"w-full",onClick:In,children:["Send just the next ",Math.min(nj,Math.max(T.length-(Xe+Re),0))," contacts"]})]}),Me==="all_done"&&e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{className:"text-center space-y-2",children:[e.jsx(Fr,{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:[Xe," emails sent successfully",Re>0&&e.jsxs("span",{className:"text-destructive",children:[" • ",Re," failed"]})]})]}),e.jsx($,{className:"w-full",onClick:or,children:"Close"})]}),Me==="composing"&&e.jsxs("div",{className:"space-y-4",children:[ce?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(Wr,{className:"h-4 w-4"})," Choose a Template"]}),e.jsxs($,{variant:"ghost",size:"sm",onClick:()=>ue(!1),className:"h-7 px-2 text-xs",children:[e.jsx(pr,{className:"h-3 w-3 mr-1"})," Write from scratch"]})]}),e.jsx(Q2n,{onSelect:Xs})]}):e.jsxs($,{variant:"outline",size:"sm",className:"gap-2",onClick:()=>ue(!0),children:[e.jsx(Wr,{className:"h-4 w-4"}),"Browse Templates"]}),e.jsx(Hl,{}),!N&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{htmlFor:"gmail-to",children:"To"}),e.jsx(k7t,{value:D,onChange:B,userId:u==null?void 0:u.id})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{htmlFor:"gmail-subject",children:"Subject"}),e.jsx(be,{id:"gmail-subject",value:q,onChange:fn=>{W(fn.target.value),ve(fn.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(se,{htmlFor:"gmail-body",children:"Message"}),e.jsxs("div",{className:"flex gap-1",children:[e.jsx($e,{variant:"outline",className:"text-[10px] cursor-pointer hover:bg-accent",onClick:()=>{K(fn=>fn+"{{first_name}}"),fe(fn=>fn+"{{first_name}}")},children:"{{first_name}}"}),e.jsx($e,{variant:"outline",className:"text-[10px] cursor-pointer hover:bg-accent",onClick:()=>{K(fn=>fn+"{{last_name}}"),fe(fn=>fn+"{{last_name}}")},children:"{{last_name}}"}),v&&e.jsx($e,{variant:"outline",className:"text-[10px] cursor-pointer hover:bg-primary/10 border-primary/40 text-primary",onClick:()=>{const fn=` When you get a sec, can you share your latest contact info with me? It only takes about a minute: ${v} `;K(Zn=>Zn+fn),fe(Zn=>Zn+fn)},title:"Insert your Connect Page link",children:"+ Connect Page"})]})]}),_t&&!je?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($,{type:"button",variant:"ghost",size:"sm",className:"h-7 px-2 text-xs",onClick:()=>Ee(!0),children:"Edit as plain text"})]}),e.jsx("div",{className:"max-h-[420px] overflow-y-auto [&_img]:max-w-full",dangerouslySetInnerHTML:{__html:rj(_t,P||{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(Is,{id:"gmail-body",value:V,onChange:fn=>{K(fn.target.value),fe(fn.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:Ge?"Your saved signature is added to the bottom of this email.":"Add a signature in Profile settings to use this."})]}),e.jsx(Tn,{checked:ft&&Ge,onCheckedChange:lt,disabled:!Ge})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs($,{type:"button",variant:"outline",size:"sm",className:"gap-2",onClick:()=>{var fn;return(fn=document.getElementById("gmail-attachments"))==null?void 0:fn.click()},disabled:Q,children:[e.jsx(NT,{className:"h-4 w-4"}),"Attach Files"]}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:["PDF, images, Word, Excel (max ",Bre(v8e)," 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:Ts})]}),ne.length>0&&e.jsx("div",{className:"flex flex-wrap gap-2",children:ne.map((fn,Zn)=>e.jsxs($e,{variant:"secondary",className:"gap-1.5 pl-2 pr-1 py-1",children:[e.jsx(NT,{className:"h-3 w-3"}),e.jsx("span",{className:"max-w-[140px] truncate text-xs",children:fn.name}),e.jsxs("span",{className:"text-[10px] text-muted-foreground",children:["(",Bre(fn.size),")"]}),e.jsx("button",{type:"button",onClick:()=>js(Zn),className:"ml-0.5 rounded-full p-0.5 hover:bg-muted",children:e.jsx(pr,{className:"h-3 w-3"})})]},Zn))}),A&&ne.some(fn=>fn.size>Uxt)&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Files over ",Bre(Uxt)," will be sent as secure download links."]})]}),e.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[e.jsx($,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),N?e.jsxs($,{onClick:()=>{Ft(T[0]||null),De("reviewing")},disabled:!q||!V,className:"gap-2",children:["Review Emails",e.jsx(ni,{className:"h-4 w-4"})]}):e.jsxs($,{onClick:Un,disabled:Q||!q||!V||!D.trim(),className:"gap-2",children:[Q?e.jsx(Ht,{className:"h-4 w-4 animate-spin"}):e.jsx(Br,{className:"h-4 w-4"}),Q?"Sending...":"Send Email"]})]})]}),Me==="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 ",nj,"."]}),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:fn=>et(fn.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(se,{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(fn=>e.jsxs("div",{className:`text-sm px-2 py-1 rounded cursor-pointer transition-colors ${(Mt==null?void 0:Mt.id)===fn.id?"bg-primary/10 text-primary font-medium":"text-muted-foreground hover:bg-accent hover:text-foreground"}`,onClick:()=>Ft(fn),children:[fn.first_name," ",fn.last_name," — ",fn.email]},fn.id))})]}),Mt&&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(nn,{className:"h-3.5 w-3.5"}),"Preview for ",Mt.first_name," ",Mt.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:"})," ",Mt.email]}),e.jsxs("p",{children:[e.jsx("span",{className:"text-muted-foreground text-xs",children:"Subject:"})," ",rj(he,Mt)]})]}),e.jsx(Hl,{}),_t?e.jsx("div",{className:"rounded-lg border bg-background max-h-72 overflow-y-auto [&_img]:max-w-full",dangerouslySetInnerHTML:{__html:rj(_t,Mt)}}):e.jsx("div",{className:"text-sm whitespace-pre-wrap bg-background rounded p-2.5 max-h-40 overflow-y-auto border",children:rj(ge,Mt)})]}),e.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[e.jsxs($,{variant:"outline",onClick:()=>{De("composing"),Ft(null)},children:[e.jsx(ka,{className:"h-4 w-4 mr-1"}),"Back to Edit"]}),e.jsxs($,{onClick:Un,disabled:Q,className:"gap-2",children:[Q?e.jsx(Ht,{className:"h-4 w-4 animate-spin"}):e.jsx(Br,{className:"h-4 w-4"}),I?`Send First ${nj}`:`Send to ${T.length}`]})]})]})]}),e.jsx(OEe,{open:g,onOpenChange:y,hasPending:!!(x!=null&&x.hasPendingSes),pendingEmails:x==null?void 0:x.pendingEmails})]})}function iNn(){const s=Vn(),{data:t}=E6t(),{data:n}=wee(),r=JCe(),{isGmailConnected:a,gmailEmail:i}=ux(),[l,o]=j.useState(null),[c,d]=j.useState(!1),[u,h]=j.useState(new Set),m=ep(new Date),p=Bd(m,30),x=A=>{if(!A)return null;const T=A.split(/[-/T]/);if(T.length<3)return null;const P=parseInt(T[1],10)-1,M=parseInt(T[2],10);return isNaN(P)||isNaN(M)?null:new Date(m.getFullYear(),P,M)},g=j.useMemo(()=>{if(!t)return[];const A=[];for(const T of t){if(T.birthday){const P=x(T.birthday);P&&(hu(P,m)||Pb(P,m)&&aw(P,p))&&A.push({contact:T,type:"birthday",date:P,daysUntil:av(P,m),dateStr:T.birthday})}if(T.home_anniversary){const P=x(T.home_anniversary);P&&(hu(P,m)||Pb(P,m)&&aw(P,p))&&A.push({contact:T,type:"anniversary",date:P,daysUntil:av(P,m),dateStr:T.home_anniversary})}if(T.wedding_anniversary){const P=x(T.wedding_anniversary);P&&(hu(P,m)||Pb(P,m)&&aw(P,p))&&A.push({contact:T,type:"wedding_anniversary",date:P,daysUntil:av(P,m),dateStr:T.wedding_anniversary})}}return A.sort((T,P)=>T.daysUntil-P.daysUntil),A},[t]),y=A=>A==="birthday"?"Birthday":A==="wedding_anniversary"?"Wedding Anniversary":"Home Anniversary",b=async A=>{const T=(n==null?void 0:n.find(P=>P.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(P=>new Set(P).add(`${A.contact.id}-${A.type}`)),ja({title:"Touch logged!",description:`Logged outreach for ${A.contact.first_name}`})}catch{ja({title:"Error",description:"Failed to log touch",variant:"destructive"})}},v=A=>{const T=`${A.contact.first_name}${A.contact.last_name?" "+A.contact.last_name:""}`,P=A.type==="birthday"?"birthday":A.type==="wedding_anniversary"?"wedding_anniversary":"home_anniversary",M=new URLSearchParams({cardType:P,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`,C=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(_e,{children:[e.jsx(Bt,{className:"pb-3",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(Ut,{className:"text-lg flex items-center gap-2",children:[e.jsx(Nl,{className:"h-5 w-5 text-primary"}),"Upcoming Milestones",e.jsx($e,{variant:"secondary",className:"text-xs font-normal",children:"Next 30 days"})]}),e.jsxs("span",{className:"text-sm text-muted-foreground",children:[g.length," event",g.length!==1?"s":""]})]})}),e.jsxs(Oe,{className:"space-y-2",children:[g.length===0&&e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(np,{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."})]}),g.map((A,T)=>{var D,B;const P=`${A.contact.id}-${A.type}`,M=u.has(P),I=`${((D=A.contact.first_name)==null?void 0:D[0])||""}${((B=A.contact.last_name)==null?void 0:B[0])||""}`.toUpperCase();return e.jsxs("div",{className:Tt("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:Tt("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:Tt("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($e,{variant:"outline",className:Tt("text-[10px] shrink-0 whitespace-nowrap",C(A.daysUntil)),children:N(A.daysUntil)})]}),e.jsxs("div",{className:Tt("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(np,{className:"h-3 w-3"})," Birthday"]}):A.type==="wedding_anniversary"?e.jsxs(e.Fragment,{children:[e.jsx(fo,{className:"h-3 w-3"})," Wedding Anniversary"]}):e.jsxs(e.Fragment,{children:[e.jsx(sa,{className:"h-3 w-3"})," Home Anniversary"]}),e.jsx("span",{children:"·"}),e.jsx("span",{children:Hs(A.date,"MMM d")})]})]})]}),e.jsxs("div",{className:"flex items-center gap-1 mt-2 pl-[52px]",children:[A.contact.phone&&e.jsx($,{variant:"ghost",size:"icon",className:"h-7 w-7",title:"Call",asChild:!0,children:e.jsx("a",{href:`tel:${A.contact.phone}`,children:e.jsx(ya,{className:"h-3.5 w-3.5"})})}),A.contact.phone&&e.jsx($,{variant:"ghost",size:"icon",className:"h-7 w-7",title:"Text",asChild:!0,children:e.jsx("a",{href:`sms:${A.contact.phone}`,children:e.jsx(Ji,{className:"h-3.5 w-3.5"})})}),A.contact.email&&e.jsx($,{variant:"ghost",size:"icon",className:"h-7 w-7",title:"Email",onClick:()=>{a?(o({id:A.contact.id,first_name:A.contact.first_name,last_name:A.contact.last_name,email:A.contact.email}),d(!0)):window.location.href=`mailto:${A.contact.email}`},children:e.jsx(nn,{className:"h-3.5 w-3.5"})}),e.jsx($,{variant:"ghost",size:"icon",className:"h-7 w-7",title:"Record video",onClick:()=>s(`/mission-control/video/record?contactId=${A.contact.id}`),children:e.jsx(Xr,{className:"h-3.5 w-3.5"})}),e.jsxs($,{variant:"ghost",size:"sm",className:Tt("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:()=>v(A),children:[e.jsx(dn,{className:"h-3.5 w-3.5"}),e.jsx("span",{children:"Card"})]}),e.jsx($,{variant:"ghost",size:"icon",className:Tt("h-7 w-7",M&&"text-green-600"),title:"Log a touch",disabled:M||r.isPending,onClick:()=>b(A),children:e.jsx(Fr,{className:"h-3.5 w-3.5"})}),e.jsx($,{variant:"ghost",size:"icon",className:"h-7 w-7",title:"View contact",onClick:()=>s(`/mission-control/contacts/${A.contact.id}`),children:e.jsx(ga,{className:"h-3.5 w-3.5"})})]})]},`${P}-${T}`)})]})]}),a&&l&&e.jsx(x2,{open:c,onOpenChange:d,contact:l,gmailEmail:i})]})}function oNn(s){const[t,n]=j.useState([]),[r,a]=j.useState(!1),{data:i,isLoading:l}=ht({queryKey:["active-visitors",s],queryFn:async()=>{if(!s)return[];try{await U.rpc("cleanup_stale_visitors")}catch{}const{data:u}=await U.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(x=>x.contact_id).filter(Boolean);let m={};if(h.length>0){const{data:x}=await U.from("innercircle_contacts").select("id, first_name, last_name, email, phone").in("id",h);(x||[]).forEach(g=>{m[g.id]=g})}const p=u.map(x=>x.auth_user_id).filter(Boolean);if(p.length>0){const{data:x}=await U.from("lead_site_consumer_profiles").select("user_id, name, phone, contact_id").eq("lead_site_id",s).in("user_id",p);(x||[]).forEach(g=>{const y=u.find(b=>b.auth_user_id===g.user_id);y&&!y.contact_id&&g.contact_id&&(y.contact_id=g.contact_id),y&&!m[y.contact_id||""]&&g.name&&(m[y.contact_id||y.auth_user_id||""]={first_name:g.name.split(" ")[0],last_name:g.name.split(" ").slice(1).join(" ")||null,email:null,phone:g.phone})})}return u.map(x=>{var g,y;return{...x,contact_name:m[x.contact_id||x.auth_user_id||""]?`${m[x.contact_id||x.auth_user_id||""].first_name} ${m[x.contact_id||x.auth_user_id||""].last_name||""}`.trim():null,contact_email:((g=m[x.contact_id||x.auth_user_id||""])==null?void 0:g.email)||null,contact_phone:((y=m[x.contact_id||x.auth_user_id||""])==null?void 0:y.phone)||null}})},enabled:!!s,refetchInterval:6e4});j.useEffect(()=>{if(!s)return;const u=U.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(x=>x.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()=>{U.removeChannel(u)}},[s]);const o=r&&t.length>0?lNn([...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 lNn(s){const t=new Set;return s.filter(n=>t.has(n.id)?!1:(t.add(n.id),!0))}const cNn={property_view:{label:"Viewed",icon:ga,color:"text-blue-500",bgColor:"bg-blue-500/10"},new_lead:{label:"New Lead",icon:il,color:"text-emerald-500",bgColor:"bg-emerald-500/10"},saved_listing:{label:"Saved",icon:fo,color:"text-rose-500",bgColor:"bg-rose-500/10"}};function dNn(){const{user:s}=_s(),t=Vn(),{isGmailConnected:n,gmailEmail:r}=ux(),{leadSite:a}=Mf(),{count:i}=oNn(a==null?void 0:a.id),[l,o]=j.useState(!1),[c,d]=j.useState(null),{data:u,isLoading:h}=ht({queryKey:["lead-site-activity",s==null?void 0:s.id],queryFn:async()=>{const{data:b,error:v}=await U.rpc("get_lead_site_activity",{_user_id:s.id});if(v)throw v;return b},enabled:!!s,refetchInterval:6e4});if(h||!(u!=null&&u.has_site))return null;const m=(u.activities||[]).filter(b=>b.visitor_name&&b.visitor_name!=="Site Visitor"),p=m.filter(b=>b.activity_type==="new_lead"),x=(u.activities||[]).filter(b=>b.activity_type==="property_view").length,g=(u.activities||[]).filter(b=>b.activity_type==="saved_listing").length,y=b=>{if(b.visitor_email)if(n){const v=(b.visitor_name||"").split(" ");d({id:b.contact_id||"",first_name:v[0]||"",last_name:v.slice(1).join(" ")||null,email:b.visitor_email}),o(!0)}else window.location.href=`mailto:${b.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(Gl,{className:"h-5 w-5 text-primary"})}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("h2",{className:"text-lg font-semibold",children:"Website Activity"}),i>0&&e.jsxs("span",{className:"inline-flex items-center gap-1 px-2 py-0.5 rounded-full bg-emerald-500/10 text-emerald-600 dark:text-emerald-400 text-[11px] font-semibold",children:[e.jsxs("span",{className:"relative flex h-1.5 w-1.5",children:[e.jsx("span",{className:"animate-ping absolute inline-flex h-full w-full rounded-full bg-emerald-400 opacity-75"}),e.jsx("span",{className:"relative inline-flex rounded-full h-1.5 w-1.5 bg-emerald-500"})]}),i," Live"]})]})]}),e.jsxs($,{variant:"ghost",size:"sm",className:"text-primary gap-1",onClick:()=>t("/mission-control/website-activity"),children:["View All",e.jsx(ni,{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(il,{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(ga,{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:x}),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(fo,{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:g}),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((b,v)=>{const N=cNn[b.activity_type],C=N.icon,A=fc(new Date(b.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(C,{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:()=>{b.contact_id&&t(`/mission-control/contacts/${b.contact_id}`)},children:b.visitor_name}),e.jsxs("div",{className:"flex items-center gap-2 text-[11px] text-muted-foreground",children:[e.jsx("span",{children:N.label}),b.mls_number&&e.jsxs("span",{children:["· MLS# ",b.mls_number]}),b.lead_type&&e.jsxs("span",{children:["· ",b.lead_type]}),e.jsxs("span",{children:["· ",A]})]})]}),e.jsxs("div",{className:"flex items-center gap-0.5 shrink-0",children:[b.visitor_email&&e.jsx($,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0 text-primary",onClick:()=>y(b),children:e.jsx(nn,{className:"h-3.5 w-3.5"})}),b.visitor_phone&&e.jsxs(e.Fragment,{children:[e.jsx($,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0 text-primary",onClick:()=>window.location.href=`tel:${b.visitor_phone}`,children:e.jsx(ya,{className:"h-3.5 w-3.5"})}),e.jsx($,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0 text-primary",onClick:()=>window.location.href=`sms:${b.visitor_phone}`,children:e.jsx(Ji,{className:"h-3.5 w-3.5"})})]}),b.contact_id&&e.jsx($,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:()=>t(`/mission-control/contacts/${b.contact_id}`),children:e.jsx(Ja,{className:"h-3.5 w-3.5"})})]})]},`${b.activity_type}-${b.occurred_at}-${v}`)}),m.length>5&&e.jsxs($,{variant:"outline",className:"w-full text-xs",onClick:()=>t("/mission-control/website-activity"),children:["View ",m.length-5," more activities",e.jsx(ni,{className:"h-3.5 w-3.5 ml-1"})]})]}):e.jsx(_e,{children:e.jsxs(Oe,{className:"p-6 text-center",children:[e.jsx(zp,{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:x>0?`${x} anonymous listing views recorded.`:"Lead engagement will appear here as visitors interact with your site."}),e.jsxs($,{variant:"outline",size:"sm",className:"mt-3",onClick:()=>t("/mission-control/website-activity"),children:["View Full Activity",e.jsx(ni,{className:"h-3.5 w-3.5 ml-1"})]})]})}),n&&c&&e.jsx(x2,{open:l,onOpenChange:o,contact:c,gmailEmail:r})]})}const qxt={Crown:Ng,FileText:Wr,Users:qn,Globe:Gl,Star:Qa,Phone:ya,MessageSquare:Ji,PenTool:kT,Video:Xr,Gift:Co},uNn={"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 hNn(){var ft,lt,Mt,Ft,Ts,js;const s=Vn(),{user:t}=_s(),{data:n}=Hb(),{data:r}=T6t(),{data:a}=M1(),{data:i}=wee(),{data:l}=xGe(),o=xAs(),c=eAe(),d=mAs(90),u=JCe(),[h,m]=j.useState(null),[p,x]=j.useState(null),[g,y]=j.useState(!1),[b,v]=j.useState(""),[N,C]=j.useState(!1),[A,T]=j.useState(""),[P,M]=j.useState(I6t()),[I,D]=j.useState("cards"),[B,q]=j.useState(!1),[W,V]=j.useState(null),[K,Q]=j.useState(null),[J,ce]=j.useState(""),{isGmailConnected:ue,gmailEmail:ne}=ux(),ee=()=>{const zt=parseInt(A,10);if(isNaN(zt)||zt<1){ja({title:"Invalid goal",description:"Please enter a number greater than 0",variant:"destructive"});return}M(zt),pAs(zt),C(!1),ja({title:"Goal updated",description:`Weekly touch goal set to ${zt}`})},le=()=>{T(P.toString()),C(!0)};j.useEffect(()=>{(async()=>{if(!(t!=null&&t.id))return;const{data:Nt}=await U.from("profiles").select("name").eq("id",t.id).single();Nt!=null&&Nt.name&&v(Nt.name.split(" ")[0])})()},[t==null?void 0:t.id]),j.useEffect(()=>{o.mutate()},[]);const he=ep(new Date),ve=Bd(he,7),ge=zt=>{if(!zt)return null;const Nt=zt.split(/[-/T]/);if(Nt.length<3)return null;const Ds=parseInt(Nt[1],10)-1,_t=parseInt(Nt[2],10);return isNaN(Ds)||isNaN(_t)?null:new Date(he.getFullYear(),Ds,_t)},fe=(a==null?void 0:a.filter(zt=>{const Nt=ge(zt.birthday),Ds=ge(zt.home_anniversary);return Nt&&hu(Nt,he)||Ds&&hu(Ds,he)}))||[],je=(a==null?void 0:a.filter(zt=>{if(!zt.birthday&&!zt.home_anniversary)return!1;const Nt=Ds=>{if(!Ds)return!1;const _t=ge(Ds);return _t?Pb(_t,he)&&aw(_t,ve):!1};return Nt(zt.birthday)||Nt(zt.home_anniversary)}).slice(0,5))||[],Ee=[],Me=(i==null?void 0:i.find(zt=>zt.name==="Call"))||(i==null?void 0:i[0]);for(const zt of fe){const Nt=ge(zt.birthday),Ds=ge(zt.home_anniversary),_t=Nt&&hu(Nt,he),Xs=Ds&&hu(Ds,he);_t&&Ee.push({contact:zt,actionType:Me||{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:((Mt=(lt=(ft=zt.tags)==null?void 0:ft[0])==null?void 0:lt.relationship_type)==null?void 0:Mt.name)||"",monthNumber:0,isSpecialDate:!0,specialDateType:"birthday"}),Xs&&Ee.push({contact:zt,actionType:Me||{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:((js=(Ts=(Ft=zt.tags)==null?void 0:Ft[0])==null?void 0:Ts.relationship_type)==null?void 0:js.name)||"",monthNumber:0,isSpecialDate:!0,specialDateType:"anniversary"})}const ze=l!==void 0?l||[]:(a==null?void 0:a.slice(0,5).map((zt,Nt)=>{var _t,Xs,rn;const Ds=i==null?void 0:i[Nt%((i==null?void 0:i.length)||1)];return Ds?{contact:zt,actionType:Ds,planName:"Quick Touch",relationshipTypeName:((rn=(Xs=(_t=zt.tags)==null?void 0:_t[0])==null?void 0:Xs.relationship_type)==null?void 0:rn.name)||"",monthNumber:0}:null}).filter(Boolean))||[],ke=[...Ee,...ze],{data:Xe}=Rq(7),Se=(Xe||[]).filter(zt=>hu(new Date(zt.completed_at),he)).length,Re=Se+ke.length,Ae=(a==null?void 0:a.length)??0,Be=Ee.length>0?`${Ee.length} celebration${Ee.length===1?"":"s"} today — a card or a call goes a long way.`:d.count>0?`${d.count} people haven't heard from you in 90+ days. Start with one.`:je.length>0?`${je.length} milestone${je.length===1?"":"s"} coming up this week — get ahead of them.`:"Consistency beats intensity. A few real conversations today is a win.",qe=async(zt,Nt,Ds)=>{await u.mutateAsync({contactId:zt,actionTypeId:Nt,scriptUsedId:Ds}),y(!1),x(null)},Ke=zt=>{zt.script?(x(zt),y(!0)):qe(zt.contact.id,zt.actionType.id)},Ze=zt=>qxt[zt||"Phone"]||ya,Ue=zt=>qxt[zt||"Users"]||qn,et=(zt,Nt)=>zt.replace(/\{\{FirstName\}\}/g,Nt.first_name).replace(/\{\{LastName\}\}/g,Nt.last_name||"").replace(/\{\{AgentName\}\}/g,b||"there"),Qe=(zt,Nt)=>({Call:`Thinking of you, ${Nt}!`,Text:`Quick hello, ${Nt}`,Email:`Checking in, ${Nt}`,"Handwritten Note":`A note for ${Nt}`,Video:`Video message for ${Nt}`,Gift:`Something special for you, ${Nt}`})[zt]||`Hello ${Nt}!`,Ge=(zt,Nt,Ds)=>{const _t=`sms:${zt}`;if(Nt&&Ds){const Xs=et(Nt,Ds);return`${_t}?body=${encodeURIComponent(Xs)}`}return _t},nt=(zt,Nt,Ds,_t,Xs)=>{const rn=`mailto:${zt}`,Ps=[];if(Xs){const _n=Ds||Qe(_t||"Email",Xs.first_name);if(Ps.push(`subject=${encodeURIComponent(_n)}`),Nt){const Zs=et(Nt,Xs);Ps.push(`body=${encodeURIComponent(Zs)}`)}}return Ps.length>0?`${rn}?${Ps.join("&")}`:rn};return e.jsxs(e.Fragment,{children:[e.jsxs(Ks,{title:"Mission Control",description:"Your relationship-first contact system",children:[e.jsxs("div",{className:"space-y-6 overflow-x-hidden",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[e.jsxs("div",{className:"flex items-center gap-2.5",children:[e.jsx("h1",{className:"text-2xl font-bold tracking-tight",children:"Mission Control"}),e.jsx("span",{className:"text-[10px] font-semibold uppercase tracking-wide px-1.5 py-0.5 rounded border border-amber-500 text-amber-600 dark:text-amber-400 bg-amber-500/10",children:"Beta"})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs($,{size:"sm",onClick:()=>s("/mission-control/video/record"),className:"gap-1.5 bg-gradient-to-r from-primary to-primary/80",children:[e.jsx(lh,{className:"h-4 w-4"}),"Quick Video"]}),e.jsxs($,{size:"sm",variant:"outline",onClick:()=>s("/mission-control/contacts"),className:"gap-1.5",children:[e.jsx(qn,{className:"h-4 w-4"}),"Contacts"]}),e.jsxs($,{size:"sm",variant:"outline",onClick:()=>s("/mission-control/video-library"),className:"gap-1.5",children:[e.jsx(Xr,{className:"h-4 w-4"}),"Library"]}),e.jsxs($,{size:"sm",variant:"outline",onClick:()=>s("/mission-control/plans"),className:"gap-1.5",children:[e.jsx(pc,{className:"h-4 w-4"}),"Plans"]})]})]}),e.jsx(q2n,{agentName:b,todayDone:Se,todayTotal:Re,focusLine:Be,weekDone:c.actionsThisWeek,weekGoal:P,streak:c.streak,staleCount:d.count,sphereCount:Ae,onEditGoal:le,onStaleClick:()=>s("/mission-control/contacts?filter=not-touched-90"),onSphereClick:()=>s("/mission-control/contacts")}),e.jsx(dNn,{}),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(Ja,{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 Nt=Ue(zt.icon),Ds=(r==null?void 0:r[zt.id])||0,_t=h===zt.id,Xs=uNn[zt.name]||"bg-secondary text-secondary-foreground";return e.jsxs("button",{onClick:()=>{_t?(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 ${_t?Xs:"bg-card hover:bg-accent"} `,children:[e.jsx(Nt,{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 ${_t?"bg-black/15":"bg-muted text-muted-foreground"}`,children:Ds})]},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($e,{variant:"outline",className:"gap-1",children:[e.jsx(dn,{className:"h-3 w-3"}),"Plan-based"]}),e.jsxs("div",{className:"ml-auto flex items-center gap-1 border rounded-lg p-0.5",children:[e.jsx($,{variant:I==="cards"?"secondary":"ghost",size:"sm",className:"h-7 px-2",onClick:()=>D("cards"),title:"Card view",children:e.jsx(_0,{className:"h-4 w-4"})}),e.jsx($,{variant:I==="table"?"secondary":"ghost",size:"sm",className:"h-7 px-2",onClick:()=>D("table"),title:"Table view",children:e.jsx(Sg,{className:"h-4 w-4"})})]})]}),e.jsx(_e,{children:e.jsx(Oe,{className:"p-4",children:ke.length===0?e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx("p",{children:"No actions scheduled for today."}),e.jsx("p",{className:"text-sm mt-1",children:"Add contacts and enable touchpoint plans to get started."}),e.jsx($,{variant:"outline",className:"mt-4",onClick:()=>s("/mission-control/plans"),children:"Manage Plans"})]}):I==="table"?e.jsx(Z2n,{actions:ke,onMarkComplete:qe,onViewScript:Ke,isLoading:u.isPending,buildSmsLink:Ge,buildEmailLink:nt,onGmailCompose:ue?zt=>{V(zt),q(!0)}:void 0}):e.jsxs("div",{className:"flex gap-3 overflow-x-auto pb-2",children:[ke.map((zt,Nt)=>{var gr,Un,In,Ar,or,qs,yr;const Ds=zt.isSpecialDate,_t=zt.specialDateType,Xs=Ds?_t==="birthday"?np:sa:Ze(((gr=zt.actionType)==null?void 0:gr.icon)||null),rn=zt.contact.phone,Ps=zt.contact.email,_n=Ds?_t==="birthday"?"#EC4899":"#8B5CF6":((Un=zt.actionType)==null?void 0:Un.color)||"#3B82F6",Zs=Ds?_t==="birthday"?"🎂 Birthday Today!":"🏠 Home Anniversary!":(In=zt.actionType)==null?void 0:In.name;return e.jsxs("div",{className:`flex-shrink-0 w-[260px] border rounded-lg overflow-hidden ${Ds?"ring-2 ring-offset-2":""}`,style:Ds?{"--tw-ring-color":_n}:void 0,children:[e.jsxs("div",{className:"p-3 text-white flex items-center gap-2",style:{backgroundColor:_n},children:[e.jsx(Xs,{className:"h-4 w-4"}),e.jsx("span",{className:"font-medium text-sm",children:Zs})]}),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:[rn&&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(ya,{className:"h-3 w-3"}),"Call"]}),e.jsxs("a",{href:Ge(zt.contact.phone,(Ar=zt.script)==null?void 0:Ar.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(Ji,{className:"h-3 w-3"}),"Text"]})]}),Ps&&(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}),q(!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(nn,{className:"h-3 w-3"}),"Email"]}):e.jsxs("a",{href:nt(zt.contact.email,(or=zt.script)==null?void 0:or.script_body,(qs=zt.script)==null?void 0:qs.email_subject,(yr=zt.actionType)==null?void 0:yr.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(nn,{className:"h-3 w-3"}),"Email"]}))]}),Ds&&e.jsxs("button",{onClick:()=>{const fn=`${zt.contact.first_name}${zt.contact.last_name?" "+zt.contact.last_name:""}`,Zn=_t==="birthday"?"birthday":"home_anniversary",Xt=new URLSearchParams({cardType:Zn,contactId:zt.contact.id,name:fn,...zt.contact.address?{address:zt.contact.address}:{},..._t==="anniversary"&&zt.contact.home_anniversary?{date:zt.contact.home_anniversary}:{}});s(`/mission-control/card-studio?${Xt.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(nn,{className:"h-3 w-3"}),"Send ",_t==="birthday"?"Birthday":"Anniversary"," Card"]}),!rn&&!Ps&&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($e,{variant:"secondary",className:"text-xs",children:zt.relationshipTypeName}),zt.monthNumber>0&&e.jsxs($e,{variant:"outline",className:"text-xs",children:["Month ",zt.monthNumber]})]}),zt.script&&e.jsx($,{size:"sm",variant:"outline",className:"w-full",onClick:()=>Ke(zt),children:"View Script"}),e.jsxs("div",{className:"flex gap-1.5",children:[e.jsxs($,{size:"sm",variant:"outline",className:"flex-1 gap-1",onClick:()=>{Q(zt.contact.id),ce(`${zt.contact.first_name} ${zt.contact.last_name||""}`.trim())},children:[e.jsx(vy,{className:"h-3.5 w-3.5"}),"Snooze"]}),e.jsx($,{size:"sm",className:"flex-1",onClick:()=>{var fn;return qe(zt.contact.id,zt.actionType.id,(fn=zt.script)==null?void 0:fn.id)},disabled:u.isPending,children:"Mark Complete"})]})]})]},zt.contact.id+Nt)}),e.jsx("div",{className:"flex-shrink-0 w-[100px] border rounded-lg flex items-center justify-center",children:e.jsxs(Hd,{children:[e.jsx(Gd,{asChild:!0,children:e.jsxs($,{variant:"ghost",className:"h-full w-full",children:[e.jsx(p0,{className:"h-5 w-5 mr-2"}),"More"]})}),e.jsx(Md,{children:e.jsx(Na,{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(yd,{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 ",P," touches"]})]}),e.jsx(Ki,{value:Math.min(c.actionsThisWeek/P*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>=P?"Goal hit for the week — anything else is bonus.":`${P-c.actionsThisWeek} more to hit your goal.`})]}),e.jsx(Os,{open:N,onOpenChange:C,children:e.jsxs(Rs,{className:"sm:max-w-[360px]",children:[e.jsxs(Us,{children:[e.jsx(zs,{children:"Set Weekly Goal"}),e.jsx(Sr,{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(se,{htmlFor:"weekly-goal-ic",children:"Weekly touch goal"}),e.jsx(be,{id:"weekly-goal-ic",type:"number",min:"1",value:A,onChange:zt=>T(zt.target.value),placeholder:"20",onKeyDown:zt=>{zt.key==="Enter"&&ee()}})]}),e.jsx($,{onClick:ee,className:"w-full",children:"Save Goal"})]})]})}),e.jsxs("div",{className:"grid md:grid-cols-2 gap-6",children:[e.jsx(O6t,{}),e.jsx(iNn,{})]})]}),e.jsx(Os,{open:g,onOpenChange:y,children:e.jsxs(Rs,{className:"max-w-md",children:[e.jsx(Us,{children:e.jsx(zs,{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:et(p.script.script_body,p.contact)})}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx($,{variant:"outline",className:"flex-1",onClick:()=>y(!1),children:"Close"}),e.jsx($,{className:"flex-1",onClick:()=>{var zt;return qe(p.contact.id,p.actionType.id,(zt=p.script)==null?void 0:zt.id)},disabled:u.isPending,children:"Mark Complete"})]})]})]})}),e.jsx(V2n,{})]}),ue&&W&&e.jsx(x2,{open:B,onOpenChange:q,contact:W,gmailEmail:ne}),e.jsx(qEe,{open:!!K,onOpenChange:zt=>!zt&&Q(null),contactId:K||"",contactName:J})]})}const mNn=[{value:"bidirectional",label:"Two-Way",icon:Tx,tooltip:"Sync contacts in both directions"},{value:"push_only",label:"Push Only",icon:sp,tooltip:"Only push Agent OS → BoldTrail"},{value:"pull_only",label:"Pull Only",icon:ax,tooltip:"Only pull BoldTrail → Agent OS"}];function h4e({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(iB,{type:"single",value:s,onValueChange:a=>{a&&t(a)},className:"justify-start",children:mNn.map(a=>e.jsxs(Mx,{children:[e.jsx(Lx,{asChild:!0,children:e.jsxs(OR,{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(tx,{children:a.tooltip})]},a.value))})]})}function pNn(){const s=ts(),[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,x]=j.useState(0),g=j.useRef(!1),{data:y}=ht({queryKey:["boldtrail-status"],queryFn:async()=>{const{data:I,error:D}=await U.functions.invoke("boldtrail-sync",{body:{action:"status"}});if(D)throw D;return I}}),b=(y==null?void 0:y.sync_direction)||"bidirectional",v=d??b,N=yt({mutationFn:async()=>{const{data:I,error:D}=await U.functions.invoke("boldtrail-sync",{body:{action:"sync_preview"}});if(D)throw D;if(I!=null&&I.error)throw new Error(I.error);return I},onSuccess:I=>{u(null),a(I),n(!0)},onError:I=>{ae.error(I.message||"Failed to generate sync preview")}}),C=yt({mutationFn:async()=>{g.current=!1,m("Initializing sync..."),x(5);const{data:I,error:D}=await U.functions.invoke("boldtrail-sync",{body:{action:"sync",phase:"init",sync_direction:v}});if(D)throw D;if(I!=null&&I.error)throw new Error(I.error);const B=I;let q=B.sync_log_id,W=B.next_phase,V=B.next_offset,K=B.push_total||0,Q=B.pull_total||0,J=B.update_total||0,ce=0,ue=0,ne=0;for(;W!=="finalize"&&!g.current;){const he=K+Q+J;W==="fetch_bt"?m("Fetching BoldTrail contacts..."):W==="analyze"?(m("Analyzing contacts..."),x(15)):W==="push"?(m(`Pushing contacts to BoldTrail... (${ce}/${K})`),x(he>0?ce/he*90:0)):W==="pull"?(m(`Pulling contacts from BoldTrail... (${ue}/${Q})`),x(he>0?(K+ue)/he*90:0)):W==="update"&&(m(`Updating existing contacts... (${ne}/${J})`),x(he>0?(K+Q+ne)/he*90:0));const{data:ve,error:ge}=await U.functions.invoke("boldtrail-sync",{body:{action:"sync",phase:W,offset:V,sync_log_id:q,sync_direction:v}});if(ge)throw ge;if(ve!=null&&ve.error)throw new Error(ve.error);const fe=ve;ce+=fe.chunk_pushed||0,ue+=fe.chunk_pulled||0,ne+=fe.chunk_updated||0,fe.push_total!==void 0&&(K=fe.push_total||0),fe.pull_total!==void 0&&(Q=fe.pull_total||0),fe.update_total!==void 0&&(J=fe.update_total||0),fe.progress&&m(fe.progress),W=fe.next_phase,V=fe.next_offset}m("Finalizing sync..."),x(95);const{data:ee,error:le}=await U.functions.invoke("boldtrail-sync",{body:{action:"sync",phase:"finalize",sync_log_id:q,sync_direction:v}});if(le)throw le;return x(100),ee},onSuccess:I=>{m(null),x(0),n(!1),s.invalidateQueries({queryKey:["boldtrail-status"]}),s.invalidateQueries({queryKey:["innercircle-contacts"]}),s.invalidateQueries({queryKey:["innercircle-contact-counts"]}),s.invalidateQueries({queryKey:["contacts-last-touch"]});const D=[`Pushed ${I.contacts_pushed||0}`,`pulled ${I.contacts_pulled||0}`,`updated ${I.contacts_updated||0}`,`skipped ${I.contacts_skipped||0} duplicates`];ae.success(`Sync complete! ${D.join(", ")}.`)},onError:I=>{m(null),x(0),ae.error(I.message||"Sync failed")}});if(!(y!=null&&y.connected))return null;const A=v==="pull_only"?0:(r==null?void 0:r.to_push)??0,T=v==="push_only"?0:(r==null?void 0:r.to_pull)??0,P=(r==null?void 0:r.to_update)??0,M=A>0||T>0||P>0;return e.jsxs(e.Fragment,{children:[e.jsxs(Mx,{children:[e.jsx(Lx,{asChild:!0,children:e.jsx($,{variant:"outline",size:"icon",onClick:()=>N.mutate(),disabled:N.isPending,className:"shrink-0",children:N.isPending?e.jsx(Wi,{className:"h-4 w-4 animate-spin"}):e.jsx(Tx,{className:"h-4 w-4 text-emerald-600"})})}),e.jsx(tx,{children:"Sync with BoldTrail"})]}),e.jsx(Os,{open:t,onOpenChange:I=>{C.isPending||n(I)},children:e.jsxs(Rs,{className:"sm:max-w-lg",children:[e.jsxs(Us,{children:[e.jsxs(zs,{className:"flex items-center gap-2",children:[e.jsx(Tx,{className:"h-5 w-5 text-emerald-600"}),"Sync Preview"]}),e.jsx(Sr,{children:"Review what will happen when you sync your contacts."})]}),r&&e.jsxs("div",{className:"space-y-4",children:[e.jsx(h4e,{value:v,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 ${v==="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(sp,{className:"h-3 w-3"})," Push to BoldTrail"]})]}),e.jsxs("div",{className:`rounded-lg border p-3 text-center ${v==="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(ax,{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:P}),e.jsxs("p",{className:"text-xs text-muted-foreground flex items-center justify-center gap-1",children:[e.jsx(Rz,{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(qn,{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"]}),P>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(Rz,{className:"h-3 w-3 inline mr-1"}),P," contacts have missing fields that will be filled from the other system"]}),A>0&&e.jsxs(uv,{open:i,onOpenChange:l,children:[e.jsx(hv,{asChild:!0,children:e.jsxs($,{variant:"ghost",size:"sm",className:"w-full justify-between text-xs",children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(sp,{className:"h-3 w-3 text-emerald-600"}),A," contacts to push to BoldTrail"]}),e.jsx(_o,{className:`h-3 w-3 transition-transform ${i?"rotate-180":""}`})]})}),e.jsx(mv,{children:e.jsxs("div",{className:"rounded border divide-y max-h-40 overflow-y-auto",children:[r.push_preview.map((I,D)=>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})]},D)),r.to_push>20&&e.jsxs("div",{className:"px-3 py-1.5 text-xs text-muted-foreground text-center",children:["...and ",r.to_push-20," more"]})]})})]}),T>0&&e.jsxs(uv,{open:o,onOpenChange:c,children:[e.jsx(hv,{asChild:!0,children:e.jsxs($,{variant:"ghost",size:"sm",className:"w-full justify-between text-xs",children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(ax,{className:"h-3 w-3 text-blue-600"}),T," contacts to pull from BoldTrail"]}),e.jsx(_o,{className:`h-3 w-3 transition-transform ${o?"rotate-180":""}`})]})}),e.jsx(mv,{children:e.jsxs("div",{className:"rounded border divide-y max-h-40 overflow-y-auto",children:[r.pull_preview.map((I,D)=>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})]},D)),r.to_pull>20&&e.jsxs("div",{className:"px-3 py-1.5 text-xs text-muted-foreground text-center",children:["...and ",r.to_pull-20," more"]})]})})]}),!M&&!C.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."}),C.isPending&&e.jsxs("div",{className:"space-y-2 py-2",children:[e.jsx(Ki,{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($,{variant:"outline",onClick:()=>n(!1),disabled:C.isPending,children:"Cancel"}),e.jsxs($,{onClick:()=>C.mutate(),disabled:C.isPending||!M,className:"gap-2",children:[C.isPending?e.jsx(Wi,{className:"h-4 w-4 animate-spin"}):e.jsx(Tx,{className:"h-4 w-4"}),C.isPending?"Syncing...":"Sync Now"]})]})]})]})})]})}const fNn=()=>{const{user:s}=_s();return ht({queryKey:["popby-items",s==null?void 0:s.id],queryFn:async()=>{const{data:t,error:n}=await U.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})},HEe=s=>{const{user:t}=_s();return ht({queryKey:["popby-logs",t==null?void 0:t.id,s],queryFn:async()=>{let n=U.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})},EYe=()=>{const{user:s}=_s();return ht({queryKey:["relationship-type-popby-defaults",s==null?void 0:s.id],queryFn:async()=>{const{data:t,error:n}=await U.from("relationship_type_popby_defaults").select("*");if(n)throw n;return t},enabled:!!s})},S7t=()=>{const{user:s}=_s();return ht({queryKey:["contact-popby-settings",s==null?void 0:s.id],queryFn:async()=>{const{data:t,error:n}=await U.from("contact_popby_settings").select("*");if(n)throw n;return t},enabled:!!s})},xNn=()=>{const{data:s}=M1();Hb();const{data:t}=HEe(),{data:n}=S7t(),{data:r}=EYe(),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=ep(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 g=d.tags.map(y=>i.get(y.relationship_type_id)).filter(y=>y!==void 0);g.length>0&&(u=Math.min(...g))}const h=a.get(d.id)||null,m=h?r2(o,ep(new Date(h))):null,p=m===null||m>=u,x=p&&m!==null?m-u:0;return{...d,lastPopby:h,daysSinceLastPopby:m,frequencyDays:u,isDue:p,daysOverdue:x}}).sort((d,u)=>u.daysOverdue-d.daysOverdue)},C7t=()=>xNn().filter(t=>t.isDue),gNn=()=>{const s=ts(),{user:t}=_s();return yt({mutationFn:async n=>{const{error:r}=await U.from("popby_items").insert({...n,owner_user_id:t==null?void 0:t.id});if(r)throw r},onSuccess:()=>{s.invalidateQueries({queryKey:["popby-items"]}),ja({title:"Popby item created!"})},onError:n=>{ja({title:"Error creating popby item",description:n.message,variant:"destructive"})}})},yNn=()=>{const s=ts(),{user:t}=_s();return yt({mutationFn:async n=>{const r=new Date().toISOString(),{error:a}=await U.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 U.from("action_types").select("id").ilike("name","Pop-By").eq("active",!0).maybeSingle();i!=null&&i.id&&await U.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"]}),ja({title:"Popby logged!"})},onError:n=>{ja({title:"Error logging popby",description:n.message,variant:"destructive"})}})},vNn=()=>{const s=ts(),{user:t}=_s();return yt({mutationFn:async n=>{const{error:r}=await U.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"]}),ja({title:"Frequency updated!"})},onError:n=>{ja({title:"Error updating frequency",description:n.message,variant:"destructive"})}})},bNn=()=>{const{data:s}=HEe(30),t=C7t(),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 _Nn(){const{user:s}=_s();return ht({queryKey:["contact-touch-logs",s==null?void 0:s.id],queryFn:async()=>{const{data:t,error:n}=await U.from("contact_touch_logs").select("*").order("completed_at",{ascending:!1});if(n)throw n;return t},enabled:!!s})}function A7t(s){const{data:t}=_Nn(),{data:n}=S7t(),{data:r}=EYe(),{data:a}=H2n();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=ep(new Date);if(l&&!aw(l,o))return{nextTouchDate:l,daysUntil:r2(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,b)=>new Date(b.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(b=>{const v=r==null?void 0:r.find(N=>N.relationship_type_id===b.relationship_type_id);return v==null?void 0:v.frequency_days}).filter(b=>b!==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=Bd(ep(u),h),x=r2(p,o);let g;return x<0?g="overdue":x<=7?g="due-soon":g="on-track",{nextTouchDate:p,daysUntil:x,status:g,frequencyDays:h,lastTouchDate:u,snoozedUntil:null}},[s,t,n,r,a])}function Vxt({contact:s}){const t=A7t(s),r=(()=>{switch(t.status){case"overdue":return{variant:"destructive",icon:xo,text:`${Math.abs(t.daysUntil)} days overdue`,className:""};case"due-soon":return{variant:"secondary",icon:Hr,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:Fr,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:vy,text:`Snoozed until ${Hs(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:ia,text:"Never touched",className:"border-dashed"}}})(),a=r.icon;return e.jsxs($e,{variant:r.variant,className:Tt("gap-1",r.className),children:[e.jsx(a,{className:"h-3 w-3"}),r.text]})}function wNn({contact:s,onLogTouch:t,onSnooze:n}){const r=A7t(s),a=W2n(),[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(xo,{className:"h-5 w-5 text-destructive"});case"due-soon":return e.jsx(Hr,{className:"h-5 w-5 text-amber-600 dark:text-amber-400"});case"on-track":return e.jsx(Fr,{className:"h-5 w-5 text-emerald-600 dark:text-emerald-400"});case"snoozed":return e.jsx(vy,{className:"h-5 w-5 text-slate-600 dark:text-slate-400"});case"never-touched":return e.jsx(ia,{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(_e,{children:[e.jsx(Bt,{className:"pb-2",children:e.jsxs(Ut,{className:"text-sm font-medium flex items-center gap-2",children:[e.jsx(ia,{className:"h-4 w-4"}),"Next Touch"]})}),e.jsxs(Oe,{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[c(),e.jsx("span",{className:Tt("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:"})," ",Hs(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:"})," ",Hs(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:"})," ",Hs(r.lastTouchDate,"MMM d, yyyy")]}),r.status!=="snoozed"&&e.jsxs("div",{className:"text-xs text-muted-foreground border-t pt-2",children:["Touch frequency: Every ",r.frequencyDays," days"]}),r.status==="snoozed"&&e.jsxs("div",{className:"flex gap-2 pt-1",children:[e.jsxs($,{size:"sm",variant:"outline",className:"flex-1",onClick:u,disabled:a.isPending,children:[e.jsx(pr,{className:"h-4 w-4 mr-1"}),"Cancel Snooze"]}),t&&e.jsx($,{size:"sm",className:"flex-1",onClick:t,children:"Log Touch"})]}),r.status!=="snoozed"&&e.jsxs("div",{className:"flex gap-2 pt-1",children:[e.jsxs($,{size:"sm",variant:"outline",className:"flex-1",onClick:()=>l(!0),children:[e.jsx(vy,{className:"h-4 w-4 mr-1"}),"Snooze"]}),(r.status==="overdue"||r.status==="due-soon"||r.status==="never-touched")&&t&&e.jsx($,{size:"sm",className:"flex-1",variant:r.status==="overdue"?"default":"outline",onClick:t,children:"Log Touch"})]})]})]}),e.jsx(qEe,{open:i,onOpenChange:l,contactId:s.id,contactName:`${s.first_name} ${s.last_name||""}`.trim()})]})}const b8e=768;function dV(){const[s,t]=j.useState(void 0);return j.useEffect(()=>{const n=window.matchMedia(`(max-width: ${b8e-1}px)`),r=()=>{t(window.innerWidthn.removeEventListener("change",r)},[]),!!s}function jNn(){const{user:s}=_s(),{hasLeadSite:t,leadSite:n}=Mf(),{data:r,isLoading:a}=ht({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 U.from("lead_site_visitors").select("contact_id").eq("lead_site_id",n.id).not("contact_id","is",null),{data:l}=await U.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 NNn={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"}},kNn={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 rBe({score:s,showScore:t=!1,showTooltip:n=!0,size:r="sm",className:a}){const i=NNn[s.status],l=kNn[r],o=e.jsxs("div",{className:Tt("inline-flex items-center rounded-full font-medium",i.bgLightClass,i.textClass,l.badge,l.text,a),children:[e.jsx("span",{className:Tt("rounded-full",i.bgClass,l.dot)}),t?e.jsx("span",{children:s.score}):e.jsx("span",{children:i.label})]});return n?e.jsx(JN,{children:e.jsxs(Mx,{children:[e.jsx(Lx,{asChild:!0,children:o}),e.jsx(tx,{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:Tt("font-bold",i.textClass),children:[s.score,"/100"]})]}),e.jsx(Ki,{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 SNn=[{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}],$re=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]},CNn=({open:s,onOpenChange:t,relationshipTypes:n,onSuccess:r})=>{const{user:a}=_s(),{toast:i}=gi(),l=j.useRef(null),[o,c]=j.useState("upload"),[d,u]=j.useState([]),[h,m]=j.useState([]),[p,x]=j.useState({}),[g,y]=j.useState([]),[b,v]=j.useState([]),[N,C]=j.useState([]),[A,T]=j.useState(""),[P,M]=j.useState(!1),[I,D]=j.useState([]),[B,q]=j.useState(!1),[W,V]=j.useState(null);j.useEffect(()=>{!s||!(a!=null&&a.id)||(async()=>{const{data:De}=await U.from("contact_custom_tags").select("id, name, color").eq("owner_user_id",a.id).order("name");v(De||[])})()},[s,a==null?void 0:a.id]);const K=De=>{C(ze=>ze.includes(De)?ze.filter(ke=>ke!==De):[...ze,De])},Q=async()=>{const De=A.trim();if(!(!De||!(a!=null&&a.id))){M(!0);try{const{data:ze,error:ke}=await U.from("contact_custom_tags").insert({owner_user_id:a.id,name:De}).select("id, name, color").single();if(ke)throw ke;ze&&(v(Xe=>[...Xe,ze].sort((Se,Re)=>Se.name.localeCompare(Re.name))),C(Xe=>[...Xe,ze.id]),T(""))}catch(ze){i({title:"Could not create tag",description:ze.message||"Try a different name.",variant:"destructive"})}finally{M(!1)}}},J=()=>{c("upload"),u([]),m([]),x({}),y([]),C([]),T(""),D([]),V(null),l.current&&(l.current.value="")},ce=()=>{J(),t(!1)},ue=De=>{const ze=De.split(` `).map(Be=>Be.trim()).filter(Be=>Be);if(ze.length===0)return{headers:[],data:[]};const ke=Be=>{const qe=[];let Ke="",Ze=!1;for(let Ue=0;Ue0&&(Xe[0]=Xe[0].replace(/^\uFEFF/,""));const Se=new Map,Re=Xe.map((Be,qe)=>{let Ke=(Be||"").trim();Ke||(Ke=`Column ${qe+1}`);const Ze=Se.get(Ke)||0;return Se.set(Ke,Ze+1),Ze===0?Ke:`${Ke} (${Ze+1})`}),Ae=ze.slice(1).map(ke);return{headers:Re,data:Ae}},ne=De=>{var Xe;const ze=(Xe=De.target.files)==null?void 0:Xe[0];if(!ze)return;const ke=new FileReader;ke.onload=Se=>{var Ke;const Re=(Ke=Se.target)==null?void 0:Ke.result,{headers:Ae,data:Be}=ue(Re);if(Ae.length===0){i({title:"No data found",description:"The CSV file appears to be empty.",variant:"destructive"});return}u(Ae),m(Be);const qe={};Ae.forEach(Ze=>{const Ue=Ze.toLowerCase().replace(/[_\s-]/g,"");Ue.includes("firstname")||Ue==="first"?qe.first_name=Ze:Ue.includes("lastname")||Ue==="last"?qe.last_name=Ze:Ue.includes("spouse")&&Ue.includes("email")?qe.spouse_email=Ze:Ue.includes("spouse")||Ue.includes("partner")?qe.spouse_name=Ze:Ue.includes("email")?qe.email=Ze:Ue.includes("phone")||Ue.includes("mobile")||Ue.includes("cell")?qe.phone=Ze:Ue.includes("address")||Ue.includes("street")?qe.address=Ze:Ue==="city"?qe.city=Ze:Ue==="state"||Ue==="province"?qe.state=Ze:Ue==="zip"||Ue==="zipcode"||Ue==="postalcode"?qe.zip=Ze:Ue.includes("company")||Ue.includes("organization")||Ue.includes("business")?qe.company_name=Ze:Ue.includes("jobtitle")||Ue.includes("title")&&!Ue.includes("spouse")?qe.job_title=Ze:Ue.includes("birthday")||Ue.includes("dob")||Ue.includes("birthdate")?qe.birthday=Ze:Ue.includes("anniversary")||Ue.includes("homeanniversary")?qe.home_anniversary=Ze:(Ue.includes("notes")||Ue.includes("comment"))&&(qe.notes=Ze)}),x(qe),c("mapping")},ke.readAsText(ze)},ee=(De,ze)=>{x(ke=>{if(ze==="none"){const{[De]:Xe,...Se}=ke;return Se}return{...ke,[De]:ze}})},le=De=>{y(ze=>ze.includes(De)?ze.filter(ke=>ke!==De):[...ze,De])},he=async()=>{if(!(a!=null&&a.id))return;const{data:De}=await U.from("innercircle_contacts").select("id, email, phone").eq("owner_user_id",a.id),ze=new Set((De||[]).filter(Se=>Se.email).map(Se=>Se.email.toLowerCase())),ke=new Set((De||[]).filter(Se=>Se.phone).map(Se=>Se.phone.replace(/[^0-9]/g,""))),Xe=h.map(Se=>{const Re=Ue=>{const et=p[Ue];if(!et)return"";const Qe=d.indexOf(et);return Qe>=0?(Se[Qe]||"").trim():""},Ae=Re("first_name"),Be=Re("email"),qe=Re("phone"),Ke=Ae.length>0,Ze=!!(Be&&ze.has(Be.toLowerCase())||qe&&ke.has(qe.replace(/[^0-9]/g,"")));return{first_name:Ae,last_name:Re("last_name"),email:Be,phone:qe,address:Re("address"),city:Re("city"),state:Re("state"),zip:Re("zip"),spouse_name:Re("spouse_name"),spouse_email:Re("spouse_email"),company_name:Re("company_name"),job_title:Re("job_title"),birthday:Re("birthday"),home_anniversary:Re("home_anniversary"),notes:Re("notes"),isValid:Ke,isDuplicate:Ze,error:Ke?void 0:"First name is required"}});D(Xe),c("preview")},ve=De=>{const ze=De.trim().split(/\s+/);return{first_name:ze[0],last_name:ze.length>1?ze.slice(1).join(" "):null}},ge=async()=>{if(!(a!=null&&a.id))return;const De=I.filter(Se=>Se.isValid);if(De.length===0){i({title:"No valid contacts",description:"There are no valid contacts to import.",variant:"destructive"});return}q(!0);let ze=0,ke=0,Xe=0;try{for(const Se of De)try{let Re=null;if(Se.email){const{data:qe}=await U.from("innercircle_contacts").select("id").eq("owner_user_id",a.id).eq("email",Se.email).maybeSingle();Re=qe}if(!Re&&Se.phone){const qe=Se.phone.replace(/[^0-9]/g,""),{data:Ke}=await U.from("innercircle_contacts").select("id, phone").eq("owner_user_id",a.id).not("phone","is",null);if(Ke){const Ze=Ke.find(Ue=>Ue.phone&&Ue.phone.replace(/[^0-9]/g,"")===qe);Ze&&(Re={id:Ze.id})}}const Ae={owner_user_id:a.id,first_name:Se.first_name,last_name:Se.last_name||null,email:Se.email||null,phone:Se.phone||null,address:Se.address||null,city:Se.city||null,state:Se.state||null,zip:Se.zip||null,spouse_name:Se.spouse_name||null,spouse_email:Se.spouse_email||null,company_name:Se.company_name||null,job_title:Se.job_title||null,birthday:$re(Se.birthday),home_anniversary:$re(Se.home_anniversary),notes:Se.notes||null};let Be=null;if(Re){const{data:qe}=await U.from("innercircle_contacts").select("*").eq("id",Re.id).single();if(qe){const Ke={},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 et=qe[Ue],Qe=Ae[Ue];(!et||et==="")&&Qe&&(Ke[Ue]=Qe)}Object.keys(Ke).length>0&&await U.from("innercircle_contacts").update(Ke).eq("id",Re.id)}Be=Re.id,ke++}else{const{data:qe,error:Ke}=await U.from("innercircle_contacts").insert(Ae).select("id").single();Ke?(console.error("Insert error for contact:",Se.first_name,Ke),Xe++):qe?(Be=qe.id,g.length>0&&await U.from("innercircle_contact_tags").insert(g.map(Ze=>({contact_id:qe.id,relationship_type_id:Ze}))),ze++):Xe++}if(Be&&N.length>0&&await U.from("contact_custom_tag_assignments").upsert(N.map(qe=>({contact_id:Be,tag_id:qe})),{onConflict:"contact_id,tag_id",ignoreDuplicates:!0}),Be&&Se.spouse_name){const qe=ve(Se.spouse_name);let Ke=null;if(Se.spouse_email){const{data:Ue}=await U.from("innercircle_contacts").select("id").eq("owner_user_id",a.id).eq("email",Se.spouse_email).maybeSingle();Ke=Ue}if(!Ke){const{data:Ue}=await U.from("innercircle_contacts").select("id").eq("owner_user_id",a.id).eq("first_name",qe.first_name).eq("last_name",qe.last_name||Se.last_name||"").maybeSingle();Ke=Ue}let Ze=null;if(Ke){Ze=Ke.id;const Ue=$re(Se.home_anniversary);Ue&&await U.from("innercircle_contacts").update({home_anniversary:Ue}).eq("id",Ke.id).is("home_anniversary",null)}else{const{data:Ue}=await U.from("innercircle_contacts").insert({owner_user_id:a.id,first_name:qe.first_name,last_name:qe.last_name||Se.last_name||null,email:Se.spouse_email||null,address:Se.address||null,city:Se.city||null,state:Se.state||null,zip:Se.zip||null,home_anniversary:$re(Se.home_anniversary),spouse_name:`${Se.first_name}${Se.last_name?" "+Se.last_name:""}`,spouse_email:Se.email||null,notes:`Spouse of ${Se.first_name} ${Se.last_name||""} (imported via CSV)`.trim()}).select("id").single();Ue&&(Ze=Ue.id,ze++)}Ze&&(await U.from("innercircle_contacts").update({spouse_contact_id:Ze}).eq("id",Be),await U.from("innercircle_contacts").update({spouse_contact_id:Be}).eq("id",Ze))}}catch(Re){console.error("Error importing contact:",Re),Xe++}V({created:ze,updated:ke,failed:Xe}),c("result"),(ze>0||ke>0)&&r(),i({title:"Import Complete",description:`${ze} created, ${ke} updated${Xe>0?`, ${Xe} failed`:""}.`})}catch(Se){console.error("Import error:",Se),i({title:"Import Failed",description:Se.message||"Failed to import contacts",variant:"destructive"})}finally{q(!1)}},fe=I.filter(De=>De.isValid).length,je=I.filter(De=>!De.isValid).length,Ee=I.filter(De=>De.isValid&&De.isDuplicate).length,Me=fe-Ee;return e.jsx(Os,{open:s,onOpenChange:ce,children:e.jsxs(Rs,{className:"max-w-3xl max-h-[85vh] overflow-hidden flex flex-col",children:[e.jsxs(Us,{children:[e.jsxs(zs,{className:"flex items-center gap-2",children:[e.jsx(PN,{className:"h-5 w-5"}),"Import Contacts from CSV"]}),e.jsx(Sr,{children:"Upload a CSV file with your contacts. You can map columns and select relationship types."})]}),o==="upload"&&e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{className:"border-2 border-dashed rounded-lg p-8 text-center",children:[e.jsx("input",{type:"file",accept:".csv,.txt",ref:l,onChange:ne,className:"hidden"}),e.jsx(si,{className:"h-10 w-10 mx-auto text-muted-foreground mb-4"}),e.jsx("p",{className:"text-sm text-muted-foreground mb-4",children:"Click to upload or drag and drop a CSV file"}),e.jsx($,{onClick:()=>{var De;return(De=l.current)==null?void 0:De.click()},children:"Select CSV File"})]}),e.jsxs("div",{className:"bg-muted/50 rounded-lg p-4 text-sm",children:[e.jsx("p",{className:"font-medium mb-2",children:"Supported Fields:"}),e.jsx("p",{className:"text-muted-foreground text-xs mb-3",children:"First Name, Last Name, Email, Phone, Street Address, City, State, Zip, Spouse Name, Spouse Email, Company, Job Title, Birthday, Home Anniversary, Notes"}),e.jsxs($,{variant:"outline",size:"sm",onClick:()=>{const De=`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`,ze=new Blob([De],{type:"text/csv"}),ke=URL.createObjectURL(ze),Xe=document.createElement("a");Xe.href=ke,Xe.download="contact_import_template.csv",Xe.click(),URL.revokeObjectURL(ke)},children:[e.jsx(di,{className:"h-4 w-4 mr-2"}),"Download Template"]})]})]}),o==="mapping"&&e.jsxs("div",{className:"flex-1 overflow-auto space-y-4 py-4",children:[e.jsxs("div",{className:"space-y-3",children:[e.jsx(se,{className:"text-base font-medium",children:"Map CSV Columns to Contact Fields"}),e.jsx("div",{className:"grid gap-3",children:SNn.map(De=>e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsxs(se,{className:"w-40 text-sm",children:[De.label,De.required&&e.jsx("span",{className:"text-destructive ml-1",children:"*"})]}),e.jsxs(vs,{value:p[De.key]||"none",onValueChange:ze=>ee(De.key,ze),children:[e.jsx(gs,{className:"w-48",children:e.jsx(bs,{placeholder:"Select column..."})}),e.jsxs(ys,{children:[e.jsx(Ye,{value:"none",children:"-- Not mapped --"}),d.map(ze=>e.jsx(Ye,{value:ze,children:ze},ze))]})]})]},De.key))})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx(se,{className:"text-base font-medium",children:"Apply Relationship Types (optional)"}),e.jsx("div",{className:"flex flex-wrap gap-2",children:n.map(De=>e.jsx($e,{variant:g.includes(De.id)?"default":"outline",className:"cursor-pointer",onClick:()=>le(De.id),children:De.name},De.id))})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx(se,{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."}),b.length>0&&e.jsx("div",{className:"flex flex-wrap gap-2",children:b.map(De=>{const ze=N.includes(De.id);return e.jsxs($e,{variant:ze?"default":"outline",className:"cursor-pointer gap-1",style:ze&&De.color?{backgroundColor:De.color,borderColor:De.color}:void 0,onClick:()=>K(De.id),children:[De.name,ze&&e.jsx(pr,{className:"h-3 w-3"})]},De.id)})}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(be,{placeholder:"Create a new tag (e.g. Open House Oct 2026)",value:A,onChange:De=>T(De.target.value),onKeyDown:De=>{De.key==="Enter"&&(De.preventDefault(),Q())},className:"max-w-xs"}),e.jsxs($,{type:"button",variant:"outline",size:"sm",onClick:Q,disabled:!A.trim()||P,children:[P?e.jsx(Ht,{className:"h-4 w-4 animate-spin"}):e.jsx(sn,{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(Fr,{className:"h-4 w-4 text-primary"}),e.jsxs("span",{children:[Me," new"]})]}),Ee>0&&e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground",children:[e.jsx(xo,{className:"h-4 w-4"}),e.jsxs("span",{children:[Ee," existing (will merge gaps)"]})]}),je>0&&e.jsxs("div",{className:"flex items-center gap-2 text-destructive",children:[e.jsx(xo,{className:"h-4 w-4"}),e.jsxs("span",{children:[je," invalid"]})]})]}),Ee>0&&e.jsx("div",{className:"bg-muted/50 rounded-lg p-3 text-xs text-muted-foreground",children:"Duplicates matched by email or phone will only fill in missing fields — your existing data won't be overwritten."}),e.jsxs("div",{className:"flex-1 overflow-auto border rounded-lg",children:[e.jsxs(Va,{children:[e.jsx(Ha,{children:e.jsxs(hn,{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(Ga,{children:I.slice(0,100).map((De,ze)=>e.jsxs(hn,{children:[e.jsx(gt,{children:De.first_name}),e.jsx(gt,{children:De.last_name}),e.jsx(gt,{children:De.email}),e.jsx(gt,{children:De.phone}),e.jsx(gt,{children:De.isValid?De.isDuplicate?e.jsx($e,{variant:"outline",className:"bg-accent text-accent-foreground",children:"Merge"}):e.jsx($e,{variant:"secondary",className:"bg-primary/10 text-primary",children:"New"}):e.jsx($e,{variant:"destructive",children:De.error||"Invalid"})})]},ze))})]}),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"&&W&&e.jsxs("div",{className:"space-y-4 py-4 text-center",children:[e.jsx(Fr,{className:"h-12 w-12 mx-auto text-primary"}),e.jsx("h3",{className:"text-lg font-semibold",children:"Import Complete"}),e.jsxs("p",{className:"text-muted-foreground",children:[W.created," created, ",W.updated," merged"]}),W.failed>0&&e.jsxs("p",{className:"text-destructive",children:[W.failed," failed to import"]})]}),e.jsxs(kr,{children:[o==="upload"&&e.jsx($,{variant:"outline",onClick:ce,children:"Cancel"}),o==="mapping"&&e.jsxs(e.Fragment,{children:[e.jsx($,{variant:"outline",onClick:J,children:"Back"}),e.jsx($,{onClick:he,disabled:!p.first_name,children:"Continue"})]}),o==="preview"&&e.jsxs(e.Fragment,{children:[e.jsx($,{variant:"outline",onClick:()=>c("mapping"),children:"Back"}),e.jsx($,{onClick:ge,disabled:B||fe===0,children:B?e.jsxs(e.Fragment,{children:[e.jsx(Ht,{className:"mr-2 h-4 w-4 animate-spin"}),"Importing..."]}):`Import ${fe} Contact${fe!==1?"s":""}`})]}),o==="result"&&e.jsx($,{onClick:ce,children:"Done"})]})]})})};function ANn(){return"contacts"in navigator&&"ContactsManager"in window}function ENn(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(x=>x.trim()).filter(Boolean).join(", "))}(i||l)&&t.push({first_name:i,last_name:l,email:o,phone:c,address:d})}return t}function TNn({open:s,onOpenChange:t,onComplete:n}){_s();const{data:r}=M1(),a=QCe(),i=j.useRef(null),[l,o]=j.useState("choose"),[c,d]=j.useState([]),[u,h]=j.useState(new Set),[m,p]=j.useState(0),[x,g]=j.useState(0),y=ANn(),b=j.useCallback(D=>{if(!r)return D;const B=new Set(r.filter(W=>W.email).map(W=>W.email.toLowerCase())),q=new Set(r.filter(W=>W.phone).map(W=>W.phone.replace(/\D/g,"")));return D.map(W=>{var Q,J;const V=(Q=W.email)==null?void 0:Q.toLowerCase(),K=(J=W.phone)==null?void 0:J.replace(/\D/g,"");return V&&B.has(V)?{...W,isDuplicate:!0,duplicateField:"email"}:K&&K.length>=7&&q.has(K)?{...W,isDuplicate:!0,duplicateField:"phone"}:W})},[r]),v=async()=>{try{const D=["name","email","tel","address"],B=await navigator.contacts.select(D,{multiple:!0});if(!B||B.length===0)return;const q=B.map(K=>{var ce,ue,ne,ee;const J=(((ce=K.name)==null?void 0:ce[0])||"").split(" ");return{first_name:J[0]||"",last_name:J.slice(1).join(" "),email:((ue=K.email)==null?void 0:ue[0])||"",phone:((ne=K.tel)==null?void 0:ne[0])||"",address:(ee=K.address)!=null&&ee[0]?[K.address[0].streetAddress,K.address[0].city,K.address[0].region,K.address[0].postalCode].filter(Boolean).join(", "):""}}),W=b(q);d(W);const V=new Set;W.forEach((K,Q)=>{K.isDuplicate||V.add(Q)}),h(V),o("preview")}catch(D){console.error("Contact Picker error:",D),ja({title:"Could not access contacts",description:"Please try the file upload option instead.",variant:"destructive"})}},N=D=>{var W;const B=(W=D.target.files)==null?void 0:W[0];if(!B)return;const q=new FileReader;q.onload=V=>{var ue;const K=(ue=V.target)==null?void 0:ue.result,Q=ENn(K);if(Q.length===0){ja({title:"No contacts found",description:"The file didn't contain any valid contacts.",variant:"destructive"});return}const J=b(Q);d(J);const ce=new Set;J.forEach((ne,ee)=>{ne.isDuplicate||ce.add(ee)}),h(ce),o("preview")},q.readAsText(B),i.current&&(i.current.value="")},C=async()=>{const D=c.filter((q,W)=>u.has(W));if(D.length===0)return;o("importing");let B=0;for(const q of D)try{await a.mutateAsync({first_name:q.first_name,last_name:q.last_name||void 0,email:q.email||void 0,phone:q.phone||void 0,address:q.address||void 0}),B++,g(Math.round(B/D.length*100))}catch(W){console.error(`Failed to import ${q.first_name} ${q.last_name}:`,W)}p(B),o("done")},A=D=>{h(B=>{const q=new Set(B);return q.has(D)?q.delete(D):q.add(D),q})},T=()=>{u.size===c.length?h(new Set):h(new Set(c.map((D,B)=>B)))},P=D=>{D||(o("choose"),d([]),h(new Set),p(0),g(0),l==="done"&&n()),t(D)},M=c.filter(D=>D.isDuplicate).length,I=u.size;return e.jsx(Os,{open:s,onOpenChange:P,children:e.jsxs(Rs,{className:"sm:max-w-lg max-h-[90vh]",children:[e.jsxs(Us,{children:[e.jsxs(zs,{className:"flex items-center gap-2",children:[e.jsx(dv,{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(Sr,{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($,{onClick:v,className:"w-full h-auto py-4 flex flex-col items-center gap-2",children:[e.jsx(dv,{className:"h-6 w-6"}),e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"font-semibold",children:"Select from Phone"}),e.jsx("div",{className:"text-xs opacity-80",children:"Pick contacts directly from your device"})]})]}),e.jsxs("div",{className:"relative",children:[y&&e.jsx("div",{className:"absolute inset-0 flex items-center",children:e.jsx("span",{className:"w-full border-t"})}),y&&e.jsx("div",{className:"relative flex justify-center text-xs uppercase",children:e.jsx("span",{className:"bg-background px-2 text-muted-foreground",children:"or"})})]}),e.jsxs($,{variant:y?"outline":"default",onClick:()=>{var D;return(D=i.current)==null?void 0:D.click()},className:"w-full h-auto py-4 flex flex-col items-center gap-2",children:[e.jsx(si,{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($,{variant:"ghost",size:"sm",onClick:T,children:u.size===c.length?"Deselect All":"Select All"})]}),e.jsx(Oi,{className:"h-[350px] rounded-md border",children:e.jsx("div",{className:"divide-y",children:c.map((D,B)=>e.jsxs("div",{className:`flex items-start gap-3 p-3 cursor-pointer hover:bg-accent/50 transition-colors ${D.isDuplicate?"opacity-60":""}`,onClick:()=>A(B),children:[e.jsx(ui,{checked:u.has(B),onCheckedChange:()=>A(B),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:[D.first_name," ",D.last_name]}),D.isDuplicate&&e.jsxs($e,{variant:"secondary",className:"text-[10px] px-1.5 py-0 bg-amber-500/10 text-amber-600 border-amber-200",children:["Exists (",D.duplicateField,")"]})]}),e.jsxs("div",{className:"text-xs text-muted-foreground space-y-0.5 mt-0.5",children:[D.phone&&e.jsx("div",{children:D.phone}),D.email&&e.jsx("div",{className:"truncate",children:D.email})]})]})]},B))})}),e.jsxs("div",{className:"flex items-center justify-between pt-2",children:[e.jsx($,{variant:"ghost",size:"sm",onClick:()=>o("choose"),children:"Back"}),e.jsxs($,{onClick:C,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(Ht,{className:"h-8 w-8 animate-spin text-primary"}),e.jsxs("div",{className:"text-center",children:[e.jsx("p",{className:"font-medium",children:"Importing contacts..."}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[x,"% complete"]})]}),e.jsx("div",{className:"w-full bg-muted rounded-full h-2",children:e.jsx("div",{className:"bg-primary h-2 rounded-full transition-all",style:{width:`${x}%`}})})]}),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(oa,{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($,{onClick:()=>P(!1),className:"mt-2",children:"Done"})]})]})})}function MNn(s){return ht({queryKey:["video-share-recipients",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await U.from("video_share_recipients").select("*").eq("video_id",s).order("sent_at",{ascending:!1});if(n)throw n;return t},enabled:!!s})}function LNn(){const{user:s}=_s();return ht({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 U.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 PNn(){const{user:s}=_s();return ht({queryKey:["video-share-history",s==null?void 0:s.id],queryFn:async()=>{if(!(s!=null&&s.id))return[];const{data:t,error:n}=await U.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 E7t(){const{user:s}=_s(),t=ts();return yt({mutationFn:async n=>{if(!(s!=null&&s.id))throw new Error("Not authenticated");const{data:r,error:a}=await U.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 T7t(s){return`https://relzejiswnotikjgvjhz.supabase.co/functions/v1/track-video-share?t=${s}&e=open`}function M7t(s){return`https://relzejiswnotikjgvjhz.supabase.co/functions/v1/track-video-share?t=${s}&e=click`}const INn=100;function DNn({open:s,onOpenChange:t,contacts:n,isGmailConnected:r,isMassEmailReady:a,onSendComplete:i}){const l=Vn(),o=Za(),c=E7t(),[d,u]=j.useState([]),[h,m]=j.useState(!1),[p,x]=j.useState(""),[g,y]=j.useState(null),[b,v]=j.useState(""),[N,C]=j.useState(""),[A,T]=j.useState(!1),[P,M]=j.useState({done:0,total:0,failed:0}),I=n.filter(J=>!!J.email),D=n.length-I.length,B=I.length>INn;j.useEffect(()=>{s&&(y(null),x(""),M({done:0,total:0,failed:0}))},[s]),j.useEffect(()=>{!s||!o||(m(!0),U.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:J})=>{u(J||[]),m(!1)}))},[s,o]),j.useEffect(()=>{if(!g)return;const J=g.title||"a quick video";v(`I recorded a video for you — ${J}`),C("Hey {{first_name}}! I recorded a quick video just for you. Click below to watch it:")},[g]);const q=d.filter(J=>!p||(J.title||"").toLowerCase().includes(p.toLowerCase())),W=(J,ce)=>{if(!g)return"";const ue=g.share_token?`https://video.relevelup.com/share/video/${g.share_token}`:"",ne=g.share_token?`https://video.relevelup.com/thumb/${g.share_token}`:g.thumbnail_url||"",ee=g.title||"Video Message",he=N.replace(/\{\{first_name\}\}/gi,J).split(/\n\n+/).map(fe=>`

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

`).join(""),ve=ce?M7t(ce):ue,ge=ce?``:"";return`
`},V=async()=>{if(!g)return;T(!0),M({done:0,total:I.length,failed:0});let J=0,ce=0;for(const ue of I)try{let ne;try{ne=(await c.mutateAsync({video_id:g.id,recipient_email:ue.email,recipient_name:`${ue.first_name} ${ue.last_name||""}`.trim(),contact_id:ue.id,sent_via:"gmail"})).share_token}catch(ge){console.warn("Tracking record failed for",ue.email,ge)}const ee=W(ue.first_name,ne),le=b.replace(/\{\{first_name\}\}/gi,ue.first_name),{data:he,error:ve}=await U.functions.invoke("gmail-send",{body:{to:ue.email,subject:le,body:ee,contactId:ue.id}});if(ve||!(he!=null&&he.success))throw new Error((he==null?void 0:he.error)||(ve==null?void 0:ve.message)||"Send failed");J+=1}catch(ne){console.error("Failed to send to",ue.email,ne),ce+=1}finally{M({done:J+ce,total:I.length,failed:ce}),await new Promise(ne=>setTimeout(ne,250))}T(!1),ce===0?ae.success(`Video sent to ${J} ${J===1?"contact":"contacts"}!`):ae.warning(`Sent to ${J}, ${ce} failed. Check console for details.`),t(!1),i==null||i()},K=()=>{if(!g)return;const J=W("there",void 0);l("/admin/email-campaigns/new",{state:{directRecipients:I.map(ce=>({email:ce.email,name:`${ce.first_name} ${ce.last_name||""}`.trim()})),initialSubject:b,initialBodyHtml:J}}),t(!1)},Q=!!g&&!!b.trim()&&I.length>0&&(B?a:r);return e.jsx(Os,{open:s,onOpenChange:t,children:e.jsxs(Rs,{className:"sm:max-w-[640px] max-h-[90vh] overflow-y-auto",children:[e.jsxs(Us,{children:[e.jsxs(zs,{className:"flex items-center gap-2",children:[e.jsx(Xr,{className:"h-5 w-5 text-primary"}),"Send Video to ",I.length," ",I.length===1?"Contact":"Contacts"]}),e.jsxs(Sr,{children:[B?e.jsxs("span",{className:"flex items-center gap-1.5 text-amber-600",children:[e.jsx(Eh,{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(nn,{className:"h-3.5 w-3.5"}),"Sent individually via your connected Gmail"]}),D>0&&e.jsxs("span",{className:"ml-2 text-xs text-muted-foreground",children:["(",D," skipped — no email)"]})]})]}),e.jsxs("div",{className:"space-y-4",children:[B&&!a&&e.jsxs("div",{className:"flex items-start gap-2 p-3 rounded-md bg-destructive/10 text-destructive text-sm",children:[e.jsx(xo,{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."]})]}),!B&&!r&&e.jsxs("div",{className:"flex items-start gap-2 p-3 rounded-md bg-destructive/10 text-destructive text-sm",children:[e.jsx(xo,{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(se,{children:"Choose a video"}),e.jsxs($,{type:"button",variant:"ghost",size:"sm",className:"gap-1",onClick:()=>l("/innercircle/videos/record"),children:[e.jsx(sn,{className:"h-3.5 w-3.5"})," Record new"]})]}),e.jsxs("div",{className:"relative",children:[e.jsx(Vr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(be,{placeholder:"Search your video library...",value:p,onChange:J=>x(J.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(on,{className:"h-14 w-full"}),e.jsx(on,{className:"h-14 w-full"})]}):q.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."}):q.map(J=>{const ce=(g==null?void 0:g.id)===J.id;return e.jsxs("button",{type:"button",onClick:()=>y(J),className:`w-full flex items-center gap-3 p-2 rounded-md border text-left transition-colors ${ce?"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:[J.thumbnail_url?e.jsx("img",{src:J.thumbnail_url,alt:"",className:"w-full h-full object-cover",referrerPolicy:"no-referrer"}):e.jsx(lh,{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(Td,{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:J.title||"Untitled Video"}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[J.duration_seconds?`${Math.round(J.duration_seconds)}s`:"",J.created_at?` · ${new Date(J.created_at).toLocaleDateString()}`:""]})]})]},J.id)})})]}),e.jsx(Hl,{}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{htmlFor:"bulk-video-subject",children:"Subject"}),e.jsx(be,{id:"bulk-video-subject",value:b,onChange:J=>v(J.target.value),placeholder:"I recorded a video for you"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs(se,{htmlFor:"bulk-video-message",children:["Personal message ",e.jsxs("span",{className:"text-xs text-muted-foreground",children:["(use ","{{first_name}}"," to personalize)"]})]}),e.jsx(Is,{id:"bulk-video-message",value:N,onChange:J=>C(J.target.value),rows:4,className:"resize-y"})]}),A&&P.total>0&&e.jsxs("div",{className:"p-3 rounded-md bg-muted text-sm",children:["Sending… ",P.done," / ",P.total,P.failed>0&&e.jsxs("span",{className:"text-destructive ml-2",children:["(",P.failed," failed)"]})]}),e.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[e.jsx($,{variant:"outline",onClick:()=>t(!1),disabled:A,children:"Cancel"}),B?e.jsxs($,{onClick:K,disabled:!Q,className:"gap-2",children:[e.jsx(Eh,{className:"h-4 w-4"}),"Continue in Mass Email"]}):e.jsxs($,{onClick:V,disabled:!Q||A,className:"gap-2",children:[A?e.jsx(Ht,{className:"h-4 w-4 animate-spin"}):e.jsx(Br,{className:"h-4 w-4"}),A?"Sending…":`Send to ${I.length}`]})]})]})]})})}function Xee(){const s=Za();return ht({queryKey:["drip-campaigns",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await U.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 RNn(s){return ht({queryKey:["drip-campaign",s],queryFn:async()=>{if(!s)return null;const{data:t,error:n}=await U.from("drip_campaigns").select("*").eq("id",s).maybeSingle();if(n)throw n;return t},enabled:!!s})}function ONn(){const s=Za(),t=ts();return yt({mutationFn:async n=>{if(!s)throw new Error("Not authenticated");const{data:r,error:a}=await U.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 L7t(){const s=ts();return yt({mutationFn:async({id:t,...n})=>{const{data:r,error:a}=await U.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 FNn(){const s=ts();return yt({mutationFn:async t=>{const{error:n}=await U.from("drip_campaigns").delete().eq("id",t);if(n)throw n},onSuccess:()=>s.invalidateQueries({queryKey:["drip-campaigns"]})})}function TYe(){const s=Za(),t=ts();return yt({mutationFn:async n=>{if(!s)throw new Error("Not authenticated");const[{data:r,error:a},{data:i,error:l}]=await Promise.all([U.from("drip_campaigns").select("*").eq("id",n).single(),U.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 U.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 U.from("drip_campaign_steps").insert(d);if(u)throw u}return o},onSuccess:()=>t.invalidateQueries({queryKey:["drip-campaigns"]})})}function P7t(s){return ht({queryKey:["drip-campaign-steps",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await U.from("drip_campaign_steps").select("*").eq("campaign_id",s).order("step_order",{ascending:!0});if(n)throw n;return t},enabled:!!s})}function zNn(){const s=ts();return yt({mutationFn:async t=>{const{data:n,error:r}=await U.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 BNn(){const s=ts();return yt({mutationFn:async({id:t,campaign_id:n,...r})=>{const{data:a,error:i}=await U.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 $Nn(){const s=ts();return yt({mutationFn:async({id:t,campaign_id:n})=>{const{error:r}=await U.from("drip_campaign_steps").delete().eq("id",t);if(r)throw r;return n},onSuccess:t=>s.invalidateQueries({queryKey:["drip-campaign-steps",t]})})}function UNn(s){return ht({queryKey:["campaign-enrollments",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await U.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 qNn(s){return ht({queryKey:["campaign-enrollment-count",s],queryFn:async()=>{if(!s)return 0;const{count:t,error:n}=await U.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 MYe(){const s=ts();return yt({mutationFn:async({campaignId:t,contactIds:n})=>{const{data:r,error:a}=await U.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 VNn(){const s=ts();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 U.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 HNn=[{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"}],GEe={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"},GNn={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 WNn({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"),[x,g]=j.useState(""),[y,b]=j.useState(!1);j.useEffect(()=>{if(!s)return;let N=!1;return(async()=>{var C,A;o(!0);try{const{data:T}=await U.auth.getSession();x||g(((A=(C=T==null?void 0:T.session)==null?void 0:C.user)==null?void 0:A.email)||"");const{data:P,error:M}=await U.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((P==null?void 0:P.html)||""),h((P==null?void 0:P.subject)||n)}catch{N||ae.error("Could not build preview")}finally{N||o(!1)}})(),()=>{N=!0}},[s,n,r,a]);const v=async()=>{if(x.trim()){b(!0);try{const{data:N,error:C}=await U.functions.invoke("process-drip-campaigns",{body:{action:"test_send",subject:n,body:r,to:x.trim(),owner_user_id:a||void 0}});if(C)throw C;N!=null&&N.success?ae.success(`Test email sent to ${x.trim()}`):ae.error((N==null?void 0:N.error)||"Could not send test email",{duration:1e4})}catch{ae.error("Could not send test email")}finally{b(!1)}}};return e.jsx(Os,{open:s,onOpenChange:t,children:e.jsxs(Rs,{className:"sm:max-w-3xl max-h-[92vh] flex flex-col p-0 gap-0",children:[e.jsxs(Us,{className:"p-5 pb-3 border-b shrink-0",children:[e.jsxs(zs,{children:["Email preview",i?` — ${i}`:""]}),e.jsx(Sr,{children:"Exactly how this email will look when it sends, with sample contact details filled in."})]}),e.jsxs("div",{className:"px-5 py-3 border-b shrink-0 space-y-2",children:[e.jsx("div",{className:"text-xs text-muted-foreground",children:"Subject"}),e.jsx("div",{className:"text-sm font-medium",children:u||n||"(no subject)"}),e.jsxs("div",{className:"flex items-center gap-1.5 pt-1",children:[e.jsxs($,{variant:m==="desktop"?"secondary":"ghost",size:"sm",className:"h-7 text-xs",onClick:()=>p("desktop"),children:[e.jsx(Hj,{className:"h-3.5 w-3.5 mr-1"})," Desktop"]}),e.jsxs($,{variant:m==="mobile"?"secondary":"ghost",size:"sm",className:"h-7 text-xs",onClick:()=>p("mobile"),children:[e.jsx(dv,{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(Ht,{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(se,{className:"text-xs",children:"Send a test to"}),e.jsx(be,{type:"email",value:x,onChange:N=>g(N.target.value),placeholder:"you@email.com",className:"h-9",onKeyDown:N=>N.key==="Enter"&&v()})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx($,{variant:"outline",onClick:()=>t(!1),children:"Close"}),e.jsxs($,{onClick:v,disabled:y||!x.trim(),children:[y?e.jsx(Ht,{className:"h-4 w-4 mr-1.5 animate-spin"}):e.jsx(Br,{className:"h-4 w-4 mr-1.5"}),"Send test"]})]})]})]})})}function hF({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,x]=j.useState("");j.useEffect(()=>{!o||!s||(m(!0),U.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 g=d.filter(y=>!p||(y.title||y.recipient_name||"").toLowerCase().includes(p.toLowerCase()));return e.jsxs(Os,{open:o,onOpenChange:c,children:[e.jsx(Ko,{asChild:!0,children:e.jsxs($,{variant:i,size:a,className:l||"gap-1.5 shrink-0",children:[e.jsx(lh,{className:"h-3.5 w-3.5"}),r]})}),e.jsxs(Rs,{className:"max-w-lg max-h-[70vh] flex flex-col",children:[e.jsxs(Us,{children:[e.jsx(zs,{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(Vr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(be,{placeholder:"Search videos...",value:p,onChange:y=>x(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(on,{className:"h-16 w-full"}),e.jsx(on,{className:"h-16 w-full"})]}):g.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"}):g.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:b=>{const v=b.currentTarget.parentElement;if(v){b.currentTarget.remove();const N=document.createElement("span");N.innerHTML="🎬",N.className="text-lg",v.appendChild(N)}}}):e.jsx(Xr,{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 KNn(){return ht({queryKey:["video-script-categories"],queryFn:async()=>{const{data:s,error:t}=await U.from("video_script_categories").select("*").order("sort_order");if(t)throw t;return s}})}function YNn(s){return ht({queryKey:["video-scripts",s],queryFn:async()=>{let t=U.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 ZNn(){const{user:s}=_s();return ht({queryKey:["user-video-scripts",s==null?void 0:s.id],queryFn:async()=>{if(!(s!=null&&s.id))return[];const{data:t,error:n}=await U.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 XNn(){const{user:s}=_s(),t=ts();return yt({mutationFn:async n=>{if(!(s!=null&&s.id))throw new Error("Not authenticated");const{data:r,error:a}=await U.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 QNn(s){const{user:t}=_s();return ht({queryKey:["agent-videos",t==null?void 0:t.id,s],queryFn:async()=>{if(!(t!=null&&t.id))return[];let n=U.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 JNn(s){return ht({queryKey:["agent-video",s],queryFn:async()=>{const{data:t,error:n}=await U.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 F5(){const{user:s}=_s(),t=ts();return yt({mutationFn:async n=>{if(!(s!=null&&s.id))throw new Error("Not authenticated");const{data:r,error:a}=await U.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 ekn(){const s=ts();return yt({mutationFn:async({id:t,...n})=>{const{data:r,error:a}=await U.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 tkn(){const s=ts();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 U.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 U.from("agent_videos").delete().eq("id",t);if(a)throw a}else{console.log("Soft deleting from database:",t);const{error:a}=await U.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 WEe(){const{user:s}=_s();return ht({queryKey:["storage-usage",s==null?void 0:s.id],queryFn:async()=>{if(!(s!=null&&s.id))return null;const{data:t,error:n}=await U.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 I7t(){const{data:s,isLoading:t}=WEe(),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 Z6(s){const{data:t,error:n}=await U.functions.invoke("bunny-upload",{body:{action:"create",title:s,isAgentVideo:!0}});if(n)throw n;return t}async function X6(s){const{data:t,error:n}=await U.functions.invoke("bunny-upload",{body:{action:"upload-url",videoId:s,isAgentVideo:!0}});if(n)throw n;return t}async function o2(s){const{data:t,error:n}=await U.functions.invoke("bunny-upload",{body:{action:"status",videoId:s,isAgentVideo:!0}});if(n)throw n;return t}function skn(){const{user:s}=_s(),t=ts();return yt({mutationFn:async({contactId:n,videoId:r,notes:a})=>{if(!(s!=null&&s.id))throw new Error("Not authenticated");const{data:i}=await U.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 U.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 D7t({open:s,onOpenChange:t,onUploadComplete:n}){const{data:r}=M1(),{data:a}=WEe(),i=F5(),l=j.useRef(null),[o,c]=j.useState(null),[d,u]=j.useState(""),[h,m]=j.useState(""),[p,x]=j.useState(""),[g,y]=j.useState(!1),[b,v]=j.useState(0),[N,C]=j.useState("idle"),A=(a==null?void 0:a.total_storage_mb)||0,P=((a==null?void 0:a.max_storage_mb)||1024)-A,M=q=>{var K;const W=(K=q.target.files)==null?void 0:K[0];if(!W)return;if(!W.type.startsWith("video/")){ae.error("Please select a video file");return}const V=W.size/(1024*1024);if(V>500){ae.error("Video file must be less than 500MB");return}if(V>P){ae.error(`Not enough storage. You have ${P.toFixed(1)} MB remaining.`);return}c(W),d||u(W.name.replace(/\.[^/.]+$/,""))},I=async()=>{if(!o){ae.error("Please select a video file");return}y(!0),v(0),C("creating");try{const{data:q,error:W}=await U.functions.invoke("bunny-upload",{body:{action:"create",title:d||o.name,isAgentVideo:!0}});if(W)throw new Error(W.message);const{videoId:V,libraryId:K}=q;C("uploading");const{data:Q,error:J}=await U.functions.invoke("bunny-upload",{body:{action:"upload-url",videoId:V,isAgentVideo:!0}});if(J)throw new Error(J.message);await new Promise((ne,ee)=>{const le=new XMLHttpRequest;le.upload.addEventListener("progress",he=>{if(he.lengthComputable){const ve=Math.round(he.loaded/he.total*100);v(ve)}}),le.addEventListener("load",()=>{le.status>=200&&le.status<300?ne():ee(new Error(`Upload failed with status ${le.status}`))}),le.addEventListener("error",()=>ee(new Error("Upload failed"))),le.open("PUT",Q.uploadUrl),le.setRequestHeader("AccessKey",Q.apiKey),le.send(o)}),C("processing");const ce=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:ce,title:d||o.name,notes:h||void 0,contact_id:p||void 0,status:"processing",touch_type:"video_upload"}),ae.success("Video uploaded successfully! Processing may take a few minutes."),n==null||n(ue),D()}catch(q){console.error("Upload error:",q),ae.error(q instanceof Error?q.message:"Failed to upload video")}finally{y(!1),C("idle")}},D=()=>{g||(c(null),u(""),m(""),x(""),v(0),C("idle"),t(!1))},B=()=>{switch(N){case"creating":return"Preparing upload...";case"uploading":return`Uploading... ${b}%`;case"processing":return"Saving video...";default:return""}};return e.jsx(Os,{open:s,onOpenChange:D,children:e.jsxs(Rs,{className:"sm:max-w-md",children:[e.jsxs(Us,{children:[e.jsx(zs,{children:"Upload Video"}),e.jsx(Sr,{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(se,{children:"Video File"}),o?e.jsxs("div",{className:"flex items-center gap-3 p-3 bg-muted rounded-lg",children:[e.jsx(Xr,{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"]})]}),!g&&e.jsx($,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:q=>{q.stopPropagation(),c(null)},children:e.jsx(pr,{className:"h-4 w-4"})})]}):e.jsxs("div",{className:"border-2 border-dashed border-muted-foreground/25 rounded-lg p-8 text-center cursor-pointer hover:border-primary/50 transition-colors",onClick:()=>{var q;return(q=l.current)==null?void 0:q.click()},children:[e.jsx(si,{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:g})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"title",children:"Title"}),e.jsx(be,{id:"title",value:d,onChange:q=>u(q.target.value),placeholder:"Enter video title",disabled:g})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Associate with Contact (optional)"}),e.jsxs(vs,{value:p||"__none__",onValueChange:q=>x(q==="__none__"?"":q),disabled:g,children:[e.jsx(gs,{children:e.jsx(bs,{placeholder:"Select a contact"})}),e.jsxs(ys,{children:[e.jsx(Ye,{value:"__none__",children:"No contact"}),r==null?void 0:r.map(q=>e.jsxs(Ye,{value:q.id,children:[q.first_name," ",q.last_name||""]},q.id))]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"notes",children:"Notes (optional)"}),e.jsx(Is,{id:"notes",value:h,onChange:q=>m(q.target.value),placeholder:"Add any notes about this video",rows:2,disabled:g})]}),g&&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(Ht,{className:"h-4 w-4 animate-spin"}),e.jsx("span",{children:B()})]}),e.jsx(Ki,{value:N==="uploading"?b:N==="processing"?100:10})]})]}),e.jsxs(kr,{children:[e.jsx($,{variant:"outline",onClick:D,disabled:g,children:"Cancel"}),e.jsx($,{onClick:I,disabled:!o||g,children:g?e.jsxs(e.Fragment,{children:[e.jsx(Ht,{className:"h-4 w-4 mr-2 animate-spin"}),"Uploading..."]}):e.jsxs(e.Fragment,{children:[e.jsx(si,{className:"h-4 w-4 mr-2"}),"Upload Video"]})})]})]})})}const nkn=["🌱","💎","🏠","🔑","📧","💌","🎂","🥂","🤝","⭐","🎉","📞"],rkn={" ":" ","&":"&","<":"<",">":">",""":'"',"'":"'"},Hxt=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=>rkn[t.toLowerCase()]||t).replace(/\n{3,}/g,` `).replace(/[ \t]+\n/g,` `).trim():s:"";function R7t({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}=RNn(o||void 0),{data:u,isLoading:h}=P7t(o||void 0),m=ONn(),p=L7t(),x=zNn(),[g,y]=j.useState(""),[b,v]=j.useState(""),[N,C]=j.useState("nurture"),[A,T]=j.useState("🌱"),[P,M]=j.useState("");j.useEffect(()=>{d?(y(d.name),v(d.description||""),C(d.category),T(d.icon),M(d.goal||"")):c||(y(""),v(""),C("nurture"),T("🌱"),M(""))},[d,c,s]);const I=GNn[N],D=async()=>{if(!g.trim()){ae.error("Give your campaign a name");return}try{if(c&&o)await p.mutateAsync({id:o,name:g,description:b,category:N,icon:A,goal:P,cover_color:I}),ae.success("Campaign updated");else{const q=await m.mutateAsync({name:g,description:b,category:N,icon:A,goal:P,cover_color:I});return ae.success("Campaign created — now add your first step!"),a(q.id),l("steps"),q}}catch(q){ae.error(q.message||"Failed to save")}},B=async()=>{if(!o){ae.error("Save the campaign first, then add steps");return}const q=((u==null?void 0:u.length)||0)+1;try{await x.mutateAsync({campaign_id:o,step_order:q,channel:"email",subject:"",body:"",delay_type:"relative",delay_days:q===1?0:2,delay_hours:0})}catch{ae.error("Failed to add step")}};return e.jsx(Os,{open:s,onOpenChange:t,children:e.jsxs(Rs,{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(zs,{className:"text-lg font-bold text-white",children:c?"Edit Campaign":"Create New Campaign"}),e.jsx(Sr,{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(ua,{value:i,onValueChange:q=>l(q),className:"flex-1 flex flex-col overflow-hidden min-h-0",children:[e.jsxs(ha,{className:"mx-5 mt-4 grid grid-cols-2 w-fit",children:[e.jsx(Qt,{value:"details",children:"Details"}),e.jsxs(Qt,{value:"steps",disabled:!c,children:["Steps ",u&&u.length>0&&e.jsx($e,{variant:"secondary",className:"ml-1.5 text-[10px]",children:u.length})]})]}),e.jsx(Jt,{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(se,{className:"text-xs",children:"Campaign Name *"}),e.jsx(be,{value:g,onChange:q=>y(q.target.value),placeholder:"e.g. New Buyer Lead — 7 Touch Nurture",className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-xs",children:"Description"}),e.jsx(Is,{value:b,onChange:q=>v(q.target.value),placeholder:"What's this campaign for? When should you use it?",rows:2,className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-xs",children:"Goal (optional)"}),e.jsx(be,{value:P,onChange:q=>M(q.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(se,{className:"text-xs",children:"Category"}),e.jsxs(vs,{value:N,onValueChange:q=>C(q),children:[e.jsx(gs,{className:"mt-1",children:e.jsx(bs,{})}),e.jsx(ys,{children:Object.entries(GEe).map(([q,W])=>e.jsx(Ye,{value:q,children:W},q))})]})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-xs",children:"Icon"}),e.jsx("div",{className:"flex gap-1.5 flex-wrap mt-1",children:nkn.map(q=>e.jsx("button",{type:"button",onClick:()=>T(q),className:`h-8 w-8 rounded-md text-lg flex items-center justify-center transition-all ${A===q?"bg-primary/15 ring-2 ring-primary":"hover:bg-muted"}`,children:q},q))})]})]}),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(Jt,{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(dn,{className:"h-8 w-8 text-muted-foreground/40 mx-auto mb-2"}),e.jsx("p",{className:"text-sm font-medium mb-1",children:"No steps yet"}),e.jsx("p",{className:"text-xs text-muted-foreground mb-3",children:"Build your sequence — each step waits for its delay, then sends."}),e.jsxs($,{size:"sm",onClick:B,disabled:x.isPending,children:[e.jsx(sn,{className:"h-3.5 w-3.5 mr-1.5"})," Add first step"]})]}):e.jsxs(e.Fragment,{children:[u.map((q,W)=>e.jsx(akn,{step:q,index:W,totalSteps:u.length},q.id)),e.jsxs($,{variant:"outline",size:"sm",onClick:B,disabled:x.isPending,className:"w-full",children:[x.isPending?e.jsx(Ht,{className:"h-3.5 w-3.5 mr-1.5 animate-spin"}):e.jsx(sn,{className:"h-3.5 w-3.5 mr-1.5"}),"Add another step"]})]})})})})]}),e.jsxs(kr,{className:"border-t p-4 shrink-0",children:[e.jsx($,{variant:"outline",onClick:()=>t(!1),children:c?"Done":"Cancel"}),e.jsxs($,{onClick:D,disabled:m.isPending||p.isPending,children:[(m.isPending||p.isPending)&&e.jsx(Ht,{className:"h-3.5 w-3.5 mr-1.5 animate-spin"}),c?"Save Changes":"Create Campaign"]})]})]})})}function akn({step:s,index:t,totalSteps:n}){const r=BNn(),a=$Nn(),i=Za(),[l,o]=j.useState(!1),[c,d]=j.useState(()=>({...s,body:Hxt(s.body)})),[u,h]=j.useState(!1),[m,p]=j.useState(!1),[x,g]=j.useState(""),[y,b]=j.useState(!1),[v,N]=j.useState(!1);j.useEffect(()=>{d({...s,body:Hxt(s.body)})},[s]);const C=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}),ae.success(`Step ${t+1} saved`)}catch{ae.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}),ae.success("Step deleted")}catch{ae.error("Failed to delete")}},P=I=>{d({...c,body:c.body+I})},M=()=>{if(c.delay_type==="calendar_anchor"){const D=c.anchor_field==="birthday"?"birthday":"home anniversary",B=c.anchor_offset_days||0;return B===0?`On their ${D}`:B<0?`${Math.abs(B)}d before ${D}`:`${B}d after ${D}`}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(ia,{className:"h-3 w-3"}):e.jsx(Hr,{className:"h-3 w-3"}),e.jsx("span",{children:M()}),e.jsx("span",{children:"·"}),c.channel==="email"?e.jsx(nn,{className:"h-3 w-3"}):e.jsx(Ji,{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(jg,{className:"h-4 w-4 text-muted-foreground"}):e.jsx(_o,{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(se,{className:"text-xs",children:"Channel"}),e.jsxs(vs,{value:c.channel,onValueChange:I=>d({...c,channel:I}),children:[e.jsx(gs,{className:"mt-1 h-9",children:e.jsx(bs,{})}),e.jsx(ys,{children:e.jsx(Ye,{value:"email",children:"📧 Email"})})]})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-xs",children:"Timing Type"}),e.jsxs(vs,{value:c.delay_type,onValueChange:I=>d({...c,delay_type:I}),children:[e.jsx(gs,{className:"mt-1 h-9",children:e.jsx(bs,{})}),e.jsxs(ys,{children:[e.jsx(Ye,{value:"relative",children:"⏱ Relative delay"}),e.jsx(Ye,{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(se,{className:"text-xs",children:"Days delay"}),e.jsx(be,{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(se,{className:"text-xs",children:"Hours delay"}),e.jsx(be,{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(se,{className:"text-xs",children:"Anchor"}),e.jsxs(vs,{value:c.anchor_field||"birthday",onValueChange:I=>d({...c,anchor_field:I}),children:[e.jsx(gs,{className:"mt-1 h-9",children:e.jsx(bs,{})}),e.jsxs(ys,{children:[e.jsx(Ye,{value:"birthday",children:"🎂 Birthday"}),e.jsx(Ye,{value:"home_anniversary",children:"🏠 Home Anniversary"})]})]})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-xs",children:"Offset (days, negative = before)"}),e.jsx(be,{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(se,{className:"text-xs",children:"Subject Line"}),e.jsx(be,{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(se,{className:"text-xs",children:"Email Body"}),e.jsxs("span",{className:"text-[10px] text-muted-foreground",children:[c.body.length," chars"]})]}),e.jsx(Is,{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:"}),HNn.map(I=>e.jsx("button",{type:"button",onClick:()=>P(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(se,{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(Xr,{className:"h-3 w-3 inline mr-1 text-primary"}),c.video_url.length>50?c.video_url.slice(0,50)+"...":c.video_url]}),e.jsx($,{variant:"ghost",size:"sm",className:"h-7 text-xs text-destructive",onClick:()=>d({...c,video_url:null}),children:"Remove"})]}):e.jsxs("div",{className:"mt-1 flex items-center gap-1.5 flex-wrap",children:[e.jsx(hF,{userId:i||void 0,onSelect:I=>d({...c,video_url:I}),triggerSize:"sm",triggerClassName:"gap-1.5 flex-1 min-w-[120px]"}),e.jsxs($,{variant:"outline",size:"sm",className:"gap-1 text-xs flex-1 min-w-[120px]",onClick:()=>b(!0),children:[e.jsx(si,{className:"h-3 w-3"})," Upload"]}),e.jsxs($,{variant:"ghost",size:"sm",className:"gap-1 text-xs text-muted-foreground flex-1 min-w-[120px]",onClick:()=>{g(""),p(!0)},children:[e.jsx(kc,{className:"h-3 w-3"})," Paste URL"]}),e.jsx(D7t,{open:y,onOpenChange:b,onUploadComplete:I=>d({...c,video_url:I})}),e.jsx(Os,{open:m,onOpenChange:p,children:e.jsxs(Rs,{className:"sm:max-w-md",children:[e.jsxs(Us,{children:[e.jsx(zs,{children:"Add video URL"}),e.jsx(Sr,{children:"Paste a YouTube, Loom, or direct video URL."})]}),e.jsx(be,{value:x,onChange:I=>g(I.target.value),placeholder:"https://...",autoFocus:!0,onKeyDown:I=>{I.key==="Enter"&&x.trim()&&(d({...c,video_url:x.trim()}),p(!1))}}),e.jsxs(kr,{children:[e.jsx($,{variant:"ghost",onClick:()=>p(!1),children:"Cancel"}),e.jsx($,{disabled:!x.trim(),onClick:()=>{d({...c,video_url:x.trim()}),p(!1)},children:"Add video"})]})]})})]})]}),e.jsxs("div",{className:"flex items-center justify-between pt-2 border-t",children:[e.jsxs($,{variant:"ghost",size:"sm",onClick:T,className:"text-destructive hover:text-destructive",children:[e.jsx(Pn,{className:"h-3.5 w-3.5 mr-1"})," Delete step"]}),e.jsxs("div",{className:"flex items-center gap-2",children:[c.channel==="email"&&e.jsxs($,{variant:"outline",size:"sm",onClick:()=>N(!0),children:[e.jsx(ga,{className:"h-3.5 w-3.5 mr-1.5"})," Preview"]}),e.jsxs($,{size:"sm",onClick:A,disabled:!C||u,children:[u&&e.jsx(Ht,{className:"h-3.5 w-3.5 mr-1.5 animate-spin"}),"Save step"]})]})]}),e.jsx(WNn,{open:v,onOpenChange:N,subject:c.subject||"",body:c.body||"",ownerUserId:i,stepLabel:`Step ${t+1}`})]})]})}function ikn({open:s,onOpenChange:t,contactIds:n,onSuccess:r}){const{data:a,isLoading:i}=Xee(),l=MYe(),[o,c]=j.useState(""),[d,u]=j.useState(null),[h,m]=j.useState(!1),p=(a||[]).filter(y=>!y.is_starter),x=p.filter(y=>y.name.toLowerCase().includes(o.toLowerCase())||(y.description||"").toLowerCase().includes(o.toLowerCase())),g=async()=>{if(d)try{const y=await l.mutateAsync({campaignId:d,contactIds:n}),b=[`${y.enrolled} enrolled`];y.skipped>0&&b.push(`${y.skipped} skipped`),y.errors>0&&b.push(`${y.errors} errors`),ae.success(b.join(" · ")),t(!1),u(null),r==null||r()}catch(y){ae.error(y.message||"Failed to enroll contacts")}};return e.jsxs(Os,{open:s,onOpenChange:t,children:[e.jsxs(Rs,{className:"max-w-md",children:[e.jsxs(Us,{children:[e.jsxs(zs,{className:"flex items-center gap-2",children:[e.jsx(dn,{className:"h-4 w-4 text-primary"}),"Enroll in Drip Campaign"]}),e.jsxs(Sr,{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(Vr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-muted-foreground"}),e.jsx(be,{placeholder:"Search campaigns...",value:o,onChange:y=>c(y.target.value),className:"pl-9 h-9"})]}),e.jsx(Oi,{className:"h-[320px] -mx-1 px-1",children:i?e.jsx("div",{className:"text-center py-8 text-sm text-muted-foreground",children:"Loading..."}):x.length===0?e.jsx("div",{className:"text-center py-8",children:p.length===0?e.jsxs(e.Fragment,{children:[e.jsx(dn,{className:"h-8 w-8 text-muted-foreground/40 mx-auto mb-2"}),e.jsx("p",{className:"text-sm font-medium mb-1",children:"No campaigns yet"}),e.jsx("p",{className:"text-xs text-muted-foreground mb-3",children:"Build a custom drip campaign to nurture these contacts on autopilot."}),e.jsxs($,{size:"sm",onClick:()=>m(!0),children:[e.jsx(sn,{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:x.map(y=>e.jsxs("button",{onClick:()=>u(y.id),className:`w-full flex items-start gap-3 p-3 rounded-lg border text-left transition-all ${d===y.id?"border-primary bg-primary/5 ring-1 ring-primary":"border-border hover:border-primary/40 hover:bg-muted/30"}`,children:[e.jsx("div",{className:`shrink-0 h-9 w-9 rounded-lg bg-gradient-to-br ${y.cover_color} flex items-center justify-center text-lg`,children:y.icon}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("p",{className:"font-medium text-sm truncate",children:y.name}),y.is_active&&e.jsx($e,{variant:"outline",className:"text-[9px] bg-emerald-500/10 text-emerald-600 border-emerald-200 px-1 py-0",children:"Active"})]}),y.description&&e.jsx("p",{className:"text-xs text-muted-foreground line-clamp-2 mt-0.5",children:y.description})]}),d===y.id&&e.jsx(oa,{className:"h-4 w-4 text-primary shrink-0 mt-1"})]},y.id))})})]}),e.jsxs(kr,{className:"gap-2 sm:gap-2",children:[p.length>0&&e.jsxs($,{variant:"ghost",size:"sm",onClick:()=>m(!0),className:"mr-auto text-xs",children:[e.jsx(sn,{className:"h-3.5 w-3.5 mr-1"})," New campaign"]}),e.jsx($,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsxs($,{onClick:g,disabled:!d||l.isPending,children:[l.isPending&&e.jsx(Ht,{className:"h-3.5 w-3.5 mr-1.5 animate-spin"}),"Enroll ",n.length," contact",n.length!==1?"s":""]})]})]}),e.jsx(R7t,{open:h,onOpenChange:m})]})}function okn({selectedIds:s,contacts:t,onClearSelection:n,onSendToLeadPond:r,showLeadPondAction:a,onTransfer:i,showTransferAction:l}){const o=Vn(),{data:c}=Hb(),d=fGe(),u=ts(),{isGmailConnected:h}=ux(),{isReady:m}=iV(),{data:p}=oV(),x=uYe(),g=zFt(),[y,b]=j.useState(!1),[v,N]=j.useState(!1),[C,A]=j.useState(!1),[T,P]=j.useState(!1),[M,I]=j.useState(!1),[D,B]=j.useState(""),q=s.size;if(q===0)return null;const W=async ne=>{b(!0);try{const le=Array.from(s).map(ve=>({contact_id:ve,relationship_type_id:ne})),{error:he}=await U.from("innercircle_contact_tags").upsert(le,{onConflict:"contact_id,relationship_type_id",ignoreDuplicates:!0});if(he)throw he;u.invalidateQueries({queryKey:["innercircle-contacts"]}),u.invalidateQueries({queryKey:["innercircle-contact-counts"]}),ja({title:`Assigned type to ${q} contacts`}),n()}catch(ee){ja({title:"Error assigning type",description:ee.message,variant:"destructive"})}finally{b(!1)}},V=async ne=>{b(!0);try{const ee=Array.from(s);for(const le of ee)try{await g.mutateAsync({contactId:le,tagId:ne})}catch{}u.invalidateQueries({queryKey:["all-contact-custom-tags"]}),ja({title:`Tagged ${q} contacts`}),I(!1),B("")}catch(ee){ja({title:"Error adding tags",description:ee.message,variant:"destructive"})}finally{b(!1)}},K=async()=>{if(D.trim()){b(!0);try{const ne=await x.mutateAsync({name:D.trim()});await V(ne.id)}catch(ne){ja({title:"Error creating tag",description:ne.message,variant:"destructive"}),b(!1)}}},Q=(p==null?void 0:p.filter(ne=>ne.name.toLowerCase().includes(D.toLowerCase())))||[],J=p==null?void 0:p.find(ne=>ne.name.toLowerCase()===D.trim().toLowerCase()),ce=()=>{const ne=t.filter(je=>s.has(je.id)),ee=["First Name","Last Name","Email","Phone","Address","Birthday","Home Anniversary","Notes","Relationship Types"],le=ne.map(je=>{var Ee;return[je.first_name,je.last_name||"",je.email||"",je.phone||"",je.address||"",je.birthday||"",je.home_anniversary||"",je.notes||"",((Ee=je.tags)==null?void 0:Ee.map(Me=>{var De;return(De=Me.relationship_type)==null?void 0:De.name}).join("; "))||""]}),he=[ee.join(","),...le.map(je=>je.map(Ee=>`"${(Ee||"").replace(/"/g,'""')}"`).join(","))].join(` `),ve=new Blob([he],{type:"text/csv"}),ge=URL.createObjectURL(ve),fe=document.createElement("a");fe.href=ge,fe.download=`contacts-export-${new Date().toISOString().slice(0,10)}.csv`,fe.click(),URL.revokeObjectURL(ge),ja({title:`Exported ${q} contacts`})},ue=async()=>{if(await Yi(`Are you sure you want to delete ${q} contacts? This cannot be undone.`)){b(!0);try{const ne=Array.from(s);for(const ee of ne)await d.mutateAsync(ee);n()}catch(ne){ja({title:"Error deleting contacts",description:ne.message,variant:"destructive"})}finally{b(!1)}}};return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center gap-3 p-3 bg-primary/5 border border-primary/20 rounded-lg",children:[e.jsxs($e,{variant:"secondary",className:"font-semibold",children:[q," selected"]}),e.jsxs(vs,{onValueChange:W,disabled:y,children:[e.jsx(gs,{className:"w-[180px] h-8",children:e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(Up,{className:"h-3.5 w-3.5"}),e.jsx("span",{className:"text-sm",children:"Assign Type"})]})}),e.jsx(ys,{children:c==null?void 0:c.filter(ne=>ne.active).map(ne=>e.jsx(Ye,{value:ne.id,children:ne.name},ne.id))})]}),e.jsxs(Sc,{open:M,onOpenChange:I,children:[e.jsx(Cc,{asChild:!0,children:e.jsxs($,{variant:"outline",size:"sm",disabled:y,children:[e.jsx(sn,{className:"h-3.5 w-3.5 mr-1"}),"Add Tag"]})}),e.jsxs(xc,{className:"w-56 p-2",align:"start",children:[e.jsx(be,{placeholder:"Search or create tag...",value:D,onChange:ne=>B(ne.target.value),onKeyDown:ne=>{ne.key==="Enter"&&D.trim()&&!J?(ne.preventDefault(),K()):ne.key==="Enter"&&J&&(ne.preventDefault(),V(J.id))},className:"h-8 text-sm mb-2"}),e.jsxs("div",{className:"max-h-[200px] overflow-y-auto space-y-0.5",children:[Q.map(ne=>e.jsxs("button",{onClick:()=>V(ne.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:ne.color}}),e.jsx("span",{className:"flex-1 text-left truncate",children:ne.name})]},ne.id)),D.trim()&&!J&&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(sn,{className:"h-3.5 w-3.5"}),'Create "',D.trim(),'"']}),Q.length===0&&!D.trim()&&e.jsx("p",{className:"text-xs text-muted-foreground text-center py-2",children:"Type to create a tag"})]})]})]}),h&&e.jsxs($,{variant:"outline",size:"sm",onClick:()=>N(!0),disabled:y,children:[e.jsx(nn,{className:"h-3.5 w-3.5 mr-1"}),"Email"]}),m&&e.jsxs($,{variant:"outline",size:"sm",onClick:()=>{const ne=Array.from(s).join(",");o(`/admin/email-campaigns/new?contactIds=${ne}`)},disabled:y,children:[e.jsx(Eh,{className:"h-3.5 w-3.5 mr-1"}),"Mass Email"]}),e.jsxs($,{variant:"outline",size:"sm",onClick:()=>A(!0),disabled:y,children:[e.jsx(Xr,{className:"h-3.5 w-3.5 mr-1"}),"Send Video"]}),e.jsxs($,{variant:"outline",size:"sm",onClick:()=>P(!0),disabled:y,children:[e.jsx(dn,{className:"h-3.5 w-3.5 mr-1"}),"Enroll in Campaign"]}),a&&r&&e.jsxs($,{variant:"outline",size:"sm",onClick:()=>r(Array.from(s)),disabled:y,children:[e.jsx(f1,{className:"h-3.5 w-3.5 mr-1"}),"Send to Lead Pond"]}),l&&i&&e.jsxs($,{variant:"outline",size:"sm",onClick:()=>i(Array.from(s)),disabled:y,children:[e.jsx(QS,{className:"h-3.5 w-3.5 mr-1"}),"Transfer"]}),e.jsxs($,{variant:"outline",size:"sm",onClick:ce,disabled:y,children:[e.jsx(di,{className:"h-3.5 w-3.5 mr-1"}),"Export"]}),e.jsxs($,{variant:"outline",size:"sm",onClick:ue,disabled:y,className:"text-destructive hover:text-destructive",children:[e.jsx(Pn,{className:"h-3.5 w-3.5 mr-1"}),"Delete"]}),e.jsxs($,{variant:"ghost",size:"sm",onClick:n,className:"ml-auto",children:[e.jsx(pr,{className:"h-3.5 w-3.5 mr-1"}),"Clear"]})]}),e.jsx(ikn,{open:T,onOpenChange:P,contactIds:Array.from(s),onSuccess:n}),e.jsx(x2,{open:v,onOpenChange:N,bulkContacts:Array.from(s).map(ne=>{const ee=t.find(le=>le.id===ne);return ee?{id:ee.id,first_name:ee.first_name,last_name:ee.last_name,email:ee.email||""}:null}).filter(ne=>ne!==null&&ne.email!==""),onSendComplete:()=>{N(!1),n()}}),e.jsx(DNn,{open:C,onOpenChange:A,contacts:Array.from(s).map(ne=>t.find(ee=>ee.id===ne)).filter(ne=>!!ne).map(ne=>({id:ne.id,first_name:ne.first_name,last_name:ne.last_name,email:ne.email})),isGmailConnected:!!h,isMassEmailReady:!!m,onSendComplete:()=>{A(!1),n()}})]})}function Gxt({contact:s,onEdit:t,onDelete:n,onSnooze:r,onSendToLeadPond:a,showLeadPondAction:i,onTransfer:l,showTransferAction:o}){const c=Vn(),{isReady:d}=iV(),u=`${s.first_name} ${s.last_name||""}`.trim();return e.jsxs(Hd,{children:[e.jsx(Gd,{asChild:!0,children:e.jsx($,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:h=>h.stopPropagation(),children:e.jsx(p0,{className:"h-4 w-4"})})}),e.jsxs(Md,{align:"end",onClick:h=>h.stopPropagation(),children:[e.jsxs(Na,{onClick:()=>c(`/mission-control/contacts/${s.id}?tab=activity&action=log`),children:[e.jsx(ya,{className:"h-4 w-4 mr-2"}),"Log Touch"]}),e.jsxs(Na,{onClick:()=>c(`/mission-control/video?contactId=${s.id}`),children:[e.jsx(Xr,{className:"h-4 w-4 mr-2"}),"Send Video"]}),e.jsxs(Na,{onClick:()=>c(`/mission-control/popbys?contactId=${s.id}`),children:[e.jsx(ai,{className:"h-4 w-4 mr-2"}),"Schedule Pop-by"]}),d&&s.email&&e.jsxs(Na,{onClick:()=>c(`/admin/email-campaigns/new?contactIds=${s.id}`),children:[e.jsx(nn,{className:"h-4 w-4 mr-2"}),"Mass Email"]}),e.jsxs(Na,{onClick:()=>r(s.id,u),children:[e.jsx(vy,{className:"h-4 w-4 mr-2"}),"Snooze"]}),i&&a&&e.jsxs(Na,{onClick:()=>a(s.id),children:[e.jsx(f1,{className:"h-4 w-4 mr-2"}),"Send to Lead Pond"]}),o&&l&&e.jsxs(Na,{onClick:()=>l(s.id),children:[e.jsx(QS,{className:"h-4 w-4 mr-2"}),"Transfer to Team Member"]}),e.jsxs(Na,{onClick:()=>t(s),children:[e.jsx(Ya,{className:"h-4 w-4 mr-2"}),"Edit"]}),e.jsxs(Na,{onClick:()=>n(s.id),className:"text-destructive focus:text-destructive",children:[e.jsx(Pn,{className:"h-4 w-4 mr-2"}),"Delete"]})]})]})}function Wxt({currentFilters:s,currentSortBy:t,onApplySmartList:n}){const{data:r}=hYe(),a=BFt(),i=$Ft(),[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(Hd,{children:[e.jsx(Gd,{asChild:!0,children:e.jsxs($,{variant:"outline",size:"sm",className:"gap-1.5",children:[e.jsx($j,{className:"h-3.5 w-3.5"}),"Smart Filters",r&&r.length>0&&e.jsx($e,{variant:"secondary",className:"h-5 px-1.5 text-[10px]",children:r.length}),e.jsx(_o,{className:"h-3.5 w-3.5"})]})}),e.jsxs(Md,{align:"start",className:"w-56",children:[r&&r.length>0?e.jsxs(e.Fragment,{children:[r.map(m=>e.jsxs(Na,{className:"flex items-center justify-between group",children:[e.jsx("span",{className:"flex-1 cursor-pointer",onClick:()=>n(m.filters,m.sort_by),children:m.name}),e.jsx($,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 opacity-0 group-hover:opacity-100",onClick:p=>{p.stopPropagation(),i.mutate(m.id)},children:e.jsx(Pn,{className:"h-3 w-3 text-destructive"})})]},m.id)),e.jsx(S0,{})]}):e.jsx(Na,{disabled:!0,className:"text-muted-foreground text-xs",children:"No saved filters yet"}),u&&e.jsxs(Na,{onClick:()=>o(!0),children:[e.jsx(fT,{className:"h-4 w-4 mr-2"}),"Save Current Filter"]})]})]}),e.jsx(Os,{open:l,onOpenChange:o,children:e.jsxs(Rs,{className:"max-w-sm",children:[e.jsx(Us,{children:e.jsx(zs,{children:"Save Smart Filter"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsx(be,{placeholder:"e.g. Buyers in 40205",value:c,onChange:m=>d(m.target.value),onKeyDown:m=>m.key==="Enter"&&h(),autoFocus:!0}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx($,{variant:"outline",onClick:()=>o(!1),children:"Cancel"}),e.jsx($,{onClick:h,disabled:!c.trim()||a.isPending,children:"Save"})]})]})]})})]})}const m4e=[{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"}],O7t=[{value:"home_anniversary",label:"Home anniversary"},{value:"wedding_anniversary",label:"Wedding anniversary"}],lkn=[{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 ckn({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}=XO();j.useEffect(()=>{s&&d(r)},[s,r]);const p=g=>d(y=>({...y,...g})),x=Object.entries(c).filter(([,g])=>g!==void 0&&g!==!1&&g!=="").length;return e.jsx(Ub,{open:s,onOpenChange:t,children:e.jsxs(T1,{side:"right",className:"w-full sm:max-w-lg overflow-y-auto",children:[e.jsxs(kw,{children:[e.jsxs(Sw,{className:"flex items-center gap-2",children:[e.jsx(dn,{className:"h-4 w-4 text-primary"}),"Advanced Filters"]}),e.jsx(dee,{children:"Slice your database by website activity, contact details, and engagement."})]}),e.jsxs(ua,{value:u,onValueChange:g=>h(g),className:"mt-4",children:[e.jsxs(ha,{className:"grid w-full grid-cols-3",children:[e.jsxs(Qt,{value:"contact",className:"gap-1.5",children:[e.jsx(qn,{className:"h-3.5 w-3.5"})," Contact"]}),e.jsxs(Qt,{value:"behavior",disabled:!n,className:"gap-1.5",children:[e.jsx(zp,{className:"h-3.5 w-3.5"})," Behavior"]}),e.jsx(Qt,{value:"engagement",children:"Engagement"})]}),e.jsxs(Jt,{value:"contact",className:"space-y-6 mt-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Contact Type"}),e.jsxs(vs,{value:i,onValueChange:l,children:[e.jsx(gs,{children:e.jsx(bs,{placeholder:"All types"})}),e.jsxs(ys,{children:[e.jsx(Ye,{value:"all",children:"All Types"}),o==null?void 0:o.map(g=>e.jsx(Ye,{value:g.id,children:g.name},g.id))]})]})]}),e.jsxs(k4,{title:"Contact Info Present",children:[e.jsx(Uy,{label:"Has email",checked:c.hasEmail===!0,onChange:g=>p({hasEmail:g||void 0})}),e.jsx(Uy,{label:"Has phone",checked:c.hasPhone===!0,onChange:g=>p({hasPhone:g||void 0})}),e.jsx(Uy,{label:"Has address",checked:c.hasAddress===!0,onChange:g=>p({hasAddress:g||void 0})}),e.jsx(Uy,{label:"Has birthday",checked:c.hasBirthday===!0,onChange:g=>p({hasBirthday:g||void 0})}),e.jsx(Uy,{label:"Has spouse",checked:c.hasSpouse===!0,onChange:g=>p({hasSpouse:g||void 0})}),e.jsx(Uy,{label:"Has company / job",checked:c.hasCompany===!0,onChange:g=>p({hasCompany:g||void 0})}),e.jsx(Uy,{label:"Has notes",checked:c.hasNotes===!0,onChange:g=>p({hasNotes:g||void 0})})]}),e.jsxs(k4,{title:"Location",children:[e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-2",children:[e.jsx(_8e,{label:"City",value:c.city||"",onChange:g=>p({city:g||void 0}),placeholder:"Any city"}),e.jsx(_8e,{label:"State",value:c.state||"",onChange:g=>p({state:g||void 0}),placeholder:"Any state"})]}),e.jsx(_8e,{label:"ZIP / Postal",value:c.zip||"",onChange:g=>p({zip:g||void 0}),placeholder:"Any ZIP"})]}),e.jsxs(k4,{title:"Important Dates",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{className:"text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:"Birthday month"}),e.jsxs(vs,{value:c.birthdayMonth?String(c.birthdayMonth):"all",onValueChange:g=>p({birthdayMonth:g==="all"?void 0:Number(g)}),children:[e.jsx(gs,{children:e.jsx(bs,{placeholder:"Any month"})}),e.jsxs(ys,{children:[e.jsx(Ye,{value:"all",children:"Any month"}),m4e.map(g=>e.jsx(Ye,{value:String(g.value),children:g.label},g.value))]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{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(vs,{value:c.anniversaryField||"home_anniversary",onValueChange:g=>p({anniversaryField:g}),children:[e.jsx(gs,{children:e.jsx(bs,{placeholder:"Field"})}),e.jsx(ys,{children:O7t.map(g=>e.jsx(Ye,{value:g.value,children:g.label},g.value))})]}),e.jsxs(vs,{value:c.anniversaryMonth?String(c.anniversaryMonth):"all",onValueChange:g=>p({anniversaryMonth:g==="all"?void 0:Number(g)}),children:[e.jsx(gs,{children:e.jsx(bs,{placeholder:"Any month"})}),e.jsxs(ys,{children:[e.jsx(Ye,{value:"all",children:"Any month"}),m4e.map(g=>e.jsx(Ye,{value:String(g.value),children:g.label},g.value))]})]})]})]})]}),e.jsx(k4,{title:"Date Added",children:e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-2",children:[e.jsx(Kxt,{label:"From",value:c.dateAddedFrom,onChange:g=>p({dateAddedFrom:g||void 0})}),e.jsx(Kxt,{label:"To",value:c.dateAddedTo,onChange:g=>p({dateAddedTo:g||void 0})})]})}),e.jsx(k4,{title:"Lead Source",children:e.jsxs(vs,{value:c.leadSourceId||"all",onValueChange:g=>p({leadSourceId:g==="all"?void 0:g}),children:[e.jsx(gs,{children:e.jsx(bs,{placeholder:"All sources"})}),e.jsxs(ys,{children:[e.jsx(Ye,{value:"all",children:"All sources"}),e.jsx(Ye,{value:"none",children:"No source"}),m==null?void 0:m.map(g=>e.jsx(Ye,{value:g.id,children:g.name},g.id))]})]})})]}),e.jsx(Jt,{value:"behavior",className:"space-y-6 mt-4",children:n?e.jsxs(e.Fragment,{children:[e.jsxs(k4,{title:"Last Active On Site",children:[e.jsx(wb,{value:c.lastActive||"",onValueChange:g=>p({lastActive:g||void 0}),className:"grid grid-cols-2 gap-2",children:lkn.map(g=>e.jsxs("label",{className:"flex items-center gap-2 rounded-md border px-3 py-2 cursor-pointer hover:bg-accent",children:[e.jsx(rh,{value:g.value}),e.jsx("span",{className:"text-sm",children:g.label})]},g.value))}),c.lastActive&&e.jsx($,{variant:"ghost",size:"sm",className:"mt-1 h-7 px-2 text-xs",onClick:()=>p({lastActive:void 0}),children:"Clear"})]}),e.jsxs(k4,{title:"Registration",children:[e.jsx(Uy,{label:"Registered on lead site",checked:c.registered==="yes",onChange:g=>p({registered:g?"yes":void 0})}),e.jsx(Uy,{label:"Anonymous visitors only",checked:c.registered==="no",onChange:g=>p({registered:g?"no":void 0})})]}),e.jsxs(k4,{title:"Property Activity",children:[e.jsx(Uy,{label:"Viewed any listing",checked:c.viewedListing==="any",onChange:g=>p({viewedListing:g?"any":void 0})}),e.jsx(Uy,{label:"Hot buyer — 3+ views in last 7 days",checked:c.viewedListing==="multiple7d",onChange:g=>p({viewedListing:g?"multiple7d":void 0})}),e.jsx(Uy,{label:"Saved a property",checked:!!c.savedProperty,onChange:g=>p({savedProperty:g||void 0})}),e.jsx(Uy,{label:"Has an active saved search / alert",checked:!!c.hasSavedSearch,onChange:g=>p({hasSavedSearch:g||void 0})})]}),e.jsxs(k4,{title:"Requests",children:[e.jsx(Uy,{label:"Requested a showing / asked a question",checked:!!c.requestedShowing,onChange:g=>p({requestedShowing:g||void 0})}),e.jsx(Uy,{label:"Requested a home valuation",checked:!!c.requestedValuation,onChange:g=>p({requestedValuation:g||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(Jt,{value:"engagement",className:"space-y-4 mt-4",children:[e.jsx(Uy,{label:"Any website activity",checked:!!c.websiteActiveOnly,onChange:g=>p({websiteActiveOnly:g||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(h4t,{className:"mt-6 flex-row gap-2 sm:justify-between",children:[e.jsx($,{variant:"ghost",onClick:()=>d({}),disabled:x===0,children:"Clear behavior filters"}),e.jsx($,{onClick:()=>{a(c),t(!1)},children:"Apply"})]})]})})}function k4({title:s,children:t}){return e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{className:"text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:s}),e.jsx("div",{className:"space-y-2",children:t})]})}function Uy({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(Tn,{checked:t,onCheckedChange:n})]})}function _8e({label:s,value:t,onChange:n,placeholder:r}){return e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{className:"text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:s}),e.jsxs("div",{className:"relative",children:[e.jsx(be,{value:t,onChange:a=>n(a.target.value),placeholder:r,className:"h-8"}),t&&e.jsx("button",{onClick:()=>n(""),className:"absolute right-2 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground",children:e.jsx(pr,{className:"h-3 w-3"})})]})]})}function Kxt({label:s,value:t,onChange:n}){const[r,a]=j.useState(!1),i=t?Lp(t):void 0;return e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{className:"text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:s}),e.jsxs(Sc,{open:r,onOpenChange:a,children:[e.jsx(Cc,{asChild:!0,children:e.jsxs($,{variant:"outline",className:Tt("w-full justify-start text-left font-normal h-8",!i&&"text-muted-foreground"),children:[e.jsx(ia,{className:"mr-2 h-3.5 w-3.5"}),i?Hs(i,"MMM d, yyyy"):e.jsx("span",{children:"Pick a date"})]})}),e.jsx(xc,{className:"w-auto p-0",align:"start",children:e.jsx(y1,{mode:"single",selected:i,onSelect:l=>{n(l?Hs(l,"yyyy-MM-dd"):void 0),a(!1)},initialFocus:!0})})]})]})}function dkn({behavior:s,onRemove:t,onClearAll:n}){const r=ukn(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 ukn(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=m4e.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=m4e.find(i=>i.value===s.anniversaryMonth),a=((n=O7t.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 ${Hs(Lp(s.dateAddedFrom),"MMM d, yyyy")}`}),s.dateAddedTo&&t.push({key:"dateAddedTo",label:`Added on/before ${Hs(Lp(s.dateAddedTo),"MMM d, yyyy")}`}),s.leadSourceId&&t.push({key:"leadSourceId",label:s.leadSourceId==="none"?"No lead source":"Lead source"}),t}async function R7(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 AG(){return{lastActiveAt:null,registered:!1,propertyViewCount:0,propertyViewCount7d:0,savedListingCount:0,activeSavedSearchCount:0,showingRequests:0,valuationRequests:0,viewedCities:[],viewedZips:[]}}function hkn(){const{user:s}=_s(),{leadSite:t,hasLeadSite:n}=Mf(),{data:r,isLoading:a}=ht({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=(b,v)=>{const N=i.get(b)||AG();i.set(b,{...N,...v})},o=await R7((b,v)=>U.from("lead_site_visitors").select("id, contact_id, last_seen_at, email").eq("lead_site_id",t.id).not("contact_id","is",null).range(b,v)),c=new Map,d=new Map;o.forEach(b=>{if(!b.contact_id)return;c.set(b.id,b.contact_id),b.email&&d.set(b.email.toLowerCase(),b.contact_id);const v=i.get(b.contact_id);(!v||!v.lastActiveAt||b.last_seen_at>v.lastActiveAt)&&l(b.contact_id,{lastActiveAt:b.last_seen_at})});const u=await R7((b,v)=>U.from("lead_site_consumer_profiles").select("contact_id, user_id").eq("lead_site_id",t.id).not("contact_id","is",null).range(b,v)),h=new Map;u.forEach(b=>{b.contact_id&&(h.set(b.user_id,b.contact_id),l(b.contact_id,{registered:!0}))});const m=new Date(Date.now()-7*24*60*60*1e3).toISOString();return(await R7((b,v)=>U.from("lead_site_property_views").select("visitor_id, viewed_at, property_address").eq("lead_site_id",t.id).not("visitor_id","is",null).range(b,v))).forEach(b=>{const v=b.visitor_id?c.get(b.visitor_id):null;if(!v)return;const N=i.get(v)||AG();N.propertyViewCount+=1,b.viewed_at>=m&&(N.propertyViewCount7d+=1),i.set(v,N)}),(await R7((b,v)=>U.from("lead_site_saved_listings").select("user_id, mls_number").eq("lead_site_id",t.id).range(b,v))).forEach(b=>{const v=h.get(b.user_id);if(!v)return;const N=i.get(v)||AG();N.savedListingCount+=1,i.set(v,N)}),(await R7((b,v)=>U.from("lead_site_saved_searches").select("user_id").eq("lead_site_id",t.id).eq("is_active",!0).range(b,v))).forEach(b=>{const v=h.get(b.user_id);if(!v)return;const N=i.get(v)||AG();N.activeSavedSearchCount+=1,i.set(v,N)}),(await R7((b,v)=>U.from("lead_site_leads").select("email, lead_type").eq("lead_site_id",t.id).not("email","is",null).range(b,v))).forEach(b=>{if(!b.email)return;const v=d.get(b.email.toLowerCase());if(!v)return;const N=i.get(v)||AG(),C=(b.lead_type||"").toLowerCase();(C.includes("showing")||C.includes("question")||C==="contact")&&(N.showingRequests+=1),(C.includes("valuation")||C.includes("cma")||C.includes("home_value"))&&(N.valuationRequests+=1),i.set(v,N)}),i},enabled:!!s&&n,staleTime:5*60*1e3});return{behaviorMap:r??new Map,hasLeadSite:n,isLoading:a}}const F7t="innercircle_geocode_cache_v1";function mkn(){try{return JSON.parse(localStorage.getItem(F7t)||"{}")}catch{return{}}}function pkn(s){try{localStorage.setItem(F7t,JSON.stringify(s))}catch{}}function fkn(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 xkn({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}),[x,g]=j.useState(!1),[y,b]=j.useState("heat");j.useEffect(()=>{if(!s)return;let N=!1;return(async()=>{d(!0);const{data:C}=await U.from("settings").select("value").eq("key","mapbox_public_token").maybeSingle();N||(o((C==null?void 0:C.value)||""),d(!1))})(),()=>{N=!0}},[s]),j.useEffect(()=>{if(!s||!l)return;let N=!1;return(async()=>{const A=mkn(),T=n.map(V=>({c:V,addr:fkn(V)})).filter(V=>V.addr),P=[],M=[];for(const{c:V,addr:K}of T){const Q=A[K];Q!==null&&(Q?P.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:Q.lat,lng:Q.lng}):M.push({c:V,addr:K}))}if(N||h(P),p({done:P.length,total:T.length}),M.length===0)return;g(!0);const I=6;let D=0;const B={...A},q=[...P],W=async()=>{var V;for(;D{N=!0}},[s,l,n]);const v=j.useMemo(()=>{const N=new Map;for(const C of n){const A=(C.city||"").trim();if(!A)continue;const T=(C.state||"").trim()||null,P=`${A.toLowerCase()}|${T||""}`,M=N.get(P);M?M.count++:N.set(P,{city:A,state:T,count:1})}return Array.from(N.values()).sort((C,A)=>A.count-C.count)},[n]);return j.useEffect(()=>{if(!(!s||!l||!a.current||i.current))return Wc.accessToken=l,i.current=new Wc.Map({container:a.current,style:"mapbox://styles/mapbox/light-v11",center:[-98.5795,39.8283],zoom:3.5}),i.current.addControl(new Wc.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 C=()=>{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]}}))},P=N.getSource("contacts-src");if(P?P.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 B;const I=(B=M.features)==null?void 0:B[0];if(!I)return;const D=I.geometry.coordinates.slice();new Wc.Popup({offset:12}).setLngLat(D).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 Wc.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()?C():N.once("load",C)},[u,y]),e.jsx(Os,{open:s,onOpenChange:t,children:e.jsxs(Rs,{className:"max-w-6xl w-[95vw] h-[90vh] p-0 flex flex-col",children:[e.jsx(Us,{className:"p-4 pb-2 border-b",children:e.jsxs(zs,{className:"flex items-center gap-2",children:[e.jsx(yd,{className:"h-5 w-5 text-orange-500"}),"Geographic Heat Map",e.jsxs($e,{variant:"secondary",className:"ml-2",children:[u.length," mapped · ",v.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(Ht,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):l?e.jsxs(e.Fragment,{children:[e.jsx("div",{ref:a,className:"absolute inset-0"}),e.jsxs("div",{className:"absolute top-3 left-3 flex flex-col gap-2 z-10",children:[e.jsxs("div",{className:"bg-background/95 backdrop-blur rounded-md shadow-md border p-1 flex",children:[e.jsxs($,{size:"sm",variant:y==="heat"?"default":"ghost",onClick:()=>b("heat"),className:"h-8",children:[e.jsx(yd,{className:"h-3.5 w-3.5 mr-1"})," Heat"]}),e.jsxs($,{size:"sm",variant:y==="points"?"default":"ghost",onClick:()=>b("points"),className:"h-8",children:[e.jsx(xR,{className:"h-3.5 w-3.5 mr-1"})," Pins"]})]}),x&&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(Ht,{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(xo,{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(ai,{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(Oi,{className:"flex-1",children:e.jsxs("div",{className:"p-2 space-y-1.5",children:[v.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."}),v.slice(0,50).map((N,C)=>{var P;const A=((P=v[0])==null?void 0:P.count)||1,T=N.count/A*100;return e.jsx(_e,{className:"cursor-pointer hover:border-primary transition-colors overflow-hidden",onClick:()=>{r==null||r(N.city,N.state),t(!1)},children:e.jsxs(Oe,{className:"p-2.5 relative",children:[e.jsx("div",{className:"absolute inset-y-0 left-0 bg-primary/10",style:{width:`${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:C===0?"🔥 Hottest market":`Rank #${C+1}`})]}),e.jsx($e,{variant:"secondary",className:"shrink-0",children:N.count})]})]})},`${N.city}-${N.state}-${C}`)})]})})]})]})]})})}function d8(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 Yxt({birthday:s,homeAnniversary:t,weddingAnniversary:n,className:r,contactId:a,contactName:i,contactAddress:l}){const o=Vn(),c=w8e(s,"birthday",7),d=w8e(t,"anniversary",7),u=w8e(n||null,"anniversary",7);if(!c&&!d&&!u)return null;const h=(m,p,x)=>{x.stopPropagation();const g=new URLSearchParams;a&&g.set("contactId",a),i&&g.set("name",i),l&&g.set("address",l),(m==="home_anniversary"||m==="wedding_anniversary")&&p&&g.set("date",p),g.set("cardType",m),o(`/mission-control/card-studio?${g.toString()}`)};return e.jsxs("div",{className:Tt("flex flex-wrap gap-1",r),children:[c&&e.jsxs("div",{className:"flex items-center gap-0.5",children:[e.jsx($e,{variant:"secondary",className:Tt("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(nn,{className:"h-2.5 w-2.5"}),"Send Card"]})]}),d&&e.jsxs("div",{className:"flex items-center gap-0.5",children:[e.jsx($e,{variant:"secondary",className:Tt("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(nn,{className:"h-2.5 w-2.5"}),"Send Card"]})]}),u&&e.jsxs("div",{className:"flex items-center gap-0.5",children:[e.jsxs($e,{variant:"secondary",className:Tt("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(nn,{className:"h-2.5 w-2.5"}),"Send Card"]})]})]})}function Zxt({deal:s}){if(!s||!s.stage)return null;const{stage:t}=s;return e.jsxs($e,{variant:"outline",className:"text-[10px] gap-1 font-medium whitespace-nowrap",style:{borderColor:t.color,color:t.color,backgroundColor:`${t.color}10`},children:[e.jsx("span",{className:"h-1.5 w-1.5 rounded-full inline-block",style:{backgroundColor:t.color}}),t.name]})}function Xxt({count:s,className:t}){return!s||s<=0?null:e.jsxs($e,{variant:"outline",className:Tt("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(MT,{className:"h-2.5 w-2.5"}),s===1?"In drip":`${s} drips`]})}function gkn(){const s=Za();return ht({queryKey:["contacts-campaign-counts",s],queryFn:async()=>{if(!s)return{};const{data:t,error:n}=await U.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 ykn(){const s=Za();return ht({queryKey:["contact-deals-map",s],queryFn:async()=>{const{data:t,error:n}=await U.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 vkn="#6366F1";function Qxt(s,t){return`color-mix(in srgb, ${s} ${t}%, transparent)`}function bkn(s){return`color-mix(in oklab, ${s} 78%, hsl(var(--foreground)))`}function z7t({label:s,color:t,className:n,onClick:r,title:a}){const i=t||vkn,l=r?"button":"span";return e.jsxs(l,{type:r?"button":void 0,onClick:r,title:a??s,style:{backgroundColor:Qxt(i,14),color:bkn(i),boxShadow:`inset 0 0 0 1px ${Qxt(i,22)}`},className:Tt("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 _kn({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:Tt("flex flex-wrap items-center gap-1.5",n),children:[i.map(o=>{var c,d;return e.jsx(z7t,{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 Jxt({contactId:s,compact:t=!1}){const{data:n}=oV(),{data:r}=l1n(s),a=uYe(),i=zFt(),l=u1n(),[o,c]=j.useState(!1),[d,u]=j.useState(""),h=j.useRef(null),m=new Set((r==null?void 0:r.map(b=>b.tag_id))||[]),p=(n==null?void 0:n.filter(b=>b.name.toLowerCase().includes(d.toLowerCase())))||[],x=n==null?void 0:n.find(b=>b.name.toLowerCase()===d.trim().toLowerCase()),g=async b=>{m.has(b.id)?await l.mutateAsync({contactId:s,tagId:b.id}):await i.mutateAsync({contactId:s,tagId:b.id})},y=async()=>{if(!(!d.trim()||x))try{const b=await a.mutateAsync({name:d.trim()});await i.mutateAsync({contactId:s,tagId:b.id}),u("")}catch{}};return e.jsxs("div",{className:"flex flex-wrap items-center gap-1.5",children:[r==null?void 0:r.map(b=>{var v,N,C;return e.jsxs($e,{variant:"outline",className:"text-xs gap-1 pr-1",style:{borderColor:((v=b.tag)==null?void 0:v.color)||"#6366F1",color:((N=b.tag)==null?void 0:N.color)||"#6366F1"},children:[e.jsx(Up,{className:"h-2.5 w-2.5"}),(C=b.tag)==null?void 0:C.name,e.jsx("button",{onClick:A=>{A.stopPropagation(),l.mutate({contactId:s,tagId:b.tag_id})},className:"ml-0.5 rounded-full hover:bg-accent p-0.5",children:e.jsx(pr,{className:"h-2.5 w-2.5"})})]},b.id)}),e.jsxs(Sc,{open:o,onOpenChange:c,children:[e.jsx(Cc,{asChild:!0,children:e.jsxs($,{variant:"ghost",size:"sm",className:t?"h-6 w-6 p-0":"h-6 px-2 text-xs",onClick:b=>b.stopPropagation(),children:[e.jsx(sn,{className:"h-3 w-3"}),!t&&e.jsx("span",{className:"ml-1",children:"Tag"})]})}),e.jsxs(xc,{className:"w-56 p-2",align:"start",onClick:b=>b.stopPropagation(),children:[e.jsx(be,{ref:h,placeholder:"Search or create tag...",value:d,onChange:b=>u(b.target.value),onKeyDown:b=>{b.key==="Enter"&&d.trim()&&!x?(b.preventDefault(),y()):b.key==="Enter"&&x&&!m.has(x.id)&&(b.preventDefault(),g(x))},className:"h-8 text-sm mb-2"}),e.jsxs("div",{className:"max-h-[200px] overflow-y-auto space-y-0.5",children:[p.map(b=>e.jsxs("button",{onClick:()=>g(b),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:b.color}}),e.jsx("span",{className:"flex-1 text-left truncate",children:b.name}),m.has(b.id)&&e.jsx(oa,{className:"h-3.5 w-3.5 text-primary shrink-0"})]},b.id)),d.trim()&&!x&&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(sn,{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 egt({contactId:s,tags:t,max:n=2}){return!t||t.length===0?null:e.jsx(_kn,{tags:t,max:n})}const Ure=["#6366F1","#8B5CF6","#EC4899","#EF4444","#F97316","#F59E0B","#10B981","#14B8A6","#06B6D4","#3B82F6","#6B7280","#1F2937"];function wkn({open:s,onOpenChange:t}){const{data:n,isLoading:r}=oV(),a=uYe(),i=d1n(),l=c1n(),[o,c]=j.useState(""),[d,u]=j.useState(Ure[0]),[h,m]=j.useState(null),[p,x]=j.useState(""),[g,y]=j.useState(""),b=async()=>{if(o.trim())try{await a.mutateAsync({name:o.trim(),color:d}),c(""),u(Ure[0]),ja({title:"Tag created"})}catch(A){ja({title:"Error",description:A.message,variant:"destructive"})}},v=async A=>{if(p.trim())try{await i.mutateAsync({id:A,name:p.trim(),color:g}),m(null),ja({title:"Tag updated"})}catch(T){ja({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),ja({title:"Tag deleted"})}catch(P){ja({title:"Error",description:P.message,variant:"destructive"})}},C=A=>{m(A.id),x(A.name),y(A.color)};return e.jsx(Os,{open:s,onOpenChange:t,children:e.jsxs(Rs,{className:"max-w-md",children:[e.jsx(Us,{children:e.jsx(zs,{children:"Manage Tags"})}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex gap-2",children:[e.jsx(be,{placeholder:"New tag name...",value:o,onChange:A=>c(A.target.value),onKeyDown:A=>A.key==="Enter"&&b(),className:"flex-1 h-9"}),e.jsxs($,{size:"sm",onClick:b,disabled:!o.trim()||a.isPending,className:"h-9",children:[e.jsx(sn,{className:"h-4 w-4 mr-1"}),"Add"]})]}),e.jsx("div",{className:"flex flex-wrap gap-1.5",children:Ure.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:Ure.map(T=>e.jsx("button",{onClick:()=>y(T),className:`h-5 w-5 rounded-full border-2 ${g===T?"border-foreground":"border-transparent"}`,style:{backgroundColor:T}},T))}),e.jsx(be,{value:p,onChange:T=>x(T.target.value),onKeyDown:T=>T.key==="Enter"&&v(A.id),className:"flex-1 h-8 text-sm",autoFocus:!0}),e.jsx($,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:()=>v(A.id),children:e.jsx(oa,{className:"h-4 w-4 text-primary"})}),e.jsx($,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:()=>m(null),children:e.jsx(pr,{className:"h-4 w-4"})})]}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"h-3.5 w-3.5 rounded-full shrink-0",style:{backgroundColor:A.color}}),e.jsx("span",{className:"flex-1 text-sm",children:A.name}),e.jsx($,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0 opacity-0 group-hover:opacity-100 transition-opacity",onClick:()=>C(A),children:e.jsx(Ya,{className:"h-3.5 w-3.5"})}),e.jsx($,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0 opacity-0 group-hover:opacity-100 transition-opacity text-destructive hover:text-destructive",onClick:()=>N(A.id,A.name),children:e.jsx(Pn,{className:"h-3.5 w-3.5"})})]})},A.id))]})]})})}function jkn({open:s,onOpenChange:t}){const{data:n,isLoading:r}=XO(),a=gGe(),i=gAs(),l=yAs(),[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(b){ae.error(b.message||"Failed to add lead source")}},x=async b=>{if(h.trim())try{await i.mutateAsync({id:b,name:h.trim()}),u(null)}catch(v){ae.error(v.message||"Failed to update")}},g=async(b,v)=>{if(await Yi(`Remove lead source "${v}"? Contacts using it will keep the label but it won't appear in new dropdowns.`))try{await l.mutateAsync(b)}catch(N){ae.error(N.message||"Failed to remove")}},y=b=>{u(b.id),m(b.name)};return e.jsx(Os,{open:s,onOpenChange:t,children:e.jsxs(Rs,{className:"max-w-md",children:[e.jsx(Us,{children:e.jsx(zs,{children:"Manage Lead Sources"})}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(be,{placeholder:"New lead source name...",value:o,onChange:b=>c(b.target.value),onKeyDown:b=>b.key==="Enter"&&p(),className:"flex-1 h-9"}),e.jsxs($,{size:"sm",onClick:p,disabled:!o.trim()||a.isPending,className:"h-9",children:[e.jsx(sn,{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(b=>e.jsx("div",{className:"flex items-center gap-2 p-2 rounded-lg hover:bg-accent/50 group",children:d===b.id?e.jsxs(e.Fragment,{children:[e.jsx(be,{value:h,onChange:v=>m(v.target.value),onKeyDown:v=>v.key==="Enter"&&x(b.id),className:"flex-1 h-8 text-sm",autoFocus:!0}),e.jsx($,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:()=>x(b.id),children:e.jsx(oa,{className:"h-4 w-4 text-primary"})}),e.jsx($,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:()=>u(null),children:e.jsx(pr,{className:"h-4 w-4"})})]}):e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"flex-1 text-sm",children:b.name}),b.owner_user_id&&e.jsxs(e.Fragment,{children:[e.jsx($,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0 opacity-0 group-hover:opacity-100 transition-opacity",onClick:()=>y(b),children:e.jsx(Ya,{className:"h-3.5 w-3.5"})}),e.jsx($,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0 opacity-0 group-hover:opacity-100 transition-opacity text-destructive hover:text-destructive",onClick:()=>g(b.id,b.name),children:e.jsx(Pn,{className:"h-3.5 w-3.5"})})]}),!b.owner_user_id&&e.jsx("span",{className:"text-xs text-muted-foreground",children:"Default"})]})},b.id))]})]})})}function B7t({value:s,onChange:t,label:n="Lead Source"}){const{data:r}=XO(),a=gGe(),[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(se,{children:n}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(vs,{value:s||"_none",onValueChange:u=>t(u==="_none"?"":u),children:[e.jsx(gs,{className:"flex-1",children:e.jsx(bs,{placeholder:"Select lead source"})}),e.jsxs(ys,{children:[e.jsx(Ye,{value:"_none",children:"No source"}),r==null?void 0:r.map(u=>e.jsx(Ye,{value:u.id,children:u.name},u.id))]})]}),e.jsx($,{type:"button",variant:"outline",size:"icon",className:"shrink-0",onClick:()=>l(!i),children:i?e.jsx(pr,{className:"h-4 w-4"}):e.jsx(sn,{className:"h-4 w-4"})})]}),i&&e.jsxs("div",{className:"flex gap-2",children:[e.jsx(be,{placeholder:"New lead source name...",value:o,onChange:u=>c(u.target.value),onKeyDown:u=>{u.key==="Enter"&&(u.preventDefault(),d())},className:"flex-1"}),e.jsx($,{type:"button",size:"sm",onClick:d,disabled:!o.trim()||a.isPending,children:"Add"})]})]})}function aBe({contactId:s,currentSpouseContactId:t,currentSpouseName:n,currentSpouseEmail:r,onLink:a,onUnlink:i,isEditing:l}){const o=Vn(),c=Za(),[d,u]=j.useState(!1),[h,m]=j.useState(""),{data:p}=ht({queryKey:["innercircle-contact-spouse",t],queryFn:async()=>{const{data:g,error:y}=await U.from("innercircle_contacts").select("id, first_name, last_name, email, phone, birthday").eq("id",t).maybeSingle();if(y)throw y;return g},enabled:!!t}),{data:x}=ht({queryKey:["spouse-search",c,s,h],queryFn:async()=>{let g=U.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 v=h.replace(/[,()%]/g," ").trim();v&&(g=g.or(`first_name.ilike.%${v}%,last_name.ilike.%${v}%,email.ilike.%${v}%,phone.ilike.%${v}%`))}const{data:y,error:b}=await g;if(b)throw b;return y},enabled:d&&!!c});if(t&&p){const g=`${p.first_name} ${p.last_name||""}`.trim();return e.jsxs("div",{className:"space-y-1",children:[e.jsx(se,{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(Lo,{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:g}),e.jsx("div",{className:"text-xs text-muted-foreground truncate",children:[p.phone,p.email].filter(Boolean).join(" · ")||"No contact info"})]}),l&&e.jsxs($,{variant:"ghost",size:"sm",onClick:i,className:"shrink-0 h-7 px-2",children:[e.jsx(AR,{className:"h-3.5 w-3.5 mr-1"}),"Unlink"]}),!l&&e.jsx($,{variant:"ghost",size:"sm",onClick:()=>o(`/mission-control/contacts/${p.id}`),className:"shrink-0 h-7 px-2",children:e.jsx(ni,{className:"h-3.5 w-3.5"})})]})]})}return!t&&(n||r)?e.jsxs("div",{className:"space-y-1",children:[e.jsx(se,{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(Lo,{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(Sc,{open:d,onOpenChange:u,children:[e.jsx(Cc,{asChild:!0,children:e.jsxs($,{variant:"outline",size:"sm",className:"shrink-0 h-7 px-2",children:[e.jsx(Dc,{className:"h-3.5 w-3.5 mr-1"}),"Link Contact"]})}),e.jsx(xc,{className:"w-72 p-2",align:"end",children:e.jsx(tgt,{search:h,setSearch:m,results:x,onSelect:g=>{a(g),u(!1),m("")}})})]})]})]}):l?e.jsxs("div",{className:"space-y-1",children:[e.jsx(se,{className:"text-sm font-medium",children:"Spouse / Partner"}),e.jsxs(Sc,{open:d,onOpenChange:u,children:[e.jsx(Cc,{asChild:!0,children:e.jsxs($,{variant:"outline",className:"w-full justify-start text-muted-foreground font-normal h-10",children:[e.jsx(Dc,{className:"h-4 w-4 mr-2"}),"Link an existing contact as spouse..."]})}),e.jsx(xc,{className:"w-72 p-2",align:"start",children:e.jsx(tgt,{search:h,setSearch:m,results:x,onSelect:g=>{a(g),u(!1),m("")}})})]})]}):null}function tgt({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(Vr,{className:"absolute left-2 top-2.5 h-3.5 w-3.5 text-muted-foreground"}),e.jsx(be,{value:s,onChange:a=>t(a.target.value),placeholder:"Search contacts...",className:"pl-7 h-8 text-sm",autoFocus:!0})]}),e.jsx(Oi,{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 Nkn={warm:"stroke-emerald-500",cooling:"stroke-amber-500","at-risk":"stroke-red-500"},kkn={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 Skn({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:Tt("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:Nkn[t]})]}),e.jsx("span",{className:Tt("absolute inset-0 flex items-center justify-center font-semibold tabular-nums",kkn[t],n>=56?"text-lg":"text-[11px]"),children:o})]})}const qre=new Map;async function Ckn(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 Akn(s,t=256){const n=s.trim().toLowerCase();if(!n||!n.includes("@"))return null;const r=`${n}|${t}`;if(qre.has(r))return qre.get(r)??null;try{const i=`https://gravatar.com/avatar/${await Ckn(n)}?s=${t}&d=404`;return qre.set(r,i),i}catch{return qre.set(r,null),null}}function Ekn(s,t=256){const[n,r]=j.useState(null);return j.useEffect(()=>{let a=!0;if(!s){r(null);return}return Akn(s,t).then(i=>{a&&r(i)}),()=>{a=!1}},[s,t]),n}function $7t({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=Ekn(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:Tt("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 Tkn({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(Mx,{children:[e.jsx(Lx,{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(qn,{className:"h-3 w-3"})})}),e.jsx(tx,{children:r})]})}function Mkn({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 x=!!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(sn,{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(yd,{className:"h-4 w-4",style:{color:"hsl(var(--hub-glow))"}}),"Heat Map"]}),e.jsxs(Hd,{children:[e.jsx(Gd,{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(si,{className:"h-4 w-4",style:{color:"hsl(var(--hub-glow))"}}),"Import",e.jsx(_o,{className:"h-3.5 w-3.5 opacity-70"})]})}),e.jsxs(Md,{align:"end",children:[e.jsxs(Na,{onClick:i,children:[e.jsx(si,{className:"mr-2 h-4 w-4"})," Import CSV"]}),e.jsxs(Na,{onClick:l,children:[e.jsx(dv,{className:"mr-2 h-4 w-4"})," Import from Phone"]}),e.jsxs(Na,{onClick:o,children:[e.jsx(Up,{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(Vr,{className:"pointer-events-none absolute left-3.5 top-1/2 h-4 w-4 -translate-y-1/2 opacity-70"}),e.jsx(be,{value:n,onChange:g=>r(g.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"})]}),x&&e.jsx("div",{className:"hub-glass inline-flex shrink-0 items-center gap-1 rounded-xl p-1",children:[{key:"my",label:"Mine",icon:qn,show:!0},{key:"team",label:"Team",icon:qn,show:!!h},{key:"lead-pond",label:"Pond",icon:f1,show:!!m}].filter(g=>g.show).map(g=>e.jsxs("button",{onClick:()=>u==null?void 0:u(g.key),className:Tt("inline-flex items-center gap-1.5 rounded-lg px-3 py-1.5 text-xs font-semibold transition-colors",d===g.key?"bg-background text-foreground shadow-sm":"hub-ink-muted"),children:[e.jsx(g.icon,{className:"h-3.5 w-3.5"}),g.label]},g.key))})]}),e.jsx("div",{className:"grid grid-cols-2 gap-2 sm:grid-cols-4",children:t.map(g=>e.jsxs("button",{onClick:g.onClick,className:Tt("hub-glass rounded-xl px-3 py-2.5 text-left transition-colors",g.active&&"ring-2 ring-white/40"),children:[e.jsx("span",{className:"text-xl font-bold",children:g.value}),e.jsx("p",{className:"mt-0.5 text-[11px] hub-ink-muted",children:g.label})]},g.label))})]})})}function Lkn({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(on,{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(on,{className:"h-9 w-9 rounded-full"}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(on,{className:"h-3.5 w-36"}),e.jsx(on,{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(on,{className:"h-3.5 w-20"})},i))]},r))})}function Pkn({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(on,{className:"h-10 w-10 rounded-full"}),e.jsxs("div",{className:"flex-1 space-y-2",children:[e.jsx(on,{className:"h-4 w-2/5"}),e.jsx(on,{className:"h-3 w-3/5"})]})]}),e.jsxs("div",{className:"mt-3 flex gap-2",children:[e.jsx(on,{className:"h-6 w-16 rounded-full"}),e.jsx(on,{className:"h-6 w-20 rounded-full"})]})]},n))})}function sgt({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 U7t(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 ngt(s){if(!s)return null;const t=mu(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:il,color:"text-violet-600 dark:text-violet-400",match:s=>s.relationshipScore.daysSinceTouch===null},{key:"stale-90",title:"Stale 90+ Days",icon:Hr,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:Z_,color:"text-cyan-600 dark:text-cyan-400",match:s=>s.relationshipScore.status==="cooling"},{key:"birthdays-soon",title:"Birthdays Soon",icon:np,color:"text-pink-600 dark:text-pink-400",match:(s,t)=>t.daysToBirthday!==null&&t.daysToBirthday<=30},{key:"anniversary-soon",title:"Home Anniversary",icon:sa,color:"text-emerald-600 dark:text-emerald-400",match:(s,t)=>t.daysToAnniv!==null&&t.daysToAnniv<=30},{key:"has-deal",title:"Active Deal",icon:ix,color:"text-teal-700 dark:text-teal-400",match:(s,t)=>t.hasDeal},{key:"website-active",title:"Active on Site",icon:Gl,color:"text-indigo-600 dark:text-indigo-400",match:()=>!1},{key:"vips",title:"VIPs",icon:dn,color:"text-amber-600 dark:text-amber-300",match:s=>s.relationshipScore.score>=80},{key:"missing-info",title:"Missing Info",icon:mc,color:"text-slate-600 dark:text-slate-400",match:s=>U7t(s)}];function Ikn({contacts:s,contactDealsMap:t,websiteActiveIds:n,totalCount:r,activeKey:a,onSelectSegment:i,currentFilters:l,currentSortBy:o,activeViewId:c,onApplyView:d,onClearAll:u}){const{data:h}=hYe(),m=BFt(),p=$Ft(),[x,g]=j.useState(!1),[y,b]=j.useState(""),v=j.useMemo(()=>{const T={"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};if(!s)return T;for(const P of s){const M={hasDeal:!!(t&&t[P.id]),daysToBirthday:ngt(P.birthday),daysToAnniv:ngt(P.home_anniversary)};for(const I of rgt)I.key!=="website-active"&&I.match(P,M)&&T[I.key]++}return T},[s,t,n]),N=!!l.search||!!l.type&&l.type!=="all"||!!l.status&&l.status!=="all"||!!l.behavior&&Object.values(l.behavior).some(T=>T!==void 0&&T!==!1),C=async()=>{y.trim()&&(await m.mutateAsync({name:y.trim(),filters:l,sort_by:o}),b(""),g(!1))},A="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:u,className:Tt(A,!a&&!c?"bg-primary text-primary-foreground border-primary":"bg-card hover:bg-accent border-border"),children:[e.jsx(qn,{className:"h-3.5 w-3.5"}),"All Contacts",e.jsx("span",{className:"tabular-nums opacity-70",children:r.toLocaleString()})]}),h==null?void 0:h.map(T=>{const P=c===T.id;return e.jsxs("div",{className:Tt(A,"group pr-1",P?"bg-primary text-primary-foreground border-primary":"bg-card hover:bg-accent border-border"),children:[e.jsx("button",{type:"button",onClick:()=>d(T.id,T.filters,T.sort_by),children:T.name}),e.jsx("button",{type:"button","aria-label":`Delete view ${T.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:()=>{p.mutate(T.id),P&&u()},children:e.jsx(pr,{className:"h-3 w-3"})})]},T.id)}),e.jsx("div",{className:"h-5 w-px bg-border shrink-0"}),rgt.map(T=>{const P=T.icon,M=v[T.key],I=a===T.key;return e.jsxs("button",{type:"button",onClick:()=>i(I?null:T.key),"aria-pressed":I,className:Tt(A,I?"bg-primary text-primary-foreground border-primary":"bg-card hover:bg-accent border-border",!I&&M===0&&"opacity-55"),children:[e.jsx(P,{className:Tt("h-3.5 w-3.5",I?"":T.color)}),T.title,e.jsx("span",{className:"tabular-nums opacity-70",children:M.toLocaleString()})]},T.key)}),e.jsxs($,{variant:"ghost",size:"sm",className:"h-8 gap-1.5 text-xs shrink-0",disabled:!N,onClick:()=>g(!0),children:[e.jsx(fT,{className:"h-3.5 w-3.5"}),"Save view"]})]}),e.jsx(Os,{open:x,onOpenChange:g,children:e.jsxs(Rs,{className:"sm:max-w-sm",children:[e.jsxs(Us,{children:[e.jsx(zs,{children:"Save this view"}),e.jsx(Sr,{children:"Your current search, filters, and sorting are saved as a one-click chip."})]}),e.jsx(be,{autoFocus:!0,placeholder:"e.g. Past clients cooling off",value:y,onChange:T=>b(T.target.value),onKeyDown:T=>T.key==="Enter"&&C()}),e.jsxs(kr,{children:[e.jsx($,{variant:"outline",onClick:()=>g(!1),children:"Cancel"}),e.jsx($,{onClick:C,disabled:!y.trim()||m.isPending,children:"Save view"})]})]})})]})}const agt=[{key:"relationship",label:"Relationship"},{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"}],j8e={relationship:!0,stage:!0,leadSource:!0,tags:!0,lastTouch:!0,nextAction:!0,dealValue:!0,email:!1,phone:!1,address:!1,birthday:!1},igt="innercircle:contact-columns:v1";function Dkn(){const[s,t]=j.useState(()=>{try{const a=localStorage.getItem(igt);if(a)return{...j8e,...JSON.parse(a)}}catch{}return j8e});j.useEffect(()=>{try{localStorage.setItem(igt,JSON.stringify(s))}catch{}},[s]);const n=j.useCallback(a=>{t(i=>({...i,[a]:!i[a]}))},[]),r=j.useCallback(()=>t(j8e),[]);return{columns:s,toggle:n,reset:r}}function Rkn({columns:s,onToggle:t,onReset:n}){const r=agt.filter(a=>s[a.key]).length;return e.jsxs(Sc,{children:[e.jsx(Cc,{asChild:!0,children:e.jsxs($,{variant:"outline",size:"sm",className:"h-8 gap-1.5 rounded-lg text-xs",children:[e.jsx(DA,{className:"h-3.5 w-3.5"}),"Columns",e.jsx($e,{variant:"secondary",className:"h-5 px-1.5 text-[10px]",children:r})]})}),e.jsxs(xc,{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(Ih,{className:"h-3 w-3"}),"Reset"]})]}),e.jsx("div",{className:"max-h-[320px] overflow-y-auto space-y-0.5",children:agt.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(ui,{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."})]})]})}function Okn(){var Io;const s=Vn(),[t,n]=oc(),{user:r}=_s(),a=dV(),i=ts(),{columns:l,toggle:o,reset:c}=Dkn(),d=t.get("type"),u=t.get("filter")??t.get("status"),h=t.get("new")==="true",{contactsWithScores:m,isLoading:p}=jee(),{activeContactIds:x,hasLeadSite:g}=jNn(),{data:y}=gkn(),{data:b}=Hb(),{data:v}=ykn(),{data:N}=oV(),{data:C}=FEe(),[A,T]=j.useState(new Set),[P,M]=j.useState("any"),I=QCe(),D=pGe(),B=fGe(),q=M6t(),[W,V]=j.useState(""),[K,Q]=j.useState(!1),[J,ce]=j.useState(d||"all"),[ue,ne]=j.useState(u||"all"),[ee,le]=j.useState("date-added"),[he,ve]=j.useState("all"),[ge,fe]=j.useState({}),je=j.useMemo(()=>Object.values(ge).filter(is=>is!==void 0&&is!==!1&&is!=="").length,[ge]),[Ee,Me]=j.useState(!1),{behaviorMap:De,hasLeadSite:ze}=hkn(),[ke,Xe]=j.useState(h),[Se,Re]=j.useState(null),[Ae,Be]=j.useState(!1),[qe,Ke]=j.useState(!1),[Ze,Ue]=j.useState(null),[et,Qe]=j.useState(""),[Ge,nt]=j.useState(new Set),[ft,lt]=j.useState(!1),Mt=Math.max(1,parseInt(t.get("page")||"1",10)||1),[Ft,Ts]=j.useState(Mt),js=j.useCallback(is=>{Ts(zr=>{const Sa=typeof is=="function"?is(zr):is;return n(Kn=>{const wn=new URLSearchParams(Kn);return Sa<=1?wn.delete("page"):wn.set("page",String(Sa)),wn},{replace:!0}),Sa})},[]),[zt,Nt]=j.useState(50),[Ds,_t]=j.useState("my"),[Xs,rn]=j.useState(!1),[Ps,_n]=j.useState(!1),{data:Zs}=Nw(),{addToLeadPond:gr}=p8t(Zs==null?void 0:Zs.teamId),{ponds:Un}=VWe(Zs==null?void 0:Zs.teamId),In=Un.filter(is=>is.has_access),[Ar,or]=j.useState(null),[qs,yr]=j.useState(""),fn=!!((Io=Zs==null?void 0:Zs.team)!=null&&Io.lead_pond_enabled&&(Zs!=null&&Zs.teamId)),Zn=!!(Zs!=null&&Zs.teamId),[Xt,rr]=j.useState([]),[Qn,Sn]=j.useState(!1),$n=is=>{rr([is]),Sn(!0)},tn=is=>{rr(is),Sn(!0)},ln=(is,zr)=>{Zs!=null&&Zs.teamId&&is.forEach(Sa=>{gr.mutate({contact_id:Sa,team_id:Zs.teamId,pond_id:zr||null})})},Cr=is=>{var zr;if(Zs!=null&&Zs.teamId){if(In.length>1){yr(In[0].id),or(is);return}ln(is,((zr=In[0])==null?void 0:zr.id)||null)}},ms=is=>Cr([is]),ot=is=>Cr(is),pt=j.useCallback(is=>{lt(!1),nt(zr=>{const Sa=new Set(zr);return Sa.has(is)?Sa.delete(is):Sa.add(is),Sa})},[]);j.useEffect(()=>{if(!(r!=null&&r.id))return;const is=U.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()=>{U.removeChannel(is)}},[i,r==null?void 0:r.id]),j.useEffect(()=>{u&&ne(u)},[u]);const[vt,At]=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&&Xe(!0)},[h]),j.useEffect(()=>{var is;Se&&At({first_name:Se.first_name||"",last_name:Se.last_name||"",email:Se.email||"",phone:Se.phone||"",address:Se.address||"",city:Se.city||"",state:Se.state||"",zip_code:Se.zip_code||"",birthday:Se.birthday||"",home_anniversary:Se.home_anniversary||"",spouse_name:Se.spouse_name||"",spouse_email:Se.spouse_email||"",lead_source_id:Se.lead_source_id||"",notes:Se.notes||"",tagIds:((is=Se.tags)==null?void 0:is.map(zr=>zr.relationship_type_id))||[]})},[Se]);const Zt=j.useMemo(()=>{const is=new Set;return N==null||N.forEach(zr=>{(zr.name==="Recruits"||zr.name==="Brokerage Agents")&&is.add(zr.id)}),is},[N]),as=j.useMemo(()=>Array.from(A).some(is=>Zt.has(is)),[A,Zt]),Ls=j.useMemo(()=>{const is={};return(m||[]).forEach(zr=>{is[zr.id]=`${zr.first_name||""} ${zr.last_name||""}`.trim()}),is},[m]),cs=j.useMemo(()=>{if(!m)return[];let is=m.filter(Kn=>{var Ju,Ld,bd,hx,Ay,Kp,Dg,Em,Lf,eh,L0;const wn=Kn.synced_source;if(!as&&(wn==="recruit"||wn==="brokerage_agent"))return!1;const ca=W===""||`${Kn.first_name} ${Kn.last_name}`.toLowerCase().includes(W.toLowerCase())||((Ju=Kn.email)==null?void 0:Ju.toLowerCase().includes(W.toLowerCase()))||((Ld=Kn.phone)==null?void 0:Ld.includes(W))||((bd=Kn.city)==null?void 0:bd.toLowerCase().includes(W.toLowerCase()))||((hx=Kn.state)==null?void 0:hx.toLowerCase().includes(W.toLowerCase()))||((Ay=Kn.address)==null?void 0:Ay.toLowerCase().includes(W.toLowerCase()))||((Kp=Kn.zip_code)==null?void 0:Kp.toLowerCase().includes(W.toLowerCase())),yo=J==="all"||((Dg=Kn.tags)==null?void 0:Dg.some(jo=>jo.relationship_type_id===J)),vo=A.size===0||(()=>{const jo=(C==null?void 0:C.filter(Zi=>Zi.contact_id===Kn.id).map(Zi=>Zi.tag_id))||[];return P==="any"?jo.some(Zi=>A.has(Zi)):Array.from(A).every(Zi=>jo.includes(Zi))})(),Vo=!!((Em=Kn.address)!=null&&Em.trim()||(Lf=Kn.city)!=null&&Lf.trim()||(eh=Kn.state)!=null&&eh.trim()||(L0=Kn.zip_code)!=null&&L0.trim()),Xc=he==="all"||he==="has-address"&&Vo||he==="no-address"&&!Vo,uo=Kn,bo=ge,od=(bo.hasEmail===void 0||!!uo.email===bo.hasEmail)&&(bo.hasPhone===void 0||!!uo.phone===bo.hasPhone)&&(bo.hasAddress===void 0||Vo===bo.hasAddress)&&(bo.hasBirthday===void 0||!!uo.birthday===bo.hasBirthday)&&(bo.hasSpouse===void 0||!!(uo.spouse_name||uo.spouse_contact_id||uo.spouse_email)===bo.hasSpouse)&&(bo.hasCompany===void 0||!!(uo.company_name||uo.job_title)===bo.hasCompany)&&(bo.hasNotes===void 0||!!(uo.notes&&uo.notes.trim())===bo.hasNotes)&&(!bo.city||(uo.city||"").toLowerCase().includes(bo.city.toLowerCase()))&&(!bo.state||(uo.state||"").toLowerCase().includes(bo.state.toLowerCase()))&&(!bo.zip||((uo.zip||"")+(uo.zip_code||"")).toLowerCase().includes(bo.zip.toLowerCase()))&&(!bo.birthdayMonth||!!uo.birthday&&mu(uo.birthday).getMonth()+1===bo.birthdayMonth)&&(!bo.anniversaryMonth||((bo.anniversaryField||"home_anniversary")==="home_anniversary"?!!uo.home_anniversary&&mu(uo.home_anniversary).getMonth()+1===bo.anniversaryMonth:!!uo.wedding_anniversary&&mu(uo.wedding_anniversary).getMonth()+1===bo.anniversaryMonth))&&(!bo.dateAddedFrom||!!uo.created_at&&uo.created_at.slice(0,10)>=bo.dateAddedFrom)&&(!bo.dateAddedTo||!!uo.created_at&&uo.created_at.slice(0,10)<=bo.dateAddedTo)&&(!bo.leadSourceId||uo.lead_source_id===bo.leadSourceId||!uo.lead_source_id&&bo.leadSourceId==="none");return ca&&yo&&vo&&Xc&&od});ue==="not-touched-90"?is=is.filter(Kn=>{const wn=Kn.relationshipScore.daysSinceTouch;return wn===null||wn>90}):ue==="at-risk"?is=is.filter(Kn=>Kn.relationshipScore.status==="at-risk"):ue==="cooling"?is=is.filter(Kn=>Kn.relationshipScore.status==="cooling"):ue==="warm"?is=is.filter(Kn=>Kn.relationshipScore.status==="warm"):ue==="has-deal"?is=is.filter(Kn=>v&&v[Kn.id]):ue==="no-deal"?is=is.filter(Kn=>!v||!v[Kn.id]):ue==="open-house"?is=is.filter(Kn=>{var Ur;return(((Ur=Kn.lead_source_ref)==null?void 0:Ur.name)||Kn.lead_source)==="Open House"}):ue==="website-active"?is=is.filter(Kn=>x.has(Kn.id)):ue==="never-contacted"?is=is.filter(Kn=>Kn.relationshipScore.daysSinceTouch===null):ue==="vips"?is=is.filter(Kn=>Kn.relationshipScore.score>=80):ue==="missing-info"?is=is.filter(Kn=>U7t(Kn)):ue==="birthdays-soon"?is=is.filter(Kn=>{const wn=d8(Kn.birthday);return wn!==null&&wn<=30}):ue==="anniversary-soon"?is=is.filter(Kn=>{const wn=d8(Kn.home_anniversary);return wn!==null&&wn<=30}):ue==="in-drip"?is=is.filter(Kn=>((y==null?void 0:y[Kn.id])??0)>0):ue==="not-in-drip"&&(is=is.filter(Kn=>((y==null?void 0:y[Kn.id])??0)===0));const zr=ge;if(zr.lastActive||zr.registered||zr.viewedListing||zr.savedProperty||zr.hasSavedSearch||zr.requestedShowing||zr.requestedValuation||zr.websiteActiveOnly){const Kn=Date.now(),wn={today:24*60*60*1e3,"7d":7*24*60*60*1e3,"30d":30*24*60*60*1e3,"90d":90*24*60*60*1e3};is=is.filter(Ur=>{const ca=De.get(Ur.id);if(zr.lastActive==="never"){if(ca!=null&&ca.lastActiveAt)return!1}else if(zr.lastActive){const yo=Kn-wn[zr.lastActive];if(!(ca!=null&&ca.lastActiveAt)||new Date(ca.lastActiveAt).getTime()0)||zr.viewedListing==="multiple7d"&&!(ca&&ca.propertyViewCount7d>=3)||zr.savedProperty&&!(ca&&ca.savedListingCount>0)||zr.hasSavedSearch&&!(ca&&ca.activeSavedSearchCount>0)||zr.requestedShowing&&!(ca&&ca.showingRequests>0)||zr.requestedValuation&&!(ca&&ca.valuationRequests>0)||zr.websiteActiveOnly&&!x.has(Ur.id))})}return is=[...is].sort((Kn,wn)=>{switch(ee){case"important-dates":{const Ur=d8(Kn.birthday),ca=d8(wn.birthday),yo=d8(Kn.home_anniversary),vo=d8(wn.home_anniversary),Vo=[Ur,yo].filter(uo=>uo!==null).sort((uo,bo)=>(uo??1/0)-(bo??1/0))[0]??1/0,Xc=[ca,vo].filter(uo=>uo!==null).sort((uo,bo)=>(uo??1/0)-(bo??1/0))[0]??1/0;return Vo-Xc}case"last-touched":{const Ur=Kn.relationshipScore.lastTouchDate,ca=wn.relationshipScore.lastTouchDate;return!Ur&&!ca?0:Ur?ca?new Date(Ur).getTime()-new Date(ca).getTime():1:-1}case"next-touch":{const Ur=Kn.relationshipScore.daysSinceTouch,ca=wn.relationshipScore.daysSinceTouch;return Ur===null&&ca===null?0:Ur===null?-1:ca===null?1:ca-Ur}case"score":return Kn.relationshipScore.score-wn.relationshipScore.score;case"date-added":{const Ur=Kn.created_at,ca=wn.created_at;return!Ur&&!ca?0:Ur?ca?new Date(ca).getTime()-new Date(Ur).getTime():-1:1}case"last-name":{const Ur=(Kn.last_name||"").toLowerCase(),ca=(wn.last_name||"").toLowerCase();if(Ur!==ca)return Ur.localeCompare(ca);const yo=(Kn.first_name||"").toLowerCase(),vo=(wn.first_name||"").toLowerCase();return yo.localeCompare(vo)}case"name":default:{const Ur=`${Kn.first_name||""} ${Kn.last_name||""}`.toLowerCase(),ca=`${wn.first_name||""} ${wn.last_name||""}`.toLowerCase();return Ur.localeCompare(ca)}}}),is},[m,W,J,A,P,ue,ee,v,C,x,y,he,ge,De,as]),qt=cs.length,Gs=Math.max(1,Math.ceil(qt/zt)),Vs=Math.min(Ft,Gs),Hn=j.useMemo(()=>{const is=(Vs-1)*zt;return cs.slice(is,is+zt)},[cs,Vs,zt]),Kr=j.useMemo(()=>{const is=(m||[]).length;return{total:is,label:is===0?"Build your database — add or import your first contacts.":`${is.toLocaleString()} ${is===1?"person":"people"} in your database`}},[m]),ma=j.useMemo(()=>{const is=m||[],zr=is.filter(Ur=>{var ca;return((ca=Ur.relationshipScore)==null?void 0:ca.status)==="at-risk"}).length,Sa=is.filter(Ur=>{var yo;const ca=(yo=Ur.relationshipScore)==null?void 0:yo.daysSinceTouch;return typeof ca=="number"&&ca<=7}).length,Kn=new Date().getMonth()+1,wn=is.filter(Ur=>Ur.birthday?String(Ur.birthday).split(/[-/T]/).map(Number)[1]===Kn:!1).length;return[{label:"Total contacts",value:Kr.total.toLocaleString(),onClick:()=>{ne("all"),js(1)},active:ue==="all"},{label:"Needs attention",value:zr,onClick:()=>{ne("at-risk"),js(1)},active:ue==="at-risk"},{label:"Touched this week",value:Sa,onClick:()=>{ne("warm"),js(1)},active:ue==="warm"},{label:"Birthdays this month",value:wn,onClick:()=>{ne("birthdays-soon"),js(1)},active:ue==="birthdays-soon"}]},[m,Kr.total,ue,js]),Or=j.useCallback(is=>{const zr=new URLSearchParams;W&&zr.set("search",W),J!=="all"&&zr.set("type",J),ue!=="all"&&zr.set("filter",ue),A.size>0&&(zr.set("tags",Array.from(A).join(",")),zr.set("tagMode",P));const Sa=zr.toString();s(`/mission-control/contacts/${is}${Sa?`?${Sa}`:""}`)},[s,W,J,ue,A,P]),ta=j.useRef(!1);j.useEffect(()=>{if(!ta.current){ta.current=!0;return}js(1)},[W,J,A,P,ue,ee,he,ge]);const da=j.useCallback(()=>{lt(!1),nt(is=>is.size>0?new Set:new Set(Hn.map(zr=>zr.id)))},[Hn]),va=j.useCallback(()=>{lt(!0),nt(new Set(cs.map(is=>is.id)))},[cs]),[hi,el]=j.useState(null),Oo=j.useCallback((is,zr)=>{V(is.search||""),ce(is.type||"all"),ne(is.status||"all"),fe(is.behavior||{}),le(zr||"name")},[]),Ei=()=>{At({first_name:"",last_name:"",email:"",phone:"",address:"",city:"",state:"",zip_code:"",birthday:"",home_anniversary:"",spouse_name:"",spouse_email:"",lead_source_id:"",notes:"",tagIds:[]})},Wa=async is=>{is.preventDefault();const zr={...vt,lead_source_id:vt.lead_source_id||null};Se?(await D.mutateAsync({id:Se.id,...zr}),Re(null)):(await I.mutateAsync(zr),Xe(!1)),Ei()},wo=async is=>{await Yi("Are you sure you want to delete this contact?")&&await B.mutateAsync(is)};return e.jsx(Ks,{title:"Contacts",description:"Manage your InnerCircle contacts",children:e.jsxs("div",{className:"space-y-6 overflow-x-hidden",children:[e.jsx(Mkn,{totalLabel:Kr.label,stats:ma,search:W,onSearchChange:V,onAddContact:()=>Xe(!0),onImportCsv:()=>Be(!0),onImportPhone:()=>Ke(!0),onManageTags:()=>rn(!0),onHeatMap:()=>Q(!0),viewMode:Ds,onViewModeChange:is=>_t(is),showTeamTab:!!Zs&&(Zs.team.contact_visibility==="full_team"||Zs.team.contact_visibility==="leader_only"&&Zs.role==="team_leader"),showLeadPondTab:!!(Zs!=null&&Zs.team.lead_pond_enabled),extraActions:e.jsx(pNn,{})}),Ds==="team"?e.jsx(HWe,{}):Ds==="lead-pond"&&Zs?e.jsx(GWe,{teamId:Zs.teamId}):e.jsxs(e.Fragment,{children:[e.jsx(Ikn,{contacts:m,contactDealsMap:v,websiteActiveIds:x,totalCount:(m||[]).length,activeViewId:hi,currentFilters:{search:W,type:J,status:ue,behavior:ge},currentSortBy:ee,onApplyView:(is,zr,Sa)=>{el(is),Oo(zr,Sa),js(1)},onClearAll:()=>{el(null),Oo({search:"",type:"all",status:"all",behavior:{}},"name"),js(1)},activeKey:{"at-risk":"needs-attention",cooling:"cooling","not-touched-90":"stale-90","never-contacted":"never-contacted","birthdays-soon":"birthdays-soon","anniversary-soon":"anniversary-soon","has-deal":"has-deal","website-active":"website-active",vips:"vips","missing-info":"missing-info"}[ue]??null,onSelectSegment:is=>{const Sa=is?{"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"}[is]:"all";ne(Sa),js(1)}}),e.jsxs(_e,{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(Ub,{children:[e.jsx(cee,{asChild:!0,children:e.jsxs($,{variant:"outline",className:"h-10 flex-1 rounded-xl relative gap-2","aria-label":"Filters",children:[e.jsx(TT,{className:"h-4 w-4"}),"Filters & Views",(()=>{const is=(J!=="all"?1:0)+(ue!=="all"?1:0)+(he!=="all"?1:0)+A.size+je;return is>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:is}):null})()]})}),e.jsxs(T1,{side:"bottom",className:"h-[85vh] rounded-t-2xl overflow-y-auto",children:[e.jsx(kw,{className:"text-left",children:e.jsx(Sw,{children:"Filters & Views"})}),e.jsxs("div",{className:"space-y-5 py-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{className:"text-xs uppercase tracking-wide text-muted-foreground",children:"Type"}),e.jsxs(vs,{value:J,onValueChange:ce,children:[e.jsx(gs,{className:"h-11 rounded-xl bg-muted/40",children:e.jsx(bs,{placeholder:"All Types"})}),e.jsxs(ys,{children:[e.jsx(Ye,{value:"all",children:"All Types"}),b==null?void 0:b.filter(is=>is.active).map(is=>e.jsx(Ye,{value:is.id,children:is.name},is.id))]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{className:"text-xs uppercase tracking-wide text-muted-foreground",children:"Status"}),e.jsxs(vs,{value:ue,onValueChange:ne,children:[e.jsx(gs,{className:"h-11 rounded-xl bg-muted/40",children:e.jsx(bs,{placeholder:"All Status"})}),e.jsxs(ys,{children:[e.jsx(Ye,{value:"all",children:"All Status"}),e.jsx(Ye,{value:"warm",children:"🟢 Warm"}),e.jsx(Ye,{value:"cooling",children:"🟡 Cooling Off"}),e.jsx(Ye,{value:"at-risk",children:"🔴 At Risk"}),e.jsx(Ye,{value:"has-deal",children:"📋 Has Deal"}),e.jsx(Ye,{value:"no-deal",children:"📭 No Deal"}),e.jsx(Ye,{value:"open-house",children:"🏠 Open House"}),g&&e.jsx(Ye,{value:"website-active",children:"🌐 Website Active"}),e.jsx(Ye,{value:"in-drip",children:"🌱 In Drip Campaign"}),e.jsx(Ye,{value:"not-in-drip",children:"🚫 Not In Drip"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{className:"text-xs uppercase tracking-wide text-muted-foreground",children:"Address"}),e.jsxs(vs,{value:he,onValueChange:is=>ve(is),children:[e.jsx(gs,{className:"h-11 rounded-xl bg-muted/40",children:e.jsx(bs,{placeholder:"All Addresses"})}),e.jsxs(ys,{children:[e.jsx(Ye,{value:"all",children:"All Addresses"}),e.jsx(Ye,{value:"has-address",children:"Has Address"}),e.jsx(Ye,{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(se,{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:()=>M("any"),className:`px-2 py-0.5 rounded text-xs font-medium ${P==="any"?"bg-background shadow-sm":"text-muted-foreground"}`,children:"Any"}),e.jsx("button",{onClick:()=>M("all"),className:`px-2 py-0.5 rounded text-xs font-medium ${P==="all"?"bg-background shadow-sm":"text-muted-foreground"}`,children:"All"})]})]}),e.jsx("div",{className:"flex flex-wrap gap-2",children:N.map(is=>{const zr=A.has(is.id);return e.jsxs("button",{onClick:()=>{T(Sa=>{const Kn=new Set(Sa);return Kn.has(is.id)?Kn.delete(is.id):Kn.add(is.id),Kn})},className:`inline-flex items-center gap-1.5 px-3 py-1.5 rounded-full text-xs border transition-colors ${zr?"bg-primary text-primary-foreground border-primary":"bg-background border-border"}`,children:[e.jsx("span",{className:"h-2 w-2 rounded-full",style:{backgroundColor:is.color}}),is.name]},is.id)})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{className:"text-xs uppercase tracking-wide text-muted-foreground",children:"Sort by"}),e.jsxs(vs,{value:ee,onValueChange:le,children:[e.jsx(gs,{className:"h-11 rounded-xl bg-muted/40",children:e.jsx(bs,{})}),e.jsxs(ys,{children:[e.jsx(Ye,{value:"name",children:"Name (A-Z)"}),e.jsx(Ye,{value:"last-name",children:"Last Name (A-Z)"}),e.jsx(Ye,{value:"important-dates",children:"Important Dates"}),e.jsx(Ye,{value:"last-touched",children:"Last Touched"}),e.jsx(Ye,{value:"next-touch",children:"Next Touch Due"}),e.jsx(Ye,{value:"score",children:"Relationship Score"}),e.jsx(Ye,{value:"date-added",children:"Date Added"})]})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-2 pt-2",children:[e.jsxs($,{variant:"outline",className:"h-11 rounded-xl gap-1.5",onClick:()=>Me(!0),children:[e.jsx(dn,{className:"h-4 w-4"})," Advanced"]}),e.jsxs($,{variant:"outline",className:"h-11 rounded-xl gap-1.5",onClick:()=>rn(!0),children:[e.jsx(Up,{className:"h-4 w-4"})," Manage Tags"]})]}),e.jsx("div",{children:e.jsx(Wxt,{currentFilters:{search:W,type:J,status:ue,behavior:ge},currentSortBy:ee,onApplySmartList:Oo})}),e.jsx($,{variant:"ghost",className:"w-full h-11 rounded-xl text-muted-foreground",onClick:()=>{ce("all"),ne("all"),ve("all"),T(new Set),fe({})},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:[qt.toLocaleString()," ",qt===1?"contact":"contacts"," shown"]}),e.jsxs(Sc,{children:[e.jsx(Cc,{asChild:!0,children:e.jsx($,{variant:"outline",size:"icon",className:"h-10 w-10 rounded-xl",title:"Sort contacts",children:e.jsx(qj,{className:"h-4 w-4"})})}),e.jsxs(xc,{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(is=>e.jsx("button",{onClick:()=>le(is.v),className:`w-full text-left px-2 py-1.5 rounded-md text-sm hover:bg-accent transition-colors ${ee===is.v?"bg-accent font-medium text-primary":""}`,children:is.l},is.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(vs,{value:J,onValueChange:ce,children:[e.jsx(gs,{className:"h-8 text-xs rounded-lg bg-background w-auto min-w-[130px] gap-2",children:e.jsx(bs,{placeholder:"All Types"})}),e.jsxs(ys,{children:[e.jsx(Ye,{value:"all",children:"All Types"}),b==null?void 0:b.filter(is=>is.active).map(is=>e.jsx(Ye,{value:is.id,children:is.name},is.id))]})]}),e.jsxs(vs,{value:ue,onValueChange:ne,children:[e.jsx(gs,{className:"h-8 text-xs rounded-lg bg-background w-auto min-w-[130px] gap-2",children:e.jsx(bs,{placeholder:"All Status"})}),e.jsxs(ys,{children:[e.jsx(Ye,{value:"all",children:"All Status"}),e.jsx(Ye,{value:"warm",children:"🟢 Warm"}),e.jsx(Ye,{value:"cooling",children:"🟡 Cooling Off"}),e.jsx(Ye,{value:"at-risk",children:"🔴 At Risk"}),e.jsx(Ye,{value:"has-deal",children:"📋 Has Deal"}),e.jsx(Ye,{value:"no-deal",children:"📭 No Deal"}),e.jsx(Ye,{value:"open-house",children:"🏠 Open House"}),g&&e.jsx(Ye,{value:"website-active",children:"🌐 Website Active"}),e.jsx(Ye,{value:"in-drip",children:"🌱 In Drip Campaign"}),e.jsx(Ye,{value:"not-in-drip",children:"🚫 Not In Drip"})]})]}),e.jsxs(vs,{value:he,onValueChange:is=>ve(is),children:[e.jsx(gs,{className:"h-8 text-xs rounded-lg bg-background w-auto min-w-[130px] gap-2",children:e.jsx(bs,{placeholder:"All Addresses"})}),e.jsxs(ys,{children:[e.jsx(Ye,{value:"all",children:"All Addresses"}),e.jsx(Ye,{value:"has-address",children:"Has Address"}),e.jsx(Ye,{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(Sc,{children:[e.jsx(Cc,{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(Up,{className:"h-3.5 w-3.5"}),A.size===0?"Filter by Tags":`${A.size} tag${A.size>1?"s":""}`]})}),e.jsx(xc,{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:()=>M("any"),className:`px-2 py-0.5 rounded text-xs font-medium transition-colors ${P==="any"?"bg-background text-foreground shadow-sm":"text-muted-foreground"}`,children:"Any"}),e.jsx("button",{onClick:()=>M("all"),className:`px-2 py-0.5 rounded text-xs font-medium transition-colors ${P==="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(is=>{const zr=A.has(is.id);return e.jsxs("button",{onClick:()=>{T(Sa=>{const Kn=new Set(Sa);return Kn.has(is.id)?Kn.delete(is.id):Kn.add(is.id),Kn})},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(ui,{checked:zr,className:"pointer-events-none"}),e.jsx("div",{className:"h-2.5 w-2.5 rounded-full shrink-0",style:{backgroundColor:is.color}}),e.jsx("span",{className:"flex-1 text-left truncate",children:is.name})]},is.id)})}),A.size>0&&e.jsx($,{variant:"ghost",size:"sm",className:"w-full text-xs",onClick:()=>T(new Set),children:"Clear tags"})]})})]}),e.jsx("div",{className:"w-px h-4 bg-border"}),e.jsxs(Hd,{children:[e.jsx(Gd,{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(pc,{className:"h-3.5 w-3.5"})})}),e.jsxs(Md,{align:"end",children:[e.jsxs(Na,{onClick:()=>rn(!0),children:[e.jsx(Up,{className:"h-4 w-4 mr-2"}),"Manage Tags"]}),e.jsxs(Na,{onClick:()=>_n(!0),children:[e.jsx(f1,{className:"h-4 w-4 mr-2"}),"Manage Lead Sources"]})]})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Wxt,{currentFilters:{search:W,type:J,status:ue,behavior:ge},currentSortBy:ee,onApplySmartList:Oo}),e.jsx("div",{className:"h-5 w-px bg-border"}),e.jsxs($,{variant:"outline",size:"sm",className:"gap-1.5 h-8 rounded-lg border-[#2a4c64]/20 text-[#2a4c64] hover:bg-[#2a4c64]/5 hover:text-[#2a4c64]",onClick:()=>Me(!0),children:[e.jsx(dn,{className:"h-3.5 w-3.5"}),"Advanced Filters",je>0&&e.jsx($e,{variant:"secondary",className:"h-5 px-1.5 text-[10px]",children:je})]}),e.jsx(Rkn,{columns:l,onToggle:o,onReset:c})]})]}),je>0&&e.jsx("div",{className:"px-3 sm:px-4 py-3 border-t bg-background",children:e.jsx(dkn,{behavior:ge,onRemove:is=>fe(zr=>{const Sa={...zr};return delete Sa[is],Sa}),onClearAll:()=>fe({})})})]}),e.jsx(ckn,{open:Ee,onOpenChange:Me,hasLeadSite:ze||g,behavior:ge,onApply:fe,selectedType:J,onSelectedTypeChange:ce,relationshipTypes:b}),e.jsx(okn,{selectedIds:Ge,contacts:cs,onClearSelection:()=>{nt(new Set),lt(!1)},showLeadPondAction:fn,onSendToLeadPond:ot,showTransferAction:Zn,onTransfer:tn}),Ge.size>0&&Ge.size===Hn.length&&!ft&&qt>zt&&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 ",Hn.length," contacts on this page are selected."]}),e.jsxs($,{variant:"link",size:"sm",className:"h-auto p-0 font-semibold",onClick:va,children:["Select all ",qt.toLocaleString()," matching contacts"]})]}),ft&&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 ",qt.toLocaleString()," matching contacts are selected.",e.jsx($,{variant:"link",size:"sm",className:"h-auto p-0",onClick:()=>{nt(new Set),lt(!1)},children:"Clear selection"})]}),qt>zt&&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 ",(Vs-1)*zt+1,"–",Math.min(Vs*zt,qt)," of ",qt.toLocaleString()," contacts"]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx($,{variant:"outline",size:"sm",disabled:Vs<=1,onClick:()=>js(1),children:"First"}),e.jsx($,{variant:"outline",size:"sm",disabled:Vs<=1,onClick:()=>js(is=>is-1),children:e.jsx(Ic,{className:"h-4 w-4"})}),e.jsxs("span",{className:"px-3 text-sm font-medium",children:["Page ",Vs," of ",Gs]}),e.jsx($,{variant:"outline",size:"sm",disabled:Vs>=Gs,onClick:()=>js(is=>is+1),children:e.jsx(Ja,{className:"h-4 w-4"})}),e.jsx($,{variant:"outline",size:"sm",disabled:Vs>=Gs,onClick:()=>js(Gs),children:"Last"})]})]}),a?e.jsx("div",{className:"space-y-3",children:p?e.jsx(Pkn,{}):cs.length===0?e.jsx(_e,{children:e.jsx(sgt,{filtered:!!W||J!=="all"||ue!=="all"||he!=="all"||A.size>0,onAdd:()=>Xe(!0),onImport:()=>Be(!0),onClearFilters:()=>{V(""),ce("all"),ne("all"),ve("all"),T(new Set),fe({})}})}):Hn.map(is=>{var Sa,Kn,wn;const{relationshipScore:zr}=is;return e.jsx(_e,{className:"cursor-pointer hover:bg-accent/50 transition-colors",onClick:()=>Or(is.id),children:e.jsx(Oe,{className:"p-4",children:e.jsxs("div",{className:"flex items-start justify-between",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2 flex-wrap",children:[e.jsxs("h3",{className:"font-semibold text-base truncate",children:[is.first_name," ",is.last_name]}),e.jsx(Xxt,{count:(y==null?void 0:y[is.id])??0}),e.jsx(Ja,{className:"h-4 w-4 text-muted-foreground shrink-0 ml-auto"})]}),e.jsxs("div",{className:"space-y-1 text-sm mb-3",children:[is.email&&e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground",children:[e.jsx(nn,{className:"h-3.5 w-3.5 shrink-0"}),e.jsx("span",{className:"truncate",children:is.email})]}),is.phone&&e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground",children:[e.jsx(ya,{className:"h-3.5 w-3.5 shrink-0"}),e.jsx("span",{children:is.phone})]})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-1 mb-2",children:[e.jsx(rBe,{score:zr,size:"sm"}),e.jsx(Vxt,{contact:is}),(((Sa=is.lead_source_ref)==null?void 0:Sa.name)||is.lead_source)&&e.jsx($e,{variant:"outline",className:"text-xs gap-1 border-primary/30 text-primary",children:((Kn=is.lead_source_ref)==null?void 0:Kn.name)||is.lead_source}),(wn=is.tags)==null?void 0:wn.map(Ur=>{var ca;return e.jsx($e,{variant:"secondary",className:"text-xs",children:(ca=Ur.relationship_type)==null?void 0:ca.name},Ur.id)}),e.jsx(egt,{contactId:is.id,tags:C==null?void 0:C.filter(Ur=>Ur.contact_id===is.id)}),e.jsx(Zxt,{deal:v==null?void 0:v[is.id]})]}),e.jsx(Yxt,{birthday:is.birthday,homeAnniversary:is.home_anniversary,weddingAnniversary:is.wedding_anniversary,className:"mb-2",contactId:is.id,contactName:`${is.first_name}${is.last_name?" "+is.last_name:""}`,contactAddress:[is.address,is.city,is.state].filter(Boolean).join(", ")}),e.jsxs("div",{className:"flex flex-wrap items-center gap-3 text-xs text-muted-foreground",children:[zr.lastTouchDate?e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(Hr,{className:"h-3 w-3"}),Hs(new Date(zr.lastTouchDate),"MMM d")]}):e.jsx("span",{className:"italic",children:"Never contacted"}),is.birthday&&e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(ia,{className:"h-3 w-3"}),Hs(mu(is.birthday),"MMM d")]}),is.home_anniversary&&e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(sa,{className:"h-3 w-3"}),Hs(mu(is.home_anniversary),"MMM d")]}),is.created_at&&e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(sn,{className:"h-3 w-3"}),"Added ",Hs(new Date(is.created_at),"MMM d, yyyy")]})]})]}),e.jsx("div",{className:"ml-2",onClick:Ur=>Ur.stopPropagation(),children:e.jsx(Gxt,{contact:is,onEdit:Re,onDelete:wo,onSnooze:(Ur,ca)=>{Ue(Ur),Qe(ca)},showLeadPondAction:fn,onSendToLeadPond:ms,showTransferAction:Zn,onTransfer:$n})})]})})},is.id)})}):e.jsx(_e,{children:e.jsx(Oe,{className:"p-0 overflow-x-auto",children:e.jsxs(Va,{className:"min-w-[800px]",children:[e.jsx(Ha,{className:"sticky top-0 z-10 bg-card/95 backdrop-blur supports-[backdrop-filter]:bg-card/80",children:e.jsxs(hn,{className:"hover:bg-transparent",children:[e.jsx(Lt,{className:"w-[40px]",children:e.jsx(ui,{checked:Hn.length>0&&Hn.every(is=>Ge.has(is.id)),onCheckedChange:()=>da()})}),e.jsx(Lt,{children:e.jsxs("button",{onClick:()=>le(is=>is==="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",ee==="name"&&e.jsx(Ja,{className:"h-3 w-3 rotate-90 text-primary"}),ee==="last-name"&&e.jsx(Ja,{className:"h-3 w-3 -rotate-90 text-primary"})]})}),l.relationship&&e.jsx(Lt,{children:"Relationship"}),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(Ga,{children:p?e.jsx(Lkn,{columns:2+Object.values(l).filter(Boolean).length}):cs.length===0?e.jsx(hn,{className:"hover:bg-transparent",children:e.jsx(gt,{colSpan:3+Object.values(l).filter(Boolean).length,className:"p-0",children:e.jsx(sgt,{filtered:!!W||J!=="all"||ue!=="all"||he!=="all"||A.size>0,onAdd:()=>Xe(!0),onImport:()=>Be(!0),onClearFilters:()=>{V(""),ce("all"),ne("all"),ve("all"),T(new Set),fe({})}})})}):Hn.map(is=>{var Kn;const{relationshipScore:zr}=is,Sa=v==null?void 0:v[is.id];return e.jsxs(hn,{className:`group cursor-pointer border-border/60 transition-colors hover:bg-accent/40 [&>td]:py-3.5 ${Ge.has(is.id)?"bg-accent/30":""}`,onClick:()=>Or(is.id),children:[e.jsx(gt,{onClick:wn=>wn.stopPropagation(),children:e.jsx(ui,{checked:Ge.has(is.id),onCheckedChange:()=>pt(is.id)})}),e.jsx(gt,{className:"min-w-[220px]",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx($7t,{firstName:is.first_name,lastName:is.last_name,avatarUrl:is.avatar_url,email:is.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:[is.first_name," ",is.last_name]}),e.jsx(Tkn,{linked:!!is.spouse_contact_id||!!is.spouse_name,spouseName:is.spouse_contact_id&&Ls[is.spouse_contact_id]||is.spouse_name||null}),e.jsx(Xxt,{count:(y==null?void 0:y[is.id])??0})]}),is.email&&!l.email&&e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:is.email}),is.phone&&!l.phone&&e.jsx("p",{className:"text-xs text-muted-foreground",children:is.phone})]})]})}),l.relationship&&e.jsx(gt,{children:e.jsxs("div",{className:"flex items-center gap-2.5",children:[e.jsx(Skn,{score:zr.score,status:zr.status}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-sm font-medium leading-tight",children:zr.status==="warm"?"Strong":zr.status==="cooling"?"Cooling":"At Risk"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:zr.daysSinceTouch===null?"Never contacted":zr.daysSinceTouch===0?"Touched today":`${zr.daysSinceTouch}d since touch`})]})]})}),l.stage&&e.jsx(gt,{children:e.jsx(Zxt,{deal:Sa})}),l.leadSource&&e.jsx(gt,{className:"text-sm text-muted-foreground max-w-[160px] truncate",children:((Kn=is.lead_source_ref)==null?void 0:Kn.name)||is.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(egt,{contactId:is.id,tags:C==null?void 0:C.filter(wn=>wn.contact_id===is.id)})})}),l.lastTouch&&e.jsx(gt,{children:zr.lastTouchDate?e.jsxs("div",{className:"flex items-center gap-1.5 text-sm text-muted-foreground",children:[e.jsx(Hr,{className:"h-3.5 w-3.5"}),Hs(new Date(zr.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(Vxt,{contact:is}),e.jsx(Yxt,{birthday:is.birthday,homeAnniversary:is.home_anniversary,weddingAnniversary:is.wedding_anniversary,contactId:is.id,contactName:`${is.first_name}${is.last_name?" "+is.last_name:""}`,contactAddress:[is.address,is.city,is.state].filter(Boolean).join(", ")})]})}),l.dealValue&&e.jsx(gt,{children:(()=>{const wn=(Sa==null?void 0:Sa.sale_price)??(Sa==null?void 0:Sa.expected_price);return wn?e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-semibold",children:Au(Number(wn))}),(Sa==null?void 0:Sa.deal_type)&&e.jsx("p",{className:"text-xs text-muted-foreground capitalize",children:String(Sa.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:is.email||"—"}),l.phone&&e.jsx(gt,{className:"text-sm text-muted-foreground whitespace-nowrap",children:is.phone||"—"}),l.address&&e.jsx(gt,{className:"text-sm text-muted-foreground max-w-[220px] truncate",children:[is.address,is.city,is.state].filter(Boolean).join(", ")||"—"}),l.birthday&&e.jsx(gt,{className:"text-sm text-muted-foreground whitespace-nowrap",children:is.birthday?(()=>{const[wn,Ur,ca]=String(is.birthday).split(/[-/T]/).map(Number);return Ur&&ca?`${Ur}/${ca}${wn&&wn>1900?`/${wn}`:""}`:"—"})():"—"}),e.jsx(gt,{onClick:wn=>wn.stopPropagation(),children:e.jsx(Gxt,{contact:is,onEdit:Re,onDelete:wo,onSnooze:(wn,Ur)=>{Ue(wn),Qe(Ur)},showLeadPondAction:fn,onSendToLeadPond:ms,showTransferAction:Zn,onTransfer:$n})})]},is.id)})})]})})}),qt>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 ",(Vs-1)*zt+1,"–",Math.min(Vs*zt,qt)," of ",qt.toLocaleString()," contacts"]}),e.jsxs(vs,{value:String(zt),onValueChange:is=>{Nt(Number(is)),js(1)},children:[e.jsx(gs,{className:"w-[80px] h-8",children:e.jsx(bs,{})}),e.jsxs(ys,{children:[e.jsx(Ye,{value:"50",children:"50"}),e.jsx(Ye,{value:"100",children:"100"}),e.jsx(Ye,{value:"250",children:"250"})]})]}),e.jsx("span",{className:"text-xs",children:"per page"})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx($,{variant:"outline",size:"sm",disabled:Vs<=1,onClick:()=>js(1),children:"First"}),e.jsx($,{variant:"outline",size:"sm",disabled:Vs<=1,onClick:()=>js(is=>is-1),children:e.jsx(Ic,{className:"h-4 w-4"})}),e.jsxs("span",{className:"px-3 text-sm font-medium",children:["Page ",Vs," of ",Gs]}),e.jsx($,{variant:"outline",size:"sm",disabled:Vs>=Gs,onClick:()=>js(is=>is+1),children:e.jsx(Ja,{className:"h-4 w-4"})}),e.jsx($,{variant:"outline",size:"sm",disabled:Vs>=Gs,onClick:()=>js(Gs),children:"Last"})]})]}),e.jsx(Os,{open:ke||!!Se,onOpenChange:is=>{is||(Xe(!1),Re(null),Ei())},children:e.jsxs(Rs,{className:"max-w-lg max-h-[90vh] overflow-y-auto",children:[e.jsx(Us,{children:e.jsx(zs,{children:Se?"Edit Contact":"Add Contact"})}),e.jsxs("form",{onSubmit:Wa,className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx(se,{htmlFor:"first_name",children:"First Name *"}),e.jsx(be,{id:"first_name",value:vt.first_name,onChange:is=>At({...vt,first_name:is.target.value}),required:!0})]}),e.jsxs("div",{children:[e.jsx(se,{htmlFor:"last_name",children:"Last Name"}),e.jsx(be,{id:"last_name",value:vt.last_name,onChange:is=>At({...vt,last_name:is.target.value})})]})]}),e.jsxs("div",{children:[e.jsx(se,{htmlFor:"email",children:"Email"}),e.jsx(be,{id:"email",type:"email",value:vt.email,onChange:is=>At({...vt,email:is.target.value})})]}),e.jsxs("div",{children:[e.jsx(se,{htmlFor:"phone",children:"Phone"}),e.jsx(be,{id:"phone",value:vt.phone,onChange:is=>At({...vt,phone:is.target.value})})]}),e.jsxs("div",{children:[e.jsx(se,{htmlFor:"address",children:"Address"}),e.jsx(be,{id:"address",value:vt.address,onChange:is=>At({...vt,address:is.target.value}),placeholder:"Street address"})]}),e.jsxs("div",{className:"grid grid-cols-3 gap-4",children:[e.jsxs("div",{children:[e.jsx(se,{htmlFor:"city",children:"City"}),e.jsx(be,{id:"city",value:vt.city,onChange:is=>At({...vt,city:is.target.value})})]}),e.jsxs("div",{children:[e.jsx(se,{htmlFor:"state",children:"State"}),e.jsx(be,{id:"state",value:vt.state,onChange:is=>At({...vt,state:is.target.value})})]}),e.jsxs("div",{children:[e.jsx(se,{htmlFor:"zip_code",children:"Zip"}),e.jsx(be,{id:"zip_code",value:vt.zip_code,onChange:is=>At({...vt,zip_code:is.target.value})})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx(se,{htmlFor:"birthday",children:"Birthday"}),e.jsx(be,{id:"birthday",type:"date",value:vt.birthday,onChange:is=>At({...vt,birthday:is.target.value})})]}),e.jsxs("div",{children:[e.jsx(se,{htmlFor:"home_anniversary",children:"Home Anniversary"}),e.jsx(be,{id:"home_anniversary",type:"date",value:vt.home_anniversary,onChange:is=>At({...vt,home_anniversary:is.target.value})})]})]}),Se&&e.jsx(aBe,{contactId:Se.id,currentSpouseContactId:(Se==null?void 0:Se.spouse_contact_id)||null,currentSpouseName:(Se==null?void 0:Se.spouse_name)||null,currentSpouseEmail:(Se==null?void 0:Se.spouse_email)||null,onLink:is=>q.mutate({contactId:Se.id,spouseContactId:is}),onUnlink:()=>q.mutate({contactId:Se.id,spouseContactId:null}),isEditing:!0}),e.jsx(B7t,{value:vt.lead_source_id,onChange:is=>At({...vt,lead_source_id:is})}),e.jsxs("div",{children:[e.jsx(se,{children:"Relationship Types"}),e.jsx("div",{className:"flex flex-wrap gap-2 mt-2",children:b==null?void 0:b.filter(is=>is.active).map(is=>e.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",children:[e.jsx(ui,{checked:vt.tagIds.includes(is.id),onCheckedChange:zr=>{At(zr?{...vt,tagIds:[...vt.tagIds,is.id]}:{...vt,tagIds:vt.tagIds.filter(Sa=>Sa!==is.id)})}}),e.jsx("span",{className:"text-sm",children:is.name})]},is.id))})]}),e.jsxs("div",{children:[e.jsx(se,{htmlFor:"notes",children:"Notes"}),e.jsx(Is,{id:"notes",value:vt.notes,onChange:is=>At({...vt,notes:is.target.value}),rows:3})]}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx($,{type:"button",variant:"outline",onClick:()=>{Xe(!1),Re(null),Ei()},children:"Cancel"}),e.jsxs($,{type:"submit",disabled:I.isPending||D.isPending,children:[Se?"Update":"Create"," Contact"]})]})]})]})}),e.jsx(CNn,{open:Ae,onOpenChange:Be,relationshipTypes:(b==null?void 0:b.filter(is=>is.active))||[],onSuccess:()=>{Be(!1)}}),e.jsx(TNn,{open:qe,onOpenChange:Ke,onComplete:()=>Ke(!1)}),e.jsx(qEe,{open:!!Ze,onOpenChange:is=>{is||Ue(null)},contactId:Ze||"",contactName:et}),e.jsx(wkn,{open:Xs,onOpenChange:rn}),e.jsx(jkn,{open:Ps,onOpenChange:_n}),e.jsx(xkn,{open:K,onOpenChange:Q,contacts:m||[],onCitySelect:is=>{V(is),js(1)}}),e.jsx(f8t,{open:Qn,onOpenChange:Sn,contactIds:Xt,contactNames:Xt.map(is=>{const zr=cs.find(Sa=>Sa.id===is);return zr?`${zr.first_name} ${zr.last_name||""}`.trim():""}),onComplete:()=>{rr([]),nt(new Set),lt(!1)}}),e.jsx(Os,{open:!!Ar,onOpenChange:is=>!is&&or(null),children:e.jsxs(Rs,{className:"sm:max-w-md",children:[e.jsx(Us,{children:e.jsx(zs,{children:"Choose a Lead Pond"})}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("p",{className:"text-sm text-muted-foreground",children:["Sharing ",(Ar==null?void 0:Ar.length)||0," contact",((Ar==null?void 0:Ar.length)||0)===1?"":"s"," with your team."]}),e.jsxs(vs,{value:qs,onValueChange:yr,children:[e.jsx(gs,{children:e.jsx(bs,{placeholder:"Select a pond"})}),e.jsx(ys,{children:In.map(is=>e.jsx(Ye,{value:is.id,children:is.name},is.id))})]}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx($,{variant:"outline",onClick:()=>or(null),children:"Cancel"}),e.jsx($,{onClick:()=>{Ar&&ln(Ar,qs),or(null)},disabled:!qs,children:"Share to Pond"})]})]})]})})]})]})})}const Fkn=5*1024*1024;function zkn({contactId:s,firstName:t,lastName:n,avatarUrl:r,email:a,size:i=88}){const l=j.useRef(null),o=ts(),[c,d]=j.useState(!1),u=()=>{o.invalidateQueries({queryKey:["innercircle-contacts"]}),o.invalidateQueries({queryKey:["innercircle-contact"]}),o.invalidateQueries({queryKey:["contact",s]})},h=async x=>{const{error:g}=await U.from("innercircle_contacts").update({avatar_url:x}).eq("id",s);if(g)throw g;u()},m=async x=>{var g;if(!x.type.startsWith("image/")){ja({title:"Please choose an image file",variant:"destructive"});return}if(x.size>Fkn){ja({title:"Image too large",description:"Please use an image under 5MB.",variant:"destructive"});return}d(!0);try{const{data:y}=await U.auth.getUser(),b=(g=y.user)==null?void 0:g.id,v=(x.name.split(".").pop()||"jpg").toLowerCase(),N=`contacts/${b}/${s}-${Date.now()}.${v}`,{error:C}=await U.storage.from("avatars").upload(N,x,{upsert:!0,contentType:x.type});if(C)throw C;const{data:A}=U.storage.from("avatars").getPublicUrl(N);await h(A.publicUrl),ja({title:"Photo updated"})}catch(y){ja({title:"Upload failed",description:y.message,variant:"destructive"})}finally{d(!1),l.current&&(l.current.value="")}},p=async()=>{d(!0);try{await h(null),ja({title:"Photo removed"})}catch(x){ja({title:"Could not remove photo",description:x.message,variant:"destructive"})}finally{d(!1)}};return e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("button",{type:"button",onClick:()=>{var x;return(x=l.current)==null?void 0:x.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($7t,{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(Ht,{className:"h-5 w-5 text-background animate-spin"}):e.jsx(y0,{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(Ht,{className:"h-5 w-5 text-background animate-spin"})})]}),r&&e.jsxs($,{variant:"ghost",size:"sm",className:"text-muted-foreground gap-1.5",onClick:p,disabled:c,children:[e.jsx(Pn,{className:"h-3.5 w-3.5"}),"Remove"]}),e.jsx("input",{ref:l,type:"file",accept:"image/*",className:"hidden",onChange:x=>{var y;const g=(y=x.target.files)==null?void 0:y[0];g&&m(g)}})]})}const Bkn={job_title:"Job title",company_name:"Company",city:"City",state:"State",avatar_url:"Profile photo"},$kn=4e3,Ukn=5*60*1e3;function qkn({open:s,onOpenChange:t,contactId:n,contactName:r,hasEmail:a}){var W;const{toast:i}=gi(),l=ts(),[o,c]=j.useState(""),[d,u]=j.useState(!1),[h,m]=j.useState(!1),[p,x]=j.useState(null),[g,y]=j.useState(!1),[b,v]=j.useState(null),[N,C]=j.useState(null),[A,T]=j.useState(0),P=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;P.current=Date.now(),T(0);let V=!1,K=null,Q=null;const J=async()=>{if(!V)try{const{data:ce,error:ue}=await U.functions.invoke("enrich-contact",{body:{contact_id:n,batch_id:N}});if(ue)throw ue;if((ce==null?void 0:ce.status)==="pending"){T(Date.now()-(P.current||Date.now()));return}ce!=null&&ce.ok&&ce.found?(x(ce.profile),v(ce.matched_on??null),C(null)):(y(!0),C(null))}catch(ce){i({title:"Enrichment status check failed",description:(ce==null?void 0:ce.message)??"Please try again.",variant:"destructive"}),C(null)}};return J(),K=setInterval(J,$kn),Q=setTimeout(()=>{V||(C(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"}))},Ukn),()=>{V=!0,K&&clearInterval(K),Q&&clearTimeout(Q)}},[N,s,n,i]);const D=async()=>{u(!0),y(!1),x(null),C(null);try{const{data:V,error:K}=await U.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)){C(V.batch_id);return}if(!(V!=null&&V.found)){y(!0);return}x(V.profile),v(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)}},B=()=>{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},q=async()=>{const V={};for(const K of B())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 U.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(Os,{open:s,onOpenChange:t,children:e.jsxs(Rs,{className:"max-w-lg",children:[e.jsxs(Us,{children:[e.jsxs(zs,{className:"flex items-center gap-2",children:[e.jsx(dn,{className:"h-4 w-4 text-primary"}),"Enrich ",r]}),e.jsx(Sr,{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(se,{htmlFor:"li-url",children:"LinkedIn URL (optional)"}),e.jsx(be,{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(Ht,{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"]})]}),g&&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(Oi,{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}),b&&e.jsxs($e,{variant:"secondary",className:"text-[10px]",children:["matched via ",b]})]}),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(Ai,{className:"h-3 w-3"}),p.company_name]}),p.location&&e.jsxs("span",{className:"inline-flex items-center gap-1",children:[e.jsx(ai,{className:"h-3 w-3"}),p.location]}),p.industry&&e.jsxs("span",{className:"inline-flex items-center gap-1",children:[e.jsx(ix,{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(kg,{className:"h-3 w-3"})," LinkedIn ",e.jsx(Tr,{className:"h-3 w-3"})]})]})]}),p.summary&&e.jsx("p",{className:"text-sm text-muted-foreground whitespace-pre-line",children:p.summary}),!!((W=p.experience)!=null&&W.length)&&e.jsxs("div",{className:"space-y-1",children:[e.jsx("p",{className:"text-xs font-semibold uppercase text-muted-foreground",children:"Experience"}),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))]}),B().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"}),B().map(V=>e.jsxs("label",{className:"flex items-start gap-2 text-sm",children:[e.jsx(ui,{checked:M[V.key],onCheckedChange:K=>I(Q=>({...Q,[V.key]:K===!0}))}),e.jsxs("span",{className:"min-w-0",children:[e.jsxs("span",{className:"font-medium",children:[Bkn[V.key],": "]}),e.jsx("span",{className:"text-muted-foreground break-all",children:V.value})]})]},V.key))]})]})})]}),e.jsxs(kr,{children:[e.jsx($,{variant:"outline",onClick:()=>t(!1),children:"Close"}),!p&&!N?e.jsxs($,{onClick:D,disabled:d,children:[d?e.jsx(Ht,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(dn,{className:"h-4 w-4 mr-2"}),d?"Searching…":"Find profile"]}):N?e.jsxs($,{disabled:!0,children:[e.jsx(Ht,{className:"h-4 w-4 mr-2 animate-spin"}),"Searching…"]}):e.jsxs($,{onClick:q,disabled:h,children:[h&&e.jsx(Ht,{className:"h-4 w-4 mr-2 animate-spin"}),"Save selected"]})]})]})})}const Vkn=["jeremy@relevelup.com"];function Hkn(){const{user:s}=_s(),t=((s==null?void 0:s.email)||"").toLowerCase();return Vkn.includes(t)}const ogt="America/New_York";function Gkn(s){const t=new Date(s),n=new Intl.DateTimeFormat("en-US",{timeZone:ogt,month:"short",day:"numeric",year:"numeric"}).format(t),r=new Intl.DateTimeFormat("en-US",{timeZone:ogt,hour:"numeric",minute:"2-digit"}).format(t);return`${n} · ${r}`}function Wkn(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 Kkn({contactId:s,ownerUserId:t,legacyNote:n}){const r=ts(),[a,i]=j.useState(""),{data:l=[],isLoading:o}=ht({queryKey:["contact-notes",s],queryFn:async()=>{const{data:u,error:h}=await U.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 g,y,b;const{data:h}=await U.auth.getUser(),m=h.user,p=((g=m==null?void 0:m.user_metadata)==null?void 0:g.full_name)||[(y=m==null?void 0:m.user_metadata)==null?void 0:y.first_name,(b=m==null?void 0:m.user_metadata)==null?void 0:b.last_name].filter(Boolean).join(" ")||(m==null?void 0:m.email)||null,{error:x}=await U.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(x)throw x},onSuccess:()=>{i(""),r.invalidateQueries({queryKey:["contact-notes",s]}),ja({title:"Note added"})},onError:u=>ja({title:"Could not add note",description:u.message,variant:"destructive"})}),d=yt({mutationFn:async u=>{const{error:h}=await U.from("innercircle_contact_notes").delete().eq("id",u);if(h)throw h},onSuccess:()=>r.invalidateQueries({queryKey:["contact-notes",s]})});return e.jsxs(_e,{children:[e.jsx(Bt,{className:"pb-3",children:e.jsxs(Ut,{className:"flex items-center gap-2 text-base",children:[e.jsx(Ji,{className:"h-4 w-4 text-primary"}),"Notes",l.length>0&&e.jsx($e,{variant:"secondary",className:"ml-1 rounded-full text-[11px]",children:l.length})]})}),e.jsxs(Oe,{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(Is,{value:a,onChange:u=>i(u.target.value),placeholder:"Add a note — it's stamped with the date and time automatically.",rows:3,className:"resize-none"}),e.jsx("div",{className:"flex justify-end",children:e.jsxs($,{size:"sm",disabled:!a.trim()||c.isPending,onClick:()=>c.mutate(a.trim()),children:[c.isPending?e.jsx(Ht,{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(Hr,{className:"h-3 w-3"}),Gkn(u.created_at)]}),e.jsxs("span",{children:["· ",Wkn(u.created_at)]}),u.source!=="agent"?e.jsxs($e,{variant:"outline",className:"gap-1 text-[10px]",children:[e.jsx(dn,{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(Pn,{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 Ykn="9a88a47c-cb2a-4401-a2b5-111a76b19f9d";function Zkn({open:s,onOpenChange:t,contact:n}){var W;const{user:r}=_s(),a=Vn(),i=ts(),{intakePage:l,isLoading:o}=VEe(),{isGmailConnected:c,gmailEmail:d}=ux(),u=JCe(),{data:h}=ht({queryKey:["profile-for-invite",r==null?void 0:r.id],enabled:!!(r!=null&&r.id)&&s,queryFn:async()=>{const{data:V}=await U.from("profiles").select("name, email, avatar_url").eq("id",r.id).maybeSingle();return V}}),m=(h==null?void 0:h.name)||((W=r==null?void 0:r.email)==null?void 0:W.split("@")[0])||"Your Agent",p=m.split(" ")[0],x=l?`https://contacts.relevelup.com/${l.slug}`:"",g=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,b]=j.useState("gmail"),[v,N]=j.useState(""),[C,A]=j.useState(""),[T,P]=j.useState(!1);j.useEffect(()=>{s&&(N(`Quick favor, ${n.first_name} — can you update your info?`),A(g),b(c?"gmail":"system"))},[s,g,n.first_name,c]);const M=j.useMemo(()=>C.split(/\n\n+/).map(V=>`

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

`).join(""),[C]),I=async()=>{var V,K;if(!l)return x;try{const{data:Q,error:J}=await U.functions.invoke("process-intake-submissions",{body:{action:"generate_tokens",contact_ids:[n.id],intake_page_id:l.id}}),ce=J?null:(K=(V=Q==null?void 0:Q.tokens)==null?void 0:V[0])==null?void 0:K.token;return ce?`${x}?t=${ce}`:x}catch{return x}},D=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

`,B=async()=>{if(!l){ae.error("Set up your Connect Page first",{action:{label:"Set Up",onClick:()=>a("/mission-control/connect-page")}});return}if(!v.trim()||!C.trim()){ae.error("Subject and message are required");return}P(!0);const V=await I(),K=D(V),Q=async()=>{const{data:J,error:ce}=await U.functions.invoke("send-connect-invite",{body:{contactEmail:n.email,subject:v,htmlBody:K,replyToEmail:(h==null?void 0:h.email)||(r==null?void 0:r.email),agentName:m}});if(ce)throw ce;if(!(J!=null&&J.success))throw new Error((J==null?void 0:J.error)||"Failed to send")};try{if(y==="gmail"&&c){const{data:J,error:ce}=await U.functions.invoke("gmail-send",{body:{to:n.email,subject:v,body:K,contactId:n.id}});let ue=J&&J.error?J:null;if(ce){ue={error:"send_failed",message:ce.message};const ne=ce.context;if(ne&&typeof ne.json=="function")try{ue=await ne.clone().json()}catch{}}if(ue)if(ue.error==="insufficient_scope")await Q(),ae.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(!(J!=null&&J.success))throw new Error("Failed to send")}else await Q();try{await u.mutateAsync({contactId:n.id,actionTypeId:Ykn,notes:`Sent Connect Page invite — Subject: "${v}"`})}catch(J){console.warn("Failed to log activity:",J)}i.invalidateQueries({queryKey:["contact-touch-logs"]}),ae.success("Connect Page invite sent!"),t(!1)}catch(J){console.error("Send error:",J),ae.error(J instanceof Error?J.message:"Failed to send invite")}finally{P(!1)}},q=C.split(/\n\n+/).filter(Boolean);return e.jsx(Os,{open:s,onOpenChange:V=>!T&&t(V),children:e.jsxs(Rs,{className:"sm:max-w-[720px] max-h-[92vh] overflow-y-auto",children:[e.jsxs(Us,{children:[e.jsxs(zs,{className:"flex items-center gap-2",children:[e.jsx(dn,{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(Ht,{className:"h-6 w-6 animate-spin text-primary"})}):l?e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(se,{className:"text-xs uppercase tracking-wide text-muted-foreground",children:"Send From"}),e.jsx(ua,{value:y,onValueChange:V=>b(V),className:"mt-1.5",children:e.jsxs(ha,{className:"grid w-full grid-cols-2",children:[e.jsxs(Qt,{value:"gmail",disabled:!c,children:[e.jsx(nn,{className:"h-3.5 w-3.5 mr-1.5"}),c?`Gmail (${d})`:"Gmail (not connected)"]}),e.jsxs(Qt,{value:"system",children:[e.jsx(dn,{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(se,{htmlFor:"invite-subject",children:"Subject"}),e.jsx(be,{id:"invite-subject",value:v,onChange:V=>N(V.target.value),className:"mt-1.5"})]}),e.jsxs("div",{children:[e.jsx(se,{htmlFor:"invite-message",children:"Personal Message"}),e.jsx(Is,{id:"invite-message",value:C,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(se,{className:"text-xs uppercase tracking-wide text-muted-foreground",children:"Preview"}),e.jsxs("a",{href:x,target:"_blank",rel:"noopener noreferrer",className:"text-xs text-primary hover:underline flex items-center gap-1",children:["Open Connect Page ",e.jsx(Tr,{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:q.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:[x,"?t=…"]})]})}),e.jsx("div",{className:"border-t border-slate-100 px-6 py-4 text-center",children:e.jsxs("p",{className:"text-[11px] text-slate-400",children:["Sent with care by ",m]})})]})}),e.jsxs("p",{className:"text-[11px] text-muted-foreground mt-1.5",children:["Each invite includes a private link that pre-fills ",n.first_name,"'s current info, so their updates come straight back to this contact record."]})]}),e.jsxs("div",{className:"flex items-center justify-end gap-2 pt-2",children:[e.jsx($,{variant:"outline",onClick:()=>t(!1),disabled:T,children:"Cancel"}),e.jsx($,{onClick:B,disabled:T,children:T?e.jsxs(e.Fragment,{children:[e.jsx(Ht,{className:"h-4 w-4 mr-1.5 animate-spin"})," Sending…"]}):e.jsxs(e.Fragment,{children:[e.jsx(Br,{className:"h-4 w-4 mr-1.5"})," Send Invite"]})})]})]}):e.jsxs("div",{className:"space-y-4 py-6 text-center",children:[e.jsx(xo,{className:"h-10 w-10 text-amber-500 mx-auto"}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:"You haven't set up a Connect Page yet"}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:"Create yours in one click — it only takes a moment."})]}),e.jsxs($,{onClick:()=>a("/mission-control/connect-page"),children:[e.jsx(Dc,{className:"h-4 w-4 mr-1"})," Set Up Connect Page"]})]})]})})}function Xkn(){const{user:s}=_s();return ht({queryKey:["cmas",s==null?void 0:s.id],queryFn:async()=>{const{data:t,error:n}=await U.from("cmas").select("*").eq("agent_id",s.id).order("updated_at",{ascending:!1});if(n)throw n;return t},enabled:!!s})}function Qkn(s){return ht({queryKey:["cma",s],queryFn:async()=>{const{data:t,error:n}=await U.from("cmas").select("*").eq("id",s).single();if(n)throw n;return t},enabled:!!s})}function Jkn(s){return ht({queryKey:["cma-comps",s],queryFn:async()=>{const{data:t,error:n}=await U.from("cma_comps").select("*").eq("cma_id",s).order("position",{ascending:!0});if(n)throw n;return t||[]},enabled:!!s})}function q7t(){const s=ts(),{user:t}=_s(),{leadSite:n}=Mf();return yt({mutationFn:async r=>{const{data:a,error:i}=await U.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 eSn(){const s=ts();return yt({mutationFn:async({id:t,patch:n})=>{const{data:r,error:a}=await U.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 tSn(){const s=ts();return yt({mutationFn:async t=>{const{error:n}=await U.from("cmas").delete().eq("id",t);if(n)throw n},onSuccess:()=>s.invalidateQueries({queryKey:["cmas"]})})}function sSn(){const{leadSite:s}=Mf();return yt({mutationFn:async t=>{const{data:n,error:r}=await U.functions.invoke("cma-subject-lookup",{body:{...t,leadSiteId:(s==null?void 0:s.id)??null}});if(r)throw r;return n}})}function nSn(){const{leadSite:s}=Mf();return yt({mutationFn:async t=>{const{data:n,error:r}=await U.functions.invoke("cma-comp-search",{body:{...t,leadSiteId:t.leadSiteId??(s==null?void 0:s.id)??null}});if(r)throw r;return n}})}function rSn(){const s=ts();return yt({mutationFn:async({cmaId:t,comps:n})=>{if(await U.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 U.from("cma_comps").insert(r);if(a)throw a},onSuccess:(t,n)=>s.invalidateQueries({queryKey:["cma-comps",n.cmaId]})})}function lgt(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 aSn(s){return ht({queryKey:["contact-video-replies",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await U.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 iSn(s){return ht({queryKey:["client-portal",s],queryFn:async()=>{if(!s)return null;const{data:t,error:n}=await U.from("client_portals").select("*").eq("deal_id",s).maybeSingle();if(n)throw n;return t},enabled:!!s})}function LYe(){const s=Za(),t=ts();return yt({mutationFn:async n=>{if(!s)throw new Error("Not authenticated");const{data:r,error:a}=await U.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 uV(){const s=ts();return yt({mutationFn:async({id:t,...n})=>{const{data:r,error:a}=await U.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 V7t(){const s=ts();return yt({mutationFn:async t=>{const{data:n,error:r}=await U.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 H7t(){const s=ts();return yt({mutationFn:async t=>{const{data:n,error:r}=await U.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 G7t(){const s=ts();return yt({mutationFn:async({id:t,dealId:n})=>{await U.from("portal_updates").delete().eq("portal_id",t);const{error:r}=await U.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 oSn(s){return ht({queryKey:["portal-updates",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await U.from("portal_updates").select("*").eq("portal_id",s).order("created_at",{ascending:!1});if(n)throw n;return t},enabled:!!s})}function W7t(){const s=ts();return yt({mutationFn:async t=>{const{data:n,error:r}=await U.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 lSn(){const s=Za();return ht({queryKey:["portal-custom-questions",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await U.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 cSn(){const s=Za(),t=ts();return yt({mutationFn:async n=>{if(!s)throw new Error("Not authenticated");const{data:r,error:a}=await U.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 dSn(){const s=ts();return yt({mutationFn:async({id:t,...n})=>{const{data:r,error:a}=await U.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 uSn(){const s=ts();return yt({mutationFn:async t=>{const{error:n}=await U.from("portal_custom_questions").update({is_active:!1}).eq("id",t);if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["portal-custom-questions"]})}})}function f5(s){const t=window.location.hostname;return t==="localhost"||t.includes("lovable.app")?`${window.location.origin}/portal/${s}`:`https://clients.relevelup.com/${s}`}function hSn({contactId:s}){const t=Vn(),n=ts(),[r,a]=j.useState(null),[i,l]=j.useState(!1),[o,c]=j.useState(!1),[d,u]=j.useState(""),[h,m]=j.useState(""),[p,x]=j.useState(null),g=uV(),y=W7t(),{data:b,isLoading:v}=ht({queryKey:["contact-portals",s],queryFn:async()=>{const{data:M,error:I}=await U.from("deal_pipeline").select("id, deal_name, deal_type").eq("contact_id",s);if(I)throw I;if(!M||M.length===0)return[];const D=M.map(W=>W.id),{data:B,error:q}=await U.from("client_portals").select("*").in("deal_id",D).is("archived_at",null);if(q)throw q;return(B||[]).map(W=>({...W,deal:M.find(V=>V.id===W.deal_id)}))},enabled:!!s}),N=(b==null?void 0:b.map(M=>M.id))||[],{data:C}=ht({queryKey:["contact-portal-updates",N],queryFn:async()=>{if(N.length===0)return{};const{data:M,error:I}=await U.from("portal_updates").select("*").in("portal_id",N).order("created_at",{ascending:!1});if(I)throw I;const D={};return(M||[]).forEach(B=>{D[B.portal_id]||(D[B.portal_id]=B)}),D},enabled:N.length>0}),A=M=>{navigator.clipboard.writeText(f5(M)),a(M),ae.success("Portal link copied!"),setTimeout(()=>a(null),2e3)},T=async M=>{d.trim()&&(await y.mutateAsync({portal_id:M,title:d,content:h||void 0}),c(!1),u(""),m(""),n.invalidateQueries({queryKey:["contact-portal-updates"]}),ae.success("Portal update posted!"))},P=async()=>{p&&(await g.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),x(null),n.invalidateQueries({queryKey:["contact-portals",s]}),ae.success("Portal settings updated!"))};return v||!b||b.length===0?null:e.jsxs(_e,{children:[e.jsx(Bt,{className:"pb-2",children:e.jsxs(Ut,{className:"text-base flex items-center gap-2",children:[e.jsx(Gl,{className:"h-4 w-4"}),"Client Portal"]})}),e.jsx(Oe,{className:"space-y-3",children:b.map(M=>{var q,W,V;const I=((q=M.stage_mapping)==null?void 0:q.length)>0?M.stage_mapping:ZCe(((W=M.deal)==null?void 0:W.deal_type)||"buyer"),D=I==null?void 0:I[M.current_stage_index??0],B=C==null?void 0:C[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"}),D&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Stage: ",D.label||D.name]})]}),e.jsx($e,{variant:M.is_enabled?"default":"secondary",className:"text-[10px] flex-shrink-0",children:M.is_enabled?"Active":"Disabled"})]}),B&&e.jsxs("div",{className:"bg-muted/50 rounded-md p-2",children:[e.jsx("p",{className:"text-xs font-medium truncate",children:B.title}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:Hs(new Date(B.created_at),"MMM d, yyyy")})]}),e.jsxs("div",{className:"flex flex-wrap gap-1.5",children:[e.jsxs($,{variant:"outline",size:"sm",className:"h-7 text-xs",onClick:()=>A(M.slug),children:[r===M.slug?e.jsx(oa,{className:"h-3 w-3 mr-1"}):e.jsx(Ca,{className:"h-3 w-3 mr-1"}),"Copy Link"]}),e.jsxs($,{variant:"outline",size:"sm",className:"h-7 text-xs",onClick:()=>window.open(f5(M.slug),"_blank"),children:[e.jsx(Tr,{className:"h-3 w-3 mr-1"}),"View"]}),e.jsxs(Os,{open:o,onOpenChange:c,children:[e.jsx(Ko,{asChild:!0,children:e.jsxs($,{variant:"outline",size:"sm",className:"h-7 text-xs",onClick:()=>c(!0),children:[e.jsx(Ji,{className:"h-3 w-3 mr-1"}),"Post Update"]})}),e.jsxs(Rs,{children:[e.jsx(Us,{children:e.jsx(zs,{children:"Post Portal Update"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(se,{children:"Title"}),e.jsx(be,{value:d,onChange:K=>u(K.target.value),placeholder:"e.g. Inspection completed!"})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Details (optional)"}),e.jsx(Is,{value:h,onChange:K=>m(K.target.value),placeholder:"Add more details...",rows:3})]}),e.jsxs($,{onClick:()=>T(M.id),disabled:!d.trim()||y.isPending,className:"w-full",children:[e.jsx(Br,{className:"h-4 w-4 mr-1"}),"Post Update"]})]})]})]}),e.jsxs(Os,{open:i,onOpenChange:l,children:[e.jsx(Ko,{asChild:!0,children:e.jsxs($,{variant:"outline",size:"sm",className:"h-7 text-xs",onClick:()=>{x({...M}),l(!0)},children:[e.jsx(pc,{className:"h-3 w-3 mr-1"}),"Settings"]})}),e.jsxs(Rs,{children:[e.jsx(Us,{children:e.jsx(zs,{children:"Portal Settings"})}),p&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(se,{children:"Portal Enabled"}),e.jsx(Tn,{checked:p.is_enabled,onCheckedChange:K=>x({...p,is_enabled:K})})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Welcome Message"}),e.jsx(Is,{value:p.welcome_message||"",onChange:K=>x({...p,welcome_message:K.target.value}),placeholder:"Welcome to your home journey!",rows:2})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Next Step"}),e.jsx(be,{value:p.next_step_text||"",onChange:K=>x({...p,next_step_text:K.target.value}),placeholder:"What your client should do next..."})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Review URL"}),e.jsx(be,{value:p.review_url||"",onChange:K=>x({...p,review_url:K.target.value}),placeholder:"https://..."})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(se,{children:"Show Post-Close Tips"}),e.jsx(Tn,{checked:p.show_post_close_tips,onCheckedChange:K=>x({...p,show_post_close_tips:K})})]}),e.jsx(Hl,{}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx($,{onClick:P,disabled:g.isPending,className:"flex-1",children:"Save Settings"}),e.jsxs($,{variant:"outline",onClick:()=>t(`/mission-control/pipeline?deal=${M.deal_id}`),children:[e.jsx(ni,{className:"h-4 w-4 mr-1"}),"Full Settings"]})]})]})]})]})]}),b.length>1&&e.jsx(Hl,{})]},M.id)})})]})}function mSn({contactId:s}){const{data:t}=ht({queryKey:["agent-lead-sites-slugs"],queryFn:async()=>{const{data:l,error:o}=await U.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}=ht({queryKey:["contact-property-views",s],queryFn:async()=>{const{data:l,error:o}=await U.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(_e,{className:"overflow-hidden",children:[e.jsx(Bt,{className:"pb-2",children:e.jsxs(Ut,{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(ga,{className:"h-4 w-4 text-primary"})}),"Property Activity",e.jsxs($e,{variant:"secondary",className:"text-xs ml-auto",children:[r.length," ",r.length===1?"property":"properties"]})]})}),e.jsx(Oe,{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(sa,{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(Hr,{className:"h-3 w-3"}),e.jsx("span",{title:Hs(new Date(l.viewed_at),"PPp"),children:fc(new Date(l.viewed_at),{addSuffix:!0})})]})]}),o&&e.jsx(Tr,{className:"h-3.5 w-3.5 text-muted-foreground opacity-0 group-hover:opacity-100 transition-opacity"})]},l.mls_number)})})})]})}const pSn=["Single Family","Condo","Townhouse","Multi-Family","Land","Commercial"];function cgt({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)&&c.current&&!c.current.contains(m.target)&&o(!1)};return document.addEventListener("mousedown",h),()=>document.removeEventListener("mousedown",h)},[]);const u=r.filter(h=>h.toLowerCase().includes(s.toLowerCase()));return e.jsxs("div",{className:"relative flex-1",children:[e.jsxs("div",{className:"flex gap-2",children:[e.jsxs("div",{className:"relative flex-1",children:[e.jsx(be,{ref:c,value:s,onChange:h=>{t(h.target.value),o(!0)},onFocus:()=>o(!0),placeholder:a,onKeyDown:h=>{h.key==="Enter"&&(h.preventDefault(),u.length>0?n(u[0]):n(s))}}),r.length>0&&e.jsx(_o,{className:"absolute right-3 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-muted-foreground pointer-events-none"})]}),e.jsx($,{type:"button",variant:"outline",size:"sm",onClick:()=>n(s),children:e.jsx(sn,{className:"h-4 w-4"})})]}),l&&u.length>0&&e.jsx("div",{ref:d,className:"absolute z-50 mt-1 w-full max-h-60 overflow-y-auto rounded-md border bg-popover shadow-md",children: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(ai,{className:"h-3 w-3 text-muted-foreground flex-shrink-0"}),h]},h))})]})}function fSn({contactId:s,contactName:t}){var ee,le,he;const{user:n}=_s(),r=Za(),{hasLeadSite:a}=Mf(),i=ts(),[l,o]=j.useState(!1),[c,d]=j.useState(""),[u,h]=j.useState(""),[m,p]=j.useState(!1),[x,g]=j.useState(""),[y,b]=j.useState(null),[v,N]=j.useState(!1),[C,A]=j.useState(!1),{data:T}=ht({queryKey:["agent-lead-site-config",r],queryFn:async()=>{const{data:ve,error:ge}=await U.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(ge||!ve)return{cities:[],zipCodes:[]};const fe=ve.theme_config||{},je=Array.isArray(fe.searchCities)?fe.searchCities:[];ve.mls_market_area&&!je.includes(ve.mls_market_area)&&je.unshift(ve.mls_market_area);const Ee=Array.isArray(fe.searchZipCodes)?fe.searchZipCodes:[];return{cities:je,zipCodes:Ee}},enabled:!!r}),{data:P,isLoading:M}=ht({queryKey:["contact-property-alert",s],queryFn:async()=>{const{data:ve,error:ge}=await U.from("contact_property_alerts").select("*").eq("contact_id",s).maybeSingle();if(ge)throw ge;return ve},enabled:!!s&&!!n}),[I,D]=j.useState({}),B=()=>{D({is_active:(P==null?void 0:P.is_active)??!0,min_price:(P==null?void 0:P.min_price)??null,max_price:(P==null?void 0:P.max_price)??null,min_beds:(P==null?void 0:P.min_beds)??null,min_baths:(P==null?void 0:P.min_baths)??null,min_sqft:(P==null?void 0:P.min_sqft)??null,max_sqft:(P==null?void 0:P.max_sqft)??null,cities:(P==null?void 0:P.cities)??[],zip_codes:(P==null?void 0:P.zip_codes)??[],property_types:(P==null?void 0:P.property_types)??[],frequency:(P==null?void 0:P.frequency)??"daily"}),o(!0)},q=yt({mutationFn:async()=>{const ve={contact_id:s,owner_user_id:r,is_active:I.is_active??!0,min_price:I.min_price||null,max_price:I.max_price||null,min_beds:I.min_beds||null,min_baths:I.min_baths||null,min_sqft:I.min_sqft||null,max_sqft:I.max_sqft||null,cities:I.cities||[],zip_codes:I.zip_codes||[],property_types:I.property_types||[],frequency:I.frequency||"daily"};if(P!=null&&P.id){const{error:ge}=await U.from("contact_property_alerts").update(ve).eq("id",P.id);if(ge)throw ge}else{const{error:ge}=await U.from("contact_property_alerts").insert(ve);if(ge)throw ge}},onSuccess:()=>{i.invalidateQueries({queryKey:["contact-property-alert",s]}),o(!1),ae.success("Property alert saved!")},onError:ve=>{ae.error(ve.message||"Failed to save alert")}}),W=yt({mutationFn:async()=>{if(!(P!=null&&P.id))return;const{error:ve}=await U.from("contact_property_alerts").delete().eq("id",P.id);if(ve)throw ve},onSuccess:()=>{i.invalidateQueries({queryKey:["contact-property-alert",s]}),o(!1),ae.success("Property alert removed")}}),V=ve=>{var fe;const ge=ve.trim();ge&&!((fe=I.cities)!=null&&fe.includes(ge))&&D(je=>({...je,cities:[...je.cities||[],ge]})),d("")},K=ve=>{var fe;const ge=ve.trim();ge&&!((fe=I.zip_codes)!=null&&fe.includes(ge))&&D(je=>({...je,zip_codes:[...je.zip_codes||[],ge]})),h("")},Q=ve=>{D(ge=>{const fe=ge.property_types||[];return{...ge,property_types:fe.includes(ve)?fe.filter(je=>je!==ve):[...fe,ve]}})},J=async()=>{if(P!=null&&P.id){N(!0),p(!0),g(""),b(null);try{const{data:ve,error:ge}=await U.functions.invoke("process-property-alerts",{body:{alert_id:P.id,mode:"preview"}});if(ge)throw ge;ve!=null&&ve.html?(g(ve.html),b({count:ve.listings_count||0,recipient:ve.recipient,subject:ve.subject})):b({count:0,message:(ve==null?void 0:ve.message)||"No matching listings found right now."})}catch(ve){ae.error(ve.message||"Failed to generate preview"),p(!1)}finally{N(!1)}}},ce=async()=>{if(P!=null&&P.id&&await Yi(`Send property alert email to ${t} now?`)){A(!0);try{const{data:ve,error:ge}=await U.functions.invoke("process-property-alerts",{body:{alert_id:P.id,mode:"send"}});if(ge)throw ge;ve!=null&&ve.sent_count?(ae.success(`Sent ${ve.sent_count} ${ve.sent_count===1?"listing":"listings"} to ${ve.recipient}`),i.invalidateQueries({queryKey:["contact-property-alert",s]})):ae.info((ve==null?void 0:ve.message)||"No new matching listings to send right now.")}catch(ve){ae.error(ve.message||"Failed to send alert")}finally{A(!1)}}};if(!a||M)return null;if(P&&!l)return e.jsxs(e.Fragment,{children:[e.jsxs(_e,{className:"overflow-hidden",children:[e.jsx(Bt,{className:"pb-2",children:e.jsxs(Ut,{className:"text-base flex items-center gap-2",children:[e.jsx("div",{className:`h-7 w-7 rounded-lg flex items-center justify-center ${P.is_active?"bg-green-500/10":"bg-muted"}`,children:P.is_active?e.jsx(Dx,{className:"h-4 w-4 text-green-600"}):e.jsx(e5,{className:"h-4 w-4 text-muted-foreground"})}),"Property Alerts",e.jsxs($e,{variant:P.is_active?"default":"secondary",className:"text-xs ml-auto",children:[P.is_active?"Active":"Paused"," · ",P.frequency]})]})}),e.jsxs(Oe,{className:"pt-0 space-y-2",children:[e.jsxs("div",{className:"flex flex-wrap gap-1.5 text-xs",children:[P.min_price||P.max_price?e.jsxs($e,{variant:"outline",className:"gap-1",children:[e.jsx(qd,{className:"h-3 w-3"}),P.min_price?`$${(P.min_price/1e3).toFixed(0)}k`:"$0"," - ",P.max_price?`$${(P.max_price/1e3).toFixed(0)}k`:"Any"]}):null,P.min_beds?e.jsxs($e,{variant:"outline",className:"gap-1",children:[e.jsx(JS,{className:"h-3 w-3"}),P.min_beds,"+ beds"]}):null,P.min_baths?e.jsxs($e,{variant:"outline",className:"gap-1",children:[e.jsx(_g,{className:"h-3 w-3"}),P.min_baths,"+ baths"]}):null,(ee=P.cities)==null?void 0:ee.map(ve=>e.jsxs($e,{variant:"outline",className:"gap-1",children:[e.jsx(ai,{className:"h-3 w-3"}),ve]},ve)),(le=P.zip_codes)==null?void 0:le.map(ve=>e.jsx($e,{variant:"outline",children:ve},ve)),(he=P.property_types)==null?void 0:he.map(ve=>e.jsx($e,{variant:"outline",children:ve},ve))]}),P.last_sent_at&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Last sent: ",new Date(P.last_sent_at).toLocaleDateString()]}),e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsxs($,{variant:"outline",size:"sm",onClick:J,disabled:v,children:[v?e.jsx(Ht,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(ga,{className:"h-4 w-4 mr-1"}),"Preview Email"]}),e.jsxs($,{size:"sm",onClick:ce,disabled:C||!P.is_active,title:P.is_active?"Send this alert email now":"Activate alert to send",children:[C?e.jsx(Ht,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(Br,{className:"h-4 w-4 mr-1"}),"Send Now"]}),e.jsx($,{variant:"outline",size:"sm",onClick:B,children:"Manage Alert"}),e.jsxs($,{variant:"destructive",size:"sm",onClick:()=>W.mutate(),disabled:W.isPending,children:[W.isPending?e.jsx(Ht,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(pr,{className:"h-4 w-4 mr-1"}),"Remove"]})]})]})]}),e.jsx(Os,{open:m,onOpenChange:p,children:e.jsxs(Rs,{className:"max-w-3xl max-h-[90vh] flex flex-col",children:[e.jsxs(Us,{children:[e.jsx(zs,{children:"Property Alert Email Preview"}),(y==null?void 0:y.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:"})," ",y.recipient]}),e.jsxs("div",{children:[e.jsx("span",{className:"font-medium",children:"Subject:"})," ",y.subject]}),e.jsxs("div",{children:[e.jsx("span",{className:"font-medium",children:"Listings:"})," ",y.count]})]})]}),e.jsx("div",{className:"flex-1 overflow-hidden border rounded-md bg-muted/30",children:v?e.jsxs("div",{className:"flex items-center justify-center h-96 text-muted-foreground",children:[e.jsx(Ht,{className:"h-5 w-5 mr-2 animate-spin"})," Building preview…"]}):x?e.jsx("iframe",{srcDoc:x,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:(y==null?void 0:y.message)||"No matching listings found right now."})}),e.jsxs(kr,{children:[e.jsx($,{variant:"outline",onClick:()=>p(!1),children:"Close"}),x&&e.jsxs($,{onClick:()=>{p(!1),ce()},disabled:C||!P.is_active,children:[e.jsx(Br,{className:"h-4 w-4 mr-1"}),"Send to ",t]})]})]})})]});const ue=((T==null?void 0:T.cities)||[]).filter(ve=>{var ge;return!((ge=I.cities)!=null&&ge.includes(ve))}),ne=((T==null?void 0:T.zipCodes)||[]).filter(ve=>{var ge;return!((ge=I.zip_codes)!=null&&ge.includes(ve))});return l?e.jsxs(_e,{children:[e.jsx(Bt,{className:"pb-3",children:e.jsxs(Ut,{className:"text-base flex items-center gap-2",children:[e.jsx(Dx,{className:"h-4 w-4 text-primary"}),P?"Edit":"Setup"," Property Alert for ",t]})}),e.jsxs(Oe,{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(se,{children:"Alert Active"}),e.jsx(Tn,{checked:I.is_active??!0,onCheckedChange:ve=>D(ge=>({...ge,is_active:ve}))})]}),e.jsxs("div",{children:[e.jsxs(se,{className:"flex items-center gap-1 mb-1.5",children:[e.jsx(qd,{className:"h-3.5 w-3.5"})," Price Range"]}),e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsx(be,{type:"number",placeholder:"Min price",value:I.min_price??"",onChange:ve=>D(ge=>({...ge,min_price:ve.target.value?Number(ve.target.value):null}))}),e.jsx(be,{type:"number",placeholder:"Max price",value:I.max_price??"",onChange:ve=>D(ge=>({...ge,max_price:ve.target.value?Number(ve.target.value):null}))})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsxs(se,{className:"flex items-center gap-1 mb-1.5",children:[e.jsx(JS,{className:"h-3.5 w-3.5"})," Min Beds"]}),e.jsxs(vs,{value:I.min_beds?String(I.min_beds):"any",onValueChange:ve=>D(ge=>({...ge,min_beds:ve==="any"?null:Number(ve)})),children:[e.jsx(gs,{children:e.jsx(bs,{placeholder:"Any"})}),e.jsxs(ys,{children:[e.jsx(Ye,{value:"any",children:"Any"}),[1,2,3,4,5].map(ve=>e.jsxs(Ye,{value:String(ve),children:[ve,"+"]},ve))]})]})]}),e.jsxs("div",{children:[e.jsxs(se,{className:"flex items-center gap-1 mb-1.5",children:[e.jsx(_g,{className:"h-3.5 w-3.5"})," Min Baths"]}),e.jsxs(vs,{value:I.min_baths?String(I.min_baths):"any",onValueChange:ve=>D(ge=>({...ge,min_baths:ve==="any"?null:Number(ve)})),children:[e.jsx(gs,{children:e.jsx(bs,{placeholder:"Any"})}),e.jsxs(ys,{children:[e.jsx(Ye,{value:"any",children:"Any"}),[1,1.5,2,2.5,3,4].map(ve=>e.jsxs(Ye,{value:String(ve),children:[ve,"+"]},ve))]})]})]})]}),e.jsxs("div",{children:[e.jsxs(se,{className:"flex items-center gap-1 mb-1.5",children:[e.jsx(o5,{className:"h-3.5 w-3.5"})," Square Feet"]}),e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsx(be,{type:"number",placeholder:"Min sqft",value:I.min_sqft??"",onChange:ve=>D(ge=>({...ge,min_sqft:ve.target.value?Number(ve.target.value):null}))}),e.jsx(be,{type:"number",placeholder:"Max sqft",value:I.max_sqft??"",onChange:ve=>D(ge=>({...ge,max_sqft:ve.target.value?Number(ve.target.value):null}))})]})]}),e.jsxs("div",{children:[e.jsxs(se,{className:"flex items-center gap-1 mb-1.5",children:[e.jsx(ai,{className:"h-3.5 w-3.5"})," Cities"]}),e.jsx(cgt,{value:c,onChange:d,onAdd:V,suggestions:ue,placeholder:"Type to search cities..."}),I.cities&&I.cities.length>0&&e.jsx("div",{className:"flex flex-wrap gap-1 mt-2",children:I.cities.map(ve=>e.jsxs($e,{variant:"secondary",className:"gap-1",children:[ve,e.jsx("button",{onClick:()=>D(ge=>{var fe;return{...ge,cities:(fe=ge.cities)==null?void 0:fe.filter(je=>je!==ve)}}),children:e.jsx(pr,{className:"h-3 w-3"})})]},ve))})]}),e.jsxs("div",{children:[e.jsx(se,{className:"mb-1.5",children:"Zip Codes"}),e.jsx(cgt,{value:u,onChange:h,onAdd:K,suggestions:ne,placeholder:"Type to search zip codes...",icon:e.jsx("span",{className:"text-xs text-muted-foreground font-mono",children:"#"})}),I.zip_codes&&I.zip_codes.length>0&&e.jsx("div",{className:"flex flex-wrap gap-1 mt-2",children:I.zip_codes.map(ve=>e.jsxs($e,{variant:"secondary",className:"gap-1",children:[ve,e.jsx("button",{onClick:()=>D(ge=>{var fe;return{...ge,zip_codes:(fe=ge.zip_codes)==null?void 0:fe.filter(je=>je!==ve)}}),children:e.jsx(pr,{className:"h-3 w-3"})})]},ve))})]}),e.jsxs("div",{children:[e.jsxs(se,{className:"flex items-center gap-1 mb-1.5",children:[e.jsx(sa,{className:"h-3.5 w-3.5"})," Property Types"]}),e.jsx("div",{className:"flex flex-wrap gap-1.5",children:pSn.map(ve=>{var ge;return e.jsx($e,{variant:(ge=I.property_types)!=null&&ge.includes(ve)?"default":"outline",className:"cursor-pointer",onClick:()=>Q(ve),children:ve},ve)})})]}),e.jsxs("div",{children:[e.jsx(se,{className:"mb-1.5",children:"Frequency"}),e.jsxs(vs,{value:I.frequency||"daily",onValueChange:ve=>D(ge=>({...ge,frequency:ve})),children:[e.jsx(gs,{children:e.jsx(bs,{})}),e.jsxs(ys,{children:[e.jsx(Ye,{value:"daily",children:"Daily"}),e.jsx(Ye,{value:"weekly",children:"Weekly"})]})]})]}),e.jsxs("div",{className:"flex gap-2 pt-2",children:[e.jsxs($,{onClick:()=>q.mutate(),disabled:q.isPending,className:"flex-1",children:[q.isPending?e.jsx(Ht,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(Jo,{className:"h-4 w-4 mr-1"}),"Save Alert"]}),e.jsx($,{variant:"outline",onClick:()=>o(!1),children:"Cancel"}),P&&e.jsx($,{variant:"destructive",size:"icon",onClick:()=>W.mutate(),disabled:W.isPending,children:e.jsx(pr,{className:"h-4 w-4"})})]})]})]}):e.jsx(_e,{className:"overflow-hidden",children:e.jsx(Oe,{className:"p-4",children:e.jsxs("button",{onClick:B,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(Dx,{className:"h-4 w-4 text-primary"})}),e.jsxs("div",{className:"text-left",children:[e.jsx("p",{className:"font-medium text-sm",children:"Set Up Property Alerts"}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Automatically email ",t," new listings matching their criteria"]})]})]})})})}function xSn({contactId:s,contactName:t}){var Q;const{user:n}=_s(),r=Za(),{hasLeadSite:a}=Mf(),i=ts(),[l,o]=j.useState(!1),[c,d]=j.useState(""),[u,h]=j.useState([]),[m,p]=j.useState(!1),[x,g]=j.useState(!1),[y,b]=j.useState(!1),[v,N]=j.useState(""),C=j.useRef(null),A=j.useRef(null),{data:T}=ht({queryKey:["agent-lead-site-cities",r],queryFn:async()=>{const{data:J,error:ce}=await U.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(ce||!J)return[];const ue=J.theme_config||{},ne=Array.isArray(ue.searchCities)?ue.searchCities:[];return J.mls_market_area&&!ne.includes(J.mls_market_area)&&ne.unshift(J.mls_market_area),ne},enabled:!!r}),{data:P,isLoading:M}=ht({queryKey:["contact-market-report",s],queryFn:async()=>{const{data:J,error:ce}=await U.from("innercircle_contacts").select("market_report_enabled, market_report_cities").eq("id",s).single();if(ce)throw ce;return J},enabled:!!s&&!!n});j.useEffect(()=>{const J=ce=>{A.current&&!A.current.contains(ce.target)&&C.current&&!C.current.contains(ce.target)&&g(!1)};return document.addEventListener("mousedown",J),()=>document.removeEventListener("mousedown",J)},[]);const I=()=>{p((P==null?void 0:P.market_report_enabled)??!1),h((P==null?void 0:P.market_report_cities)??[]),o(!0)},D=J=>{const ce=(J||c).trim();ce&&!u.includes(ce)&&h([...u,ce]),d(""),g(!1)},B=(T||[]).filter(J=>!u.includes(J)&&J.toLowerCase().includes(c.toLowerCase())),q=yt({mutationFn:async()=>{const{data:J,error:ce}=await U.functions.invoke("send-market-report",{body:{action:"preview",agentId:r,cities:(P==null?void 0:P.market_report_cities)??[]}});if(ce)throw new Error(ce.message||"Failed to generate preview");if(J&&!J.ok&&J.error)throw new Error(J.error);return J},onSuccess:J=>{N(J.html),b(!0)},onError:J=>{ae.error(J.message||"Failed to generate preview")}}),W=yt({mutationFn:async()=>{const{data:J,error:ce}=await U.functions.invoke("send-market-report",{body:{action:"send",agentId:r,cities:(P==null?void 0:P.market_report_cities)??[],contactIds:[s]}});if(ce)throw new Error(ce.message||"Failed to send report");if(J&&!J.ok&&J.error)throw new Error(J.error);return J},onSuccess:()=>{ae.success(`Market report sent to ${t}!`)},onError:J=>{ae.error(J.message||"Failed to send report")}}),V=yt({mutationFn:async()=>{const{error:J}=await U.from("innercircle_contacts").update({market_report_enabled:m,market_report_cities:u}).eq("id",s);if(J)throw J},onSuccess:()=>{i.invalidateQueries({queryKey:["contact-market-report",s]}),o(!1),ae.success(m?"Monthly market report enabled!":"Market report disabled")},onError:J=>{ae.error(J.message||"Failed to save")}}),K=yt({mutationFn:async()=>{const{error:J}=await U.from("innercircle_contacts").update({market_report_enabled:!1,market_report_cities:[]}).eq("id",s);if(J)throw J},onSuccess:()=>{i.invalidateQueries({queryKey:["contact-market-report",s]}),o(!1),p(!1),h([]),ae.success("Market report removed")},onError:J=>{ae.error(J.message||"Failed to remove market report")}});return!a||M?null:P!=null&&P.market_report_enabled&&!l?e.jsxs(_e,{className:"overflow-hidden",children:[e.jsx(Bt,{className:"pb-2",children:e.jsxs(Ut,{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(ml,{className:"h-4 w-4 text-primary"})}),"Monthly Market Report",e.jsx($e,{variant:"default",className:"text-xs ml-auto",children:"Active"})]})}),e.jsxs(Oe,{className:"pt-0 space-y-2",children:[e.jsx("div",{className:"flex flex-wrap gap-1.5 text-xs",children:((Q=P.market_report_cities)==null?void 0:Q.length)>0?P.market_report_cities.map(J=>e.jsxs($e,{variant:"outline",className:"gap-1",children:[e.jsx(ai,{className:"h-3 w-3"}),J]},J)):e.jsx("span",{className:"text-muted-foreground",children:"Using default market area"})}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[t," receives a branded market report on the 1st of each month."]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs($,{variant:"outline",size:"sm",onClick:()=>q.mutate(),disabled:q.isPending,className:"flex-1",children:[q.isPending?e.jsx(Ht,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(ga,{className:"h-4 w-4 mr-1"}),"Preview"]}),e.jsxs($,{variant:"default",size:"sm",onClick:()=>W.mutate(),disabled:W.isPending,className:"flex-1",children:[W.isPending?e.jsx(Ht,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(Br,{className:"h-4 w-4 mr-1"}),"Send Now"]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx($,{variant:"outline",size:"sm",onClick:I,className:"flex-1",children:"Manage"}),e.jsxs($,{variant:"destructive",size:"sm",onClick:()=>K.mutate(),disabled:K.isPending,className:"flex-1",children:[K.isPending?e.jsx(Ht,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(pr,{className:"h-4 w-4 mr-1"}),"Remove"]})]}),e.jsx(Os,{open:y,onOpenChange:b,children:e.jsxs(Rs,{className:"max-w-3xl max-h-[85vh] overflow-hidden flex flex-col",children:[e.jsx(Us,{children:e.jsxs(zs,{className:"flex items-center gap-2",children:[e.jsx(ml,{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:v}})}),e.jsxs("div",{className:"flex gap-2 pt-4 border-t",children:[e.jsxs($,{onClick:()=>{b(!1),W.mutate()},disabled:W.isPending,className:"flex-1",children:[W.isPending?e.jsx(Ht,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(Br,{className:"h-4 w-4 mr-1"}),"Send to ",t]}),e.jsx($,{variant:"outline",onClick:()=>b(!1),children:"Close"})]})]})})]})]}):l?e.jsxs(_e,{children:[e.jsx(Bt,{className:"pb-3",children:e.jsxs(Ut,{className:"text-base flex items-center gap-2",children:[e.jsx(ml,{className:"h-4 w-4 text-primary"}),"Market Report for ",t]})}),e.jsxs(Oe,{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(se,{children:"Send Monthly Report"}),e.jsx(Tn,{checked:m,onCheckedChange:p})]}),m&&e.jsxs("div",{children:[e.jsxs(se,{className:"flex items-center gap-1 mb-1.5",children:[e.jsx(ai,{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(be,{ref:C,value:c,onChange:J=>{d(J.target.value),g(!0)},onFocus:()=>g(!0),placeholder:"Type to search cities...",onKeyDown:J=>{J.key==="Enter"&&(J.preventDefault(),B.length>0?D(B[0]):D())}}),e.jsx(_o,{className:"absolute right-3 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-muted-foreground pointer-events-none"})]}),e.jsx($,{type:"button",variant:"outline",size:"sm",onClick:()=>D(),children:e.jsx(sn,{className:"h-4 w-4"})})]}),x&&B.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:B.map(J=>e.jsxs("button",{type:"button",className:"w-full text-left px-3 py-2 text-sm hover:bg-accent hover:text-accent-foreground transition-colors flex items-center gap-2",onClick:()=>D(J),children:[e.jsx(ai,{className:"h-3 w-3 text-muted-foreground flex-shrink-0"}),J]},J))})]}),u.length>0&&e.jsx("div",{className:"flex flex-wrap gap-1 mt-2",children:u.map(J=>e.jsxs($e,{variant:"secondary",className:"gap-1",children:[J,e.jsx("button",{onClick:()=>h(u.filter(ce=>ce!==J)),children:e.jsx(pr,{className:"h-3 w-3"})})]},J))})]}),e.jsxs("div",{className:"flex gap-2 pt-2",children:[e.jsxs($,{onClick:()=>V.mutate(),disabled:V.isPending,className:"flex-1",children:[V.isPending?e.jsx(Ht,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(Jo,{className:"h-4 w-4 mr-1"}),"Save"]}),e.jsx($,{variant:"outline",onClick:()=>o(!1),children:"Cancel"})]})]})]}):e.jsx(_e,{className:"overflow-hidden",children:e.jsx(Oe,{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(ml,{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 gSn({contactId:s,contactName:t}){const n=ts(),[r,a]=j.useState(""),{data:i,isLoading:l}=ht({queryKey:["contact-email-prefs",s],enabled:!!s,queryFn:async()=>{const{data:d,error:u}=await U.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 U.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"]}),ae.success(d?`${t} will no longer receive newsletters or marketing emails`:`${t} is opted back in to marketing emails`)},onError:d=>ae.error(d.message)}),c=!!(i!=null&&i.email_opt_out);return e.jsxs(_e,{children:[e.jsx(Bt,{className:"pb-3",children:e.jsxs(Ut,{className:"flex items-center gap-2 text-base",children:[e.jsx(wT,{className:"h-4 w-4"}),"Email Preferences",c&&e.jsx($e,{variant:"destructive",className:"ml-1",children:"Opted out"})]})}),e.jsx(Oe,{className:"space-y-4",children:l?e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(Ht,{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(se,{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(Tn,{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(se,{htmlFor:"opt-out-reason",className:"text-xs",children:"Reason (optional)"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(be,{id:"opt-out-reason",value:r,placeholder:"e.g. Asked to stop monthly newsletter",onChange:d=>a(d.target.value)}),e.jsx($,{variant:"outline",size:"sm",disabled:o.isPending||r===((i==null?void 0:i.email_opt_out_reason)||""),onClick:()=>o.mutate({optOut:!0,reasonText:r}),children:"Save"})]}),(i==null?void 0:i.email_opt_out_at)&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Opted out ",Hs(new Date(i.email_opt_out_at),"MMM d, yyyy")]})]})]})})]})}function ySn(s){return ht({queryKey:["contact-drip-activity",s],queryFn:async()=>{if(!s)return{enrollments:[],stepLogs:[]};const{data:t,error:n}=await U.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 U.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 U.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 vSn(s){switch(s){case"active":return e.jsx($e,{variant:"secondary",className:"bg-emerald-500/10 text-emerald-600 border-emerald-500/20",children:"Active"});case"paused":return e.jsx($e,{variant:"secondary",className:"bg-amber-500/10 text-amber-600 border-amber-500/20",children:"Paused"});case"completed":return e.jsx($e,{variant:"secondary",className:"bg-sky-500/10 text-sky-600 border-sky-500/20",children:"Completed"});case"exited":return e.jsx($e,{variant:"outline",children:"Exited"});default:return e.jsx($e,{variant:"outline",children:s})}}function dgt(s){return s==="sent"?e.jsx(Fr,{className:"h-4 w-4 text-emerald-500"}):s==="failed"?e.jsx(mc,{className:"h-4 w-4 text-destructive"}):s==="skipped"?e.jsx(vy,{className:"h-4 w-4 text-muted-foreground"}):e.jsx(Hr,{className:"h-4 w-4 text-muted-foreground"})}function bSn({contactId:s}){const t=Vn(),{data:n,isLoading:r}=ySn(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(_e,{children:[e.jsx(Bt,{children:e.jsxs(Ut,{className:"flex items-center gap-2 text-base",children:[e.jsx(MT,{className:"h-5 w-5 text-emerald-500"}),"Drip Campaign Activity"]})}),e.jsxs(Oe,{className:"space-y-4",children:[l.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{className:"text-xs font-semibold uppercase tracking-wider text-muted-foreground",children:"Enrollments"}),l.map(c=>{var d;return e.jsxs("button",{onClick:()=>t("/mission-control/smart-drips"),className:"w-full text-left flex items-start gap-3 p-3 rounded-lg border hover:bg-muted/50 transition-colors",children:[e.jsx("div",{className:"h-8 w-8 rounded-full bg-emerald-500/10 flex items-center justify-center text-emerald-600 flex-shrink-0",children:e.jsx(MT,{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"}),vSn(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: ",fc(new Date(c.next_send_at),{addSuffix:!0})]}),c.completed_at&&e.jsxs(e.Fragment,{children:[" · Completed ",fc(new Date(c.completed_at),{addSuffix:!0})]}),c.exited_at&&!c.completed_at&&e.jsxs(e.Fragment,{children:[" · ",c.exit_reason||"Exited"," ",fc(new Date(c.exited_at),{addSuffix:!0})]})]})]}),e.jsx(Ja,{className:"h-4 w-4 text-muted-foreground mt-1 flex-shrink-0"})]},c.id)})]}),o.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("p",{className:"text-xs font-semibold uppercase tracking-wider text-muted-foreground",children:["Send History (",o.length,")"]}),e.jsxs("div",{className:"space-y-1",children:[o.slice(0,8).map(c=>{var d,u;return e.jsxs(Os,{open:(a==null?void 0:a.id)===c.id,onOpenChange:h=>!h&&i(null),children:[e.jsx(Ko,{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:dgt(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(Ji,{className:"h-3 w-3 text-muted-foreground flex-shrink-0"}):e.jsx(nn,{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"," · ",Hs(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(Rs,{className:"max-w-lg",children:[e.jsx(Us,{children:e.jsxs(zs,{className:"flex items-center gap-2",children:[dgt(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:Hs(new Date(c.sent_at),"MMM d, yyyy h:mm a")})]}),c.error_message&&e.jsx("div",{className:"rounded-md border border-destructive/30 bg-destructive/5 p-2 text-destructive text-xs",children:c.error_message})]})]})]},c.id)}),o.length>8&&e.jsx($,{variant:"ghost",size:"sm",className:"w-full text-xs",onClick:()=>t("/mission-control/smart-drips"),children:"View all in Smart Drips"})]})]})]})]})}function K7t({contactId:s}={}){const{user:t}=_s();return ht({queryKey:["sent-emails",t==null?void 0:t.id,s??"all"],enabled:!!t,queryFn:async()=>{const n=t.id;let r=U.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=U.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 U.from("email_campaigns").select("id, subject").eq("user_id",n),l=(i.data||[]).map(g=>g.id),o=new Map((i.data||[]).map(g=>[g.id,g.subject]));let c=[];if(l.length>0){let g=U.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&&(g=g.eq("contact_id",s)),c=(await g).data||[]}const[d,u]=await Promise.all([r,a]),h=(d.data||[]).map(g=>({id:`g-${g.id}`,channel:g.source==="portal_invite"?"Client Portal Invite":"Gmail",subject:g.subject,to_email:g.to_email,contact_id:g.contact_id,sent_at:g.sent_at,source:g.source})),m=(u.data||[]).map(g=>({id:`b-${g.id}`,channel:"Mass Email",subject:g.subject,to_email:g.contact_email,contact_id:g.contact_id,sent_at:g.sent_at,source:g.source,opened_at:g.opened_at,clicked_at:g.clicked_at})),p=c.map(g=>({id:`c-${g.id}`,channel:"Campaign",subject:o.get(g.campaign_id)||"(campaign)",to_email:g.email,contact_id:g.contact_id,sent_at:g.sent_at,source:null,campaign_id:g.campaign_id,opened_at:g.opened_at,clicked_at:g.clicked_at})),x=[...h,...m,...p];return x.sort((g,y)=>g.sent_at0&&e.jsx($e,{variant:"secondary",className:"ml-1",children:t.length})]})}),e.jsx(Oe,{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(nn,{className:"h-8 w-8 mx-auto mb-2 opacity-50"}),"No emails sent to this contact yet."]}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"space-y-2",children:i.map(l=>e.jsx("div",{className:"flex items-start justify-between gap-3 p-3 rounded-lg border hover:bg-muted/30",children:e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx($e,{variant:"outline",className:`text-xs ${_Sn[l.channel]}`,children:l.channel}),e.jsx("span",{className:"text-xs text-muted-foreground",children:Hs(new Date(l.sent_at),"MMM d, yyyy h:mm a")})]}),e.jsx("p",{className:"text-sm font-medium truncate",children:l.subject}),e.jsxs("p",{className:"text-xs text-muted-foreground truncate",children:["to ",l.to_email]})]})},l.id))}),t.length>5&&e.jsx($,{variant:"ghost",size:"sm",className:"w-full mt-3",onClick:()=>a(!r),children:r?"Show less":`Show all ${t.length}`}),e.jsx("div",{className:"mt-3 pt-3 border-t",children:e.jsx(Wn,{to:"/mission-control/sent-emails",className:"text-xs text-primary hover:underline",children:"View all sent emails →"})})]})})]})}function jSn({videoId:s}){var l;const{data:t,isLoading:n,error:r}=JNn(s);if(n)return e.jsxs("div",{className:"space-y-4",children:[e.jsx(on,{className:"w-full aspect-video rounded-lg"}),e.jsx(on,{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(mc,{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 NSn({contactId:s}){const t=Vn(),[n,r]=j.useState(!1),{data:a,isLoading:i}=ht({queryKey:["deal-tasks","contact",s],queryFn:async()=>{const{data:h,error:m}=await U.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 U.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}=ht({queryKey:["deal-tasks","contact",s],queryFn:async()=>{const{data:h,error:m}=await U.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(_e,{children:[e.jsx(Bt,{className:"pb-2",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(Ut,{className:"text-base flex items-center gap-2",children:[e.jsx(oa,{className:"h-4 w-4"}),"Tasks",d.length>0&&e.jsx($e,{variant:"secondary",className:"text-xs",children:d.length})]}),e.jsxs("div",{className:"flex gap-1",children:[e.jsx($,{variant:"ghost",size:"sm",onClick:()=>t("/mission-control/tasks"),children:"View All"}),e.jsx($,{variant:"outline",size:"sm",onClick:()=>r(!0),children:e.jsx(sn,{className:"h-3.5 w-3.5"})})]})]})}),e.jsx(Oe,{className:"space-y-1",children:i?e.jsx(on,{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:Hs(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(kSn,{contactId:s,open:n,onOpenChange:h=>{r(h),h||o()}})]})}function kSn({contactId:s,open:t,onOpenChange:n}){const[r,a]=j.useState(""),[i,l]=j.useState("medium"),[o,c]=j.useState(),{data:d}=ht({queryKey:["session"],queryFn:async()=>{const{data:h}=await U.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 U.from("deal_tasks").insert([{owner_user_id:d.user.id,contact_id:s,title:r.trim(),priority:i,status:"todo",due_date:o?Hs(o,"yyyy-MM-dd"):null}]);if(h){console.error("Task create error:",h);return}n(!1)};return e.jsx(Os,{open:t,onOpenChange:n,children:e.jsxs(Rs,{className:"sm:max-w-[400px]",children:[e.jsx(Us,{children:e.jsx(zs,{children:"Add Task"})}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx(se,{children:"Title"}),e.jsx(be,{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(se,{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(se,{children:"Due Date"}),e.jsx(be,{type:"date",value:o?Hs(o,"yyyy-MM-dd"):"",onChange:h=>c(h.target.value?new Date(h.target.value+"T00:00:00"):void 0)})]})]}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx($,{variant:"outline",onClick:()=>n(!1),children:"Cancel"}),e.jsx($,{onClick:u,disabled:!r.trim(),children:"Create Task"})]})]})]})})}function SSn({contactId:s}){const t=Vn(),{data:n,isLoading:r}=ht({queryKey:["contact-linked-deals",s],queryFn:async()=>{const{data:a,error:i}=await U.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(_e,{children:[e.jsx(Bt,{className:"pb-2",children:e.jsxs(Ut,{className:"text-base flex items-center gap-2",children:[e.jsx(ix,{className:"h-4 w-4"}),"Linked Deals"]})}),e.jsx(Oe,{className:"space-y-2",children:n.map(a=>{const i=a.stage;return e.jsx("button",{onClick:()=>t(`/mission-control/pipeline?deal=${a.id}`),className:"w-full text-left p-3 rounded-lg border hover:bg-accent transition-colors group",children:e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:"font-medium text-sm truncate",children:a.deal_name}),a.property_address&&e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:a.property_address}),e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[e.jsx($e,{variant:"outline",className:"text-[10px] capitalize",children:a.deal_type}),i&&e.jsxs($e,{variant:"outline",className:"text-[10px] gap-1",style:{borderColor:i.color,color:i.color,backgroundColor:`${i.color}10`},children:[e.jsx("span",{className:"h-1.5 w-1.5 rounded-full inline-block",style:{backgroundColor:i.color}}),i.name]})]})]}),e.jsx(ni,{className:"h-4 w-4 text-muted-foreground group-hover:text-primary transition-colors flex-shrink-0"})]})},a.id)})})]})}function CSn(){var Un,In,Ar,or;const{contactId:s}=Vi(),{hasIdx:t}=Mf(),n=Vn(),[r]=oc(),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(qs=>qs.trim()).filter(Boolean)),[o]),{data:u,isLoading:h}=sAs(s||""),{data:m}=Hb(),{data:p}=wee(),{data:x}=Rq(3650),{data:g}=HEe(365),{data:y}=aSn(s),{contactsWithScores:b}=jee(),{data:v}=FEe(),{score:N}=EAs(s||""),C=pGe(),A=fGe(),T=JCe(),P=M6t(),[M,I]=j.useState(!1),[D,B]=j.useState("overview"),[q,W]=j.useState(!1),V=Hkn(),[K,Q]=j.useState({}),[J,ce]=j.useState(!1),[ue,ne]=j.useState(null),[ee,le]=j.useState(""),[he,ve]=j.useState(void 0),[ge,fe]=j.useState(""),[je,Ee]=j.useState(null),[Me,De]=j.useState(!1),[ze,ke]=j.useState(null),[Xe,Se]=j.useState(!1),{isGmailConnected:Re,gmailEmail:Ae}=ux(),{isReady:Be}=iV(),qe=Be||Re,Ke=q7t(),[Ze,Ue]=j.useState(!1),{data:et}=ht({queryKey:["cma-eligible"],queryFn:async()=>{const{data:{user:qs}}=await U.auth.getUser();if(!qs)return!1;const{data:yr}=await U.from("lead_sites").select("id, mls_provider_id, no_mls_mode, is_active").eq("agent_id",qs.id);return(yr||[]).some(fn=>fn.is_active&&fn.mls_provider_id&&!fn.no_mls_mode)}}),Qe=async()=>{var Xt,rr,Qn,Sn;if(!u)return;const qs=(Xt=u.address)==null?void 0:Xt.trim(),yr=(rr=u.city)==null?void 0:rr.trim(),fn=(Qn=u.state)==null?void 0:Qn.trim().toUpperCase(),Zn=((Sn=u.zip_code)==null?void 0:Sn.trim())||"";if(!qs||!yr||!fn){ae.error("Add a full address (street, city, state) before creating a CMA.");return}try{Ue(!0);const $n=await Ke.mutateAsync({subject:{address:qs,city:yr,state:fn,zip:Zn},contactId:u.id,title:`${u.first_name||""} ${u.last_name||""}`.trim()+" — "+qs});n(`/mission-control/cma/${$n.id}`)}catch($n){ae.error("Could not create CMA: "+(($n==null?void 0:$n.message)||"unknown error"))}finally{Ue(!1)}},{data:Ge}=ht({queryKey:["gmail-sent-emails",s],queryFn:async()=>{const{data:qs,error:yr}=await U.from("gmail_sent_emails").select("*").eq("contact_id",s).order("sent_at",{ascending:!1});if(yr)throw yr;return qs},enabled:!!s}),nt=qs=>{if(!qs)return null;const yr=qs.match(/Video ID:\s*([a-f0-9-]+)/i);return yr?yr[1]:null},ft=j.useMemo(()=>{if(!b)return[];const qs=new Map;if(d.size>0&&v)for(const fn of v)qs.has(fn.contact_id)||qs.set(fn.contact_id,new Set),qs.get(fn.contact_id).add(fn.tag_id);let yr=b.filter(fn=>{var Qn,Sn,$n;const Zn=a===""||`${fn.first_name} ${fn.last_name}`.toLowerCase().includes(a.toLowerCase())||((Qn=fn.email)==null?void 0:Qn.toLowerCase().includes(a.toLowerCase()))||((Sn=fn.phone)==null?void 0:Sn.includes(a)),Xt=i==="all"||(($n=fn.tags)==null?void 0:$n.some(tn=>tn.relationship_type_id===i));let rr=!0;if(d.size>0){const tn=qs.get(fn.id)||new Set;c==="all"?rr=Array.from(d).every(ln=>tn.has(ln)):rr=Array.from(d).some(ln=>tn.has(ln))}return Zn&&Xt&&rr});return l==="not-touched-90"?yr=yr.filter(fn=>{const Zn=fn.relationshipScore.daysSinceTouch;return Zn===null||Zn>90}):l==="at-risk"?yr=yr.filter(fn=>fn.relationshipScore.status==="at-risk"):l==="cooling"?yr=yr.filter(fn=>fn.relationshipScore.status==="cooling"):l==="warm"&&(yr=yr.filter(fn=>fn.relationshipScore.status==="warm")),yr.map(fn=>fn.id)},[b,a,i,l,d,c,v]),lt=ft.indexOf(s||""),Mt=lt>0?ft[lt-1]:null,Ft=lt1&<!==-1,js=qs=>{const yr=new URLSearchParams;a&&yr.set("search",a),i!=="all"&&yr.set("type",i),l!=="all"&&yr.set("status",l),d.size>0&&(yr.set("tags",Array.from(d).join(",")),yr.set("tagMode",c));const fn=yr.toString();return`/mission-control/contacts/${qs}${fn?`?${fn}`:""}`},zt=j.useMemo(()=>{const qs=((x==null?void 0:x.filter(fn=>fn.contact_id===s))||[]).map(fn=>{var Qn,Sn,$n;const Zn=nt(fn.notes);let Xt=((Qn=fn.action_type)==null?void 0:Qn.name)||"Touch",rr=fn.notes;if(Xt==="Other"&&((Sn=fn.notes)!=null&&Sn.startsWith("["))){const tn=fn.notes.indexOf("]");tn>0&&(Xt=fn.notes.substring(1,tn),rr=fn.notes.substring(tn+1).replace(/^\s*—\s*/,"").trim()||null)}return{id:fn.id,type:"touch",completed_at:fn.completed_at,name:Xt,color:(($n=fn.action_type)==null?void 0:$n.color)||"#3B82F6",notes:rr,videoId:Zn}}),yr=((g==null?void 0:g.filter(fn=>fn.contact_id===s))||[]).map(fn=>({id:fn.id,type:"popby",completed_at:fn.completed_at,name:"Pop-by",color:"#F97316",notes:fn.notes,videoId:null}));return[...qs,...yr].sort((fn,Zn)=>new Date(Zn.completed_at).getTime()-new Date(fn.completed_at).getTime())},[x,g,s]),Nt=qs=>{var yr;return{first_name:qs.first_name||"",last_name:qs.last_name||"",email:qs.email||"",phone:qs.phone||"",address:qs.address||"",city:qs.city||"",state:qs.state||"",zip_code:qs.zip_code||"",birthday:qs.birthday||"",home_anniversary:qs.home_anniversary||"",wedding_anniversary:qs.wedding_anniversary||"",spouse_birthday:qs.spouse_birthday||"",spouse_name:qs.spouse_name||"",spouse_email:qs.spouse_email||"",company_name:qs.company_name||"",job_title:qs.job_title||"",lead_source_id:qs.lead_source_id||"",notes:qs.notes||"",tagIds:((yr=qs.tags)==null?void 0:yr.map(fn=>fn.relationship_type_id))||[]}};j.useEffect(()=>{I(!1),Q({})},[s]);const Ds=j.useRef(null);j.useEffect(()=>{u!=null&&u.id&&Ds.current!==u.id&&(Ds.current=u.id,Q(Nt(u)))},[u==null?void 0:u.id,u]);const _t=()=>{u&&(Q(Nt(u)),I(!0))},Xs=async()=>{await C.mutateAsync({id:s,...K,lead_source_id:K.lead_source_id||null}),I(!1)},rn=async()=>{await Yi("Are you sure you want to delete this contact?")&&(await A.mutateAsync(s),n("/mission-control/contacts"))},_n=((Un=p==null?void 0:p.find(qs=>qs.id===ue))==null?void 0:Un.name)==="Other",Zs=async()=>{if(!ue||_n&&!ge.trim())return;const qs=he?new Date(he.getFullYear(),he.getMonth(),he.getDate(),12,0,0).toISOString():void 0,yr=_n?`[${ge.trim()}]${ee?" — "+ee:""}`:ee;await T.mutateAsync({contactId:s,actionTypeId:ue,notes:yr,completedAt:qs}),ce(!1),ne(null),le(""),ve(void 0),fe("")},gr=(qs,yr)=>{qe&&u?(ke({email:qs,name:yr||`${u.first_name} ${u.last_name||""}`.trim()}),De(!0)):window.location.href=`mailto:${qs}`};return h?e.jsx(Ks,{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(Ks,{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($,{variant:"ghost",size:"sm",className:"-ml-2",onClick:()=>{window.history.length>1?n(-1):n("/mission-control/contacts")},children:[e.jsx(Ic,{className:"h-4 w-4 mr-1"}),"Back to Contacts"]}),Ts&&e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx($,{variant:"outline",size:"sm",className:"h-8 px-2",onClick:()=>Mt&&n(js(Mt)),disabled:!Mt,children:e.jsx(Ic,{className:"h-4 w-4"})}),e.jsxs("span",{className:"px-1 text-xs text-muted-foreground whitespace-nowrap",children:[lt+1," of ",ft.length]}),e.jsx($,{variant:"outline",size:"sm",className:"h-8 px-2",onClick:()=>Ft&&n(js(Ft)),disabled:!Ft,children:e.jsx(Ja,{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(zkn,{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(wT,{className:"h-3 w-3"}),"Emails opted out"]}),(((In=u.lead_source_ref)==null?void 0:In.name)||u.lead_source)&&e.jsx("span",{className:"hub-glass rounded-full px-2.5 py-1 text-[11px] font-medium",children:((Ar=u.lead_source_ref)==null?void 0:Ar.name)||u.lead_source}),(or=u.tags)==null?void 0:or.map(qs=>{const yr=m==null?void 0:m.find(fn=>fn.id===qs.relationship_type_id);return yr?e.jsx("span",{className:"hub-glass rounded-full px-2.5 py-1 text-[11px] font-medium",children:yr.name},qs.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:()=>gr(u.email),className:"inline-flex min-w-0 items-center gap-1.5 hub-ink-muted transition-opacity hover:opacity-100",children:[e.jsx(nn,{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(ya,{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(ai,{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:()=>W(!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(dn,{className:"h-4 w-4"}),"Enrich"]}),e.jsxs("button",{onClick:()=>{_t(),B("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(bm,{className:"h-4 w-4"}),"Edit"]}),e.jsx("button",{onClick:rn,className:"hub-glass inline-flex h-9 w-9 items-center justify-center rounded-full",title:"Delete contact",children:e.jsx(Pn,{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(ya,{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(Ji,{className:"h-4 w-4",style:{color:"hsl(var(--hub-glow))"}}),"Text"]}),u.email&&e.jsxs("button",{onClick:()=>gr(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(nn,{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(Xr,{className:"h-4 w-4",style:{color:"hsl(var(--hub-glow))"}}),"Video"]}),e.jsxs("button",{onClick:()=>ce(!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(sn,{className:"h-4 w-4",style:{color:"hsl(var(--hub-glow))"}}),"Log Action"]}),u.email&&e.jsxs("button",{onClick:()=>Se(!0),className:"hub-glass inline-flex items-center justify-center gap-2 rounded-xl px-4 py-2.5 text-sm font-medium",children:[e.jsx(dn,{className:"h-4 w-4",style:{color:"hsl(var(--hub-glow))"}}),"Connect Page"]})]})]})}),e.jsxs(ua,{value:D,onValueChange:qs=>{qs==="details"&&!M&&_t(),B(qs)},children:[e.jsx("div",{className:"-mx-1 overflow-x-auto px-1",children:e.jsxs(ha,{className:"inline-flex h-10 w-auto",children:[e.jsx(Qt,{value:"overview",children:"Overview"}),e.jsx(Qt,{value:"details",children:"Details"}),e.jsx(Qt,{value:"activity",children:"Activity"}),e.jsx(Qt,{value:"marketing",children:"Marketing"})]})}),e.jsx(Jt,{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(wNn,{contact:u,onLogTouch:()=>ce(!0)}),e.jsxs(_e,{children:[e.jsx(Bt,{className:"pb-3",children:e.jsxs(Ut,{className:"flex items-center gap-2 text-base",children:[e.jsx(ia,{className:"h-4 w-4 text-primary"}),"Key Dates"]})}),e.jsxs(Oe,{children:[e.jsx("div",{className:"grid gap-3 sm:grid-cols-2",children:[{icon:Co,label:"Birthday",value:u.birthday},{icon:sa,label:"Home Anniversary",value:u.home_anniversary},{icon:fo,label:"Wedding Anniversary",value:u.wedding_anniversary},{icon:fo,label:"Spouse Birthday",value:u.spouse_birthday}].map(({icon:qs,label:yr,value:fn})=>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(qs,{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:yr}),e.jsx("p",{className:"truncate text-sm font-medium",children:fn?Hs(mu(fn),mu(fn).getFullYear()===1900?"MMMM d":"MMMM d, yyyy"):"—"})]})]},yr))}),zt.length>0&&e.jsxs("p",{className:"mt-3 text-xs text-muted-foreground",children:["Last contacted ",Hs(new Date(zt[0].completed_at),"MMM d, yyyy")," (",zt[0].name,")",u.created_at&&` · Added ${Hs(new Date(u.created_at),"MMM d, yyyy")}`]})]})]}),(u.address||u.city)&&e.jsxs(_e,{children:[e.jsx(Bt,{className:"pb-3",children:e.jsxs(Ut,{className:"flex items-center gap-2 text-base",children:[e.jsx(sa,{className:"h-4 w-4 text-primary"}),"Home"]})}),e.jsxs(Oe,{className:"flex flex-wrap items-start justify-between gap-3",children:[e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx(ai,{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}`:""]})]})]}),et&&u.address&&u.city&&u.state&&e.jsxs($,{size:"sm",variant:"outline",onClick:Qe,disabled:Ze,children:[Ze?e.jsx(Ht,{className:"mr-1 h-4 w-4 animate-spin"}):e.jsx(s5,{className:"mr-1 h-4 w-4"}),"Create CMA"]})]})]}),e.jsx(Kkn,{contactId:u.id,ownerUserId:u.owner_user_id,legacyNote:u.notes}),e.jsx(NSn,{contactId:s})]}),e.jsxs("div",{className:"space-y-5",children:[e.jsxs(_e,{children:[e.jsx(Bt,{className:"pb-3",children:e.jsx(Ut,{className:"text-base",children:"Tags"})}),e.jsx(Oe,{children:e.jsx(Jxt,{contactId:s})})]}),e.jsxs(_e,{children:[e.jsx(Bt,{className:"pb-3",children:e.jsxs(Ut,{className:"flex items-center gap-2 text-base",children:[e.jsx(Lo,{className:"h-4 w-4 text-primary"}),"People & Work"]})}),e.jsxs(Oe,{className:"space-y-3",children:[e.jsx(aBe,{contactId:s,currentSpouseContactId:(u==null?void 0:u.spouse_contact_id)||null,currentSpouseName:u.spouse_name||null,currentSpouseEmail:u.spouse_email||null,onLink:qs=>P.mutate({contactId:s,spouseContactId:qs}),onUnlink:()=>P.mutate({contactId:s,spouseContactId:null}),isEditing:!1}),e.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[e.jsx(Ai,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:Tt(!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(SSn,{contactId:s}),e.jsx(hSn,{contactId:s})]})]})}),e.jsx(Jt,{value:"details",className:"mt-4",children:e.jsxs(_e,{children:[e.jsx(Bt,{className:"pb-3",children:e.jsx(Ut,{className:"text-base",children:"Edit Contact"})}),e.jsxs(Oe,{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(se,{htmlFor:"first_name",children:"First Name"}),e.jsx(be,{id:"first_name",value:K.first_name||"",onChange:qs=>Q({...K,first_name:qs.target.value})})]}),e.jsxs("div",{children:[e.jsx(se,{htmlFor:"last_name",children:"Last Name"}),e.jsx(be,{id:"last_name",value:K.last_name||"",onChange:qs=>Q({...K,last_name:qs.target.value})})]}),e.jsxs("div",{children:[e.jsx(se,{htmlFor:"email",children:"Email"}),e.jsx(be,{id:"email",type:"email",value:K.email||"",onChange:qs=>Q({...K,email:qs.target.value})})]}),e.jsxs("div",{children:[e.jsx(se,{htmlFor:"phone",children:"Phone"}),e.jsx(be,{id:"phone",value:K.phone||"",onChange:qs=>Q({...K,phone:qs.target.value})})]})]})]}),e.jsx(Hl,{}),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(se,{htmlFor:"address",children:"Street Address"}),e.jsx(be,{id:"address",value:K.address||"",onChange:qs=>Q({...K,address:qs.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(se,{htmlFor:"city",children:"City"}),e.jsx(be,{id:"city",value:K.city||"",onChange:qs=>Q({...K,city:qs.target.value}),placeholder:"City"})]}),e.jsxs("div",{children:[e.jsx(se,{htmlFor:"state",children:"State"}),e.jsx(be,{id:"state",value:K.state||"",onChange:qs=>Q({...K,state:qs.target.value}),placeholder:"TX",maxLength:2})]}),e.jsxs("div",{children:[e.jsx(se,{htmlFor:"zip_code",children:"Zip Code"}),e.jsx(be,{id:"zip_code",value:K.zip_code||"",onChange:qs=>Q({...K,zip_code:qs.target.value}),placeholder:"12345"})]})]})]}),e.jsx(Hl,{}),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(se,{htmlFor:"birthday",children:"Birthday"}),e.jsx(be,{id:"birthday",type:"date",value:K.birthday||"",onChange:qs=>Q({...K,birthday:qs.target.value})})]}),e.jsxs("div",{children:[e.jsx(se,{htmlFor:"home_anniversary",children:"Home Anniversary"}),e.jsx(be,{id:"home_anniversary",type:"date",value:K.home_anniversary||"",onChange:qs=>Q({...K,home_anniversary:qs.target.value})})]}),e.jsxs("div",{children:[e.jsx(se,{htmlFor:"wedding_anniversary",children:"Wedding Anniversary"}),e.jsx(be,{id:"wedding_anniversary",type:"date",value:K.wedding_anniversary||"",onChange:qs=>Q({...K,wedding_anniversary:qs.target.value})})]}),e.jsxs("div",{children:[e.jsx(se,{htmlFor:"spouse_birthday",children:"Spouse Birthday"}),e.jsx(be,{id:"spouse_birthday",type:"date",value:K.spouse_birthday||"",onChange:qs=>Q({...K,spouse_birthday:qs.target.value})})]})]})]}),e.jsx(Hl,{}),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(aBe,{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:qs=>P.mutate({contactId:s,spouseContactId:qs}),onUnlink:()=>P.mutate({contactId:s,spouseContactId:null}),isEditing:!0}),e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[e.jsxs("div",{children:[e.jsx(se,{htmlFor:"company_name",children:"Company"}),e.jsx(be,{id:"company_name",value:K.company_name||"",onChange:qs=>Q({...K,company_name:qs.target.value}),placeholder:"Enter company name"})]}),e.jsxs("div",{children:[e.jsx(se,{htmlFor:"job_title",children:"Job Title"}),e.jsx(be,{id:"job_title",value:K.job_title||"",onChange:qs=>Q({...K,job_title:qs.target.value}),placeholder:"Enter job title"})]})]}),e.jsx(B7t,{value:K.lead_source_id||"",onChange:qs=>Q({...K,lead_source_id:qs})})]}),e.jsx(Hl,{}),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(qs=>qs.active).map(qs=>{var fn;const yr=!!((fn=K.tagIds)!=null&&fn.includes(qs.id));return e.jsxs("label",{className:Tt("inline-flex cursor-pointer items-center gap-2 rounded-full border px-3 py-1.5 text-sm transition-colors",yr?"border-primary bg-primary/10 text-primary":"border-border hover:bg-accent"),children:[e.jsx(ui,{checked:yr,onCheckedChange:Zn=>{var Xt;Q(Zn?{...K,tagIds:[...K.tagIds||[],qs.id]}:{...K,tagIds:(Xt=K.tagIds)==null?void 0:Xt.filter(rr=>rr!==qs.id)})}}),qs.name]},qs.id)})}),e.jsxs("div",{children:[e.jsx(se,{children:"Tags"}),e.jsx("div",{className:"mt-2",children:e.jsx(Jxt,{contactId:s})})]})]}),e.jsx(Hl,{}),e.jsxs("div",{children:[e.jsx(se,{htmlFor:"notes",children:"Notes"}),e.jsx(Is,{id:"notes",value:K.notes||"",onChange:qs=>Q({...K,notes:qs.target.value}),rows:5})]}),e.jsxs("div",{className:"sticky bottom-0 -mx-6 flex flex-wrap items-center justify-end gap-2 border-t bg-card/95 px-6 py-3 backdrop-blur",children:[e.jsx($,{variant:"outline",onClick:()=>{I(!1),B("overview")},children:"Cancel"}),e.jsxs($,{onClick:Xs,disabled:C.isPending,children:[C.isPending?e.jsx(Ht,{className:"mr-1 h-4 w-4 animate-spin"}):e.jsx(oa,{className:"mr-1 h-4 w-4"}),"Save Changes"]})]})]})]})}),e.jsx(Jt,{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(_e,{children:[e.jsxs(Bt,{className:"flex flex-row items-center justify-between gap-2 pb-3",children:[e.jsx(Ut,{className:"text-base",children:"Activity Log"}),e.jsxs($,{size:"sm",variant:"outline",onClick:()=>ce(!0),children:[e.jsx(sn,{className:"mr-1 h-3.5 w-3.5"})," Log Action"]})]}),e.jsx(Oe,{children:zt.length>0?e.jsx("div",{className:"space-y-4",children:zt.map(qs=>{var yr;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:qs.color},children:qs.type==="popby"?e.jsx(Co,{className:"h-4 w-4"}):(yr=qs.name)==null?void 0:yr.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:qs.name}),qs.videoId&&e.jsxs($,{variant:"ghost",size:"sm",className:"h-6 px-2 text-xs",onClick:()=>Ee(qs.videoId),children:[e.jsx(Td,{className:"mr-1 h-3 w-3"}),"Preview"]})]}),e.jsx("div",{className:"text-xs text-muted-foreground",children:Hs(new Date(qs.completed_at),"MMM d, yyyy h:mm a")}),qs.notes&&!qs.videoId&&e.jsx("p",{className:"mt-1 text-sm text-muted-foreground",children:qs.notes})]})]},qs.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(_e,{children:[e.jsx(Bt,{className:"pb-3",children:e.jsxs(Ut,{className:"flex items-center gap-2 text-base",children:[e.jsx(Ji,{className:"h-4 w-4 text-primary"}),"Video Replies"]})}),e.jsx(Oe,{children:e.jsx("div",{className:"space-y-4",children:y.map(qs=>{var yr,fn;return e.jsxs("div",{className:"flex items-start gap-3 border-b pb-3 last:border-0",children:[(yr=qs.video)!=null&&yr.thumbnail_url?e.jsx("img",{src:qs.video.thumbnail_url,alt:qs.video.title||"Video",className:"h-12 w-16 cursor-pointer rounded object-cover transition-opacity hover:opacity-80",onClick:()=>Ee(qs.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:()=>Ee(qs.video_id),children:e.jsx(Xr,{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: ",((fn=qs.video)==null?void 0:fn.title)||"Untitled Video"]}),e.jsx("div",{className:"text-xs text-muted-foreground",children:Hs(new Date(qs.created_at),"MMM d, yyyy h:mm a")}),qs.message&&e.jsxs("p",{className:"mt-1 line-clamp-2 text-sm text-muted-foreground",children:['"',qs.message,'"']})]})]},qs.id)})})})]}),Ge&&Ge.length>0&&e.jsxs(_e,{children:[e.jsx(Bt,{className:"pb-3",children:e.jsxs(Ut,{className:"flex items-center gap-2 text-base",children:[e.jsx(Br,{className:"h-4 w-4 text-sky-500"}),"Sent Emails"]})}),e.jsx(Oe,{children:e.jsx("div",{className:"space-y-3",children:Ge.map(qs=>e.jsxs(Os,{children:[e.jsx(Ko,{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(nn,{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:qs.subject}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["To: ",qs.to_email," · ",Hs(new Date(qs.sent_at),"MMM d, yyyy h:mm a")]})]}),e.jsx(Ja,{className:"mt-1 h-4 w-4 flex-shrink-0 text-muted-foreground"})]})}),e.jsxs(Rs,{className:"flex max-h-[85vh] max-w-2xl flex-col",children:[e.jsxs(Us,{children:[e.jsxs(zs,{className:"flex items-center gap-2",children:[e.jsx(nn,{className:"h-5 w-5 text-sky-500"}),qs.subject]}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:["To: ",qs.to_email," · ",Hs(new Date(qs.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:qs.body,className:"h-[400px] w-full border-0",sandbox:"",title:`Email: ${qs.subject}`})})]})]},qs.id))})})]}),e.jsx(wSn,{contactId:s})]})]})}),e.jsx(Jt,{value:"marketing",className:"mt-4",children:e.jsxs("div",{className:"grid gap-5 lg:grid-cols-2",children:[e.jsx(gSn,{contactId:s,contactName:u.first_name}),e.jsx(mSn,{contactId:s}),t&&e.jsxs(e.Fragment,{children:[e.jsx(fSn,{contactId:s,contactName:u.first_name}),e.jsx(xSn,{contactId:s,contactName:u.first_name})]}),e.jsx(bSn,{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($,{variant:"outline",className:"w-full",children:[e.jsx(ya,{className:"mr-1 h-4 w-4"})," Call"]})}),u.phone&&e.jsxs($,{variant:"outline",className:"flex-1",onClick:()=>window.location.href=`sms:${u.phone}`,children:[e.jsx(Ji,{className:"mr-1 h-4 w-4"})," Text"]}),e.jsxs($,{className:"flex-1",onClick:()=>ce(!0),children:[e.jsx(sn,{className:"mr-1 h-4 w-4"})," Log"]})]}),e.jsx(Os,{open:J,onOpenChange:ce,children:e.jsxs(Rs,{className:"max-h-[85vh] overflow-y-auto",children:[e.jsx(Us,{children:e.jsx(zs,{children:"Log an Action"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(se,{children:"Action Type"}),e.jsx("div",{className:"mt-2 grid grid-cols-2 gap-2",children:p==null?void 0:p.filter(qs=>qs.active).map(qs=>e.jsxs("button",{onClick:()=>ne(qs.id),className:Tt("rounded-lg border p-3 text-left transition-all",ue===qs.id?"border-primary bg-primary/10":"hover:bg-accent"),children:[e.jsx("div",{className:"font-medium",children:qs.name}),e.jsx("div",{className:"text-xs text-muted-foreground",children:qs.description})]},qs.id))}),_n&&e.jsxs("div",{className:"mt-3",children:[e.jsx(se,{htmlFor:"custom-action-name",children:"What did you do?"}),e.jsx(be,{id:"custom-action-name",value:ge,onChange:qs=>fe(qs.target.value),placeholder:"e.g. Met a client for lunch, Dropped off a gift...",className:"mt-1"})]})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Date (optional — backdate if needed)"}),e.jsxs(Sc,{children:[e.jsx(Cc,{asChild:!0,children:e.jsxs($,{variant:"outline",className:Tt("mt-2 w-full justify-start text-left font-normal",!he&&"text-muted-foreground"),children:[e.jsx(ia,{className:"mr-2 h-4 w-4"}),he?Hs(he,"PPP"):"Today (default)"]})}),e.jsx(xc,{className:"w-auto p-0",align:"start",children:e.jsx(y1,{mode:"single",selected:he,onSelect:ve,disabled:qs=>qs>new Date,initialFocus:!0,className:Tt("p-3 pointer-events-auto")})})]})]}),e.jsxs("div",{children:[e.jsx(se,{htmlFor:"action-notes",children:"Notes (optional)"}),e.jsx(Is,{id:"action-notes",value:ee,onChange:qs=>le(qs.target.value),placeholder:"Add any notes about this interaction...",rows:3})]}),e.jsxs($,{onClick:Zs,disabled:!ue||_n&&!ge.trim()||T.isPending,className:"w-full",children:[e.jsx(oa,{className:"mr-1 h-4 w-4"}),"Complete Action"]})]})]})}),e.jsx(Os,{open:!!je,onOpenChange:qs=>!qs&&Ee(null),children:e.jsxs(Rs,{className:"max-w-2xl",children:[e.jsx(Us,{children:e.jsx(zs,{children:"Video Preview"})}),je&&e.jsx(jSn,{videoId:je})]})})]})}),V&&u&&e.jsx(qkn,{open:q,onOpenChange:W,contactId:u.id,contactName:`${u.first_name} ${u.last_name||""}`.trim(),hasEmail:!!u.email}),qe&&u&&ze&&e.jsx(x2,{open:Me,onOpenChange:De,contact:{id:u.id,first_name:u.first_name,last_name:u.last_name,email:ze.email},gmailEmail:Ae}),u&&u.email&&e.jsx(Zkn,{open:Xe,onOpenChange:Se,contact:{id:u.id,first_name:u.first_name,last_name:u.last_name,email:u.email}})]}):e.jsx(Ks,{title:"Contact Not Found",children:e.jsxs("div",{className:"text-center py-12",children:[e.jsx("p",{className:"text-muted-foreground mb-4",children:"This contact was not found."}),e.jsx($,{onClick:()=>n("/mission-control/contacts"),children:"Back to Contacts"})]})})}function ASn({rangeDays:s}){const{user:t}=_s(),n=ts(),[r,a]=j.useState(null),[i,l]=j.useState(null),[o,c]=j.useState(!1),{data:d=[],isLoading:u}=ht({queryKey:["newsletter-campaigns",t==null?void 0:t.id,s],enabled:!!t,queryFn:async()=>{let p=U.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:x,error:g}=await p;if(g)throw g;return x||[]}}),{data:h}=ht({queryKey:["newsletter-campaign-recipients",r],enabled:!!r,queryFn:async()=>{const{data:p,error:x}=await U.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(x)throw x;return p||[]}}),m=async()=>{if(!(!i||!t)){c(!0);try{const{data:p,error:x}=await U.from("email_campaign_recipients").select("email, name, contact_id").eq("campaign_id",i.id).eq("status","sent").is("opened_at",null).limit(5e3);if(x)throw x;if(!p||p.length===0){ae.info("All recipients opened — nothing to resend!"),l(null),c(!1);return}const{data:g}=await U.from("email_campaigns").select("subject, body_html, from_email, reply_to_email").eq("id",i.id).single();if(!g)throw new Error("Original campaign not found");const{data:y,error:b}=await U.from("email_campaigns").insert({user_id:t.id,name:`${i.name} (Resend to non-openers)`,subject:g.subject,body_html:g.body_html,from_email:g.from_email,reply_to_email:g.reply_to_email,total_recipients:p.length,status:"draft"}).select("id").single();if(b)throw b;const v=p.map(C=>({campaign_id:y.id,contact_id:C.contact_id,email:C.email,name:C.name,status:"pending"}));for(let C=0;C{const x=p.sent_count||0,g=x>0?p.open_count/x*100:0,y=x>0?p.click_count/x*100:0,b=p.sent_at?r2(new Date,new Date(p.sent_at)):0,v=p.status==="sent"&&b>=3&&x>0&&p.open_counta(p.id),children:[e.jsx(ga,{className:"h-3.5 w-3.5 mr-1"})," Details"]}),v&&e.jsxs($,{variant:"outline",size:"sm",onClick:()=>l(p),children:[e.jsx(jR,{className:"h-3.5 w-3.5 mr-1"})," Resend"]})]})]}),p.status==="sent"&&x>0&&e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-3 mt-3",children:[e.jsx(Vre,{icon:e.jsx(Br,{className:"h-3.5 w-3.5"}),label:"Sent",value:x,sub:`of ${p.total_recipients}`}),e.jsx(Vre,{icon:e.jsx(ga,{className:"h-3.5 w-3.5 text-blue-600"}),label:"Opens",value:p.open_count,sub:`${g.toFixed(1)}%`,children:e.jsx(Ki,{value:g,className:"h-1 mt-1"})}),e.jsx(Vre,{icon:e.jsx(uu,{className:"h-3.5 w-3.5 text-purple-600"}),label:"Clicks",value:p.click_count,sub:`${y.toFixed(1)}%`,children:e.jsx(Ki,{value:y,className:"h-1 mt-1"})}),e.jsx(Vre,{icon:e.jsx(wT,{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(Ub,{open:!!r,onOpenChange:p=>!p&&a(null),children:e.jsxs(T1,{className:"w-full sm:max-w-2xl overflow-y-auto",children:[e.jsx(kw,{children:e.jsx(Sw,{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($e,{variant:"default",className:"text-xs",children:Hs(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($e,{variant:"default",className:"text-xs bg-purple-600",children:Hs(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($e,{variant:"outline",className:"text-xs",children:"sent"}),p.status==="pending"&&e.jsx($e,{variant:"secondary",className:"text-xs",children:"queued"}),p.status==="failed"&&e.jsx($e,{variant:"destructive",className:"text-xs",title:p.error_message||"",children:"failed"}),p.status==="suppressed"&&e.jsx($e,{variant:"outline",className:"text-xs",children:"suppressed"})]})]},p.id))})]}):e.jsx("p",{className:"text-sm text-muted-foreground",children:"Loading…"})})]})}),e.jsx(Ll,{open:!!i,onOpenChange:p=>!p&&l(null),children:e.jsxs(yl,{children:[e.jsxs(vl,{children:[e.jsx(_l,{children:"Resend to non-openers?"}),e.jsxs(wl,{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(bl,{children:[e.jsx(jl,{disabled:o,children:"Cancel"}),e.jsx(fl,{onClick:m,disabled:o,children:o?e.jsxs(e.Fragment,{children:[e.jsx(Ht,{className:"h-4 w-4 mr-1 animate-spin"}),"Resending…"]}):e.jsxs(e.Fragment,{children:[e.jsx(jR,{className:"h-4 w-4 mr-1"}),"Resend"]})})]})]})})]})}function Vre({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 QX(){var r;const{data:{session:s}}=await U.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 U.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 ESn(){const{user:s}=_s(),t=Vn(),n=ts(),{data:r=[],isLoading:a}=ht({queryKey:["scheduled-email-campaigns",s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:d,error:u}=await U.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 QX(),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:()=>{ae.success("Schedule cancelled — saved as draft"),n.invalidateQueries({queryKey:["scheduled-email-campaigns"]})},onError:d=>ae.error(d.message)}),o=yt({mutationFn:d=>i("delete",d),onSuccess:()=>{ae.success("Scheduled email deleted"),n.invalidateQueries({queryKey:["scheduled-email-campaigns"]})},onError:d=>ae.error(d.message)}),c=yt({mutationFn:async({id:d,iso:u})=>{const{error:h}=await U.from("email_campaigns").update({scheduled_at:u,status:"scheduled"}).eq("id",d);if(h)throw h;await i("schedule",d)},onSuccess:()=>{ae.success("Send time updated"),n.invalidateQueries({queryKey:["scheduled-email-campaigns"]})},onError:d=>ae.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(_e,{children:e.jsxs(Oe,{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(Hr,{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(TSn,{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 TSn({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 ae.error("Pick a date");const x=new Date(`${Hs(d,"yyyy-MM-dd")}T${h}:00`).toISOString();if(new Date(x).getTime()xm(x.target.value)})]})]}),e.jsxs(kr,{children:[e.jsx($,{variant:"ghost",onClick:()=>c(!1),children:"Cancel"}),e.jsxs($,{onClick:p,disabled:i,children:[i&&e.jsx(Ht,{className:"h-4 w-4 mr-1.5 animate-spin"}),"Save new time"]})]})]})]}),e.jsxs(Ll,{children:[e.jsx(_f,{asChild:!0,children:e.jsxs($,{size:"sm",variant:"outline",disabled:i,children:[e.jsx($d,{className:"h-3.5 w-3.5 mr-1.5"})," Cancel Send"]})}),e.jsxs(yl,{children:[e.jsxs(vl,{children:[e.jsx(_l,{children:"Cancel this scheduled send?"}),e.jsxs(wl,{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(bl,{children:[e.jsx(jl,{children:"Keep scheduled"}),e.jsx(fl,{onClick:n,children:"Cancel send"})]})]})]}),e.jsxs(Ll,{children:[e.jsx(_f,{asChild:!0,children:e.jsxs($,{size:"sm",variant:"ghost",className:"text-destructive hover:text-destructive",disabled:i,children:[e.jsx(Pn,{className:"h-3.5 w-3.5 mr-1.5"})," Delete"]})}),e.jsxs(yl,{children:[e.jsxs(vl,{children:[e.jsx(_l,{children:"Delete this scheduled email?"}),e.jsx(wl,{children:"This permanently removes the scheduled email and all its recipient records. This can't be undone."})]}),e.jsxs(bl,{children:[e.jsx(jl,{children:"Keep"}),e.jsx(fl,{onClick:r,className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Delete permanently"})]})]})]})]})]})})})}function MSn({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 Hre({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:Tt("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(Ja,{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 LSn({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(MSn,{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(Hre,{icon:e.jsx(Fr,{className:"h-3.5 w-3.5"}),label:"Delivered",value:s.toLocaleString(),hint:"All sends completed"}),e.jsx(Hre,{icon:e.jsx(ga,{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(Hre,{icon:e.jsx(uu,{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(Hre,{icon:e.jsx(Hr,{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 ugt=["Gmail","Mass Email","Campaign","Client Portal Invite"],PSn={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 ISn(){const{user:s}=_s(),[t,n]=oc(),{data:r=[],isLoading:a}=K7t(),[i,l]=j.useState(""),[o,c]=j.useState("all"),[d,u]=j.useState("30"),[h,m]=j.useState(!1),[p,x]=j.useState(t.get("tab")==="scheduled"?"scheduled":"sent"),{gmailEmail:g}=ux(),{data:y=0}=ht({queryKey:["scheduled-email-count",s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{count:P}=await U.from("email_campaigns").select("id",{count:"exact",head:!0}).eq("user_id",s.id).eq("status","scheduled");return P||0},refetchInterval:3e4});j.useEffect(()=>{const P=new URLSearchParams(t);p==="scheduled"?P.set("tab","scheduled"):P.delete("tab"),n(P,{replace:!0})},[p]);const b=j.useMemo(()=>Array.from(new Set(r.map(P=>P.contact_id).filter(Boolean))),[r]),{data:v}=ht({queryKey:["sent-emails-contact-names",s==null?void 0:s.id,b.length],enabled:b.length>0,queryFn:async()=>{const{data:P}=await U.from("innercircle_contacts").select("id, first_name, last_name").in("id",b),M=new Map;return(P||[]).forEach(I=>{M.set(I.id,[I.first_name,I.last_name].filter(Boolean).join(" ")||"Contact")}),M}}),N=j.useMemo(()=>{const P=d==="all"?null:Date.now()-parseInt(d)*864e5,M=i.trim().toLowerCase();return r.filter(I=>{if(o!=="all"&&I.channel!==o||P&&new Date(I.sent_at).getTime(){const P={};let M=0,I=0,D=0;return N.forEach(B=>{P[B.channel]=(P[B.channel]||0)+1,(B.channel==="Campaign"||B.channel==="Mass Email")&&(D++,B.opened_at&&M++,B.clicked_at&&I++)}),{byChannel:P,opened:M,clicked:I,trackable:D}},[N]),A=d==="all"?"All time":`Last ${d} days`,T=ugt.map(P=>C.byChannel[P]?`${C.byChannel[P]} ${P}`:null).filter(Boolean).join(" · ");return e.jsx(Ks,{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(Br,{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:()=>x("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(Br,{className:"h-3.5 w-3.5"})," Sent"]}),e.jsxs("button",{onClick:()=>x("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(Hr,{className:"h-3.5 w-3.5"})," Scheduled",y>0&&e.jsx($e,{variant:"secondary",className:"ml-0.5 h-5 min-w-5 px-1.5 text-xs",children:y})]})]}),e.jsxs($,{onClick:()=>m(!0),className:"rounded-full",children:[e.jsx(nn,{className:"h-4 w-4 mr-2"})," Send Email"]})]})]}),e.jsxs(ua,{value:p,onValueChange:P=>x(P),className:"space-y-5",children:[e.jsxs(Jt,{value:"sent",className:"space-y-5 mt-0",children:[e.jsx(LSn,{total:N.length,opened:C.opened,clicked:C.clicked,trackable:C.trackable,scheduled:y,rangeLabel:A,channelSummary:T,onScheduledClick:()=>x("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(Vr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(be,{placeholder:"Search subject, recipient, contact...",value:i,onChange:P=>l(P.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(vs,{value:o,onValueChange:c,children:[e.jsx(gs,{className:"w-[170px] rounded-full h-9",children:e.jsx(bs,{})}),e.jsxs(ys,{children:[e.jsx(Ye,{value:"all",children:"All Channels"}),ugt.map(P=>e.jsx(Ye,{value:P,children:P},P))]})]}),e.jsxs(vs,{value:d,onValueChange:u,children:[e.jsx(gs,{className:"w-[150px] rounded-full h-9",children:e.jsx(bs,{})}),e.jsxs(ys,{children:[e.jsx(Ye,{value:"7",children:"Last 7 days"}),e.jsx(Ye,{value:"30",children:"Last 30 days"}),e.jsx(Ye,{value:"90",children:"Last 90 days"}),e.jsx(Ye,{value:"365",children:"Last year"}),e.jsx(Ye,{value:"all",children:"All time"})]})]})]})]}),e.jsxs("p",{className:"text-xs text-muted-foreground -mt-3 px-1",children:[e.jsx(r5,{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(ASn,{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(_e,{className:"rounded-2xl",children:e.jsxs(Oe,{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(nn,{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(_e,{className:"rounded-2xl overflow-hidden",children:e.jsx(Oe,{className:"p-0",children:e.jsxs("div",{className:"overflow-x-auto",children:[e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{className:"bg-muted/50 text-xs uppercase text-muted-foreground",children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left py-3 px-4 font-medium",children:"Sent"}),e.jsx("th",{className:"text-left py-3 px-4 font-medium",children:"Channel"}),e.jsx("th",{className:"text-left py-3 px-4 font-medium",children:"Subject"}),e.jsx("th",{className:"text-left py-3 px-4 font-medium",children:"Recipient"}),e.jsx("th",{className:"text-left py-3 px-4 font-medium",children:"Contact"}),e.jsx("th",{className:"text-left py-3 px-4 font-medium",children:e.jsx(JN,{children:e.jsxs(Mx,{children:[e.jsxs(Lx,{className:"inline-flex items-center gap-1",children:["Engagement ",e.jsx(r5,{className:"h-3 w-3"})]}),e.jsx(tx,{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(P=>{const M=P.contact_id?v==null?void 0:v.get(P.contact_id):null,I=P.channel==="Campaign"||P.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:Hs(new Date(P.sent_at),"MMM d, yyyy h:mm a")}),e.jsx("td",{className:"py-3 px-4",children:e.jsx($e,{variant:"outline",className:PSn[P.channel],children:P.channel})}),e.jsx("td",{className:"py-3 px-4 max-w-xs truncate font-medium",children:P.subject}),e.jsx("td",{className:"py-3 px-4 text-muted-foreground",children:P.to_email}),e.jsx("td",{className:"py-3 px-4",children:P.contact_id&&M?e.jsx(Wn,{to:`/mission-control/contacts/${P.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($e,{variant:"outline",className:"bg-slate-50 text-slate-700 border-slate-200 gap-1",children:[e.jsx(Fr,{className:"h-3 w-3"})," Delivered"]}),P.opened_at&&e.jsxs($e,{variant:"outline",className:"bg-blue-50 text-blue-700 border-blue-200 gap-1",children:[e.jsx(ga,{className:"h-3 w-3"})," Opened"]}),P.clicked_at&&e.jsxs($e,{variant:"outline",className:"bg-emerald-50 text-emerald-700 border-emerald-200 gap-1",children:[e.jsx(uu,{className:"h-3 w-3"})," Clicked"]})]}):e.jsx("span",{className:"text-xs text-muted-foreground",children:"Not tracked"})})]},P.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(Jt,{value:"scheduled",className:"mt-0",children:e.jsx(ESn,{})})]}),e.jsx(x2,{open:h,onOpenChange:m,gmailEmail:g})]})})}const hgt={Crown:Ng,FileText:Wr,Users:qn,Globe:Gl,Star:Qa,Phone:ya,MessageSquare:Ji,PenTool:kT,Video:Xr,Gift:Co},Gre=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function DSn(){var lt,Mt;const s=Vn(),{user:t}=_s(),{data:n}=Hb(),{data:r}=rAs(),{data:a}=uAs(),{data:i}=T6t(),{data:l}=wee(),{data:o}=nAs(),c=hAs(),d=aAs(),u=oAs(),h=lAs(),m=cAs(),p=dAs(),x=iAs(),[g,y]=j.useState(null),[b,v]=j.useState(!1),[N,C]=j.useState(null),[A,T]=j.useState(""),[P,M]=j.useState(""),[I,D]=j.useState([]),[B,q]=j.useState(null),[W,V]=j.useState(null),[K,Q]=j.useState(null),[J,ce]=j.useState(!1),[ue,ne]=j.useState(""),[ee,le]=j.useState(""),[he,ve]=j.useState(""),[ge,fe]=j.useState(""),je=(Ft,Ts)=>a==null?void 0:a.some(js=>js.plan_id===Ft&&js.relationship_type_id===Ts&&js.active),Ee=Ft=>a==null?void 0:a.find(Ts=>Ts.relationship_type_id===Ft&&Ts.active),Me=async(Ft,Ts)=>{const js=je(Ft,Ts);await c.mutateAsync({planId:Ft,relationshipTypeId:Ts,active:!js})},De=(r==null?void 0:r.filter(Ft=>Ft.active&&!Ft.owner_user_id))||[],ze=(r==null?void 0:r.filter(Ft=>Ft.owner_user_id===(t==null?void 0:t.id)))||[],ke=n==null?void 0:n.find(Ft=>Ft.id===g),Xe=g?Ee(g):null,Se=r==null?void 0:r.find(Ft=>Ft.id===(Xe==null?void 0:Xe.plan_id)),Re=async()=>{if(!A.trim())return;const Ft=await d.mutateAsync({name:A,description:P});Ft&&I.length>0&&await m.mutateAsync({planId:Ft.id,items:I}),Ke()},Ae=async()=>{!A.trim()||!N||(await u.mutateAsync({id:N,name:A,description:P}),await m.mutateAsync({planId:N,items:I}),Ke())},Be=Ft=>{var Ts;C(Ft.id),T(Ft.name),M(Ft.description||""),D(((Ts=Ft.items)==null?void 0:Ts.map(js=>({month_number:js.month_number,action_type_id:js.action_type_id,default_script_id:js.default_script_id||void 0,notes:js.notes||void 0})))||[]),v(!0)},qe=async(Ft,Ts)=>{if(Ft.owner_user_id===(t==null?void 0:t.id)){Be(Ft);return}try{const js=await x.mutateAsync({sourcePlanId:Ft.id,newName:`${Ft.name} (My Copy)`});if(!js)return;await c.mutateAsync({planId:Ft.id,relationshipTypeId:Ts,active:!1}),await c.mutateAsync({planId:js.id,relationshipTypeId:Ts,active:!0}),C(js.id),T(js.name),M(js.description||""),D((Ft.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}))),v(!0)}catch{}},Ke=()=>{v(!1),C(null),T(""),M(""),D([])},Ze=(Ft,Ts)=>{V(Ts)},Ue=(Ft,Ts,js)=>{D(zt=>[...zt.filter(Ds=>Ds.month_number!==Ft),{month_number:Ft,action_type_id:Ts,default_script_id:js}]),q(null),V(null)},et=Ft=>{D(Ts=>Ts.filter(js=>js.month_number!==Ft))},Qe=async()=>{if(!ue.trim()||!ee.trim()||!W)return;const Ft=await p.mutateAsync({actionTypeId:W,title:ue,scriptBody:ee,emailSubject:he||void 0,tone:ge||void 0});Ft&&B!==null&&Ue(B,W,Ft.id),ce(!1),ne(""),le(""),ve(""),fe("")},Ge=W?o==null?void 0:o.filter(Ft=>Ft.action_type_id===W&&Ft.active):[],nt=Ft=>hgt[Ft||"Phone"]||ya,ft=Ft=>hgt[Ft||"Users"]||qn;return e.jsxs(Ks,{title:"Touchpoint Plans",description:"Assign plans to your contact groups",children:[e.jsxs("div",{className:"space-y-6 overflow-x-hidden",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("h1",{className:"text-2xl font-bold",children:"Touchpoint Plans"}),e.jsx("span",{className:"text-[10px] font-semibold uppercase tracking-wide px-1.5 py-0.5 rounded border border-amber-500 text-amber-600 dark:text-amber-400 bg-amber-500/10",children:"Beta"})]}),e.jsxs("div",{className:"flex flex-col sm:flex-row items-start sm:items-center justify-between gap-3",children:[e.jsxs($,{variant:"ghost",size:"sm",onClick:()=>s("/mission-control"),children:[e.jsx(Ic,{className:"h-4 w-4 mr-1"}),"Back"]}),e.jsxs($,{onClick:()=>v(!0),className:"w-full sm:w-auto",children:[e.jsx(sn,{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(Ft=>Ft.active).map(Ft=>{const Ts=ft(Ft.icon),js=(i==null?void 0:i[Ft.id])||0,zt=Ee(Ft.id),Nt=r==null?void 0:r.find(_t=>_t.id===(zt==null?void 0:zt.plan_id)),Ds=g===Ft.id;return e.jsxs("button",{onClick:()=>y(Ft.id),className:` w-full flex items-center gap-3 p-4 rounded-lg border text-left transition-all ${Ds?"border-primary bg-primary/5 ring-2 ring-primary":"hover:bg-accent"} `,children:[e.jsx(Ts,{className:"h-5 w-5 text-muted-foreground"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"font-medium",children:Ft.name}),e.jsxs("div",{className:"text-sm text-muted-foreground",children:[js," contacts"]})]}),Nt?e.jsxs($e,{variant:"secondary",className:"text-xs",children:[e.jsx(Ro,{className:"h-3 w-3 mr-1"}),Nt.name.split(" ")[0]]}):e.jsx($e,{variant:"outline",className:"text-xs text-muted-foreground",children:"No plan"})]},Ft.id)})]}),e.jsx("div",{className:"lg:col-span-2",children:g&&ke?e.jsxs(_e,{children:[e.jsxs(Bt,{children:[e.jsxs(Ut,{className:"flex items-center gap-2",children:[(()=>{const Ft=ft(ke.icon);return e.jsx(Ft,{className:"h-5 w-5"})})(),ke.name," Touchpoint Plan"]}),e.jsxs(vr,{children:["Choose a plan for your ",ke.name," contacts"]})]}),e.jsxs(Oe,{className:"space-y-6",children:[Se&&e.jsxs("div",{className:"p-4 bg-primary/5 rounded-lg border border-primary/20",children:[e.jsxs("div",{className:"flex items-center justify-between mb-3",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"font-medium flex items-center gap-2",children:[e.jsx(Ro,{className:"h-4 w-4 text-green-500"}),"Currently using: ",Se.name]}),Se.description&&e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:Se.description})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs($,{variant:"outline",size:"sm",disabled:x.isPending||c.isPending,onClick:()=>qe(Se,g),children:[e.jsx(kj,{className:"h-4 w-4 mr-1"}),"Edit Steps"]}),e.jsx($,{variant:"outline",size:"sm",onClick:()=>Me(Se.id,g),children:"Disable"})]})]}),Se.items&&Se.items.length>0&&e.jsxs("div",{className:"mt-4",children:[e.jsxs("div",{className:"text-sm font-medium mb-2 flex items-center gap-2",children:[e.jsx(ia,{className:"h-4 w-4"}),"12-Month Schedule"]}),e.jsx("div",{className:"grid grid-cols-4 sm:grid-cols-6 gap-2",children:Gre.map((Ft,Ts)=>{var Ds,_t;const js=((Ds=Se.items)==null?void 0:Ds.filter(Xs=>Xs.month_number===Ts+1))||[],zt=(_t=js[0])==null?void 0:_t.action_type,Nt=zt?nt(zt.icon):null;return e.jsxs("div",{className:` p-2 rounded border text-center ${js.length>0?"bg-primary/10 border-primary":"bg-muted"} `,children:[e.jsx("div",{className:"text-xs text-muted-foreground",children:Ft}),Nt&&e.jsx(Nt,{className:"h-4 w-4 mx-auto mt-1",style:{color:(zt==null?void 0:zt.color)||"#3B82F6"}})]},Ts)})})]})]}),e.jsxs("div",{children:[e.jsx("h4",{className:"font-medium mb-3",children:Se?"Switch to a Different Plan":"Choose a Plan"}),De.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"}),De.map(Ft=>{var js;const Ts=(Se==null?void 0:Se.id)===Ft.id;return e.jsxs("div",{className:` flex items-center justify-between p-3 rounded-lg border ${Ts?"opacity-50":"hover:bg-accent"} `,children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:Ft.name}),e.jsxs("div",{className:"text-sm text-muted-foreground",children:[((js=Ft.items)==null?void 0:js.length)||0," touchpoints/year"]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx($,{size:"sm",variant:"ghost",title:"View plan details",onClick:()=>Q(Ft.id),children:e.jsx(ga,{className:"h-4 w-4"})}),e.jsx($,{size:"sm",variant:"ghost",title:"Duplicate as my own plan",disabled:x.isPending,onClick:()=>{const zt=`${Ft.name} (Copy)`;x.mutate({sourcePlanId:Ft.id,newName:zt})},children:e.jsx(Ca,{className:"h-4 w-4"})}),e.jsx($,{size:"sm",variant:Ts?"outline":"default",disabled:Ts||c.isPending,onClick:()=>Me(Ft.id,g),children:Ts?"Active":"Use This"})]})]},Ft.id)})]}),ze.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsx("div",{className:"text-sm text-muted-foreground",children:"My Custom Plans"}),ze.map(Ft=>{var js;const Ts=(Se==null?void 0:Se.id)===Ft.id;return e.jsxs("div",{className:` flex items-center justify-between p-3 rounded-lg border ${Ts?"opacity-50":"hover:bg-accent"} `,children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:Ft.name}),e.jsxs("div",{className:"text-sm text-muted-foreground",children:[((js=Ft.items)==null?void 0:js.length)||0," touchpoints/year"]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx($,{size:"sm",variant:"ghost",title:"View plan details",onClick:()=>Q(Ft.id),children:e.jsx(ga,{className:"h-4 w-4"})}),e.jsx($,{size:"sm",variant:"ghost",title:"Edit plan",onClick:()=>Be(Ft),children:e.jsx(kj,{className:"h-4 w-4"})}),e.jsx($,{size:"sm",variant:"ghost",title:"Delete plan",onClick:()=>h.mutate(Ft.id),children:e.jsx(Pn,{className:"h-4 w-4 text-destructive"})}),e.jsx($,{size:"sm",variant:Ts?"outline":"default",disabled:Ts||c.isPending,onClick:()=>Me(Ft.id,g),children:Ts?"Active":"Use This"})]})]},Ft.id)})]}),De.length===0&&ze.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(_e,{children:e.jsxs(Oe,{className:"py-12 text-center text-muted-foreground",children:[e.jsx(ia,{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(_e,{className:"bg-muted/50",children:e.jsx(Oe,{className:"py-4",children:e.jsxs("p",{className:"text-sm text-muted-foreground",children:[e.jsx("strong",{children:"How it works:"})," When you assign a plan to a contact group, those contacts will appear in your daily suggested actions based on the plan's schedule."]})})})]}),e.jsx(Os,{open:b,onOpenChange:Ft=>{Ft?v(!0):Ke()},children:e.jsxs(Rs,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsx(Us,{children:e.jsx(zs,{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(se,{htmlFor:"plan-name",children:"Plan Name"}),e.jsx(be,{id:"plan-name",value:A,onChange:Ft=>T(Ft.target.value),placeholder:"e.g., My VIP Plan"})]}),e.jsxs("div",{children:[e.jsx(se,{htmlFor:"plan-description",children:"Description (optional)"}),e.jsx(Is,{id:"plan-description",value:P,onChange:Ft=>M(Ft.target.value),placeholder:"Describe your plan...",rows:2})]})]}),e.jsxs("div",{children:[e.jsx(se,{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:Gre.map((Ft,Ts)=>{const js=Ts+1,zt=I.find(_t=>_t.month_number===js),Nt=zt?l==null?void 0:l.find(_t=>_t.id===zt.action_type_id):null,Ds=Nt?nt(Nt.icon):null;return e.jsxs("div",{className:"relative",children:[e.jsxs("button",{type:"button",onClick:()=>q(B===js?null:js),className:` w-full p-3 rounded-lg border text-center transition-all ${zt?"bg-primary/10 border-primary":"bg-muted hover:bg-accent"} ${B===js?"ring-2 ring-primary":""} `,children:[e.jsx("div",{className:"text-xs text-muted-foreground font-medium",children:Ft}),Ds?e.jsx(Ds,{className:"h-5 w-5 mx-auto mt-1",style:{color:(Nt==null?void 0:Nt.color)||"#3B82F6"}}):e.jsx(sn,{className:"h-5 w-5 mx-auto mt-1 text-muted-foreground/50"})]}),zt&&e.jsx("button",{type:"button",onClick:_t=>{_t.stopPropagation(),et(js)},className:"absolute -top-1 -right-1 p-1 bg-destructive text-destructive-foreground rounded-full",children:e.jsx(pr,{className:"h-3 w-3"})})]},Ts)})}),B!==null&&!W&&e.jsxs("div",{className:"mt-4 p-3 bg-muted rounded-lg",children:[e.jsxs("div",{className:"text-sm font-medium mb-2",children:["Step 1: Select action for ",Gre[B-1],":"]}),e.jsx("div",{className:"flex flex-wrap gap-2",children:l==null?void 0:l.filter(Ft=>Ft.active).map(Ft=>{const Ts=nt(Ft.icon);return e.jsxs("button",{type:"button",onClick:()=>Ze(B,Ft.id),className:"flex items-center gap-2 px-3 py-2 rounded-lg border bg-background hover:bg-accent transition-colors",children:[e.jsx(Ts,{className:"h-4 w-4",style:{color:Ft.color||"#3B82F6"}}),e.jsx("span",{className:"text-sm",children:Ft.name})]},Ft.id)})})]}),B!==null&&W&&e.jsxs("div",{className:"mt-4 p-3 bg-muted rounded-lg space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("div",{className:"text-sm font-medium",children:"Step 2: Select a script (optional)"}),e.jsxs($,{variant:"ghost",size:"sm",onClick:()=>V(null),children:[e.jsx(Ic,{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(B,W),className:"w-full flex items-center gap-3 p-3 rounded-lg border bg-background hover:bg-accent transition-colors text-left",children:e.jsxs("div",{className:"flex-1",children:[e.jsx("div",{className:"font-medium text-sm",children:"No Script"}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Use without a predefined script"})]})}),Ge==null?void 0:Ge.map(Ft=>e.jsx("button",{type:"button",onClick:()=>Ue(B,W,Ft.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:Ft.title}),Ft.tone&&e.jsx($e,{variant:"secondary",className:"text-xs mt-1",children:Ft.tone}),e.jsxs("div",{className:"text-xs text-muted-foreground mt-1 line-clamp-2",children:[Ft.script_body.substring(0,100),"..."]})]})},Ft.id)),e.jsxs("button",{type:"button",onClick:()=>ce(!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(sn,{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(kr,{children:[e.jsx($,{variant:"outline",onClick:Ke,children:"Cancel"}),e.jsxs($,{onClick:N?Ae:Re,disabled:!A.trim()||d.isPending||u.isPending,children:[e.jsx(Jo,{className:"h-4 w-4 mr-2"}),N?"Save Changes":"Create Plan"]})]})]})}),e.jsx(Os,{open:J,onOpenChange:ce,children:e.jsxs(Rs,{className:"max-w-lg",children:[e.jsx(Us,{children:e.jsx(zs,{children:"Create Custom Script"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(se,{htmlFor:"script-title",children:"Script Title"}),e.jsx(be,{id:"script-title",value:ue,onChange:Ft=>ne(Ft.target.value),placeholder:"e.g., Friendly Check-in Call"})]}),e.jsxs("div",{children:[e.jsx(se,{htmlFor:"script-tone",children:"Tone (optional)"}),e.jsxs(vs,{value:ge,onValueChange:fe,children:[e.jsx(gs,{children:e.jsx(bs,{placeholder:"Select tone..."})}),e.jsxs(ys,{children:[e.jsx(Ye,{value:"friendly",children:"Friendly"}),e.jsx(Ye,{value:"professional",children:"Professional"}),e.jsx(Ye,{value:"casual",children:"Casual"}),e.jsx(Ye,{value:"formal",children:"Formal"})]})]})]}),((Mt=(lt=l==null?void 0:l.find(Ft=>Ft.id===W))==null?void 0:lt.name)==null?void 0:Mt.toLowerCase().includes("email"))&&e.jsxs("div",{children:[e.jsx(se,{htmlFor:"script-email-subject",children:"Email Subject"}),e.jsx(be,{id:"script-email-subject",value:he,onChange:Ft=>ve(Ft.target.value),placeholder:"e.g., Quick Hello!"})]}),e.jsxs("div",{children:[e.jsx(se,{htmlFor:"script-body",children:"Script Content"}),e.jsx(Is,{id:"script-body",value:ee,onChange:Ft=>le(Ft.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(kr,{children:[e.jsx($,{variant:"outline",onClick:()=>ce(!1),children:"Cancel"}),e.jsxs($,{onClick:Qe,disabled:!ue.trim()||!ee.trim()||p.isPending,children:[e.jsx(Jo,{className:"h-4 w-4 mr-2"}),"Create & Use Script"]})]})]})}),e.jsx(Os,{open:!!K,onOpenChange:Ft=>{Ft||Q(null)},children:e.jsx(Rs,{className:"max-w-3xl max-h-[90vh] overflow-y-auto",children:(()=>{const Ft=r==null?void 0:r.find(zt=>zt.id===K);if(!Ft)return null;const Ts=Ft.owner_user_id===(t==null?void 0:t.id),js=[...Ft.items||[]].sort((zt,Nt)=>zt.month_number-Nt.month_number);return e.jsxs(e.Fragment,{children:[e.jsxs(Us,{children:[e.jsxs(zs,{className:"flex items-center gap-2",children:[Ft.name,!Ts&&e.jsx($e,{variant:"secondary",children:"Template"})]}),Ft.description&&e.jsx("p",{className:"text-sm text-muted-foreground",children:Ft.description})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"text-sm text-muted-foreground",children:[js.length," touchpoint",js.length!==1?"s":""," per year"]}),e.jsx("div",{className:"space-y-2",children:Array.from({length:12},(zt,Nt)=>Nt+1).map(zt=>{const Nt=js.find(rn=>rn.month_number===zt),Ds=Nt?l==null?void 0:l.find(rn=>rn.id===Nt.action_type_id):null,_t=Nt!=null&&Nt.default_script_id?o==null?void 0:o.find(rn=>rn.id===Nt.default_script_id):null,Xs=Ds?nt(Ds.icon):null;return e.jsxs("div",{className:`p-3 rounded-lg border flex items-start gap-3 ${Nt?"bg-muted/30":"opacity-60"}`,children:[e.jsx("div",{className:"w-16 shrink-0 font-medium text-sm",children:Gre[zt-1]}),Nt&&Ds?e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[Xs&&e.jsx(Xs,{className:"h-4 w-4",style:{color:Ds.color||"#3B82F6"}}),e.jsx("span",{className:"font-medium text-sm",children:Ds.name}),_t&&e.jsx($e,{variant:"outline",className:"text-xs",children:_t.title})]}),_t&&e.jsx("div",{className:"mt-2 text-sm text-muted-foreground whitespace-pre-wrap bg-background p-2 rounded border",children:_t.script_body}),Nt.notes&&e.jsx("div",{className:"mt-1 text-xs text-muted-foreground italic",children:Nt.notes})]}):e.jsx("div",{className:"flex-1 text-sm text-muted-foreground",children:"No touchpoint scheduled"})]},zt)})})]}),e.jsxs(kr,{children:[e.jsx($,{variant:"outline",onClick:()=>Q(null),children:"Close"}),Ts?e.jsxs($,{onClick:()=>{const zt=r==null?void 0:r.find(Nt=>Nt.id===K);zt&&(Q(null),Be(zt))},children:[e.jsx(kj,{className:"h-4 w-4 mr-2"}),"Edit Plan"]}):e.jsxs($,{disabled:x.isPending,onClick:()=>{x.mutate({sourcePlanId:Ft.id,newName:`${Ft.name} (Copy)`}),Q(null)},children:[e.jsx(Ca,{className:"h-4 w-4 mr-2"}),"Duplicate to Edit"]})]})]})})()})})]})}const N8e="https://cma.relevelup.com";function Y7t({open:s,onOpenChange:t,cma:n}){var Q;const{user:r}=_s(),{toast:a}=gi(),[i,l]=j.useState([]),[o,c]=j.useState(null),[d,u]=j.useState(!1),[h,m]=j.useState(""),[p,x]=j.useState(""),[g,y]=j.useState(""),[b,v]=j.useState(!1),[N,C]=j.useState(null),[A,T]=j.useState(!1),[P,M]=j.useState(!1),[I,D]=j.useState(null);j.useEffect(()=>{!s||!r||(async()=>{var ve;const[J,ce,ue,ne,ee]=await Promise.all([U.from("innercircle_contacts").select("id, first_name, last_name, email").eq("owner_user_id",r.id).not("email","is",null).order("first_name"),U.from("profiles").select("name, email, phone, brokerage_name, avatar_url, email_signature").eq("id",r.id).maybeSingle(),U.from("gmail_integrations").select("id, is_active").eq("user_id",r.id).maybeSingle(),U.from("ses_verified_emails").select("email, status").eq("user_id",r.id).eq("status","Success").limit(1),U.from("mass_email_settings").select("*").eq("user_id",r.id).maybeSingle()]),le=(J.data||[]).filter(ge=>ge.email&&ge.email.includes("@"));l(le),C(ce.data||null),T(!!((ve=ue.data)!=null&&ve.is_active)),M(!!(ne.data&&ne.data.length>0)),D(ee.data||null);const he=n.contact_id?le.find(ge=>ge.id===n.contact_id):null;he&&(c(he),m(he.email))})()},[s,r,n.contact_id]),j.useEffect(()=>{var ne;if(!s)return;const J=((ne=n.subject)==null?void 0:ne.address)||"your home",ce=((N==null?void 0:N.name)||"").split(" ")[0]||"your agent",ue=(o==null?void 0:o.first_name)||"there";x(`Your home value report for ${J}`),y(`Hi ${ue}, I put together a fresh market analysis for ${J}. 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)||ce}`)},[s,o==null?void 0:o.id,N==null?void 0:N.name,(Q=n.subject)==null?void 0:Q.address]);const B=j.useMemo(()=>A?"Gmail (your inbox)":P?"Amazon SES":null,[A,P]),q=!!(h.trim()&&p.trim()&&g.trim()&&B&&!b),W=J=>{c(J),m(J.email||""),u(!1)},V=J=>{const ce=`${N8e}/${n.share_token}?e=${J}`,ee=g.replace(/&/g,"&").replace(//g,">").replace(/\{\{cma_link\}\}/g,`View Your Home Value Report`).split(/\n{2,}/).map(ve=>`

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

`).join(""),le=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?``:""}
`,he=``;return`
${ee} ${le}
Prepared with LevelUp · ReLevelUp Real Estate
${he}
`},K=async()=>{if(!(!r||!q)){v(!0);try{const{data:J,error:ce}=await U.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(ce)throw ce;const ue=V(J.id);if(A){const{data:ne,error:ee}=await U.functions.invoke("gmail-send",{body:{to:h.trim(),subject:p.trim(),body:ue}});if(ee)throw ee;if(!(ne!=null&&ne.success))throw new Error((ne==null?void 0:ne.error)||"Gmail send failed")}else if(P){const ne=(I==null?void 0:I.display_name)||(N==null?void 0:N.name)||"ReLevelUp",ee=`${ne.toLowerCase().replace(/[^a-z]/g,".").replace(/^\.+|\.+$/g,"")||"noreply"}@send.relevelup.com`,{data:le,error:he}=await U.functions.invoke("ses-send-campaign",{body:{action:"test_send",to:h.trim(),from_email:`${ne} <${ee}>`,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(he)throw he;if(!(le!=null&&le.success))throw new Error((le==null?void 0:le.error)||"SES send failed")}o&&!n.contact_id&&await U.from("cmas").update({contact_id:o.id}).eq("id",n.id),a({title:"CMA sent",description:`Delivered to ${h.trim()}`}),t(!1)}catch(J){console.error("Send CMA error:",J),a({title:"Send failed",description:J.message||"Could not send email",variant:"destructive"})}finally{v(!1)}}};return e.jsx(Os,{open:s,onOpenChange:t,children:e.jsxs(Rs,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsx(Us,{children:e.jsxs(zs,{className:"flex items-center gap-2",children:[e.jsx(nn,{className:"w-5 h-5"}),"Send CMA to contact"]})}),B?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:B})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Contact"}),e.jsxs(Sc,{open:d,onOpenChange:u,children:[e.jsx(Cc,{asChild:!0,children:e.jsxs($,{variant:"outline",role:"combobox",className:"w-full justify-between font-normal",children:[o?`${o.first_name} ${o.last_name||""}`.trim():"Pick a contact (optional)",e.jsx(sw,{className:"w-4 h-4 opacity-50"})]})}),e.jsx(xc,{className:"w-[--radix-popover-trigger-width] p-0",align:"start",children:e.jsxs(pw,{children:[e.jsx(fw,{placeholder:"Search contacts…"}),e.jsxs(xw,{children:[e.jsx(gw,{children:"No contacts with email found."}),e.jsx($b,{children:i.map(J=>e.jsxs(iv,{value:`${J.first_name} ${J.last_name||""} ${J.email}`,onSelect:()=>W(J),children:[e.jsx(oa,{className:Tt("w-4 h-4 mr-2",(o==null?void 0:o.id)===J.id?"opacity-100":"opacity-0")}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"font-medium",children:[J.first_name," ",J.last_name||""]}),e.jsx("div",{className:"text-xs text-muted-foreground truncate",children:J.email})]})]},J.id))})]})]})})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"To email"}),e.jsx(be,{type:"email",value:h,onChange:J=>m(J.target.value),placeholder:"client@example.com"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Subject"}),e.jsx(be,{value:p,onChange:J=>x(J.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Message"}),e.jsx(Is,{rows:10,value:g,onChange:J=>y(J.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(Tr,{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:`${N8e}/${n.share_token}`,target:"_blank",rel:"noreferrer",children:`${N8e}/${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(kr,{children:[e.jsx($,{variant:"ghost",onClick:()=>t(!1),children:"Cancel"}),e.jsxs($,{onClick:K,disabled:!q,children:[b?e.jsx(Ht,{className:"w-4 h-4 mr-2 animate-spin"}):e.jsx(Br,{className:"w-4 h-4 mr-2"}),"Send CMA"]})]})]})})}function RSn(s){const{user:t}=_s(),n=ts(),{data:r}=ht({queryKey:["lead-site-upgrade-requests",t==null?void 0:t.id],enabled:!!t,queryFn:async()=>{const{data:l,error:o}=await U.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 U.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]}),ae.success("Request sent — we'll reach out about upgrading your site.")},onError:l=>ae.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 OSn="free_luxury",FSn="free_beta";function Z7t(s){const t=s==null?void 0:s.planTier;return t===OSn||t===FSn}const zSn={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 BSn({featureKey:s,siteId:t,bullets:n}){const r=zSn[s],{requestUpgrade:a,hasRequested:i,isSending:l}=RSn(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(Ad,{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(dn,{className:"h-4 w-4 mt-0.5 text-amber-500 shrink-0"}),c]},c))}):null,e.jsx($,{className:"mt-5",disabled:o||l,onClick:()=>a.mutate({featureKey:s}),children:o?e.jsxs(e.Fragment,{children:[e.jsx(oa,{className:"h-4 w-4 mr-2"})," Upgrade requested"]}):"Request this upgrade"})]})]})})}function $Sn({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=sSn(),m=q7t(),{toast:p}=gi(),[x,g]=j.useState([]),y=async()=>{var N;g([]);try{const C=await h.mutateAsync({address:r,city:i,state:o,zip:d});g(C.matches||[]),(N=C.matches)!=null&&N.length||p({title:"No MLS match",description:'Use "Create from manual entry" below.'})}catch(C){p({title:"Search failed",description:C.message,variant:"destructive"})}},b=async N=>{const C=await m.mutateAsync({subject:N});n(!1),s(C.id)},v=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(Os,{open:t,onOpenChange:n,children:[e.jsx(Ko,{asChild:!0,children:e.jsxs($,{children:[e.jsx(sn,{className:"w-4 h-4 mr-2"}),"New CMA"]})}),e.jsxs(Rs,{className:"max-w-2xl",children:[e.jsx(Us,{children:e.jsx(zs,{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(be,{className:"md:col-span-2",placeholder:"Street address",value:r,onChange:N=>a(N.target.value)}),e.jsx(be,{placeholder:"City",value:i,onChange:N=>l(N.target.value)}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(be,{placeholder:"ST",maxLength:2,value:o,onChange:N=>c(N.target.value.toUpperCase())}),e.jsx(be,{placeholder:"ZIP",value:d,onChange:N=>u(N.target.value)})]})]}),e.jsxs($,{onClick:y,disabled:!r||h.isPending,className:"w-full",children:[h.isPending?e.jsx(Ht,{className:"w-4 h-4 mr-2 animate-spin"}):e.jsx(Vr,{className:"w-4 h-4 mr-2"}),"Find in MLS"]}),x.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:[x.length," match(es) — pick the subject property:"]}),x.map((N,C)=>{var A;return e.jsxs("button",{onClick:()=>b(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]})]},C)})]}),e.jsx("div",{className:"border-t pt-3",children:e.jsxs($,{variant:"outline",onClick:v,disabled:m.isPending,className:"w-full",children:[e.jsx(sa,{className:"w-4 h-4 mr-2"}),"Create from manual entry"]})})]})]})]})}function USn(){const{data:s,isLoading:t}=Xkn(),n=tSn(),r=Vn(),{toast:a}=gi(),[i,l]=j.useState(null),{isFreePlan:o,leadSite:c}=Mf();return o?e.jsx(Ks,{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(Wr,{className:"w-7 h-7"})," CMAs"]}),e.jsx(BSn,{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(Ks,{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(Wr,{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($Sn,{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(_e,{className:"hover:shadow-md transition",children:e.jsxs(Oe,{className:"p-4 flex flex-wrap items-center gap-3 justify-between",children:[e.jsxs("div",{className:"flex-1 min-w-[200px]",children:[e.jsx("div",{className:"font-semibold",children:d.title||((u=d.subject)==null?void 0:u.address)||"Untitled CMA"}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:[(h=d.subject)==null?void 0:h.city,", ",(m=d.subject)==null?void 0:m.state," · ",d.buyer_mode?"Buyer":"Seller"," ·"," ",e.jsx($e,{variant:d.status==="shared"?"default":"secondary",className:"ml-1",children:d.status})]}),d.price_likely?e.jsxs("div",{className:"text-sm mt-1",children:["Suggested: ",e.jsxs("span",{className:"font-medium",children:["$",d.price_likely.toLocaleString()]}),d.price_low&&d.price_high?e.jsxs("span",{className:"text-muted-foreground",children:[" · $",d.price_low.toLocaleString(),"–$",d.price_high.toLocaleString()]}):null]}):null]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx($,{variant:"outline",size:"sm",onClick:()=>r(`/mission-control/cma/${d.id}`),children:"Open"}),d.status==="shared"&&e.jsxs(e.Fragment,{children:[e.jsx($,{variant:"ghost",size:"sm",onClick:()=>{const p=`https://cma.relevelup.com/${d.share_token}`;navigator.clipboard.writeText(p),a({title:"Share link copied"})},children:e.jsx(Tr,{className:"w-4 h-4"})}),e.jsxs($,{variant:"secondary",size:"sm",onClick:()=>l(d),children:[e.jsx(nn,{className:"w-4 h-4 mr-1"}),"Send"]})]}),e.jsx($,{variant:"ghost",size:"sm",onClick:async()=>{await Yi("Delete this CMA?")&&n.mutate(d.id)},children:e.jsx(Pn,{className:"w-4 h-4"})})]})]})},d.id)})}):e.jsx(_e,{children:e.jsx(Oe,{className:"py-12 text-center text-muted-foreground",children:"No CMAs yet. Start one above."})}),i&&e.jsx(Y7t,{open:!!i,onOpenChange:d=>!d&&l(null),cma:i})]})})}function qSn(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 mgt(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 VSn({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 U.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;Wc.accessToken=o;const u=new Wc.Map({container:a.current,style:"mapbox://styles/mapbox/light-v11",center:[d.lng,d.lat],zoom:12});return u.addControl(new Wc.NavigationControl({showCompass:!1}),"top-right"),u.on("load",()=>{u.addSource("radius",{type:"geojson",data:mgt(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(mgt(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 Wc.Marker({element:h}).setLngLat([d.lng,d.lat]).setPopup(new Wc.Popup({offset:18}).setHTML(`Subject
${s.address??""}`)).addTo(u);l.current.push(m);const p=new Wc.LngLatBounds;p.extend([d.lng,d.lat]),t.forEach((y,b)=>{const v=Number(y.latitude),N=Number(y.longitude);if(!Number.isFinite(v)||!Number.isFinite(N))return;const C=qSn(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: ${C}; 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(b)),A.appendChild(T);const P=y.soldPrice||y.price,M=new Wc.Popup({offset:14}).setHTML(`
${y.address??""}
${y.status??""}`+(P?` · $${P.toLocaleString()}`:"")+"
"),I=new Wc.Marker({element:A}).setLngLat([N,v]).setPopup(M).addTo(u);l.current.push(I),p.extend([N,v])});const g=n*1.60934/110.574;p.extend([d.lng,d.lat+g]),p.extend([d.lng,d.lat-g]);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 eb=null;function HSn(){if(eb)return eb;try{const s=document.createElement("canvas"),t=s.getContext("webgl2")||s.getContext("webgl");if(!t)return eb={canRunVirtualBg:!1,reason:"WebGL is not supported on this device"},eb;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 eb={canRunVirtualBg:!1,reason:"Your device uses a software renderer which may cause lag",renderer:r},eb;const o=performance;return o.memory&&o.memory.jsHeapSizeLimit<256*1024*1024?(eb={canRunVirtualBg:!1,reason:"Limited device memory detected",renderer:r},eb):navigator.hardwareConcurrency&&navigator.hardwareConcurrency<2?(eb={canRunVirtualBg:!1,reason:"Single-core device detected — virtual backgrounds may cause lag",renderer:r},eb):(eb={canRunVirtualBg:!0,renderer:r},eb)}catch{return eb={canRunVirtualBg:!0},eb}}const GSn=[{type:"none",label:"Off"},{type:"blur",label:"Blur"}];function WSn({value:s,onChange:t,isLoading:n=!1,disabled:r=!1,className:a}){const i=j.useRef(null),[l,o]=j.useState(!1),[c]=j.useState(()=>HSn()),d=!c.canRunVirtualBg,{data:u=[],refetch:h}=ht({queryKey:["video-backgrounds"],queryFn:async()=>{const{data:{user:y}}=await U.auth.getUser();if(!y)return[];const{data:b,error:v}=await U.from("video_backgrounds").select("*").eq("is_active",!0).order("sort_order",{ascending:!0});return v?(console.error("Failed to load backgrounds:",v),[]):b||[]}}),m=u.map(y=>({type:"image",label:y.name,imageUrl:y.image_url,thumbnail:y.thumbnail_url||y.image_url})),p=[...GSn,...m],x=y=>y.type!==s.type?!1:y.type==="image"?y.imageUrl===s.imageUrl:!0,g=async y=>{var v;const b=(v=y.target.files)==null?void 0:v[0];if(b){if(!b.type.startsWith("image/")){ae.error("Please select an image file");return}if(b.size>5*1024*1024){ae.error("Image must be under 5MB");return}o(!0);try{const{data:{user:N}}=await U.auth.getUser();if(!N)throw new Error("Not authenticated");const C=b.name.split(".").pop()||"jpg",A=`${N.id}/${crypto.randomUUID()}.${C}`,{error:T}=await U.storage.from("video-backgrounds").upload(A,b,{contentType:b.type});if(T)throw T;const{data:P}=U.storage.from("video-backgrounds").getPublicUrl(A),M=P.publicUrl,{error:I}=await U.from("video_backgrounds").insert({name:b.name.replace(/\.[^.]+$/,""),image_url:M,thumbnail_url:M,category:"custom",is_stock:!1,user_id:N.id});if(I)throw I;await h(),t({type:"image",imageUrl:M,blurRadius:15}),ae.success("Background uploaded!")}catch(N){console.error("Upload error:",N),ae.error("Failed to upload background")}finally{o(!1),i.current&&(i.current.value="")}}};return e.jsxs("div",{className:Tt("flex flex-col gap-1",a),children:[d&&e.jsxs("div",{className:"flex items-center gap-1.5 text-xs text-amber-600 bg-amber-50 dark:bg-amber-950/30 dark:text-amber-400 rounded px-2 py-1",children:[e.jsx(mc,{className:"h-3 w-3 flex-shrink-0"}),e.jsx("span",{children:c.reason||"Virtual backgrounds may cause lag on this device"})]}),e.jsxs("div",{className:"flex items-center gap-2 overflow-x-auto py-2 px-1 scrollbar-none",children:[e.jsx("span",{className:"text-xs text-muted-foreground whitespace-nowrap mr-1 font-medium",children:"Background:"}),n&&e.jsxs("div",{className:"flex items-center gap-1 text-xs text-muted-foreground",children:[e.jsx(Ht,{className:"h-3 w-3 animate-spin"}),e.jsx("span",{children:"Loading…"})]}),p.map((y,b)=>{const v=x(y);return e.jsxs("button",{type:"button",disabled:r,onClick:()=>t({type:y.type,imageUrl:y.imageUrl,blurRadius:15}),className:Tt("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",v?"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:[y.type==="none"&&e.jsx(fz,{className:"h-4 w-4 text-muted-foreground"}),y.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"})}),y.type==="image"&&y.thumbnail&&e.jsx("img",{src:y.thumbnail,alt:y.label,className:"w-full h-full object-cover"})]}),e.jsx("span",{className:"text-[10px] text-muted-foreground truncate max-w-14",children:y.label})]},`${y.type}-${y.imageUrl||b}`)}),e.jsxs("button",{type:"button",disabled:r||l,onClick:()=>{var y;return(y=i.current)==null?void 0:y.click()},className:Tt("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(Ht,{className:"h-4 w-4 animate-spin text-muted-foreground"}):e.jsx(sn,{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:g}),e.jsxs("button",{type:"button",disabled:r,onClick:()=>t({...s,mirror:!s.mirror}),className:Tt("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(SK,{className:"h-4 w-4 text-muted-foreground"})}),e.jsx("span",{className:"text-[10px] text-muted-foreground",children:"Mirror"})]})]})]})}var $U=typeof self<"u"?self:{};function X7t(s,t){e:{for(var n=["CLOSURE_FLAGS"],r=$U,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 J7t(s){$U.setTimeout(()=>{throw s},0)}var iBe,XSn=X7t(610401301,!1),fgt=X7t(748402147,!0);function xgt(){var s=$U.navigator;return s&&(s=s.userAgent)?s:""}const ggt=$U.navigator;function KEe(s){return KEe[" "](s),s}iBe=ggt&&ggt.userAgentData||null,KEe[" "]=function(){};const e9t={};let TW=null;function QSn(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 t9t(){if(!TW){TW={};var s="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789".split(""),t=["+/=","+/","-_=","-_.","-_"];for(let n=0;n<5;n++){const r=s.concat(t[n].split(""));e9t[n]=r;for(let a=0;a0)&&(xgt().indexOf("Trident")!=-1||xgt().indexOf("MSIE")!=-1))&&typeof btoa=="function";const ygt=/[-_.]/g,e5n={"-":"+",_:"/",".":"="};function t5n(s){return e5n[s]||""}function n9t(s){if(!s9t)return QSn(s);s=ygt.test(s)?s.replace(ygt,t5n):s,s=atob(s);const t=new Uint8Array(s.length);for(let n=0;n=t||(n[s]=r+1,a9t(s=Error(),"incident"),J7t(s))}}function hV(){return typeof BigInt=="function"}var mV=typeof Symbol=="function"&&typeof Symbol()=="symbol";function z5(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 r5n=z5("jas",void 0,!0),vgt=z5(void 0,"0di"),EG=z5(void 0,"1oa"),cw=z5(void 0,Symbol()),a5n=z5(void 0,"0ub"),i5n=z5(void 0,"0ubs"),lBe=z5(void 0,"0ubsb"),o5n=z5(void 0,"0actk"),VU=z5("m_m","Pa",!0),bgt=z5();const i9t={Ga:{value:0,configurable:!0,writable:!0,enumerable:!1}},o9t=Object.defineProperties,Ao=mV?r5n:"Ga";var mF;const _gt=[];function Qee(s,t){mV||Ao in s||o9t(s,i9t),s[Ao]|=t}function Mg(s,t){mV||Ao in s||o9t(s,i9t),s[Ao]=t}function Jee(s){return Qee(s,34),s}function JX(s){return Qee(s,8192),s}Mg(_gt,7),mF=Object.freeze(_gt);var HU={};function yw(s,t){return t===void 0?s.h!==TO&&!!(2&(0|s.v[Ao])):!!(2&t)&&s.h!==TO}const TO={};function DYe(s,t){if(s!=null){if(typeof s=="string")s=s?new x5(s,UU):EO();else if(s.constructor!==x5)if(PYe(s))s=s.length?new x5(new Uint8Array(s),UU):EO();else{if(!t)throw Error();s=void 0}}return s}let wgt=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 l5n=Object.freeze({});function l9t(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"),jgt=YEe(s=>typeof s=="string"),d5n=YEe(s=>typeof s=="boolean"),ZEe=typeof $U.BigInt=="function"&&typeof $U.BigInt(0)=="bigint";function dw(s){var t=s;if(jgt(t)){if(!/^\s*(?:-?[1-9]\d*|0)?\s*$/.test(t))throw Error(String(t))}else if(c5n(t)&&!Number.isSafeInteger(t))throw Error(String(t));return ZEe?BigInt(s):s=d5n(s)?s?"1":"0":jgt(s)?s.trim()||"0":String(s)}var cBe=YEe(s=>ZEe?s>=h5n&&s<=p5n:s[0]==="-"?Ngt(s,u5n):Ngt(s,m5n));const u5n=Number.MIN_SAFE_INTEGER.toString(),h5n=ZEe?BigInt(Number.MIN_SAFE_INTEGER):void 0,m5n=Number.MAX_SAFE_INTEGER.toString(),p5n=ZEe?BigInt(Number.MAX_SAFE_INTEGER):void 0;function Ngt(s,t){if(s.length>t.length)return!1;if(s.lengtha)return!1;if(r>>0;Ep=t,Ax=(s-t)/4294967296>>>0}function GU(s){if(s<0){kgt(-s);const[t,n]=FYe(Ep,Ax);Ep=t>>>0,Ax=n>>>0}else kgt(s)}function RYe(s){const t=x5n||(x5n=new DataView(new ArrayBuffer(8)));t.setFloat32(0,+s,!0),Ax=0,Ep=t.getUint32(0,!0)}function d9t(s,t){const n=4294967296*t+(s>>>0);return Number.isSafeInteger(n)?n:eQ(s,t)}function g5n(s,t){return dw(hV()?BigInt.asUintN(64,(BigInt(t>>>0)<>>0)):eQ(s,t))}function u9t(s,t){return hV()?dw(BigInt.asIntN(64,(BigInt.asUintN(32,BigInt(t))<>>=0,(t>>>=0)<=2097151)var n=""+(4294967296*t+s);else hV()?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+Sgt(n)+Sgt(s));return n}function Sgt(s){return s=String(s),"0000000".slice(s.length)+s}function OYe(s,t){if(2147483648&t)if(hV())s=""+(BigInt(0|t)<>>0));else{const[n,r]=FYe(s,t);s="-"+eQ(n,r)}else s=eQ(s,t);return s}function XEe(s){if(s.length<16)GU(Number(s));else if(hV())s=BigInt(s),Ep=Number(s&BigInt(4294967295))>>>0,Ax=Number(s>>BigInt(32)&BigInt(4294967295));else{const t=+(s[0]==="-");Ax=Ep=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));Ax*=1e6,Ep=1e6*Ep+i,Ep>=4294967296&&(Ax+=Math.trunc(Ep/4294967296),Ax>>>=0,Ep>>>=0)}if(t){const[r,a]=FYe(Ep,Ax);Ep=r,Ax=a}}}function FYe(s,t){return t=~t,s?s=1+~s:t+=1,[s,t]}function UN(s){return Array.prototype.slice.call(s)}const ete=typeof BigInt=="function"?BigInt.asIntN:void 0,y5n=typeof BigInt=="function"?BigInt.asUintN:void 0,MO=Number.isSafeInteger,QEe=Number.isFinite,WU=Math.trunc,v5n=dw(0);function MW(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 HS(s){return s==null||typeof s=="number"?s:s==="NaN"||s==="Infinity"||s==="-Infinity"?Number(s):void 0}function tQ(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 h9t(s){return s==null||typeof s=="boolean"?s:typeof s=="number"?!!s:void 0}const b5n=/^-?([1-9][0-9]*|0)(\.[0-9]+)?$/;function tte(s){switch(typeof s){case"bigint":return!0;case"number":return QEe(s);case"string":return b5n.test(s);default:return!1}}function fV(s){if(s==null)return s;if(typeof s=="string"&&s)s=+s;else if(typeof s!="number")return;return QEe(s)?0|s:void 0}function m9t(s){if(s==null)return s;if(typeof s=="string"&&s)s=+s;else if(typeof s!="number")return;return QEe(s)?s>>>0:void 0}function p9t(s){const t=s.length;return(s[0]==="-"?t<20||t===20&&s<="-9223372036854775808":t<19||t===19&&s<="9223372036854775807")?s:(XEe(s),OYe(Ep,Ax))}function zYe(s){if(s=WU(s),!MO(s)){GU(s);var t=Ep,n=Ax;(s=2147483648&n)&&(n=~n>>>0,(t=1+~t>>>0)==0&&(n=n+1>>>0)),s=typeof(t=d9t(t,n))=="number"?s?-t:t:s?"-"+t:t}return s}function f9t(s){var t=WU(Number(s));return MO(t)?String(t):((t=s.indexOf("."))!==-1&&(s=s.substring(0,t)),p9t(s))}function x9t(s){var t=WU(Number(s));return MO(t)?dw(t):((t=s.indexOf("."))!==-1&&(s=s.substring(0,t)),hV()?dw(ete(64,BigInt(s))):dw(p9t(s)))}function g9t(s){return MO(s)?s=dw(zYe(s)):(s=WU(s),MO(s)?s=String(s):(GU(s),s=OYe(Ep,Ax)),s=dw(s)),s}function p4e(s){const t=typeof s;return s==null?s:t==="bigint"?dw(ete(64,s)):tte(s)?t==="string"?x9t(s):g9t(s):void 0}function y9t(s){if(typeof s!="string")throw Error();return s}function ste(s){if(s!=null&&typeof s!="string")throw Error();return s}function _y(s){return s==null||typeof s=="string"?s:void 0}function BYe(s,t,n,r){return s!=null&&s[VU]===HU?s:Array.isArray(s)?((r=(n=0|s[Ao])|32&r|2&r)!==n&&Mg(s,r),new t(s)):(n?2&r?((s=t[vgt])||(Jee((s=new t).v),s=t[vgt]=s),t=s):t=new t:t=void 0,t)}function _5n(s,t,n){if(t)e:{if(!tte(t=s))throw oBe("int64");switch(typeof t){case"string":t=x9t(t);break e;case"bigint":t=dw(ete(64,t));break e;default:t=g9t(t)}}else t=p4e(s);return(s=t)==null?n?v5n:void 0:s}const w5n={};let j5n=function(){try{return KEe(new class extends Map{constructor(){super()}}),!1}catch{return!0}}(),S8e=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 N5n=j5n?(Object.setPrototypeOf(S8e.prototype,Map.prototype),Object.defineProperties(S8e.prototype,{size:{value:0,configurable:!0,enumerable:!0,writable:!0}}),S8e):class extends Map{constructor(){super()}};function Cgt(s){return s}function C8e(s){if(2&s.J)throw Error("Cannot mutate an immutable Map")}var pC=class extends N5n{constructor(s,t,n=Cgt,r=Cgt){super(),this.J=0|s[Ao],this.K=t,this.S=n,this.fa=this.K?k5n:r;for(let a=0;a{s.call(t,a.get(r),r,a)}):super.forEach(s,t)}set(s,t){return C8e(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 k5n(s,t,n,r,a,i){return s=BYe(s,r,n,i),a&&(s=UYe(s)),s}function S5n(s){return[s,this.get(s)]}let C5n;function Agt(){return C5n||(C5n=new pC(Jee([]),void 0,void 0,void 0,w5n))}function JEe(s){return cw?s[cw]:void 0}function f4e(s,t){for(const n in s)!isNaN(n)&&t(s,+n,s[n])}pC.prototype.toJSON=void 0;var dBe=class{};const A5n={Ka:!0};function E5n(s,t){t<100||qU(i5n,1)}function eTe(s,t,n,r){const a=r!==void 0;r=!!r;var i,l=cw;!a&&mV&&l&&(i=s[l])&&f4e(i,E5n),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 x=m-h;(t??(t={}))[x]=p}else l[m]=p}if(c)for(let p in c){if((o=c[p])==null||(o=n(o,r))==null)continue;let x;m=+p,u&&!Number.isNaN(m)&&(x=m+h){x[y]=UN(b)}),x.da=p.da,x}(s)),l}function T5n(s){return s[0]=sQ(s[0]),s[1]=sQ(s[1]),s}function sQ(s){switch(typeof s){case"number":return Number.isFinite(s)?s:""+s;case"bigint":return cBe(s)?Number(s):""+s;case"boolean":return s?1:0;case"object":if(Array.isArray(s)){var t=0|s[Ao];return s.length===0&&1&t?void 0:eTe(s,t,sQ)}if(s!=null&&s[VU]===HU)return v9t(s);if(s instanceof x5){if((t=s.g)==null)s="";else if(typeof t=="string")s=t;else{if(s9t){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 pC?s=s.size!==0?s.V(T5n):void 0:void 0}return s}let M5n,L5n;function v9t(s){return eTe(s=s.v,0|s[Ao],sQ)}function qR(s,t){return b9t(s,t[0],t[1])}function b9t(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[Ao],fgt&&1&a)throw Error("rfarr");if(2048&a&&!(2&a)&&function(){if(fgt)throw Error("carr");qU(o5n,5)}(),256&a)throw Error("farr");if(64&a)return(a|r)!==a&&Mg(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 Mg(s,64|a|r),s}function P5n(s,t){if(typeof s!="object")return s;if(Array.isArray(s)){var n=0|s[Ao];return s.length===0&&1&n?void 0:Egt(s,n,t)}if(s!=null&&s[VU]===HU)return Tgt(s);if(s instanceof pC){if(2&(t=s.J))return s;if(!s.size)return;if(n=Jee(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 oh(s,t,n,r){yV(s),Ag(s=s.v,0|s[Ao],t,n,r)}function Ag(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[Ao]))>>14&1023||536870912)?r!=null&&(s[l+(a?0:-1)]={[n]:r}):s[i]=r),t)}function V8(){return l5n===void 0?2:4}function H8(s,t,n,r,a){let i=s.v,l=0|i[Ao];r=yw(s,l)?1:r,a=!!a||r===3,r===2&&gV(s)&&(i=s.v,l=0|i[Ao]);let o=(s=VYe(i,t))===mF?7:0|s[Ao],c=HYe(o,l);var d=!(4&c);if(d){4&c&&(s=UN(s),o=0,c=HR(c,l),l=Ag(i,l,t,s));let u=0,h=0;for(;u{const o=BYe(l,n,!1,t);return i=o!==l&&o!=null,o}))!=null)return i&&!yw(r)&&pF(s,t),r}function Qd(s,t,n,r){let a=s.v,i=0|a[Ao];if((t=S9t(a,i,t,n,r))==null)return t;if(i=0|a[Ao],!yw(s,i)){const l=UYe(t);l!==t&&(gV(s)&&(a=s.v,i=0|a[Ao]),i=Ag(a,i,n,t=l,r),pF(a,i))}return t}function C9t(s,t,n,r,a,i,l,o){var c=yw(s,n);i=c?1:i,l=!!l||i===3,c=o&&!c,(i===2||c)&&gV(s)&&(n=0|(t=s.v)[Ao]);var d=(s=VYe(t,a))===mF?7:0|s[Ao],u=HYe(d,n);if(o=!(4&u)){var h=s,m=n;const p=!!(2&u);p&&(m|=2);let x=!p,g=!0,y=0,b=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 QYe(s){let t=0,n=s.g;const r=n+10,a=s.h;for(;n>>0}function g4e(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],GR(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 I5n(s){return c6(s)}function GR(s,t){if(s.g=t,t>s.l)throw Error()}function E9t(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 T9t(s,t){if(t==0)return EO();var n=E9t(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):f5n?s.slice(n,t):new Uint8Array(s.subarray(n,t))),n.length==0?EO():new x5(n,UU)}var Mgt=[];function M9t(s,t,n,r){if(y4e.length){const a=y4e.pop();return a.o(r),a.g.init(s,t,n,r),a}return new D5n(s,t,n,r)}function L9t(s){s.g.clear(),s.l=-1,s.h=-1,y4e.length<100&&y4e.push(s)}function P9t(s){var t=s.g;if(t.g==t.l)return!1;s.m=s.g.g;var n=C5(s.g);if(t=n>>>3,!((n&=7)>=0&&n<=5)||t<1)throw Error();return s.l=t,s.h=n,!0}function H2e(s){switch(s.h){case 0:s.h!=0?H2e(s):QYe(s.g);break;case 1:GR(s=s.g,s.g+8);break;case 2:if(s.h!=2)H2e(s);else{var t=C5(s.g);GR(s=s.g,s.g+t)}break;case 5:GR(s=s.g,s.g+4);break;case 3:for(t=s.l;;){if(!P9t(s))throw Error();if(s.h==4){if(s.l!=t)throw Error();break}H2e(s)}break;default:throw Error()}}function nte(s,t,n){const r=s.g.l;var a=C5(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 JYe(s){var t=C5(s.g),n=E9t(s=s.g,t);if(s=s.h,KSn){var r,a=s;(r=k8e)||(r=k8e=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(Wre===void 0){try{r.decode(new Uint8Array([128]))}catch{}try{r.decode(new Uint8Array([97])),Wre=!0}catch{Wre=!1}}throw!Wre&&(k8e=void 0),o}}else{t=(i=n)+t,n=[];let o,c=null;for(;i=t?UM():(o=s[i++],l<194||(192&o)!=128?(i--,UM()):n.push((31&l)<<6|63&o)):l<240?i>=t-1?UM():(o=s[i++],(192&o)!=128||l===224&&o<160||l===237&&o>=160||(192&(r=s[i++]))!=128?(i--,UM()):n.push((15&l)<<12|(63&o)<<6|63&r)):l<=244?i>=t-2?UM():(o=s[i++],(192&o)!=128||o-144+(l<<28)>>30||(192&(r=s[i++]))!=128||(192&(a=s[i++]))!=128?(i--,UM()):(l=(7&l)<<18|(63&o)<<12|(63&r)<<6|63&a,l-=65536,n.push(55296+(l>>10&1023),56320+(1023&l)))):UM(),n.length>=8192&&(c=pgt(c,n),n.length=0)}i=pgt(c,n)}return i}function I9t(s){const t=C5(s.g);return T9t(s.g,t)}function sTe(s,t,n){var r=C5(s.g);for(r=s.g.g+r;s.g.g>>0,this.g=t>>>0}};let R5n;function Pgt(s){return s?/^-?\d+$/.test(s)?(XEe(s),new hBe(Ep,Ax)):null:O5n||(O5n=new hBe(0,0))}var hBe=class{constructor(s,t){this.h=s>>>0,this.g=t>>>0}};let O5n;function hB(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 bV(s,t){for(;t>127;)s.g.push(127&t|128),t>>>=7;s.g.push(t)}function nTe(s,t){if(t>=0)bV(s,t);else{for(let n=0;n<9;n++)s.g.push(127&t|128),t>>=7;s.g.push(1)}}function eZe(s){var t=Ep;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 KU(s,t){t.length!==0&&(s.l.push(t),s.h+=t.length)}function g2(s,t,n){bV(s.g,8*t+n)}function tZe(s,t){return g2(s,t,2),t=s.g.end(),KU(s,t),t.push(s.h),t}function sZe(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 rTe(s,t,n){g2(s,t,2),bV(s.g,n.length),KU(s,s.g.end()),KU(s,n)}function v4e(s,t,n,r){n!=null&&(t=tZe(s,t),r(n,s),sZe(s,t))}function B5(){const s=class{constructor(){throw Error()}};return Object.setPrototypeOf(s,s.prototype),s}var nZe=B5(),D9t=B5(),rZe=B5(),aZe=B5(),iZe=B5(),R9t=B5(),F5n=B5(),aTe=B5(),O9t=B5(),F9t=B5();function $5(s,t,n){var r=s.v;cw&&cw in r&&(r=r[cw])&&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 Eo=class{constructor(s,t){this.v=b9t(s,t,void 0,2048)}toJSON(){return v9t(this)}j(){var a;var s=v4n,t=this.v,n=s.g,r=cw;if(mV&&r&&((a=t[r])==null?void 0:a[n])!=null&&qU(a5n,3),t=s.g,bgt&&cw&&bgt===void 0&&(r=(n=this.v)[cw])&&(r=r.da))try{r(n,t,A5n)}catch(i){J7t(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[Ao];return qYe(this,s,t)?$Ye(this,s,!0):new this.constructor(xV(s,t,!1))}};Eo.prototype[VU]=HU,Eo.prototype.toString=function(){return this.v.toString()};var _V=class{constructor(s,t,n){this.g=s,this.h=t,s=nZe,this.l=!!s&&n===s||!1}};function iTe(s,t){return new _V(s,t,nZe)}function z9t(s,t,n,r,a){v4e(s,n,q9t(t,r),a)}const z5n=iTe(function(s,t,n,r,a){return s.h===2&&(nte(s,KYe(t,r,n),a),!0)},z9t),B5n=iTe(function(s,t,n,r,a){return s.h===2&&(nte(s,KYe(t,r,n),a),!0)},z9t);var oTe=Symbol(),lTe=Symbol(),mBe=Symbol(),Igt=Symbol(),Dgt=Symbol();let B9t,$9t;function fF(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 M5n||(M5n=[0,void 0,!0]);case"number":return h>0?void 0:h===0?L5n||(L5n=[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,B9t??(B9t=i),$9t??($9t=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 lZe(s,t,n,r,a){const i=n.g;let l,o;s[t]=(c,d,u)=>i(c,d,u,o||(o=fF(lTe,oZe,lZe,r).T),l||(l=cZe(r)),a)}function cZe(s){let t=s[mBe];if(t!=null)return t;const n=fF(lTe,oZe,lZe,s);return t=n.ma?(r,a)=>B9t(r,a,n):(r,a)=>{for(;P9t(a)&&a.h!=4;){var i=a.l,l=n[i];if(l==null){var o=n.ba;o&&(o=o[i])&&(o=U5n(o))!=null&&(l=n[i]=o)}if(l==null||!l(a,r,i)){if(l=(o=a).m,H2e(o),o.ha)var c=void 0;else c=o.g.g-l,o.g.g=l,c=T9t(o.g,c);l=void 0,o=r,c&&((l=o[cw]??(o[cw]=new dBe))[i]??(l[i]=[])).push(c)}}return(r=JEe(r))&&(r.da=n.qa[Dgt]),!0},s[mBe]=t,s[Dgt]=$5n.bind(s),t}function $5n(s,t,n,r){var a=this[lTe];const i=this[mBe],l=qR(void 0,a.T),o=JEe(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=M9t(p);try{c=!0,i(l,u)}finally{L9t(u)}}else r==null||r(s,h,m)},t==null)f4e(o,a);else if(o!=null){const u=o[t];u&&a(o,t,u)}if(c){let u=0|s[Ao];if(2&u&&2048&u&&!(n!=null&&n.Ka))throw Error();const h=pV(u),m=(p,x)=>{if(fC(s,p,h)!=null){if((n==null?void 0:n.Qa)===1)return;throw Error()}x!=null&&(u=Ag(s,u,p,x,h)),delete o[p]};t==null?l9t(l,0|l[Ao],(p,x)=>{m(p,x)}):m(t,fC(l,t,h))}}}}function U5n(s){const t=(s=U9t(s))[0].g;if(s=s[1]){const n=cZe(s),r=fF(lTe,oZe,lZe,s).T;return(a,i,l)=>t(a,i,l,r,n)}return t}function cTe(s,t,n){s[t]=n.h}function dTe(s,t,n,r){let a,i;const l=n.h;s[t]=(o,c,d)=>l(o,c,d,i||(i=fF(oTe,cTe,dTe,r).T),a||(a=V9t(r)))}function V9t(s){let t=s[Igt];if(!t){const n=fF(oTe,cTe,dTe,s);t=(r,a)=>H9t(r,a,n),s[Igt]=t}return t}function H9t(s,t,n){l9t(s,0|s[Ao],(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=U9t(c))[0].h;if(c=c[1]){const u=V9t(c),h=fF(oTe,cTe,dTe,c).T;c=l.ma?$9t(h,u):(m,p,x)=>d(m,p,x,h,u)}else c=d;return l[o]=c}}(n,r);i?i(t,a,r):r<500||qU(lBe,3)}}),(s=JEe(s))&&f4e(s,(r,a,i)=>{for(KU(t,t.g.end()),r=0;r{v4e(s,n,qR([l,i],r),a)});else if(Array.isArray(t)){for(let i=0;i>BigInt(32))),hB(s.g,n.h,n.g);break;default:n=Pgt(t),hB(s.g,n.h,n.g)}}function K9t(s,t,n){(t=fV(t))!=null&&t!=null&&(g2(s,n,0),nTe(s.g,t))}function Y9t(s,t,n){(t=h9t(t))!=null&&(g2(s,n,0),s.g.g.push(t?1:0))}function Z9t(s,t,n){(t=_y(t))!=null&&rTe(s,n,Q7t(t))}function X9t(s,t,n,r,a){v4e(s,n,q9t(t,r),a)}function Q9t(s,t,n){(t=t==null||typeof t=="string"||t instanceof x5?t:void 0)!=null&&rTe(s,n,ZYe(t,!0).buffer)}function J9t(s,t,n){(t=m9t(t))!=null&&t!=null&&(g2(s,n,0),bV(s.g,t))}function ezt(s,t,n){return(s.h===5||s.h===2)&&(t=vV(t,0|t[Ao],n),s.h==2?sTe(s,g4e,t):t.push(g4e(s.g)),!0)}var Ix=wv(function(s,t,n){return s.h===5&&(jv(t,n,g4e(s.g)),!0)},G9t,aTe),H5n=jV(ezt,function(s,t,n){if((t=wV(HS,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"))||(XEe(r),r=eQ(Ep,Ax))),r;if(a==="number")return(r=WU(r))>=0&&MO(r)||(GU(r),r=d9t(Ep,Ax)),r}}(t),t!=null&&(typeof t=="string"&&Lgt(t),t!=null))switch(g2(s,n,0),typeof t){case"number":s=s.g,GU(t),hB(s,Ep,Ax);break;case"bigint":n=BigInt.asUintN(64,t),n=new uBe(Number(n&BigInt(4294967295)),Number(n>>BigInt(32))),hB(s.g,n.h,n.g);break;default:n=Lgt(t),hB(s.g,n.h,n.g)}},F5n),vg=wv(function(s,t,n){return s.h===0&&(jv(t,n,c6(s.g)),!0)},K9t,aZe),rte=jV(function(s,t,n){return(s.h===0||s.h===2)&&(t=vV(t,0|t[Ao],n),s.h==2?sTe(s,c6,t):t.push(c6(s.g)),!0)},function(s,t,n){if((t=wV(fV,t))!=null&&t.length){n=tZe(s,n);for(let r=0;r{{const i={ea:!0};r&&Object.assign(i,r),n=M9t(n,void 0,void 0,i);try{const l=new s,o=l.v;cZe(t)(o,n);var a=l}finally{L9t(n)}}return a}}function uTe(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}}}};H9t(this.v,t,fF(oTe,cTe,dTe,s)),KU(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=Fgt.createPolicy("goog#html",{createHTML:r,createScript:r,createScriptURL:r})}catch{}return n}()),s=(t=T8e)?t.createScriptURL(s):s,new class{constructor(n){this.g=n}toString(){return this.g+""}}(s)}function Kre(s,...t){if(t.length===0)return zgt(s[0]);let n=s[0];for(let r=0;r({index:Oj(r,1)??0??-1,score:Wf(r,2)??0,categoryName:_y(Dp(r,3))??""??"",displayName:_y(Dp(r,4))??""??""})),headIndex:t,headName:n}}function j4n(s){const t={classifications:xC(s,r4n,1).map(n=>{var r;return yZe(((r=Qd(n,czt,4))==null?void 0:r.g())??[],Oj(n,2)??0,_y(Dp(n,3))??"")})};return function(n){return n==null?n:typeof n=="bigint"?(cBe(n)?n=Number(n):(n=ete(64,n),n=cBe(n)?Number(n):String(n)),n):tte(n)?typeof n=="number"?zYe(n):f9t(n):void 0}(Dp(s,2,void 0,void 0,p4e))!=null&&(t.timestampMs=Rzt(Dp(s,2,void 0,void 0,p4e)??_9t)),t}function Ozt(s){var l,o;var t=H8(s,3,HS,V8()),n=H8(s,2,fV,V8()),r=H8(s,1,_y,V8()),a=H8(s,9,_y,V8());const i={categories:[],keypoints:[]};for(let c=0;ct>127?t-256:t)}function Xgt(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 Qgt(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 Bzt(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 Mo(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 Jgt(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]=Bzt(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 e0t(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 Bk(s,t,n){s.i.simpleListeners=s.i.simpleListeners||{},s.i.simpleListeners[t]=n}function cA(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)}}f9.forVisionTasks=function(s,t=!1){return Zre("vision",s??Kre``,t)},f9.forTextTasks=function(s,t=!1){return Zre("text",s??Kre``,t)},f9.forGenAiTasks=function(s,t=!1){return Zre("genai",s??Kre``,t)},f9.forAudioTasks=function(s,t=!1){return Zre("audio",s??Kre``,t)},f9.isSimdSupported=function(s=!1){return Fzt(s)};async function k4n(s,t,n,r){return s=await(async(a,i,l,o,c)=>{if(i&&await Qgt(i),!self.ModuleFactory||l&&(await Qgt(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 P8e(s,t){const n=Qd(s.baseOptions,b4e,1)||new b4e;typeof t=="string"?(oh(n,2,ste(t)),oh(n,1)):t instanceof Uint8Array&&(oh(n,1,DYe(t,!1)),oh(n,2)),al(s.baseOptions,0,1,n)}function t0t(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 lo(s,t){s.C=Math.max(s.C,t)}function fTe(s,t){s.B=new Yb,vw(s.B,2,"PassThroughCalculator"),rp(s.B,"free_memory"),Cd(s.B,"free_memory_unused_out"),Vp(t,"free_memory"),y2(t,s.B)}function YU(s,t){rp(s.B,t),Cd(s.B,t+"_unused_out")}function xTe(s){s.g.addBoolToStream(!0,"free_memory",s.C)}var yBe=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=Qd(this.baseOptions,b4e,1))!=null&&a.g()||(i=Qd(this.baseOptions,b4e,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=Qd(d.baseOptions,Ggt,3);if(!h){var m=h=new Ggt,p=new Bgt;ZY(m,4,G2e,p)}"delegate"in u&&(u.delegate==="GPU"?(u=h,m=new X5n,ZY(u,2,G2e,m)):(u=h,m=new Bgt,ZY(u,4,G2e,m))),al(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),P8e(this,"/model.dat"),this.m(),this.L()});if(c.modelAssetBuffer instanceof Uint8Array)P8e(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=>{P8e(this,d),this.m(),this.L()})}return this.m(),this.L(),Promise.resolve()}L(){}ca(){let s;if(this.g.ca(t=>{s=Q5n(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,t0t(this)}finishProcessing(){this.g.finishProcessing(),t0t(this)}close(){this.B=void 0,this.g.closeGraph()}};function VT(s,t){if(!s)throw Error(`Unable to obtain required WebGL resource: ${t}`);return s}yBe.prototype.close=yBe.prototype.close;class S4n{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 s0t(s,t,n){const r=s.g;if(n=VT(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 n0t(s,t){const n=s.g,r=VT(n.createVertexArray(),"Failed to create vertex array");n.bindVertexArray(r);const a=VT(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=VT(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 S4n(n,r,a,i)}function vZe(s,t){if(s.g){if(t!==s.g)throw Error("Cannot change GL context once initialized")}else s.g=t}function C4n(s,t,n,r){return vZe(s,t),s.h||(s.m(),s.D()),n?(s.u||(s.u=n0t(s,!0)),n=s.u):(s.A||(s.A=n0t(s,!1)),n=s.A),t.useProgram(s.h),n.bind(),s.l(),s=r(),n.g.bindVertexArray(null),s}function $zt(s,t,n){return vZe(s,t),s=VT(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 Uzt(s,t,n){vZe(s,t),s.B||(s.B=VT(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 A4n(s){var t;(t=s.g)==null||t.bindFramebuffer(s.g.FRAMEBUFFER,null)}var qzt=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=VT(s.createProgram(),"Failed to create WebGL program"),this.X=s0t(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=s0t(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 A3(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 vBe(s){var t=A3(s,1);if(!t){if(t=A3(s,0))t=new Float32Array(t).map(r=>r/255);else{t=new Float32Array(s.width*s.height);const r=ZU(s);var n=bZe(s);if(Uzt(n,r,Vzt(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 vBe(this)}N(){return Vzt(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=ZU(this),a=bZe(this);r.activeTexture(r.TEXTURE1),n=$zt(a,r,this.m?r.LINEAR:r.NEAREST),r.bindTexture(r.TEXTURE_2D,n);const i=Hzt(this);r.texImage2D(r.TEXTURE_2D,0,i,this.width,this.height,0,r.RED,r.FLOAT,null),r.bindTexture(r.TEXTURE_2D,null),Uzt(a,r,n),C4n(a,r,!1,()=>{Gzt(this),r.clearColor(0,0,0,0),r.clear(r.COLOR_BUFFER_BIT),r.drawArrays(r.TRIANGLE_FAN,0,4),bBe(this)}),A4n(a),bBe(this)}}s.push(n)}return new t0(s,this.m,this.R(),this.canvas,this.l,this.width,this.height)}close(){this.j&&ZU(this).deleteTexture(A3(this,2)),r0t=-1}};t0.prototype.close=t0.prototype.close,t0.prototype.clone=t0.prototype.clone,t0.prototype.getAsWebGLTexture=t0.prototype.N,t0.prototype.getAsFloat32Array=t0.prototype.ia,t0.prototype.getAsUint8Array=t0.prototype.ja,t0.prototype.hasWebGLTexture=t0.prototype.R,t0.prototype.hasFloat32Array=t0.prototype.ka,t0.prototype.hasUint8Array=t0.prototype.Fa;var r0t=250;function lk(...s){return s.map(([t,n])=>({start:t,end:n}))}const E4n=function(s){return class extends s{Ja(){this.i._registerModelResourcesGraphService()}}}((a0t=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:zzt()?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?'),Mo(this,r||"input_audio",i=>{Mo(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){Bk(this,"__graph_config__",t=>{s(t)}),Mo(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),Mo(this,r,l=>{this.i._addAudioToInputStream(this.g,t,n,l,a)})}addGpuBufferToStream(s,t,n){Mo(this,t,r=>{const[a,i]=Jgt(this,s,r);this.i._addBoundTextureToStream(r,a,i,n)})}addBoolToStream(s,t,n){Mo(this,t,r=>{this.i._addBoolToInputStream(s,r,n)})}addDoubleToStream(s,t,n){Mo(this,t,r=>{this.i._addDoubleToInputStream(s,r,n)})}addFloatToStream(s,t,n){Mo(this,t,r=>{this.i._addFloatToInputStream(s,r,n)})}addIntToStream(s,t,n){Mo(this,t,r=>{this.i._addIntToInputStream(s,r,n)})}addUintToStream(s,t,n){Mo(this,t,r=>{this.i._addUintToInputStream(s,r,n)})}addStringToStream(s,t,n){Mo(this,t,r=>{Mo(this,s,a=>{this.i._addStringToInputStream(a,r,n)})})}addStringRecordToStream(s,t,n){Mo(this,t,r=>{e0t(this,Object.keys(s),a=>{e0t(this,Object.values(s),i=>{this.i._addFlatHashMapToInputStream(a,i,Object.keys(s).length,r,n)})})})}addProtoToStream(s,t,n,r){Mo(this,n,a=>{Mo(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){Mo(this,s,n=>{this.i._addEmptyPacketToInputStream(n,t)})}addBoolVectorToStream(s,t,n){Mo(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){Mo(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){Mo(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){Mo(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){Mo(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){Mo(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)Mo(this,i,l=>{this.i._addStringVectorEntry(a,l)});this.i._addStringVectorToInputStream(a,r,n)})}addBoolToInputSidePacket(s,t){Mo(this,t,n=>{this.i._addBoolToInputSidePacket(s,n)})}addDoubleToInputSidePacket(s,t){Mo(this,t,n=>{this.i._addDoubleToInputSidePacket(s,n)})}addFloatToInputSidePacket(s,t){Mo(this,t,n=>{this.i._addFloatToInputSidePacket(s,n)})}addIntToInputSidePacket(s,t){Mo(this,t,n=>{this.i._addIntToInputSidePacket(s,n)})}addUintToInputSidePacket(s,t){Mo(this,t,n=>{this.i._addUintToInputSidePacket(s,n)})}addStringToInputSidePacket(s,t){Mo(this,t,n=>{Mo(this,s,r=>{this.i._addStringToInputSidePacket(r,n)})})}addProtoToInputSidePacket(s,t,n){Mo(this,n,r=>{Mo(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){Mo(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){Mo(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){Mo(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){Mo(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){Mo(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){Mo(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)Mo(this,a,i=>{this.i._addStringVectorEntry(r,i)});this.i._addStringVectorToInputSidePacket(r,n)})}attachBoolListener(s,t){Bk(this,s,t),Mo(this,s,n=>{this.i._attachBoolListener(n)})}attachBoolVectorListener(s,t){cA(this,s,t),Mo(this,s,n=>{this.i._attachBoolVectorListener(n)})}attachIntListener(s,t){Bk(this,s,t),Mo(this,s,n=>{this.i._attachIntListener(n)})}attachIntVectorListener(s,t){cA(this,s,t),Mo(this,s,n=>{this.i._attachIntVectorListener(n)})}attachUintListener(s,t){Bk(this,s,t),Mo(this,s,n=>{this.i._attachUintListener(n)})}attachUintVectorListener(s,t){cA(this,s,t),Mo(this,s,n=>{this.i._attachUintVectorListener(n)})}attachDoubleListener(s,t){Bk(this,s,t),Mo(this,s,n=>{this.i._attachDoubleListener(n)})}attachDoubleVectorListener(s,t){cA(this,s,t),Mo(this,s,n=>{this.i._attachDoubleVectorListener(n)})}attachFloatListener(s,t){Bk(this,s,t),Mo(this,s,n=>{this.i._attachFloatListener(n)})}attachFloatVectorListener(s,t){cA(this,s,t),Mo(this,s,n=>{this.i._attachFloatVectorListener(n)})}attachStringListener(s,t){Bk(this,s,t),Mo(this,s,n=>{this.i._attachStringListener(n)})}attachStringVectorListener(s,t){cA(this,s,t),Mo(this,s,n=>{this.i._attachStringVectorListener(n)})}attachProtoListener(s,t,n){Bk(this,s,t),Mo(this,s,r=>{this.i._attachProtoListener(r,n||!1)})}attachProtoVectorListener(s,t,n){cA(this,s,t),Mo(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?'),Bk(this,s,(r,a)=>{r=new Float32Array(r.buffer,r.byteOffset,r.length/4),t(r,a)}),Mo(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 a0t{get ga(){return this.i}pa(s,t,n){Mo(this,t,r=>{const[a,i]=Jgt(this,s,r);this.ga._addBoundTextureAsImageToStream(r,a,i,n)})}Z(s,t){Bk(this,s,t),Mo(this,s,n=>{this.ga._attachImageListener(n)})}aa(s,t){cA(this,s,t),Mo(this,s,n=>{this.ga._attachImageVectorListener(n)})}}));var a0t,ck=class extends E4n{};async function Vd(s,t,n){return async function(r,a,i,l){return k4n(r,a,i,l)}(s,n.canvas??(zzt()?void 0:document.createElement("canvas")),t,n)}function Wzt(s,t,n,r){if(s.U){const i=new pzt;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].");zo(i,1,(a.left+a.right)/2),zo(i,2,(a.top+a.bottom)/2),zo(i,4,a.right-a.left),zo(i,3,a.bottom-a.top)}else zo(i,1,.5),zo(i,2,.5),zo(i,4,1),zo(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(zo(i,5,-Math.PI*n.rotationDegrees/180),(n==null?void 0:n.rotationDegrees)%180!=0){const[l,o]=Bzt(t);n=Wf(i,3)*o/l,a=Wf(i,4)*l/o,zo(i,4,n),zo(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 dk(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'.");Wzt(s,t,n,s.C+1)}function q5(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'.");Wzt(s,t,n,r)}function XU(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 t0([a],n,!1,s.g.i.canvas,s.P,i,t),r?s.clone():s}var bw=class extends yBe{constructor(s,t,n,r){super(s),this.g=s,this.X=t,this.U=n,this.oa=r,this.P=new qzt}l(s,t=!0){if("runningMode"in s&&oh(this.baseOptions,2,tQ(!!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()}};bw.prototype.close=bw.prototype.close;var aj=class extends bw{constructor(s,t){super(new ck(s,t),"image_in","norm_rect_in",!1),this.j={detections:[]},al(s=this.h=new mTe,0,1,t=new Af),zo(this.h,2,.5),zo(this.h,3,.3)}get baseOptions(){return Qd(this.h,Af,1)}set baseOptions(s){al(this.h,0,1,s)}o(s){return"minDetectionConfidence"in s&&zo(this.h,2,s.minDetectionConfidence??.5),"minSuppressionThreshold"in s&&zo(this.h,3,s.minSuppressionThreshold??.3),this.l(s)}F(s,t){return this.j={detections:[]},dk(this,s,t),this.j}G(s,t,n){return this.j={detections:[]},q5(this,s,n,t),this.j}m(){var s=new Aw;Vp(s,"image_in"),Vp(s,"norm_rect_in"),cu(s,"detections");const t=new Cw;$5(t,d4n,this.h);const n=new Yb;vw(n,2,"mediapipe.tasks.vision.face_detector.FaceDetectorGraph"),rp(n,"IMAGE:image_in"),rp(n,"NORM_RECT:norm_rect_in"),Cd(n,"DETECTIONS:detections"),n.o(t),y2(s,n),this.g.attachProtoVectorListener("detections",(r,a)=>{for(const i of r)r=uzt(i),this.j.detections.push(Ozt(r));lo(this,a)}),this.g.attachEmptyPacketListener("detections",r=>{lo(this,r)}),s=s.g(),this.setGraph(new Uint8Array(s),!0)}};aj.prototype.detectForVideo=aj.prototype.G,aj.prototype.detect=aj.prototype.F,aj.prototype.setOptions=aj.prototype.o,aj.createFromModelPath=async function(s,t){return Vd(aj,s,{baseOptions:{modelAssetPath:t}})},aj.createFromModelBuffer=function(s,t){return Vd(aj,s,{baseOptions:{modelAssetBuffer:t}})},aj.createFromOptions=function(s,t){return Vd(aj,s,t)};var _Ze=lk([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]),wZe=lk([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]),jZe=lk([276,283],[283,282],[282,295],[295,285],[300,293],[293,334],[334,296],[296,336]),Kzt=lk([474,475],[475,476],[476,477],[477,474]),NZe=lk([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]),kZe=lk([46,53],[53,52],[52,65],[65,55],[70,63],[63,105],[105,66],[66,107]),Yzt=lk([469,470],[470,471],[471,472],[472,469]),SZe=lk([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]),Zzt=[..._Ze,...wZe,...jZe,...NZe,...kZe,...SZe],Xzt=lk([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 i0t(s){s.j={faceLandmarks:[],faceBlendshapes:[],facialTransformationMatrixes:[]}}var of=class extends bw{constructor(s,t){super(new ck(s,t),"image_in","norm_rect",!1),this.j={faceLandmarks:[],faceBlendshapes:[],facialTransformationMatrixes:[]},this.outputFacialTransformationMatrixes=this.outputFaceBlendshapes=!1,al(s=this.h=new vzt,0,1,t=new Af),this.A=new yzt,al(this.h,0,3,this.A),this.u=new mTe,al(this.h,0,2,this.u),gC(this.u,4,1),zo(this.u,2,.5),zo(this.A,2,.5),zo(this.h,4,.5)}get baseOptions(){return Qd(this.h,Af,1)}set baseOptions(s){al(this.h,0,1,s)}o(s){return"numFaces"in s&&gC(this.u,4,s.numFaces??1),"minFaceDetectionConfidence"in s&&zo(this.u,2,s.minFaceDetectionConfidence??.5),"minTrackingConfidence"in s&&zo(this.h,4,s.minTrackingConfidence??.5),"minFacePresenceConfidence"in s&&zo(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 i0t(this),dk(this,s,t),this.j}G(s,t,n){return i0t(this),q5(this,s,n,t),this.j}m(){var s=new Aw;Vp(s,"image_in"),Vp(s,"norm_rect"),cu(s,"face_landmarks");const t=new Cw;$5(t,h4n,this.h);const n=new Yb;vw(n,2,"mediapipe.tasks.vision.face_landmarker.FaceLandmarkerGraph"),rp(n,"IMAGE:image_in"),rp(n,"NORM_RECT:norm_rect"),Cd(n,"NORM_LANDMARKS:face_landmarks"),n.o(t),y2(s,n),this.g.attachProtoVectorListener("face_landmarks",(r,a)=>{for(const i of r)r=ate(i),this.j.faceLandmarks.push(pTe(r));lo(this,a)}),this.g.attachEmptyPacketListener("face_landmarks",r=>{lo(this,r)}),this.outputFaceBlendshapes&&(cu(s,"blendshapes"),Cd(n,"BLENDSHAPES:blendshapes"),this.g.attachProtoVectorListener("blendshapes",(r,a)=>{if(this.outputFaceBlendshapes)for(const i of r)r=hTe(i),this.j.faceBlendshapes.push(yZe(r.g()??[]));lo(this,a)}),this.g.attachEmptyPacketListener("blendshapes",r=>{lo(this,r)})),this.outputFacialTransformationMatrixes&&(cu(s,"face_geometry"),Cd(n,"FACE_GEOMETRY:face_geometry"),this.g.attachProtoVectorListener("face_geometry",(r,a)=>{if(this.outputFacialTransformationMatrixes)for(const i of r)(r=Qd(r=u4n(i),s4n,2))&&this.j.facialTransformationMatrixes.push({rows:Oj(r,1)??0??0,columns:Oj(r,2)??0??0,data:H8(r,3,HS,V8()).slice()??[]});lo(this,a)}),this.g.attachEmptyPacketListener("face_geometry",r=>{lo(this,r)})),s=s.g(),this.setGraph(new Uint8Array(s),!0)}};of.prototype.detectForVideo=of.prototype.G,of.prototype.detect=of.prototype.F,of.prototype.setOptions=of.prototype.o,of.createFromModelPath=function(s,t){return Vd(of,s,{baseOptions:{modelAssetPath:t}})},of.createFromModelBuffer=function(s,t){return Vd(of,s,{baseOptions:{modelAssetBuffer:t}})},of.createFromOptions=function(s,t){return Vd(of,s,t)},of.FACE_LANDMARKS_LIPS=_Ze,of.FACE_LANDMARKS_LEFT_EYE=wZe,of.FACE_LANDMARKS_LEFT_EYEBROW=jZe,of.FACE_LANDMARKS_LEFT_IRIS=Kzt,of.FACE_LANDMARKS_RIGHT_EYE=NZe,of.FACE_LANDMARKS_RIGHT_EYEBROW=kZe,of.FACE_LANDMARKS_RIGHT_IRIS=Yzt,of.FACE_LANDMARKS_FACE_OVAL=SZe,of.FACE_LANDMARKS_CONTOURS=Zzt,of.FACE_LANDMARKS_TESSELATION=Xzt;var CZe=lk([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 o0t(s){s.gestures=[],s.landmarks=[],s.worldLandmarks=[],s.handedness=[]}function l0t(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 c0t(s,t=!0){const n=[];for(const a of s){var r=hTe(a);s=[];for(const i of r.g())r=t&&Oj(i,1)!=null?Oj(i,1)??0:-1,s.push({score:Wf(i,2)??0,index:r,categoryName:_y(Dp(i,3))??""??"",displayName:_y(Dp(i,4))??""??""});n.push(s)}return n}var m_=class extends bw{constructor(s,t){super(new ck(s,t),"image_in","norm_rect",!1),this.gestures=[],this.landmarks=[],this.worldLandmarks=[],this.handedness=[],al(s=this.j=new wzt,0,1,t=new Af),this.u=new pZe,al(this.j,0,2,this.u),this.D=new mZe,al(this.u,0,3,this.D),this.A=new _zt,al(this.u,0,2,this.A),this.h=new m4n,al(this.j,0,3,this.h),zo(this.A,2,.5),zo(this.u,4,.5),zo(this.D,2,.5)}get baseOptions(){return Qd(this.j,Af,1)}set baseOptions(s){al(this.j,0,1,s)}o(s){var a,i,l,o;if(gC(this.A,3,s.numHands??1),"minHandDetectionConfidence"in s&&zo(this.A,2,s.minHandDetectionConfidence??.5),"minTrackingConfidence"in s&&zo(this.u,4,s.minTrackingConfidence??.5),"minHandPresenceConfidence"in s&&zo(this.D,2,s.minHandPresenceConfidence??.5),s.cannedGesturesClassifierOptions){var t=new F7,n=t,r=gBe(s.cannedGesturesClassifierOptions,(a=Qd(this.h,F7,3))==null?void 0:a.l());al(n,0,2,r),al(this.h,0,3,t)}else s.cannedGesturesClassifierOptions===void 0&&((i=Qd(this.h,F7,3))==null||i.g());return s.customGesturesClassifierOptions?(al(n=t=new F7,0,2,r=gBe(s.customGesturesClassifierOptions,(l=Qd(this.h,F7,4))==null?void 0:l.l())),al(this.h,0,4,t)):s.customGesturesClassifierOptions===void 0&&((o=Qd(this.h,F7,4))==null||o.g()),this.l(s)}Ha(s,t){return o0t(this),dk(this,s,t),l0t(this)}Ia(s,t,n){return o0t(this),q5(this,s,n,t),l0t(this)}m(){var s=new Aw;Vp(s,"image_in"),Vp(s,"norm_rect"),cu(s,"hand_gestures"),cu(s,"hand_landmarks"),cu(s,"world_hand_landmarks"),cu(s,"handedness");const t=new Cw;$5(t,p4n,this.j);const n=new Yb;vw(n,2,"mediapipe.tasks.vision.gesture_recognizer.GestureRecognizerGraph"),rp(n,"IMAGE:image_in"),rp(n,"NORM_RECT:norm_rect"),Cd(n,"HAND_GESTURES:hand_gestures"),Cd(n,"LANDMARKS:hand_landmarks"),Cd(n,"WORLD_LANDMARKS:world_hand_landmarks"),Cd(n,"HANDEDNESS:handedness"),n.o(t),y2(s,n),this.g.attachProtoVectorListener("hand_landmarks",(r,a)=>{for(const i of r){r=ate(i);const l=[];for(const o of xC(r,mzt,1))l.push({x:Wf(o,1)??0,y:Wf(o,2)??0,z:Wf(o,3)??0,visibility:Wf(o,4)??0});this.landmarks.push(l)}lo(this,a)}),this.g.attachEmptyPacketListener("hand_landmarks",r=>{lo(this,r)}),this.g.attachProtoVectorListener("world_hand_landmarks",(r,a)=>{for(const i of r){r=mB(i);const l=[];for(const o of xC(r,hzt,1))l.push({x:Wf(o,1)??0,y:Wf(o,2)??0,z:Wf(o,3)??0,visibility:Wf(o,4)??0});this.worldLandmarks.push(l)}lo(this,a)}),this.g.attachEmptyPacketListener("world_hand_landmarks",r=>{lo(this,r)}),this.g.attachProtoVectorListener("hand_gestures",(r,a)=>{this.gestures.push(...c0t(r,!1)),lo(this,a)}),this.g.attachEmptyPacketListener("hand_gestures",r=>{lo(this,r)}),this.g.attachProtoVectorListener("handedness",(r,a)=>{this.handedness.push(...c0t(r)),lo(this,a)}),this.g.attachEmptyPacketListener("handedness",r=>{lo(this,r)}),s=s.g(),this.setGraph(new Uint8Array(s),!0)}};function d0t(s){return{landmarks:s.landmarks,worldLandmarks:s.worldLandmarks,handednesses:s.handedness,handedness:s.handedness}}m_.prototype.recognizeForVideo=m_.prototype.Ia,m_.prototype.recognize=m_.prototype.Ha,m_.prototype.setOptions=m_.prototype.o,m_.createFromModelPath=function(s,t){return Vd(m_,s,{baseOptions:{modelAssetPath:t}})},m_.createFromModelBuffer=function(s,t){return Vd(m_,s,{baseOptions:{modelAssetBuffer:t}})},m_.createFromOptions=function(s,t){return Vd(m_,s,t)},m_.HAND_CONNECTIONS=CZe;var p_=class extends bw{constructor(s,t){super(new ck(s,t),"image_in","norm_rect",!1),this.landmarks=[],this.worldLandmarks=[],this.handedness=[],al(s=this.h=new pZe,0,1,t=new Af),this.u=new mZe,al(this.h,0,3,this.u),this.j=new _zt,al(this.h,0,2,this.j),gC(this.j,3,1),zo(this.j,2,.5),zo(this.u,2,.5),zo(this.h,4,.5)}get baseOptions(){return Qd(this.h,Af,1)}set baseOptions(s){al(this.h,0,1,s)}o(s){return"numHands"in s&&gC(this.j,3,s.numHands??1),"minHandDetectionConfidence"in s&&zo(this.j,2,s.minHandDetectionConfidence??.5),"minTrackingConfidence"in s&&zo(this.h,4,s.minTrackingConfidence??.5),"minHandPresenceConfidence"in s&&zo(this.u,2,s.minHandPresenceConfidence??.5),this.l(s)}F(s,t){return this.landmarks=[],this.worldLandmarks=[],this.handedness=[],dk(this,s,t),d0t(this)}G(s,t,n){return this.landmarks=[],this.worldLandmarks=[],this.handedness=[],q5(this,s,n,t),d0t(this)}m(){var s=new Aw;Vp(s,"image_in"),Vp(s,"norm_rect"),cu(s,"hand_landmarks"),cu(s,"world_hand_landmarks"),cu(s,"handedness");const t=new Cw;$5(t,f4n,this.h);const n=new Yb;vw(n,2,"mediapipe.tasks.vision.hand_landmarker.HandLandmarkerGraph"),rp(n,"IMAGE:image_in"),rp(n,"NORM_RECT:norm_rect"),Cd(n,"LANDMARKS:hand_landmarks"),Cd(n,"WORLD_LANDMARKS:world_hand_landmarks"),Cd(n,"HANDEDNESS:handedness"),n.o(t),y2(s,n),this.g.attachProtoVectorListener("hand_landmarks",(r,a)=>{for(const i of r)r=ate(i),this.landmarks.push(pTe(r));lo(this,a)}),this.g.attachEmptyPacketListener("hand_landmarks",r=>{lo(this,r)}),this.g.attachProtoVectorListener("world_hand_landmarks",(r,a)=>{for(const i of r)r=mB(i),this.worldLandmarks.push(QY(r));lo(this,a)}),this.g.attachEmptyPacketListener("world_hand_landmarks",r=>{lo(this,r)}),this.g.attachProtoVectorListener("handedness",(r,a)=>{var i=this.handedness,l=i.push;const o=[];for(const c of r){r=hTe(c);const d=[];for(const u of r.g())d.push({score:Wf(u,2)??0,index:Oj(u,1)??0??-1,categoryName:_y(Dp(u,3))??""??"",displayName:_y(Dp(u,4))??""??""});o.push(d)}l.call(i,...o),lo(this,a)}),this.g.attachEmptyPacketListener("handedness",r=>{lo(this,r)}),s=s.g(),this.setGraph(new Uint8Array(s),!0)}};p_.prototype.detectForVideo=p_.prototype.G,p_.prototype.detect=p_.prototype.F,p_.prototype.setOptions=p_.prototype.o,p_.createFromModelPath=function(s,t){return Vd(p_,s,{baseOptions:{modelAssetPath:t}})},p_.createFromModelBuffer=function(s,t){return Vd(p_,s,{baseOptions:{modelAssetBuffer:t}})},p_.createFromOptions=function(s,t){return Vd(p_,s,t)},p_.HAND_CONNECTIONS=CZe;var Qzt=lk([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 u0t(s){s.h={faceLandmarks:[],faceBlendshapes:[],poseLandmarks:[],poseWorldLandmarks:[],poseSegmentationMasks:[],leftHandLandmarks:[],leftHandWorldLandmarks:[],rightHandLandmarks:[],rightHandWorldLandmarks:[]}}function h0t(s){try{if(!s.D)return s.h;s.D(s.h)}finally{xTe(s)}}function Qre(s,t){s=ate(s),t.push(pTe(s))}var qm=class extends bw{constructor(s,t){super(new ck(s,t),"input_frames_image",null,!1),this.h={faceLandmarks:[],faceBlendshapes:[],poseLandmarks:[],poseWorldLandmarks:[],poseSegmentationMasks:[],leftHandLandmarks:[],leftHandWorldLandmarks:[],rightHandLandmarks:[],rightHandWorldLandmarks:[]},this.outputPoseSegmentationMasks=this.outputFaceBlendshapes=!1,al(s=this.j=new Czt,0,1,t=new Af),this.I=new mZe,al(this.j,0,2,this.I),this.W=new x4n,al(this.j,0,3,this.W),this.u=new mTe,al(this.j,0,4,this.u),this.O=new yzt,al(this.j,0,5,this.O),this.A=new kzt,al(this.j,0,6,this.A),this.M=new Szt,al(this.j,0,7,this.M),zo(this.u,2,.5),zo(this.u,3,.3),zo(this.O,2,.5),zo(this.A,2,.5),zo(this.A,3,.3),zo(this.M,2,.5),zo(this.I,2,.5)}get baseOptions(){return Qd(this.j,Af,1)}set baseOptions(s){al(this.j,0,1,s)}o(s){return"minFaceDetectionConfidence"in s&&zo(this.u,2,s.minFaceDetectionConfidence??.5),"minFaceSuppressionThreshold"in s&&zo(this.u,3,s.minFaceSuppressionThreshold??.3),"minFacePresenceConfidence"in s&&zo(this.O,2,s.minFacePresenceConfidence??.5),"outputFaceBlendshapes"in s&&(this.outputFaceBlendshapes=!!s.outputFaceBlendshapes),"minPoseDetectionConfidence"in s&&zo(this.A,2,s.minPoseDetectionConfidence??.5),"minPoseSuppressionThreshold"in s&&zo(this.A,3,s.minPoseSuppressionThreshold??.3),"minPosePresenceConfidence"in s&&zo(this.M,2,s.minPosePresenceConfidence??.5),"outputPoseSegmentationMasks"in s&&(this.outputPoseSegmentationMasks=!!s.outputPoseSegmentationMasks),"minHandLandmarksConfidence"in s&&zo(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,u0t(this),dk(this,s,r),h0t(this)}G(s,t,n,r){const a=typeof n!="function"?n:{};return this.D=typeof n=="function"?n:r,u0t(this),q5(this,s,a,t),h0t(this)}m(){var s=new Aw;Vp(s,"input_frames_image"),cu(s,"pose_landmarks"),cu(s,"pose_world_landmarks"),cu(s,"face_landmarks"),cu(s,"left_hand_landmarks"),cu(s,"left_hand_world_landmarks"),cu(s,"right_hand_landmarks"),cu(s,"right_hand_world_landmarks");const t=new Cw,n=new Rgt;vw(n,1,"type.googleapis.com/mediapipe.tasks.vision.holistic_landmarker.proto.HolisticLandmarkerGraphOptions"),function(a,i){if(i!=null)if(Array.isArray(i))oh(a,2,eTe(i,0,sQ));else{if(!(typeof i=="string"||i instanceof x5||PYe(i)))throw Error("invalid value in Any.value field: "+i+" expected a ByteString, a base64 encoded string, a Uint8Array or a jspb array");HA(a,2,DYe(i,!1),EO())}}(n,this.j.g());const r=new Yb;vw(r,2,"mediapipe.tasks.vision.holistic_landmarker.HolisticLandmarkerGraph"),YYe(r,8,Rgt,n),rp(r,"IMAGE:input_frames_image"),Cd(r,"POSE_LANDMARKS:pose_landmarks"),Cd(r,"POSE_WORLD_LANDMARKS:pose_world_landmarks"),Cd(r,"FACE_LANDMARKS:face_landmarks"),Cd(r,"LEFT_HAND_LANDMARKS:left_hand_landmarks"),Cd(r,"LEFT_HAND_WORLD_LANDMARKS:left_hand_world_landmarks"),Cd(r,"RIGHT_HAND_LANDMARKS:right_hand_landmarks"),Cd(r,"RIGHT_HAND_WORLD_LANDMARKS:right_hand_world_landmarks"),r.o(t),y2(s,r),fTe(this,s),this.g.attachProtoListener("pose_landmarks",(a,i)=>{Qre(a,this.h.poseLandmarks),lo(this,i)}),this.g.attachEmptyPacketListener("pose_landmarks",a=>{lo(this,a)}),this.g.attachProtoListener("pose_world_landmarks",(a,i)=>{var l=this.h.poseWorldLandmarks;a=mB(a),l.push(QY(a)),lo(this,i)}),this.g.attachEmptyPacketListener("pose_world_landmarks",a=>{lo(this,a)}),this.outputPoseSegmentationMasks&&(Cd(r,"POSE_SEGMENTATION_MASK:pose_segmentation_mask"),YU(this,"pose_segmentation_mask"),this.g.Z("pose_segmentation_mask",(a,i)=>{this.h.poseSegmentationMasks=[XU(this,a,!0,!this.D)],lo(this,i)}),this.g.attachEmptyPacketListener("pose_segmentation_mask",a=>{this.h.poseSegmentationMasks=[],lo(this,a)})),this.g.attachProtoListener("face_landmarks",(a,i)=>{Qre(a,this.h.faceLandmarks),lo(this,i)}),this.g.attachEmptyPacketListener("face_landmarks",a=>{lo(this,a)}),this.outputFaceBlendshapes&&(cu(s,"extra_blendshapes"),Cd(r,"FACE_BLENDSHAPES:extra_blendshapes"),this.g.attachProtoListener("extra_blendshapes",(a,i)=>{var l=this.h.faceBlendshapes;this.outputFaceBlendshapes&&(a=hTe(a),l.push(yZe(a.g()??[]))),lo(this,i)}),this.g.attachEmptyPacketListener("extra_blendshapes",a=>{lo(this,a)})),this.g.attachProtoListener("left_hand_landmarks",(a,i)=>{Qre(a,this.h.leftHandLandmarks),lo(this,i)}),this.g.attachEmptyPacketListener("left_hand_landmarks",a=>{lo(this,a)}),this.g.attachProtoListener("left_hand_world_landmarks",(a,i)=>{var l=this.h.leftHandWorldLandmarks;a=mB(a),l.push(QY(a)),lo(this,i)}),this.g.attachEmptyPacketListener("left_hand_world_landmarks",a=>{lo(this,a)}),this.g.attachProtoListener("right_hand_landmarks",(a,i)=>{Qre(a,this.h.rightHandLandmarks),lo(this,i)}),this.g.attachEmptyPacketListener("right_hand_landmarks",a=>{lo(this,a)}),this.g.attachProtoListener("right_hand_world_landmarks",(a,i)=>{var l=this.h.rightHandWorldLandmarks;a=mB(a),l.push(QY(a)),lo(this,i)}),this.g.attachEmptyPacketListener("right_hand_world_landmarks",a=>{lo(this,a)}),s=s.g(),this.setGraph(new Uint8Array(s),!0)}};qm.prototype.detectForVideo=qm.prototype.G,qm.prototype.detect=qm.prototype.F,qm.prototype.setOptions=qm.prototype.o,qm.createFromModelPath=function(s,t){return Vd(qm,s,{baseOptions:{modelAssetPath:t}})},qm.createFromModelBuffer=function(s,t){return Vd(qm,s,{baseOptions:{modelAssetBuffer:t}})},qm.createFromOptions=function(s,t){return Vd(qm,s,t)},qm.HAND_CONNECTIONS=CZe,qm.POSE_CONNECTIONS=Qzt,qm.FACE_LANDMARKS_LIPS=_Ze,qm.FACE_LANDMARKS_LEFT_EYE=wZe,qm.FACE_LANDMARKS_LEFT_EYEBROW=jZe,qm.FACE_LANDMARKS_LEFT_IRIS=Kzt,qm.FACE_LANDMARKS_RIGHT_EYE=NZe,qm.FACE_LANDMARKS_RIGHT_EYEBROW=kZe,qm.FACE_LANDMARKS_RIGHT_IRIS=Yzt,qm.FACE_LANDMARKS_FACE_OVAL=SZe,qm.FACE_LANDMARKS_CONTOURS=Zzt,qm.FACE_LANDMARKS_TESSELATION=Xzt;var ij=class extends bw{constructor(s,t){super(new ck(s,t),"input_image","norm_rect",!0),this.j={classifications:[]},al(s=this.h=new Azt,0,1,t=new Af)}get baseOptions(){return Qd(this.h,Af,1)}set baseOptions(s){al(this.h,0,1,s)}o(s){return al(this.h,0,2,gBe(s,Qd(this.h,uZe,2))),this.l(s)}sa(s,t){return this.j={classifications:[]},dk(this,s,t),this.j}ta(s,t,n){return this.j={classifications:[]},q5(this,s,n,t),this.j}m(){var s=new Aw;Vp(s,"input_image"),Vp(s,"norm_rect"),cu(s,"classifications");const t=new Cw;$5(t,g4n,this.h);const n=new Yb;vw(n,2,"mediapipe.tasks.vision.image_classifier.ImageClassifierGraph"),rp(n,"IMAGE:input_image"),rp(n,"NORM_RECT:norm_rect"),Cd(n,"CLASSIFICATIONS:classifications"),n.o(t),y2(s,n),this.g.attachProtoListener("classifications",(r,a)=>{this.j=j4n(a4n(r)),lo(this,a)}),this.g.attachEmptyPacketListener("classifications",r=>{lo(this,r)}),s=s.g(),this.setGraph(new Uint8Array(s),!0)}};ij.prototype.classifyForVideo=ij.prototype.ta,ij.prototype.classify=ij.prototype.sa,ij.prototype.setOptions=ij.prototype.o,ij.createFromModelPath=function(s,t){return Vd(ij,s,{baseOptions:{modelAssetPath:t}})},ij.createFromModelBuffer=function(s,t){return Vd(ij,s,{baseOptions:{modelAssetBuffer:t}})},ij.createFromOptions=function(s,t){return Vd(ij,s,t)};var f_=class extends bw{constructor(s,t){super(new ck(s,t),"image_in","norm_rect",!0),this.h=new Ezt,this.embeddings={embeddings:[]},al(s=this.h,0,1,t=new Af)}get baseOptions(){return Qd(this.h,Af,1)}set baseOptions(s){al(this.h,0,1,s)}o(s){var t=this.h,n=Qd(this.h,Hgt,2);return n=n?n.clone():new Hgt,s.l2Normalize!==void 0?oh(n,1,tQ(s.l2Normalize)):"l2Normalize"in s&&oh(n,1),s.quantize!==void 0?oh(n,2,tQ(s.quantize)):"quantize"in s&&oh(n,2),al(t,0,2,n),this.l(s)}za(s,t){return dk(this,s,t),this.embeddings}Aa(s,t,n){return q5(this,s,n,t),this.embeddings}m(){var s=new Aw;Vp(s,"image_in"),Vp(s,"norm_rect"),cu(s,"embeddings_out");const t=new Cw;$5(t,y4n,this.h);const n=new Yb;vw(n,2,"mediapipe.tasks.vision.image_embedder.ImageEmbedderGraph"),rp(n,"IMAGE:image_in"),rp(n,"NORM_RECT:norm_rect"),Cd(n,"EMBEDDINGS:embeddings_out"),n.o(t),y2(s,n),this.g.attachProtoListener("embeddings_out",(r,a)=>{r=l4n(r),this.embeddings=function(i){return{embeddings:xC(i,o4n,1).map(l=>{var d,u;const o={headIndex:Oj(l,3)??0??-1,headName:_y(Dp(l,4))??""??""};var c=l.v;return S9t(c,0|c[Ao],Vgt,A8e(l,1))!==void 0?(l=H8(l=Qd(l,Vgt,A8e(l,1),void 0),1,HS,V8()),o.floatEmbedding=l.slice()):(c=new Uint8Array(0),o.quantizedEmbedding=((u=(d=Qd(l,i4n,A8e(l,2),void 0))==null?void 0:d.na())==null?void 0:u.h())??c),o}),timestampMs:Rzt(Dp(i,2,void 0,void 0,p4e)??_9t)}}(r),lo(this,a)}),this.g.attachEmptyPacketListener("embeddings_out",r=>{lo(this,r)}),s=s.g(),this.setGraph(new Uint8Array(s),!0)}};f_.cosineSimilarity=function(s,t){if(s.floatEmbedding&&t.floatEmbedding)s=Xgt(s.floatEmbedding,t.floatEmbedding);else{if(!s.quantizedEmbedding||!t.quantizedEmbedding)throw Error("Cannot compute cosine similarity between quantized and float embeddings.");s=Xgt(Zgt(s.quantizedEmbedding),Zgt(t.quantizedEmbedding))}return s},f_.prototype.embedForVideo=f_.prototype.Aa,f_.prototype.embed=f_.prototype.za,f_.prototype.setOptions=f_.prototype.o,f_.createFromModelPath=function(s,t){return Vd(f_,s,{baseOptions:{modelAssetPath:t}})},f_.createFromModelBuffer=function(s,t){return Vd(f_,s,{baseOptions:{modelAssetBuffer:t}})},f_.createFromOptions=function(s,t){return Vd(f_,s,t)};var _Be=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 T4n(s){var n,r;const t=function(a){return xC(a,Yb,1)}(s.ca()).filter(a=>(_y(Dp(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=Qd(t[0],Cw,7))==null?void 0:n.j())==null?void 0:r.g())??new Map).forEach((a,i)=>{s.u[Number(i)]=_y(Dp(a,1))??""})}function m0t(s){s.categoryMask=void 0,s.confidenceMasks=void 0,s.qualityScores=void 0}function p0t(s){try{const t=new _Be(s.confidenceMasks,s.categoryMask,s.qualityScores);if(!s.j)return t;s.j(t)}finally{xTe(s)}}_Be.prototype.close=_Be.prototype.close;var Hv=class extends bw{constructor(s,t){super(new ck(s,t),"image_in","norm_rect",!1),this.u=[],this.outputCategoryMask=!1,this.outputConfidenceMasks=!0,this.h=new gZe,this.A=new Tzt,al(this.h,0,3,this.A),al(s=this.h,0,1,t=new Af)}get baseOptions(){return Qd(this.h,Af,1)}set baseOptions(s){al(this.h,0,1,s)}o(s){return s.displayNamesLocale!==void 0?oh(this.h,2,ste(s.displayNamesLocale)):"displayNamesLocale"in s&&oh(this.h,2),"outputCategoryMask"in s&&(this.outputCategoryMask=s.outputCategoryMask??!1),"outputConfidenceMasks"in s&&(this.outputConfidenceMasks=s.outputConfidenceMasks??!0),super.l(s)}L(){T4n(this)}segment(s,t,n){const r=typeof t!="function"?t:{};return this.j=typeof t=="function"?t:n,m0t(this),dk(this,s,r),p0t(this)}La(s,t,n,r){const a=typeof n!="function"?n:{};return this.j=typeof n=="function"?n:r,m0t(this),q5(this,s,a,t),p0t(this)}Da(){return this.u}m(){var s=new Aw;Vp(s,"image_in"),Vp(s,"norm_rect");const t=new Cw;$5(t,Lzt,this.h);const n=new Yb;vw(n,2,"mediapipe.tasks.vision.image_segmenter.ImageSegmenterGraph"),rp(n,"IMAGE:image_in"),rp(n,"NORM_RECT:norm_rect"),n.o(t),y2(s,n),fTe(this,s),this.outputConfidenceMasks&&(cu(s,"confidence_masks"),Cd(n,"CONFIDENCE_MASKS:confidence_masks"),YU(this,"confidence_masks"),this.g.aa("confidence_masks",(r,a)=>{this.confidenceMasks=r.map(i=>XU(this,i,!0,!this.j)),lo(this,a)}),this.g.attachEmptyPacketListener("confidence_masks",r=>{this.confidenceMasks=[],lo(this,r)})),this.outputCategoryMask&&(cu(s,"category_mask"),Cd(n,"CATEGORY_MASK:category_mask"),YU(this,"category_mask"),this.g.Z("category_mask",(r,a)=>{this.categoryMask=XU(this,r,!1,!this.j),lo(this,a)}),this.g.attachEmptyPacketListener("category_mask",r=>{this.categoryMask=void 0,lo(this,r)})),cu(s,"quality_scores"),Cd(n,"QUALITY_SCORES:quality_scores"),this.g.attachFloatVectorListener("quality_scores",(r,a)=>{this.qualityScores=r,lo(this,a)}),this.g.attachEmptyPacketListener("quality_scores",r=>{this.categoryMask=void 0,lo(this,r)}),s=s.g(),this.setGraph(new Uint8Array(s),!0)}};Hv.prototype.getLabels=Hv.prototype.Da,Hv.prototype.segmentForVideo=Hv.prototype.La,Hv.prototype.segment=Hv.prototype.segment,Hv.prototype.setOptions=Hv.prototype.o,Hv.createFromModelPath=function(s,t){return Vd(Hv,s,{baseOptions:{modelAssetPath:t}})},Hv.createFromModelBuffer=function(s,t){return Vd(Hv,s,{baseOptions:{modelAssetBuffer:t}})},Hv.createFromOptions=function(s,t){return Vd(Hv,s,t)};var wBe=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()}};wBe.prototype.close=wBe.prototype.close;var $k=class extends bw{constructor(s,t){super(new ck(s,t),"image_in","norm_rect_in",!1),this.outputCategoryMask=!1,this.outputConfidenceMasks=!0,this.h=new gZe,this.u=new Tzt,al(this.h,0,3,this.u),al(s=this.h,0,1,t=new Af)}get baseOptions(){return Qd(this.h,Af,1)}set baseOptions(s){al(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 Pzt,t.keypoint&&t.scribble)throw Error("Cannot provide both keypoint and scribble.");if(t.keypoint){var i=new L8e;HA(i,3,tQ(!0),!1),HA(i,1,MW(t.keypoint.x),0),HA(i,2,MW(t.keypoint.y),0),ZY(r,1,xBe,i)}else{if(!t.scribble)throw Error("Must provide either a keypoint or a scribble.");{const o=new b4n;for(i of t.scribble)HA(t=new L8e,3,tQ(!0),!1),HA(t,1,MW(i.x),0),HA(t,2,MW(i.y),0),YYe(o,1,L8e,t);ZY(r,2,xBe,o)}}this.g.addProtoToStream(r.g(),"mediapipe.tasks.vision.interactive_segmenter.proto.RegionOfInterest","roi_in",n),dk(this,s,a);e:{try{const o=new wBe(this.confidenceMasks,this.categoryMask,this.qualityScores);if(!this.j){var l=o;break e}this.j(o)}finally{xTe(this)}l=void 0}return l}m(){var s=new Aw;Vp(s,"image_in"),Vp(s,"roi_in"),Vp(s,"norm_rect_in");const t=new Cw;$5(t,Lzt,this.h);const n=new Yb;vw(n,2,"mediapipe.tasks.vision.interactive_segmenter.InteractiveSegmenterGraphV2"),rp(n,"IMAGE:image_in"),rp(n,"ROI:roi_in"),rp(n,"NORM_RECT:norm_rect_in"),n.o(t),y2(s,n),fTe(this,s),this.outputConfidenceMasks&&(cu(s,"confidence_masks"),Cd(n,"CONFIDENCE_MASKS:confidence_masks"),YU(this,"confidence_masks"),this.g.aa("confidence_masks",(r,a)=>{this.confidenceMasks=r.map(i=>XU(this,i,!0,!this.j)),lo(this,a)}),this.g.attachEmptyPacketListener("confidence_masks",r=>{this.confidenceMasks=[],lo(this,r)})),this.outputCategoryMask&&(cu(s,"category_mask"),Cd(n,"CATEGORY_MASK:category_mask"),YU(this,"category_mask"),this.g.Z("category_mask",(r,a)=>{this.categoryMask=XU(this,r,!1,!this.j),lo(this,a)}),this.g.attachEmptyPacketListener("category_mask",r=>{this.categoryMask=void 0,lo(this,r)})),cu(s,"quality_scores"),Cd(n,"QUALITY_SCORES:quality_scores"),this.g.attachFloatVectorListener("quality_scores",(r,a)=>{this.qualityScores=r,lo(this,a)}),this.g.attachEmptyPacketListener("quality_scores",r=>{this.categoryMask=void 0,lo(this,r)}),s=s.g(),this.setGraph(new Uint8Array(s),!0)}};$k.prototype.segment=$k.prototype.segment,$k.prototype.setOptions=$k.prototype.o,$k.createFromModelPath=function(s,t){return Vd($k,s,{baseOptions:{modelAssetPath:t}})},$k.createFromModelBuffer=function(s,t){return Vd($k,s,{baseOptions:{modelAssetBuffer:t}})},$k.createFromOptions=function(s,t){return Vd($k,s,t)};var oj=class extends bw{constructor(s,t){super(new ck(s,t),"input_frame_gpu","norm_rect",!1),this.j={detections:[]},al(s=this.h=new Izt,0,1,t=new Af)}get baseOptions(){return Qd(this.h,Af,1)}set baseOptions(s){al(this.h,0,1,s)}o(s){return s.displayNamesLocale!==void 0?oh(this.h,2,ste(s.displayNamesLocale)):"displayNamesLocale"in s&&oh(this.h,2),s.maxResults!==void 0?gC(this.h,3,s.maxResults):"maxResults"in s&&oh(this.h,3),s.scoreThreshold!==void 0?zo(this.h,4,s.scoreThreshold):"scoreThreshold"in s&&oh(this.h,4),s.categoryAllowlist!==void 0?x4e(this.h,5,s.categoryAllowlist):"categoryAllowlist"in s&&oh(this.h,5),s.categoryDenylist!==void 0?x4e(this.h,6,s.categoryDenylist):"categoryDenylist"in s&&oh(this.h,6),this.l(s)}F(s,t){return this.j={detections:[]},dk(this,s,t),this.j}G(s,t,n){return this.j={detections:[]},q5(this,s,n,t),this.j}m(){var s=new Aw;Vp(s,"input_frame_gpu"),Vp(s,"norm_rect"),cu(s,"detections");const t=new Cw;$5(t,_4n,this.h);const n=new Yb;vw(n,2,"mediapipe.tasks.vision.ObjectDetectorGraph"),rp(n,"IMAGE:input_frame_gpu"),rp(n,"NORM_RECT:norm_rect"),Cd(n,"DETECTIONS:detections"),n.o(t),y2(s,n),this.g.attachProtoVectorListener("detections",(r,a)=>{for(const i of r)r=uzt(i),this.j.detections.push(Ozt(r));lo(this,a)}),this.g.attachEmptyPacketListener("detections",r=>{lo(this,r)}),s=s.g(),this.setGraph(new Uint8Array(s),!0)}};oj.prototype.detectForVideo=oj.prototype.G,oj.prototype.detect=oj.prototype.F,oj.prototype.setOptions=oj.prototype.o,oj.createFromModelPath=async function(s,t){return Vd(oj,s,{baseOptions:{modelAssetPath:t}})},oj.createFromModelBuffer=function(s,t){return Vd(oj,s,{baseOptions:{modelAssetBuffer:t}})},oj.createFromOptions=function(s,t){return Vd(oj,s,t)};var jBe=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 f0t(s){s.landmarks=[],s.worldLandmarks=[],s.segmentationMasks=void 0}function x0t(s){try{const t=new jBe(s.landmarks,s.worldLandmarks,s.segmentationMasks);if(!s.u)return t;s.u(t)}finally{xTe(s)}}jBe.prototype.close=jBe.prototype.close;var x_=class extends bw{constructor(s,t){super(new ck(s,t),"image_in","norm_rect",!1),this.landmarks=[],this.worldLandmarks=[],this.outputSegmentationMasks=!1,al(s=this.h=new Dzt,0,1,t=new Af),this.A=new Szt,al(this.h,0,3,this.A),this.j=new kzt,al(this.h,0,2,this.j),gC(this.j,4,1),zo(this.j,2,.5),zo(this.A,2,.5),zo(this.h,4,.5)}get baseOptions(){return Qd(this.h,Af,1)}set baseOptions(s){al(this.h,0,1,s)}o(s){return"numPoses"in s&&gC(this.j,4,s.numPoses??1),"minPoseDetectionConfidence"in s&&zo(this.j,2,s.minPoseDetectionConfidence??.5),"minTrackingConfidence"in s&&zo(this.h,4,s.minTrackingConfidence??.5),"minPosePresenceConfidence"in s&&zo(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,f0t(this),dk(this,s,r),x0t(this)}G(s,t,n,r){const a=typeof n!="function"?n:{};return this.u=typeof n=="function"?n:r,f0t(this),q5(this,s,a,t),x0t(this)}m(){var s=new Aw;Vp(s,"image_in"),Vp(s,"norm_rect"),cu(s,"normalized_landmarks"),cu(s,"world_landmarks"),cu(s,"segmentation_masks");const t=new Cw;$5(t,w4n,this.h);const n=new Yb;vw(n,2,"mediapipe.tasks.vision.pose_landmarker.PoseLandmarkerGraph"),rp(n,"IMAGE:image_in"),rp(n,"NORM_RECT:norm_rect"),Cd(n,"NORM_LANDMARKS:normalized_landmarks"),Cd(n,"WORLD_LANDMARKS:world_landmarks"),n.o(t),y2(s,n),fTe(this,s),this.g.attachProtoVectorListener("normalized_landmarks",(r,a)=>{this.landmarks=[];for(const i of r)r=ate(i),this.landmarks.push(pTe(r));lo(this,a)}),this.g.attachEmptyPacketListener("normalized_landmarks",r=>{this.landmarks=[],lo(this,r)}),this.g.attachProtoVectorListener("world_landmarks",(r,a)=>{this.worldLandmarks=[];for(const i of r)r=mB(i),this.worldLandmarks.push(QY(r));lo(this,a)}),this.g.attachEmptyPacketListener("world_landmarks",r=>{this.worldLandmarks=[],lo(this,r)}),this.outputSegmentationMasks&&(Cd(n,"SEGMENTATION_MASK:segmentation_masks"),YU(this,"segmentation_masks"),this.g.aa("segmentation_masks",(r,a)=>{this.segmentationMasks=r.map(i=>XU(this,i,!0,!this.u)),lo(this,a)}),this.g.attachEmptyPacketListener("segmentation_masks",r=>{this.segmentationMasks=[],lo(this,r)})),s=s.g(),this.setGraph(new Uint8Array(s),!0)}};x_.prototype.detectForVideo=x_.prototype.G,x_.prototype.detect=x_.prototype.F,x_.prototype.setOptions=x_.prototype.o,x_.createFromModelPath=function(s,t){return Vd(x_,s,{baseOptions:{modelAssetPath:t}})},x_.createFromModelBuffer=function(s,t){return Vd(x_,s,{baseOptions:{modelAssetBuffer:t}})},x_.createFromOptions=function(s,t){return Vd(x_,s,t)},x_.POSE_CONNECTIONS=Qzt;let G8=null,LW=null;async function M4n(){return G8||LW||(LW=(async()=>{const s=await f9.forVisionTasks("https://cdn.jsdelivr.net/npm/@mediapipe/tasks-vision@latest/wasm");return G8=await Hv.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}),G8})(),LW)}function L4n(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 P4n(){G8&&(G8.close(),G8=null,LW=null)}function I4n(s,t){const n=j.useRef(null),r=j.useRef(null),a=j.useRef(null),i=j.useRef(null),l=j.useRef(0);j.useRef(0);const[o,c]=j.useState(null),[d,u]=j.useState(!1),[h,m]=j.useState(null),p=t.type!=="none"&&s!==null;return j.useEffect(()=>{if(t.type==="image"&&t.imageUrl){const x=new Image;x.crossOrigin="anonymous",x.src=t.imageUrl,x.onload=()=>{i.current=x}}else i.current=null},[t.type,t.imageUrl]),j.useEffect(()=>{if(!p||!s){a.current&&(a.current.srcObject=null,a.current=null);return}const x=document.createElement("video");return x.srcObject=s,x.muted=!0,x.playsInline=!0,x.autoplay=!0,x.play().catch(()=>{}),a.current=x,()=>{x.srcObject=null,a.current=null}},[p,s]),j.useEffect(()=>{if(!p){c(null),m(null);return}let x=!1;return(async()=>{u(!0),m(null);try{const y=await M4n();if(x)return;u(!1);const b=a.current;if(!b||(await new Promise(je=>{if(b.videoWidth>0)return je();b.onloadedmetadata=()=>je(),setTimeout(je,2e3)}),x))return;const v=b.videoWidth||640,N=b.videoHeight||480,C=n.current;if(!C)return;C.width=v,C.height=N;const A=C.getContext("2d",{willReadFrequently:!1,alpha:!1});r.current||(r.current=document.createElement("canvas"));const T=r.current;T.width=v,T.height=N;const P=T.getContext("2d",{willReadFrequently:!1}),M=document.createElement("canvas");M.width=v,M.height=N;const I=M.getContext("2d",{alpha:!1}),D=document.createElement("canvas");D.width=v,D.height=N;const B=D.getContext("2d",{willReadFrequently:!1}),q=B.createImageData(v,N),W=q.data;for(let je=0;jeV.addTrack(je)),x||c(V);const Q=t.blurRadius??15,J=t.mirror??!1,ce=new Float32Array(v*N),ue=new Float32Array(v*N),ne=new Float32Array(v*N);let ee=!1;const le=4,he=.35,ve=typeof b.requestVideoFrameCallback=="function",ge=()=>{if(x||!a.current)return;const je=a.current;if(je.readyState<2){fe(je);return}try{const Ee=performance.now(),De=y.segmentForVideo(je,Ee).confidenceMasks;if(De&&De.length>0){ue.fill(0);for(let ze=1;ze1?1:Re}}if(L4n(ue,ce,v,N,le),ee)for(let ze=0;ze=1?255:Xe*255|0}if(B.putImageData(q,0,0),t.type==="blur")I.filter=`blur(${Q}px)`,I.drawImage(je,0,0,v,N),I.filter="none",A.drawImage(M,0,0);else if(t.type==="image"&&i.current){const ze=i.current,ke=ze.width/ze.height,Xe=v/N;let Se=0,Re=0,Ae=ze.width,Be=ze.height;ke>Xe?(Ae=ze.height*Xe,Se=(ze.width-Ae)/2):(Be=ze.width/Xe,Re=(ze.height-Be)/2),A.drawImage(ze,Se,Re,Ae,Be,0,0,v,N)}else A.fillStyle="#000",A.fillRect(0,0,v,N);P.globalCompositeOperation="source-over",P.clearRect(0,0,v,N),P.drawImage(je,0,0,v,N),P.globalCompositeOperation="destination-in",P.drawImage(D,0,0),P.globalCompositeOperation="source-over",J?(A.save(),A.translate(v,0),A.scale(-1,1),A.drawImage(T,0,0),A.restore()):A.drawImage(T,0,0);for(const ze of De)ze.close()}else A.drawImage(je,0,0,v,N)}catch{A.drawImage(je,0,0,v,N)}fe(je)},fe=je=>{x||(ve?je.requestVideoFrameCallback(()=>ge()):l.current=requestAnimationFrame(ge))};fe(b)}catch(y){console.error("[useVirtualBackground] init error:",y),x||(u(!1),m(y.message||"Failed to initialize virtual background"))}})(),()=>{x=!0,l.current&&cancelAnimationFrame(l.current),c(null)}},[p,t.type,t.blurRadius,t.imageUrl,s]),j.useEffect(()=>()=>{P4n()},[]),{canvasRef:n,compositedStream:o,isLoading:d,isActive:p,error:h}}function J6({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),x=j.useRef(null),g=j.useRef(null),y=dV(),[b,v]=j.useState("camera"),N=j.useRef(null),C=j.useRef(null),A=j.useRef(null),T=j.useRef(null),P=j.useRef(null),M=j.useRef(null),[I,D]=j.useState(!0),[B,q]=j.useState(!0),[W,V]=j.useState(null),[K,Q]=j.useState(!1),[J,ce]=j.useState(!1),[ue,ne]=j.useState(null),[ee,le]=j.useState(null),[he,ve]=j.useState(0),[ge,fe]=j.useState("user"),[je,Ee]=j.useState(0),[Me,De]=j.useState(!1),[ze,ke]=j.useState(!0),[Xe,Se]=j.useState(null),[Re,Ae]=j.useState(!1),[Be,qe]=j.useState(null),Ke=j.useRef(null),[Ze,Ue]=j.useState(()=>{try{const Sn=localStorage.getItem("video-bg-config");if(Sn)return JSON.parse(Sn)}catch{}return{type:"none"}});j.useEffect(()=>{try{localStorage.setItem("video-bg-config",JSON.stringify(Ze))}catch{}},[Ze]);const[et,Qe]=j.useState([]),[Ge,nt]=j.useState([]),[ft,lt]=j.useState(()=>{try{return localStorage.getItem("video-mic-id")||""}catch{return""}}),[Mt,Ft]=j.useState(()=>{try{return localStorage.getItem("video-cam-id")||""}catch{return""}});j.useEffect(()=>{try{localStorage.setItem("video-mic-id",ft)}catch{}},[ft]),j.useEffect(()=>{try{localStorage.setItem("video-cam-id",Mt)}catch{}},[Mt]),j.useEffect(()=>{var $n,tn,ln;if(!(($n=navigator.mediaDevices)!=null&&$n.enumerateDevices))return;const Sn=async()=>{try{const Cr=await navigator.mediaDevices.enumerateDevices();Qe(Cr.filter(ms=>ms.kind==="audioinput")),nt(Cr.filter(ms=>ms.kind==="videoinput"))}catch(Cr){console.warn("[VideoRecorder] enumerateDevices failed",Cr)}};return Sn(),(ln=(tn=navigator.mediaDevices).addEventListener)==null||ln.call(tn,"devicechange",Sn),()=>{var Cr,ms;return(ms=(Cr=navigator.mediaDevices).removeEventListener)==null?void 0:ms.call(Cr,"devicechange",Sn)}},[W]);const{canvasRef:Ts,compositedStream:js,isLoading:zt,isActive:Nt,error:Ds}=I4n(d,Ze),_t=j.useRef(n);_t.current=n;const Xs=j.useCallback(Sn=>{D(Sn)},[]),rn=j.useRef(I),Ps=j.useCallback(()=>{A.current&&(cancelAnimationFrame(A.current),A.current=null),T.current&&(T.current.terminate(),T.current=null),N.current&&(N.current.getTracks().forEach(Sn=>Sn.stop()),N.current=null),P.current&&(P.current.getTracks().forEach(Sn=>Sn.stop()),P.current=null),M.current&&(M.current.srcObject=null,M.current=null)},[]),_n=j.useCallback(async()=>{var Sn;try{const $n=await navigator.mediaDevices.getDisplayMedia({video:{width:{ideal:1920},height:{ideal:1080}},audio:!0});N.current=$n;let tn=null;try{tn=await navigator.mediaDevices.getUserMedia({video:Mt?{deviceId:{exact:Mt},width:{ideal:320},height:{ideal:240}}:{width:{ideal:320},height:{ideal:240}},audio:!1})}catch{console.warn("[VideoRecorder] No webcam for PiP overlay")}let ln=null;try{ln=await navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0,...ft?{deviceId:{exact:ft}}:{}}}),console.log("[VideoRecorder] mic acquired for screen recording",ln.getAudioTracks().map(Or=>Or.label))}catch(Or){console.warn("[VideoRecorder] No mic audio for screen recording",Or);try{ln=await navigator.mediaDevices.getUserMedia({audio:!0})}catch{}}const Cr=$n.getVideoTracks()[0],ms=Cr.getSettings(),ot=ms.width||1920,pt=ms.height||1080,vt=document.createElement("canvas");vt.width=ot,vt.height=pt,C.current=vt;const At=vt.getContext("2d");let Zt=null;tn&&(Zt=document.createElement("video"),Zt.srcObject=tn,Zt.muted=!0,Zt.playsInline=!0,Zt.autoplay=!0,await Zt.play(),M.current=Zt);const as=document.createElement("video");as.srcObject=$n,as.muted=!0,as.playsInline=!0,as.autoplay=!0,await as.play();const Ls=()=>{if(At.drawImage(as,0,0,ot,pt),Zt&&Zt.readyState>=2){const Or=Math.round(ot*.2),ta=Math.round(Or*(Zt.videoHeight/Zt.videoWidth||.75)),da=ot-Or-20,va=pt-ta-20,hi=12;At.save(),At.beginPath(),At.moveTo(da+hi,va),At.lineTo(da+Or-hi,va),At.quadraticCurveTo(da+Or,va,da+Or,va+hi),At.lineTo(da+Or,va+ta-hi),At.quadraticCurveTo(da+Or,va+ta,da+Or-hi,va+ta),At.lineTo(da+hi,va+ta),At.quadraticCurveTo(da,va+ta,da,va+ta-hi),At.lineTo(da,va+hi),At.quadraticCurveTo(da,va,da+hi,va),At.closePath(),At.clip(),At.translate(da+Or,va),At.scale(-1,1),At.drawImage(Zt,0,0,Or,ta),At.restore(),At.strokeStyle="rgba(255,255,255,0.6)",At.lineWidth=2,At.beginPath(),At.moveTo(da+hi,va),At.lineTo(da+Or-hi,va),At.quadraticCurveTo(da+Or,va,da+Or,va+hi),At.lineTo(da+Or,va+ta-hi),At.quadraticCurveTo(da+Or,va+ta,da+Or-hi,va+ta),At.lineTo(da+hi,va+ta),At.quadraticCurveTo(da,va+ta,da,va+ta-hi),At.lineTo(da,va+hi),At.quadraticCurveTo(da,va,da+hi,va),At.closePath(),At.stroke()}},cs="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}}",qt=new Blob([cs],{type:"application/javascript"}),Gs=new Worker(URL.createObjectURL(qt));T.current=Gs,Gs.onmessage=()=>Ls(),Gs.postMessage({type:"start",fps:30}),Ls();const Vs=vt.captureStream(30),Hn=[],Kr=$n.getAudioTracks();Kr.length&&Hn.push(...Kr),ln&&Hn.push(...ln.getAudioTracks());const ma=new MediaStream([...Vs.getVideoTracks(),...Hn]);return P.current=ma,Cr.onended=()=>{o.current&&o.current.state!=="inactive"&&o.current.stop(),Ps()},ma}catch($n){return console.error("[VideoRecorder] Screen capture error:",$n),$n.name!=="NotAllowedError"&&((Sn=_t.current)==null||Sn.call(_t,"Failed to start screen capture: "+($n.message||"Unknown error"))),null}},[Ps]),Zs=j.useCallback(async()=>{var $n,tn;q(!0),Se(null);const Sn=y&&I;console.log("[VideoRecorder] initCamera start",{isMobile:y,usePortraitMode:I,shouldBePortrait:Sn,facingMode:ge});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(At=>At.stop()));const ln=y&&Sn?{width:{ideal:720},height:{ideal:1280}}:{width:{ideal:1280},height:{ideal:720}},Cr=Mt?{...ln,deviceId:{exact:Mt}}:{...ln,facingMode:{ideal:ge}},ms={echoCancellation:!0,noiseSuppression:!0,...ft?{deviceId:{exact:ft}}:{}};console.log("[VideoRecorder] requesting getUserMedia",Cr);const ot=await navigator.mediaDevices.getUserMedia({video:Cr,audio:ms});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 vt=ot.getVideoTracks()[0].getSettings();if(console.log("[VideoRecorder] Camera initialized with dimensions:",vt.width,"x",vt.height),l.current){const At=l.current;At.srcObject=ot,At.muted=!0,At.playsInline=!0,At.autoplay=!0,At.setAttribute("muted",""),At.setAttribute("playsinline",""),At.setAttribute("autoplay","");try{($n=At.load)==null||$n.call(At)}catch(as){console.warn("[VideoRecorder] videoEl.load failed",as)}const Zt=async()=>{try{return await At.play(),console.log("[VideoRecorder] preview play ok"),Ae(!1),setTimeout(()=>{console.debug("[VideoRecorder] preview metrics",{readyState:At.readyState,videoWidth:At.videoWidth,videoHeight:At.videoHeight})},300),!0}catch(as){return console.warn("[VideoRecorder] preview play blocked",as),Ae(!0),!1}};await new Promise(as=>{let Ls=!1;const cs=()=>{Ls||(Ls=!0,as())},qt=()=>{Zt().finally(cs)};At.onloadedmetadata=qt,At.onloadeddata=qt,setTimeout(cs,1500)})}try{p.current=new AudioContext;const At=p.current.createMediaStreamSource(ot);x.current=p.current.createAnalyser(),x.current.fftSize=256,At.connect(x.current);const Zt=()=>{if(x.current){const as=new Uint8Array(x.current.frequencyBinCount);x.current.getByteFrequencyData(as);const Ls=as.reduce((cs,qt)=>cs+qt)/as.length;Ee(Math.min(100,Ls/128*100))}g.current=requestAnimationFrame(Zt)};Zt()}catch(At){console.warn("Audio context not available:",At)}}catch(ln){console.error("Camera initialization error:",ln),V(!1);let Cr="Failed to access camera or microphone.";ln.name==="NotAllowedError"?Cr="Camera permission denied. Please allow camera access in your browser settings.":ln.name==="NotFoundError"?Cr="No camera found. Please connect a camera and try again.":ln.name==="NotReadableError"?Cr="Camera is in use by another application. Please close other apps using the camera.":ln.message&&(Cr=ln.message),Se(Cr),(tn=_t.current)==null||tn.call(_t,Cr)}finally{q(!1)}},[ge,y,I,ft,Mt]);j.useEffect(()=>{rn.current!==I&&W&&!K&&!ee&&(rn.current=I,Zs())},[I,W,K,ee,Zs]),j.useEffect(()=>(Zs(),()=>{c.current&&c.current.getTracks().forEach(Sn=>Sn.stop()),m.current&&clearInterval(m.current),g.current&&cancelAnimationFrame(g.current),p.current&&p.current.close(),Ke.current&&clearInterval(Ke.current),ee&&URL.revokeObjectURL(ee),Ps()}),[Zs,ee]),j.useEffect(()=>{if(B||W!==!0||ee)return;const Sn=c.current,$n=l.current;!Sn||!$n||Nt||($n.srcObject!==Sn&&($n.srcObject=Sn,$n.muted=!0,$n.playsInline=!0,$n.autoplay=!0,$n.setAttribute("muted",""),$n.setAttribute("playsinline",""),$n.setAttribute("autoplay","")),$n.play().then(()=>Ae(!1)).catch(tn=>{Ae(!0),console.warn("Live preview play blocked on mount:",tn)}))},[W,B,ee,Nt]),j.useEffect(()=>{r==null||r(K)},[K,r]);const gr=j.useCallback(async()=>{if(ee)return;const Sn=l.current;if(Sn)try{await Sn.play(),Ae(!1)}catch($n){Ae(!0),console.warn("Live preview still blocked (needs user gesture):",$n)}},[ee]),Un=j.useCallback(()=>{o.current&&o.current.state!=="inactive"&&o.current.stop(),m.current&&(clearInterval(m.current),m.current=null),Ps(),Q(!1),ce(!1)},[Ps]),In=j.useCallback(async()=>{let Sn=null;if(b==="screen"){if(Sn=await _n(),!Sn)return}else Sn=Nt&&js?js:c.current;if(!Sn)return;gr(),h.current=[],ve(0);const tn=["video/webm;codecs=vp9,opus","video/webm;codecs=vp8,opus","video/webm;codecs=vp9","video/webm;codecs=vp8","video/webm","video/mp4"].find(Cr=>MediaRecorder.isTypeSupported(Cr)),ln=new MediaRecorder(Sn,tn?{mimeType:tn,videoBitsPerSecond:b==="screen"?4e6:25e5}:{videoBitsPerSecond:b==="screen"?4e6:25e5});ln.ondataavailable=Cr=>{Cr.data.size>0&&h.current.push(Cr.data)},ln.onstop=()=>{var pt;const Cr=ln.mimeType||tn||((pt=h.current[0])==null?void 0:pt.type)||"video/webm",ms=new Blob(h.current,{type:Cr});ne(ms);const ot=URL.createObjectURL(ms);le(ot)},o.current=ln,ln.start(100),Q(!0),m.current=setInterval(()=>{ve(Cr=>Cr>=s-1?(Un(),s):Cr+1)},1e3)},[gr,s,Un,Nt,js,b,_n]),Ar=j.useCallback(()=>{Ke.current&&(clearInterval(Ke.current),Ke.current=null),qe(3);let Sn=3;Ke.current=setInterval(()=>{Sn-=1,Sn<=0?(Ke.current&&clearInterval(Ke.current),Ke.current=null,qe(null),In()):qe(Sn)},1e3)},[In]),or=j.useCallback(()=>{o.current&&o.current.state==="recording"&&(o.current.pause(),ce(!0),m.current&&clearInterval(m.current))},[]),qs=j.useCallback(()=>{o.current&&o.current.state==="paused"&&(o.current.resume(),ce(!1),m.current=setInterval(()=>{ve(Sn=>Sn>=s-1?(Un(),s):Sn+1)},1e3))},[s,Un]),yr=j.useCallback(()=>{ee&&URL.revokeObjectURL(ee),ne(null),le(null),ve(0),De(!1),ke(!0),l.current&&c.current&&!Nt&&(l.current.srcObject=c.current,l.current.muted=!0,gr())},[gr,ee,Nt]),fn=j.useCallback(()=>{fe(Sn=>Sn==="user"?"environment":"user")},[]),Zn=j.useCallback(()=>{ue&&t(ue,he)},[ue,he,t]),Xt=j.useCallback(()=>{l.current&&ee&&(Me?l.current.pause():(ke(!1),l.current.muted=!1,l.current.play()),De(!Me))},[ee,Me]);j.useEffect(()=>{if(!ee)return;const Sn=l.current;if(!Sn)return;ke(!1),Sn.pause(),Sn.removeAttribute("src"),Sn.srcObject=null,Sn.load(),Sn.src=ee,Sn.currentTime=0,Sn.playsInline=!0,Sn.muted=!1,Sn.onended=()=>De(!1);const $n=()=>{var Cr;const tn=Sn.error,ln=tn?`Recorded video failed to play (code ${tn.code}). Likely unsupported format/codec in this browser.`:"Recorded video failed to play.";console.warn("[VideoRecorder] recorded playback error",tn),(Cr=_t.current)==null||Cr.call(_t,ln)};return Sn.addEventListener("error",$n),Sn.load(),()=>{Sn.removeEventListener("error",$n)}},[ee]);const rr=Sn=>{const $n=Math.floor(Sn/60),tn=Sn%60;return`${$n}:${tn.toString().padStart(2,"0")}`},Qn=b==="screen"?"aspect-video":y&&I?"aspect-[9/16]":"aspect-video";return B?e.jsx("div",{className:Tt("flex items-center justify-center bg-black rounded-lg",Qn,a),children:e.jsxs("div",{className:"text-center text-white",children:[e.jsx(Ht,{className:"h-12 w-12 animate-spin mx-auto mb-4"}),e.jsx("p",{children:"Initializing camera..."})]})}):W===!1?e.jsx("div",{className:Tt("flex items-center justify-center bg-black rounded-lg",Qn,a),children:e.jsxs("div",{className:"text-center text-white p-8 max-w-md",children:[e.jsx(xo,{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:Xe||"Please allow camera and microphone access to record videos."}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs($,{onClick:()=>Zs(),variant:"secondary",className:"w-full",children:[e.jsx(Wi,{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:Tt("flex flex-col gap-2",a),children:[!K&&!ee&&e.jsxs("div",{className:"flex items-center justify-center gap-1 p-1 bg-muted rounded-lg",children:[e.jsxs($,{variant:b==="camera"?"default":"ghost",size:"sm",className:"gap-1.5 flex-1",onClick:()=>v("camera"),children:[e.jsx(y0,{className:"h-4 w-4"}),"Camera"]}),e.jsxs($,{variant:b==="screen"?"default":"ghost",size:"sm",className:"gap-1.5 flex-1",onClick:()=>v("screen"),children:[e.jsx(wR,{className:"h-4 w-4"}),"Screen"]})]}),b==="camera"&&!K&&!ee&&e.jsx(WSn,{value:Ze,onChange:Ue,isLoading:zt,disabled:K}),!K&&!ee&&(et.length>0||Ge.length>0)&&e.jsxs("div",{className:"flex flex-wrap items-center gap-3 px-3 py-2 bg-muted/40 rounded-lg",children:[et.length>0&&e.jsxs("div",{className:"flex items-center gap-2 flex-1 min-w-[200px]",children:[e.jsx(Vj,{className:"h-4 w-4 text-muted-foreground shrink-0"}),e.jsxs(vs,{value:ft||"default",onValueChange:Sn=>lt(Sn==="default"?"":Sn),children:[e.jsx(gs,{className:"h-8 text-xs",children:e.jsx(bs,{placeholder:"Default microphone"})}),e.jsxs(ys,{children:[e.jsx(Ye,{value:"default",children:"Default microphone"}),et.map(Sn=>e.jsx(Ye,{value:Sn.deviceId,children:Sn.label||`Microphone ${Sn.deviceId.slice(0,6)}`},Sn.deviceId))]})]})]}),Ge.length>1&&b==="camera"&&e.jsxs("div",{className:"flex items-center gap-2 flex-1 min-w-[200px]",children:[e.jsx(y0,{className:"h-4 w-4 text-muted-foreground shrink-0"}),e.jsxs(vs,{value:Mt||"default",onValueChange:Sn=>Ft(Sn==="default"?"":Sn),children:[e.jsx(gs,{className:"h-8 text-xs",children:e.jsx(bs,{placeholder:"Default camera"})}),e.jsxs(ys,{children:[e.jsx(Ye,{value:"default",children:"Default camera"}),Ge.map(Sn=>e.jsx(Ye,{value:Sn.deviceId,children:Sn.label||`Camera ${Sn.deviceId.slice(0,6)}`},Sn.deviceId))]})]})]})]}),b==="camera"&&y&&!K&&!ee&&e.jsxs("div",{className:"flex items-center justify-center gap-3 py-2 bg-muted/50 rounded-lg",children:[e.jsx(Hj,{className:Tt("h-4 w-4",I?"text-muted-foreground":"text-primary")}),e.jsx(se,{htmlFor:"orientation-toggle",className:"text-sm text-muted-foreground",children:"Landscape"}),e.jsx(Tn,{id:"orientation-toggle",checked:I,onCheckedChange:Xs}),e.jsx(se,{htmlFor:"orientation-toggle",className:"text-sm text-muted-foreground",children:"Portrait"}),e.jsx(dv,{className:Tt("h-4 w-4",I?"text-primary":"text-muted-foreground")})]}),b==="screen"&&!K&&!ee&&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(wR,{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:Tt("relative bg-black rounded-lg overflow-hidden"),onPointerDown:()=>{gr()},children:[e.jsx("video",{ref:l,src:ee??void 0,className:Tt("w-full bg-black",I&&!ee?"object-contain":"object-cover",Qn,!ee&&ge==="user"!==(Ze.mirror??!1)&&"scale-x-[-1]",Nt&&!ee&&"hidden"),playsInline:!0,controls:!!ee,muted:ee?ze:!0,autoPlay:!ee},ee??"live"),Nt&&!ee&&e.jsx("canvas",{ref:Ts,className:Tt("w-full bg-black",I?"object-contain":"object-cover",Qn,ge==="user"!==(Ze.mirror??!1)&&"scale-x-[-1]")}),Nt&&zt&&!ee&&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(Ht,{className:"h-8 w-8 animate-spin mx-auto mb-2"}),e.jsx("p",{className:"text-sm",children:"Loading virtual background…"})]})}),!ee&&Re&&e.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-black/40",children:e.jsx($,{type:"button",variant:"secondary",onClick:()=>void gr(),className:"bg-white/20 hover:bg-white/30 text-white",children:"Tap to enable preview"})}),i&&!ee&&e.jsx("div",{className:"absolute inset-0 pointer-events-none",children:i}),Be!==null&&!ee&&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:Be},Be),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:Tt("w-3 h-3 rounded-full",J?"bg-yellow-500":"bg-red-500 animate-pulse")}),e.jsxs("span",{className:"text-white text-sm font-medium",children:[rr(he)," / ",rr(s)]})]}),K&&e.jsx("div",{className:"absolute top-0 left-0 right-0",children:e.jsx(Ki,{value:he/s*100,className:"h-1 rounded-none"})}),!ee&&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(Vj,{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:`${je}%`}})})]}),e.jsx("div",{className:"absolute bottom-4 left-0 right-0 flex justify-center gap-3 px-4",children:ee?e.jsxs(e.Fragment,{children:[e.jsxs($,{variant:"secondary",size:"lg",className:"bg-white/20 hover:bg-white/30 text-white",onClick:yr,children:[e.jsx(Wi,{className:"h-5 w-5 mr-2"}),"Re-record"]}),e.jsx($,{variant:"secondary",size:"icon",className:"h-12 w-12 rounded-full bg-white/20 hover:bg-white/30 text-white",onClick:Xt,children:Me?e.jsx(vy,{className:"h-5 w-5"}):e.jsx(Td,{className:"h-5 w-5"})}),e.jsxs($,{size:"lg",className:"bg-green-500 hover:bg-green-600 text-white",onClick:Zn,children:[e.jsx(oa,{className:"h-5 w-5 mr-2"}),"Use This Video"]})]}):e.jsxs(e.Fragment,{children:[b==="camera"?e.jsx($,{variant:"secondary",size:"icon",className:"h-12 w-12 rounded-full bg-white/20 hover:bg-white/30 text-white",onClick:fn,disabled:K||Be!==null,children:e.jsx(Ih,{className:"h-5 w-5"})}):e.jsx("div",{className:"h-12 w-12"}),!K&&Be===null?e.jsx($,{size:"icon",className:"h-16 w-16 rounded-full bg-red-500 hover:bg-red-600 text-white",onClick:b==="screen"?In:Ar,children:b==="screen"?e.jsx(wR,{className:"h-6 w-6"}):e.jsx(Xr,{className:"h-6 w-6"})}):e.jsxs(e.Fragment,{children:[e.jsx($,{size:"icon",className:"h-12 w-12 rounded-full bg-white/20 hover:bg-white/30 text-white",onClick:J?qs:or,children:J?e.jsx(Td,{className:"h-5 w-5"}):e.jsx(vy,{className:"h-5 w-5"})}),e.jsx($,{size:"icon",className:"h-16 w-16 rounded-full bg-red-500 hover:bg-red-600 text-white",onClick:Un,children:e.jsx(Lb,{className:"h-6 w-6 fill-current"})})]}),e.jsx("div",{className:"h-12 w-12"})]})})]})]})}function D4n({open:s,onOpenChange:t,onUploaded:n}){const{user:r}=_s(),{toast:a}=gi(),[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 U.storage.from("cma-videos").upload(h,c,{contentType:c.type||"video/webm",upsert:!1});if(m)throw m;const{data:p,error:x}=await U.storage.from("cma-videos").createSignedUrl(h,60*60*24*365*5);if(x||!(p!=null&&p.signedUrl))throw x||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(Os,{open:s,onOpenChange:c=>!i&&t(c),children:e.jsxs(Rs,{className:"max-w-2xl",children:[e.jsxs(Us,{children:[e.jsx(zs,{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(Ht,{className:"w-8 h-8 animate-spin text-primary"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Uploading your video…"})]}):e.jsx(J6,{maxDurationSeconds:180,onRecordingComplete:o})]})})}function R4n({value:s,onChange:t}){const{user:n}=_s(),[r,a]=j.useState(!1);return e.jsxs(_e,{children:[e.jsxs(Bt,{children:[e.jsxs(Ut,{className:"text-base flex items-center gap-2",children:[e.jsx(Xr,{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(Oe,{className:"space-y-3",children:[s!=null&&s.url?e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"relative rounded-lg overflow-hidden bg-black aspect-video group",children:[e.jsx("video",{src:s.url,poster:s.thumb,controls:!0,className:"w-full h-full object-cover"}),e.jsx("button",{className:"absolute top-2 right-2 bg-black/60 text-white rounded-full p-1.5 opacity-0 group-hover:opacity-100 transition-opacity",onClick:()=>t(null),"aria-label":"Remove video",type:"button",children:e.jsx(pr,{className:"w-3.5 h-3.5"})})]}),e.jsxs("p",{className:"text-xs text-emerald-700 flex items-center gap-1",children:[e.jsx(Td,{className:"w-3 h-3"})," Video attached"]})]}):e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsx(hF,{userId:n==null?void 0:n.id,triggerLabel:"Pick from Library",triggerVariant:"outline",triggerSize:"default",triggerClassName:"w-full justify-center gap-2",onSelect:()=>{},onSelectVideo:i=>t({url:i.playback_url,thumb:i.thumbnail_url,label:i.title||i.recipient_name})}),e.jsxs($,{variant:"outline",onClick:()=>a(!0),className:"gap-2",children:[e.jsx(Xr,{className:"w-4 h-4"}),"Record New"]})]}),e.jsx(D4n,{open:r,onOpenChange:a,onUploaded:i=>t({url:i,label:"Personal message"})})]})]})}function vN(s){const t=Number(String(s).replace(/[^0-9.]/g,""));return Number.isFinite(t)&&t>0?t:null}function O4n({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:vN(i.bedrooms),bathrooms:vN(i.bathrooms),sqft:vN(i.sqft),yearBuilt:vN(i.yearBuilt),propertyType:i.propertyType||null,propertySubType:i.propertySubType||null}),t(!1)};return e.jsx(Os,{open:s,onOpenChange:t,children:e.jsxs(Rs,{className:"max-w-lg",children:[e.jsx(Us,{children:e.jsx(zs,{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(se,{className:"text-xs",children:"Beds"}),e.jsx(be,{inputMode:"decimal",value:i.bedrooms,onChange:c=>l(d=>({...d,bedrooms:c.target.value})),placeholder:"3"})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-xs",children:"Baths"}),e.jsx(be,{inputMode:"decimal",value:i.bathrooms,onChange:c=>l(d=>({...d,bathrooms:c.target.value})),placeholder:"2"})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-xs",children:"Sq Ft"}),e.jsx(be,{inputMode:"numeric",value:i.sqft,onChange:c=>l(d=>({...d,sqft:c.target.value})),placeholder:"1850"})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-xs",children:"Year Built"}),e.jsx(be,{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(se,{className:"text-xs",children:"Property Type"}),e.jsx(be,{value:i.propertyType,onChange:c=>l(d=>({...d,propertyType:c.target.value})),placeholder:"Residential"})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-xs",children:"Subtype"}),e.jsx(be,{value:i.propertySubType,onChange:c=>l(d=>({...d,propertySubType:c.target.value})),placeholder:"Single Family"})]})]}),e.jsxs($,{className:"w-full",onClick:o,disabled:a,children:[a?e.jsx(Ht,{className:"w-4 h-4 mr-2 animate-spin"}):e.jsx(Jo,{className:"w-4 h-4 mr-2"}),"Save subject details"]})]})]})})}function F4n({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=vN(a.price),c=vN(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:vN(a.bedrooms),bathrooms:vN(a.bathrooms),sqft:c,yearBuilt:vN(a.yearBuilt),photos:[]}),t(!1))};return e.jsx(Os,{open:s,onOpenChange:t,children:e.jsxs(Rs,{className:"max-w-2xl",children:[e.jsx(Us,{children:e.jsx(zs,{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(se,{className:"text-xs",children:"Address"}),e.jsx(be,{value:a.address,onChange:o=>i(c=>({...c,address:o.target.value})),placeholder:"123 Comparable St"})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-xs",children:"City"}),e.jsx(be,{value:a.city,onChange:o=>i(c=>({...c,city:o.target.value}))})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-xs",children:"State"}),e.jsx(be,{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(se,{className:"text-xs",children:"Status"}),e.jsx(be,{value:a.status,onChange:o=>i(c=>({...c,status:o.target.value})),placeholder:"Closed"})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-xs",children:"Price"}),e.jsx(be,{inputMode:"numeric",value:a.price,onChange:o=>i(c=>({...c,price:o.target.value})),placeholder:"525000"})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-xs",children:"Sq Ft"}),e.jsx(be,{inputMode:"numeric",value:a.sqft,onChange:o=>i(c=>({...c,sqft:o.target.value})),placeholder:"1800"})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-xs",children:"Beds"}),e.jsx(be,{inputMode:"decimal",value:a.bedrooms,onChange:o=>i(c=>({...c,bedrooms:o.target.value})),placeholder:"3"})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-xs",children:"Baths"}),e.jsx(be,{inputMode:"decimal",value:a.bathrooms,onChange:o=>i(c=>({...c,bathrooms:o.target.value})),placeholder:"2"})]})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-xs",children:"Year Built"}),e.jsx(be,{className:"max-w-[180px]",inputMode:"numeric",value:a.yearBuilt,onChange:o=>i(c=>({...c,yearBuilt:o.target.value})),placeholder:"2005"})]}),e.jsxs($,{className:"w-full",onClick:l,disabled:!a.address.trim()||!vN(a.price)||!vN(a.sqft),children:[e.jsx(sn,{className:"w-4 h-4 mr-2"}),"Add comp to CMA"]})]})]})})}function z4n(){var fe,je,Ee,Me,De,ze,ke;const{id:s}=Vi(),t=Vn(),{toast:n}=gi(),{data:r,isLoading:a}=Qkn(s),{data:i}=Jkn(s),l=eSn(),o=nSn(),c=rSn(),{leadSite:d,isLoading:u}=Mf(),[h,m]=j.useState([]),[p,x]=j.useState({sqftPct:.2,monthsBack:6,maxMiles:5,statuses:["Active","Pending","Closed"]}),[g,y]=j.useState(null),[b,v]=j.useState(!1),[N,C]=j.useState({low:"",likely:"",high:"",note:""}),[A,T]=j.useState(!1),[P,M]=j.useState(!1),[I,D]=j.useState(!1),[B,q]=j.useState(null),W=async Xe=>{var Ke,Ze;if(!r||!(Xe!=null&&Xe.address)||!(Xe!=null&&Xe.city)||!(Xe!=null&&Xe.state))return Xe;let Se={...Xe};const Re=async Ue=>{const{data:et,error:Qe}=await U.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(Qe)throw Qe;return(et==null?void 0:et.matches)||[]},Ae=Ue=>{const Qe=Ue.find(lt=>Number.isFinite(Number(lt.latitude))&&Number.isFinite(Number(lt.longitude)))||Ue[0];if(!Qe)return;const Ge=typeof Qe.match_type=="string"&&Qe.match_type.startsWith("nearby-"),nt=Ge&&Number.isFinite(Number(Se.latitude))&&Number.isFinite(Number(Se.longitude)),ft=lt=>Qe[lt]!==void 0&&Qe[lt]!==null&&Qe[lt]!==""&&Qe[lt]!==0?Qe[lt]:Se[lt];Se={...Se,bedrooms:ft("bedrooms"),bathrooms:ft("bathrooms"),sqft:ft("sqft"),yearBuilt:ft("yearBuilt"),lotSize:ft("lotSize"),propertyType:ft("propertyType"),propertySubType:ft("propertySubType"),source_provider:Qe.source_provider??Se.source_provider,match_type:Qe.match_type??Se.match_type,matched_mls_address:Ge?Qe.address:Se.matched_mls_address,latitude:nt?Se.latitude:Qe.latitude??Se.latitude,longitude:nt?Se.longitude:Qe.longitude??Se.longitude,mlsNumber:Ge?Se.mlsNumber:Qe.mlsNumber??Se.mlsNumber,photos:!Ge&&Array.isArray(Qe.photos)&&Qe.photos.length?Qe.photos:Se.photos}};Ae(await Re(Se));const Be=()=>Number.isFinite(Number(Se.latitude))&&Number.isFinite(Number(Se.longitude));if(!Be()){const{data:Ue}=await U.from("settings").select("value").eq("key","mapbox_public_token").maybeSingle(),et=Ue==null?void 0:Ue.value;if(et){const Qe=encodeURIComponent(`${Se.address}, ${Se.city}, ${Se.state} ${Se.zip||""}`.trim()),nt=await(await fetch(`https://api.mapbox.com/geocoding/v5/mapbox.places/${Qe}.json?access_token=${et}&limit=1&country=us`)).json(),ft=(Ze=(Ke=nt==null?void 0:nt.features)==null?void 0:Ke[0])==null?void 0:Ze.center;Array.isArray(ft)&&ft.length===2&&(Se.longitude=ft[0],Se.latitude=ft[1])}}if((!Se.bedrooms||!Se.bathrooms||!Se.sqft||!Se.yearBuilt)&&Be())try{Ae(await Re(Se))}catch(Ue){console.warn("second-pass subject lookup failed",Ue)}return JSON.stringify(Se)!==JSON.stringify(Xe)&&await l.mutateAsync({id:r.id,patch:{subject:Se}}),Se};j.useEffect(()=>{var Re,Ae;r!=null&&r.settings&&x({sqftPct:r.settings.sqftPct??.2,monthsBack:r.settings.monthsBack??6,maxMiles:r.settings.maxMiles??5,statuses:r.settings.statuses??["Active","Pending","Closed"]});const Xe=(Re=r==null?void 0:r.settings)==null?void 0:Re.priceOverride;Xe!=null&&Xe.enabled&&(v(!0),C({low:Xe.low!=null?String(Xe.low):"",likely:Xe.likely!=null?String(Xe.likely):"",high:Xe.high!=null?String(Xe.high):"",note:Xe.note??""}));const Se=(Ae=r==null?void 0:r.settings)==null?void 0:Ae.personalVideo;Se!=null&&Se.url&&q({url:Se.url,thumb:Se.thumb,label:Se.label})},[r==null?void 0:r.id]);const V=j.useRef(!1);j.useEffect(()=>{V.current||i!=null&&i.length&&(m(i.map(Xe=>({...Xe.snapshot,selected:Xe.selected,manual:Xe.manual,score:Xe.score}))),V.current=!0)},[i]);const K=j.useRef(null);j.useEffect(()=>{if(!r||u)return;const Xe=r.subject||{},Se=Number.isFinite(Number(Xe.latitude))&&Number.isFinite(Number(Xe.longitude)),Re=!!(Number(Xe.bedrooms)||Number(Xe.bathrooms)||Number(Xe.sqft)||Number(Xe.yearBuilt));if(Se&&Re)return;const Ae=`${r.id}:${(d==null?void 0:d.id)??r.lead_site_id??"no-site"}`;K.current!==Ae&&(!Xe.address||!Xe.city||!Xe.state||(K.current=Ae,(async()=>{try{await W(Xe)}catch(Be){console.warn("subject enrich failed",Be)}})()))},[r==null?void 0:r.id,r==null?void 0:r.lead_site_id,d==null?void 0:d.id,u]);const Q=j.useMemo(()=>r?lgt(r.subject,h):null,[r,h]),J=async()=>{if(r)try{const Xe=await W(r.subject),Se=await o.mutateAsync({subject:Xe,filters:p,leadSiteId:(d==null?void 0:d.id)??r.lead_site_id});m(Se.comps.map(Re=>({...Re,selected:!0})).slice(0,12)),n({title:`Found ${Se.comps.length} comps`,description:`Top ${Math.min(12,Se.comps.length)} auto-selected.`})}catch(Xe){n({title:"Search failed",description:Xe.message,variant:"destructive"})}},ce=Xe=>{m(Se=>Se.map((Re,Ae)=>Ae===Xe?{...Re,selected:!Re.selected}:Re))},ue=Xe=>{m(Se=>Se.filter((Re,Ae)=>Ae!==Xe))},ne=async Xe=>{if(!r)return;const Se=Object.fromEntries(Object.entries(Xe).filter(([,Ae])=>Ae!=null&&Ae!=="")),Re={...r.subject,...Se,manually_enriched:!0};await l.mutateAsync({id:r.id,patch:{subject:Re}}),n({title:"Subject details saved",description:Re.sqft?"You can now find comps or add your own.":"Add square footage to unlock suggested pricing."})},ee=Xe=>{m(Se=>[{...Xe,selected:!0,manual:!0},...Se]),n({title:"Manual comp added"})},le=async(Xe=!1)=>{if(!r)return;const Se=lgt(r.subject,h),Re=Ze=>{const Ue=Number(String(Ze).replace(/[^0-9.]/g,""));return Number.isFinite(Ue)&&Ue>0?Math.round(Ue):null},Ae=b?Re(N.likely):null,Be=b?Re(N.low):null,qe=b?Re(N.high):null,Ke=b&&Ae;await l.mutateAsync({id:r.id,patch:{settings:{...p,priceOverride:{enabled:b,low:Be,likely:Ae,high:qe,note:N.note||null},personalVideo:B},price_low:Ke?Be??Ae:Se.low??null,price_likely:Ke?Ae:Se.likely??null,price_high:Ke?qe??Ae:Se.high??null,status:Xe?"shared":r.status}}),await c.mutateAsync({cmaId:r.id,comps:h}),n({title:Xe?"CMA published":"CMA saved"})},he=r?`https://cma.relevelup.com/${r.share_token}`:"";if(a||!r)return e.jsx(Ks,{children:e.jsx("div",{className:"p-6",children:e.jsx(Ht,{className:"w-6 h-6 animate-spin"})})});const ve=h.filter(Xe=>Xe.selected).length,ge=!((fe=r.subject)!=null&&fe.bedrooms)||!((je=r.subject)!=null&&je.bathrooms)||!((Ee=r.subject)!=null&&Ee.sqft)||!((Me=r.subject)!=null&&Me.yearBuilt);return e.jsx(Ks,{children:e.jsxs("div",{className:"container mx-auto p-4 md:p-6 max-w-7xl",children:[e.jsxs("div",{className:"flex items-center justify-between mb-4 gap-2 flex-wrap",children:[e.jsxs($,{variant:"ghost",size:"sm",onClick:()=>t("/mission-control/cma"),children:[e.jsx(ka,{className:"w-4 h-4 mr-1"})," All CMAs"]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs($,{variant:"outline",onClick:()=>le(!1),disabled:l.isPending,children:[e.jsx(Jo,{className:"w-4 h-4 mr-1"}),"Save"]}),e.jsxs($,{onClick:()=>le(!0),disabled:l.isPending,children:[e.jsx(vd,{className:"w-4 h-4 mr-1"}),"Publish & Share"]}),r.status==="shared"&&e.jsxs(e.Fragment,{children:[e.jsxs($,{variant:"secondary",onClick:()=>{navigator.clipboard.writeText(he),n({title:"Link copied"})},children:[e.jsx(Tr,{className:"w-4 h-4 mr-1"}),"Copy Link"]}),e.jsxs($,{onClick:()=>T(!0),children:[e.jsx(nn,{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(_e,{children:[e.jsx(Bt,{children:e.jsx(Ut,{className:"text-base",children:"Subject Property"})}),e.jsxs(Oe,{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:"})," ",((De=r.subject.sqft)==null?void 0:De.toLocaleString())??"—"]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Year:"})," ",r.subject.yearBuilt??"—"]})]}),ge&&e.jsxs("div",{className:"rounded-lg border border-amber-200 bg-amber-50 p-3 text-amber-950 space-y-2",children:[e.jsx("p",{className:"font-medium",children:"No panic — we can still build this."}),e.jsx("p",{className:"text-xs leading-relaxed",children:"If the MLS/feed does not return beds, baths, sqft, or year, add them manually and LevelUp will use them for comps and pricing."}),e.jsxs($,{size:"sm",variant:"outline",className:"bg-white",onClick:()=>M(!0),children:[e.jsx(Ya,{className:"w-3.5 h-3.5 mr-1"}),"Fill in property details"]})]}),!ge&&e.jsxs($,{size:"sm",variant:"ghost",className:"px-0",onClick:()=>M(!0),children:[e.jsx(Ya,{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(se,{className:"text-xs",children:"Subject SqFt (needed for price band)"}),e.jsx(be,{type:"number",defaultValue:"",onBlur:async Xe=>{const Se=Number(Xe.target.value);Se>0&&await l.mutateAsync({id:r.id,patch:{subject:{...r.subject,sqft:Se}}})}})]})]})]}),e.jsxs(_e,{children:[e.jsx(Bt,{children:e.jsxs(Ut,{className:"text-base flex items-center gap-2",children:[e.jsx(s5,{className:"w-4 h-4"}),"Suggested Price"]})}),e.jsxs(Oe,{className:"space-y-3",children:[Q!=null&&Q.likely?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"text-3xl font-bold",children:["$",(b&&Number(N.likely)>0?Number(N.likely):Q.likely).toLocaleString()]}),e.jsxs("div",{className:"text-xs text-muted-foreground mt-1",children:["Comps suggest: $",(ze=Q.low)==null?void 0:ze.toLocaleString()," – $",(ke=Q.high)==null?void 0:ke.toLocaleString()]}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:["$",Q.ppsf,"/sqft median · ",ve," comps"]})]}):e.jsx("p",{className:"text-sm text-muted-foreground",children:"Add comps with sqft + price to see suggested pricing."}),e.jsxs("div",{className:"pt-3 border-t space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(se,{htmlFor:"override-toggle",className:"text-sm font-medium",children:"Override with my price"}),e.jsx(Tn,{id:"override-toggle",checked:b,onCheckedChange:v})]}),b&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{children:[e.jsx(se,{className:"text-xs",children:"My suggested price"}),e.jsx(be,{type:"number",placeholder:"e.g. 750000",value:N.likely,onChange:Xe=>C(Se=>({...Se,likely:Xe.target.value}))})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsxs("div",{children:[e.jsx(se,{className:"text-xs",children:"Range low"}),e.jsx(be,{type:"number",placeholder:"optional",value:N.low,onChange:Xe=>C(Se=>({...Se,low:Xe.target.value}))})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-xs",children:"Range high"}),e.jsx(be,{type:"number",placeholder:"optional",value:N.high,onChange:Xe=>C(Se=>({...Se,high:Xe.target.value}))})]})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-xs",children:"Why this price (optional)"}),e.jsx(Is,{rows:2,maxLength:500,placeholder:"Notes shown to your client",value:N.note,onChange:Xe=>C(Se=>({...Se,note:Xe.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(R4n,{value:B,onChange:q}),e.jsxs(_e,{children:[e.jsx(Bt,{children:e.jsx(Ut,{className:"text-base",children:"Filters"})}),e.jsxs(Oe,{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsxs(se,{className:"text-xs",children:["SqFt tolerance: ±",Math.round(p.sqftPct*100),"%"]}),e.jsx(rx,{value:[p.sqftPct*100],min:5,max:50,step:5,onValueChange:([Xe])=>x(Se=>({...Se,sqftPct:Xe/100}))})]}),e.jsxs("div",{children:[e.jsxs(se,{className:"text-xs",children:["Search radius: ",p.maxMiles," mi"]}),e.jsx(rx,{value:[p.maxMiles],min:1,max:25,step:1,onValueChange:([Xe])=>x(Se=>({...Se,maxMiles:Xe}))})]}),e.jsxs("div",{children:[e.jsxs(se,{className:"text-xs",children:["Sold within: ",p.monthsBack," months"]}),e.jsx(rx,{value:[p.monthsBack],min:1,max:24,step:1,onValueChange:([Xe])=>x(Se=>({...Se,monthsBack:Xe}))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{className:"text-xs",children:"Status"}),["Active","Pending","Closed"].map(Xe=>e.jsxs("label",{className:"flex items-center gap-2 text-sm",children:[e.jsx(ui,{checked:p.statuses.includes(Xe),onCheckedChange:Se=>x(Re=>({...Re,statuses:Se?[...Re.statuses,Xe]:Re.statuses.filter(Ae=>Ae!==Xe)}))})," ",Xe]},Xe))]}),e.jsxs($,{className:"w-full",onClick:J,disabled:o.isPending,children:[o.isPending?e.jsx(Ht,{className:"w-4 h-4 animate-spin mr-2"}):e.jsx(dn,{className:"w-4 h-4 mr-2"}),"Find Comps"]}),e.jsxs($,{variant:"outline",className:"w-full",onClick:()=>D(!0),children:[e.jsx(sn,{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(VSn,{subject:r.subject,comps:h,radiusMiles:p.maxMiles,onMarkerClick:Xe=>y(Xe)}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("h2",{className:"text-lg font-semibold",children:["Comparables (",h.length,")"]}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[ve," selected"]})]}),h.length?e.jsx("div",{className:"space-y-2",children:h.map((Xe,Se)=>{var Re;return e.jsx(_e,{className:Xe.selected?"":"opacity-50",children:e.jsxs(Oe,{className:"p-3 flex gap-3 items-center",children:[e.jsx(ui,{checked:Xe.selected,onCheckedChange:()=>ce(Se)}),e.jsxs("button",{type:"button",onClick:()=>y(Se),className:"flex gap-3 items-center flex-1 min-w-0 text-left hover:bg-muted/40 -mx-1 px-1 py-1 rounded transition",children:[e.jsx(sSe,{photos:Xe.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:Xe.address}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:[Xe.city,", ",Xe.state," · ",Xe.bedrooms??"?","bd/",Xe.bathrooms??"?","ba · ",((Re=Xe.sqft)==null?void 0:Re.toLocaleString())??"?"," sqft",Xe.yearBuilt?` · ${Xe.yearBuilt}`:""]}),e.jsxs("div",{className:"text-xs mt-0.5",children:[e.jsx($e,{variant:"outline",className:"mr-1",children:Xe.status}),Xe.score!=null&&e.jsxs("span",{className:"text-muted-foreground",children:["Score ",Xe.score]})]})]}),e.jsxs("div",{className:"text-right",children:[e.jsxs("div",{className:"font-semibold",children:["$",(Xe.soldPrice||Xe.price||0).toLocaleString()]}),Xe.sqft&&(Xe.soldPrice||Xe.price)?e.jsxs("div",{className:"text-xs text-muted-foreground",children:["$",Math.round((Xe.soldPrice||Xe.price)/Xe.sqft),"/sqft"]}):null]})]}),e.jsx($,{variant:"ghost",size:"icon",onClick:()=>y(Se),title:"View details",children:e.jsx(ga,{className:"w-4 h-4"})}),e.jsx($,{variant:"ghost",size:"icon",onClick:()=>ue(Se),title:"Remove",children:e.jsx(Pn,{className:"w-4 h-4"})})]})},Se)})}):e.jsx(_e,{children:e.jsx(Oe,{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:[ge&&e.jsx($,{variant:"outline",size:"sm",onClick:()=>M(!0),children:"Fill subject details"}),e.jsx($,{variant:"outline",size:"sm",onClick:()=>D(!0),children:"Add manual comp"})]})]})})})]})]}),e.jsx(WTt,{comp:g!=null?h[g]:null,open:g!=null,onClose:()=>y(null)}),e.jsx(O4n,{open:P,onOpenChange:M,subject:r.subject,onSave:ne,isSaving:l.isPending}),e.jsx(F4n,{open:I,onOpenChange:D,subject:r.subject,onAdd:ee}),e.jsx(Y7t,{open:A,onOpenChange:T,cma:r})]})})}const u6="listing-presentations";function Jzt(){const{user:s}=_s(),t=ts(),n=ht({queryKey:["listing-presentation-saved-templates",s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:o,error:c}=await U.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 U.from("listing_presentation_saved_templates").insert({...o,owner_user_id:s.id}).select().single();if(d)throw d;return c},onSuccess:()=>{r(),ae.success("Template saved")},onError:o=>ae.error(o.message||"Could not save the template")}),i=yt({mutationFn:async({id:o,...c})=>{const{error:d}=await U.from("listing_presentation_saved_templates").update(c).eq("id",o);if(d)throw d},onSuccess:()=>{r(),ae.success("Template updated")},onError:o=>ae.error(o.message||"Could not update the template")}),l=yt({mutationFn:async o=>{const{error:c}=await U.from("listing_presentation_saved_templates").delete().eq("id",o);if(c)throw c},onSuccess:()=>{r(),ae.success("Template deleted")},onError:o=>ae.error(o.message||"Could not delete the template")});return{savedTemplates:n.data??[],isLoading:n.isLoading,save:a,update:i,remove:l}}function B4n(){return ht({queryKey:["listing-presentation-templates"],staleTime:10*60*1e3,queryFn:async()=>{const{data:s,error:t}=await U.from("listing_presentation_templates").select("*").eq("is_active",!0).order("sort_order",{ascending:!0});if(t)throw t;return s}})}function eBt(){const{user:s}=_s(),t=ts(),n=ht({queryKey:["listing-presentations",s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:c,error:d}=await U.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 U.from("listing_presentations").insert({...c,owner_user_id:s.id}).select().single();if(u)throw u;return d},onSuccess:r,onError:c=>ae.error(c.message||"Could not create presentation")}),i=yt({mutationFn:async({id:c,...d})=>{const{data:u,error:h}=await U.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=>ae.error(c.message||"Could not save presentation")}),l=yt({mutationFn:async c=>{let d=null;const{data:u,error:h}=await U.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 U.storage.from(u6).copy(c.property_photo_path,d);m||await U.from("listing_presentations").update({property_photo_path:d}).eq("id",u.id)}return u},onSuccess:()=>{r(),ae.success("Presentation duplicated")},onError:c=>ae.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 U.storage.from(u6).remove(d);const{error:u}=await U.from("listing_presentations").delete().eq("id",c.id);if(u)throw u},onSuccess:()=>{r(),ae.success("Presentation deleted")},onError:c=>ae.error(c.message||"Could not delete")});return{presentations:n.data??[],isLoading:n.isLoading,create:a,update:i,duplicate:l,remove:o}}function $4n(s){return ht({queryKey:["listing-presentation",s],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await U.from("listing_presentations").select("*").eq("id",s).maybeSingle();if(n)throw n;return t}})}async function U4n(s,t=3600){if(!s)return null;const{data:n,error:r}=await U.storage.from(u6).createSignedUrl(s,t);return r?null:(n==null?void 0:n.signedUrl)??null}const q4n="#2a4c64",V4n="#B8965A";function tBt(){const{user:s}=_s();return ht({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([U.from("profiles").select("name, email, phone, avatar_url, website_url, title, brokerage_name, brokerage_id").eq("id",t).maybeSingle(),U.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),U.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 U.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||q4n,accentColor:o.accent_color||V4n,tagline:c.positioning_statement||i.title||c.title||null}}})}const NBe={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."}},H4n={cover:"Cover",welcome:"Marketing commitment",agent:"About your agent",overview:"Marketing plan overview",closing:"Closing commitment"};function sBt(s,t){var i;const n=((i=s==null?void 0:s.copy)==null?void 0:i[t])||{},r=NBe[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 nBt={enabled:!1,name:"",title:null,headshotUrl:null,phone:null,email:null,brokerageName:null,licenseNumber:null,bio:null};function rBt(s){return{...nBt,...s||{}}}const I8e=[{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."}],aBt=()=>typeof crypto<"u"&&"randomUUID"in crypto?crypto.randomUUID():`cp_${Math.random().toString(36).slice(2)}`;function AZe(s,t=0){const n={id:aBt(),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 iBt(s){return Array.isArray(s)?s.filter(t=>t&&typeof t=="object").map((t,n)=>({...AZe(t.layout||"story",n),...t,id:t.id||aBt(),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 kBe={hidden:["overview"]},SBe={x:.5,y:.5},Mc=(s,t,n=!0)=>({key:s,label:t,enabled:n}),_4e=[{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:[Mc("hdr","Full HDR interior and exterior photo set"),Mc("drone","Aerial drone photography of the home and lot"),Mc("twilight","Twilight exterior session for the hero image"),Mc("staging","Virtual staging for vacant or transitional rooms",!1),Mc("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:[Mc("walkthrough","Cinematic full-property walkthrough video"),Mc("reels","Vertical short-form cuts for Reels, Shorts, and TikTok"),Mc("oncamera","On-camera agent introduction to the home"),Mc("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:[Mc("data","Complete, accurate MLS data so your home shows in every filter"),Mc("copy","Copywriting that leads with the features buyers pay for"),Mc("pricing","Pricing built on live comparable and absorption data"),Mc("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:[Mc("zillow","Zillow — the highest-traffic buyer search portal"),Mc("realtor","Realtor.com — direct MLS-sourced listing feed"),Mc("homes","Homes.com — agent-attributed listing exposure"),Mc("others","Redfin, Trulia, Movoto, and hundreds of partner sites"),Mc("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:[Mc("gallery","Full-screen gallery, video, and floor plan in one place"),Mc("mobile","Mobile-first design with a one-tap inquiry form"),Mc("link","Shareable link used across ads, email, and QR signage"),Mc("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:[Mc("organic","Just-listed launch across feed, stories, and reels"),Mc("ads","Geo-targeted paid campaigns aimed at active buyers"),Mc("retarget","Retargeting so interested viewers keep seeing your home"),Mc("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:[Mc("database","Direct email to my buyer and past-client database"),Mc("agents","Broadcast to area agents with matching buyers"),Mc("referral","Referral partner network notified at launch"),Mc("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:[Mc("public","Strategically timed public open houses"),Mc("broker","Broker open house for agents with active buyers"),Mc("signin","Digital sign-in that captures every visitor"),Mc("neighbors","Neighbor invitations and just-listed mailers"),Mc("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:[Mc("weekly","Weekly seller report on the schedule you prefer"),Mc("feedback","Showing feedback delivered as it comes in"),Mc("analytics","Online traffic and engagement analytics"),Mc("access","Direct access to me by call, text, or email")]}],G4n=Object.fromEntries(_4e.map(s=>[s.key,(s.options||[]).map(t=>t.label)]));function CBe(s){return s!=null&&s.length?_4e.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}}):_4e.map(t=>{var n;return{...t,options:(n=t.options)==null?void 0:n.map(r=>({...r}))}})}const W4n={welcome:"Marketing commitment",agent:"About your agent",overview:"Marketing plan overview",closing:"Closing commitment"};function Wu(s){"@babel/helpers - typeof";return Wu=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},Wu(s)}var ZN=Uint8Array,Q_=Uint16Array,EZe=Int32Array,TZe=new ZN([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]),MZe=new ZN([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]),g0t=new ZN([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),oBt=function(s,t){for(var n=new Q_(31),r=0;r<31;++r)n[r]=t+=1<>1|(Nm&21845)<<1;dA=(dA&52428)>>2|(dA&13107)<<2,dA=(dA&61680)>>4|(dA&3855)<<4,EBe[Nm]=((dA&65280)>>8|(dA&255)<<8)>>1}var JY=function(s,t,n){for(var r=s.length,a=0,i=new Q_(t);a>c]=d}else for(o=new Q_(r),a=0;a>15-s[a]);return o},LO=new ZN(288);for(var Nm=0;Nm<144;++Nm)LO[Nm]=8;for(var Nm=144;Nm<256;++Nm)LO[Nm]=9;for(var Nm=256;Nm<280;++Nm)LO[Nm]=7;for(var Nm=280;Nm<288;++Nm)LO[Nm]=8;var w4e=new ZN(32);for(var Nm=0;Nm<32;++Nm)w4e[Nm]=5;var Z4n=JY(LO,9,0),X4n=JY(w4e,5,0),cBt=function(s){return(s+7)/8|0},Q4n=function(s,t,n){return(n==null||n>s.length)&&(n=s.length),new ZN(s.subarray(t,n))},S4=function(s,t,n){n<<=t&7;var r=t/8|0;s[r]|=n,s[r+1]|=n>>8},TG=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},D8e=function(s,t){for(var n=[],r=0;rm&&(m=i[r].s);var p=new Q_(m+1),x=TBe(n[u-1],p,0);if(x>t){var r=0,g=0,y=x-t,b=1<t)g+=b-(1<>=y;g>0;){var N=i[r].s;p[N]=0&&g;--r){var C=i[r].s;p[C]==t&&(--p[C],++g)}x=t}return{t:new ZN(p),l:x}},TBe=function(s,t,n){return s.s==-1?Math.max(TBe(s.l,t,n+1),TBe(s.r,t,n+1)):t[s.s]=n},v0t=function(s){for(var t=s.length;t&&!s[--t];);for(var n=new Q_(++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}},MG=function(s,t){for(var n=0,r=0;r>8,s[a+2]=s[a]^255,s[a+3]=s[a+1]^255;for(var i=0;i4&&!D[g0t[q-1]];--q);var W=d+5<<3,V=MG(a,LO)+MG(i,w4e)+l,K=MG(a,m)+MG(i,g)+l+14+3*q+MG(P,D)+2*P[16]+3*P[17]+7*P[18];if(c>=0&&W<=V&&W<=K)return dBt(t,u,s.subarray(c,c+d));var Q,J,ce,ue;if(S4(t,u,1+(K15&&(S4(t,u,he[M]>>5&127),u+=he[M]>>12)}}else Q=Z4n,J=LO,ce=X4n,ue=w4e;for(var M=0;M255){var ve=ge>>18&31;TG(t,u,Q[ve+257]),u+=J[ve+257],ve>7&&(S4(t,u,ge>>23&31),u+=TZe[ve]);var fe=ge&31;TG(t,u,ce[fe]),u+=ue[fe],fe>3&&(TG(t,u,ge>>5&8191),u+=MZe[fe])}else TG(t,u,Q[ge]),u+=J[ge]}return TG(t,u,Q[256]),u+J[256]},J4n=new EZe([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),uBt=new ZN(0),e3n=function(s,t,n,r,a,i){var l=i.z||s.length,o=new ZN(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=J4n[t-1],m=h>>13,p=h&8191,x=(1<7e3||D>24576)&&(Q>423||!d)){u=b0t(s,c,0,C,A,T,M,D,q,I-q,u),D=P=M=0,q=I;for(var J=0;J<286;++J)A[J]=0;for(var J=0;J<30;++J)T[J]=0}var ce=2,ue=0,ne=p,ee=V-K&32767;if(Q>2&&W==N(I-ee))for(var le=Math.min(m,Q)-1,he=Math.min(32767,I),ve=Math.min(258,Q);ee<=he&&--ne&&V!=K;){if(s[I+ce]==s[I+ce-ee]){for(var ge=0;gece){if(ce=ge,ue=ee,ge>le)break;for(var fe=Math.min(ee,ge-2),je=0,J=0;Jje&&(je=De,K=Ee)}}}V=K,K=g[V],ee+=V-K&32767}if(ue){C[D++]=268435456|ABe[ce]<<18|y0t[ue];var ze=ABe[ce]&31,ke=y0t[ue]&31;M+=TZe[ze]+MZe[ke],++A[257+ze],++T[ke],B=I+ce,++P}else C[D++]=s[I],++A[s[I]]}}for(I=Math.max(I,B);I=l&&(c[u/8|0]=d,Xe=l),u=dBt(c,u+1,s.subarray(I,Xe))}i.i=l}return Q4n(o,0,r+cBt(u)+a)},hBt=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}}},t3n=function(s,t,n,r,a){if(!a&&(a={l:1},t.dictionary)){var i=t.dictionary.subarray(-32768),l=new ZN(i.length+s.length);l.set(i),l.set(s,i.length),s=l,a.w=i.length}return e3n(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)},mBt=function(s,t,n){for(;n;++t)s[t]=n,n>>>=8},s3n=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=hBt();a.p(t.dictionary),mBt(s,2,a.d())}};function MBe(s,t){t||(t={});var n=hBt();n.p(s);var r=t3n(s,t,t.dictionary?6:2,4);return s3n(r,t),mBt(r,r.length-4,n.d()),r}var n3n=typeof TextDecoder<"u"&&new TextDecoder,r3n=0;try{n3n.decode(uBt,{stream:!0}),r3n=1}catch{}function a3n(s){if(Array.isArray(s))return s}function i3n(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 _0t(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])})(),R8e={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 LZe{constructor(t=u3n,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 LZe)&&(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=R8e[n].BYTES_PER_ELEMENT*t,a=this.byteOffset+this.offset,i=this.buffer.slice(a,a+r);if(this.littleEndian===h3n&&n!=="uint8"&&n!=="int8"){const o=new Uint8Array(this.buffer.slice(a,a+r));o.reverse();const c=new R8e[n](o.buffer);return this.offset+=r,c.reverse(),c}const l=new R8e[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 m3n=4,N0t=0,k0t=1,p3n=2;function NV(s){let t=s.length;for(;--t>=0;)s[t]=0}const f3n=0,pBt=1,x3n=2,g3n=3,y3n=258,PZe=29,ite=256,nQ=ite+1+PZe,pB=30,IZe=19,fBt=2*nQ+1,W8=15,O8e=16,v3n=7,DZe=256,xBt=16,gBt=17,yBt=18,LBe=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]),W2e=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]),b3n=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7]),vBt=new Uint8Array([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),_3n=512,J4=new Array((nQ+2)*2);NV(J4);const eZ=new Array(pB*2);NV(eZ);const rQ=new Array(_3n);NV(rQ);const aQ=new Array(y3n-g3n+1);NV(aQ);const RZe=new Array(PZe);NV(RZe);const j4e=new Array(pB);NV(j4e);function F8e(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 bBt,_Bt,wBt;function z8e(s,t){this.dyn_tree=s,this.max_code=0,this.stat_desc=t}const jBt=s=>s<256?rQ[s]:rQ[256+(s>>>7)],iQ=(s,t)=>{s.pending_buf[s.pending++]=t&255,s.pending_buf[s.pending++]=t>>>8&255},Nb=(s,t,n)=>{s.bi_valid>O8e-n?(s.bi_buf|=t<>O8e-s.bi_valid,s.bi_valid+=n-O8e):(s.bi_buf|=t<{Nb(s,n[t*2],n[t*2+1])},NBt=(s,t)=>{let n=0;do n|=s&1,s>>>=1,n<<=1;while(--t>0);return n>>>1},w3n=s=>{s.bi_valid===16?(iQ(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)},j3n=(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,x,g=0;for(m=0;m<=W8;m++)s.bl_count[m]=0;for(n[s.heap[s.heap_max]*2+1]=0,d=s.heap_max+1;dc&&(m=c,g++),n[u*2+1]=m,!(u>r)&&(s.bl_count[m]++,p=0,u>=o&&(p=l[u-o]),x=n[u*2],s.opt_len+=x*(m+p),i&&(s.static_len+=x*(a[u*2+1]+p)));if(g!==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]--,g-=2}while(g>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--)}},kBt=(s,t,n)=>{const r=new Array(W8+1);let a=0,i,l;for(i=1;i<=W8;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]=NBt(r[o]++,o))}},N3n=()=>{let s,t,n,r,a;const i=new Array(W8+1);for(n=0,r=0;r>=7;r{let t;for(t=0;t{s.bi_valid>8?iQ(s,s.bi_buf):s.bi_valid>0&&(s.pending_buf[s.pending++]=s.bi_buf),s.bi_buf=0,s.bi_valid=0},S0t=(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?FS(s,a,t):(l=aQ[a],FS(s,l+ite+1,t),o=LBe[l],o!==0&&(a-=RZe[l],Nb(s,a,o)),r--,l=jBt(r),FS(s,l,n),o=W2e[l],o!==0&&(r-=j4e[l],Nb(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=fBt,l=0;l>1;l>=1;l--)B8e(s,n,l);d=i;do l=s.heap[1],s.heap[1]=s.heap[s.heap_len--],B8e(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++,B8e(s,n,1);while(s.heap_len>=2);s.heap[--s.heap_max]=s.heap[1],j3n(s,t),kBt(n,c,s.bl_count)},A0t=(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(A0t(s,s.dyn_ltree,s.l_desc.max_code),A0t(s,s.dyn_dtree,s.d_desc.max_code),PBe(s,s.bl_desc),t=IZe-1;t>=3&&s.bl_tree[vBt[t]*2+1]===0;t--);return s.opt_len+=3*(t+1)+5+5+4,t},S3n=(s,t,n,r)=>{let a;for(Nb(s,t-257,5),Nb(s,n-1,5),Nb(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 N0t;if(s.dyn_ltree[9*2]!==0||s.dyn_ltree[10*2]!==0||s.dyn_ltree[13*2]!==0)return k0t;for(n=32;n{T0t||(N3n(),T0t=!0),s.l_desc=new z8e(s.dyn_ltree,bBt),s.d_desc=new z8e(s.dyn_dtree,_Bt),s.bl_desc=new z8e(s.bl_tree,wBt),s.bi_buf=0,s.bi_valid=0,SBt(s)},ABt=(s,t,n,r)=>{Nb(s,(f3n<<1)+(r?1:0),3),CBt(s),iQ(s,n),iQ(s,~n),n&&s.pending_buf.set(s.window.subarray(t,t+n),s.pending),s.pending+=n},E3n=s=>{Nb(s,pBt<<1,3),FS(s,DZe,J4),w3n(s)},T3n=(s,t,n,r)=>{let a,i,l=0;s.level>0?(s.strm.data_type===p3n&&(s.strm.data_type=C3n(s)),PBe(s,s.l_desc),PBe(s,s.d_desc),l=k3n(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?ABt(s,t,n,r):s.strategy===m3n||i===a?(Nb(s,(pBt<<1)+(r?1:0),3),C0t(s,J4,eZ)):(Nb(s,(x3n<<1)+(r?1:0),3),S3n(s,s.l_desc.max_code+1,s.d_desc.max_code+1,l+1),C0t(s,s.dyn_ltree,s.dyn_dtree)),SBt(s),r&&CBt(s)},M3n=(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[(aQ[n]+ite+1)*2]++,s.dyn_dtree[jBt(t)*2]++),s.sym_next===s.sym_end);var L3n=A3n,P3n=ABt,I3n=T3n,D3n=M3n,R3n=E3n,O3n={_tr_init:L3n,_tr_stored_block:P3n,_tr_flush_block:I3n,_tr_tally:D3n,_tr_align:R3n};const F3n=(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 oQ=F3n;const z3n=()=>{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},B3n=new Uint32Array(z3n()),$3n=(s,t,n,r)=>{const a=B3n,i=r+n;s^=-1;for(let l=r;l>>8^a[(s^t[l])&255];return s^-1};var l0=$3n,QU={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"},ote={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:U3n,_tr_stored_block:IBe,_tr_flush_block:q3n,_tr_tally:HT,_tr_align:V3n}=O3n,{Z_NO_FLUSH:GT,Z_PARTIAL_FLUSH:H3n,Z_FULL_FLUSH:G3n,Z_FINISH:Mj,Z_BLOCK:M0t,Z_OK:ay,Z_STREAM_END:L0t,Z_STREAM_ERROR:g5,Z_DATA_ERROR:W3n,Z_BUF_ERROR:$8e,Z_DEFAULT_COMPRESSION:K3n,Z_FILTERED:Y3n,Z_HUFFMAN_ONLY:Jre,Z_RLE:Z3n,Z_FIXED:X3n,Z_DEFAULT_STRATEGY:Q3n,Z_UNKNOWN:J3n,Z_DEFLATED:gTe}=ote,eCn=9,tCn=15,sCn=8,nCn=29,rCn=256,DBe=rCn+1+nCn,aCn=30,iCn=19,oCn=2*DBe+1,lCn=15,fd=3,tT=258,y5=tT+fd+1,cCn=32,JU=42,OZe=57,RBe=69,OBe=73,FBe=91,zBe=103,K8=113,PW=666,h1=1,kV=2,PO=3,SV=4,dCn=3,Y8=(s,t)=>(s.msg=QU[t],t),P0t=s=>s*2-(s>4?9:0),aE=s=>{let t=s.length;for(;--t>=0;)s[t]=0},uCn=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 hCn=(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))},J_=(s,t)=>{q3n(s,s.block_start>=0?s.block_start:-1,s.strstart-s.block_start,t),s.block_start=s.strstart,S_(s.strm)},ou=(s,t)=>{s.pending_buf[s.pending++]=t},LG=(s,t)=>{s.pending_buf[s.pending++]=t>>>8&255,s.pending_buf[s.pending++]=t&255},BBe=(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=oQ(s.adler,t,a,n):s.state.wrap===2&&(s.adler=l0(s.adler,t,a,n)),s.next_in+=a,s.total_in+=a,a)},EBt=(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-y5?s.strstart-(s.w_size-y5):0,d=s.window,u=s.w_mask,h=s.prev,m=s.strstart+tT;let p=d[r+l-1],x=d[r+l];s.prev_length>=s.good_match&&(n>>=2),o>s.lookahead&&(o=s.lookahead);do if(a=t,!(d[a+l]!==x||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],x=d[r+l]}}while((t=h[t&u])>c&&--n!==0);return l<=s.lookahead?l:s.lookahead},eq=s=>{const t=s.w_size;let n,r,a;do{if(r=s.window_size-s.lookahead-s.strstart,s.strstart>=t+(t-y5)&&(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),uCn(s),r+=t),s.strm.avail_in===0)break;if(n=BBe(s.strm,s.window,s.strstart+s.lookahead,r),s.lookahead+=n,s.lookahead+s.insert>=fd)for(a=s.strstart-s.insert,s.ins_h=s.window[a],s.ins_h=WT(s,s.ins_h,s.window[a+1]);s.insert&&(s.ins_h=WT(s,s.ins_h,s.window[a+fd-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,S_(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&&(BBe(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&&(BBe(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===Mj)&&t!==GT&&s.strm.avail_in===0&&a<=i)&&(r=a>i?i:a,l=t===Mj&&s.strm.avail_in===0&&r===a?1:0,IBe(s,s.block_start,r,l),s.block_start+=r,S_(s.strm)),l?PO:h1)},U8e=(s,t)=>{let n,r;for(;;){if(s.lookahead=fd&&(s.ins_h=WT(s,s.ins_h,s.window[s.strstart+fd-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-y5&&(s.match_length=EBt(s,n)),s.match_length>=fd)if(r=HT(s,s.strstart-s.match_start,s.match_length-fd),s.lookahead-=s.match_length,s.match_length<=s.max_lazy_match&&s.lookahead>=fd){s.match_length--;do s.strstart++,s.ins_h=WT(s,s.ins_h,s.window[s.strstart+fd-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=WT(s,s.ins_h,s.window[s.strstart+1]);else r=HT(s,0,s.window[s.strstart]),s.lookahead--,s.strstart++;if(r&&(J_(s,!1),s.strm.avail_out===0))return h1}return s.insert=s.strstart{let n,r,a;for(;;){if(s.lookahead=fd&&(s.ins_h=WT(s,s.ins_h,s.window[s.strstart+fd-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=fd-1,n!==0&&s.prev_length4096)&&(s.match_length=fd-1)),s.prev_length>=fd&&s.match_length<=s.prev_length){a=s.strstart+s.lookahead-fd,r=HT(s,s.strstart-1-s.prev_match,s.prev_length-fd),s.lookahead-=s.prev_length-1,s.prev_length-=2;do++s.strstart<=a&&(s.ins_h=WT(s,s.ins_h,s.window[s.strstart+fd-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=fd-1,s.strstart++,r&&(J_(s,!1),s.strm.avail_out===0))return h1}else if(s.match_available){if(r=HT(s,0,s.window[s.strstart-1]),r&&J_(s,!1),s.strstart++,s.lookahead--,s.strm.avail_out===0)return h1}else s.match_available=1,s.strstart++,s.lookahead--}return s.match_available&&(r=HT(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<=tT){if(eq(s),s.lookahead<=tT&&t===GT)return h1;if(s.lookahead===0)break}if(s.match_length=0,s.lookahead>=fd&&s.strstart>0&&(a=s.strstart-1,r=l[a],r===l[++a]&&r===l[++a]&&r===l[++a])){i=s.strstart+tT;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>=fd?(n=HT(s,1,s.match_length-fd),s.lookahead-=s.match_length,s.strstart+=s.match_length,s.match_length=0):(n=HT(s,0,s.window[s.strstart]),s.lookahead--,s.strstart++),n&&(J_(s,!1),s.strm.avail_out===0))return h1}return s.insert=0,t===Mj?(J_(s,!0),s.strm.avail_out===0?PO:SV):s.sym_next&&(J_(s,!1),s.strm.avail_out===0)?h1:kV},pCn=(s,t)=>{let n;for(;;){if(s.lookahead===0&&(eq(s),s.lookahead===0)){if(t===GT)return h1;break}if(s.match_length=0,n=HT(s,0,s.window[s.strstart]),s.lookahead--,s.strstart++,n&&(J_(s,!1),s.strm.avail_out===0))return h1}return s.insert=0,t===Mj?(J_(s,!0),s.strm.avail_out===0?PO:SV):s.sym_next&&(J_(s,!1),s.strm.avail_out===0)?h1:kV};function Uk(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 IW=[new Uk(0,0,0,0,TBt),new Uk(4,4,8,4,U8e),new Uk(4,5,16,8,U8e),new Uk(4,6,32,32,U8e),new Uk(4,4,16,16,z7),new Uk(8,16,32,32,z7),new Uk(8,16,128,128,z7),new Uk(8,32,128,256,z7),new Uk(32,128,258,1024,z7),new Uk(32,258,258,4096,z7)],fCn=s=>{s.window_size=2*s.w_size,aE(s.head),s.max_lazy_match=IW[s.level].max_lazy,s.good_match=IW[s.level].good_length,s.nice_match=IW[s.level].nice_length,s.max_chain_length=IW[s.level].max_chain,s.strstart=0,s.block_start=0,s.lookahead=0,s.insert=0,s.match_length=s.prev_length=fd-1,s.match_available=0,s.ins_h=0};function xCn(){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=gTe,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(oCn*2),this.dyn_dtree=new Uint16Array((2*aCn+1)*2),this.bl_tree=new Uint16Array((2*iCn+1)*2),aE(this.dyn_ltree),aE(this.dyn_dtree),aE(this.bl_tree),this.l_desc=null,this.d_desc=null,this.bl_desc=null,this.bl_count=new Uint16Array(lCn+1),this.heap=new Uint16Array(2*DBe+1),aE(this.heap),this.heap_len=0,this.heap_max=0,this.depth=new Uint16Array(2*DBe+1),aE(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 lte=s=>{if(!s)return 1;const t=s.state;return!t||t.strm!==s||t.status!==JU&&t.status!==OZe&&t.status!==RBe&&t.status!==OBe&&t.status!==FBe&&t.status!==zBe&&t.status!==K8&&t.status!==PW?1:0},MBt=s=>{if(lte(s))return Y8(s,g5);s.total_in=s.total_out=0,s.data_type=J3n;const t=s.state;return t.pending=0,t.pending_out=0,t.wrap<0&&(t.wrap=-t.wrap),t.status=t.wrap===2?OZe:t.wrap?JU:K8,s.adler=t.wrap===2?0:1,t.last_flush=-2,U3n(t),ay},LBt=s=>{const t=MBt(s);return t===ay&&fCn(s.state),t},gCn=(s,t)=>lte(s)||s.state.wrap!==2?g5:(s.state.gzhead=t,ay),PBt=(s,t,n,r,a,i)=>{if(!s)return g5;let l=1;if(t===K3n&&(t=6),r<0?(l=0,r=-r):r>15&&(l=2,r-=16),a<1||a>eCn||n!==gTe||r<8||r>15||t<0||t>9||i<0||i>X3n||r===8&&l!==1)return Y8(s,g5);r===8&&(r=9);const o=new xCn;return s.state=o,o.strm=s,o.status=JU,o.wrap=l,o.gzhead=null,o.w_bits=r,o.w_size=1<PBt(s,t,gTe,tCn,sCn,Q3n),vCn=(s,t)=>{if(lte(s)||t>M0t||t<0)return s?Y8(s,g5):g5;const n=s.state;if(!s.output||s.avail_in!==0&&!s.input||n.status===PW&&t!==Mj)return Y8(s,s.avail_out===0?$8e:g5);const r=n.last_flush;if(n.last_flush=t,n.pending!==0){if(S_(s),s.avail_out===0)return n.last_flush=-1,ay}else if(s.avail_in===0&&P0t(t)<=P0t(r)&&t!==Mj)return Y8(s,$8e);if(n.status===PW&&s.avail_in!==0)return Y8(s,$8e);if(n.status===JU&&n.wrap===0&&(n.status=K8),n.status===JU){let a=gTe+(n.w_bits-8<<4)<<8,i=-1;if(n.strategy>=Jre||n.level<2?i=0:n.level<6?i=1:n.level===6?i=2:i=3,a|=i<<6,n.strstart!==0&&(a|=cCn),a+=31-a%31,LG(n,a),n.strstart!==0&&(LG(n,s.adler>>>16),LG(n,s.adler&65535)),s.adler=1,n.status=K8,S_(s),n.pending!==0)return n.last_flush=-1,ay}if(n.status===OZe){if(s.adler=0,ou(n,31),ou(n,139),ou(n,8),n.gzhead)ou(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)),ou(n,n.gzhead.time&255),ou(n,n.gzhead.time>>8&255),ou(n,n.gzhead.time>>16&255),ou(n,n.gzhead.time>>24&255),ou(n,n.level===9?2:n.strategy>=Jre||n.level<2?4:0),ou(n,n.gzhead.os&255),n.gzhead.extra&&n.gzhead.extra.length&&(ou(n,n.gzhead.extra.length&255),ou(n,n.gzhead.extra.length>>8&255)),n.gzhead.hcrc&&(s.adler=l0(s.adler,n.pending_buf,n.pending,0)),n.gzindex=0,n.status=RBe;else if(ou(n,0),ou(n,0),ou(n,0),ou(n,0),ou(n,0),ou(n,n.level===9?2:n.strategy>=Jre||n.level<2?4:0),ou(n,dCn),n.status=K8,S_(s),n.pending!==0)return n.last_flush=-1,ay}if(n.status===RBe){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=l0(s.adler,n.pending_buf,n.pending-a,a)),n.gzindex+=o,S_(s),n.pending!==0)return n.last_flush=-1,ay;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=l0(s.adler,n.pending_buf,n.pending-a,a)),n.gzindex=0}n.status=OBe}if(n.status===OBe){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=l0(s.adler,n.pending_buf,n.pending-a,a)),S_(s),n.pending!==0)return n.last_flush=-1,ay;a=0}n.gzindexa&&(s.adler=l0(s.adler,n.pending_buf,n.pending-a,a)),n.gzindex=0}n.status=FBe}if(n.status===FBe){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=l0(s.adler,n.pending_buf,n.pending-a,a)),S_(s),n.pending!==0)return n.last_flush=-1,ay;a=0}n.gzindexa&&(s.adler=l0(s.adler,n.pending_buf,n.pending-a,a))}n.status=zBe}if(n.status===zBe){if(n.gzhead.hcrc){if(n.pending+2>n.pending_buf_size&&(S_(s),n.pending!==0))return n.last_flush=-1,ay;ou(n,s.adler&255),ou(n,s.adler>>8&255),s.adler=0}if(n.status=K8,S_(s),n.pending!==0)return n.last_flush=-1,ay}if(s.avail_in!==0||n.lookahead!==0||t!==GT&&n.status!==PW){let a=n.level===0?TBt(n,t):n.strategy===Jre?pCn(n,t):n.strategy===Z3n?mCn(n,t):IW[n.level].func(n,t);if((a===PO||a===SV)&&(n.status=PW),a===h1||a===PO)return s.avail_out===0&&(n.last_flush=-1),ay;if(a===kV&&(t===H3n?V3n(n):t!==M0t&&(IBe(n,0,0,!1),t===G3n&&(aE(n.head),n.lookahead===0&&(n.strstart=0,n.block_start=0,n.insert=0))),S_(s),s.avail_out===0))return n.last_flush=-1,ay}return t!==Mj?ay:n.wrap<=0?L0t:(n.wrap===2?(ou(n,s.adler&255),ou(n,s.adler>>8&255),ou(n,s.adler>>16&255),ou(n,s.adler>>24&255),ou(n,s.total_in&255),ou(n,s.total_in>>8&255),ou(n,s.total_in>>16&255),ou(n,s.total_in>>24&255)):(LG(n,s.adler>>>16),LG(n,s.adler&65535)),S_(s),n.wrap>0&&(n.wrap=-n.wrap),n.pending!==0?ay:L0t)},bCn=s=>{if(lte(s))return g5;const t=s.state.status;return s.state=null,t===K8?Y8(s,W3n):ay},_Cn=(s,t)=>{let n=t.length;if(lte(s))return g5;const r=s.state,a=r.wrap;if(a===2||a===1&&r.status!==JU||r.lookahead)return g5;if(a===1&&(s.adler=oQ(s.adler,t,n,0)),r.wrap=0,n>=r.w_size){a===0&&(aE(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,eq(r);r.lookahead>=fd;){let c=r.strstart,d=r.lookahead-(fd-1);do r.ins_h=WT(r,r.ins_h,r.window[c+fd-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=fd-1,eq(r)}return r.strstart+=r.lookahead,r.block_start=r.strstart,r.insert=r.lookahead,r.lookahead=0,r.match_length=r.prev_length=fd-1,r.match_available=0,s.next_in=l,s.input=o,s.avail_in=i,r.wrap=a,ay};var wCn=yCn,jCn=PBt,NCn=LBt,kCn=MBt,SCn=gCn,CCn=vCn,ACn=bCn,ECn=_Cn,TCn="pako deflate (from Nodeca project)",tZ={deflateInit:wCn,deflateInit2:jCn,deflateReset:NCn,deflateResetKeep:kCn,deflateSetHeader:SCn,deflate:CCn,deflateEnd:ACn,deflateSetDictionary:ECn,deflateInfo:TCn};const MCn=(s,t)=>Object.prototype.hasOwnProperty.call(s,t);var LCn=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)MCn(n,r)&&(s[r]=n[r])}}return s},PCn=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;lQ[254]=lQ[254]=1;var ICn=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 DCn=(s,t)=>{if(t<65534&&s.subarray&&IBt)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 DCn(i,a)},OCn=(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+lQ[s[n]]>t?n:t},cQ={string2buf:ICn,buf2string:RCn,utf8border:OCn};function FCn(){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 DBt=FCn;const RBt=Object.prototype.toString,{Z_NO_FLUSH:zCn,Z_SYNC_FLUSH:BCn,Z_FULL_FLUSH:$Cn,Z_FINISH:UCn,Z_OK:N4e,Z_STREAM_END:qCn,Z_DEFAULT_COMPRESSION:VCn,Z_DEFAULT_STRATEGY:HCn,Z_DEFLATED:GCn}=ote;function FZe(s){this.options=yTe.assign({level:VCn,method:GCn,chunkSize:16384,windowBits:15,memLevel:8,strategy:HCn},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 DBt,this.strm.avail_out=0;let n=tZ.deflateInit2(this.strm,t.level,t.method,t.windowBits,t.memLevel,t.strategy);if(n!==N4e)throw new Error(QU[n]);if(t.header&&tZ.deflateSetHeader(this.strm,t.header),t.dictionary){let r;if(typeof t.dictionary=="string"?r=cQ.string2buf(t.dictionary):RBt.call(t.dictionary)==="[object ArrayBuffer]"?r=new Uint8Array(t.dictionary):r=t.dictionary,n=tZ.deflateSetDictionary(this.strm,r),n!==N4e)throw new Error(QU[n]);this._dict_set=!0}}FZe.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?UCn:zCn,typeof s=="string"?n.input=cQ.string2buf(s):RBt.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===BCn||i===$Cn)&&n.avail_out<=6){this.onData(n.output.subarray(0,n.next_out)),n.avail_out=0;continue}if(a=tZ.deflate(n,i),a===qCn)return n.next_out>0&&this.onData(n.output.subarray(0,n.next_out)),a=tZ.deflateEnd(this.strm),this.onEnd(a),this.ended=!0,a===N4e;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};FZe.prototype.onData=function(s){this.chunks.push(s)};FZe.prototype.onEnd=function(s){s===N4e&&(this.result=yTe.flattenChunks(this.chunks)),this.chunks=[],this.err=s,this.msg=this.strm.msg};const eae=16209,WCn=16191;var KCn=function(t,n){let r,a,i,l,o,c,d,u,h,m,p,x,g,y,b,v,N,C,A,T,P,M,I,D;const B=t.state;r=t.next_in,I=t.input,a=r+(t.avail_in-5),i=t.next_out,D=t.output,l=i-(n-t.avail_out),o=i+(t.avail_out-257),c=B.dmax,d=B.wsize,u=B.whave,h=B.wnext,m=B.window,p=B.hold,x=B.bits,g=B.lencode,y=B.distcode,b=(1<>>24,p>>>=C,x-=C,C=N>>>16&255,C===0)D[i++]=N&65535;else if(C&16){A=N&65535,C&=15,C&&(x>>=C,x-=C),x<15&&(p+=I[r++]<>>24,p>>>=C,x-=C,C=N>>>16&255,C&16){if(T=N&65535,C&=15,xc){t.msg="invalid distance too far back",B.mode=eae;break e}if(p>>>=C,x-=C,C=i-l,T>C){if(C=T-C,C>u&&B.sane){t.msg="invalid distance too far back",B.mode=eae;break e}if(P=0,M=m,h===0){if(P+=d-C,C2;)D[i++]=M[P++],D[i++]=M[P++],D[i++]=M[P++],A-=3;A&&(D[i++]=M[P++],A>1&&(D[i++]=M[P++]))}else{P=i-T;do D[i++]=D[P++],D[i++]=D[P++],D[i++]=D[P++],A-=3;while(A>2);A&&(D[i++]=D[P++],A>1&&(D[i++]=D[P++]))}}else if(C&64){t.msg="invalid distance code",B.mode=eae;break e}else{N=y[(N&65535)+(p&(1<>3,r-=A,x-=A<<3,p&=(1<{const c=o.bits;let d=0,u=0,h=0,m=0,p=0,x=0,g=0,y=0,b=0,v=0,N,C,A,T,P,M=null,I;const D=new Uint16Array(B7+1),B=new Uint16Array(B7+1);let q=null,W,V,K;for(d=0;d<=B7;d++)D[d]=0;for(u=0;u=1&&D[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===R0t||m!==1))return-1;for(B[1]=0,d=1;dI0t||s===O0t&&b>D0t)return 1;for(;;){W=d-g,l[u]+1=I?(V=q[l[u]-I],K=M[l[u]-I]):(V=96,K=0),N=1<>g)+C]=W<<24|V<<16|K|0;while(C!==0);for(N=1<>=1;if(N!==0?(v&=N-1,v+=N):v=0,u++,--D[d]===0){if(d===m)break;d=t[n+l[u]]}if(d>p&&(v&T)!==A){for(g===0&&(g=p),P+=h,x=d-g,y=1<I0t||s===O0t&&b>D0t)return 1;A=v&T,a[A]=p<<24|x<<16|P-i|0}}return v!==0&&(a[P+v]=d-g<<24|64<<16|0),o.bits=p,0};var sZ=JCn;const eAn=0,OBt=1,FBt=2,{Z_FINISH:F0t,Z_BLOCK:tAn,Z_TREES:tae,Z_OK:IO,Z_STREAM_END:sAn,Z_NEED_DICT:nAn,Z_STREAM_ERROR:l2,Z_DATA_ERROR:zBt,Z_MEM_ERROR:BBt,Z_BUF_ERROR:rAn,Z_DEFLATED:z0t}=ote,vTe=16180,B0t=16181,$0t=16182,U0t=16183,q0t=16184,V0t=16185,H0t=16186,G0t=16187,W0t=16188,K0t=16189,k4e=16190,C4=16191,V8e=16192,Y0t=16193,H8e=16194,Z0t=16195,X0t=16196,Q0t=16197,J0t=16198,sae=16199,nae=16200,eyt=16201,tyt=16202,syt=16203,nyt=16204,ryt=16205,G8e=16206,ayt=16207,iyt=16208,Vm=16209,$Bt=16210,UBt=16211,aAn=852,iAn=592,oAn=15,lAn=oAn,oyt=s=>(s>>>24&255)+(s>>>8&65280)+((s&65280)<<8)+((s&255)<<24);function cAn(){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 xF=s=>{if(!s)return 1;const t=s.state;return!t||t.strm!==s||t.modeUBt?1:0},qBt=s=>{if(xF(s))return l2;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=vTe,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(aAn),t.distcode=t.distdyn=new Int32Array(iAn),t.sane=1,t.back=-1,IO},VBt=s=>{if(xF(s))return l2;const t=s.state;return t.wsize=0,t.whave=0,t.wnext=0,qBt(s)},HBt=(s,t)=>{let n;if(xF(s))return l2;const r=s.state;return t<0?(n=0,t=-t):(n=(t>>4)+5,t<48&&(t&=15)),t&&(t<8||t>15)?l2:(r.window!==null&&r.wbits!==t&&(r.window=null),r.wrap=n,r.wbits=t,VBt(s))},GBt=(s,t)=>{if(!s)return l2;const n=new cAn;s.state=n,n.strm=s,n.window=null,n.mode=vTe;const r=HBt(s,t);return r!==IO&&(s.state=null),r},dAn=s=>GBt(s,lAn);let lyt=!0,W8e,K8e;const uAn=s=>{if(lyt){W8e=new Int32Array(512),K8e=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(sZ(OBt,s.lens,0,288,W8e,0,s.work,{bits:9}),t=0;t<32;)s.lens[t++]=5;sZ(FBt,s.lens,0,32,K8e,0,s.work,{bits:5}),lyt=!1}s.lencode=W8e,s.lenbits=9,s.distcode=K8e,s.distbits=5},WBt=(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,x,g,y=0,b,v,N,C,A,T,P,M;const I=new Uint8Array(4);let D,B;const q=new Uint8Array([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]);if(xF(s)||!s.output||!s.input&&s.avail_in!==0)return l2;n=s.state,n.mode===C4&&(n.mode=V8e),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=IO;e:for(;;)switch(n.mode){case vTe:if(n.wrap===0){n.mode=V8e;break}for(;u<16;){if(o===0)break e;o--,d+=r[i++]<>>8&255,n.check=l0(n.check,I,2,0),d=0,u=0,n.mode=B0t;break}if(n.head&&(n.head.done=!1),!(n.wrap&1)||(((d&255)<<8)+(d>>8))%31){s.msg="incorrect header check",n.mode=Vm;break}if((d&15)!==z0t){s.msg="unknown compression method",n.mode=Vm;break}if(d>>>=4,u-=4,P=(d&15)+8,n.wbits===0&&(n.wbits=P),P>15||P>n.wbits){s.msg="invalid window size",n.mode=Vm;break}n.dmax=1<>8&1),n.flags&512&&n.wrap&4&&(I[0]=d&255,I[1]=d>>>8&255,n.check=l0(n.check,I,2,0)),d=0,u=0,n.mode=$0t;case $0t: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=l0(n.check,I,4,0)),d=0,u=0,n.mode=U0t;case U0t: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=l0(n.check,I,2,0)),d=0,u=0,n.mode=q0t;case q0t:if(n.flags&1024){for(;u<16;){if(o===0)break e;o--,d+=r[i++]<>>8&255,n.check=l0(n.check,I,2,0)),d=0,u=0}else n.head&&(n.head.extra=null);n.mode=V0t;case V0t:if(n.flags&1024&&(p=n.length,p>o&&(p=o),p&&(n.head&&(P=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),P)),n.flags&512&&n.wrap&4&&(n.check=l0(n.check,r,p,i)),o-=p,i+=p,n.length-=p),n.length))break e;n.length=0,n.mode=H0t;case H0t:if(n.flags&2048){if(o===0)break e;p=0;do P=r[i+p++],n.head&&P&&n.length<65536&&(n.head.name+=String.fromCharCode(P));while(P&&p>9&1,n.head.done=!0),s.adler=n.check=0,n.mode=C4;break;case K0t:for(;u<32;){if(o===0)break e;o--,d+=r[i++]<>>=u&7,u-=u&7,n.mode=G8e;break}for(;u<3;){if(o===0)break e;o--,d+=r[i++]<>>=1,u-=1,d&3){case 0:n.mode=Y0t;break;case 1:if(uAn(n),n.mode=sae,t===tae){d>>>=2,u-=2;break e}break;case 2:n.mode=X0t;break;case 3:s.msg="invalid block type",n.mode=Vm}d>>>=2,u-=2;break;case Y0t: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=Vm;break}if(n.length=d&65535,d=0,u=0,n.mode=H8e,t===tae)break e;case H8e:n.mode=Z0t;case Z0t: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=C4;break;case X0t: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=Vm;break}n.have=0,n.mode=Q0t;case Q0t:for(;n.have>>=3,u-=3}for(;n.have<19;)n.lens[q[n.have++]]=0;if(n.lencode=n.lendyn,n.lenbits=7,D={bits:n.lenbits},M=sZ(eAn,n.lens,0,19,n.lencode,0,n.work,D),n.lenbits=D.bits,M){s.msg="invalid code lengths set",n.mode=Vm;break}n.have=0,n.mode=J0t;case J0t:for(;n.have>>24,v=y>>>16&255,N=y&65535,!(b<=u);){if(o===0)break e;o--,d+=r[i++]<>>=b,u-=b,n.lens[n.have++]=N;else{if(N===16){for(B=b+2;u>>=b,u-=b,n.have===0){s.msg="invalid bit length repeat",n.mode=Vm;break}P=n.lens[n.have-1],p=3+(d&3),d>>>=2,u-=2}else if(N===17){for(B=b+3;u>>=b,u-=b,P=0,p=3+(d&7),d>>>=3,u-=3}else{for(B=b+7;u>>=b,u-=b,P=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=Vm;break}for(;p--;)n.lens[n.have++]=P}}if(n.mode===Vm)break;if(n.lens[256]===0){s.msg="invalid code -- missing end-of-block",n.mode=Vm;break}if(n.lenbits=9,D={bits:n.lenbits},M=sZ(OBt,n.lens,0,n.nlen,n.lencode,0,n.work,D),n.lenbits=D.bits,M){s.msg="invalid literal/lengths set",n.mode=Vm;break}if(n.distbits=6,n.distcode=n.distdyn,D={bits:n.distbits},M=sZ(FBt,n.lens,n.nlen,n.ndist,n.distcode,0,n.work,D),n.distbits=D.bits,M){s.msg="invalid distances set",n.mode=Vm;break}if(n.mode=sae,t===tae)break e;case sae:n.mode=nae;case nae: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,KCn(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===C4&&(n.back=-1);break}for(n.back=0;y=n.lencode[d&(1<>>24,v=y>>>16&255,N=y&65535,!(b<=u);){if(o===0)break e;o--,d+=r[i++]<>C)],b=y>>>24,v=y>>>16&255,N=y&65535,!(C+b<=u);){if(o===0)break e;o--,d+=r[i++]<>>=C,u-=C,n.back+=C}if(d>>>=b,u-=b,n.back+=b,n.length=N,v===0){n.mode=ryt;break}if(v&32){n.back=-1,n.mode=C4;break}if(v&64){s.msg="invalid literal/length code",n.mode=Vm;break}n.extra=v&15,n.mode=eyt;case eyt:if(n.extra){for(B=n.extra;u>>=n.extra,u-=n.extra,n.back+=n.extra}n.was=n.length,n.mode=tyt;case tyt:for(;y=n.distcode[d&(1<>>24,v=y>>>16&255,N=y&65535,!(b<=u);){if(o===0)break e;o--,d+=r[i++]<>C)],b=y>>>24,v=y>>>16&255,N=y&65535,!(C+b<=u);){if(o===0)break e;o--,d+=r[i++]<>>=C,u-=C,n.back+=C}if(d>>>=b,u-=b,n.back+=b,v&64){s.msg="invalid distance code",n.mode=Vm;break}n.offset=N,n.extra=v&15,n.mode=syt;case syt:if(n.extra){for(B=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=Vm;break}n.mode=nyt;case nyt: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=Vm;break}p>n.wnext?(p-=n.wnext,x=n.wsize-p):x=n.wnext-p,p>n.length&&(p=n.length),g=n.window}else g=a,x=l-n.offset,p=n.length;p>c&&(p=c),c-=p,n.length-=p;do a[l++]=g[x++];while(--p);n.length===0&&(n.mode=nae);break;case ryt:if(c===0)break e;a[l++]=n.length,c--,n.mode=nae;break;case G8e:if(n.wrap){for(;u<32;){if(o===0)break e;o--,d|=r[i++]<{if(xF(s))return l2;let t=s.state;return t.window&&(t.window=null),s.state=null,IO},pAn=(s,t)=>{if(xF(s))return l2;const n=s.state;return n.wrap&2?(n.head=t,t.done=!1,IO):l2},fAn=(s,t)=>{const n=t.length;let r,a,i;return xF(s)||(r=s.state,r.wrap!==0&&r.mode!==k4e)?l2:r.mode===k4e&&(a=1,a=oQ(a,t,n,0),a!==r.check)?zBt:(i=WBt(s,t,n,n),i?(r.mode=$Bt,BBt):(r.havedict=1,IO))};var xAn=VBt,gAn=HBt,yAn=qBt,vAn=dAn,bAn=GBt,_An=hAn,wAn=mAn,jAn=pAn,NAn=fAn,kAn="pako inflate (from Nodeca project)",e3={inflateReset:xAn,inflateReset2:gAn,inflateResetKeep:yAn,inflateInit:vAn,inflateInit2:bAn,inflate:_An,inflateEnd:wAn,inflateGetHeader:jAn,inflateSetDictionary:NAn,inflateInfo:kAn};function SAn(){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 CAn=SAn;const KBt=Object.prototype.toString,{Z_NO_FLUSH:AAn,Z_FINISH:EAn,Z_OK:dQ,Z_STREAM_END:Y8e,Z_NEED_DICT:Z8e,Z_STREAM_ERROR:TAn,Z_DATA_ERROR:cyt,Z_MEM_ERROR:MAn}=ote;function cte(s){this.options=yTe.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 DBt,this.strm.avail_out=0;let n=e3.inflateInit2(this.strm,t.windowBits);if(n!==dQ)throw new Error(QU[n]);if(this.header=new CAn,e3.inflateGetHeader(this.strm,this.header),t.dictionary&&(typeof t.dictionary=="string"?t.dictionary=cQ.string2buf(t.dictionary):KBt.call(t.dictionary)==="[object ArrayBuffer]"&&(t.dictionary=new Uint8Array(t.dictionary)),t.raw&&(n=e3.inflateSetDictionary(this.strm,t.dictionary),n!==dQ)))throw new Error(QU[n])}cte.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?EAn:AAn,KBt.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=e3.inflate(n,l),i===Z8e&&a&&(i=e3.inflateSetDictionary(n,a),i===dQ?i=e3.inflate(n,l):i===cyt&&(i=Z8e));n.avail_in>0&&i===Y8e&&n.state.wrap>0&&s[n.next_in]!==0;)e3.inflateReset(n),i=e3.inflate(n,l);switch(i){case TAn:case cyt:case Z8e:case MAn:return this.onEnd(i),this.ended=!0,!1}if(o=n.avail_out,n.next_out&&(n.avail_out===0||i===Y8e))if(this.options.to==="string"){let c=cQ.utf8border(n.output,n.next_out),d=n.next_out-c,u=cQ.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===dQ&&o===0)){if(i===Y8e)return i=e3.inflateEnd(this.strm),this.onEnd(i),this.ended=!0,!0;if(n.avail_in===0)break}}return!0};cte.prototype.onData=function(s){this.chunks.push(s)};cte.prototype.onEnd=function(s){s===dQ&&(this.options.to==="string"?this.result=this.chunks.join(""):this.result=yTe.flattenChunks(this.chunks)),this.chunks=[],this.err=s,this.msg=this.strm.msg};function zZe(s,t){const n=new cte(t);if(n.push(s),n.err)throw n.msg||QU[n.err];return n.result}function LAn(s,t){return t=t||{},t.raw=!0,zZe(s,t)}var PAn=cte,IAn=zZe,DAn=LAn,RAn=zZe,OAn=ote,FAn={Inflate:PAn,inflate:IAn,inflateRaw:DAn,ungzip:RAn,constants:OAn};const{Inflate:zAn,inflate:BAn,inflateRaw:SQn,ungzip:CQn}=FAn;var dyt=zAn,$An=BAn;const YBt=[];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;YBt[s]=t}const uyt=4294967295;function UAn(s,t,n){let r=s;for(let a=0;a>>8;return r}function qAn(s,t){return(UAn(uyt,s,t)^uyt)>>>0}function hyt(s,t,n){const r=s.readUint32(),a=qAn(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 ZBt(s,t,n){for(let r=0;r>1)&255}else{for(;i>1)&255;for(;i>1)&255}}function e$t(s,t,n,r,a){let i=0;if(n.length===0){for(;i=n||T>=r))for(let P=0;P>8&255}const XAn=new Uint16Array([255]),QAn=new Uint8Array(XAn.buffer),JAn=QAn[0]===255,eEn=new Uint8Array(0);function myt(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=eEn,u=0,h,m;for(let p=0;p>8&255}const K2e=Uint8Array.of(137,80,78,71,13,10,26,10);function pyt(s){if(!sEn(s.readBytes(K2e.length)))throw new Error("wrong PNG signature")}function sEn(s){if(s.length79)throw new Error("keyword length must be between 1 and 79")}const iEn=/^[\u0000-\u00FF]*$/;function oEn(s){if(!iEn.test(s))throw new Error("invalid latin1 text")}function lEn(s,t,n){const r=s$t(t);s[r]=cEn(t,n-r.length-1)}function s$t(s){for(s.mark();s.readByte()!==rEn;);const t=s.offset;s.reset();const n=t$t.decode(s.readBytes(t-s.offset-1));return s.skip(1),aEn(n),n}function cEn(s,t){return t$t.decode(s.readBytes(t))}const g_={UNKNOWN:-1,GREYSCALE:0,TRUECOLOUR:2,INDEXED_COLOUR:3,GREYSCALE_ALPHA:4,TRUECOLOUR_ALPHA:6},X8e={UNKNOWN:-1,DEFLATE:0},fyt={UNKNOWN:-1,ADAPTIVE:0},Q8e={UNKNOWN:-1,NO_INTERLACE:0,ADAM7:1},rae={NONE:0,BACKGROUND:1,PREVIOUS:2},J8e={SOURCE:0,OVER:1};class dEn extends LZe{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 dyt,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=X8e.UNKNOWN,this._filterMethod=fyt.UNKNOWN,this._interlaceMethod=Q8e.UNKNOWN,this._colorType=g_.UNKNOWN,this._isAnimated=!1,this._numberOfFrames=1,this._numberOfPlays=0,this._frames=[],this._writingDataChunks=!1,this.setBigEndian()}decode(){for(pyt(this);!this._end;){const n=this.readUint32(),r=this.readChars(4);this.decodeChunk(n,r)}return this.decodeImage(),this._png}decodeApng(){for(pyt(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 nEn:lEn(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?hyt(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?hyt(this,n+4,r):this.skip(4)}decodeIHDR(){const n=this._png;n.width=this.readUint32(),n.height=this.readUint32(),n.depth=uEn(this.readUint8());const r=this.readUint8();this._colorType=r;let a;switch(r){case g_.GREYSCALE:a=1;break;case g_.TRUECOLOUR:a=3;break;case g_.INDEXED_COLOUR:a=1;break;case g_.GREYSCALE_ALPHA:a=2;break;case g_.TRUECOLOUR_ALPHA:a=4;break;case g_.UNKNOWN:default:throw new Error(`Unknown color type: ${r}`)}if(this._png.channels=a,this._compressionMethod=this.readUint8(),this._compressionMethod!==X8e.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 J8e.SOURCE:for(let l=0;l=200&&t.status<=299}function aae(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 u8=El.saveAs||((typeof window>"u"?"undefined":Wu(window))!=="object"||window!==El?function(){}:typeof HTMLAnchorElement<"u"&&"download"in HTMLAnchorElement.prototype?function(s,t,n){var r=El.URL||El.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?gyt(a.href)?tDe(s,t,n):aae(a,a.target="_blank"):aae(a)):(a.href=r.createObjectURL(s),setTimeout(function(){r.revokeObjectURL(a.href)},4e4),setTimeout(function(){aae(a)},0))}:"msSaveOrOpenBlob"in navigator?function(s,t,n){if(t=t||s.name||"download",typeof s=="string")if(gyt(s))tDe(s,t,n);else{var r=document.createElement("a");r.href=s,r.target="_blank",setTimeout(function(){aae(r)})}else navigator.msSaveOrOpenBlob(function(a,i){return i===void 0?i={autoBom:!1}:Wu(i)!=="object"&&(jh.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 tDe(s,t,n);var a=s.type==="application/octet-stream",i=/constructor/i.test(El.HTMLElement)||El.safari,l=/CriOS\/[\d]+/.test(navigator.userAgent);if((l||a&&i)&&(typeof FileReader>"u"?"undefined":Wu(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=El.URL||El.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 n$t(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 Y2e=El.atob.bind(El),yyt=El.btoa.bind(El);/** * @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 sDe(s,t){var n=s[0],r=s[1],a=s[2],i=s[3];n=qy(n,r,a,i,t[0],7,-680876936),i=qy(i,n,r,a,t[1],12,-389564586),a=qy(a,i,n,r,t[2],17,606105819),r=qy(r,a,i,n,t[3],22,-1044525330),n=qy(n,r,a,i,t[4],7,-176418897),i=qy(i,n,r,a,t[5],12,1200080426),a=qy(a,i,n,r,t[6],17,-1473231341),r=qy(r,a,i,n,t[7],22,-45705983),n=qy(n,r,a,i,t[8],7,1770035416),i=qy(i,n,r,a,t[9],12,-1958414417),a=qy(a,i,n,r,t[10],17,-42063),r=qy(r,a,i,n,t[11],22,-1990404162),n=qy(n,r,a,i,t[12],7,1804603682),i=qy(i,n,r,a,t[13],12,-40341101),a=qy(a,i,n,r,t[14],17,-1502002290),n=Vy(n,r=qy(r,a,i,n,t[15],22,1236535329),a,i,t[1],5,-165796510),i=Vy(i,n,r,a,t[6],9,-1069501632),a=Vy(a,i,n,r,t[11],14,643717713),r=Vy(r,a,i,n,t[0],20,-373897302),n=Vy(n,r,a,i,t[5],5,-701558691),i=Vy(i,n,r,a,t[10],9,38016083),a=Vy(a,i,n,r,t[15],14,-660478335),r=Vy(r,a,i,n,t[4],20,-405537848),n=Vy(n,r,a,i,t[9],5,568446438),i=Vy(i,n,r,a,t[14],9,-1019803690),a=Vy(a,i,n,r,t[3],14,-187363961),r=Vy(r,a,i,n,t[8],20,1163531501),n=Vy(n,r,a,i,t[13],5,-1444681467),i=Vy(i,n,r,a,t[2],9,-51403784),a=Vy(a,i,n,r,t[7],14,1735328473),n=Hy(n,r=Vy(r,a,i,n,t[12],20,-1926607734),a,i,t[5],4,-378558),i=Hy(i,n,r,a,t[8],11,-2022574463),a=Hy(a,i,n,r,t[11],16,1839030562),r=Hy(r,a,i,n,t[14],23,-35309556),n=Hy(n,r,a,i,t[1],4,-1530992060),i=Hy(i,n,r,a,t[4],11,1272893353),a=Hy(a,i,n,r,t[7],16,-155497632),r=Hy(r,a,i,n,t[10],23,-1094730640),n=Hy(n,r,a,i,t[13],4,681279174),i=Hy(i,n,r,a,t[0],11,-358537222),a=Hy(a,i,n,r,t[3],16,-722521979),r=Hy(r,a,i,n,t[6],23,76029189),n=Hy(n,r,a,i,t[9],4,-640364487),i=Hy(i,n,r,a,t[12],11,-421815835),a=Hy(a,i,n,r,t[15],16,530742520),n=Gy(n,r=Hy(r,a,i,n,t[2],23,-995338651),a,i,t[0],6,-198630844),i=Gy(i,n,r,a,t[7],10,1126891415),a=Gy(a,i,n,r,t[14],15,-1416354905),r=Gy(r,a,i,n,t[5],21,-57434055),n=Gy(n,r,a,i,t[12],6,1700485571),i=Gy(i,n,r,a,t[3],10,-1894986606),a=Gy(a,i,n,r,t[10],15,-1051523),r=Gy(r,a,i,n,t[1],21,-2054922799),n=Gy(n,r,a,i,t[8],6,1873313359),i=Gy(i,n,r,a,t[15],10,-30611744),a=Gy(a,i,n,r,t[6],15,-1560198380),r=Gy(r,a,i,n,t[13],21,1309151649),n=Gy(n,r,a,i,t[4],6,-145523070),i=Gy(i,n,r,a,t[11],10,-1120210379),a=Gy(a,i,n,r,t[2],15,718787259),r=Gy(r,a,i,n,t[9],21,-343485551),s[0]=sT(n,s[0]),s[1]=sT(r,s[1]),s[2]=sT(a,s[2]),s[3]=sT(i,s[3])}function bTe(s,t,n,r,a,i){return t=sT(sT(t,s),sT(r,i)),sT(t<>>32-a,n)}function qy(s,t,n,r,a,i,l){return bTe(t&n|~t&r,s,t,a,i,l)}function Vy(s,t,n,r,a,i,l){return bTe(t&r|n&~r,s,t,a,i,l)}function Hy(s,t,n,r,a,i,l){return bTe(t^n^r,s,t,a,i,l)}function Gy(s,t,n,r,a,i,l){return bTe(n^(t|~r),s,t,a,i,l)}function r$t(s){var t,n=s.length,r=[1732584193,-271733879,-1732584194,271733878];for(t=64;t<=s.length;t+=64)sDe(r,mEn(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(sDe(r,a),t=0;t<16;t++)a[t]=0;return a[14]=8*n,sDe(r,a),r}function mEn(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 vyt="0123456789abcdef".split("");function pEn(s){for(var t="",n=0;n<4;n++)t+=vyt[s>>8*n+4&15]+vyt[s>>8*n&15];return t}function fEn(s){return String.fromCharCode(255&s,(65280&s)>>8,(16711680&s)>>16,(4278190080&s)>>24)}function $Be(s){return r$t(s).map(fEn).join("")}var xEn=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 UBe(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,x="";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=$Be(i+this.O+this.lsbFirstWord(this.P)+this.hexToBytes(r)).substr(0,5),this.U=UBe(this.encryptionKey,this.padding)}function g9(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 _yt(s){if(Wu(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){El.console&&jh.error("jsPDF PubSub Error",o.message,o)}l[1]&&a.push(i)}a.length&&a.forEach(this.unsubscribe)}},this.getTopics=function(){return t}}function S4e(s){if(!(this instanceof S4e))return new S4e(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 a$t(s,t){this.gState=s,this.matrix=t,this.id="",this.objectNumber=-1}function j8(s,t,n,r,a){if(!(this instanceof j8))return new j8(s,t,n,r,a);this.type=s==="axial"?2:3,this.coords=t,this.colors=n,a$t.call(this,r,a)}function sz(s,t,n,r,a){if(!(this instanceof sz))return new sz(s,t,n,r,a);this.boundingBox=s,this.xStep=t,this.yStep=n,this.stream="",this.cloneIndex=0,a$t.call(this,r,a)}function go(s){var t,n=typeof arguments[0]=="string"?arguments[0]:"p",r=arguments[1],a=arguments[2],i=arguments[3],l=[],o=1,c=16,d="S",u=null;Wu(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=_yt;var x="1.3",g=p.__private__.getPdfVersion=function(){return x};p.__private__.setPdfVersion=function(at){x=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 b=p.__private__.getPageFormat=function(at){return y[at]};a=a||"a4";var v="compat",N="advanced",C=v;function A(){this.saveGraphicsState(),Re(new Zn(Ts,0,0,-Ts,0,om()*Ts).toString()+" cm"),this.setFontSize(this.getFontSize()/Ts),d="n",C=N}function T(){this.restoreGraphicsState(),d="S",C=v}var P=p.__private__.combineFontStyleAndFontWeight=function(at,Wt){if(at=="bold"&&Wt=="normal"||at=="bold"&&Wt==400||at=="normal"&&Wt=="italic"||at=="bold"&&Wt=="italic")throw new Error("Invalid Combination of fontweight and fontstyle");return Wt&&(at=Wt==400||Wt==="normal"?at==="italic"?"italic":"normal":Wt!=700&&Wt!=="bold"||at!=="normal"?(Wt==700?"bold":Wt)+""+at:"bold"),at};p.advancedAPI=function(at){var Wt=C===v;return Wt&&A.call(this),typeof at!="function"||(at(this),Wt&&T.call(this)),this},p.compatAPI=function(at){var Wt=C===N;return Wt&&T.call(this),typeof at!="function"||(at(this),Wt&&A.call(this)),this},p.isAdvancedAPI=function(){return C===N};var M,I=function(at){if(C!==N)throw new Error(at+" is only available in 'advanced' API mode. You need to call advancedAPI() first.")},D=p.roundToPrecision=p.__private__.roundToPrecision=function(at,Wt){var Bs=t||Wt;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 D(at,c)}:c==="smart"?function(at){if(isNaN(at))throw new Error("Invalid argument passed to jsPDF.hpf");return D(at,at>-1&&at<1?16:5)}:function(at){if(isNaN(at))throw new Error("Invalid argument passed to jsPDF.hpf");return D(at,16)};var B=p.f2=p.__private__.f2=function(at){if(isNaN(at))throw new Error("Invalid argument passed to jsPDF.f2");return D(at,2)},q=p.__private__.f3=function(at){if(isNaN(at))throw new Error("Invalid argument passed to jsPDF.f3");return D(at,3)},W=p.scale=p.__private__.scale=function(at){if(isNaN(at))throw new Error("Invalid argument passed to jsPDF.scale");return C===v?at*Ts:C===N?at:void 0},V=function(at){return W(function(Wt){return C===v?om()-Wt:C===N?Wt:void 0}(at))};p.__private__.setPrecision=p.setPrecision=function(at){typeof parseInt(at,10)=="number"&&(t=parseInt(at,10))};var K,Q="00000000000000000000000000000000",J=p.__private__.getFileId=function(){return Q},ce=p.__private__.setFileId=function(at){return Q=at!==void 0&&/^[a-fA-F0-9]{32}$/.test(at)?at.toUpperCase():Q.split("").map(function(){return"ABCDEF0123456789".charAt(Math.floor(16*Math.random()))}).join(""),u!==null&&(vo=new x9(u.userPermissions,u.userPassword,u.ownerPassword,Q)),Q};p.setFileId=function(at){return ce(at),this},p.getFileId=function(){return J()};var ue=p.__private__.convertDateToPDFDate=function(at){var Wt=at.getTimezoneOffset(),Bs=Wt<0?"+":"-",Ys=Math.floor(Math.abs(Wt/60)),jn=Math.abs(Wt%60),Ir=[Bs,ve(Ys),"'",ve(jn),"'"].join("");return["D:",at.getFullYear(),ve(at.getMonth()+1),ve(at.getDate()),ve(at.getHours()),ve(at.getMinutes()),ve(at.getSeconds()),Ir].join("")},ne=p.__private__.convertPDFDateToDate=function(at){var Wt=parseInt(at.substr(2,4),10),Bs=parseInt(at.substr(6,2),10)-1,Ys=parseInt(at.substr(8,2),10),jn=parseInt(at.substr(10,2),10),Ir=parseInt(at.substr(12,2),10),kt=parseInt(at.substr(14,2),10);return new Date(Wt,Bs,Ys,jn,Ir,kt,0)},ee=p.__private__.setCreationDate=function(at){var Wt;if(at===void 0&&(at=new Date),at instanceof Date)Wt=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");Wt=at}return K=Wt},le=p.__private__.getCreationDate=function(at){var Wt=K;return at==="jsDate"&&(Wt=ne(K)),Wt};p.setCreationDate=function(at){return ee(at),this},p.getCreationDate=function(at){return le(at)};var he,ve=p.__private__.padd2=function(at){return("0"+parseInt(at)).slice(-2)},ge=p.__private__.padd2Hex=function(at){return("00"+(at=at.toString())).substr(at.length)},fe=0,je=[],Ee=[],Me=0,De=[],ze=[],ke=!1,Xe=Ee;p.__private__.setCustomOutputDestination=function(at){ke=!0,Xe=at};var Se=function(at){ke||(Xe=at)};p.__private__.resetCustomOutputDestination=function(){ke=!1,Xe=Ee};var Re=p.__private__.out=function(at){return at=at.toString(),Me+=at.length+1,Xe.push(at),Xe},Ae=p.__private__.write=function(at){return Re(arguments.length===1?at.toString():Array.prototype.join.call(arguments," "))},Be=p.__private__.getArrayBuffer=function(at){for(var Wt=at.length,Bs=new ArrayBuffer(Wt),Ys=new Uint8Array(Bs);Wt--;)Ys[Wt]=at.charCodeAt(Wt);return Bs},qe=[["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 qe};var Ke=s.fontSize||16;p.__private__.setFontSize=p.setFontSize=function(at){return Ke=C===N?at/Ts:at,this};var Ze,Ue=p.__private__.getFontSize=p.getFontSize=function(){return C===v?Ke:Ke*Ts},et=s.R2L||!1;p.__private__.setR2L=p.setR2L=function(at){return et=at,this},p.__private__.getR2L=p.getR2L=function(){return et};var Qe,Ge=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 nt,ft=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.');Qe=at};p.__private__.getPageMode=function(){return Qe};var lt=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.');nt=at};p.__private__.getLayoutMode=function(){return nt},p.__private__.setDisplayMode=p.setDisplayMode=function(at,Wt,Bs){return Ge(at),lt(Wt),ft(Bs),this};var Mt={title:"",subject:"",author:"",keywords:"",creator:""};p.__private__.getDocumentProperty=function(at){if(Object.keys(Mt).indexOf(at)===-1)throw new Error("Invalid argument passed to jsPDF.getDocumentProperty");return Mt[at]},p.__private__.getDocumentProperties=function(){return Mt},p.__private__.setDocumentProperties=p.setProperties=p.setDocumentProperties=function(at){for(var Wt in Mt)Mt.hasOwnProperty(Wt)&&at[Wt]&&(Mt[Wt]=at[Wt]);return this},p.__private__.setDocumentProperty=function(at,Wt){if(Object.keys(Mt).indexOf(at)===-1)throw new Error("Invalid arguments passed to jsPDF.setDocumentProperty");return Mt[at]=Wt};var Ft,Ts,js,zt,Nt,Ds={},_t={},Xs=[],rn={},Ps={},_n={},Zs={},gr=null,Un=0,In=[],Ar=new _yt(p),or=s.hotfixes||[],qs={},yr={},fn=[],Zn=function at(Wt,Bs,Ys,jn,Ir,kt){if(!(this instanceof at))return new at(Wt,Bs,Ys,jn,Ir,kt);isNaN(Wt)&&(Wt=1),isNaN(Bs)&&(Bs=0),isNaN(Ys)&&(Ys=0),isNaN(jn)&&(jn=1),isNaN(Ir)&&(Ir=0),isNaN(kt)&&(kt=0),this._matrix=[Wt,Bs,Ys,jn,Ir,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 Wt=at.sx*this.sx+at.shy*this.shx,Bs=at.sx*this.shy+at.shy*this.sy,Ys=at.shx*this.sx+at.sy*this.shx,jn=at.shx*this.shy+at.sy*this.sy,Ir=at.tx*this.sx+at.ty*this.shx+this.tx,kt=at.tx*this.shy+at.ty*this.sy+this.ty;return new Zn(Wt,Bs,Ys,jn,Ir,kt)},Zn.prototype.decompose=function(){var at=this.sx,Wt=this.shy,Bs=this.shx,Ys=this.sy,jn=this.tx,Ir=this.ty,kt=Math.sqrt(at*at+Wt*Wt),Cs=(at/=kt)*Bs+(Wt/=kt)*Ys;Bs-=at*Cs,Ys-=Wt*Cs;var xn=Math.sqrt(Bs*Bs+Ys*Ys);return Cs/=xn,at*(Ys/=xn)>16&255,Ys=xn>>8&255,jn=255&xn}if(Ys===void 0||Ir===void 0&&Bs===Ys&&Ys===jn)Wt=typeof Bs=="string"?Bs+" "+kt[0]:at.precision===2?B(Bs/255)+" "+kt[0]:q(Bs/255)+" "+kt[0];else if(Ir===void 0||Wu(Ir)==="object"){if(Ir&&!isNaN(Ir.a)&&Ir.a===0)return["1.","1.","1.",kt[1]].join(" ");Wt=typeof Bs=="string"?[Bs,Ys,jn,kt[1]].join(" "):at.precision===2?[B(Bs/255),B(Ys/255),B(jn/255),kt[1]].join(" "):[q(Bs/255),q(Ys/255),q(jn/255),kt[1]].join(" ")}else Wt=typeof Bs=="string"?[Bs,Ys,jn,Ir,kt[2]].join(" "):at.precision===2?[B(Bs),B(Ys),B(jn),B(Ir),kt[2]].join(" "):[q(Bs),q(Ys),q(jn),q(Ir),kt[2]].join(" ");return Wt},At=p.__private__.getFilters=function(){return l},Zt=p.__private__.putStream=function(at){var Wt=(at=at||{}).data||"",Bs=at.filters||At(),Ys=at.alreadyAppliedFilters||[],jn=at.addLength1||!1,Ir=Wt.length,kt=at.objectId,Cs=function(ri){return ri};if(u!==null&&kt===void 0)throw new Error("ObjectId must be passed to putStream for file encryption");u!==null&&(Cs=vo.encryptor(kt,0));var xn={};Bs===!0&&(Bs=["FlateEncode"]);var Rr=at.additionalKeyValues||[],Dr=(xn=go.API.processDataByFilters!==void 0?go.API.processDataByFilters(Wt,Bs):{data:Wt,reverseChain:[]}).reverseChain+(Array.isArray(Ys)?Ys.join(" "):Ys.toString());if(xn.data.length!==0&&(Rr.push({key:"Length",value:xn.data.length}),jn===!0&&Rr.push({key:"Length1",value:Ir})),Dr.length!=0)if(Dr.split("/").length-1==1)Rr.push({key:"Filter",value:Dr});else{Rr.push({key:"Filter",value:"["+Dr+"]"});for(var Aa=0;Aa>"),xn.data.length!==0&&(Re("stream"),Re(Cs(xn.data)),Re("endstream"))},as=p.__private__.putPage=function(at){var Wt=at.number,Bs=at.data,Ys=at.objId,jn=at.contentsObjId;ln(Ys,!0),Re("<>"),Re("endobj");var Ir=Bs.join(` `);return C===N&&(Ir+=` Q`),ln(jn,!0),Zt({data:Ir,filters:At(),objectId:jn}),Re("endobj"),Ys},Ls=p.__private__.putPages=function(){var at,Wt,Bs=[];for(at=1;at<=Un;at++)In[at].objId=tn(),In[at].contentsObjId=tn();for(at=1;at<=Un;at++)Bs.push(as({number:at,data:ze[at],objId:In[at].objId,contentsObjId:In[at].contentsObjId,mediaBox:In[at].mediaBox,cropBox:In[at].cropBox,bleedBox:In[at].bleedBox,trimBox:In[at].trimBox,artBox:In[at].artBox,userUnit:In[at].userUnit,rootDictionaryObjId:ms,resourceDictionaryObjId:ot}));ln(ms,!0),Re("<>"),Re("endobj"),Ar.publish("postPutPages")},cs=function(at){Ar.publish("putFont",{font:at,out:Re,newObject:$n,putStream:Zt}),at.isAlreadyPutted!==!0&&(at.objectNumber=$n(),Re("<<"),Re("/Type /Font"),Re("/BaseFont /"+g9(at.postScriptName)),Re("/Subtype /Type1"),typeof at.encoding=="string"&&Re("/Encoding /"+at.encoding),Re("/FirstChar 32"),Re("/LastChar 255"),Re(">>"),Re("endobj"))},qt=function(at){at.objectNumber=$n();var Wt=[];Wt.push({key:"Type",value:"/XObject"}),Wt.push({key:"Subtype",value:"/Form"}),Wt.push({key:"BBox",value:"["+[M(at.x),M(at.y),M(at.x+at.width),M(at.y+at.height)].join(" ")+"]"}),Wt.push({key:"Matrix",value:"["+at.matrix.toString()+"]"});var Bs=at.pages[1].join(` `);Zt({data:Bs,additionalKeyValues:Wt,objectId:at.objectNumber}),Re("endobj")},Gs=function(at,Wt){Wt||(Wt=21);var Bs=$n(),Ys=function(kt,Cs){var xn,Rr=[],Dr=1/(Cs-1);for(xn=0;xn<1;xn+=Dr)Rr.push(xn);if(Rr.push(1),kt[0].offset!=0){var Aa={offset:0,color:kt[0].color};kt.unshift(Aa)}if(kt[kt.length-1].offset!=1){var Ua={offset:1,color:kt[kt.length-1].color};kt.push(Ua)}for(var sr="",Ra=0,ri=0;rikt[Ra+1].offset;)Ra++;var Ho=kt[Ra].offset,Kl=(xn-Ho)/(kt[Ra+1].offset-Ho),Hi=kt[Ra].color,lm=kt[Ra+1].color;sr+=ge(Math.round((1-Kl)*Hi[0]+Kl*lm[0]).toString(16))+ge(Math.round((1-Kl)*Hi[1]+Kl*lm[1]).toString(16))+ge(Math.round((1-Kl)*Hi[2]+Kl*lm[2]).toString(16))}return sr.trim()}(at.colors,Wt),jn=[];jn.push({key:"FunctionType",value:"0"}),jn.push({key:"Domain",value:"[0.0 1.0]"}),jn.push({key:"Size",value:"["+Wt+"]"}),jn.push({key:"BitsPerSample",value:"8"}),jn.push({key:"Range",value:"[0.0 1.0 0.0 1.0 0.0 1.0]"}),jn.push({key:"Decode",value:"[0.0 1.0 0.0 1.0 0.0 1.0]"}),Zt({data:Ys,additionalKeyValues:jn,alreadyAppliedFilters:["/ASCIIHexDecode"],objectId:Bs}),Re("endobj"),at.objectNumber=$n(),Re("<< /ShadingType "+at.type),Re("/ColorSpace /DeviceRGB");var Ir="/Coords ["+M(parseFloat(at.coords[0]))+" "+M(parseFloat(at.coords[1]))+" ";at.type===2?Ir+=M(parseFloat(at.coords[2]))+" "+M(parseFloat(at.coords[3])):Ir+=M(parseFloat(at.coords[2]))+" "+M(parseFloat(at.coords[3]))+" "+M(parseFloat(at.coords[4]))+" "+M(parseFloat(at.coords[5])),Re(Ir+="]"),at.matrix&&Re("/Matrix ["+at.matrix.toString()+"]"),Re("/Function "+Bs+" 0 R"),Re("/Extend [true true]"),Re(">>"),Re("endobj")},Vs=function(at,Wt){var Bs=tn(),Ys=$n();Wt.push({resourcesOid:Bs,objectOid:Ys}),at.objectNumber=Ys;var jn=[];jn.push({key:"Type",value:"/Pattern"}),jn.push({key:"PatternType",value:"1"}),jn.push({key:"PaintType",value:"1"}),jn.push({key:"TilingType",value:"1"}),jn.push({key:"BBox",value:"["+at.boundingBox.map(M).join(" ")+"]"}),jn.push({key:"XStep",value:M(at.xStep)}),jn.push({key:"YStep",value:M(at.yStep)}),jn.push({key:"Resources",value:Bs+" 0 R"}),at.matrix&&jn.push({key:"Matrix",value:"["+at.matrix.toString()+"]"}),Zt({data:at.stream,additionalKeyValues:jn,objectId:at.objectNumber}),Re("endobj")},Hn=function(at){for(var Wt in at.objectNumber=$n(),Re("<<"),at)switch(Wt){case"opacity":Re("/ca "+B(at[Wt]));break;case"stroke-opacity":Re("/CA "+B(at[Wt]))}Re(">>"),Re("endobj")},Kr=function(at){ln(at.resourcesOid,!0),Re("<<"),Re("/ProcSet [/PDF /Text /ImageB /ImageC /ImageI]"),function(){for(var Wt in Re("/Font <<"),Ds)Ds.hasOwnProperty(Wt)&&(h===!1||h===!0&&m.hasOwnProperty(Wt))&&Re("/"+Wt+" "+Ds[Wt].objectNumber+" 0 R");Re(">>")}(),function(){if(Object.keys(rn).length>0){for(var Wt in Re("/Shading <<"),rn)rn.hasOwnProperty(Wt)&&rn[Wt]instanceof j8&&rn[Wt].objectNumber>=0&&Re("/"+Wt+" "+rn[Wt].objectNumber+" 0 R");Ar.publish("putShadingPatternDict"),Re(">>")}}(),function(Wt){if(Object.keys(rn).length>0){for(var Bs in Re("/Pattern <<"),rn)rn.hasOwnProperty(Bs)&&rn[Bs]instanceof p.TilingPattern&&rn[Bs].objectNumber>=0&&rn[Bs].objectNumber>")}}(at.objectOid),function(){if(Object.keys(_n).length>0){var Wt;for(Wt in Re("/ExtGState <<"),_n)_n.hasOwnProperty(Wt)&&_n[Wt].objectNumber>=0&&Re("/"+Wt+" "+_n[Wt].objectNumber+" 0 R");Ar.publish("putGStateDict"),Re(">>")}}(),function(){for(var Wt in Re("/XObject <<"),qs)qs.hasOwnProperty(Wt)&&qs[Wt].objectNumber>=0&&Re("/"+Wt+" "+qs[Wt].objectNumber+" 0 R");Ar.publish("putXobjectDict"),Re(">>")}(),Re(">>"),Re("endobj")},ma=function(at){_t[at.fontName]=_t[at.fontName]||{},_t[at.fontName][at.fontStyle]=at.id},Or=function(at,Wt,Bs,Ys,jn){var Ir={id:"F"+(Object.keys(Ds).length+1).toString(10),postScriptName:at,fontName:Wt,fontStyle:Bs,encoding:Ys,isStandardFont:jn||!1,metadata:{}};return Ar.publish("addFont",{font:Ir,instance:this}),Ds[Ir.id]=Ir,ma(Ir),Ir.id},ta=p.__private__.pdfEscape=p.pdfEscape=function(at,Wt){return function(Bs,Ys){var jn,Ir,kt,Cs,xn,Rr,Dr,Aa,Ua;if(kt=(Ys=Ys||{}).sourceEncoding||"Unicode",xn=Ys.outputEncoding,(Ys.autoencode||xn)&&Ds[Ft].metadata&&Ds[Ft].metadata[kt]&&Ds[Ft].metadata[kt].encoding&&(Cs=Ds[Ft].metadata[kt].encoding,!xn&&Ds[Ft].encoding&&(xn=Ds[Ft].encoding),!xn&&Cs.codePages&&(xn=Cs.codePages[0]),typeof xn=="string"&&(xn=Cs[xn]),xn)){for(Dr=!1,Rr=[],jn=0,Ir=Bs.length;jn>8&&(Dr=!0);Bs=Rr.join("")}for(jn=Bs.length;Dr===void 0&&jn!==0;)Bs.charCodeAt(jn-1)>>8&&(Dr=!0),jn--;if(!Dr)return Bs;for(Rr=Ys.noBOM?[]:[254,255],jn=0,Ir=Bs.length;jn>8)>>8)throw new Error("Character at position "+jn+" of string '"+Bs+"' exceeds 16bits. Cannot be encoded into UCS-2 BE");Rr.push(Ua),Rr.push(Aa-(Ua<<8))}return String.fromCharCode.apply(void 0,Rr)}(at,Wt).replace(/\\/g,"\\\\").replace(/\(/g,"\\(").replace(/\)/g,"\\)")},da=p.__private__.beginPage=function(at){ze[++Un]=[],In[Un]={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])}},el(Un),Se(ze[he])},va=function(at,Wt){var Bs,Ys,jn;switch(n=Wt||n,typeof at=="string"&&(Bs=b(at.toLowerCase()),Array.isArray(Bs)&&(Ys=Bs[0],jn=Bs[1])),Array.isArray(at)&&(Ys=at[0]*Ts,jn=at[1]*Ts),isNaN(Ys)&&(Ys=a[0],jn=a[1]),(Ys>14400||jn>14400)&&(jh.warn("A page in a PDF can not be wider or taller than 14400 userUnit. jsPDF limits the width/height to 14400"),Ys=Math.min(14400,Ys),jn=Math.min(14400,jn)),a=[Ys,jn],n.substr(0,1)){case"l":jn>Ys&&(a=[jn,Ys]);break;case"p":Ys>jn&&(a=[jn,Ys])}da(a),Pf(Zi),Re(Kd),ph!==0&&Re(ph+" J"),am!==0&&Re(am+" j"),Ar.publish("addPage",{pageNumber:Un})},hi=function(at){at>0&&at<=Un&&(ze.splice(at,1),In.splice(at,1),Un--,he>Un&&(he=Un),this.setPage(he))},el=function(at){at>0&&at<=Un&&(he=at)},Oo=p.__private__.getNumberOfPages=p.getNumberOfPages=function(){return ze.length-1},Ei=function(at,Wt,Bs){var Ys,jn=void 0;return Bs=Bs||{},at=at!==void 0?at:Ds[Ft].fontName,Wt=Wt!==void 0?Wt:Ds[Ft].fontStyle,Ys=at.toLowerCase(),_t[Ys]!==void 0&&_t[Ys][Wt]!==void 0?jn=_t[Ys][Wt]:_t[at]!==void 0&&_t[at][Wt]!==void 0?jn=_t[at][Wt]:Bs.disableWarning===!1&&jh.warn("Unable to look up font label for font '"+at+"', '"+Wt+"'. Refer to getFontList() for available fonts."),jn||Bs.noFallback||(jn=_t.times[Wt])==null&&(jn=_t.times.normal),jn},Wa=p.__private__.putInfo=function(){var at=$n(),Wt=function(Ys){return Ys};for(var Bs in u!==null&&(Wt=vo.encryptor(at,0)),Re("<<"),Re("/Producer ("+ta(Wt("jsPDF "+go.version))+")"),Mt)Mt.hasOwnProperty(Bs)&&Mt[Bs]&&Re("/"+Bs.substr(0,1).toUpperCase()+Bs.substr(1)+" ("+ta(Wt(Mt[Bs]))+")");Re("/CreationDate ("+ta(Wt(K))+")"),Re(">>"),Re("endobj")},wo=p.__private__.putCatalog=function(at){var Wt=(at=at||{}).rootDictionaryObjId||ms;switch($n(),Re("<<"),Re("/Type /Catalog"),Re("/Pages "+Wt+" 0 R"),Ze||(Ze="fullwidth"),Ze){case"fullwidth":Re("/OpenAction [3 0 R /FitH null]");break;case"fullheight":Re("/OpenAction [3 0 R /FitV null]");break;case"fullpage":Re("/OpenAction [3 0 R /Fit]");break;case"original":Re("/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"&&Re("/OpenAction [3 0 R /XYZ null null "+B(Ze)+"]")}switch(nt||(nt="continuous"),nt){case"continuous":Re("/PageLayout /OneColumn");break;case"single":Re("/PageLayout /SinglePage");break;case"two":case"twoleft":Re("/PageLayout /TwoColumnLeft");break;case"tworight":Re("/PageLayout /TwoColumnRight")}Qe&&Re("/PageMode /"+Qe),Ar.publish("putCatalog"),Re(">>"),Re("endobj")},Io=p.__private__.putTrailer=function(){Re("trailer"),Re("<<"),Re("/Size "+(fe+1)),Re("/Root "+fe+" 0 R"),Re("/Info "+(fe-1)+" 0 R"),u!==null&&Re("/Encrypt "+vo.oid+" 0 R"),Re("/ID [ <"+Q+"> <"+Q+"> ]"),Re(">>")},is=p.__private__.putHeader=function(){Re("%PDF-"+x),Re("%ºß¬à")},zr=p.__private__.putXRef=function(){var at="0000000000";Re("xref"),Re("0 "+(fe+1)),Re("0000000000 65535 f ");for(var Wt=1;Wt<=fe;Wt++)typeof je[Wt]=="function"?Re((at+je[Wt]()).slice(-10)+" 00000 n "):je[Wt]!==void 0?Re((at+je[Wt]).slice(-10)+" 00000 n "):Re("0000000000 00000 n ")},Sa=p.__private__.buildDocument=function(){var at;fe=0,Me=0,Ee=[],je=[],De=[],ms=tn(),ot=tn(),Se(Ee),Ar.publish("buildDocument"),is(),Ls(),function(){Ar.publish("putAdditionalObjects");for(var Bs=0;Bs"),Re("/O <"+vo.toHexString(vo.O)+">"),Re("/P "+vo.P),Re(">>"),Re("endobj")),Wa(),wo();var Wt=Me;return zr(),Io(),Re("startxref"),Re(""+Wt),Re("%%EOF"),Se(ze[he]),Ee.join(` `)},Kn=p.__private__.getBlob=function(at){return new Blob([Be(at)],{type:"application/pdf"})},wn=function(at){for(;at.firstChild;)at.removeChild(at.firstChild)},Ur=function(at){var Wt,Bs=at.document,Ys=Bs.documentElement,jn=Bs.head,Ir=Bs.body;return jn||(jn=Bs.createElement("head"),Ys.appendChild(jn)),Ir||(Ir=Bs.createElement("body"),Ys.appendChild(Ir)),wn(jn),wn(Ir),(Wt=Bs.createElement("style")).appendChild(Bs.createTextNode("html, body { padding: 0; margin: 0; } iframe { width: 100%; height: 100%; border: 0;}")),jn.appendChild(Wt),{document:Bs,body:Ir}},ca=p.output=p.__private__.output=(Sn=function(at,Wt){switch(typeof(Wt=Wt||{})=="string"?Wt={filename:Wt}:Wt.filename=Wt.filename||"generated.pdf",at){case void 0:return Sa();case"save":p.save(Wt.filename);break;case"arraybuffer":return Be(Sa());case"blob":return Kn(Sa());case"bloburi":case"bloburl":if(El.URL!==void 0&&typeof El.URL.createObjectURL=="function")return El.URL&&El.URL.createObjectURL(Kn(Sa()))||void 0;jh.warn("bloburl is not supported by your system, because URL.createObjectURL is not supported by your browser.");break;case"datauristring":case"dataurlstring":var Bs="",Ys=Sa();try{Bs=yyt(Ys)}catch{Bs=yyt(unescape(encodeURIComponent(Ys)))}return"data:application/pdf;filename="+encodeURIComponent(Wt.filename)+";base64,"+Bs;case"pdfobjectnewwindow":if(Object.prototype.toString.call(El)==="[object Window]"){var jn="https://cdnjs.cloudflare.com/ajax/libs/pdfobject/2.1.1/pdfobject.min.js",Ir=!Wt.pdfObjectUrl;Ir||(jn=Wt.pdfObjectUrl);var kt=El.open();if(kt!==null){var Cs=Ur(kt),xn=Cs.document.createElement("script"),Rr=this;xn.src=jn,Ir&&(xn.integrity="sha512-4ze/a9/4jqu+tX9dfOqJYSvyYd5M6qum/3HpCLr+/Jqf0whc37VUbkpNGHR7/8pSnCFw47T1fmIpwBV7UySh3g==",xn.crossOrigin="anonymous"),xn.onload=function(){kt.PDFObject.embed(Rr.output("dataurlstring"),Wt)},Cs.body.appendChild(xn)}return kt}throw new Error("The option pdfobjectnewwindow just works in a browser-environment.");case"pdfjsnewwindow":if(Object.prototype.toString.call(El)==="[object Window]"){var Dr=Wt.pdfJsUrl||"examples/PDF.js/web/viewer.html",Aa=El.open();if(Aa!==null){var Ua=Ur(Aa),sr=Ua.document.createElement("iframe"),Ra=Dr.indexOf("?")===-1?"?":"&";Rr=this,sr.id="pdfViewer",sr.width="500px",sr.height="400px",sr.src=Dr+Ra+"file=&downloadName="+encodeURIComponent(Wt.filename),sr.onload=function(){Aa.document.title=Wt.filename,sr.contentWindow.PDFViewerApplication.open(Rr.output("bloburl"))},Ua.body.appendChild(sr)}return Aa}throw new Error("The option pdfjsnewwindow just works in a browser-environment.");case"dataurlnewwindow":if(Object.prototype.toString.call(El)!=="[object Window]")throw new Error("The option dataurlnewwindow just works in a browser-environment.");var ri=El.open();if(ri!==null){var Ho=Ur(ri),Kl=Ho.document.createElement("iframe");Kl.src=this.output("datauristring",Wt),Ho.body.appendChild(Kl),ri.document.title=Wt.filename}if(ri||typeof safari>"u")return ri;break;case"datauri":case"dataurl":return El.document.location.href=this.output("datauristring",Wt);default:return null}},Sn.foo=function(){try{return Sn.apply(this,arguments)}catch(Bs){var at=Bs.stack||"";~at.indexOf(" at ")&&(at=at.split(" at ")[1]);var Wt="Error in function "+at.split(` `)[0].split("<")[0]+": "+Bs.message;if(!El.console)throw new Error(Wt);El.console.error(Wt,Bs),El.alert&&alert(Wt)}},Sn.foo.bar=Sn,Sn.foo),yo=function(at){return Array.isArray(or)===!0&&or.indexOf(at)>-1};switch(r){case"pt":Ts=1;break;case"mm":Ts=72/25.4;break;case"cm":Ts=72/2.54;break;case"in":Ts=72;break;case"px":Ts=yo("px_scaling")==1?.75:96/72;break;case"pc":case"em":Ts=12;break;case"ex":Ts=6;break;default:if(typeof r!="number")throw new Error("Invalid unit: "+r);Ts=r}var vo=null;ee(),ce();var Vo=p.__private__.getPageInfo=p.getPageInfo=function(at){if(isNaN(at)||at%1!=0)throw new Error("Invalid argument passed to jsPDF.getPageInfo");return{objId:In[at].objId,pageNumber:at,pageContext:In[at]}},Xc=p.__private__.getPageInfoByObjId=function(at){if(isNaN(at)||at%1!=0)throw new Error("Invalid argument passed to jsPDF.getPageInfoByObjId");for(var Wt in In)if(In[Wt].objId===at)break;return Vo(Wt)},uo=p.__private__.getCurrentPageInfo=p.getCurrentPageInfo=function(){return{objId:In[he].objId,pageNumber:he,pageContext:In[he]}};p.addPage=function(){return va.apply(this,arguments),this},p.setPage=function(){return el.apply(this,arguments),Se.call(this,ze[he]),this},p.insertPage=function(at){return this.addPage(),this.movePage(he,at),this},p.movePage=function(at,Wt){var Bs,Ys;if(at>Wt){Bs=ze[at],Ys=In[at];for(var jn=at;jn>Wt;jn--)ze[jn]=ze[jn-1],In[jn]=In[jn-1];ze[Wt]=Bs,In[Wt]=Ys,this.setPage(Wt)}else if(at0&&(typeof at=="string"?at=Ra.splitTextToSize(at,Dr):Object.prototype.toString.call(at)==="[object Array]"&&(at=at.reduce(function(tl,Go){return tl.concat(Ra.splitTextToSize(Go,Dr))},[]))),Ir={text:at,x:Wt,y:Bs,options:Ys,mutex:{pdfEscape:ta,activeFontKey:Ft,fonts:Ds,activeFontSize:Ke}},Ar.publish("preProcessText",Ir),at=Ir.text,Cs=(Ys=Ir.options).angle,sr instanceof Zn==0&&Cs&&typeof Cs=="number"){Cs*=Math.PI/180,Ys.rotationDirection===0&&(Cs=-Cs),C===N&&(Cs=-Cs);var My=Math.cos(Cs),cd=Math.sin(Cs);sr=new Zn(My,cd,-cd,My,0,0)}else Cs&&Cs instanceof Zn&&(sr=Cs);C!==N||sr||(sr=rr),(Rr=Ys.charSpace||Tm)!==void 0&&(Kl+=M(W(Rr))+` Tc `,this.setCharSpace(this.getCharSpace()||0)),(Ua=Ys.horizontalScale)!==void 0&&(Kl+=M(100*Ua)+` Tz `),Ys.lang;var wd=-1,Pu=Ys.renderingMode!==void 0?Ys.renderingMode:Ys.stroke,Lm=Ra.internal.getCurrentPageInfo().pageContext;switch(Pu){case 0:case!1:case"fill":wd=0;break;case 1:case!0:case"stroke":wd=1;break;case 2:case"fillThenStroke":wd=2;break;case 3:case"invisible":wd=3;break;case 4:case"fillAndAddForClipping":wd=4;break;case 5:case"strokeAndAddPathForClipping":wd=5;break;case 6:case"fillThenStrokeAndAddToPathForClipping":wd=6;break;case 7:case"addToPathForClipping":wd=7}var Rf=Lm.usedRenderingMode!==void 0?Lm.usedRenderingMode:-1;wd!==-1?Kl+=wd+` Tr `:Rf!==-1&&(Kl+=`0 Tr `),wd!==-1&&(Lm.usedRenderingMode=wd),xn=Ys.align||"left";var kl,Ma=Ke*Hi,qr=Ra.internal.pageSize.getWidth(),Yl=Ds[Ft];Rr=Ys.charSpace||Tm,Dr=Ys.maxWidth||0,Aa=Object.assign({autoencode:!0,noBOM:!0},Ys.flags);var La=[],Pm=function(tl){return Ra.getStringUnitWidth(tl,{font:Yl,charSpace:Rr,fontSize:Ke,doKerning:!1})*Ke/lm};if(Object.prototype.toString.call(at)==="[object Array]"){var dd;kt=Bg(at),xn!=="left"&&(kl=kt.map(Pm));var pa,Gx=0;if(xn==="right"){Wt-=kl[0],at=[],Yd=kt.length;for(var $g=0;$g0?(Dr-kl[qc])/mp:0;qc":")"),Ac=parseFloat(kt[vu][1]),Wx=parseFloat(kt[vu][2]);break;case 0:O0=(Ho?"<":"(")+kt[vu]+(Ho?">":")"),Ac=Df(Wt),Wx=Lu(Bs)}La!==void 0&&La[vu]!==void 0&&(Ff=La[vu]+` Tw `),vu===0?at.push(Ff+P1(Ac,Wx,sr)+O0):xh===0?at.push(Ff+O0):xh===1&&at.push(Ff+P1(Ac,Wx,sr)+O0)}at=xh===0?at.join(` Tj T* `):at.join(` Tj `),at+=` Tj `;var Zl=`BT /`;return Zl+=Ft+" "+Ke+` Tf `,Zl+=M(Ke*Hi)+` TL `,Zl+=rm+` `,Zl+=Kl,Zl+=at,Re(Zl+="ET"),m[Ft]=!0,Ra};var bo=p.__private__.clip=p.clip=function(at){return Re(at==="evenodd"?"W*":"W"),this};p.clipEvenOdd=function(){return bo("evenodd")},p.__private__.discardPath=p.discardPath=function(){return Re("n"),this};var od=p.__private__.isValidStyle=function(at){var Wt=!1;return[void 0,null,"S","D","F","DF","FD","f","f*","B","B*","n"].indexOf(at)!==-1&&(Wt=!0),Wt};p.__private__.setDefaultPathOperation=p.setDefaultPathOperation=function(at){return od(at)&&(d=at),this};var Ju=p.__private__.getStyle=p.getStyle=function(at){var Wt=d;switch(at){case"D":case"S":Wt="S";break;case"F":Wt="f";break;case"FD":case"DF":Wt="B";break;case"f":case"f*":case"B":case"B*":Wt=at}return Wt},Ld=p.close=function(){return Re("h"),this};p.stroke=function(){return Re("S"),this},p.fill=function(at){return bd("f",at),this},p.fillEvenOdd=function(at){return bd("f*",at),this},p.fillStroke=function(at){return bd("B",at),this},p.fillStrokeEvenOdd=function(at){return bd("B*",at),this};var bd=function(at,Wt){Wu(Wt)==="object"?Kp(Wt,at):Re(at)},hx=function(at){at===null||C===N&&at===void 0||(at=Ju(at),Re(at))};function Ay(at,Wt,Bs,Ys,jn){var Ir=new sz(Wt||this.boundingBox,Bs||this.xStep,Ys||this.yStep,this.gState,jn||this.matrix);Ir.stream=this.stream;var kt=at+"$$"+this.cloneIndex+++"$$";return Qn(kt,Ir),Ir}var Kp=function(at,Wt){var Bs=Ps[at.key],Ys=rn[Bs];if(Ys instanceof j8)Re("q"),Re(Dg(Wt)),Ys.gState&&p.setGState(Ys.gState),Re(at.matrix.toString()+" cm"),Re("/"+Bs+" sh"),Re("Q");else if(Ys instanceof sz){var jn=new Zn(1,0,0,-1,0,om());at.matrix&&(jn=jn.multiply(at.matrix||rr),Bs=Ay.call(Ys,at.key,at.boundingBox,at.xStep,at.yStep,jn).id),Re("q"),Re("/Pattern cs"),Re("/"+Bs+" scn"),Ys.gState&&p.setGState(Ys.gState),Re(Wt),Re("Q")}},Dg=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"}},Em=p.moveTo=function(at,Wt){return Re(M(W(at))+" "+M(V(Wt))+" m"),this},Lf=p.lineTo=function(at,Wt){return Re(M(W(at))+" "+M(V(Wt))+" l"),this},eh=p.curveTo=function(at,Wt,Bs,Ys,jn,Ir){return Re([M(W(at)),M(V(Wt)),M(W(Bs)),M(V(Ys)),M(W(jn)),M(V(Ir)),"c"].join(" ")),this};p.__private__.line=p.line=function(at,Wt,Bs,Ys,jn){if(isNaN(at)||isNaN(Wt)||isNaN(Bs)||isNaN(Ys)||!od(jn))throw new Error("Invalid arguments passed to jsPDF.line");return C===v?this.lines([[Bs-at,Ys-Wt]],at,Wt,[1,1],jn||"S"):this.lines([[Bs-at,Ys-Wt]],at,Wt,[1,1]).stroke()},p.__private__.lines=p.lines=function(at,Wt,Bs,Ys,jn,Ir){var kt,Cs,xn,Rr,Dr,Aa,Ua,sr,Ra,ri,Ho,Kl;if(typeof at=="number"&&(Kl=Bs,Bs=Wt,Wt=at,at=Kl),Ys=Ys||[1,1],Ir=Ir||!1,isNaN(Wt)||isNaN(Bs)||!Array.isArray(at)||!Array.isArray(Ys)||!od(jn)||typeof Ir!="boolean")throw new Error("Invalid arguments passed to jsPDF.lines");for(Em(Wt,Bs),kt=Ys[0],Cs=Ys[1],Rr=at.length,ri=Wt,Ho=Bs,xn=0;xn>8&255,s>>16&255,s>>24&255)},x9.prototype.toHexString=function(s){return s.split("").map(function(t){return("0"+(255&t.charCodeAt(0)).toString(16)).slice(-2)}).join("")},x9.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 UBe(n,r)}},S4e.prototype.equals=function(s){var t,n="id,objectNumber,equals";if(!s||Wu(s)!==Wu(this))return!1;var r=0;for(t in this)if(!(n.indexOf(t)>=0)){if(this.hasOwnProperty(t)&&!s.hasOwnProperty(t)||this[t]!==s[t])return!1;r++}for(t in s)s.hasOwnProperty(t)&&n.indexOf(t)<0&&r--;return r===0},go.API={events:[]},go.version="4.2.1";var mf=go.API,BZe=1,gF=function(s){return s.replace(/\\/g,"\\\\").replace(/\(/g,"\\(").replace(/\)/g,"\\)")},$7=function(s){return s.replace(/\\\\/g,"\\").replace(/\\\(/g,"(").replace(/\\\)/g,")")},DO=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)})},Vl=function(s){return s.toFixed(2)},uA=function(s){return s.toFixed(5)};mf.__acroform__={};var Zb=function(s,t){s.prototype=Object.create(t.prototype),s.prototype.constructor=s},wyt=function(s){return s*BZe},Xk=function(s){var t=new o$t,n=io.internal.getHeight(s)||0,r=io.internal.getWidth(s)||0;return t.BBox=[0,0,Number(Vl(r)),Number(Vl(n))],t},gEn=mf.__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=iae("3",s,i).height,m=s.multiline?l-i:(l-h)/2,p=m+=2,x=0,g=0,y=0;if(i<=0){t=`(...) Tj `,t+="% Width of Text: "+iae(t,s,i=12).width+", FieldWidth:"+o+` `;break}for(var b="",v=0,N=0;Nl)continue e;b+=a[N][y],C=!0,g=N,N--}else{b=(b+=a[N][y]+" ").substr(b.length-1)==" "?b.substr(0,b.length-1):b;var A=parseInt(N),T=c(A,b,i),P=N>=a.length-1;if(T&&!P){b+=" ",y=0;continue}if(T||P){if(P)g=A;else if(s.multiline&&(h+2)*(v+2)+2>l)continue e}else{if(!s.multiline||(h+2)*(v+2)+2>l)continue e;g=A}}for(var M="",I=x;I<=g;I++){var D=a[I];if(s.multiline){if(I===g){M+=D[y]+" ",y=(y+1)%D.length;continue}if(I===x){M+=D[D.length-1]+" ";continue}}M+=D[0]+" "}switch(M=M.substr(M.length-1)==" "?M.substr(0,M.length-1):M,u=iae(M,s,i).width,s.textAlign){case"right":d=o-u-2;break;case"center":d=(o-u)/2;break;default:d=2}t+=Vl(d)+" "+Vl(p)+` Td `,t+="("+gF(M)+`) Tj `,t+=-Vl(d)+` 0 Td `,p=-(i+2),u=0,x=C?g:g+1,v++,b=""}break}return r.text=t,r.fontSize=i,r},iae=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}},wEn={fields:[],xForms:[],acroFormDictionaryRoot:null,printedOut:!1,internal:null,isInitialized:!1},jEn=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)},NEn=function(s,t){if(t.scope=s,s.internal!==void 0&&(s.internal.acroformPlugin===void 0||s.internal.acroformPlugin.isInitialized===!1)){if(uk.FieldNum=0,s.internal.acroformPlugin=JSON.parse(JSON.stringify(wEn)),s.internal.acroformPlugin.acroFormDictionaryRoot)throw new Error("Exception while creating AcroformDictionary");BZe=s.internal.scaleFactor,s.internal.acroformPlugin.acroFormDictionaryRoot=new l$t,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&&jEn(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=bEn(o.Rect,a)),a.internal.newObjectDeferredBegin(o.objId,!0),o.DA=io.createDefaultAppearanceStream(o),Wu(o)==="object"&&typeof o.getKeyValueListForStream=="function"&&(c=o.getKeyValueListForStream()),o.Rect=d,o.hasAppearanceStream&&!o.appearanceStreamContent){var u=_En(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 x=p[l];typeof x=="function"&&(x=x.call(a,o)),h+="/"+l+" "+x+" ",a.internal.acroformPlugin.xForms.indexOf(x)>=0||a.internal.acroformPlugin.xForms.push(x)}}else typeof(x=p)=="function"&&(x=x.call(a,o)),h+="/"+l+" "+x,a.internal.acroformPlugin.xForms.indexOf(x)>=0||a.internal.acroformPlugin.xForms.push(x);h+=">>"}c.push({key:"AP",value:`<< `+h+">>"})}a.internal.putStream({additionalKeyValues:c,objectId:o.objId}),a.internal.out("endobj")}i&&function(g,y){for(var b in g)if(g.hasOwnProperty(b)){var v=b,N=g[b];y.internal.newObjectDeferredBegin(N.objId,!0),Wu(N)==="object"&&typeof N.putStream=="function"&&N.putStream(),delete g[v]}}(a.internal.acroformPlugin.xForms,a)})(n,s)}),s.internal.acroformPlugin.isInitialized=!0}},i$t=mf.__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)),"("+gF(n(s))+")"}},set:function(n){s=n}})};Zb(l$t,GS);var uk=function s(){GS.call(this);var t=4;Object.defineProperty(this,"F",{enumerable:!1,configurable:!1,get:function(){return t},set:function(b){if(isNaN(b))throw new Error('Invalid value "'+b+'" for attribute F supplied.');t=b}}),Object.defineProperty(this,"showWhenPrinted",{enumerable:!0,configurable:!0,get:function(){return!!Yf(t,3)},set:function(b){b?this.F=Zf(t,3):this.F=Xf(t,3)}});var n=0;Object.defineProperty(this,"Ff",{enumerable:!1,configurable:!1,get:function(){return n},set:function(b){if(isNaN(b))throw new Error('Invalid value "'+b+'" for attribute Ff supplied.');n=b}});var r=[];Object.defineProperty(this,"Rect",{enumerable:!1,configurable:!1,get:function(){if(r.length!==0)return r},set:function(b){r=b!==void 0?b:[]}}),Object.defineProperty(this,"x",{enumerable:!0,configurable:!0,get:function(){return!r||isNaN(r[0])?0:r[0]},set:function(b){r[0]=b}}),Object.defineProperty(this,"y",{enumerable:!0,configurable:!0,get:function(){return!r||isNaN(r[1])?0:r[1]},set:function(b){r[1]=b}}),Object.defineProperty(this,"width",{enumerable:!0,configurable:!0,get:function(){return!r||isNaN(r[2])?0:r[2]},set:function(b){r[2]=b}}),Object.defineProperty(this,"height",{enumerable:!0,configurable:!0,get:function(){return!r||isNaN(r[3])?0:r[3]},set:function(b){r[3]=b}});var a="";Object.defineProperty(this,"FT",{enumerable:!0,configurable:!1,get:function(){return a},set:function(b){switch(b){case"/Btn":case"/Tx":case"/Ch":case"/Sig":a=b;break;default:throw new Error('Invalid value "'+b+'" 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 C4e)return;i="FieldObject"+s.FieldNum++}var b=function(v){return v};return this.scope&&(b=this.scope.internal.getEncryptor(this.objId)),"("+gF(b(i))+")"},set:function(b){i=b.toString()}}),Object.defineProperty(this,"fieldName",{configurable:!0,enumerable:!0,get:function(){return i},set:function(b){i=b}});var l="helvetica";Object.defineProperty(this,"fontName",{enumerable:!0,configurable:!0,get:function(){return l},set:function(b){l=b}});var o="normal";Object.defineProperty(this,"fontStyle",{enumerable:!0,configurable:!0,get:function(){return o},set:function(b){o=b}});var c=0;Object.defineProperty(this,"fontSize",{enumerable:!0,configurable:!0,get:function(){return c},set:function(b){c=b}});var d=void 0;Object.defineProperty(this,"maxFontSize",{enumerable:!0,configurable:!0,get:function(){return d===void 0?50/BZe:d},set:function(b){d=b}});var u="black";Object.defineProperty(this,"color",{enumerable:!0,configurable:!0,get:function(){return u},set:function(b){u=b}});var h="/F1 0 Tf 0 g";Object.defineProperty(this,"DA",{enumerable:!0,configurable:!1,get:function(){if(!(!h||this instanceof C4e||this instanceof KR))return nDe(h,this.objId,this.scope)},set:function(b){b=b.toString(),h=b}});var m=null;Object.defineProperty(this,"DV",{enumerable:!1,configurable:!1,get:function(){if(m)return this instanceof m0==0?nDe(m,this.objId,this.scope):m},set:function(b){b=b.toString(),m=this instanceof m0==0?b.substr(0,1)==="("?$7(b.substr(1,b.length-2)):$7(b):b}}),Object.defineProperty(this,"defaultValue",{enumerable:!0,configurable:!0,get:function(){return this instanceof m0==1?$7(m.substr(1,m.length-1)):m},set:function(b){b=b.toString(),m=this instanceof m0==1?"/"+DO(b):b}});var p=null;Object.defineProperty(this,"_V",{enumerable:!1,configurable:!1,get:function(){if(p)return p},set:function(b){this.V=b}}),Object.defineProperty(this,"V",{enumerable:!1,configurable:!1,get:function(){if(p)return this instanceof m0==0?nDe(p,this.objId,this.scope):p},set:function(b){b=b.toString(),p=this instanceof m0==0?b.substr(0,1)==="("?$7(b.substr(1,b.length-2)):$7(b):b}}),Object.defineProperty(this,"value",{enumerable:!0,configurable:!0,get:function(){return this instanceof m0==1?$7(p.substr(1,p.length-1)):p},set:function(b){b=b.toString(),p=this instanceof m0==1?"/"+DO(b):b}}),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 x,g=!1;Object.defineProperty(this,"hasAppearanceStream",{enumerable:!0,configurable:!0,get:function(){return g},set:function(b){b=!!b,g=b}}),Object.defineProperty(this,"page",{enumerable:!0,configurable:!0,get:function(){if(x)return x},set:function(b){x=b}}),Object.defineProperty(this,"readOnly",{enumerable:!0,configurable:!0,get:function(){return!!Yf(this.Ff,1)},set:function(b){b?this.Ff=Zf(this.Ff,1):this.Ff=Xf(this.Ff,1)}}),Object.defineProperty(this,"required",{enumerable:!0,configurable:!0,get:function(){return!!Yf(this.Ff,2)},set:function(b){b?this.Ff=Zf(this.Ff,2):this.Ff=Xf(this.Ff,2)}}),Object.defineProperty(this,"noExport",{enumerable:!0,configurable:!0,get:function(){return!!Yf(this.Ff,3)},set:function(b){b?this.Ff=Zf(this.Ff,3):this.Ff=Xf(this.Ff,3)}});var y=null;Object.defineProperty(this,"Q",{enumerable:!0,configurable:!1,get:function(){if(y!==null)return y},set:function(b){if([0,1,2].indexOf(b)===-1)throw new Error('Invalid value "'+b+'" for attribute Q supplied.');y=b}}),Object.defineProperty(this,"textAlign",{get:function(){var b;switch(y){case 0:default:b="left";break;case 1:b="center";break;case 2:b="right"}return b},configurable:!0,enumerable:!0,set:function(b){switch(b){case"right":case 2:y=2;break;case"center":case 1:y=1;break;default:y=0}}})};Zb(uk,GS);var fB=function(){uk.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 i$t(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!!Yf(this.Ff,18)},set:function(n){n?this.Ff=Zf(this.Ff,18):this.Ff=Xf(this.Ff,18)}}),Object.defineProperty(this,"edit",{enumerable:!0,configurable:!0,get:function(){return!!Yf(this.Ff,19)},set:function(n){this.combo===!0&&(n?this.Ff=Zf(this.Ff,19):this.Ff=Xf(this.Ff,19))}}),Object.defineProperty(this,"sort",{enumerable:!0,configurable:!0,get:function(){return!!Yf(this.Ff,20)},set:function(n){n?(this.Ff=Zf(this.Ff,20),t.sort()):this.Ff=Xf(this.Ff,20)}}),Object.defineProperty(this,"multiSelect",{enumerable:!0,configurable:!0,get:function(){return!!Yf(this.Ff,22)},set:function(n){n?this.Ff=Zf(this.Ff,22):this.Ff=Xf(this.Ff,22)}}),Object.defineProperty(this,"doNotSpellCheck",{enumerable:!0,configurable:!0,get:function(){return!!Yf(this.Ff,23)},set:function(n){n?this.Ff=Zf(this.Ff,23):this.Ff=Xf(this.Ff,23)}}),Object.defineProperty(this,"commitOnSelChange",{enumerable:!0,configurable:!0,get:function(){return!!Yf(this.Ff,27)},set:function(n){n?this.Ff=Zf(this.Ff,27):this.Ff=Xf(this.Ff,27)}}),this.hasAppearanceStream=!1};Zb(fB,uk);var xB=function(){fB.call(this),this.fontName="helvetica",this.combo=!1};Zb(xB,fB);var gB=function(){xB.call(this),this.combo=!0};Zb(gB,xB);var Z2e=function(){gB.call(this),this.edit=!0};Zb(Z2e,gB);var m0=function(){uk.call(this),this.FT="/Btn",Object.defineProperty(this,"noToggleToOff",{enumerable:!0,configurable:!0,get:function(){return!!Yf(this.Ff,15)},set:function(n){n?this.Ff=Zf(this.Ff,15):this.Ff=Xf(this.Ff,15)}}),Object.defineProperty(this,"radio",{enumerable:!0,configurable:!0,get:function(){return!!Yf(this.Ff,16)},set:function(n){n?this.Ff=Zf(this.Ff,16):this.Ff=Xf(this.Ff,16)}}),Object.defineProperty(this,"pushButton",{enumerable:!0,configurable:!0,get:function(){return!!Yf(this.Ff,17)},set:function(n){n?this.Ff=Zf(this.Ff,17):this.Ff=Xf(this.Ff,17)}}),Object.defineProperty(this,"radioIsUnison",{enumerable:!0,configurable:!0,get:function(){return!!Yf(this.Ff,26)},set:function(n){n?this.Ff=Zf(this.Ff,26):this.Ff=Xf(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+" ("+gF(n(t[r]))+")");return a.push(">>"),a.join(` `)}},set:function(n){Wu(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="/"+DO(r)}}),Object.defineProperty(this,"appearanceState",{enumerable:!0,configurable:!0,get:function(){return s.substr(1,s.length-1)},set:function(n){s="/"+DO(n)}})};Zb(m0,uk);var X2e=function(){m0.call(this),this.pushButton=!0};Zb(X2e,m0);var yB=function(){m0.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:[]}})};Zb(yB,m0);var C4e=function(){var s,t;uk.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+" ("+gF(a(r[i]))+")");return l.push(">>"),l.join(` `)},set:function(a){Wu(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="/"+DO(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="/"+DO(i)}}),this.caption="l",this.appearanceState="Off",this._AppearanceType=io.RadioButton.Circle,this.appearanceStreamContent=this._AppearanceType.createAppearanceStream(this.optionName)};Zb(C4e,uk),yB.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()}},yB.prototype.createOption=function(s){var t=new C4e;return t.Parent=this,t.optionName=s,this.Kids.push(t),kEn.call(this.scope,t),t};var Q2e=function(){m0.call(this),this.fontName="zapfdingbats",this.caption="3",this.appearanceState="On",this.value="On",this.textAlign="center",this.appearanceStreamContent=io.CheckBox.createAppearanceStream()};Zb(Q2e,m0);var KR=function(){uk.call(this),this.FT="/Tx",Object.defineProperty(this,"multiline",{enumerable:!0,configurable:!0,get:function(){return!!Yf(this.Ff,13)},set:function(t){t?this.Ff=Zf(this.Ff,13):this.Ff=Xf(this.Ff,13)}}),Object.defineProperty(this,"fileSelect",{enumerable:!0,configurable:!0,get:function(){return!!Yf(this.Ff,21)},set:function(t){t?this.Ff=Zf(this.Ff,21):this.Ff=Xf(this.Ff,21)}}),Object.defineProperty(this,"doNotSpellCheck",{enumerable:!0,configurable:!0,get:function(){return!!Yf(this.Ff,23)},set:function(t){t?this.Ff=Zf(this.Ff,23):this.Ff=Xf(this.Ff,23)}}),Object.defineProperty(this,"doNotScroll",{enumerable:!0,configurable:!0,get:function(){return!!Yf(this.Ff,24)},set:function(t){t?this.Ff=Zf(this.Ff,24):this.Ff=Xf(this.Ff,24)}}),Object.defineProperty(this,"comb",{enumerable:!0,configurable:!0,get:function(){return!!Yf(this.Ff,25)},set:function(t){t?this.Ff=Zf(this.Ff,25):this.Ff=Xf(this.Ff,25)}}),Object.defineProperty(this,"richText",{enumerable:!0,configurable:!0,get:function(){return!!Yf(this.Ff,26)},set:function(t){t?this.Ff=Zf(this.Ff,26):this.Ff=Xf(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}})};Zb(KR,uk);var J2e=function(){KR.call(this),Object.defineProperty(this,"password",{enumerable:!0,configurable:!0,get:function(){return!!Yf(this.Ff,14)},set:function(s){s?this.Ff=Zf(this.Ff,14):this.Ff=Xf(this.Ff,14)}}),this.password=!0};Zb(J2e,KR);var io={CheckBox:{createAppearanceStream:function(){return{N:{On:io.CheckBox.YesNormal},D:{On:io.CheckBox.YesPushDown,Off:io.CheckBox.OffPushDown}}},YesPushDown:function(s){var t=Xk(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=qBe(s,s.caption);return n.push("0.749023 g"),n.push("0 0 "+Vl(io.internal.getWidth(s))+" "+Vl(io.internal.getHeight(s))+" re"),n.push("f"),n.push("BMC"),n.push("q"),n.push("0 0 1 rg"),n.push("/"+r+" "+Vl(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=Xk(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=io.internal.getHeight(s),l=io.internal.getWidth(s),o=qBe(s,s.caption);return a.push("1 g"),a.push("0 0 "+Vl(l)+" "+Vl(i)+" re"),a.push("f"),a.push("q"),a.push("0 0 1 rg"),a.push("0 0 "+Vl(l-1)+" "+Vl(i-1)+" re"),a.push("W"),a.push("n"),a.push("0 g"),a.push("BT"),a.push("/"+n+" "+Vl(o.fontSize)+" Tf "+r),a.push(o.text),a.push("ET"),a.push("Q"),t.stream=a.join(` `),t},OffPushDown:function(s){var t=Xk(s);t.scope=s.scope;var n=[];return n.push("0.749023 g"),n.push("0 0 "+Vl(io.internal.getWidth(s))+" "+Vl(io.internal.getHeight(s))+" re"),n.push("f"),t.stream=n.join(` `),t}},RadioButton:{Circle:{createAppearanceStream:function(s){var t={D:{Off:io.RadioButton.Circle.OffPushDown},N:{}};return t.N[s]=io.RadioButton.Circle.YesNormal,t.D[s]=io.RadioButton.Circle.YesPushDown,t},getCA:function(){return"l"},YesNormal:function(s){var t=Xk(s);t.scope=s.scope;var n=[],r=io.internal.getWidth(s)<=io.internal.getHeight(s)?io.internal.getWidth(s)/4:io.internal.getHeight(s)/4;r=Number((.9*r).toFixed(5));var a=io.internal.Bezier_C,i=Number((r*a).toFixed(5));return n.push("q"),n.push("1 0 0 1 "+uA(io.internal.getWidth(s)/2)+" "+uA(io.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=Xk(s);t.scope=s.scope;var n=[],r=io.internal.getWidth(s)<=io.internal.getHeight(s)?io.internal.getWidth(s)/4:io.internal.getHeight(s)/4;r=Number((.9*r).toFixed(5));var a=Number((2*r).toFixed(5)),i=Number((a*io.internal.Bezier_C).toFixed(5)),l=Number((r*io.internal.Bezier_C).toFixed(5));return n.push("0.749023 g"),n.push("q"),n.push("1 0 0 1 "+uA(io.internal.getWidth(s)/2)+" "+uA(io.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 "+uA(io.internal.getWidth(s)/2)+" "+uA(io.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=Xk(s);t.scope=s.scope;var n=[],r=io.internal.getWidth(s)<=io.internal.getHeight(s)?io.internal.getWidth(s)/4:io.internal.getHeight(s)/4;r=Number((.9*r).toFixed(5));var a=Number((2*r).toFixed(5)),i=Number((a*io.internal.Bezier_C).toFixed(5));return n.push("0.749023 g"),n.push("q"),n.push("1 0 0 1 "+uA(io.internal.getWidth(s)/2)+" "+uA(io.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:io.RadioButton.Cross.OffPushDown},N:{}};return t.N[s]=io.RadioButton.Cross.YesNormal,t.D[s]=io.RadioButton.Cross.YesPushDown,t},getCA:function(){return"8"},YesNormal:function(s){var t=Xk(s);t.scope=s.scope;var n=[],r=io.internal.calculateCross(s);return n.push("q"),n.push("1 1 "+Vl(io.internal.getWidth(s)-2)+" "+Vl(io.internal.getHeight(s)-2)+" re"),n.push("W"),n.push("n"),n.push(Vl(r.x1.x)+" "+Vl(r.x1.y)+" m"),n.push(Vl(r.x2.x)+" "+Vl(r.x2.y)+" l"),n.push(Vl(r.x4.x)+" "+Vl(r.x4.y)+" m"),n.push(Vl(r.x3.x)+" "+Vl(r.x3.y)+" l"),n.push("s"),n.push("Q"),t.stream=n.join(` `),t},YesPushDown:function(s){var t=Xk(s);t.scope=s.scope;var n=io.internal.calculateCross(s),r=[];return r.push("0.749023 g"),r.push("0 0 "+Vl(io.internal.getWidth(s))+" "+Vl(io.internal.getHeight(s))+" re"),r.push("f"),r.push("q"),r.push("1 1 "+Vl(io.internal.getWidth(s)-2)+" "+Vl(io.internal.getHeight(s)-2)+" re"),r.push("W"),r.push("n"),r.push(Vl(n.x1.x)+" "+Vl(n.x1.y)+" m"),r.push(Vl(n.x2.x)+" "+Vl(n.x2.y)+" l"),r.push(Vl(n.x4.x)+" "+Vl(n.x4.y)+" m"),r.push(Vl(n.x3.x)+" "+Vl(n.x3.y)+" l"),r.push("s"),r.push("Q"),t.stream=r.join(` `),t},OffPushDown:function(s){var t=Xk(s);t.scope=s.scope;var n=[];return n.push("0.749023 g"),n.push("0 0 "+Vl(io.internal.getWidth(s))+" "+Vl(io.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}};io.internal={Bezier_C:.551915024494,calculateCross:function(s){var t=io.internal.getWidth(s),n=io.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}}}},io.internal.getWidth=function(s){var t=0;return Wu(s)==="object"&&(t=wyt(s.Rect[2])),t},io.internal.getHeight=function(s){var t=0;return Wu(s)==="object"&&(t=wyt(s.Rect[3])),t};var kEn=mf.addField=function(s){if(NEn(this,s),!(s instanceof uk))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};mf.AcroFormChoiceField=fB,mf.AcroFormListBox=xB,mf.AcroFormComboBox=gB,mf.AcroFormEditBox=Z2e,mf.AcroFormButton=m0,mf.AcroFormPushButton=X2e,mf.AcroFormRadioButton=yB,mf.AcroFormCheckBox=Q2e,mf.AcroFormTextField=KR,mf.AcroFormPasswordField=J2e,mf.AcroFormAppearance=io,mf.AcroForm={ChoiceField:fB,ListBox:xB,ComboBox:gB,EditBox:Z2e,Button:m0,PushButton:X2e,RadioButton:yB,CheckBox:Q2e,TextField:KR,PasswordField:J2e,Appearance:io},go.AcroForm={ChoiceField:fB,ListBox:xB,ComboBox:gB,EditBox:Z2e,Button:m0,PushButton:X2e,RadioButton:yB,CheckBox:Q2e,TextField:KR,PasswordField:J2e,Appearance:io};function c$t(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(B,q){var W,V,K,Q,J,ce=n;if((q=q||n)==="RGBA"||B.data!==void 0&&B.data instanceof Uint8ClampedArray&&"height"in B&&"width"in B)return"RGBA";if(T(B))for(J in r)for(K=r[J],W=0;W>"}),"transparency"in q&&Array.isArray(q.transparency)&&q.transparency.length>0){for(var J="",ce=0,ue=q.transparency.length;ce>",g.content=i;var N=g.objId+" 0 R";i="<>";else if(r.options.pageNumber)switch(i="<=0};s.__arabicParser__.arabicLetterHasIsolatedForm=function(g){return l(g)&&i(g)&&t[g.charCodeAt(0)].length>=1};var d=s.__arabicParser__.arabicLetterHasFinalForm=function(g){return l(g)&&i(g)&&t[g.charCodeAt(0)].length>=2};s.__arabicParser__.arabicLetterHasInitialForm=function(g){return l(g)&&i(g)&&t[g.charCodeAt(0)].length>=3};var u=s.__arabicParser__.arabicLetterHasMedialForm=function(g){return l(g)&&i(g)&&t[g.charCodeAt(0)].length==4},h=s.__arabicParser__.resolveLigatures=function(g){var y=0,b=n,v="",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}])}(go.API),function(s){var t={left:0,top:0,bottom:0,right:0},n=!1,r=function(){this.internal.__cell__===void 0&&(this.internal.__cell__={},this.internal.__cell__.padding=3,this.internal.__cell__.headerFunction=void 0,this.internal.__cell__.margins=Object.assign({},t),this.internal.__cell__.margins.width=this.getPageWidth(),a.call(this))},a=function(){this.internal.__cell__.lastCell=new i,this.internal.__cell__.pages=1},i=function(){var c=arguments[0];Object.defineProperty(this,"x",{enumerable:!0,get:function(){return c},set:function(g){c=g}});var d=arguments[1];Object.defineProperty(this,"y",{enumerable:!0,get:function(){return d},set:function(g){d=g}});var u=arguments[2];Object.defineProperty(this,"width",{enumerable:!0,get:function(){return u},set:function(g){u=g}});var h=arguments[3];Object.defineProperty(this,"height",{enumerable:!0,get:function(){return h},set:function(g){h=g}});var m=arguments[4];Object.defineProperty(this,"text",{enumerable:!0,get:function(){return m},set:function(g){m=g}});var p=arguments[5];Object.defineProperty(this,"lineNumber",{enumerable:!0,get:function(){return p},set:function(g){p=g}});var x=arguments[6];return Object.defineProperty(this,"align",{enumerable:!0,get:function(){return x},set:function(g){x=g}}),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,x=0,g=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 b=d.maxWidth;b>0?typeof c=="string"?c=this.splitTextToSize(c,b):Object.prototype.toString.call(c)==="[object Array]"&&(c=c.reduce(function(N,C){return N.concat(y.splitTextToSize(C,b))},[])):c=Array.isArray(c)?c:[c];for(var v=0;vthis.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,x,g,y,b=[],v=[],N=[],C={},A={},T=[],P=[],M=(m=m||{}).autoSize||!1,I=m.printHeaders!==!1,D=m.css&&m.css["font-size"]!==void 0?16*m.css["font-size"]:m.fontSize||12,B=m.margins||Object.assign({width:this.getPageWidth()},t),q=typeof m.padding=="number"?m.padding:3,W=m.headerBackgroundColor||"#c8c8c8",V=m.headerTextColor||"#000";if(a.call(this),this.internal.__cell__.printHeaders=I,this.internal.__cell__.margins=B,this.internal.__cell__.table_font_size=D,this.internal.__cell__.padding=q,this.internal.__cell__.headerBackgroundColor=W,this.internal.__cell__.headerTextColor=V,this.setFontSize(D),h==null)v=b=Object.keys(u[0]),N=b.map(function(){return"left"});else if(Array.isArray(h)&&Wu(h[0])==="object")for(b=h.map(function(ne){return ne.name}),v=h.map(function(ne){return ne.prompt||ne.name||""}),N=h.map(function(ne){return ne.align||"left"}),p=0;p0&&this.setTableHeaderRow(m),this.setFont(void 0,"normal"),n=!1}}(go.API);var d$t={italic:["italic","oblique","normal"],oblique:["oblique","italic","normal"],normal:["normal","oblique","italic"]},u$t=["ultra-condensed","extra-condensed","condensed","semi-condensed","normal","semi-expanded","expanded","extra-expanded","ultra-expanded"],VBe=c$t(u$t),h$t=[100,200,300,400,500,600,700,800,900],SEn=c$t(h$t);function rDe(s){var t=s.family.replace(/"|'/g,"").toLowerCase(),n=function(i){return d$t[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 VBe[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 jyt(s,t,n,r){var a;for(a=n;a>=0&&a=0&&a>>1)&255}return a}function Iyt(s,t,n){var r=s.length,a=[];a[0]=4;for(var i=0;i>i&l}function Dyt(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,m$t(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,x=null;for(this.width=n,this.height=r;d&&t=0))throw Error("Invalid block size");if(B===0)break;t+=B}break;case 249:if(s[t++]!==4||s[t+4]!==0)throw new Error("Invalid graphics extension block.");var g=s[t++];h=s[t++]|s[t++]<<8,m=s[t++],1&g||(m=null),p=g>>2&7,t++;break;case 254:for(;;){if(!((B=s[t++])>=0))throw Error("Invalid block size");if(B===0)break;t+=B}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,b=s[t++]|s[t++]<<8,v=s[t++]|s[t++]<<8,N=s[t++]|s[t++]<<8,C=s[t++],A=C>>6&1,T=1<<1+(7&C),P=o,M=c,I=!1;C>>7&&(I=!0,P=t,M=T,t+=3*T);var D=t;for(t++;;){var B;if(!((B=s[t++])>=0))throw Error("Invalid block size");if(B===0)break;t+=B}u.push({x:y,y:b,width:v,height:N,has_local_palette:I,palette_offset:P,palette_size:M,data_offset:D,data_length:t-D,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 x},this.frameInfo=function(q){if(q<0||q>=u.length)throw new Error("Frame index out of range.");return u[q]},this.decodeAndBlitFrameBGRA=function(q,W){var V=this.frameInfo(q),K=V.width*V.height;if(K>536870912)throw new Error("Image dimensions exceed 512MB, which is too large.");var Q=new Uint8Array(K);Ryt(s,V.data_offset,Q,K);var J=V.palette_offset,ce=V.transparent_index;ce===null&&(ce=256);var ue=V.width,ne=n-ue,ee=ue,le=4*(V.y*n+V.x),he=4*((V.y+V.height)*n+V.x),ve=le,ge=4*ne;V.interlaced===!0&&(ge+=4*n*7);for(var fe=8,je=0,Ee=Q.length;je=he&&(ge=4*ne+4*n*(fe-1),ve=le+(ue+ne)*(fe<<1),fe>>=1)),Me===ce)ve+=4;else{var De=s[J+3*Me],ze=s[J+3*Me+1],ke=s[J+3*Me+2];W[ve++]=ke,W[ve++]=ze,W[ve++]=De,W[ve++]=255}--ee}},this.decodeAndBlitFrameRGBA=function(q,W){var V=this.frameInfo(q),K=V.width*V.height;if(K>536870912)throw new Error("Image dimensions exceed 512MB, which is too large.");var Q=new Uint8Array(K);Ryt(s,V.data_offset,Q,K);var J=V.palette_offset,ce=V.transparent_index;ce===null&&(ce=256);var ue=V.width,ne=n-ue,ee=ue,le=4*(V.y*n+V.x),he=4*((V.y+V.height)*n+V.x),ve=le,ge=4*ne;V.interlaced===!0&&(ge+=4*n*7);for(var fe=8,je=0,Ee=Q.length;je=he&&(ge=4*ne+4*n*(fe-1),ve=le+(ue+ne)*(fe<<1),fe>>=1)),Me===ce)ve+=4;else{var De=s[J+3*Me],ze=s[J+3*Me+1],ke=s[J+3*Me+2];W[ve++]=De,W[ve++]=ze,W[ve++]=ke,W[ve++]=255}--ee}}}function Ryt(s,t,n,r){for(var a=s[t++],i=1<>=c,u-=c,y!==i){if(y===l)break;for(var b=yi;)N=x[N]>>8,++v;var C=N;if(m+v+(b!==y?1:0)>r)return void jh.log("Warning, gif stream longer than expected.");n[m++]=C;var A=m+=v;for(b!==y&&(n[m++]=C),N=b;v--;)N=x[N],n[--A]=255&N,N>>=8;g!==null&&o<4096&&(x[o++]=g<<8|C,o>=d+1&&c<12&&(++c,d=d<<1|1)),g=y}else o=l+1,d=(1<<(c=a+1))-1,g=null}return m!==r&&jh.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 oDe(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),x=new Array(64),g=[],y=0,b=7,v=new Array(64),N=new Array(64),C=new Array(64),A=new Array(256),T=new Array(2048),P=[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],D=[0,0,2,1,3,3,2,4,3,5,5,4,4,0,0,1,125],B=[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],q=[0,0,3,1,1,1,1,1,1,1,1,1,0,0,0,0,0],W=[0,1,2,3,4,5,6,7,8,9,10,11],V=[0,0,2,1,2,4,4,3,4,7,5,4,4,0,1,2,119],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 Q(le,he){for(var ve=0,ge=0,fe=new Array,je=1;je<=16;je++){for(var Ee=1;Ee<=le[je];Ee++)fe[he[ge]]=[],fe[he[ge]][0]=ve,fe[he[ge]][1]=je,ge++,ve++;ve*=2}return fe}function J(le){for(var he=le[0],ve=le[1]-1;ve>=0;)he&1<>8&255),ce(255&le)}function ne(le,he,ve,ge,fe){for(var je,Ee=fe[0],Me=fe[240],De=function(Ke,Ze){var Ue,et,Qe,Ge,nt,ft,lt,Mt,Ft,Ts,js=0;for(Ft=0;Ft<8;++Ft){Ue=Ke[js],et=Ke[js+1],Qe=Ke[js+2],Ge=Ke[js+3],nt=Ke[js+4],ft=Ke[js+5],lt=Ke[js+6];var zt=Ue+(Mt=Ke[js+7]),Nt=Ue-Mt,Ds=et+lt,_t=et-lt,Xs=Qe+ft,rn=Qe-ft,Ps=Ge+nt,_n=Ge-nt,Zs=zt+Ps,gr=zt-Ps,Un=Ds+Xs,In=Ds-Xs;Ke[js]=Zs+Un,Ke[js+4]=Zs-Un;var Ar=.707106781*(In+gr);Ke[js+2]=gr+Ar,Ke[js+6]=gr-Ar;var or=.382683433*((Zs=_n+rn)-(In=_t+Nt)),qs=.5411961*Zs+or,yr=1.306562965*In+or,fn=.707106781*(Un=rn+_t),Zn=Nt+fn,Xt=Nt-fn;Ke[js+5]=Xt+qs,Ke[js+3]=Xt-qs,Ke[js+1]=Zn+yr,Ke[js+7]=Zn-yr,js+=8}for(js=0,Ft=0;Ft<8;++Ft){Ue=Ke[js],et=Ke[js+8],Qe=Ke[js+16],Ge=Ke[js+24],nt=Ke[js+32],ft=Ke[js+40],lt=Ke[js+48];var rr=Ue+(Mt=Ke[js+56]),Qn=Ue-Mt,Sn=et+lt,$n=et-lt,tn=Qe+ft,ln=Qe-ft,Cr=Ge+nt,ms=Ge-nt,ot=rr+Cr,pt=rr-Cr,vt=Sn+tn,At=Sn-tn;Ke[js]=ot+vt,Ke[js+32]=ot-vt;var Zt=.707106781*(At+pt);Ke[js+16]=pt+Zt,Ke[js+48]=pt-Zt;var as=.382683433*((ot=ms+ln)-(At=$n+Qn)),Ls=.5411961*ot+as,cs=1.306562965*At+as,qt=.707106781*(vt=ln+$n),Gs=Qn+qt,Vs=Qn-qt;Ke[js+40]=Vs+Ls,Ke[js+24]=Vs-Ls,Ke[js+8]=Gs+cs,Ke[js+56]=Gs-cs,js++}for(Ft=0;Ft<64;++Ft)Ts=Ke[Ft]*Ze[Ft],p[Ft]=Ts>0?Ts+.5|0:Ts-.5|0;return p}(le,he),ze=0;ze<64;++ze)x[P[ze]]=De[ze];var ke=x[0]-ve;ve=x[0],ke==0?J(ge[0]):(J(ge[m[je=32767+ke]]),J(h[je]));for(var Xe=63;Xe>0&&x[Xe]==0;)Xe--;if(Xe==0)return J(Ee),ve;for(var Se,Re=1;Re<=Xe;){for(var Ae=Re;x[Re]==0&&Re<=Xe;)++Re;var Be=Re-Ae;if(Be>=16){Se=Be>>4;for(var qe=1;qe<=Se;++qe)J(Me);Be&=15}je=32767+x[Re],J(fe[(Be<<4)+m[je]]),J(h[je]),Re++}return Xe!=63&&J(Ee),ve}function ee(le){le=Math.min(Math.max(le,1),100),i!=le&&(function(he){for(var ve=[16,11,10,16,24,40,51,61,12,12,14,19,26,58,60,55,14,13,16,24,40,57,69,56,14,17,22,29,51,87,80,62,18,22,37,56,68,109,103,77,24,35,55,64,81,104,113,92,49,64,78,87,103,121,120,101,72,92,95,98,112,100,103,99],ge=0;ge<64;ge++){var fe=l((ve[ge]*he+50)/100);fe=Math.min(Math.max(fe,1),255),o[P[ge]]=fe}for(var je=[17,18,24,47,99,99,99,99,18,21,26,66,99,99,99,99,24,26,56,99,99,99,99,99,47,66,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99],Ee=0;Ee<64;Ee++){var Me=l((je[Ee]*he+50)/100);Me=Math.min(Math.max(Me,1),255),c[P[Ee]]=Me}for(var De=[1,1.387039845,1.306562965,1.175875602,1,.785694958,.5411961,.275899379],ze=0,ke=0;ke<8;ke++)for(var Xe=0;Xe<8;Xe++)d[ze]=1/(o[P[ze]]*De[ke]*De[Xe]*8),u[ze]=1/(c[P[ze]]*De[ke]*De[Xe]*8),ze++}(le<50?Math.floor(5e3/le):Math.floor(200-2*le)),i=le)}this.encode=function(le,he){he&&ee(he),g=new Array,y=0,b=7,ue(65496),ue(65504),ue(16),ce(74),ce(70),ce(73),ce(70),ce(0),ce(1),ce(1),ce(0),ue(1),ue(1),ce(0),ce(0),function(){ue(65499),ue(132),ce(0);for(var et=0;et<64;et++)ce(o[et]);ce(1);for(var Qe=0;Qe<64;Qe++)ce(c[Qe])}(),function(et,Qe){ue(65472),ue(17),ce(8),ue(Qe),ue(et),ce(3),ce(1),ce(17),ce(0),ce(2),ce(17),ce(1),ce(3),ce(17),ce(1)}(le.width,le.height),function(){ue(65476),ue(418),ce(0);for(var et=0;et<16;et++)ce(M[et+1]);for(var Qe=0;Qe<=11;Qe++)ce(I[Qe]);ce(16);for(var Ge=0;Ge<16;Ge++)ce(D[Ge+1]);for(var nt=0;nt<=161;nt++)ce(B[nt]);ce(1);for(var ft=0;ft<16;ft++)ce(q[ft+1]);for(var lt=0;lt<=11;lt++)ce(W[lt]);ce(17);for(var Mt=0;Mt<16;Mt++)ce(V[Mt+1]);for(var Ft=0;Ft<=161;Ft++)ce(K[Ft])}(),ue(65498),ue(12),ce(3),ce(1),ce(0),ce(2),ce(17),ce(3),ce(17),ce(0),ce(63),ce(0);var ve=0,ge=0,fe=0;y=0,b=7,this.encode.displayName="_encode_";for(var je,Ee,Me,De,ze,ke,Xe,Se,Re,Ae=le.data,Be=le.width,qe=le.height,Ke=4*Be,Ze=0;Ze>3)*Ke+(Xe=4*(7&Re)),Ze+Se>=qe&&(ke-=Ke*(Ze+1+Se-qe)),je+Xe>=Ke&&(ke-=je+Xe-Ke+4),Ee=Ae[ke++],Me=Ae[ke++],De=Ae[ke++],v[Re]=(T[Ee]+T[Me+256|0]+T[De+512|0]>>16)-128,N[Re]=(T[Ee+768|0]+T[Me+1024|0]+T[De+1280|0]>>16)-128,C[Re]=(T[Ee+1280|0]+T[Me+1536|0]+T[De+1792|0]>>16)-128;ve=ne(v,d,ve,t,r),ge=ne(N,u,ge,n,a),fe=ne(C,u,fe,n,a),je+=32}Ze+=8}if(b>=0){var Ue=[];Ue[1]=b+1,Ue[0]=(1<q;q++)if(I[D+q]!=B.charCodeAt(q))return!0;return!1}function r(I,D,B,q,W){for(var V=0;VV+1?[]:new D),!(K.length>>0;Ce&mt;)mt>>>=1;return mt?(Ce&mt-1)+mt:Ce}function B(Ce,Fe,mt,bt,Yt){t(!(bt%mt));do Ce[Fe+(bt-=mt)]=Yt;while(0=Yt),512>=Yt)var ls=i(512);else if((ls=i(Yt))==null)return 0;return function(ps,Ss,Es,Qs,Cn,Xn){var Js,On,nr=Ss,Mr=1<Js;++Js){if(xr[Js]>1<(sl-=xr[Js]))return 0;for(;0=Js;++Js,Cn<<=1){if(bi+=sl<<=1,0>(sl-=xr[Js]))return 0;for(;0ba&&!(0>=($r-=xr[ba]));)++ba,$r<<=1;Mr+=Li=1<<($r=ba-Es),ps[Ss+(ba=Fi&fa)].g=$r+Es,ps[Ss+ba].value=nr-Ss-ba}Qs.g=Js-Es,Qs.value=Xn[On++],B(ps,nr+(Fi>>Es),Cn,Li,Qs),Fi=D(Fi,Js)}}return bi!=2*Fn[15]-1?0:Mr}(Ce,Fe,mt,bt,Yt,ls)}function W(){this.value=this.g=0}function V(){this.value=this.g=0}function K(){this.G=l(5,W),this.H=i(5),this.jc=this.Qb=this.qb=this.nd=0,this.pd=l(Yl,V)}function Q(Ce,Fe,mt,bt){t(Ce!=null),t(Fe!=null),t(2147483648>bt),Ce.Ca=254,Ce.I=0,Ce.b=-8,Ce.Ka=0,Ce.oa=Fe,Ce.pa=mt,Ce.Jd=Fe,Ce.Yc=mt+bt,Ce.Zc=4<=bt?mt+bt-4+1:mt,Ee(Ce)}function J(Ce,Fe){for(var mt=0;0bt),Ce.Sb=bt,Ce.Ra=0,Ce.u=0,Ce.h=0,4>>=8,Ce.Ra+=Ce.oa[Ce.pa+Ce.bb]<>>0,++Ce.bb,Ce.u-=8;ge(Ce)&&(Ce.h=1,Ce.u=0)}function ee(Ce,Fe){if(t(0<=Fe),!Ce.h&&Fe<=Pm){var mt=ve(Ce)&La[Fe];return Ce.u+=Fe,ne(Ce),mt}return Ce.h=1,Ce.u=0}function le(){this.b=this.Ca=this.I=0,this.oa=[],this.pa=0,this.Jd=[],this.Yc=0,this.Zc=[],this.Ka=0}function he(){this.Ra=0,this.oa=[],this.h=this.u=this.bb=this.Sb=this.pa=0}function ve(Ce){return Ce.Ra>>>(Ce.u&dd-1)>>>0}function ge(Ce){return t(Ce.bb<=Ce.Sb),Ce.h||Ce.bb==Ce.Sb&&Ce.u>dd}function fe(Ce,Fe){Ce.u=Fe,Ce.h=ge(Ce)}function je(Ce){Ce.u>=pa&&(t(Ce.u>=pa),ne(Ce))}function Ee(Ce){t(Ce!=null&&Ce.oa!=null),Ce.pa>>0,Ce.b+=8):(t(Ce!=null&&Ce.oa!=null),Ce.paCe.b&&Ee(Ce);var bt=Ce.b,Yt=mt*Fe>>>8,ls=(Ce.I>>>bt>Yt)+0;for(ls?(mt-=Yt,Ce.I-=Yt+1<>>0):mt=Yt+1,bt=mt,Yt=0;256<=bt;)Yt+=8,bt>>=8;return bt=7^Yt+Gx[bt],Ce.b-=bt,Ce.Ca=(mt<>24&255,Ce[Fe+1]=mt>>16&255,Ce[Fe+2]=mt>>8&255,Ce[Fe+3]=255&mt}function ke(Ce,Fe){return Ce[Fe+0]|Ce[Fe+1]<<8}function Xe(Ce,Fe){return ke(Ce,Fe)|Ce[Fe+2]<<16}function Se(Ce,Fe){return ke(Ce,Fe)|ke(Ce,Fe+2)<<16}function Re(Ce,Fe){var mt=1<=Yt||0>=ls?0:(mt[0]=Yt,bt[0]=ls,1)}function Ke(Ce,Fe){return Ce+(1<>>Fe}function Ze(Ce,Fe){return((4278255360&Ce)+(4278255360&Fe)>>>0&4278255360)+((16711935&Ce)+(16711935&Fe)>>>0&16711935)>>>0}function Ue(Ce,Fe){I[Fe]=function(mt,bt,Yt,ls,ps,Ss,Es){var Qs;for(Qs=0;Qs>>1)+(Ce&Fe)>>>0}function Ge(Ce){return 0<=Ce&&256>Ce?Ce:0>Ce?0:255>1))}function ft(Ce,Fe,mt){return Math.abs(Fe-mt)-Math.abs(Ce-mt)}function lt(Ce,Fe,mt,bt,Yt,ls,ps){for(bt=ls[ps-1],mt=0;mt>8&255,Es=16711935&(Es=(Es=16711935&ps)+((Ss<<16)+Ss));bt[Yt+ls]=(4278255360&ps)+Es>>>0}}function Ft(Ce,Fe){Fe.jd=255&Ce,Fe.hd=Ce>>8&255,Fe.ud=Ce>>16&255}function Ts(Ce,Fe,mt,bt,Yt,ls){var ps;for(ps=0;ps>>8,Qs=Ss,Cn=255&(Cn=(Cn=Ss>>>16)+((Ce.jd<<24>>24)*(Es<<24>>24)>>>5));Qs=255&(Qs=(Qs+=(Ce.hd<<24>>24)*(Es<<24>>24)>>>5)+((Ce.ud<<24>>24)*(Cn<<24>>24)>>>5)),Yt[ls+ps]=(4278255360&Ss)+(Cn<<16)+Qs}}function js(Ce,Fe,mt,bt,Yt){I[Fe]=function(ls,ps,Ss,Es,Qs,Cn,Xn,Js,On){for(Es=Xn;Es>ls.b,On=ls.Ea,nr=ls.K[0],Mr=ls.w;if(8>Js)for(ls=(1<>=Js}else I["VP8LMapColor"+mt](Es,Qs,nr,Mr,Cn,Xn,ps,Ss,On)}}function zt(Ce,Fe,mt,bt,Yt){for(mt=Fe+mt;Fe>16&255,bt[Yt++]=ls>>8&255,bt[Yt++]=255&ls}}function Nt(Ce,Fe,mt,bt,Yt){for(mt=Fe+mt;Fe>16&255,bt[Yt++]=ls>>8&255,bt[Yt++]=255&ls,bt[Yt++]=ls>>24&255}}function Ds(Ce,Fe,mt,bt,Yt){for(mt=Fe+mt;Fe>16&240|ps>>12&15,ps=240&ps|ps>>28&15;bt[Yt++]=ls,bt[Yt++]=ps}}function _t(Ce,Fe,mt,bt,Yt){for(mt=Fe+mt;Fe>16&248|ps>>13&7,ps=ps>>5&224|ps>>3&31;bt[Yt++]=ls,bt[Yt++]=ps}}function Xs(Ce,Fe,mt,bt,Yt){for(mt=Fe+mt;Fe>8&255,bt[Yt++]=ls>>16&255}}function rn(Ce,Fe,mt,bt,Yt,ls){if(ls==0)for(mt=Fe+mt;Fe>24|ls[1]>>8&65280|ls[2]<<8&16711680|ls[3]<<24)>>>0),Yt+=32;else r(bt,Yt,Ce,Fe,mt)}function Ps(Ce,Fe){I[Fe][0]=I[Ce+"0"],I[Fe][1]=I[Ce+"1"],I[Fe][2]=I[Ce+"2"],I[Fe][3]=I[Ce+"3"],I[Fe][4]=I[Ce+"4"],I[Fe][5]=I[Ce+"5"],I[Fe][6]=I[Ce+"6"],I[Fe][7]=I[Ce+"7"],I[Fe][8]=I[Ce+"8"],I[Fe][9]=I[Ce+"9"],I[Fe][10]=I[Ce+"10"],I[Fe][11]=I[Ce+"11"],I[Fe][12]=I[Ce+"12"],I[Fe][13]=I[Ce+"13"],I[Fe][14]=I[Ce+"0"],I[Fe][15]=I[Ce+"0"]}function _n(Ce){return Ce==Cv||Ce==j2||Ce==Lw||Ce==Ug}function Zs(){this.eb=[],this.size=this.A=this.fb=0}function gr(){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 Un(){this.Rd=this.height=this.width=this.S=0,this.f={},this.f.RGBA=new Zs,this.f.kb=new gr,this.sd=null}function In(){this.width=[0],this.height=[0],this.Pd=[0],this.Qd=[0],this.format=[0]}function Ar(){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 or(Ce){return alert("todo:WebPSamplerProcessPlane"),Ce.T}function qs(Ce,Fe){var mt=Ce.T,bt=Fe.ba.f.RGBA,Yt=bt.eb,ls=bt.fb+Ce.ka*bt.A,ps=Xp[Fe.ba.S],Ss=Ce.y,Es=Ce.O,Qs=Ce.f,Cn=Ce.N,Xn=Ce.ea,Js=Ce.W,On=Fe.cc,nr=Fe.dc,Mr=Fe.Mc,xr=Fe.Nc,Fn=Ce.ka,$r=Ce.ka+Ce.T,ba=Ce.U,fa=ba+1>>1;for(Fn==0?ps(Ss,Es,null,null,Qs,Cn,Xn,Js,Qs,Cn,Xn,Js,Yt,ls,null,null,ba):(ps(Fe.ec,Fe.fc,Ss,Es,On,nr,Mr,xr,Qs,Cn,Xn,Js,Yt,ls-bt.A,Yt,ls,ba),++mt);Fn+2<$r;Fn+=2)On=Qs,nr=Cn,Mr=Xn,xr=Js,Cn+=Ce.Rc,Js+=Ce.Rc,ls+=2*bt.A,ps(Ss,(Es+=2*Ce.fa)-Ce.fa,Ss,Es,On,nr,Mr,xr,Qs,Cn,Xn,Js,Yt,ls-bt.A,Yt,ls,ba);return Es+=Ce.fa,Ce.j+$rmt,Yt=mt==O1||mt==Zp||mt==Ly||mt==$0||mt==12||_n(mt);if(Fe.memory=null,Fe.Ib=null,Fe.Jb=null,Fe.Nd=null,!kl(Fe.Oa,Ce,Yt?11:12))return 0;if(Yt&&_n(mt)&&lm(),Ce.da)alert("todo:use_scaling");else{if(bt){if(Fe.Ib=or,Ce.Kb){if(mt=Ce.U+1>>1,Fe.memory=i(Ce.U+2*mt),Fe.memory==null)return 0;Fe.ec=Fe.memory,Fe.fc=0,Fe.cc=Fe.ec,Fe.dc=Fe.fc+Ce.U,Fe.Mc=Fe.cc,Fe.Nc=Fe.dc+mt,Fe.Ib=qs,lm()}}else alert("todo:EmitYUV");Yt&&(Fe.Jb=yr,bt&&Kl())}if(bt&&!Fw){for(Ce=0;256>Ce;++Ce)zw[Ce]=89858*(Ce-128)+Rw>>Py,vk[Ce]=-22014*(Ce-128)+Rw,S2[Ce]=-45773*(Ce-128),r_[Ce]=113618*(Ce-128)+Rw>>Py;for(Ce=Ow;Ce>Py,LC[Ce-Ow]=Wa(Fe,255),a_[Ce-Ow]=Wa(Fe+8>>4,15);Fw=1}return 1}function Zn(Ce){var Fe=Ce.ma,mt=Ce.U,bt=Ce.T;return t(!(1&Ce.ka)),0>=mt||0>=bt?0:(mt=Fe.Ib(Ce,Fe),Fe.Jb!=null&&Fe.Jb(Ce,Fe,mt),Fe.Dc+=mt,1)}function Xt(Ce){Ce.ma.memory=null}function rr(Ce,Fe,mt,bt){return ee(Ce,8)!=47?0:(Fe[0]=ee(Ce,14)+1,mt[0]=ee(Ce,14)+1,bt[0]=ee(Ce,1),ee(Ce,3)!=0?0:!Ce.h)}function Qn(Ce,Fe){if(4>Ce)return Ce+1;var mt=Ce-2>>1;return(2+(1&Ce)<>4)*Ce+(8-(15&mt)))?mt:1;var mt}function $n(Ce,Fe,mt){var bt=ve(mt),Yt=Ce[Fe+=255&bt].g-8;return 0>>0,t(8>=mt.g),Ce.g}function ln(Ce,Fe,mt){var bt=Ce.xc;return t((Fe=bt==0?0:Ce.vc[Ce.md*(mt>>bt)+(Fe>>bt)])>Li.b)*bi;Mrba&&(Di=ba),(0,yu[Dl[Pd++]>>8&15])(Js,On+ +nl,Fn,$r+nl-ba,Di-nl,Fn,$r+nl),nl=Di}On+=ba,$r+=ba,++Mr&Fi||(Li+=bi)}Xn!=Qs.nc&&r(Es,Ss-nr,Es,Ss+(Xn-Cn-1)*nr,nr);break;case 1:for(nr=Js,xr=On,ba=(Js=Qs.Ea)-($r=Js&~(Fn=(On=1<>Qs.b)*Mr;Cn=Yt),0ls.o&&(bt=ls.o),mt=bt?mt=0:(Yt[0]+=4*ls.v,ls.ka=mt-ls.j,ls.U=ls.va-ls.v,ls.T=bt-mt,mt=1),mt){if(Ss=Ss[0],11>(mt=Ce.ca).S){var Cn=mt.f.RGBA,Xn=(bt=mt.S,Yt=ls.U,ls=ls.T,Qs=Cn.eb,Cn.A),Js=ls;for(Cn=Cn.fb+Ce.Ma*Cn.A;0bt){var Yt=Ce.l.width,ls=mt.ca,ps=mt.tb+Yt*bt,Ss=Ce.V,Es=Ce.Ba+Ce.c*bt,Qs=Ce.gc;t(Ce.ab==1),t(Qs[0].hc==3),hp(Qs[0],bt,Fe,Ss,Es,ls,ps),pt(mt,bt,Fe,ls,ps,Yt)}Ce.C=Ce.Ma=Fe}function At(Ce,Fe,mt,bt,Yt,ls,ps){var Ss=Ce.$/bt,Es=Ce.$%bt,Qs=Ce.m,Cn=Ce.s,Xn=mt+Ce.$,Js=Xn;Yt=mt+bt*Yt;var On=mt+bt*ls,nr=280+Cn.ua,Mr=Ce.Pb?Ss:16777216,xr=0=Mr){var Fi=Xn-mt;t((Mr=Ce).Pb),Mr.wd=Mr.m,Mr.xd=Fi,0sl.g?(fe(fa,fa.u+sl.g),Fi[bi]=sl.value,fa=0):(fe(fa,fa.u+sl.g-256),t(256<=sl.value),fa=sl.value),fa==0&&(ba=!0)}else fa=$n($r.G[0],$r.H[0],Qs);if(Qs.h)break;if(ba||256>fa){if(!ba)if($r.nd)Fe[Xn]=($r.qb|fa<<8)>>>0;else{if(je(Qs),ba=$n($r.G[1],$r.H[1],Qs),je(Qs),Fi=$n($r.G[2],$r.H[2],Qs),bi=$n($r.G[3],$r.H[3],Qs),Qs.h)break;Fe[Xn]=(bi<<24|ba<<16|fa<<8|Fi)>>>0}if(ba=!1,++Xn,++Es>=bt&&(Es=0,++Ss,ps!=null&&Ss<=ls&&!(Ss%16)&&ps(Ce,Ss),xr!=null))for(;Js>>xr.Mb]=fa}else if(280>fa){if(fa=Qn(fa-256,Qs),Fi=$n($r.G[4],$r.H[4],Qs),je(Qs),Fi=Sn(bt,Fi=Qn(Fi,Qs)),Qs.h)break;if(Xn-mt=bt;)Es-=bt,++Ss,ps!=null&&Ss<=ls&&!(Ss%16)&&ps(Ce,Ss);if(t(Xn<=Yt),Es&Fn&&($r=ln(Cn,Es,Ss)),xr!=null)for(;Js>>xr.Mb]=fa}else{if(!(fa>>xr.Mb]=fa;fa=Xn,t(!(ba>>>(Fi=xr).Xa)),Fe[fa]=Fi.X[ba],ba=!0}ba||t(Qs.h==ge(Qs))}if(Ce.Pb&&Qs.h&&Xnls?ls:Ss),Ce.a=0,Ce.$=Xn-mt}return 1}return Ce.a=3,0}function Zt(Ce){t(Ce!=null),Ce.vc=null,Ce.yc=null,Ce.Ya=null;var Fe=Ce.Wa;Fe!=null&&(Fe.X=null),Ce.vb=null,t(Ce!=null)}function as(){var Ce=new Cs;return Ce==null?null:(Ce.a=0,Ce.xb=X5,Ps("Predictor","VP8LPredictors"),Ps("Predictor","VP8LPredictors_C"),Ps("PredictorAdd","VP8LPredictorsAdd"),Ps("PredictorAdd","VP8LPredictorsAdd_C"),R0=Mt,Qc=Ts,mp=zt,Nv=Nt,kv=Ds,Ac=_t,Wx=Xs,I.VP8LMapColor32b=qc,I.VP8LMapColor8b=fh,Ce)}function Ls(Ce,Fe,mt,bt,Yt){var ls=1,ps=[Ce],Ss=[Fe],Es=bt.m,Qs=bt.s,Cn=null,Xn=0;e:for(;;){if(mt)for(;ls&&ee(Es,1);){var Js=ps,On=Ss,nr=bt,Mr=1,xr=nr.m,Fn=nr.gc[nr.ab],$r=ee(xr,2);if(nr.Oc&1<<$r)ls=0;else{switch(nr.Oc|=1<<$r,Fn.hc=$r,Fn.Ea=Js[0],Fn.nc=On[0],Fn.K=[null],++nr.ab,t(4>=nr.ab),$r){case 0:case 1:Fn.b=ee(xr,3)+2,Mr=Ls(Ke(Fn.Ea,Fn.b),Ke(Fn.nc,Fn.b),0,nr,Fn.K),Fn.K=Fn.K[0];break;case 3:var ba,fa=ee(xr,8)+1,Fi=16>Li.b),Pd=i(Dl);if(Pd==null)ba=0;else{var nl=Li.K[0],Di=Li.w;for(Pd[0]=Li.K[0][0],bi=1;bi<1*sl;++bi)Pd[bi]=Ze(nl[Di+bi],Pd[bi-1]);for(;bi<4*Dl;++bi)Pd[bi]=0;Li.K[0]=null,Li.K[0]=Pd,ba=1}}Mr=ba;break;case 2:break;default:t(0)}ls=Mr}}if(ps=ps[0],Ss=Ss[0],ls&&ee(Es,1)&&!(ls=1<=(Xn=ee(Es,4))&&11>=Xn)){bt.a=3;break e}var ti;if(ti=ls)t:{var ol,co,Yo,jd=bt,Oh=ps,Nd=Ss,tu=Xn,Xd=mt,Jp=jd.m,ud=jd.s,gc=[null],ed=1,_u=0,Tc=MC[tu];s:for(;;){if(Xd&&ee(Jp,1)){var Iu=ee(Jp,3)+2,Im=Ke(Oh,Iu),Vc=Ke(Nd,Iu),th=Im*Vc;if(!Ls(Im,Vc,0,jd,gc))break s;for(gc=gc[0],ud.xc=Iu,ol=0;ol>8&65535;gc[ol]=Xl,Xl>=ed&&(ed=Xl+1)}}if(Jp.h)break s;for(co=0;5>co;++co){var Du=mk[co];!co&&0=Id),tf=ef;var Rm=i(_u);if(tf==null||Rm==null||Dm==null){jd.a=1;break s}var vh=Dm;for(ol=Yo=0;olco;++co){Du=mk[co],br[co]=vh,No[co]=Yo,!co&&0q1)break n}else Ry=q1;for(gx=0;gxH1)Hw[gx++]=H1,H1!=0&&(V0=H1);else{var e4=H1==16,bk=H1-16,Tv=ho[bk],Mv=ee(wu,W5[bk])+Tv;if(gx+Mv>q1)break n;for(var t4=e4?V0:0;0=co){var Lv,Gg=Rm[0];for(Lv=1;LvGg&&(Gg=Rm[Lv]);vc+=Gg}}if(yc.nd=lc,yc.Qb=0,lc&&(yc.qb=(br[3][No[3]+0].value<<24|br[1][No[1]+0].value<<16|br[2][No[2]+0].value)>>>0,Fc==0&&256>br[0][No[0]+0].value&&(yc.Qb=1,yc.qb+=br[0][No[0]+0].value<<8)),yc.jc=!yc.Qb&&6>vc,yc.jc){var C2,Ru=yc;for(C2=0;C2>=tn(rf,8,Dd),um>>=tn(Ru.G[1][Ru.H[1]+um],16,Dd),um>>=tn(Ru.G[2][Ru.H[2]+um],0,Dd),tn(Ru.G[3][Ru.H[3]+um],24,Dd))}}}ud.vc=gc,ud.Wb=ed,ud.Ya=tf,ud.yc=Dm,ti=1;break t}ti=0}if(!(ls=ti)){bt.a=3;break e}if(0bt+1?[]:0),!(Yt.lengthCe?0:Ce>Fe?Fe:Ce}function wo(){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 Io(){var Ce=new Ei;return Ce!=null&&(Ce.a=0,Ce.sc="OK",Ce.cb=0,Ce.Xb=0,F1||(F1=Kn)),Ce}function is(Ce,Fe,mt){return Ce.a==0&&(Ce.a=Fe,Ce.sc=mt,Ce.cb=0),0}function zr(Ce,Fe,mt){return 3<=mt&&Ce[Fe+0]==157&&Ce[Fe+1]==1&&Ce[Fe+2]==42}function Sa(Ce,Fe){if(Ce==null)return 0;if(Ce.a=0,Ce.sc="OK",Fe==null)return is(Ce,2,"null VP8Io passed to VP8GetHeaders()");var mt=Fe.data,bt=Fe.w,Yt=Fe.ha;if(4>Yt)return is(Ce,7,"Truncated header.");var ls=mt[bt+0]|mt[bt+1]<<8|mt[bt+2]<<16,ps=Ce.Od;if(ps.Rb=!(1&ls),ps.td=ls>>1&7,ps.yd=ls>>4&1,ps.ub=ls>>5,3Yt)return is(Ce,7,"cannot parse picture header");if(!zr(mt,bt,Yt))return is(Ce,3,"Bad code word");Ss.c=16383&(mt[bt+4]<<8|mt[bt+3]),Ss.Td=mt[bt+4]>>6,Ss.i=16383&(mt[bt+6]<<8|mt[bt+5]),Ss.Ud=mt[bt+6]>>6,bt+=7,Yt-=7,Ce.za=Ss.c+15>>4,Ce.Ub=Ss.i+15>>4,Fe.width=Ss.c,Fe.height=Ss.i,Fe.Da=0,Fe.j=0,Fe.v=0,Fe.va=Fe.width,Fe.o=Fe.height,Fe.da=0,Fe.ib=Fe.width,Fe.hb=Fe.height,Fe.U=Fe.width,Fe.T=Fe.height,a((ls=Ce.Pa).jb,0,255,ls.jb.length),t((ls=Ce.Qa)!=null),ls.Cb=0,ls.Bb=0,ls.Fb=1,a(ls.Zb,0,0,ls.Zb.length),a(ls.Lb,0,0,ls.Lb)}if(ps.ub>Yt)return is(Ce,7,"bad partition length");Q(ls=Ce.m,mt,bt,ps.ub),bt+=ps.ub,Yt-=ps.ub,ps.Rb&&(Ss.Ld=Me(ls),Ss.Kd=Me(ls)),Ss=Ce.Qa;var Es,Qs=Ce.Pa;if(t(ls!=null),t(Ss!=null),Ss.Cb=Me(ls),Ss.Cb){if(Ss.Bb=Me(ls),Me(ls)){for(Ss.Fb=Me(ls),Es=0;4>Es;++Es)Ss.Zb[Es]=Me(ls)?ce(ls,7):0;for(Es=0;4>Es;++Es)Ss.Lb[Es]=Me(ls)?ce(ls,6):0}if(Ss.Bb)for(Es=0;3>Es;++Es)Qs.jb[Es]=Me(ls)?J(ls,8):255}else Ss.Bb=0;if(ls.Ka)return is(Ce,3,"cannot parse segment header");if((Ss=Ce.ed).zd=Me(ls),Ss.Tb=J(ls,6),Ss.wb=J(ls,3),Ss.Pc=Me(ls),Ss.Pc&&Me(ls)){for(Qs=0;4>Qs;++Qs)Me(ls)&&(Ss.vd[Qs]=ce(ls,6));for(Qs=0;4>Qs;++Qs)Me(ls)&&(Ss.od[Qs]=ce(ls,6))}if(Ce.L=Ss.Tb==0?0:Ss.zd?1:2,ls.Ka)return is(Ce,3,"cannot parse filter header");var Cn=Yt;if(Yt=Es=bt,bt=Es+Cn,Ss=Cn,Ce.Xb=(1<Ss&&(Xn=Ss),Q(Ce.Jc[+Cn],mt,Es,Xn),Es+=Xn,Ss-=Xn,Yt+=3}Q(Ce.Jc[+Qs],mt,Es,Ss),mt=EsXn;++Xn){if(Cn.Cb){var Js=Cn.Zb[Xn];Cn.Fb||(Js+=mt)}else{if(0>16,8>On.Eb[1]&&(On.Eb[1]=8),On.Qc[0]=s_[Wa(Js+Qs,117)],On.Qc[1]=Z5[Wa(Js+Es,127)],On.lc=Js+Es}if(!ps.Rb)return is(Ce,4,"Not a key frame.");for(Me(ls),ps=Ce.Pa,mt=0;4>mt;++mt){for(Yt=0;8>Yt;++Yt)for(bt=0;3>bt;++bt)for(Ss=0;11>Ss;++Ss)Qs=De(ls,z1[mt][Yt][bt][Ss])?J(ls,8):n_[mt][Yt][bt][Ss],ps.Wc[mt][Yt].Yb[bt][Ss]=Qs;for(Yt=0;17>Yt;++Yt)ps.Xc[mt][Yt]=ps.Wc[mt][B1[Yt]]}return Ce.kc=Me(ls),Ce.kc&&(Ce.Bd=J(ls,8)),Ce.cb=1}function Kn(Ce,Fe,mt,bt,Yt,ls,ps){var Ss=Fe[Yt].Yb[mt];for(mt=0;16>Yt;++Yt){if(!De(Ce,Ss[mt+0]))return Yt;for(;!De(Ce,Ss[mt+1]);)if(Ss=Fe[++Yt].Yb[0],mt=0,Yt==16)return 16;var Es=Fe[Yt+1].Yb;if(De(Ce,Ss[mt+2])){var Qs=Ce,Cn=0;if(De(Qs,(Js=Ss)[(Xn=mt)+3]))if(De(Qs,Js[Xn+6])){for(Ss=0,Xn=2*(Cn=De(Qs,Js[Xn+8]))+(Js=De(Qs,Js[Xn+9+Cn])),Cn=0,Js=aM[Xn];Js[Ss];++Ss)Cn+=Cn+De(Qs,Js[Ss]);Cn+=3+(8<(Qs=Ce).b&&Ee(Qs);var Xn,Js=Qs.b,On=(Xn=Qs.Ca>>1)-(Qs.I>>Js)>>31;--Qs.b,Qs.Ca+=On,Qs.Ca|=1,Qs.I-=(Xn+1&On)<>3),Ce[Fe+mt+32*bt]=-256&Yt?0>Yt?0:255:Yt}function ca(Ce,Fe,mt,bt,Yt,ls){Ur(Ce,Fe,0,mt,bt+Yt),Ur(Ce,Fe,1,mt,bt+ls),Ur(Ce,Fe,2,mt,bt-ls),Ur(Ce,Fe,3,mt,bt-Yt)}function yo(Ce){return(20091*Ce>>16)+Ce}function vo(Ce,Fe,mt,bt){var Yt,ls=0,ps=i(16);for(Yt=0;4>Yt;++Yt){var Ss=Ce[Fe+0]+Ce[Fe+8],Es=Ce[Fe+0]-Ce[Fe+8],Qs=(35468*Ce[Fe+4]>>16)-yo(Ce[Fe+12]),Cn=yo(Ce[Fe+4])+(35468*Ce[Fe+12]>>16);ps[ls+0]=Ss+Cn,ps[ls+1]=Es+Qs,ps[ls+2]=Es-Qs,ps[ls+3]=Ss-Cn,ls+=4,Fe++}for(Yt=ls=0;4>Yt;++Yt)Ss=(Ce=ps[ls+0]+4)+ps[ls+8],Es=Ce-ps[ls+8],Qs=(35468*ps[ls+4]>>16)-yo(ps[ls+12]),Ur(mt,bt,0,0,Ss+(Cn=yo(ps[ls+4])+(35468*ps[ls+12]>>16))),Ur(mt,bt,1,0,Es+Qs),Ur(mt,bt,2,0,Es-Qs),Ur(mt,bt,3,0,Ss-Cn),ls++,bt+=32}function Vo(Ce,Fe,mt,bt){var Yt=Ce[Fe+0]+4,ls=35468*Ce[Fe+4]>>16,ps=yo(Ce[Fe+4]),Ss=35468*Ce[Fe+1]>>16;ca(mt,bt,0,Yt+ps,Ce=yo(Ce[Fe+1]),Ss),ca(mt,bt,1,Yt+ls,Ce,Ss),ca(mt,bt,2,Yt-ls,Ce,Ss),ca(mt,bt,3,Yt-ps,Ce,Ss)}function Xc(Ce,Fe,mt,bt,Yt){vo(Ce,Fe,mt,bt),Yt&&vo(Ce,Fe+16,mt,bt+4)}function uo(Ce,Fe,mt,bt){xh(Ce,Fe+0,mt,bt,1),xh(Ce,Fe+32,mt,bt+128,1)}function bo(Ce,Fe,mt,bt){var Yt;for(Ce=Ce[Fe+0]+4,Yt=0;4>Yt;++Yt)for(Fe=0;4>Fe;++Fe)Ur(mt,bt,Fe,Yt,Ce)}function od(Ce,Fe,mt,bt){Ce[Fe+0]&&vu(Ce,Fe+0,mt,bt),Ce[Fe+16]&&vu(Ce,Fe+16,mt,bt+4),Ce[Fe+32]&&vu(Ce,Fe+32,mt,bt+128),Ce[Fe+48]&&vu(Ce,Fe+48,mt,bt+128+4)}function Ju(Ce,Fe,mt,bt){var Yt,ls=i(16);for(Yt=0;4>Yt;++Yt){var ps=Ce[Fe+0+Yt]+Ce[Fe+12+Yt],Ss=Ce[Fe+4+Yt]+Ce[Fe+8+Yt],Es=Ce[Fe+4+Yt]-Ce[Fe+8+Yt],Qs=Ce[Fe+0+Yt]-Ce[Fe+12+Yt];ls[0+Yt]=ps+Ss,ls[8+Yt]=ps-Ss,ls[4+Yt]=Qs+Es,ls[12+Yt]=Qs-Es}for(Yt=0;4>Yt;++Yt)ps=(Ce=ls[0+4*Yt]+3)+ls[3+4*Yt],Ss=ls[1+4*Yt]+ls[2+4*Yt],Es=ls[1+4*Yt]-ls[2+4*Yt],Qs=Ce-ls[3+4*Yt],mt[bt+0]=ps+Ss>>3,mt[bt+16]=Qs+Es>>3,mt[bt+32]=ps-Ss>>3,mt[bt+48]=Qs-Es>>3,bt+=64}function Ld(Ce,Fe,mt){var bt,Yt=Fe-32,ls=yh,ps=255-Ce[Yt-1];for(bt=0;btmt;++mt)r(Ce,Fe+32*mt,Ce,Fe-32,16)}function Dg(Ce,Fe){var mt;for(mt=16;0bt;++bt)a(Fe,mt+32*bt,Ce,16)}function Lf(Ce,Fe){var mt,bt=16;for(mt=0;16>mt;++mt)bt+=Ce[Fe-1+32*mt]+Ce[Fe+mt-32];Em(bt>>5,Ce,Fe)}function eh(Ce,Fe){var mt,bt=8;for(mt=0;16>mt;++mt)bt+=Ce[Fe-1+32*mt];Em(bt>>4,Ce,Fe)}function L0(Ce,Fe){var mt,bt=8;for(mt=0;16>mt;++mt)bt+=Ce[Fe+mt-32];Em(bt>>4,Ce,Fe)}function jo(Ce,Fe){Em(128,Ce,Fe)}function Zi(Ce,Fe,mt){return Ce+2*Fe+mt+2>>2}function Ey(Ce,Fe){var mt,bt=Fe-32;for(bt=new Uint8Array([Zi(Ce[bt-1],Ce[bt+0],Ce[bt+1]),Zi(Ce[bt+0],Ce[bt+1],Ce[bt+2]),Zi(Ce[bt+1],Ce[bt+2],Ce[bt+3]),Zi(Ce[bt+2],Ce[bt+3],Ce[bt+4])]),mt=0;4>mt;++mt)r(Ce,Fe+32*mt,bt,0,bt.length)}function Pf(Ce,Fe){var mt=Ce[Fe-1],bt=Ce[Fe-1+32],Yt=Ce[Fe-1+64],ls=Ce[Fe-1+96];ze(Ce,Fe+0,16843009*Zi(Ce[Fe-1-32],mt,bt)),ze(Ce,Fe+32,16843009*Zi(mt,bt,Yt)),ze(Ce,Fe+64,16843009*Zi(bt,Yt,ls)),ze(Ce,Fe+96,16843009*Zi(Yt,ls,ls))}function If(Ce,Fe){var mt,bt=4;for(mt=0;4>mt;++mt)bt+=Ce[Fe+mt-32]+Ce[Fe-1+32*mt];for(bt>>=3,mt=0;4>mt;++mt)a(Ce,Fe+32*mt,bt,4)}function Rg(Ce,Fe){var mt=Ce[Fe-1+0],bt=Ce[Fe-1+32],Yt=Ce[Fe-1+64],ls=Ce[Fe-1-32],ps=Ce[Fe+0-32],Ss=Ce[Fe+1-32],Es=Ce[Fe+2-32],Qs=Ce[Fe+3-32];Ce[Fe+0+96]=Zi(bt,Yt,Ce[Fe-1+96]),Ce[Fe+1+96]=Ce[Fe+0+64]=Zi(mt,bt,Yt),Ce[Fe+2+96]=Ce[Fe+1+64]=Ce[Fe+0+32]=Zi(ls,mt,bt),Ce[Fe+3+96]=Ce[Fe+2+64]=Ce[Fe+1+32]=Ce[Fe+0+0]=Zi(ps,ls,mt),Ce[Fe+3+64]=Ce[Fe+2+32]=Ce[Fe+1+0]=Zi(Ss,ps,ls),Ce[Fe+3+32]=Ce[Fe+2+0]=Zi(Es,Ss,ps),Ce[Fe+3+0]=Zi(Qs,Es,Ss)}function ql(Ce,Fe){var mt=Ce[Fe+1-32],bt=Ce[Fe+2-32],Yt=Ce[Fe+3-32],ls=Ce[Fe+4-32],ps=Ce[Fe+5-32],Ss=Ce[Fe+6-32],Es=Ce[Fe+7-32];Ce[Fe+0+0]=Zi(Ce[Fe+0-32],mt,bt),Ce[Fe+1+0]=Ce[Fe+0+32]=Zi(mt,bt,Yt),Ce[Fe+2+0]=Ce[Fe+1+32]=Ce[Fe+0+64]=Zi(bt,Yt,ls),Ce[Fe+3+0]=Ce[Fe+2+32]=Ce[Fe+1+64]=Ce[Fe+0+96]=Zi(Yt,ls,ps),Ce[Fe+3+32]=Ce[Fe+2+64]=Ce[Fe+1+96]=Zi(ls,ps,Ss),Ce[Fe+3+64]=Ce[Fe+2+96]=Zi(ps,Ss,Es),Ce[Fe+3+96]=Zi(Ss,Es,Es)}function Df(Ce,Fe){var mt=Ce[Fe-1+0],bt=Ce[Fe-1+32],Yt=Ce[Fe-1+64],ls=Ce[Fe-1-32],ps=Ce[Fe+0-32],Ss=Ce[Fe+1-32],Es=Ce[Fe+2-32],Qs=Ce[Fe+3-32];Ce[Fe+0+0]=Ce[Fe+1+64]=ls+ps+1>>1,Ce[Fe+1+0]=Ce[Fe+2+64]=ps+Ss+1>>1,Ce[Fe+2+0]=Ce[Fe+3+64]=Ss+Es+1>>1,Ce[Fe+3+0]=Es+Qs+1>>1,Ce[Fe+0+96]=Zi(Yt,bt,mt),Ce[Fe+0+64]=Zi(bt,mt,ls),Ce[Fe+0+32]=Ce[Fe+1+96]=Zi(mt,ls,ps),Ce[Fe+1+32]=Ce[Fe+2+96]=Zi(ls,ps,Ss),Ce[Fe+2+32]=Ce[Fe+3+96]=Zi(ps,Ss,Es),Ce[Fe+3+32]=Zi(Ss,Es,Qs)}function Lu(Ce,Fe){var mt=Ce[Fe+0-32],bt=Ce[Fe+1-32],Yt=Ce[Fe+2-32],ls=Ce[Fe+3-32],ps=Ce[Fe+4-32],Ss=Ce[Fe+5-32],Es=Ce[Fe+6-32],Qs=Ce[Fe+7-32];Ce[Fe+0+0]=mt+bt+1>>1,Ce[Fe+1+0]=Ce[Fe+0+64]=bt+Yt+1>>1,Ce[Fe+2+0]=Ce[Fe+1+64]=Yt+ls+1>>1,Ce[Fe+3+0]=Ce[Fe+2+64]=ls+ps+1>>1,Ce[Fe+0+32]=Zi(mt,bt,Yt),Ce[Fe+1+32]=Ce[Fe+0+96]=Zi(bt,Yt,ls),Ce[Fe+2+32]=Ce[Fe+1+96]=Zi(Yt,ls,ps),Ce[Fe+3+32]=Ce[Fe+2+96]=Zi(ls,ps,Ss),Ce[Fe+3+64]=Zi(ps,Ss,Es),Ce[Fe+3+96]=Zi(Ss,Es,Qs)}function lp(Ce,Fe){var mt=Ce[Fe-1+0],bt=Ce[Fe-1+32],Yt=Ce[Fe-1+64],ls=Ce[Fe-1+96];Ce[Fe+0+0]=mt+bt+1>>1,Ce[Fe+2+0]=Ce[Fe+0+32]=bt+Yt+1>>1,Ce[Fe+2+32]=Ce[Fe+0+64]=Yt+ls+1>>1,Ce[Fe+1+0]=Zi(mt,bt,Yt),Ce[Fe+3+0]=Ce[Fe+1+32]=Zi(bt,Yt,ls),Ce[Fe+3+32]=Ce[Fe+1+64]=Zi(Yt,ls,ls),Ce[Fe+3+64]=Ce[Fe+2+64]=Ce[Fe+0+96]=Ce[Fe+1+96]=Ce[Fe+2+96]=Ce[Fe+3+96]=ls}function Ty(Ce,Fe){var mt=Ce[Fe-1+0],bt=Ce[Fe-1+32],Yt=Ce[Fe-1+64],ls=Ce[Fe-1+96],ps=Ce[Fe-1-32],Ss=Ce[Fe+0-32],Es=Ce[Fe+1-32],Qs=Ce[Fe+2-32];Ce[Fe+0+0]=Ce[Fe+2+32]=mt+ps+1>>1,Ce[Fe+0+32]=Ce[Fe+2+64]=bt+mt+1>>1,Ce[Fe+0+64]=Ce[Fe+2+96]=Yt+bt+1>>1,Ce[Fe+0+96]=ls+Yt+1>>1,Ce[Fe+3+0]=Zi(Ss,Es,Qs),Ce[Fe+2+0]=Zi(ps,Ss,Es),Ce[Fe+1+0]=Ce[Fe+3+32]=Zi(mt,ps,Ss),Ce[Fe+1+32]=Ce[Fe+3+64]=Zi(bt,mt,ps),Ce[Fe+1+64]=Ce[Fe+3+96]=Zi(Yt,bt,mt),Ce[Fe+1+96]=Zi(ls,Yt,bt)}function Kd(Ce,Fe){var mt;for(mt=0;8>mt;++mt)r(Ce,Fe+32*mt,Ce,Fe-32,8)}function Ti(Ce,Fe){var mt;for(mt=0;8>mt;++mt)a(Ce,Fe,Ce[Fe-1],8),Fe+=32}function rm(Ce,Fe,mt){var bt;for(bt=0;8>bt;++bt)a(Fe,mt+32*bt,Ce,8)}function mh(Ce,Fe){var mt,bt=8;for(mt=0;8>mt;++mt)bt+=Ce[Fe+mt-32]+Ce[Fe-1+32*mt];rm(bt>>4,Ce,Fe)}function Tm(Ce,Fe){var mt,bt=4;for(mt=0;8>mt;++mt)bt+=Ce[Fe+mt-32];rm(bt>>3,Ce,Fe)}function Yp(Ce,Fe){var mt,bt=4;for(mt=0;8>mt;++mt)bt+=Ce[Fe-1+32*mt];rm(bt>>3,Ce,Fe)}function ph(Ce,Fe){rm(128,Ce,Fe)}function am(Ce,Fe,mt){var bt=Ce[Fe-mt],Yt=Ce[Fe+0],ls=3*(Yt-bt)+e_[1020+Ce[Fe-2*mt]-Ce[Fe+mt]],ps=pp[112+(ls+4>>3)];Ce[Fe-mt]=yh[255+bt+pp[112+(ls+3>>3)]],Ce[Fe+0]=yh[255+Yt-ps]}function Og(Ce,Fe,mt,bt){var Yt=Ce[Fe+0],ls=Ce[Fe+mt];return lr[255+Ce[Fe-2*mt]-Ce[Fe-mt]]>bt||lr[255+ls-Yt]>bt}function Fg(Ce,Fe,mt,bt){return 4*lr[255+Ce[Fe-mt]-Ce[Fe+0]]+lr[255+Ce[Fe-2*mt]-Ce[Fe+mt]]<=bt}function Mm(Ce,Fe,mt,bt,Yt){var ls=Ce[Fe-3*mt],ps=Ce[Fe-2*mt],Ss=Ce[Fe-mt],Es=Ce[Fe+0],Qs=Ce[Fe+mt],Cn=Ce[Fe+2*mt],Xn=Ce[Fe+3*mt];return 4*lr[255+Ss-Es]+lr[255+ps-Qs]>bt?0:lr[255+Ce[Fe-4*mt]-ls]<=Yt&&lr[255+ls-ps]<=Yt&&lr[255+ps-Ss]<=Yt&&lr[255+Xn-Cn]<=Yt&&lr[255+Cn-Qs]<=Yt&&lr[255+Qs-Es]<=Yt}function im(Ce,Fe,mt,bt){var Yt=2*bt+1;for(bt=0;16>bt;++bt)Fg(Ce,Fe+bt,mt,Yt)&&am(Ce,Fe+bt,mt)}function Vx(Ce,Fe,mt,bt){var Yt=2*bt+1;for(bt=0;16>bt;++bt)Fg(Ce,Fe+bt*mt,1,Yt)&&am(Ce,Fe+bt*mt,1)}function mx(Ce,Fe,mt,bt){var Yt;for(Yt=3;0>7,Fn=18*$r+63>>7,$r=9*$r+63>>7;Es[Qs-3*Cn]=yh[255+Es[Qs-3*Cn]+$r],Es[Qs-2*Cn]=yh[255+Xn+Fn],Es[Qs-Cn]=yh[255+Js+xr],Es[Qs+0]=yh[255+On-xr],Es[Qs+Cn]=yh[255+nr-Fn],Es[Qs+2*Cn]=yh[255+Mr-$r]}Fe+=bt}}function Oc(Ce,Fe,mt,bt,Yt,ls,ps,Ss){for(ls=2*ls+1;0>3)],Mr=pp[112+(Mr+3>>3)],xr=nr+1>>1;Es[Qs-2*Cn]=yh[255+Es[Qs-2*Cn]+xr],Es[Qs-Cn]=yh[255+Xn+Mr],Es[Qs+0]=yh[255+Js-nr],Es[Qs+Cn]=yh[255+On-xr]}Fe+=bt}}function cp(Ce,Fe,mt,bt,Yt,ls){ld(Ce,Fe,mt,1,16,bt,Yt,ls)}function _d(Ce,Fe,mt,bt,Yt,ls){ld(Ce,Fe,1,mt,16,bt,Yt,ls)}function dp(Ce,Fe,mt,bt,Yt,ls){var ps;for(ps=3;0Qs?0:255:Qs)&255,Qs=Es,Yt[ls+Ss]=Cn}}function Ua(Ce,Fe,mt,bt){var Yt=Fe.width,ls=Fe.o;if(t(Ce!=null&&Fe!=null),0>mt||0>=bt||mt+bt>ls)return null;if(!Ce.Cc){if(Ce.ga==null){var ps;if(Ce.ga=new xn,(ps=Ce.ga==null)||(ps=Fe.width*Fe.o,t(Ce.Gb.length==0),Ce.Gb=i(ps),Ce.Uc=0,Ce.Gb==null?ps=0:(Ce.mb=Ce.Gb,Ce.nb=Ce.Uc,Ce.rc=null,ps=1),ps=!ps),!ps){ps=Ce.ga;var Ss=Ce.Fa,Es=Ce.P,Qs=Ce.qc,Cn=Ce.mb,Xn=Ce.nb,Js=Es+1,On=Qs-1,nr=ps.l;if(t(Ss!=null&&Cn!=null&&Fe!=null),fx[0]=null,fx[1]=Rr,fx[2]=Dr,fx[3]=Aa,ps.ca=Cn,ps.tb=Xn,ps.c=Fe.width,ps.i=Fe.height,t(0=Qs)Fe=0;else if(ps.$a=3&Ss[Es+0],ps.Z=Ss[Es+0]>>2&3,ps.Lc=Ss[Es+0]>>4&3,Es=Ss[Es+0]>>6&3,0>ps.$a||1=ps.c*ps.i;ps=!Fe}if(ps)return null;Ce.ga.Lc!=1?Ce.Ga=0:bt=ls-mt}t(Ce.ga!=null),t(mt+bt<=ls);e:{if(Fe=(Ss=Ce.ga).c,ls=Ss.l.o,Ss.$a==0){if(Js=Ce.rc,On=Ce.Vc,nr=Ce.Fa,Es=Ce.P+1+mt*Fe,Qs=Ce.mb,Cn=Ce.nb+mt*Fe,t(Es<=Ce.P+Ce.qc),Ss.Z!=0)for(t(fx[Ss.Z]!=null),ps=0;ps=Fe)Fe=1;else if(Ss.ic||Kl(),Ss.ic){Ss=ps.V,Js=ps.Ba,On=ps.c;var Mr=ps.i,xr=(nr=1,Es=ps.$/On,Qs=ps.$%On,Cn=ps.m,Xn=ps.s,ps.$),Fn=On*Mr,$r=On*Fe,ba=Xn.wc,fa=xr<$r?ln(Xn,Qs,Es):null;t(xr<=Fn),t(Fe<=Mr),t(ot(Xn));t:for(;;){for(;!Cn.h&&xr<$r;){if(Qs&ba||(fa=ln(Xn,Qs,Es)),t(fa!=null),je(Cn),256>(Mr=$n(fa.G[0],fa.H[0],Cn)))Ss[Js+xr]=Mr,++xr,++Qs>=On&&(Qs=0,++Es<=Fe&&!(Es%16)&&vt(ps,Es));else{if(!(280>Mr)){nr=0;break t}Mr=Qn(Mr-256,Cn);var Fi,bi=$n(fa.G[4],fa.H[4],Cn);if(je(Cn),!(xr>=(bi=Sn(On,bi=Qn(bi,Cn)))&&Fn-xr>=Mr)){nr=0;break t}for(Fi=0;Fi=On;)Qs-=On,++Es<=Fe&&!(Es%16)&&vt(ps,Es);xr<$r&&Qs&ba&&(fa=ln(Xn,Qs,Es))}t(Cn.h==ge(Cn))}vt(ps,Es>Fe?Fe:Es);break t}!nr||Cn.h&&xr=ls&&(Ce.Cc=1),bt=1}if(!bt)return null;if(Ce.Cc&&((bt=Ce.ga)!=null&&(bt.mc=null),Ce.ga=null,0>23,Ss[Es+4*ps+1]=Ss[Es+4*ps+1]*Xn>>23,Ss[Es+4*ps+2]=Ss[Es+4*ps+2]*Xn>>23)}Fe+=ls}}function Ra(Ce,Fe,mt,bt,Yt){for(;0>4)*Es>>16;Ce[Fe+2*ls+0]=(240&ps|ps>>4)*Es>>16&240|(15&ps|ps<<4)*Es>>16>>4&15,Ce[Fe+2*ls+1]=240&Qs|Ss}Fe+=Yt}}function ri(Ce,Fe,mt,bt,Yt,ls,ps,Ss){var Es,Qs,Cn=255;for(Qs=0;Qs>8}function Kl(){z0=sr,Mw=Ra,B0=ri,Jb=Ho}function Hi(Ce,Fe,mt){I[Ce]=function(bt,Yt,ls,ps,Ss,Es,Qs,Cn,Xn,Js,On,nr,Mr,xr,Fn,$r,ba){var fa,Fi=ba-1>>1,bi=Ss[Es+0]|Qs[Cn+0]<<16,sl=Xn[Js+0]|On[nr+0]<<16;t(bt!=null);var Li=3*bi+sl+131074>>2;for(Fe(bt[Yt+0],255&Li,Li>>16,Mr,xr),ls!=null&&(Li=3*sl+bi+131074>>2,Fe(ls[ps+0],255&Li,Li>>16,Fn,$r)),fa=1;fa<=Fi;++fa){var Dl=Ss[Es+fa]|Qs[Cn+fa]<<16,Pd=Xn[Js+fa]|On[nr+fa]<<16,nl=bi+Dl+sl+Pd+524296,Di=nl+2*(Dl+sl)>>3;Li=Di+bi>>1,bi=(nl=nl+2*(bi+Pd)>>3)+Dl>>1,Fe(bt[Yt+2*fa-1],255&Li,Li>>16,Mr,xr+(2*fa-1)*mt),Fe(bt[Yt+2*fa-0],255&bi,bi>>16,Mr,xr+(2*fa-0)*mt),ls!=null&&(Li=nl+sl>>1,bi=Di+Pd>>1,Fe(ls[ps+2*fa-1],255&Li,Li>>16,Fn,$r+(2*fa-1)*mt),Fe(ls[ps+2*fa+0],255&bi,bi>>16,Fn,$r+(2*fa+0)*mt)),bi=Dl,sl=Pd}1&ba||(Li=3*bi+sl+131074>>2,Fe(bt[Yt+ba-1],255&Li,Li>>16,Mr,xr+(ba-1)*mt),ls!=null&&(Li=3*sl+bi+131074>>2,Fe(ls[ps+ba-1],255&Li,Li>>16,Fn,$r+(ba-1)*mt)))}}function lm(){Xp[R1]=k2,Xp[O1]=Iw,Xp[Sv]=fk,Xp[Zp]=Dw,Xp[Ly]=Qp,Xp[$0]=fp,Xp[t_]=Q5,Xp[Cv]=Iw,Xp[j2]=Dw,Xp[Lw]=Qp,Xp[Ug]=fp}function zg(Ce){return Ce&~yk?0>Ce?0:255:Ce>>gk}function Bg(Ce,Fe){return zg((19077*Ce>>8)+(26149*Fe>>8)-14234)}function gu(Ce,Fe,mt){return zg((19077*Ce>>8)-(6419*Fe>>8)-(13320*mt>>8)+8708)}function tc(Ce,Fe){return zg((19077*Ce>>8)+(33050*Fe>>8)-17685)}function L1(Ce,Fe,mt,bt,Yt){bt[Yt+0]=Bg(Ce,mt),bt[Yt+1]=gu(Ce,Fe,mt),bt[Yt+2]=tc(Ce,Fe)}function Hx(Ce,Fe,mt,bt,Yt){bt[Yt+0]=tc(Ce,Fe),bt[Yt+1]=gu(Ce,Fe,mt),bt[Yt+2]=Bg(Ce,mt)}function I0(Ce,Fe,mt,bt,Yt){var ls=gu(Ce,Fe,mt);Fe=ls<<3&224|tc(Ce,Fe)>>3,bt[Yt+0]=248&Bg(Ce,mt)|ls>>5,bt[Yt+1]=Fe}function Yd(Ce,Fe,mt,bt,Yt){var ls=240&tc(Ce,Fe)|15;bt[Yt+0]=240&Bg(Ce,mt)|gu(Ce,Fe,mt)>>4,bt[Yt+1]=ls}function up(Ce,Fe,mt,bt,Yt){bt[Yt+0]=255,L1(Ce,Fe,mt,bt,Yt+1)}function D0(Ce,Fe,mt,bt,Yt){Hx(Ce,Fe,mt,bt,Yt),bt[Yt+3]=255}function My(Ce,Fe,mt,bt,Yt){L1(Ce,Fe,mt,bt,Yt),bt[Yt+3]=255}function cd(Ce,Fe,mt){I[Ce]=function(bt,Yt,ls,ps,Ss,Es,Qs,Cn,Xn){for(var Js=Cn+(-2&Xn)*mt;Cn!=Js;)Fe(bt[Yt+0],ls[ps+0],Ss[Es+0],Qs,Cn),Fe(bt[Yt+1],ls[ps+0],Ss[Es+0],Qs,Cn+mt),Yt+=2,++ps,++Es,Cn+=2*mt;1&Xn&&Fe(bt[Yt+0],ls[ps+0],Ss[Es+0],Qs,Cn)}}function wd(Ce,Fe,mt){return mt==0?Ce==0?Fe==0?6:5:Fe==0?4:0:mt}function Pu(Ce,Fe,mt,bt,Yt){switch(Ce>>>30){case 3:xh(Fe,mt,bt,Yt,0);break;case 2:Ff(Fe,mt,bt,Yt);break;case 1:vu(Fe,mt,bt,Yt)}}function Lm(Ce,Fe){var mt,bt,Yt=Fe.M,ls=Fe.Nb,ps=Ce.oc,Ss=Ce.pc+40,Es=Ce.oc,Qs=Ce.pc+584,Cn=Ce.oc,Xn=Ce.pc+600;for(mt=0;16>mt;++mt)ps[Ss+32*mt-1]=129;for(mt=0;8>mt;++mt)Es[Qs+32*mt-1]=129,Cn[Xn+32*mt-1]=129;for(0mt;++mt)r(ps,Ss+32*mt-4,ps,Ss+32*mt+12,4);for(mt=-1;8>mt;++mt)r(Es,Qs+32*mt-4,Es,Qs+32*mt+4,4),r(Cn,Xn+32*mt-4,Cn,Xn+32*mt+4,4)}var On=Ce.Gd,nr=Ce.Hd+bt,Mr=Js.ad,xr=Js.Hc;if(0=Ce.za-1?a(Fn,$r,On[nr].y[15],4):r(Fn,$r,On[nr+1].y,0,4)),mt=0;4>mt;mt++)Fn[$r+128+mt]=Fn[$r+256+mt]=Fn[$r+384+mt]=Fn[$r+0+mt];for(mt=0;16>mt;++mt,xr<<=2)Fn=ps,$r=Ss+Iy[mt],eu[Js.Ob[mt]](Fn,$r),Pu(xr,Mr,16*+mt,Fn,$r)}else if(Fn=wd(bt,Yt,Js.Ob[0]),zf[Fn](ps,Ss),xr!=0)for(mt=0;16>mt;++mt,xr<<=2)Pu(xr,Mr,16*+mt,ps,Ss+Iy[mt]);for(mt=Js.Gc,Fn=wd(bt,Yt,Js.Dd),Vg[Fn](Es,Qs),Vg[Fn](Cn,Xn),xr=Mr,Fn=Es,$r=Qs,255&(Js=0|mt)&&(170&Js?P1(xr,256,Fn,$r):Zl(xr,256,Fn,$r)),Js=Cn,xr=Xn,255&(mt>>=8)&&(170&mt?P1(Mr,320,Js,xr):Zl(Mr,320,Js,xr)),Ytmt;++mt)r(On,nr+mt*Ce.R,ps,Ss+32*mt,16);for(mt=0;8>mt;++mt)r(Mr,Js+mt*Ce.B,Es,Qs+32*mt,8),r(xr,Fn+mt*Ce.B,Cn,Xn+32*mt,8)}}function Rf(Ce,Fe,mt,bt,Yt,ls,ps,Ss,Es){var Qs=[0],Cn=[0],Xn=0,Js=Es!=null?Es.kd:0,On=Es??new jn;if(Ce==null||12>mt)return 7;On.data=Ce,On.w=Fe,On.ha=mt,Fe=[Fe],mt=[mt],On.gb=[On.gb];e:{var nr=Fe,Mr=mt,xr=On.gb;if(t(Ce!=null),t(Mr!=null),t(xr!=null),xr[0]=0,12<=Mr[0]&&!n(Ce,nr[0],"RIFF")){if(n(Ce,nr[0]+8,"WEBP")){xr=3;break e}var Fn=Se(Ce,nr[0]+4);if(12>Fn||4294967286Mr[0]-8){xr=7;break e}xr[0]=Fn,nr[0]+=12,Mr[0]-=12}xr=0}if(xr!=0)return xr;for(Fn=0xr[0])xr=7;else{if(!n($r,Mr[0],"VP8X")){if(Se($r,Mr[0]+4)!=10){xr=3;break e}if(18>xr[0]){xr=7;break e}var bi=Se($r,Mr[0]+8),sl=1+Xe($r,Mr[0]+12);if(2147483648<=sl*($r=1+Xe($r,Mr[0]+15))){xr=3;break e}Fi!=null&&(Fi[0]=bi),ba!=null&&(ba[0]=sl),fa!=null&&(fa[0]=$r),Mr[0]+=18,xr[0]-=18,Li[0]=1}xr=0}}if(Xn=Xn[0],nr=nr[0],xr!=0)return xr;if(Mr=!!(2&nr),!Fn&&Xn)return 3;if(ls!=null&&(ls[0]=!!(16&nr)),ps!=null&&(ps[0]=Mr),Ss!=null&&(Ss[0]=0),ps=Qs[0],nr=Cn[0],Xn&&Mr&&Es==null){xr=0;break}if(4>mt){xr=7;break}if(Fn&&Xn||!Fn&&!Xn&&!n(Ce,Fe[0],"ALPH")){mt=[mt],On.na=[On.na],On.P=[On.P],On.Sa=[On.Sa];e:{bi=Ce,xr=Fe,Fn=mt;var Li=On.gb;ba=On.na,fa=On.P,Fi=On.Sa,sl=22,t(bi!=null),t(Fn!=null),$r=xr[0];var Dl=Fn[0];for(t(ba!=null),t(Fi!=null),ba[0]=null,fa[0]=null,Fi[0]=0;;){if(xr[0]=$r,Fn[0]=Dl,8>Dl){xr=7;break e}var Pd=Se(bi,$r+4);if(4294967286Li){xr=3;break e}if(!n(bi,$r,"VP8 ")||!n(bi,$r,"VP8L")){xr=0;break e}if(Dl[0]Fn[0])xr=7;else{if($r||sl){if(Li=Se(Li,bi+4),12<=ba&&Li>ba-12){xr=3;break e}if(Js&&Li>Fn[0]-8){xr=7;break e}fa[0]=Li,xr[0]+=8,Fn[0]-=8,Fi[0]=sl}else Fi[0]=5<=Fn[0]&&Li[bi+0]==47&&!(Li[bi+4]>>5),fa[0]=Fn[0];xr=0}if(mt=mt[0],On.Ja=On.Ja[0],On.xa=On.xa[0],Fe=Fe[0],xr!=0)break;if(4294967286mt){xr=7;break}Ss=ps,Js=nr,Mr=ls,Ce==null||5>mt?Ce=0:5<=mt&&Ce[Fe+0]==47&&!(Ce[Fe+4]>>5)?(Fn=[0],Li=[0],ba=[0],ue(fa=new he,Ce,Fe,mt),rr(fa,Fn,Li,ba)?(Ss!=null&&(Ss[0]=Fn[0]),Js!=null&&(Js[0]=Li[0]),Mr!=null&&(Mr[0]=ba[0]),Ce=1):Ce=0):Ce=0}else{if(10>mt){xr=7;break}Ss=nr,Ce==null||10>mt||!zr(Ce,Fe+3,mt-3)?Ce=0:(Js=Ce[Fe+0]|Ce[Fe+1]<<8|Ce[Fe+2]<<16,Mr=16383&(Ce[Fe+7]<<8|Ce[Fe+6]),Ce=16383&(Ce[Fe+9]<<8|Ce[Fe+8]),1&Js||3<(Js>>1&7)||!(Js>>4&1)||Js>>5>=On.Ja||!Mr||!Ce?Ce=0:(ps&&(ps[0]=Mr),Ss&&(Ss[0]=Ce),Ce=1))}if(!Ce||(ps=ps[0],nr=nr[0],Xn&&(Qs[0]!=ps||Cn[0]!=nr)))return 3;Es!=null&&(Es[0]=On,Es.offset=Fe-Es.w,t(4294967286>Fe-Es.w),t(Es.offset==Es.ha-mt));break}return xr==0||xr==7&&Xn&&Es==null?(ls!=null&&(ls[0]|=On.na!=null&&0mt||(ls&=-2,ps&=-2),0>ls||0>ps||0>=Ss||0>=Es||ls+Ss>bt||ps+Es>Yt))return 0;if(Fe.v=ls,Fe.j=ps,Fe.va=ls+Ss,Fe.o=ps+Es,Fe.U=Ss,Fe.T=Es,Fe.da=Ce!=null&&0Ce.S){var Fe=Ce.f.RGBA;Fe.fb+=(Ce.height-1)*Fe.A,Fe.A=-Fe.A}else Fe=Ce.f.kb,Ce=Ce.height,Fe.O+=(Ce-1)*Fe.fa,Fe.fa=-Fe.fa,Fe.N+=(Ce-1>>1)*Fe.Ab,Fe.Ab=-Fe.Ab,Fe.W+=(Ce-1>>1)*Fe.Db,Fe.Db=-Fe.Db,Fe.F!=null&&(Fe.J+=(Ce-1)*Fe.lb,Fe.lb=-Fe.lb);return 0}function qr(Ce,Fe,mt,bt){if(bt==null||0>=Ce||0>=Fe)return 2;if(mt!=null){if(mt.Da){var Yt=mt.cd,ls=mt.bd,ps=-2&mt.v,Ss=-2&mt.j;if(0>ps||0>Ss||0>=Yt||0>=ls||ps+Yt>Ce||Ss+ls>Fe)return 2;Ce=Yt,Fe=ls}if(mt.da){if(!qe(Ce,Fe,Yt=[mt.ib],ls=[mt.hb]))return 2;Ce=Yt[0],Fe=ls[0]}}bt.width=Ce,bt.height=Fe;e:{var Es=bt.width,Qs=bt.height;if(Ce=bt.S,0>=Es||0>=Qs||!(Ce>=R1&&13>Ce))Ce=2;else{if(0>=bt.Rd&&bt.sd==null){ps=ls=Yt=Fe=0;var Cn=(Ss=Es*i_[Ce])*Qs;if(11>Ce||(ls=(Qs+1)/2*(Fe=(Es+1)/2),Ce==12&&(ps=(Yt=Es)*Qs)),(Qs=i(Cn+2*ls+ps))==null){Ce=1;break e}bt.sd=Qs,11>Ce?((Es=bt.f.RGBA).eb=Qs,Es.fb=0,Es.A=Ss,Es.size=Cn):((Es=bt.f.kb).y=Qs,Es.O=0,Es.fa=Ss,Es.Fd=Cn,Es.f=Qs,Es.N=0+Cn,Es.Ab=Fe,Es.Cd=ls,Es.ea=Qs,Es.W=0+Cn+ls,Es.Db=Fe,Es.Ed=ls,Ce==12&&(Es.F=Qs,Es.J=0+Cn+2*ls),Es.Tc=ps,Es.lb=Yt)}if(Fe=1,Yt=bt.S,ls=bt.width,ps=bt.height,Yt>=R1&&13>Yt)if(11>Yt)Ce=bt.f.RGBA,Fe&=(Ss=Math.abs(Ce.A))*(ps-1)+ls<=Ce.size,Fe&=Ss>=ls*i_[Yt],Fe&=Ce.eb!=null;else{Ce=bt.f.kb,Ss=(ls+1)/2,Cn=(ps+1)/2,Es=Math.abs(Ce.fa),Qs=Math.abs(Ce.Ab);var Xn=Math.abs(Ce.Db),Js=Math.abs(Ce.lb),On=Js*(ps-1)+ls;Fe&=Es*(ps-1)+ls<=Ce.Fd,Fe&=Qs*(Cn-1)+Ss<=Ce.Cd,Fe=(Fe&=Xn*(Cn-1)+Ss<=Ce.Ed)&Es>=ls&Qs>=Ss&Xn>=Ss,Fe&=Ce.y!=null,Fe&=Ce.f!=null,Fe&=Ce.ea!=null,Yt==12&&(Fe&=Js>=ls,Fe&=On<=Ce.Tc,Fe&=Ce.F!=null)}else Fe=0;Ce=Fe?0:2}}return Ce!=0||mt!=null&&mt.fd&&(Ce=Ma(bt)),Ce}var Yl=64,La=[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],Pm=24,dd=32,pa=8,Gx=[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(Ce){return Ce},I.Predictor2=function(Ce,Fe,mt){return Fe[mt+0]},I.Predictor3=function(Ce,Fe,mt){return Fe[mt+1]},I.Predictor4=function(Ce,Fe,mt){return Fe[mt-1]},I.Predictor5=function(Ce,Fe,mt){return Qe(Qe(Ce,Fe[mt+1]),Fe[mt+0])},I.Predictor6=function(Ce,Fe,mt){return Qe(Ce,Fe[mt-1])},I.Predictor7=function(Ce,Fe,mt){return Qe(Ce,Fe[mt+0])},I.Predictor8=function(Ce,Fe,mt){return Qe(Fe[mt-1],Fe[mt+0])},I.Predictor9=function(Ce,Fe,mt){return Qe(Fe[mt+0],Fe[mt+1])},I.Predictor10=function(Ce,Fe,mt){return Qe(Qe(Ce,Fe[mt-1]),Qe(Fe[mt+0],Fe[mt+1]))},I.Predictor11=function(Ce,Fe,mt){var bt=Fe[mt+0];return 0>=ft(bt>>24&255,Ce>>24&255,(Fe=Fe[mt-1])>>24&255)+ft(bt>>16&255,Ce>>16&255,Fe>>16&255)+ft(bt>>8&255,Ce>>8&255,Fe>>8&255)+ft(255&bt,255&Ce,255&Fe)?bt:Ce},I.Predictor12=function(Ce,Fe,mt){var bt=Fe[mt+0];return(Ge((Ce>>24&255)+(bt>>24&255)-((Fe=Fe[mt-1])>>24&255))<<24|Ge((Ce>>16&255)+(bt>>16&255)-(Fe>>16&255))<<16|Ge((Ce>>8&255)+(bt>>8&255)-(Fe>>8&255))<<8|Ge((255&Ce)+(255&bt)-(255&Fe)))>>>0},I.Predictor13=function(Ce,Fe,mt){var bt=Fe[mt-1];return(nt((Ce=Qe(Ce,Fe[mt+0]))>>24&255,bt>>24&255)<<24|nt(Ce>>16&255,bt>>16&255)<<16|nt(Ce>>8&255,bt>>8&255)<<8|nt(255&Ce,255&bt))>>>0};var $g=I.PredictorAdd0;I.PredictorAdd1=lt,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 px=I.PredictorAdd2;js("ColorIndexInverseTransform","MapARGB","32b",function(Ce){return Ce>>8&255},function(Ce){return Ce}),js("VP8LColorIndexInverseTransformAlpha","MapAlpha","8b",function(Ce){return Ce},function(Ce){return Ce>>8&255});var R0,Of=I.ColorIndexInverseTransform,qc=I.MapARGB,hp=I.VP8LColorIndexInverseTransformAlpha,fh=I.MapAlpha,yu=I.VP8LPredictorsAdd=[];yu.length=16,(I.VP8LPredictors=[]).length=16,(I.VP8LPredictorsAdd_C=[]).length=16,(I.VP8LPredictors_C=[]).length=16;var Qc,mp,Nv,kv,Ac,Wx,O0,xh,Ff,P1,vu,Zl,tl,Go,Zd,Jc,Kx,F0,gh,Xb,Tw,Qb,Yx,bu,z0,Mw,B0,Jb,b2=i(511),_2=i(2041),I1=i(225),D1=i(767),w2=0,e_=_2,pp=I1,yh=D1,lr=b2,R1=0,O1=1,Sv=2,Zp=3,Ly=4,$0=5,t_=6,Cv=7,j2=8,Lw=9,Ug=10,W5=[2,3,7],ho=[3,3,11],mk=[280,256,256,256,40],K5=[0,1,1,1,0],rM=[17,18,0,1,2,3,4,5,16,6,7,8,9,10,11,12,13,14,15],Y5=[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],MC=[2954,2956,2958,2962,2970,2986,3018,3082,3212,3468,3980,5004],Ec=8,s_=[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],Z5=[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],F1=null,aM=[[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]],qg=[0,1,4,8,5,2,3,6,9,12,13,10,7,11,14,15],Pw=[-0,1,-1,2,-2,3,4,6,-3,5,-4,-5,-6,7,-7,8,-8,-9],n_=[[[[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]]]],pk=[[[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]]],z1=[[[[255,255,255,255,255,255,255,255,255,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]]]],B1=[0,1,2,3,6,4,5,6,6,6,6,6,6,6,6,7,0],zf=[],eu=[],Vg=[],N2=1,X5=2,fx=[],Xp=[];Hi("UpsampleRgbLinePair",L1,3),Hi("UpsampleBgrLinePair",Hx,3),Hi("UpsampleRgbaLinePair",My,4),Hi("UpsampleBgraLinePair",D0,4),Hi("UpsampleArgbLinePair",up,4),Hi("UpsampleRgba4444LinePair",Yd,2),Hi("UpsampleRgb565LinePair",I0,2);var k2=I.UpsampleRgbLinePair,fk=I.UpsampleBgrLinePair,Iw=I.UpsampleRgbaLinePair,Dw=I.UpsampleBgraLinePair,Qp=I.UpsampleArgbLinePair,fp=I.UpsampleRgba4444LinePair,Q5=I.UpsampleRgb565LinePair,Py=16,Rw=1<bt.ca.S||(alert("todo:WebPInitConvertARGBToYUV"),bt.ca.f.kb.F!=null&&Kl()),bt.Pb&&0(Es=mt.Md)?0:100Qs;++Qs)12>(Xn=Yt.pb[Qs]).lc&&(Xn.ia=Es*cm[0>Xn.lc?0:Xn.lc]>>3),Cn|=Xn.ia;Cn&&(alert("todo:VP8InitRandom"),Yt.ia=1)}Yt.Ga=mt.Id,100Yt.Ga&&(Yt.Ga=0)}(function(Js,On){if(Js==null)return 0;if(On==null)return is(Js,2,"NULL VP8Io parameter in VP8Decode().");if(!Js.cb&&!Sa(Js,On))return 0;if(t(Js.cb),On.ac==null||On.ac(On)){On.ob&&(Js.L=0);var nr=Bw[Js.L];if(Js.L==2?(Js.yb=0,Js.zb=0):(Js.yb=On.v-nr>>4,Js.zb=On.j-nr>>4,0>Js.yb&&(Js.yb=0),0>Js.zb&&(Js.zb=0)),Js.Va=On.o+15+nr>>4,Js.Hb=On.va+15+nr>>4,Js.Hb>Js.za&&(Js.Hb=Js.za),Js.Va>Js.Ub&&(Js.Va=Js.Ub),0nr;++nr){var xr;if(Js.Qa.Cb){var Fn=Js.Qa.Lb[nr];Js.Qa.Fb||(Fn+=Mr.Tb)}else Fn=Mr.Tb;for(xr=0;1>=xr;++xr){var $r=Js.gd[nr][xr],ba=Fn;if(Mr.Pc&&(ba+=Mr.vd[0],xr&&(ba+=Mr.od[0])),0<(ba=0>ba?0:63>2:fa>>1)>9-Mr.wb&&(fa=9-Mr.wb),1>fa&&(fa=1),$r.dd=fa,$r.tc=2*ba+fa,$r.ld=40<=ba?2:15<=ba?1:0}else $r.tc=0;$r.La=xr}}}nr=0}else is(Js,6,"Frame setup failed"),nr=Js.a;if(nr=nr==0){if(nr){Js.$c=0,0Js.Vb){if(Js.Vb=0,Js.Ec=i($r),Js.Fc=0,Js.Ec==null){nr=is(Js,1,"no memory during frame initialization.");break t}Js.Vb=$r}$r=Js.Ec,ba=Js.Fc,Js.Ac=$r,Js.Bc=ba,ba+=Mr,Js.Gd=l(Fi,Oo),Js.Hd=0,Js.rb=l(bi+1,da),Js.sb=1,Js.wa=sl?l(sl,ta):null,Js.Y=0,Js.D.Nb=0,Js.D.wa=Js.wa,Js.D.Y=Js.Y,0=nr;++nr)b2[255+nr]=0>nr?-nr:nr;for(nr=-1020;1020>=nr;++nr)_2[1020+nr]=-128>nr?-128:127=nr;++nr)I1[112+nr]=-16>nr?-16:15=nr;++nr)D1[255+nr]=0>nr?0:255Yo;++Yo){var ud,gc=Nd[0+Yo];for(ud=0;4>ud;++ud){gc=pk[jd[Oh+ud]][gc];for(var ed=Pw[De(co,gc[0])];0>3;for(ed=0;256>ed;ed+=16)Yo[Xd+ed]=th}Iu=1,Im=Oh[0]}var Xl=15&co.la,Du=15&Jp.la;for(ed=0;4>ed;++ed){var Dm=1&Du;for(th=Tc=0;4>th;++th)Xl=Xl>>1|(Dm=(Vc=F1(jd,Im,Vc=Dm+(1&Xl),tu.Sc,Iu,Yo,Xd))>Iu)<<7,Tc=Tc<<2|(3>=4,Du=Du>>1|Dm<<7,ud=(ud<<8|Tc)>>>0}for(Im=Xl,Iu=Du>>4,_u=0;4>_u;_u+=2){for(Tc=0,Xl=co.la>>4+_u,Du=Jp.la>>4+_u,ed=0;2>ed;++ed){for(Dm=1&Du,th=0;2>th;++th)Vc=Dm+(1&Xl),Xl=Xl>>1|(Dm=0<(Vc=F1(jd,Oh[2],Vc,tu.Qc,0,Yo,Xd)))<<3,Tc=Tc<<2|(3>=2,Du=Du>>1|Dm<<5}gc|=Tc<<4*_u,Im|=Xl<<4<<_u,Iu|=(240&Du)<<_u}co.la=Im,Jp.la=Iu,Nd.Hc=ud,Nd.Gc=gc,Nd.ia=43690&gc?0:tu.ia,Oh=!(ud|gc)}if(0=Di.zb&&Di.M<=Di.Va,Di.Aa==0)t:{if(nl.M=Di.M,nl.uc=co,Lm(Di,nl),ol=1,nl=(Tc=Di.D).Nb,co=(gc=Bw[Di.L])*Di.R,jd=gc/2*Di.B,ed=16*nl*Di.R,th=8*nl*Di.B,Oh=Di.sa,Nd=Di.ta-co+ed,tu=Di.qa,Yo=Di.ra-jd+th,Xd=Di.Ha,Jp=Di.Ia-jd+th,Du=(Xl=Tc.M)==0,ud=Xl>=Di.Va-1,Di.Aa==2&&Lm(Di,Tc),Tc.uc)for(Dm=(Vc=Di).D.M,t(Vc.D.uc),Tc=Vc.yb;Tcti.o&&(Xl=ti.o),ti.F=null,ti.J=null,Di.Fa!=null&&0>1),ti.W+=Di.B*(gc>>1),ti.F!=null&&(ti.J+=ti.width*gc)),Tc>1,ti.W+=ti.v>>1,ti.F!=null&&(ti.J+=ti.v),ti.ka=Tc-ti.j,ti.U=ti.va-ti.v,ti.T=Xl-Tc,ol=ti.put(ti))}nl+1!=Di.Ic||ud||(r(Di.sa,Di.ta-co,Oh,Nd+16*Di.R,co),r(Di.qa,Di.ra-jd,tu,Yo+8*Di.B,jd),r(Di.Ha,Di.Ia-jd,Xd,Jp+8*Di.B,jd))}if(!ol)return is(Dl,6,"Output aborted.")}return 1}(Js,On)),On.bc!=null&&On.bc(On),nr&=1}return nr?(Js.cb=0,nr):0})(Ce,bt)||(Fe=Ce.a)}}else Fe=Ce.a}Fe==0&&ps.Oa!=null&&ps.Oa.fd&&(Fe=Ma(ps.ba))}ps=Fe}ls=ps!=0?null:11>ls?Ss.f.RGBA.eb:Ss.f.kb.y}else ls=null;return ls};var i_=[3,4,3,4,4,2,2,4,4,4,2,1,1]};function d(I,D){for(var B="",q=0;q<4;q++)B+=String.fromCharCode(I[D++]);return B}function u(I,D){return I[D+0]|I[D+1]<<8}function h(I,D){return(I[D+0]|I[D+1]<<8|I[D+2]<<16)>>>0}function m(I,D){return(I[D+0]|I[D+1]<<8|I[D+2]<<16|I[D+3]<<24)>>>0}new c;var p=[0],x=[0],g=[],y=new c,b=s,v=function(I,D){var B={},q=0,W=!1,V=0,K=0;if(B.frames=[],!function(le,he){for(var ve=0;ve<4;ve++)if(le[he+ve]!="RIFF".charCodeAt(ve))return!0;return!1}(I,D)){for(m(I,D+=4),D+=8;D>1&1}Q!="ANMF"&&(D+=ce)}return B}}(b,0);v.response=b,v.rgbaoutput=!0,v.dataurl=!1;var N=v.header?v.header:null,C=v.frames?v.frames:null;if(N){N.loop_counter=N.loop_count,p=[N.canvas_height],x=[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 DEn(){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(le){return le=le||{},this.isStrokeTransparent=le.isStrokeTransparent||!1,this.strokeOpacity=le.strokeOpacity||1,this.strokeStyle=le.strokeStyle||"#000000",this.fillStyle=le.fillStyle||"#000000",this.isFillTransparent=le.isFillTransparent||!1,this.fillOpacity=le.fillOpacity||1,this.font=le.font||"10px sans-serif",this.textBaseline=le.textBaseline||"alphabetic",this.textAlign=le.textAlign||"left",this.lineWidth=le.lineWidth||1,this.lineJoin=le.lineJoin||"miter",this.lineCap=le.lineCap||"butt",this.path=le.path||[],this.transform=le.transform!==void 0?le.transform.clone():new c,this.globalCompositeOperation=le.globalCompositeOperation||"normal",this.globalAlpha=le.globalAlpha||1,this.clip_path=le.clip_path||[],this.currentPoint=le.currentPoint||new l,this.miterLimit=le.miterLimit||10,this.lastPoint=le.lastPoint||new l,this.lineDashOffset=le.lineDashOffset||0,this.lineDash=le.lineDash||[],this.margin=le.margin||[0,0,0,0],this.prevPageLastElemOffset=le.prevPageLastElemOffset||0,this.ignoreClearRect=typeof le.ignoreClearRect!="boolean"||le.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(le){Object.defineProperty(this,"canvas",{get:function(){return{parentNode:!1,style:!1}}});var he=le;Object.defineProperty(this,"pdf",{get:function(){return he}});var ve=!1;Object.defineProperty(this,"pageWrapXEnabled",{get:function(){return ve},set:function(Re){ve=!!Re}});var ge=!1;Object.defineProperty(this,"pageWrapYEnabled",{get:function(){return ge},set:function(Re){ge=!!Re}});var fe=0;Object.defineProperty(this,"posX",{get:function(){return fe},set:function(Re){isNaN(Re)||(fe=Re)}});var je=0;Object.defineProperty(this,"posY",{get:function(){return je},set:function(Re){isNaN(Re)||(je=Re)}}),Object.defineProperty(this,"margin",{get:function(){return d.margin},set:function(Re){var Ae;typeof Re=="number"?Ae=[Re,Re,Re,Re]:((Ae=new Array(4))[0]=Re[0],Ae[1]=Re.length>=2?Re[1]:Ae[0],Ae[2]=Re.length>=3?Re[2]:Ae[0],Ae[3]=Re.length>=4?Re[3]:Ae[1]),d.margin=Ae}});var Ee=!1;Object.defineProperty(this,"autoPaging",{get:function(){return Ee},set:function(Re){Ee=Re}});var Me=0;Object.defineProperty(this,"lastBreak",{get:function(){return Me},set:function(Re){Me=Re}});var De=[];Object.defineProperty(this,"pageBreaks",{get:function(){return De},set:function(Re){De=Re}}),Object.defineProperty(this,"ctx",{get:function(){return d},set:function(Re){Re instanceof u&&(d=Re)}}),Object.defineProperty(this,"path",{get:function(){return d.path},set:function(Re){d.path=Re}});var ze=[];Object.defineProperty(this,"ctxStack",{get:function(){return ze},set:function(Re){ze=Re}}),Object.defineProperty(this,"fillStyle",{get:function(){return this.ctx.fillStyle},set:function(Re){var Ae;Ae=m(Re),this.ctx.fillStyle=Ae.style,this.ctx.isFillTransparent=Ae.a===0,this.ctx.fillOpacity=Ae.a,this.pdf.setFillColor(Ae.r,Ae.g,Ae.b,{a:Ae.a}),this.pdf.setTextColor(Ae.r,Ae.g,Ae.b,{a:Ae.a})}}),Object.defineProperty(this,"strokeStyle",{get:function(){return this.ctx.strokeStyle},set:function(Re){var Ae=m(Re);this.ctx.strokeStyle=Ae.style,this.ctx.isStrokeTransparent=Ae.a===0,this.ctx.strokeOpacity=Ae.a,Ae.a===0?this.pdf.setDrawColor(255,255,255):(Ae.a,this.pdf.setDrawColor(Ae.r,Ae.g,Ae.b))}}),Object.defineProperty(this,"lineCap",{get:function(){return this.ctx.lineCap},set:function(Re){["butt","round","square"].indexOf(Re)!==-1&&(this.ctx.lineCap=Re,this.pdf.setLineCap(Re))}}),Object.defineProperty(this,"lineWidth",{get:function(){return this.ctx.lineWidth},set:function(Re){isNaN(Re)||(this.ctx.lineWidth=Re,this.pdf.setLineWidth(Re))}}),Object.defineProperty(this,"lineJoin",{get:function(){return this.ctx.lineJoin},set:function(Re){["bevel","round","miter"].indexOf(Re)!==-1&&(this.ctx.lineJoin=Re,this.pdf.setLineJoin(Re))}}),Object.defineProperty(this,"miterLimit",{get:function(){return this.ctx.miterLimit},set:function(Re){isNaN(Re)||(this.ctx.miterLimit=Re,this.pdf.setMiterLimit(Re))}}),Object.defineProperty(this,"textBaseline",{get:function(){return this.ctx.textBaseline},set:function(Re){this.ctx.textBaseline=Re}}),Object.defineProperty(this,"textAlign",{get:function(){return this.ctx.textAlign},set:function(Re){["right","end","center","left","start"].indexOf(Re)!==-1&&(this.ctx.textAlign=Re)}});var ke=null,Xe=null,Se=null;Object.defineProperty(this,"fontFaces",{get:function(){return Se},set:function(Re){ke=null,Xe=null,Se=Re}}),Object.defineProperty(this,"font",{get:function(){return this.ctx.font},set:function(Re){var Ae;if(this.ctx.font=Re,(Ae=/^\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(Re))!==null){var Be=Ae[1];Ae[2];var qe=Ae[3],Ke=Ae[4];Ae[5];var Ze=Ae[6],Ue=/^([.\d]+)((?:%|in|[cem]m|ex|p[ctx]))$/i.exec(Ke)[2];Ke=Math.floor(Ue==="px"?parseFloat(Ke)*this.pdf.internal.scaleFactor:Ue==="em"?parseFloat(Ke)*this.pdf.getFontSize():parseFloat(Ke)*this.pdf.internal.scaleFactor),this.pdf.setFontSize(Ke);var et=function(js){var zt,Nt,Ds=[],_t=js.trim();if(_t==="")return aDe;if(_t in Nyt)return[Nyt[_t]];for(;_t!=="";){switch(Nt=null,zt=(_t=Syt(_t)).charAt(0)){case'"':case"'":Nt=AEn(_t.substring(1),zt);break;default:Nt=EEn(_t)}if(Nt===null||(Ds.push(Nt[0]),(_t=Syt(Nt[1]))!==""&&_t.charAt(0)!==","))return aDe;_t=_t.replace(/^,/,"")}return Ds}(Ze);if(this.fontFaces){var Qe=function(js,zt){var Nt=js.getFontList(),Ds=JSON.stringify(Nt);if(ke===null||Xe!==Ds){var _t=function(Xs){var rn=[];return Object.keys(Xs).forEach(function(Ps){Xs[Ps].forEach(function(_n){var Zs=null;switch(_n){case"bold":Zs={family:Ps,weight:"bold"};break;case"italic":Zs={family:Ps,style:"italic"};break;case"bolditalic":Zs={family:Ps,weight:"bold",style:"italic"};break;case"":case"normal":Zs={family:Ps}}Zs!==null&&(Zs.ref={name:Ps,style:_n},rn.push(Zs))})}),rn}(Nt);ke=function(Xs){for(var rn={},Ps=0;Ps=700||Be==="bold")&&(ft="bold"),Be==="italic"&&(ft+="italic"),ft.length===0&&(ft="normal");for(var lt="",Mt={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"},Ft=0;Ft=2*Math.PI&&(ge=0,fe=2*Math.PI),this.path.push({type:"arc",x:le,y:he,radius:ve,startAngle:ge,endAngle:fe,counterclockwise:je})},h.prototype.arcTo=function(le,he,ve,ge,fe){throw new Error("arcTo not implemented.")},h.prototype.rect=function(le,he,ve,ge){if(isNaN(le)||isNaN(he)||isNaN(ve)||isNaN(ge))throw jh.error("jsPDF.context2d.rect: Invalid arguments",arguments),new Error("Invalid arguments passed to jsPDF.context2d.rect");this.moveTo(le,he),this.lineTo(le+ve,he),this.lineTo(le+ve,he+ge),this.lineTo(le,he+ge),this.lineTo(le,he),this.lineTo(le+ve,he),this.lineTo(le,he)},h.prototype.fillRect=function(le,he,ve,ge){if(isNaN(le)||isNaN(he)||isNaN(ve)||isNaN(ge))throw jh.error("jsPDF.context2d.fillRect: Invalid arguments",arguments),new Error("Invalid arguments passed to jsPDF.context2d.fillRect");if(!p.call(this)){var fe={};this.lineCap!=="butt"&&(fe.lineCap=this.lineCap,this.lineCap="butt"),this.lineJoin!=="miter"&&(fe.lineJoin=this.lineJoin,this.lineJoin="miter"),this.beginPath(),this.rect(le,he,ve,ge),this.fill(),fe.hasOwnProperty("lineCap")&&(this.lineCap=fe.lineCap),fe.hasOwnProperty("lineJoin")&&(this.lineJoin=fe.lineJoin)}},h.prototype.strokeRect=function(le,he,ve,ge){if(isNaN(le)||isNaN(he)||isNaN(ve)||isNaN(ge))throw jh.error("jsPDF.context2d.strokeRect: Invalid arguments",arguments),new Error("Invalid arguments passed to jsPDF.context2d.strokeRect");x.call(this)||(this.beginPath(),this.rect(le,he,ve,ge),this.stroke())},h.prototype.clearRect=function(le,he,ve,ge){if(isNaN(le)||isNaN(he)||isNaN(ve)||isNaN(ge))throw jh.error("jsPDF.context2d.clearRect: Invalid arguments",arguments),new Error("Invalid arguments passed to jsPDF.context2d.clearRect");this.ignoreClearRect||(this.fillStyle="#ffffff",this.fillRect(le,he,ve,ge))},h.prototype.save=function(le){le=typeof le!="boolean"||le;for(var he=this.pdf.internal.getCurrentPageInfo().pageNumber,ve=0;ve0||this.margin[1]>0||this.margin[2]>0||this.margin[3]>0};h.prototype.drawImage=function(le,he,ve,ge,fe,je,Ee,Me,De){var ze=this.pdf.getImageProperties(le),ke=1,Xe=1,Se=1,Re=1;ge!==void 0&&Me!==void 0&&(Se=Me/ge,Re=De/fe,ke=ze.width/ge*Me/ge,Xe=ze.height/fe*De/fe),je===void 0&&(je=he,Ee=ve,he=0,ve=0),ge!==void 0&&Me===void 0&&(Me=ge,De=fe),ge===void 0&&Me===void 0&&(Me=ze.width,De=ze.height);var Ae=this.ctx.transform.decompose(),Be=ce(Ae.rotate.shx),qe=new c,Ke=(qe=(qe=(qe=qe.multiply(Ae.translate)).multiply(Ae.skew)).multiply(Ae.scale)).applyToRectangle(new o(je-he*Se,Ee-ve*Re,ge*ke,fe*Xe));if(this.autoPaging){for(var Ze,Ue=y.call(this,Ke),et=[],Qe=0;QeGe||ftKe||Ue0)){for(;De>=0;De--)if(fe[De-1].close!==!0&&fe[De-1].begin!==!0){fe[De-1].deltas.push(ve),fe[De-1].abs.push(Me);break}}break;case"bct":ve=[Me.x1-je[Ee-1].x,Me.y1-je[Ee-1].y,Me.x2-je[Ee-1].x,Me.y2-je[Ee-1].y,Me.x-je[Ee-1].x,Me.y-je[Ee-1].y],fe[fe.length-1].deltas.push(ve);break;case"qct":var ze=je[Ee-1].x+2/3*(Me.x1-je[Ee-1].x),ke=je[Ee-1].y+2/3*(Me.y1-je[Ee-1].y),Xe=Me.x+2/3*(Me.x1-Me.x),Se=Me.y+2/3*(Me.y1-Me.y),Re=Me.x,Ae=Me.y;ve=[ze-je[Ee-1].x,ke-je[Ee-1].y,Xe-je[Ee-1].x,Se-je[Ee-1].y,Re-je[Ee-1].x,Ae-je[Ee-1].y],fe[fe.length-1].deltas.push(ve);break;case"arc":fe.push({deltas:[],abs:[],arc:!0}),Array.isArray(fe[fe.length-1].abs)&&fe[fe.length-1].abs.push(Me)}}ge=he?null:le==="stroke"?"stroke":"fill";for(var Be=!1,qe=0;qe=.01&&(ge=this.pdf.internal.getFontSize(),this.pdf.setFontSize(ge*le.scale),fe=this.lineWidth,this.lineWidth=fe*le.scale);var Ts=this.autoPaging!=="text";if(Ts||Ft.y+Ft.h<=Qe){if(Ts||Ft.y>=Ue&&Ft.x<=nt){var js=Ts?le.text:this.pdf.splitTextToSize(le.text,le.maxWidth||nt-Ft.x)[0],zt=v([JSON.parse(JSON.stringify(Xe))],this.posX+this.margin[3],-lt+Ue+this.ctx.prevPageLastElemOffset)[0],Nt=Ts&&(Ze>qe||Ze=.01&&(this.pdf.setFontSize(ge),this.lineWidth=fe)}}else le.scale>=.01&&(ge=this.pdf.internal.getFontSize(),this.pdf.setFontSize(ge*le.scale),fe=this.lineWidth,this.lineWidth=fe*le.scale),this.pdf.text(le.text,De.x+this.posX,De.y+this.posY,{angle:le.angle,align:he,renderingMode:le.renderingMode,maxWidth:le.maxWidth}),le.scale>=.01&&(this.pdf.setFontSize(ge),this.lineWidth=fe)},W=function(le,he,ve,ge){ve=ve||0,ge=ge||0,this.pdf.internal.out(n(le+ve)+" "+r(he+ge)+" l")},V=function(le,he,ve){return this.pdf.lines(le,he,ve,null,null)},K=function(le,he,ve,ge,fe,je,Ee,Me){this.pdf.internal.out([t(a(ve+le)),t(i(ge+he)),t(a(fe+le)),t(i(je+he)),t(a(Ee+le)),t(i(Me+he)),"c"].join(" "))},Q=function(le,he,ve,ge){for(var fe=2*Math.PI,je=Math.PI/2;he>ve;)he-=fe;var Ee=Math.abs(ve-he);Ee1e-5;){var ke=ze+De*Math.min(Ee,je);Me.push(J.call(this,le,ze,ke)),Ee-=Math.abs(ke-ze),ze=ke}return Me},J=function(le,he,ve){var ge=(ve-he)/2,fe=le*Math.cos(ge),je=le*Math.sin(ge),Ee=fe,Me=-je,De=Ee*Ee+Me*Me,ze=De+Ee*fe+Me*je,ke=4/3*(Math.sqrt(2*De*ze)-ze)/(Ee*je-Me*fe),Xe=Ee-ke*Me,Se=Me+ke*Ee,Re=Xe,Ae=-Se,Be=ge+he,qe=Math.cos(Be),Ke=Math.sin(Be);return{x1:le*Math.cos(he),y1:le*Math.sin(he),x2:Xe*qe-Se*Ke,y2:Xe*Ke+Se*qe,x3:Re*qe-Ae*Ke,y3:Re*Ke+Ae*qe,x4:le*Math.cos(ve),y4:le*Math.sin(ve)}},ce=function(le){return 180*le/Math.PI},ue=function(le,he,ve,ge,fe,je){var Ee=le+.5*(ve-le),Me=he+.5*(ge-he),De=fe+.5*(ve-fe),ze=je+.5*(ge-je),ke=Math.min(le,fe,Ee,De),Xe=Math.max(le,fe,Ee,De),Se=Math.min(he,je,Me,ze),Re=Math.max(he,je,Me,ze);return new o(ke,Se,Xe-ke,Re-Se)},ne=function(le,he,ve,ge,fe,je,Ee,Me){var De,ze,ke,Xe,Se,Re,Ae,Be,qe,Ke,Ze,Ue,et,Qe,Ge=ve-le,nt=ge-he,ft=fe-ve,lt=je-ge,Mt=Ee-fe,Ft=Me-je;for(ze=0;ze<41;ze++)qe=(Ae=(ke=le+(De=ze/40)*Ge)+De*((Se=ve+De*ft)-ke))+De*(Se+De*(fe+De*Mt-Se)-Ae),Ke=(Be=(Xe=he+De*nt)+De*((Re=ge+De*lt)-Xe))+De*(Re+De*(je+De*Ft-Re)-Be),ze==0?(Ze=qe,Ue=Ke,et=qe,Qe=Ke):(Ze=Math.min(Ze,qe),Ue=Math.min(Ue,Ke),et=Math.max(et,qe),Qe=Math.max(Qe,Ke));return new o(Math.round(Ze),Math.round(Ue),Math.round(et-Ze),Math.round(Qe-Ue))},ee=function(){if(this.prevLineDash||this.ctx.lineDash.length||this.ctx.lineDashOffset){var le,he,ve=(le=this.ctx.lineDash,he=this.ctx.lineDashOffset,JSON.stringify({lineDash:le,lineDashOffset:he}));this.prevLineDash!==ve&&(this.pdf.setLineDash(this.ctx.lineDash,this.ctx.lineDashOffset),this.prevLineDash=ve)}}})(go.API),function(s){var t=function(l){var o,c,d,u,h,m,p,x,g,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)-(g=h%85))/85)-(x=h%85))/85)-(p=h%85))/85)%85,c.push(m+33,p+33,x+33,g+33,y+33)):c.push(122);return function(b,v){for(var N=v;N>0;N--)b.pop()}(c,o.length),String.fromCharCode.apply(String,c)+"~>"},n=function(l){var o,c,d,u,h,m=String,p="length",x=255,g="charCodeAt",y="slice",b="replace";for(l[y](-2),l=l[y](0,-2)[b](/\s/g,"")[b]("z","!!!!!"),d=[],u=0,h=(l+=o="uuuuu"[y](l[p]%5||5))[p];h>u;u+=5)c=52200625*(l[g](u)-33)+614125*(l[g](u+1)-33)+7225*(l[g](u+2)-33)+85*(l[g](u+3)-33)+(l[g](u+4)-33),d.push(x&c>>24,x&c>>16,x&c>>8,x&c);return function(v,N){for(var C=N;C>0;C--)v.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(El.DOMPurify?Promise.resolve(El.DOMPurify):mi(()=>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=Wu(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;pg&&(x=y,y=g,g=x);else{if(o!=="l"&&o!=="landscape")throw"Invalid orientation: "+o;o="l",g>y&&(x=y,y=g,g=x)}return{width:y,height:g,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(rDe):null;var d=new l(c);return c.worker?d:d.from(o).doCallback()}}(go.API),go.API.addJS=function(s){var t,n,r=function(a){for(var i="",l=0;l=0&&a[d]==="\\";d--)c++;i+=c%2==0?"\\"+o:o}else i+=o}return i}(s);return this.internal.events.subscribe("postPutResources",function(){t=this.internal.newObject(),this.internal.out("<<"),this.internal.out("/Names [(EmbeddedJS) "+(t+1)+" 0 R]"),this.internal.out(">>"),this.internal.out("endobj"),n=this.internal.newObject(),this.internal.out("<<"),this.internal.out("/S /JavaScript"),this.internal.out("/JS ("+r+")"),this.internal.out(">>"),this.internal.out("endobj")}),this.internal.events.subscribe("putCatalog",function(){t!==void 0&&n!==void 0&&this.internal.out("/Names <>")}),this},function(s){var t;s.events.push(["postPutResources",function(){var n=this,r=/^(\d+) 0 obj$/;if(this.outline.root.children.length>0)for(var a=n.outline.render().split(/\r\n/),i=0;i> endobj")}var 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,Q=void 0;var fe=I*D;J=new Uint8Array(fe);for(var je=new DataView(B.buffer),Ee=0;Ee536870912)throw new Error("Image dimensions exceed 512MB, which is too large.");this.data=new Uint8Array(t);try{this[s]()}catch(n){jh.log("bit decode error:"+n)}},V2.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)}},V2.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)}},V2.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}},V2.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}},V2.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},Eyt=function(s,t,n){n||(n={});var r,a,i,l,o,c,d,u=[],h=[u],m=n.textIndent||0,p=0,x=0,g=s.split(" "),y=oae.apply(this,[" ",n])[0];if(c=n.lineIndent===-1?g[0].length+2:n.lineIndent||0){var b=Array(c).join(" "),v=[];g.map(function(C){(C=C.split(/\s*\n/)).length>1?v=v.concat(C.map(function(A,T){return(T&&A.length?` `:"")+A})):v.push(C[0])}),g=v,c=Cyt.apply(this,[b,n])}for(i=0,l=g.length;it||N){if(x>t){for(o=Ayt.apply(this,[r,a,t-(m+p),t]),u.push(o.shift()),u=[o.pop()];o.length;)h.push([o.shift()]);x=a.slice(r.length-(u[0]?u[0].length:0)).reduce(function(C,A){return C+A},0)}else u=[r];h.push(u),m=x+c,p=y}else u.push(r),m+=p+x,p=y}return d=c?function(C,A){return(A?b:"")+C.join(" ")}:function(C){return C.join(" ")},h.map(d)},U7.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-CkaqucVz.js"),[])).catch(function(m){return Promise.reject(new Error("Could not load canvg: "+m))}).then(function(m){return m.default?m.default:m}).then(function(m){return m.fromString(d,s,u)},function(){return Promise.reject(new Error("Could not load canvg."))}).then(function(m){return m.render(u)}).then(function(){h.addImage(c.toDataURL("image/jpeg",1),t,n,r,a,l,o)})},go.API.putTotalPages=function(s){var t,n=0;parseInt(this.internal.getFont().id.substr(1),10)<15?(t=new RegExp(s,"g"),n=this.internal.getNumberOfPages()):(t=new RegExp(this.pdfEscape16(s,this.internal.getFont()),"g"),n=this.pdfEscape16(this.internal.getNumberOfPages()+"",this.internal.getFont()));for(var r=1;r<=this.internal.getNumberOfPages();r++)for(var a=0;a1){for(u=0;u>`)}),this.internal.viewerpreferences.isSubscribed=!0),this.internal.viewerpreferences.configuration=n,this},go.API.addMetadata=function(s,t){return this.internal.__metadata__===void 0&&(this.internal.__metadata__={metadata:s,namespaceUri:t??"http://jspdf.default.namespaceuri/",rawXml:typeof t=="boolean"&&t},this.internal.events.subscribe("putCatalog",DEn),this.internal.events.subscribe("postPutResources",IEn)),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,x){return p-x})).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="",x=0;x>"),c("endobj");var v=d();c("<<"),c("/Type /Font"),c("/BaseFont /"+g9(o.fontName)),c("/FontDescriptor "+b+" 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 /"+g9(o.fontName)),c("/Encoding /"+o.encoding),c("/DescendantFonts ["+v+" 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 b=0;b>"),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,x=h.fonts,g=p,y="",b=0,v="",N=x[g].encoding;if(x[g].encoding!=="Identity-H")return{text:o,x:c,y:d,options:u,mutex:h};for(v=o,g=p,Array.isArray(o)&&(v=o[0]),b=0;b","<","[","]","[","{","}","{","«","»","«","‹","›","‹","⁅","⁆","⁅","⁽","⁾","⁽","₍","₎","₍","≤","≥","≤","〈","〉","〈","﹙","﹚","﹙","﹛","﹜","﹛","﹝","﹞","﹝","﹤","﹥","﹤"],b=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)$/),v=!1,N=0;this.__bidiEngine__={};var C=function(B){var q=B.charCodeAt(),W=q>>8,V=g[W];return V!==void 0?h[256*V+(255&q)]:W===252||W===253?"AL":b.test(W)?"L":W===8?"R":"N"},A=function(B){for(var q,W=0;W=q.length||(K=W[V-1])!=="EN"&&K!=="AN"||(Q=q[V+1])!=="EN"&&Q!=="AN"?ue="N":v&&(Q="AN"),ue=Q===K?Q:"N";break;case"ES":ue=(K=V>0?W[V-1]:"B")==="EN"&&V+10&&W[V-1]==="EN"){ue="EN";break}if(v){ue="N";break}for(J=V+1,ce=q.length;J=1425&&ne<=2303||ne===64286;if(K=q[J],ee&&(K==="R"||K==="AL")){ue="R";break}}}ue=V<1||(K=q[V-1])==="B"?"N":W[V-1];break;case"B":v=!1,a=!0,ue=N;break;case"S":i=!0,ue="N"}return ue},P=function(B,q,W){var V=B.split("");return W&&M(V,W,{hiLevel:N}),V.reverse(),q&&q.reverse(),V.join("")},M=function(B,q,W){var V,K,Q,J,ce,ue=-1,ne=B.length,ee=0,le=[],he=N?p:m,ve=[];for(v=!1,a=!1,i=!1,K=0;K0)if(V===16){for(K=ue;K-1){for(K=ue;K=0&&ge[Me]==="WS";Me--)fe[Me]=N}}(ve,q,ne)},I=function(B,q,W,V,K){if(!(K.hiLevel=B){for(ce=ee+1;ce=B;)ce++;for(ue=ee,J=ce-1;ue=0&&(Q[ne]=y[ue+1])}(V,W,K),I(2,V,q,W,K),I(1,V,q,W,K),V.join("")};return this.__bidiEngine__.doBidiReorder=function(B,q,W){if(function(K,Q){if(Q)for(var J=0;J>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 hk,h6=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,x,g;for(g 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 h6).writeInt(this.scalarType),a.writeShort(p),a.writeShort(h),a.writeShort(l),a.writeShort(u),i=16*p,d=a.pos+i,o=null,x=[],n)for(m=n[g],a.writeString(g),a.writeInt(s(m)),a.writeInt(d),a.writeInt(m.length),x=x.concat(m),g==="head"&&(o=d),d+=m.length;d%4;)x.push(0),d++;return a.write(x),r=2981146554-s(a.data),a.pos=o+8,a.writeUInt32(r),a.data},s=function(n){var r,a,i,l;for(n=f$t.call(n);n.length%4;)n.push(0);for(i=new h6(n),a=0,r=0,l=n.length;rm;c=0<=m?++C:--C)A.push(t.readUInt16());return A}(),t.pos+=2,g=function(){var C,A;for(A=[],c=C=0;0<=m?Cm;c=0<=m?++C:--C)A.push(t.readUInt16());return A}(),d=function(){var C,A;for(A=[],c=C=0;0<=m?Cm;c=0<=m?++C:--C)A.push(t.readUInt16());return A}(),u=function(){var C,A;for(A=[],c=C=0;0<=m?Cm;c=0<=m?++C:--C)A.push(t.readUInt16());return A}(),a=(this.length-t.pos+this.offset)/2,o=function(){var C,A;for(A=[],c=C=0;0<=a?Ca;c=0<=a?++C:--C)A.push(t.readUInt16());return A}(),c=b=0,N=i.length;b=y;r=x<=y?++v:--v)u[c]===0?l=r+d[c]:(l=o[u[c]/2+(r-x)-(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,x,g,y,b,v,N,C,A,T,P,M,I,D,B,q,W,V,K,Q,J,ce,ue,ne,ee,le,he,ve,ge,fe,je,Ee,Me,De,ze,ke;switch(V=new h6,l=Object.keys(t).sort(function(Xe,Se){return Xe-Se}),n){case"macroman":for(g=0,y=function(){var Xe=[];for(x=0;x<256;++x)Xe.push(0);return Xe}(),v={0:0},i={},K=0,ue=l.length;K=32768)for(c.push(0),T.push(2*(p.length+I-x)),a=ce=B;B<=u?ce<=u:ce>=u;a=B<=u?++ce:--ce)p.push(r[a].new);else c.push(W-B),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(D),V.writeUInt16(M),V.writeUInt16(m),V.writeUInt16(P),je=0,le=h.length;jea;r=0<=a?++r:--r)n=new Fyt(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=Fyt.encode(t,n),(a=new h6).writeUInt16(0),a.writeUInt16(1),r.table=a.data.concat(r.subtable),r},s}(),zEn=function(){function s(){return s.__super__.constructor.apply(this,arguments)}return V5(s,hk),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}(),BEn=function(){function s(){return s.__super__.constructor.apply(this,arguments)}return V5(s,hk),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}(),$En=function(){function s(){return s.__super__.constructor.apply(this,arguments)}return V5(s,hk),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}(),UEn=function(s,t){this.raw=s,this.length=s.length,this.platformID=t.platformID,this.encodingID=t.encodingID,this.languageID=t.languageID},qEn=function(){function s(){return s.__super__.constructor.apply(this,arguments)}return V5(s,hk),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}(),f$t=[].slice,GEn=function(){function s(){return s.__super__.constructor.apply(this,arguments)}return V5(s,hk),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 h6(n.read(a))).readShort(),d=o.readShort(),h=o.readShort(),c=o.readShort(),u=o.readShort(),this.cache[t]=l===-1?new KEn(o,d,h,c,u):new WEn(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}(),ZEn=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,x,g,y,b;for(a in r=p$t.encode(this.generateCmap(),"unicode"),l=this.glyphsFor(t),p={0:0},b=r.charMap)p[(c=b[a]).old]=c.new;for(x in m=r.maxGlyphID,l)x in p||(p[x]=m++);return u=function(v){var N,C;for(N in C={},v)C[v[N]]=N;return C}(p),h=Object.keys(u).sort(function(v,N){return v-N}),g=function(){var v,N,C;for(C=[],v=0,N=h.length;v>"),i.join(` `)}return""+n},t}();const HBe=[{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}],XEn="signature";function QEn(s){return HBe.find(t=>t.id===s)||HBe[0]}const ec=792,Kh=612,Jr=52;function q7(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 Op(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 H5=[22,24,28],v1=[124,128,136],po=[255,255,255];function JEn(s){return s==null||!Number.isFinite(Number(s))?null:new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(Number(s))}const lDe="https://relzejiswnotikjgvjhz.supabase.co";function eTn(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(lDe).origin?s:`${lDe}/functions/v1/image-proxy?url=${encodeURIComponent(t.toString())}`}catch{return s}}async function PG(s,t=2e3){if(!s)return null;try{const n=await fetch(eTn(s),{mode:"cors"});if(!n.ok)return null;const r=await n.blob(),a=URL.createObjectURL(r),i=await new Promise((g,y)=>{const b=new Image;b.crossOrigin="anonymous",b.onload=()=>g(b),b.onerror=y,b.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(g=>{const y=new Image;y.onload=()=>g(y),y.onerror=()=>g(y),y.src=p}),dataUrl:p,w:o,h:c,format:m}}catch{return null}}let x$t={x:.5,y:.5};function tTn(s){x$t={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 dte(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 x=0,g=0,y=t.w,b=t.h;const v=l.focal??x$t;if(m>p?(y=t.h*p,x=Math.min(Math.max(0,t.w*v.x-y/2),t.w-y)):(b=t.w/p,g=Math.min(Math.max(0,t.h*v.y-b/2),t.h-b)),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,x,g,y,b,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,P]=l.tint.color;h.globalCompositeOperation="multiply",h.fillStyle=`rgba(${A},${T},${P},${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 C=u.toDataURL("image/jpeg",.92);s.addImage(C,"JPEG",n,r,a,i,void 0,"FAST")}function YR(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,x=t.h;u>1?(p=t.h,h=(t.w-p)/2):(x=t.w,m=(t.h-x)/2);try{d.drawImage(t.el,h,m,p,x,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 $Ze(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 xb(s,t){const n=s.GState;n&&s.setGState(new n({opacity:t}))}function sTn(s,t,n,r,a,i={font:"helvetica",size:10,color:H5}){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 CV(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=sTn(s,c,n+13,l,a-13,{font:i.font,size:i.size,color:i.color,leading:o})+(i.gap??7)}),l}function gv(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 yF='',vF='',nTn={title:"Facebook",slug:"facebook",get svg(){return yF+"Facebook"+vF+this.path+bF},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"},rTn={title:"Instagram",slug:"instagram",get svg(){return yF+"Instagram"+vF+this.path+bF},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"},aTn={title:"Pinterest",slug:"pinterest",get svg(){return yF+"Pinterest"+vF+this.path+bF},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"},iTn={title:"TikTok",slug:"tiktok",get svg(){return yF+"TikTok"+vF+this.path+bF},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"},oTn={title:"trulia",slug:"trulia",get svg(){return yF+"trulia"+vF+this.path+bF},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"},lTn={title:"YouTube",slug:"youtube",get svg(){return yF+"YouTube"+vF+this.path+bF},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"},cTn={title:"Zillow",slug:"zillow",get svg(){return yF+"Zillow"+vF+this.path+bF},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"},dTn={facebook:nTn,instagram:rTn,youtube:lTn,tiktok:iTn,pinterest:aTn,zillow:cTn,trulia:oTn},zyt=new Map;function uTn(s,t,n){return`${s}|${t}|${n}`}function hTn(s,t,n=128){const r=s.toLowerCase().replace(/[^a-z]/g,""),a=dTn[r];if(!a)return null;const i=uTn(r,t,n),l=zyt.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 zyt.set(i,d),d}catch{return null}}const ad="helvetica";let tq="helvetica";function g$t(s,t,n,r,a,i){const l=`#${n.map(d=>Math.round(d).toString(16).padStart(2,"0")).join("")}`,o=hTn(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(ad,"bold"),s.setFontSize(c*1.15),s.setTextColor(...po),s.text(t.charAt(0).toUpperCase(),r,a+c*.42,{align:"center"})}let ute=[252,251,248],RO=[244,247,250],Bb=[223,228,234],Sy=[72,78,88];function hte(s,t){return sBt(s.data.pages,t)}function UZe(s){var n;const t=s.coAgent;return t!=null&&t.enabled&&((n=t.name)!=null&&n.trim())?t:null}function y$t(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 mTn(s){return[s.agent.brokerageName,s.agent.phone,s.agent.email].filter(Boolean).join(" | ")}function Qf(s,t,n,r,a,i,l){const o=l.font||ad,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 fu(s,t,n,r,a,i){s.setFont(ad,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 AV(s,t,n,r,a,i){const{doc:l}=s;l.setFont(ad,"bold"),l.setFontSize(7.5),l.setTextColor(...a||s.accent),l.text(t.toUpperCase(),n,r,{charSpace:1.8,align:i})}function E0(s,t=ute){s.doc.addPage("letter","landscape"),s.pageNo+=1,s.doc.setFillColor(...t),s.doc.rect(0,0,ec,Kh,"F")}function Cy(s,t,n,r,a={}){const{doc:i}=s,l=!!a.dark,o=a.width??ec-Jr*2-60;AV(s,t,Jr,62,s.accent),i.setFont(tq,"bold"),i.setFontSize(tq==="times"?25:23);const c=i.splitTextToSize(n,o).slice(0,3);i.setTextColor(...l?po:s.brand),c.forEach((u,h)=>i.text(u,Jr,96+h*29));let d=96+(c.length-1)*29;return r&&(d=fu(i,r,Jr,d+26,Math.min(o+40,ec-Jr*2),{size:10,color:l?Op(po,s.deep,.28):v1,leading:15,maxLines:2})),d+34}function T0(s,t=!1){const{doc:n,data:r}=s,a=t?Op(po,s.deep,.7):Bb;n.setDrawColor(...a),n.setLineWidth(.6),n.line(Jr,Kh-46,ec-Jr,Kh-46);const i=Kh-30;n.setFont(ad,"bold"),n.setFontSize(7),n.setTextColor(...t?po:s.brand),t&&xb(n,.9),n.text((r.agent.name||"").toUpperCase(),Jr,i,{charSpace:1.4});const l=mTn(r);l&&(n.setFont(ad,"normal"),n.setFontSize(7),n.setTextColor(...t?po:v1),Qf(n,l,ec/2,i,ec/2-Jr-40,7,{color:t?po:v1,align:"center"})),n.setFont(ad,"normal"),n.setFontSize(7),n.setTextColor(...t?po:v1),n.text(String(s.pageNo).padStart(2,"0"),ec-Jr,i,{align:"right"}),t&&xb(n,1)}function v$t(s,t,n,r,a){const{doc:i}=s;i.setFont(ad,"bold"),i.setFontSize(8);const l=i.splitTextToSize(t,a-28),o=16+l.length*12;return gv(i,n,r,a,o,6,Op(s.accent,po,.86)),i.setTextColor(...Op(s.brand,H5,.2)),l.forEach((c,d)=>i.text(c,n+14,r+20+d*12)),r+o}function qZe(s,t,n,r,a,i={}){const{doc:l}=s;s.hero?dte(l,s.hero,t,n,r,a,{radius:10,dpi:s.dpi,tint:i.tint?{color:s.deep,amount:i.tint}:void 0}):gv(l,t,n,r,a,10,Op(s.deep,po,.12))}function pTn(s){const{doc:t,data:n}=s,{line1:r,line2:a}=y$t(n),i=336;s.hero?dte(t,s.hero,0,0,ec,Kh,{dpi:s.dpi,darken:.12}):(t.setFillColor(...s.deep),t.rect(0,0,ec,Kh,"F")),t.setFillColor(...s.deep),t.rect(0,0,i,Kh,"F"),t.setFillColor(...s.accent),t.rect(i-3,0,3,Kh,"F");const l=hte(s,"cover");AV(s,l.kicker,Jr,66),t.setFont(tq,"bold"),t.setFontSize(tq==="times"?29:26),t.setTextColor(...po);const o=t.splitTextToSize(r,i-Jr*2).slice(0,3);o.forEach((y,b)=>t.text(y,Jr,102+b*30));let c=102+(o.length-1)*30;a&&(t.setFont(ad,"normal"),t.setFontSize(9),xb(t,.9),Qf(t,a.toUpperCase(),Jr,c+22,i-Jr*2,9,{color:po,charSpace:1.4}),xb(t,1),c+=22),c=fu(t,l.body,Jr,c+34,i-Jr*2,{size:10,color:Op(po,s.deep,.22),leading:16});const d=[JEn(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(Jr,c+30,Jr+40,c+30),Qf(t,d.join(" · "),Jr,c+54,i-Jr*2,10,{style:"bold",color:po,charSpace:1}));const u=UZe(n),h=Kh-(u?152:128);let m=Jr;s.headshot&&(YR(t,s.headshot,Jr+22,h+18,22),u&&s.coHeadshot?(YR(t,s.coHeadshot,Jr+56,h+18,22),m=Jr+90):m=Jr+56),Qf(t,u?`${n.agent.name} + ${u.name}`:n.agent.name,m,h+12,i-m-24,14,{style:"bold",color:po}),t.setFont(ad,"normal"),t.setFontSize(8),xb(t,.85);const p=[n.agent.brokerageName].filter(Boolean).join("");p&&Qf(t,p,m,h+26,i-m-24,8,{color:po});const x=[n.agent.phone,n.agent.email].filter(Boolean).join(" · ");if(x&&Qf(t,x,m,h+38,i-m-24,8,{color:po}),u){const y=[u.title||"Co-listing agent",u.phone].filter(Boolean).join(" · ");y&&Qf(t,y,Jr,h+56,i-Jr-24,8,{color:po})}xb(t,1),s.logo&&(xb(t,.95),$Ze(t,s.logo,Jr,Kh-74,132,30,"left"),xb(t,1));const g=n.sellerName?`PREPARED FOR ${n.sellerName.toUpperCase()}`:"PREPARED FOR YOUR HOME";t.setFont(ad,"bold"),t.setFontSize(7.5),t.setTextColor(...po),xb(t,.9),t.text(g,ec-Jr,Kh-34,{align:"right",charSpace:1.6}),xb(t,1)}function fTn(s){E0(s);const{doc:t}=s,n=hte(s,"welcome"),r=Cy(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(...Op(s.accent,po,.85)),t.circle(Jr+13,i-3,13,"F"),t.setFont(ad,"bold"),t.setFontSize(9),t.setTextColor(...s.brand),t.text(String(c+1).padStart(2,"0"),Jr+13,i,{align:"center"});const d=Jr+44,u=ec-d-Jr-40;t.setFont(ad,"bold"),t.setFontSize(11.5),t.setTextColor(...H5),t.text(l,d,i),fu(t,o,d,i+18,u,{size:9.5,color:Sy,leading:14,maxLines:2}),i+=88}),T0(s)}function xTn(s){E0(s,po);const{doc:t,data:n}=s,r=hte(s,"agent"),a=Cy(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=UZe(n),l=ec-Jr-260,o=a-6,c=262;if(i){const x=(g,y,b,v)=>{gv(t,l,g,260,124,10,RO,"FD",Bb),t.setFillColor(...s.accent),t.rect(l,g,260,3,"F");let N=l+18;b&&(YR(t,b,l+48,g+62+2,30),N=l+90);const C=260-(N-l)-18;Qf(t,y,N,g+40,C,13,{style:"bold",color:s.brand});let A=g+56;v.filter(Boolean).slice(0,4).forEach(T=>{Qf(t,String(T),N,A,C,8,{color:v1}),A+=13})};x(o,n.agent.name,s.headshot,[n.agent.brokerageName,n.agent.phone,n.agent.email]),x(o+124+14,i.name,s.coHeadshot,[i.title||"Co-listing agent",i.brokerageName||n.agent.brokerageName,i.phone,i.email])}else{gv(t,l,o,260,c,10,RO,"FD",Bb),t.setFillColor(...s.accent),t.rect(l,o,260,3,"F"),s.headshot&&YR(t,s.headshot,l+130,o+72,42),Qf(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=>{Qf(t,String(p),l+130,m,220,8.5,{color:v1,align:"center"}),m+=14}),s.logo&&$Ze(t,s.logo,l+80,o+c-44,100,28,"left")}const d=l-Jr-44;let u=fu(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.",Jr,a+4,d,{size:10,color:Sy,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(ad,"bold"),t.setFontSize(7),t.setTextColor(...v1),t.text(m.toUpperCase(),Jr,u,{charSpace:1.4}),Qf(t,p,Jr+86,u,d-86,10.5,{color:H5}),t.setDrawColor(...Bb),t.setLineWidth(.5),t.line(Jr,u+11,Jr+d,u+11),u+=36}),T0(s)}function gTn(s,t){E0(s);const{doc:n}=s,r=hte(s,"overview"),a=Cy(s,r.kicker,r.headline,r.subhead||null),i=4,l=14,o=(ec-Jr*2-l*(i-1))/i,c=96;t.slice(0,8).forEach((d,u)=>{const h=Jr+u%i*(o+l),m=a+Math.floor(u/i)*(c+l);gv(n,h,m,o,c,8,po,"FD",Bb),n.setFillColor(...s.accent),n.rect(h,m,3,c,"F"),n.setFont(ad,"bold"),n.setFontSize(15),n.setTextColor(...Op(s.brand,po,.55)),n.text(String(u+1).padStart(2,"0"),h+16,m+30),fu(n,d.title,h+16,m+52,o-30,{size:9.5,style:"bold",color:H5,leading:13,maxLines:3})}),T0(s)}function eM(s,t=5){var n;return(((n=s.options)==null?void 0:n.filter(r=>r.enabled).map(r=>r.label))??G4n[s.key]??[]).slice(0,t)}function Byt(s,t,n){E0(s,n.dark?s.deep:ute);const{doc:r}=s,a=Cy(s,n.kicker,n.headline,n.sub,{dark:n.dark}),i=404,l=272,o=!!n.flip,c=o?ec-Jr-i:Jr,d=o?Jr:Jr+i+40,u=ec-Jr*2-i-40;qZe(s,c,a,i,l,{tint:n.dark?.1:0}),AV(s,t.title,d,a+12);let h=fu(r,t.body,d,a+32,u,{size:9.5,color:n.dark?Op(po,s.deep,.2):Sy,leading:15,maxLines:4});const m=eM(t,5);if(m.length&&(h=CV(r,m,d,h+28,u,{font:ad,size:9.5,color:n.dark?po:H5,accent:s.accent,gap:7})),n.note&&!n.dark){const p=Math.min(h+14,Kh-120);v$t(s,n.note,d,p,u)}else n.note&&(r.setFont(ad,"bold"),r.setFontSize(9.5),r.setTextColor(...po),xb(r,.9),fu(r,n.note,Jr,Kh-78,ec-Jr*2,{size:9.5,style:"bold",color:po,leading:13,maxLines:1}),xb(r,1));T0(s,n.dark)}function yTn(s,t){E0(s);const{doc:n}=s,r=Cy(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=eM(t,4),i=["Price + position","MLS story","Media ready","Go live"],l=Math.max(1,a.length||4),o=16,c=(ec-Jr*2-o*(l-1))/l,d=176;(a.length?a:i).forEach((u,h)=>{const m=Jr+h*(c+o);gv(n,m,r,c,d,8,po,"FD",Bb),n.setFont(ad,"bold"),n.setFontSize(16),n.setTextColor(...s.accent),n.text(String(h+1),m+16,r+34),n.setFont(ad,"bold"),n.setFontSize(7.5),n.setTextColor(...v1),n.text((i[h]||`STEP ${h+1}`).toUpperCase(),m+16,r+56,{charSpace:1.2}),fu(n,u,m+16,r+76,c-32,{size:9,color:Sy,leading:13,maxLines:5})}),fu(n,t.body,Jr,r+d+34,ec-Jr*2-120,{size:10,style:"bold",color:s.brand,leading:15,maxLines:2}),T0(s)}function vTn(s,t){E0(s);const{doc:n}=s,r=Cy(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=(ec-Jr*2-l*(i-1))/i,c=68;a.forEach(([u,h],m)=>{const p=Jr+m%i*(o+l),x=r+Math.floor(m/i)*(c+l);gv(n,p,x,o,c,8,po,"FD",Bb),g$t(n,u,h,p+28,x+c/2,20),Qf(n,u,p+48,x+c/2+4,o-64,13,{style:"bold",color:h})});const d=r+2*(c+l)+22;fu(n,t.body,Jr,d,ec-Jr*2-140,{size:9.5,color:Sy,leading:14,maxLines:3}),n.setFont(ad,"normal"),n.setFontSize(7.5),n.setTextColor(...v1),n.text("Distribution varies by MLS, market, and portal policies.",Jr,Kh-62),T0(s)}function bTn(s,t){E0(s,RO);const{doc:n,data:r}=s,{line1:a}=y$t(r),i=Cy(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;gv(n,Jr,i,l,o,10,po,"FD",Bb),gv(n,Jr,i,l,22,10,s.deep),n.setFillColor(...s.deep),n.rect(Jr,i+12,l,10,"F"),n.setFont(ad,"bold"),n.setFontSize(7),n.setTextColor(...po);const c=(r.agent.website||`${a}`).replace(/^https?:\/\//,"").toUpperCase();Qf(n,c,Jr+14,i+15,l-28,7,{style:"bold",color:po,charSpace:1}),qZe(s,Jr+14,i+36,186,142);const d=Jr+214,u=l-228;Qf(n,a,d,i+54,u,12,{style:"bold",color:s.brand}),fu(n,"Welcome home.",d,i+72,u,{size:9,color:s.accent,leading:12,maxLines:1}),fu(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:Sy,leading:12,maxLines:5}),v$t(s,"Shareable. Trackable. Memorable.",Jr+14,i+o-46,l-28);const h=Jr+l+40,m=ec-h-Jr;AV(s,t.title,h,i+12);let p=fu(n,t.body,h,i+32,m,{size:9.5,color:Sy,leading:15,maxLines:5});const x=eM(t,5);x.length&&CV(n,x,h,p+26,m,{font:ad,size:9,color:H5,accent:s.accent,gap:7}),T0(s)}function _Tn(s,t){E0(s,s.deep);const{doc:n}=s,r=Cy(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=Jr+h*(i+l);gv(n,m,r,i,i,12,po),g$t(n,d,u,m+i/2,r+i/2-4,30),n.setFont(ad,"bold"),n.setFontSize(6.5),n.setTextColor(...v1),n.text(d.toUpperCase(),m+i/2,r+i-8,{align:"center",charSpace:.6})});const o=Jr+5*(i+l)+14,c=ec-o-Jr;AV(s,"The campaign can include",o,r+12),CV(n,eM(t,5),o,r+32,c,{font:ad,size:9,color:po,accent:s.accent,gap:7}),fu(n,t.body,Jr,r+i+44,420,{size:9.5,color:Op(po,s.deep,.2),leading:15,maxLines:4}),fu(n,"Every post sends attention back to the property.",Jr,Kh-84,460,{size:11,style:"bold",color:po,leading:14,maxLines:1}),T0(s,!0)}function wTn(s,t){E0(s);const{doc:n}=s,r=Cy(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=eM(t,4),i=["Email announcement","Agent-to-agent outreach","Database follow-up","Local community visibility"];let l=r+6;a.forEach((o,c)=>{gv(n,Jr,l-14,34,34,8,Op(s.accent,po,.85)),n.setFont(ad,"bold"),n.setFontSize(11),n.setTextColor(...s.brand),n.text(String(c+1),Jr+17,l+7,{align:"center"});const d=Jr+52,u=ec-d-Jr-20;n.setFont(ad,"bold"),n.setFontSize(8),n.setTextColor(...s.brand),n.text((i[c]||t.title).toUpperCase(),d,l-2,{charSpace:1.2}),fu(n,o,d,l+14,u,{size:9.5,color:Sy,leading:14,maxLines:2}),l+=76}),fu(n,t.body,Jr,Math.min(l+8,Kh-92),ec-Jr*2-120,{size:9.5,color:v1,leading:14,maxLines:2}),T0(s)}function jTn(s,t){E0(s);const{doc:n}=s,r=Cy(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=eM(t,4),i=["Open house","Signage","Neighborhood","Follow-up"],l=2,o=20,c=(ec-Jr*2-o)/l,d=112;a.forEach((u,h)=>{const m=Jr+h%l*(c+o),p=r+Math.floor(h/l)*(d+o);gv(n,m,p,c,d,8,RO,"FD",Bb),n.setFont(ad,"bold"),n.setFontSize(7.5),n.setTextColor(...s.brand),n.text((i[h]||t.title).toUpperCase(),m+16,p+24,{charSpace:1.2}),fu(n,u,m+16,p+46,c-32,{size:9.5,color:Sy,leading:14,maxLines:3})}),T0(s)}function NTn(s,t){E0(s,RO);const{doc:n}=s,r=Cy(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=eM(t,4),i=["Weekly update","Market check","Smart adjustments","Direct access"];let l=r+10;a.forEach((o,c)=>{n.setFont(ad,"bold"),n.setFontSize(11),n.setTextColor(...s.accent),n.text(String(c+1).padStart(2,"0"),Jr,l),n.setFont(ad,"bold"),n.setFontSize(9),n.setTextColor(...s.brand),n.text((i[c]||"").toUpperCase(),Jr+48,l,{charSpace:1.2}),fu(n,o,Jr+250,l-1,ec-Jr-250-Jr,{size:9.5,color:Sy,leading:13,maxLines:2}),n.setDrawColor(...Bb),n.setLineWidth(.5),n.line(Jr,l+22,ec-Jr,l+22),l+=62}),fu(n,"Marketing creates opportunity. Communication helps us act on it.",Jr,Math.min(l+18,Kh-84),520,{size:11,style:"bold",color:s.brand,leading:14,maxLines:1}),T0(s)}function kTn(s){E0(s,s.deep);const{doc:t,data:n}=s;s.hero&&dte(t,s.hero,0,0,ec,Kh,{tint:{color:s.deep,amount:.92},darken:.25,dpi:s.dpi});const r=hte(s,"closing"),a=Cy(s,r.kicker,r.headline,r.subhead||null,{dark:!0,width:520}),i=420;let l=fu(t,r.body,Jr,a,i,{size:10.5,color:Op(po,s.deep,.18),leading:17});l+=30,CV(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"],Jr,l,i,{font:ad,size:9.5,color:po,accent:s.accent,gap:8});const o=UZe(n),c=250,d=ec-Jr-c,u=a-20,h=o?300:258;gv(t,d,u,c,h,10,po),t.setFillColor(...s.accent),t.rect(d,u,c,3,"F"),s.headshot&&(o&&s.coHeadshot?(YR(t,s.headshot,d+c/2-34,u+70,32),YR(t,s.coHeadshot,d+c/2+34,u+70,32)):YR(t,s.headshot,d+c/2,u+70,38)),Qf(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=>{Qf(t,String(p),d+c/2,m,c-30,8.5,{color:v1,align:"center"}),m+=14}),o?(m+=6,t.setDrawColor(...Bb),t.setLineWidth(.5),t.line(d+24,m-8,d+c-24,m-8),Qf(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=>{Qf(t,String(p),d+c/2,m,c-30,8.5,{color:v1,align:"center"}),m+=13})):s.logo&&$Ze(t,s.logo,d+c/2-50,u+h-44,100,28,"left"),t.setFont(ad,"bold"),t.setFontSize(9),t.setTextColor(...po),xb(t,.9),t.text("LET'S MAKE YOUR HOME THE ONE BUYERS REMEMBER.",Jr,Kh-72,{charSpace:1.4}),xb(t,1),T0(s,!0)}function VZe(s,t){return s.customImages[t.id]||null}function b$t(s,t,n,r,a,i){const l=VZe(s,t);l?dte(s.doc,l,n,r,a,i,{radius:10,dpi:s.dpi}):qZe(s,n,r,a,i)}function STn(s,t){E0(s,t.dark?s.deep:ute);const{doc:n}=s,r=Cy(s,t.kicker||"About",t.headline,t.subhead||null,{dark:t.dark}),a=300,i=t.imageSide!=="left",l=i?ec-Jr-a:Jr,o=i?Jr:Jr+a+40,c=ec-Jr*2-a-40;b$t(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=fu(n,h,o,u,c,{size:10,color:t.dark?Op(po,s.deep,.2):Sy,leading:16,maxLines:7}),u+=26}),t.bullets.length&&CV(n,t.bullets.slice(0,5),o,Math.min(u,Kh-150),c,{font:ad,size:9.5,color:t.dark?po:H5,accent:s.accent,gap:7}),T0(s,t.dark)}function CTn(s,t){E0(s,t.dark?s.deep:RO);const{doc:n}=s,r=Cy(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=(ec-Jr*2-l*(i-1))/i,c=Math.ceil(a.length/i)||1,d=Kh-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 x=Jr+p%i*(o+l),g=r+Math.floor(p/i)*(u+l);gv(n,x,g,o,u,10,t.dark?Op(s.deep,po,.08):po,"FD",Bb),n.setFillColor(...s.accent),n.rect(x,g,3,u,"F"),n.setFont(tq,"bold"),n.setFontSize(30),n.setTextColor(...Op(s.accent,t.dark?s.deep:po,.4)),n.text("“",x+18,g+40),fu(n,m.quote,x+18,g+56,o-40,{size:9.5,color:t.dark?Op(po,s.deep,.2):Sy,leading:14,maxLines:h}),n.setDrawColor(...s.accent),n.setLineWidth(1.2),n.line(x+18,g+u-32,x+42,g+u-32),n.setFont(ad,"bold"),n.setFontSize(8),n.setTextColor(...s.brand);const y=[m.name,m.detail].filter(Boolean).join(" · ");y&&Qf(n,y.toUpperCase(),x+18,g+u-16,o-36,8,{style:"bold",color:t.dark?po:s.brand,charSpace:1.1})}),t.body&&fu(n,t.body,Jr,Math.min(r+c*(u+l)+14,Kh-88),ec-Jr*2-120,{size:9.5,color:t.dark?Op(po,s.deep,.2):v1,leading:14,maxLines:2}),T0(s,t.dark)}function ATn(s,t){E0(s,t.dark?s.deep:ute);const{doc:n}=s,r=Cy(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=(ec-Jr*2-18*(a.length-1))/a.length,o=150;a.forEach((c,d)=>{const u=Jr+d*(l+18);gv(n,u,r,l,o,10,t.dark?Op(s.deep,po,.1):po,"FD",Bb),n.setFillColor(...s.accent),n.rect(u,r,l,3,"F"),Qf(n,c.value||"—",u+l/2,r+76,l-28,34,{style:"bold",color:t.dark?po:s.brand,align:"center"}),fu(n,c.label||"",u+20,r+100,l-40,{size:9,color:t.dark?Op(po,s.deep,.3):v1,leading:12,maxLines:2,align:"center"})}),t.body&&fu(n,t.body,Jr,r+o+40,ec-Jr*2-140,{size:10,color:t.dark?Op(po,s.deep,.2):Sy,leading:15,maxLines:3})}else t.body&&fu(n,t.body,Jr,r,ec-Jr*2-140,{size:10.5,color:t.dark?po:Sy,leading:16});T0(s,t.dark)}function ETn(s,t){E0(s,t.dark?s.deep:po);const{doc:n}=s,r=Cy(s,t.kicker||"Our promise",t.headline,t.subhead||null,{dark:t.dark}),i=!!VZe(s,t)||!!s.hero,l=i?ec-Jr*2-280:ec-Jr*2-140;let o=r;t.body&&(o=fu(n,t.body,Jr,o,l,{size:10,color:t.dark?Op(po,s.deep,.2):Sy,leading:15,maxLines:3})+28),t.bullets.filter(d=>d==null?void 0:d.trim()).slice(0,7).forEach(d=>{gv(n,Jr,o-9,14,14,4,s.accent),n.setFont(ad,"bold"),n.setFontSize(8),n.setTextColor(...po),n.text("✓",Jr+7,o+1,{align:"center"}),o=fu(n,d,Jr+26,o,l-26,{size:10,color:t.dark?po:H5,leading:14,maxLines:2})+22}),i&&b$t(s,t,ec-Jr-240,r,240,250),T0(s,t.dark)}function TTn(s,t){E0(s,s.deep);const{doc:n}=s,r=VZe(s,t)||s.hero;r&&dte(n,r,0,0,ec,Kh,{tint:{color:s.deep,amount:.82},darken:.28,dpi:s.dpi}),AV(s,t.kicker||"Our approach",Jr,Kh/2-84),n.setFont(ad,"bold"),n.setFontSize(30),n.setTextColor(...po);const a=n.splitTextToSize(t.headline||"",ec-Jr*2-140).slice(0,4);a.forEach((i,l)=>n.text(i,Jr,Kh/2-44+l*38)),t.body&&fu(n,t.body,Jr,Kh/2+a.length*38-24,480,{size:10.5,color:Op(po,s.deep,.2),leading:16,maxLines:4}),T0(s,!0)}function $yt(s,t){switch(t.layout){case"testimonials":return CTn(s,t);case"stats":return ATn(s,t);case"checklist":return ETn(s,t);case"statement":return TTn(s,t);case"story":default:return STn(s,t)}}async function MTn(s,t,n){var P,M,I,D;const r=n==="print"?4:2,a=n==="print"?2600:1600,i=QEn((P=t.pages)==null?void 0:P.theme);ute=q7(i.paper),RO=q7(i.paperCool),Bb=q7(i.softLine),Sy=q7(i.bodyInk),tq=i.headFont;const l=q7((i.useAgentColors?t.agent.brandColor:i.brand)||i.brand||"#0E1B2C"),o=q7((i.useAgentColors?t.agent.accentColor:i.accent)||i.accent||"#B8965A"),c=Op(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(B=>B.enabled).sort((B,q)=>B.order-q.order),[h,m,p,x,...g]=await Promise.all([PG(t.property.photoUrl,a),PG(t.agent.headshotUrl,700),PG(t.agent.brokerageLogoUrl,800),PG((d==null?void 0:d.headshotUrl)||null,700),...u.map(B=>PG(B.imageUrl||null,a))]),y={};u.forEach((B,q)=>{y[B.id]=g[q]??null}),tTn(t.focal);const b={doc:s,data:t,brand:l,accent:o,deep:c,hero:h,headshot:m,coHeadshot:x,logo:p,customImages:y,dpi:r,pageNo:1},v=new Set(((D=t.pages)==null?void 0:D.hidden)||[]),N=[...t.services].filter(B=>B.enabled).sort((B,q)=>B.order-q.order),C=B=>N.find(q=>q.key===B);pTn(b),v.has("welcome")||fTn(b),v.has("agent")||xTn(b),u.filter(B=>B.placement!=="end").forEach(B=>$yt(b,B)),v.has("overview")||gTn(b,N);const A=new Set,T=(B,q)=>{const W=C(B);W&&(A.add(B),q(W))};T("photography",B=>Byt(b,B,{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",B=>Byt(b,B,{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",B=>yTn(b,B)),T("syndication",B=>vTn(b,B)),T("website",B=>bTn(b,B)),T("social",B=>_Tn(b,B)),T("email",B=>wTn(b,B)),T("openhouse",B=>jTn(b,B)),T("communication",B=>NTn(b,B)),N.filter(B=>!A.has(B.key)).forEach(B=>{E0(b);const q=Cy(b,"Marketing",B.title,null),W=eM(B,6),V=fu(s,B.body,Jr,q,ec-Jr*2-160,{size:10.5,color:Sy,leading:16});W.length&&CV(s,W,Jr,V+30,ec-Jr*2-160,{font:ad,size:9.5,color:H5,accent:b.accent,gap:8}),T0(b)}),u.filter(B=>B.placement==="end").forEach(B=>$yt(b,B)),v.has("closing")||kTn(b)}const Uyt=[{id:"signature",name:"Signature",description:"Editorial full-bleed cover with a brand-tinted photo motif throughout.",render:MTn}];function LTn(s){return Uyt.find(t=>t.id===s)||Uyt[0]}async function _$t(s,t,n="screen"){const r=new go({unit:"pt",format:"letter",orientation:"landscape",compress:!0});return await LTn(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 PTn(s){return`${(s.property.addressLine1||s.title||"listing-presentation").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"")||"listing-presentation"}-presentation.pdf`}const ITn={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 A4e(s){if(!s)return null;const{data:t}=await U.storage.from(u6).createSignedUrl(s,3600);return(t==null?void 0:t.signedUrl)??null}function E4e(s,t,n){const r=s.agent_snapshot||{},a={...ITn,...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:rBt(s.co_agent),customPages:iBt(s.custom_pages),services:CBe(s.services),pages:s.page_settings&&Object.keys(s.page_settings).length?s.page_settings:kBe,focal:s.photo_focal||SBe}}async function w$t(s,t){if(s.property.photoUrl||!t)return s;const n=await A4e(t);return{...s,property:{...s.property,photoUrl:n}}}async function j$t(s,t,n){const r=await w$t(s,n);return(await _$t(r,t,"screen")).output("blob")}async function N$t(s,t,n="print",r){const a=await w$t(s,r),l=(await _$t(a,t,n)).output("blob"),o=URL.createObjectURL(l),c=document.createElement("a");return c.href=o,c.download=PTn(a),document.body.appendChild(c),c.click(),c.remove(),setTimeout(()=>URL.revokeObjectURL(o),4e3),l}async function k$t(s,t,n){const r=`${s}/${t}/presentation.pdf`,{error:a}=await U.storage.from(u6).upload(r,n,{upsert:!0,contentType:"application/pdf"});return a?null:(await U.from("listing_presentations").update({pdf_path:r,last_generated_at:new Date().toISOString(),status:"final"}).eq("id",t),r)}async function S$t(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 DTn(s,t,n){const r=await S$t(n),a=`${s}/${t}/photo.jpg`,{error:i}=await U.storage.from(u6).upload(a,r,{upsert:!0,contentType:"image/jpeg"});if(i)throw i;return a}async function RTn(s,t,n="presentation",r=1800){const a=await S$t(t,r),i=`${s}/${n}-${Date.now()}.jpg`,{error:l}=await U.storage.from("avatars").upload(i,a,{upsert:!0,contentType:"image/jpeg"});if(l)throw l;const{data:o}=U.storage.from("avatars").getPublicUrl(i);return o.publicUrl}function OTn({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 U4n(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(sa,{className:"h-8 w-8 text-primary/50"})})}const qyt=60*60*24*30;function C$t({open:s,onOpenChange:t,row:n,brand:r,photoUrl:a}){const{user:i}=_s(),[l,o]=j.useState([]),[c,d]=j.useState(""),[u,h]=j.useState([]),[m,p]=j.useState(!1),[x,g]=j.useState(""),[y,b]=j.useState(""),[v,N]=j.useState(!1),C=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([]),g(`Your listing presentation for ${A}`),b(`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(()=>{C.current&&clearTimeout(C.current);const D=c.trim();if(!i||D.length<2||/\S+@\S+\.\S+/.test(D)){h([]);return}return C.current=setTimeout(async()=>{p(!0);const B=`%${D}%`,q=U,{data:W}=await q.from("innercircle_contacts").select("id, first_name, last_name, email").eq("owner_user_id",i.id).not("email","is",null).or(`first_name.ilike.${B},last_name.ilike.${B},email.ilike.${B}`).order("first_name",{ascending:!0}).limit(6);p(!1),h(W||[])},200),()=>{C.current&&clearTimeout(C.current)}},[c,i==null?void 0:i.id]);const T=D=>{D.email&&(o(B=>B.some(q=>q.email.toLowerCase()===D.email.toLowerCase())?B:[...B,D]),d(""),h([]))},P=()=>{const D=c.trim();if(!/\S+@\S+\.\S+/.test(D)){ae.error("Enter a valid email address");return}T({email:D})},M=j.useMemo(()=>!!n&&l.length>0&&x.trim().length>0&&!v,[n,l,x,v]),I=async()=>{if(!(!n||!i)){if(!n.property_photo_path){ae.error("Add the primary exterior photo before emailing the presentation");return}N(!0);try{const D=await j$t(E4e(n,r,a??null),n.template_id,n.property_photo_path),B=await k$t(i.id,n.id,D)||n.pdf_path;if(!B)throw new Error("Could not save the presentation PDF");const{data:q,error:W}=await U.storage.from(u6).createSignedUrl(B,qyt);if(W||!(q!=null&&q.signedUrl))throw new Error("Could not create a share link");const V=await A4e(n.property_photo_path).then(ce=>ce).catch(()=>null),{data:K}=await U.storage.from(u6).createSignedUrl(n.property_photo_path,qyt),{data:Q,error:J}=await U.functions.invoke("listing-presentation-email",{body:{presentation_id:n.id,subject:x,message:y,pdf_url:q.signedUrl,photo_url:(K==null?void 0:K.signedUrl)||V,recipients:l}});if(J)throw J;if(!(Q!=null&&Q.success))throw new Error((Q==null?void 0:Q.error)||"Could not send the email");ae.success(Q.failed?`Sent to ${Q.sent} · ${Q.failed} failed`:`Presentation emailed to ${Q.sent} ${Q.sent===1?"contact":"contacts"}`),t(!1)}catch(D){ae.error((D==null?void 0:D.message)||"Could not send the presentation")}finally{N(!1)}}};return e.jsx(Os,{open:s,onOpenChange:t,children:e.jsxs(Rs,{className:"max-w-lg",children:[e.jsxs(Us,{children:[e.jsxs(zs,{className:"flex items-center gap-2",children:[e.jsx(nn,{className:"h-4 w-4"})," Email this presentation"]}),e.jsxs(Sr,{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(se,{children:"To"}),l.length>0&&e.jsx("div",{className:"flex flex-wrap gap-1.5",children:l.map(D=>e.jsxs($e,{variant:"secondary",className:"gap-1 py-1",children:[[D.first_name,D.last_name].filter(Boolean).join(" ")||D.email,e.jsx("button",{type:"button",onClick:()=>o(B=>B.filter(q=>q.email!==D.email)),"aria-label":`Remove ${D.email}`,children:e.jsx(pr,{className:"h-3 w-3"})})]},D.email))}),e.jsxs("div",{className:"relative",children:[e.jsxs("div",{className:"flex gap-2",children:[e.jsx(be,{value:c,onChange:D=>d(D.target.value),onKeyDown:D=>{D.key==="Enter"&&(D.preventDefault(),P())},placeholder:"Search contacts or type an email"}),e.jsx($,{type:"button",variant:"outline",size:"icon",onClick:P,children:e.jsx(sn,{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(Ht,{className:"h-3 w-3 animate-spin"})," Searching…"]}),u.map(D=>e.jsxs("button",{type:"button",className:"flex w-full items-center gap-2 px-3 py-2 text-left text-sm hover:bg-accent",onClick:()=>T({email:D.email,first_name:D.first_name,last_name:D.last_name,contact_id:D.id}),children:[e.jsx(Lo,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"truncate",children:[D.first_name,D.last_name].filter(Boolean).join(" ")||D.email}),e.jsx("span",{className:"ml-auto truncate text-xs text-muted-foreground",children:D.email})]},D.id))]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"pres-subject",children:"Subject"}),e.jsx(be,{id:"pres-subject",value:x,onChange:D=>g(D.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"pres-message",children:"Message"}),e.jsx(Is,{id:"pres-message",rows:7,value:y,onChange:D=>b(D.target.value)})]})]}),e.jsxs(kr,{children:[e.jsx($,{variant:"outline",onClick:()=>t(!1),disabled:v,children:"Cancel"}),e.jsxs($,{onClick:I,disabled:!M,className:"gap-2",children:[v?e.jsx(Ht,{className:"h-4 w-4 animate-spin"}):e.jsx(Br,{className:"h-4 w-4"}),v?"Sending…":`Send${l.length?` (${l.length})`:""}`]})]})]})})}const FTn=()=>{const s=Vn(),{presentations:t,isLoading:n,create:r,duplicate:a,remove:i,update:l}=eBt(),{data:o}=B4n(),{data:c}=tBt(),{savedTemplates:d,remove:u}=Jzt(),[h,m]=j.useState(null),[p,x]=j.useState(""),[g,y]=j.useState(null),[b,v]=j.useState(null),[N,C]=j.useState(null),A=j.useMemo(()=>{var I,D;return(D=(I=o==null?void 0:o[0])==null?void 0:I.default_services)!=null&&D.length?o[0].default_services:_4e},[o]),T=async()=>{var D;if(!c)return;const I=await r.mutateAsync({title:"Untitled Presentation",template_id:((D=o==null?void 0:o[0])==null?void 0:D.slug)||"signature",agent_snapshot:c,services:A});s(`/apps/listing-presentation-studio/${I.id}`)},P=async I=>{var B;const D=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:(B=I.services)!=null&&B.length?I.services:A,page_settings:I.page_settings});s(`/apps/listing-presentation-studio/${D.id}`)},M=async I=>{try{v(I.id),await N$t(E4e(I,c),I.template_id,"print",I.property_photo_path)}catch(D){ae.error((D==null?void 0:D.message)||"Could not build the PDF")}finally{v(null)}};return e.jsxs(Ks,{children:[e.jsxs("div",{className:"space-y-8",children:[e.jsx("div",{className:"relative overflow-hidden rounded-2xl border bg-gradient-to-br from-primary/10 via-background to-accent/10 p-8",children:e.jsxs("div",{className:"flex flex-col gap-6 md:flex-row md:items-center md:justify-between",children:[e.jsxs("div",{className:"space-y-3",children:[e.jsxs($e,{variant:"secondary",className:"gap-1",children:[e.jsx(dn,{className:"h-3 w-3"})," Listing Presentation Studio"]}),e.jsx("h1",{className:"text-3xl font-semibold tracking-tight",children:"Win the listing before you walk in"}),e.jsx("p",{className:"max-w-2xl text-sm text-muted-foreground",children:"Enter an address, drop in one exterior photo, and get a beautiful 12-page seller presentation branded with your profile — ready to present or print in under two minutes."})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs($,{size:"lg",onClick:T,disabled:r.isPending||!c,className:"gap-2",children:[r.isPending?e.jsx(Ht,{className:"h-4 w-4 animate-spin"}):e.jsx(sn,{className:"h-4 w-4"}),"New presentation"]}),d.length>0&&e.jsxs(Hd,{children:[e.jsx(Gd,{asChild:!0,children:e.jsxs($,{size:"lg",variant:"outline",className:"gap-2",children:[e.jsx(wg,{className:"h-4 w-4"})," From template",e.jsx(_o,{className:"h-4 w-4"})]})}),e.jsx(Md,{align:"end",className:"w-64",children:d.map(I=>e.jsxs(Na,{onClick:()=>P(I),children:[e.jsx(wg,{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(_e,{className:"transition-shadow hover:shadow-md",children:e.jsxs(Oe,{className:"flex items-start justify-between gap-3 p-4",children:[e.jsxs("button",{className:"min-w-0 flex-1 text-left",onClick:()=>P(I),disabled:r.isPending,children:[e.jsxs("p",{className:"flex items-center gap-2 truncate font-medium",children:[e.jsx(wg,{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($,{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(Pn,{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(on,{className:"h-56 rounded-xl"},I))}):t.length===0?e.jsx(_e,{className:"border-dashed",children:e.jsxs(Oe,{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(Wr,{className:"h-7 w-7 text-muted-foreground"})}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:"No presentations yet"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Create your first seller presentation — it takes about two minutes."})]}),e.jsxs($,{onClick:T,disabled:r.isPending||!c,className:"gap-2",children:[e.jsx(sn,{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 D=I.property_address_line1||"No address yet",B=[I.city,I.state].filter(Boolean).join(", ");return e.jsxs(_e,{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(OTn,{path:I.property_photo_path,alt:`${D} property photo`})}),e.jsxs(Oe,{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:[D,B?` · ${B}`:""]})]}),e.jsxs(Hd,{children:[e.jsx(Gd,{asChild:!0,children:e.jsx($,{variant:"ghost",size:"icon",className:"h-8 w-8 shrink-0",children:e.jsx(cy,{className:"h-4 w-4"})})}),e.jsxs(Md,{align:"end",children:[e.jsxs(Na,{onClick:()=>s(`/apps/listing-presentation-studio/${I.id}`),children:[e.jsx(Ya,{className:"mr-2 h-4 w-4"})," Open"]}),e.jsxs(Na,{onClick:()=>{m(I),x(I.title)},children:[e.jsx(Wr,{className:"mr-2 h-4 w-4"})," Rename"]}),e.jsxs(Na,{onClick:()=>a.mutate(I),children:[e.jsx(Ca,{className:"mr-2 h-4 w-4"})," Duplicate"]}),e.jsxs(Na,{onClick:()=>M(I),children:[e.jsx(di,{className:"mr-2 h-4 w-4"})," Download PDF"]}),e.jsxs(Na,{onClick:()=>C(I),children:[e.jsx(nn,{className:"mr-2 h-4 w-4"})," Email to a contact"]}),e.jsx(S0,{}),e.jsxs(Na,{className:"text-destructive",onClick:()=>y(I),children:[e.jsx(Pn,{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 ",Hs(new Date(I.updated_at),"MMM d, yyyy")]}),I.last_generated_at?e.jsx($e,{variant:"secondary",className:"text-[10px]",children:"PDF ready"}):e.jsx($e,{variant:"outline",className:"text-[10px]",children:"Draft"})]}),e.jsxs($,{variant:"outline",size:"sm",className:"w-full gap-2",disabled:b===I.id,onClick:()=>M(I),children:[b===I.id?e.jsx(Ht,{className:"h-4 w-4 animate-spin"}):e.jsx(di,{className:"h-4 w-4"}),"Download PDF"]})]})]},I.id)})})]}),e.jsx(Os,{open:!!h,onOpenChange:I=>!I&&m(null),children:e.jsxs(Rs,{className:"sm:max-w-md",children:[e.jsx(Us,{children:e.jsx(zs,{children:"Rename presentation"})}),e.jsx(be,{value:p,onChange:I=>x(I.target.value),autoFocus:!0}),e.jsxs(kr,{children:[e.jsx($,{variant:"outline",onClick:()=>m(null),children:"Cancel"}),e.jsx($,{onClick:async()=>{h&&(await l.mutateAsync({id:h.id,title:p.trim()||"Untitled Presentation"}),m(null),ae.success("Renamed"))},children:"Save"})]})]})}),e.jsx(Ll,{open:!!g,onOpenChange:I=>!I&&y(null),children:e.jsxs(yl,{children:[e.jsxs(vl,{children:[e.jsx(_l,{children:"Delete this presentation?"}),e.jsx(wl,{children:"This permanently removes the presentation, its property photo, and the generated PDF."})]}),e.jsxs(bl,{children:[e.jsx(jl,{children:"Cancel"}),e.jsx(fl,{className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",onClick:()=>{g&&i.mutate(g),y(null)},children:"Delete"})]})]})}),e.jsx(C$t,{open:!!N,onOpenChange:I=>!I&&C(null),row:N,brand:c})]})};var nZ={};nZ.d=(s,t)=>{for(var n in t)nZ.o(t,n)&&!nZ.o(s,n)&&Object.defineProperty(s,n,{enumerable:!0,get:t[n]})};nZ.o=(s,t)=>Object.prototype.hasOwnProperty.call(s,t);var Wl=globalThis.pdfjsLib={};nZ.d(Wl,{AbortException:()=>wF,AnnotationEditorLayer:()=>sUe,AnnotationEditorParamsType:()=>zl,AnnotationEditorType:()=>hc,AnnotationEditorUIManager:()=>FO,AnnotationLayer:()=>RMn,AnnotationMode:()=>iE,ColorPicker:()=>P4e,DOMSVGFactory:()=>sXe,DrawLayer:()=>iUe,FeatureTest:()=>b1,GlobalWorkerOptions:()=>E3,ImageKind:()=>eNe,InvalidPDFException:()=>E$t,MissingPDFException:()=>_F,OPS:()=>Q2,OutputScale:()=>ZBe,PDFDataRangeTransport:()=>kUt,PDFDateString:()=>YZe,PDFWorker:()=>bB,PasswordResponses:()=>UTn,PermissionFlag:()=>$Tn,PixelsPerInch:()=>m6,RenderingCancelledException:()=>WZe,TextLayer:()=>uQ,UnexpectedResponseException:()=>NTe,Util:()=>ko,VerbosityLevel:()=>_Te,XfaLayer:()=>CUt,build:()=>xMn,createValidAbsoluteUrl:()=>GTn,fetchData:()=>STe,getDocument:()=>oMn,getFilenameFromUrl:()=>t6n,getPdfFilenameFromUrl:()=>s6n,getXfaPageViewport:()=>n6n,isDataScheme:()=>CTe,isPdfFile:()=>KZe,noContextMenu:()=>c2,normalizeUnicode:()=>QTn,setLayerDimensions:()=>OO,shadow:()=>xd,version:()=>fMn});const lv=typeof process=="object"&&process+""=="[object process]"&&!process.versions.nw&&!(process.versions.electron&&process.type&&process.type!=="browser"),A$t=[1,0,0,1,0,0],GBe=[.001,0,0,.001,0,0],zTn=1e7,cDe=1.35,O_={ANY:1,DISPLAY:2,PRINT:4,SAVE:8,ANNOTATIONS_FORMS:16,ANNOTATIONS_STORAGE:32,ANNOTATIONS_DISABLE:64,IS_EDITING:128,OPLIST:256},iE={DISABLE:0,ENABLE:1,ENABLE_FORMS:2,ENABLE_STORAGE:3},BTn="pdfjs_internal_editor_",hc={DISABLE:-1,NONE:0,FREETEXT:3,HIGHLIGHT:9,STAMP:13,INK:15},zl={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},$Tn={PRINT:4,MODIFY_CONTENTS:8,COPY:16,MODIFY_ANNOTATIONS:32,FILL_INTERACTIVE_FORMS:256,COPY_FOR_ACCESSIBILITY:512,ASSEMBLE:1024,PRINT_HIGH_QUALITY:2048},Wy={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},eNe={GRAYSCALE_1BPP:1,RGB_24BPP:2,RGBA_32BPP:3},eg={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},IG={SOLID:1,DASHED:2,BEVELED:3,INSET:4,UNDERLINE:5},_Te={ERRORS:0,WARNINGS:1,INFOS:5},Q2={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},UTn={NEED_PASSWORD:1,INCORRECT_PASSWORD:2};let wTe=_Te.WARNINGS;function qTn(s){Number.isInteger(s)&&(wTe=s)}function VTn(){return wTe}function jTe(s){wTe>=_Te.INFOS&&console.log(`Info: ${s}`)}function Pc(s){wTe>=_Te.WARNINGS&&console.log(`Warning: ${s}`)}function km(s){throw new Error(s)}function fg(s,t){s||km(t)}function HTn(s){switch(s==null?void 0:s.protocol){case"http:":case"https:":case"ftp:":case"mailto:":case"tel:":return!0;default:return!1}}function GTn(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=XTn(s)}catch{}}const r=t?new URL(s,t):new URL(s);if(HTn(r))return r}catch{}return null}function xd(s,t,n,r=!1){return Object.defineProperty(s,t,{value:n,enumerable:!r,configurable:!0,writable:!1}),n}const tM=function(){function t(n,r){this.message=n,this.name=r}return t.prototype=new Error,t.constructor=t,t}();class WBe extends tM{constructor(t,n){super(t,"PasswordException"),this.code=n}}class KBe extends tM{constructor(t,n){super(t,"UnknownErrorException"),this.details=n}}class E$t extends tM{constructor(t){super(t,"InvalidPDFException")}}class _F extends tM{constructor(t){super(t,"MissingPDFException")}}class NTe extends tM{constructor(t,n){super(t,"UnexpectedResponseException"),this.status=n}}class WTn extends tM{constructor(t){super(t,"FormatError")}}class wF extends tM{constructor(t){super(t,"AbortException")}}function T$t(s){(typeof s!="object"||(s==null?void 0:s.length)===void 0)&&km("Invalid argument for bytesToString");const t=s.length,n=8192;if(t>24&255,s>>16&255,s>>8&255,s&255)}function HZe(s){const t=Object.create(null);for(const[n,r]of s)t[n]=r;return t}function YTn(){const s=new Uint8Array(4);return s[0]=1,new Uint32Array(s.buffer,0,1)[0]===1}function ZTn(){try{return new Function(""),!0}catch{return!1}}class b1{static get isLittleEndian(){return xd(this,"isLittleEndian",YTn())}static get isEvalSupported(){return xd(this,"isEvalSupported",ZTn())}static get isOffscreenCanvasSupported(){return xd(this,"isOffscreenCanvasSupported",typeof OffscreenCanvas<"u")}static get platform(){return typeof navigator<"u"&&typeof(navigator==null?void 0:navigator.platform)=="string"?xd(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")}):xd(this,"platform",{isMac:!1,isWindows:!1,isFirefox:!1})}static get isCSSRoundSupported(){var t,n;return xd(this,"isCSSRoundSupported",(n=(t=globalThis.CSS)==null?void 0:t.supports)==null?void 0:n.call(t,"width: round(1.5px, 1px)"))}}const dDe=Array.from(Array(256).keys(),s=>s.toString(16).padStart(2,"0"));var tC,tNe,YBe;class ko{static makeHexColor(t,n,r){return`#${dDe[t]}${dDe[n]}${dDe[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)],Kt(this,tC,YBe).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),Kt(this,tC,YBe).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}}tC=new WeakSet,tNe=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,x=h*(h*(h*t+3*d*n)+3*m*r)+p*a,g=h*(h*(h*i+3*d*l)+3*m*o)+p*c;u[0]=Math.min(u[0],x),u[1]=Math.min(u[1],g),u[2]=Math.max(u[2],x),u[3]=Math.max(u[3],g)},YBe=function(t,n,r,a,i,l,o,c,d,u,h,m){if(Math.abs(d)<1e-12){Math.abs(u)>=1e-12&&Kt(this,tC,tNe).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 x=Math.sqrt(p),g=2*d;Kt(this,tC,tNe).call(this,t,n,r,a,i,l,o,c,(-u+x)/g,m),Kt(this,tC,tNe).call(this,t,n,r,a,i,l,o,c,(-u-x)/g,m)},rs(ko,tC);function XTn(s){return decodeURIComponent(escape(s))}let uDe=null,Vyt=null;function QTn(s){return uDe||(uDe=/([\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,Vyt=new Map([["ſt","ſt"]])),s.replaceAll(uDe,(t,n,r)=>n?n.normalize("NFKC"):Vyt.get(r))}function JTn(){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 T$t(s)}const GZe="pdfjs_internal_id_",A4={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 e6n(s){return Uint8Array.prototype.toBase64?s.toBase64():btoa(T$t(s))}const F4="http://www.w3.org/2000/svg",N8=class N8{};Lr(N8,"CSS",96),Lr(N8,"PDF",72),Lr(N8,"PDF_TO_CSS_UNITS",N8.CSS/N8.PDF);let m6=N8;async function STe(s,t="text"){if(DW(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 mte{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,x,g,y;d===0?(p=Math.abs(c-t[1])*n+a,x=Math.abs(o-t[0])*n+i,g=(t[3]-t[1])*n,y=(t[2]-t[0])*n):(p=Math.abs(o-t[0])*n+a,x=Math.abs(c-t[1])*n+i,g=(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,x-u*n*o-m*n*c],this.width=g,this.height=y}get rawDims(){const{viewBox:t}=this;return xd(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 mte({viewBox:this.viewBox.slice(),scale:t,rotation:n,offsetX:r,offsetY:a,dontFlip:i})}convertToViewportPoint(t,n){return ko.applyTransform([t,n],this.transform)}convertToViewportRectangle(t){const n=ko.applyTransform([t[0],t[1]],this.transform),r=ko.applyTransform([t[2],t[3]],this.transform);return[n[0],n[1],r[0],r[1]]}convertToPdfPoint(t,n){return ko.applyInverseTransform([t,n],this.transform)}}class WZe extends tM{constructor(t,n=0){super(t,"RenderingCancelledException"),this.extraDelay=n}}function CTe(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))}}SQ=new WeakMap,rs(YZe,SQ);function n6n(s,{scale:t=1,rotation:n=0}){const{width:r,height:a}=s.attributes.style,i=[0,0,parseInt(r),parseInt(a)];return new mte({viewBox:i,scale:t,rotation:n})}function ZZe(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):(Pc(`Not a valid color format: "${s}"`),[0,0,0])}function r6n(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,ZZe(r))}t.remove()}function kp(s){const{a:t,b:n,c:r,d:a,e:i,f:l}=s.getTransform();return[t,n,r,a,i,l]}function E4(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 OO(s,t,n=!1,r=!0){if(t instanceof mte){const{pageWidth:a,pageHeight:i}=t.rawDims,{style:l}=s,o=b1.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 ZBe{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 gE,oD,tN,lD,CQ,AQ,t3e,M$t,_1,L$t,P$t,sNe,I$t,QBe;const W4=class W4{constructor(t){rs(this,_1);rs(this,gE,null);rs(this,oD,null);rs(this,tN);rs(this,lD,null);rs(this,CQ,null);$t(this,tN,t),pe(W4,AQ)||$t(W4,AQ,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,gE,document.createElement("div"));t.classList.add("editToolbar","hidden"),t.setAttribute("role","toolbar");const n=pe(this,tN)._uiManager._signal;t.addEventListener("contextmenu",c2,{signal:n}),t.addEventListener("pointerdown",Kt(W4,t3e,M$t),{signal:n});const r=$t(this,lD,document.createElement("div"));r.className="buttons",t.append(r);const a=pe(this,tN).toolbarPosition;if(a){const{style:i}=t,l=pe(this,tN)._uiManager.direction==="ltr"?1-a[0]:a[0];i.insetInlineEnd=`${100*l}%`,i.top=`calc(${100*a[1]}% + var(--editor-toolbar-vert-offset))`}return Kt(this,_1,I$t).call(this),t}get div(){return pe(this,gE)}hide(){var t;pe(this,gE).classList.add("hidden"),(t=pe(this,oD))==null||t.hideDropdown()}show(){var t;pe(this,gE).classList.remove("hidden"),(t=pe(this,CQ))==null||t.shown()}async addAltText(t){const n=await t.render();Kt(this,_1,sNe).call(this,n),pe(this,lD).prepend(n,pe(this,_1,QBe)),$t(this,CQ,t)}addColorPicker(t){$t(this,oD,t);const n=t.renderButton();Kt(this,_1,sNe).call(this,n),pe(this,lD).prepend(n,pe(this,_1,QBe))}remove(){var t;pe(this,gE).remove(),(t=pe(this,oD))==null||t.destroy(),$t(this,oD,null)}};gE=new WeakMap,oD=new WeakMap,tN=new WeakMap,lD=new WeakMap,CQ=new WeakMap,AQ=new WeakMap,t3e=new WeakSet,M$t=function(t){t.stopPropagation()},_1=new WeakSet,L$t=function(t){pe(this,tN)._focusEventsAllowed=!1,t.preventDefault(),t.stopPropagation()},P$t=function(t){pe(this,tN)._focusEventsAllowed=!0,t.preventDefault(),t.stopPropagation()},sNe=function(t){const n=pe(this,tN)._uiManager._signal;t.addEventListener("focusin",Kt(this,_1,L$t).bind(this),{capture:!0,signal:n}),t.addEventListener("focusout",Kt(this,_1,P$t).bind(this),{capture:!0,signal:n}),t.addEventListener("contextmenu",c2,{signal:n})},I$t=function(){const{editorType:t,_uiManager:n}=pe(this,tN),r=document.createElement("button");r.className="delete",r.tabIndex=0,r.setAttribute("data-l10n-id",pe(W4,AQ)[t]),Kt(this,_1,sNe).call(this,r),r.addEventListener("click",a=>{n.delete()},{signal:n._signal}),pe(this,lD).append(r)},QBe=function(){const t=document.createElement("div");return t.className="divider",t},rs(W4,t3e),rs(W4,AQ,null);let XBe=W4;var EQ,cD,dD,y6,D$t,R$t,O$t;class a6n{constructor(t){rs(this,y6);rs(this,EQ,null);rs(this,cD,null);rs(this,dD);$t(this,dD,t)}show(t,n,r){const[a,i]=Kt(this,y6,R$t).call(this,n,r),{style:l}=pe(this,cD)||$t(this,cD,Kt(this,y6,D$t).call(this));t.append(pe(this,cD)),l.insetInlineEnd=`${100*a}%`,l.top=`calc(${100*i}% + var(--editor-toolbar-vert-offset))`}hide(){pe(this,cD).remove()}}EQ=new WeakMap,cD=new WeakMap,dD=new WeakMap,y6=new WeakSet,D$t=function(){const t=$t(this,cD,document.createElement("div"));t.className="editToolbar",t.setAttribute("role","toolbar"),t.addEventListener("contextmenu",c2,{signal:pe(this,dD)._signal});const n=$t(this,EQ,document.createElement("div"));return n.className="buttons",t.append(n),Kt(this,y6,O$t).call(this),t},R$t=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{pe(this,dD).highlightSelection("floating_button")},{signal:r}),pe(this,EQ).append(t)};function T4e(s,t,n){for(const r of n)t.addEventListener(r,s[r].bind(s))}function i6n(s){return Math.round(Math.min(255,Math.max(1,255*s))).toString(16).padStart(2,"0")}var s3e;class o6n{constructor(){rs(this,s3e,0)}get id(){return`${BTn}${Xg(this,s3e)._++}`}}s3e=new WeakMap;var BB,TQ,Zy,$B,nNe;const gQe=class gQe{constructor(){rs(this,$B);rs(this,BB,JTn());rs(this,TQ,0);rs(this,Zy,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 xd(this,"_isSVGFittingCanvas",i)}async getFromFile(t){const{lastModified:n,name:r,size:a,type:i}=t;return Kt(this,$B,nNe).call(this,`${n}_${r}_${a}_${i}`,t)}async getFromUrl(t){return Kt(this,$B,nNe).call(this,t,t)}async getFromBlob(t,n){const r=await n;return Kt(this,$B,nNe).call(this,t,r)}async getFromId(t){pe(this,Zy)||$t(this,Zy,new Map);const n=pe(this,Zy).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){pe(this,Zy)||$t(this,Zy,new Map);let r=pe(this,Zy).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_${pe(this,BB)}_${Xg(this,TQ)._++}`,refCounter:1,isSvg:!1},pe(this,Zy).set(t,r),pe(this,Zy).set(r.id,r),r}getSvgUrl(t){const n=pe(this,Zy).get(t);return n!=null&&n.isSvg?n.svgUrl:null}deleteId(t){var a;pe(this,Zy)||$t(this,Zy,new Map);const n=pe(this,Zy).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_${pe(this,BB)}_`)}};BB=new WeakMap,TQ=new WeakMap,Zy=new WeakMap,$B=new WeakSet,nNe=async function(t,n){pe(this,Zy)||$t(this,Zy,new Map);let r=pe(this,Zy).get(t);if(r===null)return null;if(r!=null&&r.bitmap)return r.refCounter+=1,r;try{r||(r={bitmap:null,id:`image_${pe(this,BB)}_${Xg(this,TQ)._++}`,refCounter:0,isSvg:!1});let a;if(typeof n=="string"?(r.url=n,a=await STe(n,"blob")):n instanceof File?a=r.file=n:n instanceof Blob&&(a=n),a.type==="image/svg+xml"){const i=gQe._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 pe(this,Zy).set(t,r),r&&pe(this,Zy).set(r.id,r),r};let JBe=gQe;var s0,yE,MQ,n0;class l6n{constructor(t=128){rs(this,s0,[]);rs(this,yE,!1);rs(this,MQ);rs(this,n0,-1);$t(this,MQ,t)}add({cmd:t,undo:n,post:r,mustExec:a,type:i=NaN,overwriteIfSameType:l=!1,keepUndo:o=!1}){if(a&&t(),pe(this,yE))return;const c={cmd:t,undo:n,post:r,type:i};if(pe(this,n0)===-1){pe(this,s0).length>0&&(pe(this,s0).length=0),$t(this,n0,0),pe(this,s0).push(c);return}if(l&&pe(this,s0)[pe(this,n0)].type===i){o&&(c.undo=pe(this,s0)[pe(this,n0)].undo),pe(this,s0)[pe(this,n0)]=c;return}const d=pe(this,n0)+1;d===pe(this,MQ)?pe(this,s0).splice(0,1):($t(this,n0,d),di===n[l]))return r3e._colorsMapping.get(r);return n}getHexCode(t){const n=this._colors.get(t);return n?ko.makeHexColor(...n):t}};Lr(r3e,"_colorsMapping",new Map([["CanvasText",[0,0,0]],["Canvas",[255,255,255]]]));let e$e=r3e;var UB,A_,ng,J0,qB,n3,VB,sN,vE,HB,uD,uS,nN,hD,LQ,PQ,GB,IQ,hS,bE,WB,_E,mS,a3e,wE,DQ,jE,mD,RQ,OQ,r0,zu,r3,pD,FQ,zQ,NE,pS,a3,BQ,fj,Ni,rNe,t$e,z$t,B$t,aNe,$$t,U$t,q$t,s$e,V$t,n$e,r$e,H$t,Gv,MA,G$t,W$t,a$e,K$t,RW,i$e;const lz=class lz{constructor(t,n,r,a,i,l,o,c,d,u,h){rs(this,Ni);rs(this,UB,new AbortController);rs(this,A_,null);rs(this,ng,new Map);rs(this,J0,new Map);rs(this,qB,null);rs(this,n3,null);rs(this,VB,null);rs(this,sN,new l6n);rs(this,vE,null);rs(this,HB,0);rs(this,uD,new Set);rs(this,uS,null);rs(this,nN,null);rs(this,hD,new Set);rs(this,LQ,!1);rs(this,PQ,!1);rs(this,GB,!1);rs(this,IQ,null);rs(this,hS,null);rs(this,bE,null);rs(this,WB,null);rs(this,_E,!1);rs(this,mS,null);rs(this,a3e,new o6n);rs(this,wE,!1);rs(this,DQ,!1);rs(this,jE,null);rs(this,mD,null);rs(this,RQ,null);rs(this,OQ,null);rs(this,r0,hc.NONE);rs(this,zu,new Set);rs(this,r3,null);rs(this,pD,null);rs(this,FQ,null);rs(this,zQ,{isEditing:!1,isEmpty:!0,hasSomethingToUndo:!1,hasSomethingToRedo:!1,hasSelectedEditor:!1,hasSelectedText:!1});rs(this,NE,[0,0]);rs(this,pS,null);rs(this,a3,null);rs(this,BQ,null);rs(this,fj,null);const m=this._signal=pe(this,UB).signal;$t(this,a3,t),$t(this,BQ,n),$t(this,qB,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}),Kt(this,Ni,$$t).call(this),Kt(this,Ni,H$t).call(this),Kt(this,Ni,s$e).call(this),$t(this,n3,i.annotationStorage),$t(this,IQ,i.filterFactory),$t(this,pD,l),$t(this,WB,o||null),$t(this,LQ,c),$t(this,PQ,d),$t(this,GB,u),$t(this,OQ,h||null),this.viewParameters={realScale:m6.PDF_TO_CSS_UNITS,rotation:0},this.isShiftKeyDown=!1}static get _keyboardManager(){const t=lz.prototype,n=l=>pe(l,a3).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 xd(this,"_keyboardManager",new pte([[["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)&&pe(l,a3).contains(o)&&!l.isEnterHandled}],[[" ","mac+ "],t.addNewEditorFromKeyboard,{checker:(l,{target:o})=>!(o instanceof HTMLButtonElement)&&pe(l,a3).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=pe(this,fj))==null||t.resolve(),$t(this,fj,null),(n=pe(this,UB))==null||n.abort(),$t(this,UB,null),this._signal=null;for(const i of pe(this,J0).values())i.destroy();pe(this,J0).clear(),pe(this,ng).clear(),pe(this,hD).clear(),$t(this,A_,null),pe(this,zu).clear(),pe(this,sN).destroy(),(r=pe(this,qB))==null||r.destroy(),(a=pe(this,mS))==null||a.hide(),$t(this,mS,null),pe(this,hS)&&(clearTimeout(pe(this,hS)),$t(this,hS,null)),pe(this,pS)&&(clearTimeout(pe(this,pS)),$t(this,pS,null))}combinedSignal(t){return AbortSignal.any([this._signal,t.signal])}get mlManager(){return pe(this,OQ)}get useNewAltTextFlow(){return pe(this,PQ)}get useNewAltTextWhenAddingImage(){return pe(this,GB)}get hcmFilter(){return xd(this,"hcmFilter",pe(this,pD)?pe(this,IQ).addHCMFilter(pe(this,pD).foreground,pe(this,pD).background):"none")}get direction(){return xd(this,"direction",getComputedStyle(pe(this,a3)).direction)}get highlightColors(){return xd(this,"highlightColors",pe(this,WB)?new Map(pe(this,WB).split(",").map(t=>t.split("=").map(n=>n.trim()))):null)}get highlightColorNames(){return xd(this,"highlightColorNames",this.highlightColors?new Map(Array.from(this.highlightColors,t=>t.reverse())):null)}setMainHighlightColorPicker(t){$t(this,RQ,t)}editAltText(t,n=!1){var r;(r=pe(this,qB))==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,GB,n);break}}onPageChanging({pageNumber:t}){$t(this,HB,t-1)}focusMainContainer(){pe(this,a3).focus()}findParent(t,n){for(const r of pe(this,J0).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){pe(this,BQ).classList.toggle("noUserSelect",t)}addShouldRescale(t){pe(this,hD).add(t)}removeShouldRescale(t){pe(this,hD).delete(t)}onScaleChanging({scale:t}){this.commitOrRemove(),this.viewParameters.realScale=t*m6.PDF_TO_CSS_UNITS;for(const n of pe(this,hD))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=Kt(this,Ni,rNe).call(this,n).closest(".textLayer"),u=this.getSelectionBoxes(d);if(!u)return;n.empty();const h=Kt(this,Ni,t$e).call(this,d),m=pe(this,r0)===hc.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(hc.HIGHLIGHT,p);return}p()}addToAnnotationStorage(t){!t.isEmpty()&&pe(this,n3)&&!pe(this,n3).has(t.id)&&pe(this,n3).setValue(t.id,t)}blur(){if(this.isShiftKeyDown=!1,pe(this,_E)&&($t(this,_E,!1),Kt(this,Ni,aNe).call(this,"main_toolbar")),!this.hasSelection)return;const{activeElement:t}=document;for(const n of pe(this,zu))if(n.div.contains(t)){$t(this,mD,[n,t]),n._focusEventsAllowed=!1;break}}focus(){if(!pe(this,mD))return;const[t,n]=pe(this,mD);$t(this,mD,null),n.addEventListener("focusin",()=>{t._focusEventsAllowed=!0},{once:!0,signal:this._signal}),n.focus()}addEditListeners(){Kt(this,Ni,s$e).call(this),Kt(this,Ni,n$e).call(this)}removeEditListeners(){Kt(this,Ni,V$t).call(this),Kt(this,Ni,r$e).call(this)}dragOver(t){for(const{type:n}of t.dataTransfer.items)for(const r of pe(this,nN))if(r.isHandlingMimeForPasting(n)){t.dataTransfer.dropEffect="copy",t.preventDefault();return}}drop(t){for(const n of t.dataTransfer.items)for(const r of pe(this,nN))if(r.isHandlingMimeForPasting(n.type)){r.paste(n,this.currentLayer),t.preventDefault();return}}copy(t){var r;if(t.preventDefault(),(r=pe(this,A_))==null||r.commitOrRemove(),!this.hasSelection)return;const n=[];for(const a of pe(this,zu)){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 pe(this,nN))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){Pc(`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)Kt(this,Ni,a$e).call(this,c);Kt(this,Ni,i$e).call(this,i)},o=()=>{for(const c of i)c.remove()};this.addCommands({cmd:l,undo:o,mustExec:!0})}catch(i){Pc(`paste: "${i.message}".`)}}keydown(t){!this.isShiftKeyDown&&t.key==="Shift"&&(this.isShiftKeyDown=!0),pe(this,r0)!==hc.NONE&&!this.isEditorHandlingKeyboard&&lz._keyboardManager.exec(this,t)}keyup(t){this.isShiftKeyDown&&t.key==="Shift"&&(this.isShiftKeyDown=!1,pe(this,_E)&&($t(this,_E,!1),Kt(this,Ni,aNe).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?(Kt(this,Ni,U$t).call(this),Kt(this,Ni,n$e).call(this),Kt(this,Ni,Gv).call(this,{isEditing:pe(this,r0)!==hc.NONE,isEmpty:Kt(this,Ni,RW).call(this),hasSomethingToUndo:pe(this,sN).hasSomethingToUndo(),hasSomethingToRedo:pe(this,sN).hasSomethingToRedo(),hasSelectedEditor:!1})):(Kt(this,Ni,q$t).call(this),Kt(this,Ni,r$e).call(this),Kt(this,Ni,Gv).call(this,{isEditing:!1}),this.disableUserSelect(!1))}registerEditorTypes(t){if(!pe(this,nN)){$t(this,nN,t);for(const n of pe(this,nN))Kt(this,Ni,MA).call(this,n.defaultPropertiesToUpdate)}}getId(){return pe(this,a3e).id}get currentLayer(){return pe(this,J0).get(pe(this,HB))}getLayer(t){return pe(this,J0).get(t)}get currentPageIndex(){return pe(this,HB)}addLayer(t){pe(this,J0).set(t.pageIndex,t),pe(this,wE)?t.enable():t.disable()}removeLayer(t){pe(this,J0).delete(t.pageIndex)}async updateMode(t,n=null,r=!1){if(pe(this,r0)!==t&&!(pe(this,fj)&&(await pe(this,fj).promise,!pe(this,fj)))){if($t(this,fj,Promise.withResolvers()),$t(this,r0,t),t===hc.NONE){this.setEditingState(!1),Kt(this,Ni,W$t).call(this),pe(this,fj).resolve();return}this.setEditingState(!0),await Kt(this,Ni,G$t).call(this),this.unselectAll();for(const a of pe(this,J0).values())a.updateMode(t);if(!n){r&&this.addNewEditorFromKeyboard(),pe(this,fj).resolve();return}for(const a of pe(this,ng).values())a.annotationElementId===n?(this.setSelected(a),a.enterInEditMode()):a.unselect();pe(this,fj).resolve()}}addNewEditorFromKeyboard(){this.currentLayer.canCreateNewEmptyEditor()&&this.currentLayer.addNewEditor()}updateToolbar(t){t!==pe(this,r0)&&this._eventBus.dispatch("switchannotationeditormode",{source:this,mode:t})}updateParams(t,n){var r;if(pe(this,nN)){switch(t){case zl.CREATE:this.currentLayer.addNewEditor();return;case zl.HIGHLIGHT_DEFAULT_COLOR:(r=pe(this,RQ))==null||r.updateColor(n);break;case zl.HIGHLIGHT_SHOW_ALL:this._eventBus.dispatch("reporttelemetry",{source:this,details:{type:"editing",data:{type:"highlight",action:"toggle_visibility"}}}),(pe(this,FQ)||$t(this,FQ,new Map)).set(t,n),this.showAllEditors("highlight",n);break}for(const a of pe(this,zu))a.updateParams(t,n);for(const a of pe(this,nN))a.updateDefaultParams(t,n)}}showAllEditors(t,n,r=!1){var i;for(const l of pe(this,ng).values())l.editorType===t&&l.show(n);(((i=pe(this,FQ))==null?void 0:i.get(zl.HIGHLIGHT_SHOW_ALL))??!0)!==n&&Kt(this,Ni,MA).call(this,[[zl.HIGHLIGHT_SHOW_ALL,n]])}enableWaiting(t=!1){if(pe(this,DQ)!==t){$t(this,DQ,t);for(const n of pe(this,J0).values())t?n.disableClick():n.enableClick(),n.div.classList.toggle("waiting",t)}}getEditors(t){const n=[];for(const r of pe(this,ng).values())r.pageIndex===t&&n.push(r);return n}getEditor(t){return pe(this,ng).get(t)}addEditor(t){pe(this,ng).set(t.id,t)}removeEditor(t){var n;t.div.contains(document.activeElement)&&(pe(this,hS)&&clearTimeout(pe(this,hS)),$t(this,hS,setTimeout(()=>{this.focusMainContainer(),$t(this,hS,null)},0))),pe(this,ng).delete(t.id),this.unselect(t),(!t.annotationElementId||!pe(this,uD).has(t.annotationElementId))&&((n=pe(this,n3))==null||n.remove(t.id))}addDeletedAnnotationElement(t){pe(this,uD).add(t.annotationElementId),this.addChangedExistingAnnotation(t),t.deleted=!0}isDeletedAnnotationElement(t){return pe(this,uD).has(t)}removeDeletedAnnotationElement(t){pe(this,uD).delete(t.annotationElementId),this.removeChangedExistingAnnotation(t),t.deleted=!1}setActiveEditor(t){pe(this,A_)!==t&&($t(this,A_,t),t&&Kt(this,Ni,MA).call(this,t.propertiesToUpdate))}updateUI(t){pe(this,Ni,K$t)===t&&Kt(this,Ni,MA).call(this,t.propertiesToUpdate)}toggleSelected(t){if(pe(this,zu).has(t)){pe(this,zu).delete(t),t.unselect(),Kt(this,Ni,Gv).call(this,{hasSelectedEditor:this.hasSelection});return}pe(this,zu).add(t),t.select(),Kt(this,Ni,MA).call(this,t.propertiesToUpdate),Kt(this,Ni,Gv).call(this,{hasSelectedEditor:!0})}setSelected(t){for(const n of pe(this,zu))n!==t&&n.unselect();pe(this,zu).clear(),pe(this,zu).add(t),t.select(),Kt(this,Ni,MA).call(this,t.propertiesToUpdate),Kt(this,Ni,Gv).call(this,{hasSelectedEditor:!0})}isSelected(t){return pe(this,zu).has(t)}get firstSelectedEditor(){return pe(this,zu).values().next().value}unselect(t){t.unselect(),pe(this,zu).delete(t),Kt(this,Ni,Gv).call(this,{hasSelectedEditor:this.hasSelection})}get hasSelection(){return pe(this,zu).size!==0}get isEnterHandled(){return pe(this,zu).size===1&&this.firstSelectedEditor.isEnterHandled}undo(){pe(this,sN).undo(),Kt(this,Ni,Gv).call(this,{hasSomethingToUndo:pe(this,sN).hasSomethingToUndo(),hasSomethingToRedo:!0,isEmpty:Kt(this,Ni,RW).call(this)})}redo(){pe(this,sN).redo(),Kt(this,Ni,Gv).call(this,{hasSomethingToUndo:!0,hasSomethingToRedo:pe(this,sN).hasSomethingToRedo(),isEmpty:Kt(this,Ni,RW).call(this)})}addCommands(t){pe(this,sN).add(t),Kt(this,Ni,Gv).call(this,{hasSomethingToUndo:!0,hasSomethingToRedo:!1,isEmpty:Kt(this,Ni,RW).call(this)})}delete(){if(this.commitOrRemove(),!this.hasSelection)return;const t=[...pe(this,zu)],n=()=>{for(const a of t)a.remove()},r=()=>{for(const a of t)Kt(this,Ni,a$e).call(this,a)};this.addCommands({cmd:n,undo:r,mustExec:!0})}commitOrRemove(){var t;(t=pe(this,A_))==null||t.commitOrRemove()}hasSomethingToControl(){return pe(this,A_)||this.hasSelection}selectAll(){for(const t of pe(this,zu))t.commit();Kt(this,Ni,i$e).call(this,pe(this,ng).values())}unselectAll(){if(!(pe(this,A_)&&(pe(this,A_).commitOrRemove(),pe(this,r0)!==hc.NONE))&&this.hasSelection){for(const t of pe(this,zu))t.unselect();pe(this,zu).clear(),Kt(this,Ni,Gv).call(this,{hasSelectedEditor:!1})}}translateSelectedEditors(t,n,r=!1){if(r||this.commitOrRemove(),!this.hasSelection)return;pe(this,NE)[0]+=t,pe(this,NE)[1]+=n;const[a,i]=pe(this,NE),l=[...pe(this,zu)],o=1e3;pe(this,pS)&&clearTimeout(pe(this,pS)),$t(this,pS,setTimeout(()=>{$t(this,pS,null),pe(this,NE)[0]=pe(this,NE)[1]=0,this.addCommands({cmd:()=>{for(const c of l)pe(this,ng).has(c.id)&&c.translateInPage(a,i)},undo:()=>{for(const c of l)pe(this,ng).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,uS,new Map);for(const t of pe(this,zu))pe(this,uS).set(t,{savedX:t.x,savedY:t.y,savedPageIndex:t.pageIndex,newX:0,newY:0,newPageIndex:-1})}}endDragSession(){if(!pe(this,uS))return!1;this.disableUserSelect(!1);const t=pe(this,uS);$t(this,uS,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(pe(this,ng).has(a.id)){const c=pe(this,J0).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(pe(this,uS))for(const r of pe(this,uS).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())||pe(this,zu).size===1&&this.firstSelectedEditor.shouldGetKeyboardEvents()}isActive(t){return pe(this,A_)===t}getActive(){return pe(this,A_)}getMode(){return pe(this,r0)}get imageManager(){return xd(this,"imageManager",new JBe)}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"&&Kt(this,Ni,aNe).call(this,"main_toolbar"))};window.addEventListener("pointerup",h,{signal:u}),window.addEventListener("blur",h,{signal:u})}},aNe=function(t=""){pe(this,r0)===hc.HIGHLIGHT?this.highlightSelection(t):pe(this,LQ)&&Kt(this,Ni,z$t).call(this)},$$t=function(){document.addEventListener("selectionchange",Kt(this,Ni,B$t).bind(this),{signal:this._signal})},U$t=function(){if(pe(this,bE))return;$t(this,bE,new AbortController);const t=this.combinedSignal(pe(this,bE));window.addEventListener("focus",this.focus.bind(this),{signal:t}),window.addEventListener("blur",this.blur.bind(this),{signal:t})},q$t=function(){var t;(t=pe(this,bE))==null||t.abort(),$t(this,bE,null)},s$e=function(){if(pe(this,jE))return;$t(this,jE,new AbortController);const t=this.combinedSignal(pe(this,jE));window.addEventListener("keydown",this.keydown.bind(this),{signal:t}),window.addEventListener("keyup",this.keyup.bind(this),{signal:t})},V$t=function(){var t;(t=pe(this,jE))==null||t.abort(),$t(this,jE,null)},n$e=function(){if(pe(this,vE))return;$t(this,vE,new AbortController);const t=this.combinedSignal(pe(this,vE));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})},r$e=function(){var t;(t=pe(this,vE))==null||t.abort(),$t(this,vE,null)},H$t=function(){const t=this._signal;document.addEventListener("dragover",this.dragOver.bind(this),{signal:t}),document.addEventListener("drop",this.drop.bind(this),{signal:t})},Gv=function(t){Object.entries(t).some(([r,a])=>pe(this,zQ)[r]!==a)&&(this._eventBus.dispatch("annotationeditorstateschanged",{source:this,details:Object.assign(pe(this,zQ),t)}),pe(this,r0)===hc.HIGHLIGHT&&t.hasSelectedEditor===!1&&Kt(this,Ni,MA).call(this,[[zl.HIGHLIGHT_FREE,!0]]))},MA=function(t){this._eventBus.dispatch("annotationeditorparamschanged",{source:this,details:t})},G$t=async function(){if(!pe(this,wE)){$t(this,wE,!0);const t=[];for(const n of pe(this,J0).values())t.push(n.enable());await Promise.all(t);for(const n of pe(this,ng).values())n.enable()}},W$t=function(){if(this.unselectAll(),pe(this,wE)){$t(this,wE,!1);for(const t of pe(this,J0).values())t.disable();for(const t of pe(this,ng).values())t.disable()}},a$e=function(t){const n=pe(this,J0).get(t.pageIndex);n?n.addOrRebuild(t):(this.addEditor(t),this.addToAnnotationStorage(t))},K$t=function(){let t=null;for(t of pe(this,zu));return t},RW=function(){if(pe(this,ng).size===0)return!0;if(pe(this,ng).size===1)for(const t of pe(this,ng).values())return t.isEmpty();return!1},i$e=function(t){for(const n of pe(this,zu))n.unselect();pe(this,zu).clear();for(const n of t)n.isEmpty()||(pe(this,zu).add(n),n.select());Kt(this,Ni,Gv).call(this,{hasSelectedEditor:this.hasSelection})},Lr(lz,"TRANSLATE_SMALL",1),Lr(lz,"TRANSLATE_BIG",10);let FO=lz;var a0,fS,rN,KB,xS,E_,YB,gS,db,i3,fD,yS,kE,EN,OW,iNe;const Kv=class Kv{constructor(t){rs(this,EN);rs(this,a0,null);rs(this,fS,!1);rs(this,rN,null);rs(this,KB,null);rs(this,xS,null);rs(this,E_,null);rs(this,YB,!1);rs(this,gS,null);rs(this,db,null);rs(this,i3,null);rs(this,fD,null);rs(this,yS,!1);$t(this,db,t),$t(this,yS,t._uiManager.useNewAltTextFlow),pe(Kv,kE)||$t(Kv,kE,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){Kv._l10n??(Kv._l10n=t)}async render(){const t=$t(this,rN,document.createElement("button"));t.className="altText",t.tabIndex="0";const n=$t(this,KB,document.createElement("span"));t.append(n),pe(this,yS)?(t.classList.add("new"),t.setAttribute("data-l10n-id",pe(Kv,kE).missing),n.setAttribute("data-l10n-id",pe(Kv,kE)["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=pe(this,db)._uiManager._signal;t.addEventListener("contextmenu",c2,{signal:r}),t.addEventListener("pointerdown",i=>i.stopPropagation(),{signal:r});const a=i=>{i.preventDefault(),pe(this,db)._uiManager.editAltText(pe(this,db)),pe(this,yS)&&pe(this,db)._reportTelemetry({action:"pdfjs.image.alt_text.image_status_label_clicked",data:{label:pe(this,EN,OW)}})};return t.addEventListener("click",a,{capture:!0,signal:r}),t.addEventListener("keydown",i=>{i.target===t&&i.key==="Enter"&&($t(this,YB,!0),a(i))},{signal:r}),await Kt(this,EN,iNe).call(this),t}finish(){pe(this,rN)&&(pe(this,rN).focus({focusVisible:pe(this,YB)}),$t(this,YB,!1))}isEmpty(){return pe(this,yS)?pe(this,a0)===null:!pe(this,a0)&&!pe(this,fS)}hasData(){return pe(this,yS)?pe(this,a0)!==null||!!pe(this,i3):this.isEmpty()}get guessedText(){return pe(this,i3)}async setGuessedText(t){pe(this,a0)===null&&($t(this,i3,t),$t(this,fD,await Kv._l10n.get("pdfjs-editor-new-alt-text-generated-alt-text-with-disclaimer",{generatedAltText:t})),Kt(this,EN,iNe).call(this))}toggleAltTextBadge(t=!1){var n;if(!pe(this,yS)||pe(this,a0)){(n=pe(this,gS))==null||n.remove(),$t(this,gS,null);return}if(!pe(this,gS)){const r=$t(this,gS,document.createElement("div"));r.className="noAltTextBadge",pe(this,db).div.append(r)}pe(this,gS).classList.toggle("hidden",!t)}serialize(t){let n=pe(this,a0);return!t&&pe(this,i3)===n&&(n=pe(this,fD)),{altText:n,decorative:pe(this,fS),guessedText:pe(this,i3),textWithDisclaimer:pe(this,fD)}}get data(){return{altText:pe(this,a0),decorative:pe(this,fS)}}set data({altText:t,decorative:n,guessedText:r,textWithDisclaimer:a,cancel:i=!1}){r&&($t(this,i3,r),$t(this,fD,a)),!(pe(this,a0)===t&&pe(this,fS)===n)&&(i||($t(this,a0,t),$t(this,fS,n)),Kt(this,EN,iNe).call(this))}toggle(t=!1){pe(this,rN)&&(!t&&pe(this,E_)&&(clearTimeout(pe(this,E_)),$t(this,E_,null)),pe(this,rN).disabled=!t)}shown(){pe(this,db)._reportTelemetry({action:"pdfjs.image.alt_text.image_status_label_displayed",data:{label:pe(this,EN,OW)}})}destroy(){var t,n;(t=pe(this,rN))==null||t.remove(),$t(this,rN,null),$t(this,KB,null),$t(this,xS,null),(n=pe(this,gS))==null||n.remove(),$t(this,gS,null)}};a0=new WeakMap,fS=new WeakMap,rN=new WeakMap,KB=new WeakMap,xS=new WeakMap,E_=new WeakMap,YB=new WeakMap,gS=new WeakMap,db=new WeakMap,i3=new WeakMap,fD=new WeakMap,yS=new WeakMap,kE=new WeakMap,EN=new WeakSet,OW=function(){return pe(this,a0)&&"added"||pe(this,a0)===null&&this.guessedText&&"review"||"missing"},iNe=async function(){var a,i,l;const t=pe(this,rN);if(!t)return;if(pe(this,yS)){if(t.classList.toggle("done",!!pe(this,a0)),t.setAttribute("data-l10n-id",pe(Kv,kE)[pe(this,EN,OW)]),(a=pe(this,KB))==null||a.setAttribute("data-l10n-id",pe(Kv,kE)[`${pe(this,EN,OW)}-label`]),!pe(this,a0)){(i=pe(this,xS))==null||i.remove();return}}else{if(!pe(this,a0)&&!pe(this,fS)){t.classList.remove("done"),(l=pe(this,xS))==null||l.remove();return}t.classList.add("done"),t.setAttribute("data-l10n-id","pdfjs-editor-alt-text-edit-button")}let n=pe(this,xS);if(!n){$t(this,xS,n=document.createElement("span")),n.className="tooltip",n.setAttribute("role","tooltip"),n.id=`alt-text-tooltip-${pe(this,db).id}`;const o=100,c=pe(this,db)._uiManager._signal;c.addEventListener("abort",()=>{clearTimeout(pe(this,E_)),$t(this,E_,null)},{once:!0}),t.addEventListener("mouseenter",()=>{$t(this,E_,setTimeout(()=>{$t(this,E_,null),pe(this,xS).classList.add("show"),pe(this,db)._reportTelemetry({action:"alt_text_tooltip"})},o))},{signal:c}),t.addEventListener("mouseleave",()=>{var d;pe(this,E_)&&(clearTimeout(pe(this,E_)),$t(this,E_,null)),(d=pe(this,xS))==null||d.classList.remove("show")},{signal:c})}pe(this,fS)?n.setAttribute("data-l10n-id","pdfjs-editor-alt-text-decorative-tooltip"):(n.removeAttribute("data-l10n-id"),n.textContent=pe(this,a0)),n.parentNode||t.append(n);const r=pe(this,db).getImageForAltText();r==null||r.setAttribute("aria-describedby",n.id)},rs(Kv,kE,null),Lr(Kv,"_l10n",null);let M4e=Kv;var xD,aN,jp,ZB,gD,ey,yD,SE,$Q,vD,CE,UQ,bD,o3,vS,XB,QB,xj,qQ,i3e,Nc,o$e,VQ,l$e,c$e,Y$t,Z$t,d$e,u$e,h$e,X$t,m$e,Q$t,J$t,eUt,p$e,FW;const Cu=class Cu{constructor(t){rs(this,Nc);rs(this,xD,null);rs(this,aN,null);rs(this,jp,null);rs(this,ZB,!1);rs(this,gD,!1);rs(this,ey,null);rs(this,yD,null);rs(this,SE,null);rs(this,$Q,"");rs(this,vD,!1);rs(this,CE,null);rs(this,UQ,!1);rs(this,bD,!1);rs(this,o3,!1);rs(this,vS,null);rs(this,XB,0);rs(this,QB,0);rs(this,xj,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);rs(this,qQ,!1);rs(this,i3e,Cu._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=Cu.prototype._resizeWithKeyboard,n=FO.TRANSLATE_SMALL,r=FO.TRANSLATE_BIG;return xd(this,"_resizerKeyboardManager",new pte([[["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"],Cu.prototype._stopResizingWithKeyboard]]))}get editorType(){return Object.getPrototypeOf(this).constructor._type}static get _defaultLineColor(){return xd(this,"_defaultLineColor",this._colorManager.getHexCode("CanvasText"))}static deleteAnnotationElement(t){const n=new c6n({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(Cu._l10n??(Cu._l10n=t),Cu._l10nResizer||(Cu._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"})),Cu._borderLineWidth!==-1)return;const r=getComputedStyle(document.documentElement);Cu._borderLineWidth=parseFloat(r.getPropertyValue("--outline-width"))||0}static updateDefaultParams(t,n){}static get defaultPropertiesToUpdate(){return[]}static isHandlingMimeForPasting(t){return!1}static paste(t,n){km("Not implemented")}get propertiesToUpdate(){return[]}get _isDraggable(){return pe(this,qQ)}set _isDraggable(t){var n;$t(this,qQ,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=pe(this,i3e)}setParent(t){t!==null?(this.pageIndex=t.pageIndex,this.pageDimensions=t.pageDimensions):Kt(this,Nc,FW).call(this),this.parent=t}focusin(t){this._focusEventsAllowed&&(pe(this,vD)?$t(this,vD,!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){Kt(this,Nc,o$e).call(this,this.parentDimensions,t,n)}translateInPage(t,n){pe(this,CE)||$t(this,CE,[this.x,this.y]),Kt(this,Nc,o$e).call(this,this.pageDimensions,t,n),this.div.scrollIntoView({block:"nearest"})}drag(t,n){pe(this,CE)||$t(this,CE,[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!!pe(this,CE)&&(pe(this,CE)[0]!==this.x||pe(this,CE)[1]!==this.y)}getBaseTranslation(){const[t,n]=this.parentDimensions,{_borderLineWidth:r}=Cu,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 Kt(r=Cu,VQ,l$e).call(r,t,n,this.parentRotation)}pageTranslationToScreen(t,n){var r;return Kt(r=Cu,VQ,l$e).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)}%`,pe(this,gD)||(this.div.style.height=`${(100*n/a).toFixed(2)}%`)}fixDims(){const{style:t}=this.div,{height:n,width:r}=t,a=r.endsWith("%"),i=!pe(this,gD)&&n.endsWith("%");if(a&&i)return;const[l,o]=this.parentDimensions;a||(t.width=`${(100*parseFloat(r)/l).toFixed(2)}%`),!pe(this,gD)&&!i&&(t.height=`${(100*parseFloat(n)/o).toFixed(2)}%`)}getInitialTranslation(){return[0,0]}altTextFinish(){var t;(t=pe(this,jp))==null||t.finish()}async addEditToolbar(){return this._editToolbar||pe(this,bD)?this._editToolbar:(this._editToolbar=new XBe(this),this.div.append(this._editToolbar.render()),pe(this,jp)&&await this._editToolbar.addAltText(pe(this,jp)),this._editToolbar)}removeEditToolbar(){var t;this._editToolbar&&(this._editToolbar.remove(),this._editToolbar=null,(t=pe(this,jp))==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(){pe(this,jp)||(M4e.initialize(Cu._l10n),$t(this,jp,new M4e(this)),pe(this,xD)&&(pe(this,jp).data=pe(this,xD),$t(this,xD,null)),await this.addEditToolbar())}get altTextData(){var t;return(t=pe(this,jp))==null?void 0:t.data}set altTextData(t){pe(this,jp)&&(pe(this,jp).data=t)}get guessedAltText(){var t;return(t=pe(this,jp))==null?void 0:t.guessedText}async setGuessedAltText(t){var n;await((n=pe(this,jp))==null?void 0:n.setGuessedText(t))}serializeAltText(t){var n;return(n=pe(this,jp))==null?void 0:n.serialize(t)}hasAltText(){return!!pe(this,jp)&&!pe(this,jp).isEmpty()}hasAltTextData(){var t;return((t=pe(this,jp))==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=pe(this,ZB)?-1:0,this._isVisible||this.div.classList.add("hidden"),this.setInForeground(),Kt(this,Nc,m$e).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),T4e(this,this.div,["pointerdown"]),this.div}pointerdown(t){const{isMac:n}=b1.platform;if(t.button!==0||t.ctrlKey&&n){t.preventDefault();return}if($t(this,vD,!0),this._isDraggable){Kt(this,Nc,X$t).call(this,t);return}Kt(this,Nc,h$e).call(this,t)}get isSelected(){return this._uiManager.isSelected(this)}moveInDOM(){pe(this,vS)&&clearTimeout(pe(this,vS)),$t(this,vS,setTimeout(()=>{var t;$t(this,vS,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,x=this.height*l;switch(r){case 0:return[h+d+o,l-m-u-x+c,h+d+p+o,l-m-u+c];case 90:return[h+u+o,l-m+d+c,h+u+x+o,l-m+d+p+c];case 180:return[h-d-p+o,l-m+u+c,h-d+o,l-m+u+x+c];case 270:return[h-u-x+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,bD,!0)}disableEditMode(){$t(this,bD,!1)}isInEditMode(){return pe(this,bD)}shouldGetKeyboardEvents(){return pe(this,o3)}needsToBeRebuilt(){return this.div&&!this.isAttachedToDOM}rebuild(){Kt(this,Nc,m$e).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){km("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,xD,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=pe(this,SE))==null||t.abort(),$t(this,SE,null),this.isEmpty()||this.commit(),this.parent?this.parent.remove(this):this._uiManager.removeEditor(this),pe(this,vS)&&(clearTimeout(pe(this,vS)),$t(this,vS,null)),Kt(this,Nc,FW).call(this),this.removeEditToolbar(),pe(this,xj)){for(const n of pe(this,xj).values())clearTimeout(n);$t(this,xj,null)}this.parent=null}get isResizable(){return!1}makeResizable(){this.isResizable&&(Kt(this,Nc,Y$t).call(this),pe(this,ey).classList.remove("hidden"),T4e(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,yD,{savedX:this.x,savedY:this.y,savedWidth:this.width,savedHeight:this.height});const n=pe(this,ey).children;if(!pe(this,aN)){$t(this,aN,Array.from(n));const l=Kt(this,Nc,Q$t).bind(this),o=Kt(this,Nc,J$t).bind(this),c=this._uiManager._signal;for(const d of pe(this,aN)){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",Kt(this,Nc,eUt).bind(this,u),{signal:c}),d.setAttribute("data-l10n-id",Cu._l10nResizer[u])}}const r=pe(this,aN)[0];let a=0;for(const l of n){if(l===r)break;a++}const i=(360-this.rotation+this.parentRotation)%360/90*(pe(this,aN).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=pe(this,jp))==null||r.toggleAltTextBadge(!1)}unselect(){var t,n,r,a,i;(t=pe(this,ey))==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=pe(this,jp))==null||i.toggleAltTextBadge(!0)}updateParams(t,n){}disableEditing(){}enableEditing(){}enterInEditMode(){}getImageForAltText(){return null}get contentDiv(){return this.div}get isEditing(){return pe(this,UQ)}set isEditing(t){$t(this,UQ,t),this.parent&&(t?(this.parent.setSelected(this),this.parent.setActiveEditor(this)):this.parent.setActiveEditor(null))}setAspectRatio(t,n){$t(this,gD,!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){pe(this,xj)||$t(this,xj,new Map);const{action:r}=t;let a=pe(this,xj).get(r);a&&clearTimeout(a),a=setTimeout(()=>{this._reportTelemetry(t),pe(this,xj).delete(r),pe(this,xj).size===0&&$t(this,xj,null)},Cu._telemetryTimeout),pe(this,xj).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,ZB,!1)}disable(){this.div&&(this.div.tabIndex=-1),$t(this,ZB,!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()}};xD=new WeakMap,aN=new WeakMap,jp=new WeakMap,ZB=new WeakMap,gD=new WeakMap,ey=new WeakMap,yD=new WeakMap,SE=new WeakMap,$Q=new WeakMap,vD=new WeakMap,CE=new WeakMap,UQ=new WeakMap,bD=new WeakMap,o3=new WeakMap,vS=new WeakMap,XB=new WeakMap,QB=new WeakMap,xj=new WeakMap,qQ=new WeakMap,i3e=new WeakMap,Nc=new WeakSet,o$e=function([t,n],r,a){[r,a]=this.screenToPageTranslation(r,a),this.x+=r/t,this.y+=a/n,this.fixAndSetPosition()},VQ=new WeakSet,l$e=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]}},c$e=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]}},Y$t=function(){if(pe(this,ey))return;$t(this,ey,document.createElement("div")),pe(this,ey).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");pe(this,ey).append(a),a.classList.add("resizer",r),a.setAttribute("data-resizer-name",r),a.addEventListener("pointerdown",Kt(this,Nc,Z$t).bind(this,r),{signal:n}),a.addEventListener("contextmenu",c2,{signal:n}),a.tabIndex=-1}this.div.prepend(pe(this,ey))},Z$t=function(t,n){var x;n.preventDefault();const{isMac:r}=b1.platform;if(n.button!==0||n.ctrlKey&&r)return;(x=pe(this,jp))==null||x.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",Kt(this,Nc,u$e).bind(this,t),{passive:!0,capture:!0,signal:l}),window.addEventListener("contextmenu",c2,{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 g;i.abort(),this.parent.togglePointerEvents(!0),(g=pe(this,jp))==null||g.toggle(!0),this._isDraggable=a,this.parent.div.style.cursor=h,this.div.style.cursor=m,Kt(this,Nc,d$e).call(this,o,c,d,u)};window.addEventListener("pointerup",p,{signal:l}),window.addEventListener("blur",p,{signal:l})},d$e=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})},u$e=function(t,n){const[r,a]=this.parentDimensions,i=this.x,l=this.y,o=this.width,c=this.height,d=Cu.MIN_SIZE/r,u=Cu.MIN_SIZE/a,h=J=>Math.round(J*1e4)/1e4,m=Kt(this,Nc,c$e).call(this,this.rotation),p=(J,ce)=>[m[0]*J+m[2]*ce,m[1]*J+m[3]*ce],x=Kt(this,Nc,c$e).call(this,360-this.rotation),g=(J,ce)=>[x[0]*J+x[2]*ce,x[1]*J+x[3]*ce];let y,b,v=!1,N=!1;switch(t){case"topLeft":v=!0,y=(J,ce)=>[0,0],b=(J,ce)=>[J,ce];break;case"topMiddle":y=(J,ce)=>[J/2,0],b=(J,ce)=>[J/2,ce];break;case"topRight":v=!0,y=(J,ce)=>[J,0],b=(J,ce)=>[0,ce];break;case"middleRight":N=!0,y=(J,ce)=>[J,ce/2],b=(J,ce)=>[0,ce/2];break;case"bottomRight":v=!0,y=(J,ce)=>[J,ce],b=(J,ce)=>[0,0];break;case"bottomMiddle":y=(J,ce)=>[J/2,ce],b=(J,ce)=>[J/2,0];break;case"bottomLeft":v=!0,y=(J,ce)=>[0,ce],b=(J,ce)=>[J,0];break;case"middleLeft":N=!0,y=(J,ce)=>[0,ce/2],b=(J,ce)=>[J,ce/2];break}const C=y(o,c),A=b(o,c);let T=p(...A);const P=h(i+T[0]),M=h(l+T[1]);let I=1,D=1,[B,q]=this.screenToPageTranslation(n.movementX,n.movementY);if([B,q]=g(B/r,q/a),v){const J=Math.hypot(o,c);I=D=Math.max(Math.min(Math.hypot(A[0]-C[0]-B,A[1]-C[1]-q)/J,1/o,1/c),d/o,u/c)}else N?I=Math.max(d,Math.min(1,Math.abs(A[0]-C[0]-B)))/o:D=Math.max(u,Math.min(1,Math.abs(A[1]-C[1]-q)))/c;const W=h(o*I),V=h(c*D);T=p(...b(W,V));const K=P-T[0],Q=M-T[1];this.width=W,this.height=V,this.x=K,this.y=Q,this.setDims(r*W,a*V),this.fixAndSetPosition()},h$e=function(t){const{isMac:n}=b1.platform;t.ctrlKey&&!n||t.shiftKey||t.metaKey&&n?this.parent.toggleSelected(this):this.parent.setSelected(this)},X$t=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,XB,t.clientX),$t(this,QB,t.clientY);const l=o=>{const{clientX:c,clientY:d}=o,[u,h]=this.screenToPageTranslation(c-pe(this,XB),d-pe(this,QB));$t(this,XB,c),$t(this,QB,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,vD,!1),this._uiManager.endDragSession()||Kt(this,Nc,h$e).call(this,t)};window.addEventListener("pointerup",i,{signal:a}),window.addEventListener("blur",i,{signal:a})},m$e=function(){if(pe(this,SE)||!this.div)return;$t(this,SE,new AbortController);const t=this._uiManager.combinedSignal(pe(this,SE));this.div.addEventListener("focusin",this.focusin.bind(this),{signal:t}),this.div.addEventListener("focusout",this.focusout.bind(this),{signal:t})},Q$t=function(t){Cu._resizerKeyboardManager.exec(this,t)},J$t=function(t){var n;pe(this,o3)&&((n=t.relatedTarget)==null?void 0:n.parentNode)!==pe(this,ey)&&Kt(this,Nc,FW).call(this)},eUt=function(t){$t(this,$Q,pe(this,o3)?t:"")},p$e=function(t){if(pe(this,aN))for(const n of pe(this,aN))n.tabIndex=t},FW=function(){if($t(this,o3,!1),Kt(this,Nc,p$e).call(this,-1),pe(this,yD)){const{savedX:t,savedY:n,savedWidth:r,savedHeight:a}=pe(this,yD);Kt(this,Nc,d$e).call(this,t,n,r,a),$t(this,yD,null)}},rs(Cu,VQ),Lr(Cu,"_l10n",null),Lr(Cu,"_l10nResizer",null),Lr(Cu,"_borderLineWidth",-1),Lr(Cu,"_colorManager",new e$e),Lr(Cu,"_zIndex",1),Lr(Cu,"_telemetryTimeout",1e3);let Vu=Cu;class c6n extends Vu{constructor(t){super(t),this.annotationElementId=t.annotationElementId,this.deleted=!0}serialize(){return this.serializeDeleted()}}const Wyt=3285377520,lj=4294901760,qk=65535;class tUt{constructor(t){this.h1=t?t&4294967295:Wyt,this.h2=t?t&4294967295:Wyt}update(t){let n,r;if(typeof t=="string"){n=new Uint8Array(t.length*2),r=0;for(let g=0,y=t.length;g>>8,n[r++]=b&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&qk,x=m&qk;for(let g=0;g>>17,o=o*m&lj|o*x&qk,d^=o,d=d<<13|d>>>19,d=d*5+3864292196):(c=l[g],c=c*h&lj|c*p&qk,c=c<<15|c>>>17,c=c*m&lj|c*x&qk,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&lj|o*p&qk,o=o<<15|o>>>17,o=o*m&lj|o*x&qk,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&lj|t*36045&qk,n=n*4283543511&lj|((n<<16|t>>>16)*2950163797&lj)>>>16,t^=n>>>1,t=t*444984403&lj|t*60499&qk,n=n*3301882366&lj|((n<<16|t>>>16)*3120437893&lj)>>>16,t^=n>>>1,(t>>>0).toString(16).padStart(8,"0")+(n>>>0).toString(16).padStart(8,"0")}}const f$e=Object.freeze({map:null,hash:"",transfer:void 0});var _D,wD,i0,o3e,sUt;class XZe{constructor(){rs(this,o3e);rs(this,_D,!1);rs(this,wD,null);rs(this,i0,new Map);this.onSetModified=null,this.onResetModified=null,this.onAnnotationEditor=null}getValue(t,n){const r=pe(this,i0).get(t);return r===void 0?n:Object.assign(n,r)}getRawValue(t){return pe(this,i0).get(t)}remove(t){if(pe(this,i0).delete(t),pe(this,i0).size===0&&this.resetModified(),typeof this.onAnnotationEditor=="function"){for(const n of pe(this,i0).values())if(n instanceof Vu)return;this.onAnnotationEditor(null)}}setValue(t,n){const r=pe(this,i0).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,pe(this,i0).set(t,n);a&&Kt(this,o3e,sUt).call(this),n instanceof Vu&&typeof this.onAnnotationEditor=="function"&&this.onAnnotationEditor(n.constructor._type)}has(t){return pe(this,i0).has(t)}getAll(){return pe(this,i0).size>0?HZe(pe(this,i0)):null}setAll(t){for(const[n,r]of Object.entries(t))this.setValue(n,r)}get size(){return pe(this,i0).size}resetModified(){pe(this,_D)&&($t(this,_D,!1),typeof this.onResetModified=="function"&&this.onResetModified())}get print(){return new nUt(this)}get serializable(){if(pe(this,i0).size===0)return f$e;const t=new Map,n=new tUt,r=[],a=Object.create(null);let i=!1;for(const[l,o]of pe(this,i0)){const c=o instanceof Vu?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}:f$e}get editorStats(){let t=null;const n=new Map;for(const r of pe(this,i0).values()){if(!(r instanceof Vu))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,wD,null)}get modifiedIds(){if(pe(this,wD))return pe(this,wD);const t=[];for(const n of pe(this,i0).values())!(n instanceof Vu)||!n.annotationElementId||!n.serialize()||t.push(n.annotationElementId);return $t(this,wD,{ids:new Set(t),hash:t.join(",")})}}_D=new WeakMap,wD=new WeakMap,i0=new WeakMap,o3e=new WeakSet,sUt=function(){pe(this,_D)||($t(this,_D,!0),typeof this.onSetModified=="function"&&this.onSetModified())};var HQ;class nUt extends XZe{constructor(n){super();rs(this,HQ);const{map:r,hash:a,transfer:i}=n.serializable,l=structuredClone(r,i?{transfer:i}:null);$t(this,HQ,{map:l,hash:a,transfer:i})}get print(){km("Should not call PrintAnnotationStorage.print")}get serializable(){return pe(this,HQ)}get modifiedIds(){return xd(this,"modifiedIds",{ids:new Set,hash:""})}}HQ=new WeakMap;var JB;class d6n{constructor({ownerDocument:t=globalThis.document,styleElement:n=null}){rs(this,JB,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(),pe(this,JB).clear(),this.styleElement&&(this.styleElement.remove(),this.styleElement=null)}async loadSystemFont({systemFontInfo:t,_inspectFont:n}){if(!(!t||pe(this,JB).has(t.loadedName))){if(fg(!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(),pe(this,JB).add(r),n==null||n(t)}catch{Pc(`Cannot load system font: ${t.baseFontName}, installing it could help to improve PDF rendering.`),this.removeNativeFontFace(l)}return}km("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 Pc(`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 xd(this,"isFontLoadingAPISupported",t)}get isSyncFontLoadingSupported(){let t=!1;return(lv||typeof navigator<"u"&&typeof(navigator==null?void 0:navigator.userAgent)=="string"&&/Mozilla\/5.0.*?rv:\d+.*? Gecko/.test(navigator.userAgent))&&(t=!0),xd(this,"isSyncFontLoadingSupported",t)}_queueLoadingCallback(t){function n(){for(fg(!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 xd(this,"_loadTestFont",t)}_prepareFontLoadEvent(t,n){function r(C,A){return C.charCodeAt(A)<<24|C.charCodeAt(A+1)<<16|C.charCodeAt(A+2)<<8|C.charCodeAt(A+3)&255}function a(C,A,T,P){const M=C.substring(0,A),I=C.substring(A+T);return M+P+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(C,A){if(++d>30){Pc("Load test font never loaded."),A();return}if(c.font="30px "+C,c.fillText(".",0,20),c.getImageData(0,0,1,1).data[3]>0){A();return}setTimeout(u.bind(null,C,A))}const h=`lt${Date.now()}${this.loadTestFontId++}`;let m=this._loadTestFont;m=a(m,976,h.length,h);const x=16,g=1482184792;let y=r(m,x);for(i=0,l=h.length-3;i{N.remove(),n.complete()})}}JB=new WeakMap;class u6n{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,${e6n(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){Pc(`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 A4.MOVE_TO:{const[o,c]=r.slice(i,i+2);a.push(d=>d.moveTo(o,c)),i+=2}break;case A4.LINE_TO:{const[o,c]=r.slice(i,i+2);a.push(d=>d.lineTo(o,c)),i+=2}break;case A4.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 A4.RESTORE:a.push(o=>o.restore());break;case A4.SAVE:a.push(o=>o.save());break;case A4.SCALE:fg(a.length===2,"Scale command is only valid at the third position.");break;case A4.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 A4.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){km("Abstract method `_fetch` called.")}}class iUt extends aUt{async _fetch(t){const n=await STe(t,this.isCompressed?"arraybuffer":"text");return n instanceof ArrayBuffer?new Uint8Array(n):kTe(n)}}class oUt{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 jD,ND,bS,l3,Xy,l3e,kD,qi,Ky,y9,v9,oNe,b9,lUt,x$e,_9,zW,BW,g$e,$W;class m6n extends oUt{constructor({docId:n,ownerDocument:r=globalThis.document}){super();rs(this,qi);rs(this,jD);rs(this,ND);rs(this,bS);rs(this,l3);rs(this,Xy);rs(this,l3e);rs(this,kD,0);$t(this,l3,n),$t(this,Xy,r)}addFilter(n){if(!n)return"none";let r=pe(this,qi,Ky).get(n);if(r)return r;const[a,i,l]=Kt(this,qi,oNe).call(this,n),o=n.length===1?a:`${a}${i}${l}`;if(r=pe(this,qi,Ky).get(o),r)return pe(this,qi,Ky).set(n,r),r;const c=`g_${pe(this,l3)}_transfer_map_${Xg(this,kD)._++}`,d=Kt(this,qi,b9).call(this,c);pe(this,qi,Ky).set(n,d),pe(this,qi,Ky).set(o,d);const u=Kt(this,qi,_9).call(this,c);return Kt(this,qi,BW).call(this,a,i,l,u),d}addHCMFilter(n,r){var x;const a=`${n}-${r}`,i="base";let l=pe(this,qi,y9).get(i);if((l==null?void 0:l.key)===a||(l?((x=l.filter)==null||x.remove(),l.key=a,l.url="none",l.filter=null):(l={key:a,url:"none",filter:null},pe(this,qi,y9).set(i,l)),!n||!r))return l.url;const o=Kt(this,qi,$W).call(this,n);n=ko.makeHexColor(...o);const c=Kt(this,qi,$W).call(this,r);if(r=ko.makeHexColor(...c),pe(this,qi,v9).style.color="",n==="#000000"&&r==="#ffffff"||n===r)return l.url;const d=new Array(256);for(let g=0;g<=255;g++){const y=g/255;d[g]=y<=.03928?y/12.92:((y+.055)/1.055)**2.4}const u=d.join(","),h=`g_${pe(this,l3)}_hcm_filter`,m=l.filter=Kt(this,qi,_9).call(this,h);Kt(this,qi,BW).call(this,u,u,u,m),Kt(this,qi,x$e).call(this,m);const p=(g,y)=>{const b=o[g]/255,v=c[g]/255,N=new Array(y+1);for(let C=0;C<=y;C++)N[C]=b+C/y*(v-b);return N.join(",")};return Kt(this,qi,BW).call(this,p(0,5),p(1,5),p(2,5),m),l.url=Kt(this,qi,b9).call(this,h),l.url}addAlphaFilter(n){let r=pe(this,qi,Ky).get(n);if(r)return r;const[a]=Kt(this,qi,oNe).call(this,[n]),i=`alpha_${a}`;if(r=pe(this,qi,Ky).get(i),r)return pe(this,qi,Ky).set(n,r),r;const l=`g_${pe(this,l3)}_alpha_map_${Xg(this,kD)._++}`,o=Kt(this,qi,b9).call(this,l);pe(this,qi,Ky).set(n,o),pe(this,qi,Ky).set(i,o);const c=Kt(this,qi,_9).call(this,l);return Kt(this,qi,g$e).call(this,a,c),o}addLuminosityFilter(n){let r=pe(this,qi,Ky).get(n||"luminosity");if(r)return r;let a,i;if(n?([a]=Kt(this,qi,oNe).call(this,[n]),i=`luminosity_${a}`):i="luminosity",r=pe(this,qi,Ky).get(i),r)return pe(this,qi,Ky).set(n,r),r;const l=`g_${pe(this,l3)}_luminosity_map_${Xg(this,kD)._++}`,o=Kt(this,qi,b9).call(this,l);pe(this,qi,Ky).set(n,o),pe(this,qi,Ky).set(i,o);const c=Kt(this,qi,_9).call(this,l);return Kt(this,qi,lUt).call(this,c),n&&Kt(this,qi,g$e).call(this,a,c),o}addHighlightHCMFilter(n,r,a,i,l){var v;const o=`${r}-${a}-${i}-${l}`;let c=pe(this,qi,y9).get(n);if((c==null?void 0:c.key)===o||(c?((v=c.filter)==null||v.remove(),c.key=o,c.url="none",c.filter=null):(c={key:o,url:"none",filter:null},pe(this,qi,y9).set(n,c)),!r||!a))return c.url;const[d,u]=[r,a].map(Kt(this,qi,$W).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,x]=[i,l].map(Kt(this,qi,$W).bind(this));m{const T=new Array(256),P=(m-h)/A,M=N/255,I=(C-N)/(255*A);let D=0;for(let B=0;B<=A;B++){const q=Math.round(h+B*P),W=M+B*I;for(let V=D;V<=q;V++)T[V]=W;D=q+1}for(let B=D;B<256;B++)T[B]=T[D-1];return T.join(",")},y=`g_${pe(this,l3)}_hcm_${n}_filter`,b=c.filter=Kt(this,qi,_9).call(this,y);return Kt(this,qi,x$e).call(this,b),Kt(this,qi,BW).call(this,g(p[0],x[0],5),g(p[1],x[1],5),g(p[2],x[2],5),b),c.url=Kt(this,qi,b9).call(this,y),c.url}destroy(n=!1){n&&pe(this,qi,y9).size!==0||(pe(this,bS)&&(pe(this,bS).parentNode.parentNode.remove(),$t(this,bS,null)),pe(this,ND)&&(pe(this,ND).clear(),$t(this,ND,null)),$t(this,kD,0))}}jD=new WeakMap,ND=new WeakMap,bS=new WeakMap,l3=new WeakMap,Xy=new WeakMap,l3e=new WeakMap,kD=new WeakMap,qi=new WeakSet,Ky=function(){return pe(this,ND)||$t(this,ND,new Map)},y9=function(){return pe(this,l3e)||$t(this,l3e,new Map)},v9=function(){if(!pe(this,bS)){const n=pe(this,Xy).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=pe(this,Xy).createElementNS(F4,"svg");a.setAttribute("width",0),a.setAttribute("height",0),$t(this,bS,pe(this,Xy).createElementNS(F4,"defs")),n.append(a),a.append(pe(this,bS)),pe(this,Xy).body.append(n)}return pe(this,bS)},oNe=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(",")]},b9=function(n){if(pe(this,jD)===void 0){$t(this,jD,"");const r=pe(this,Xy).URL;r!==pe(this,Xy).baseURI&&(CTe(r)?Pc('#createUrl: ignore "data:"-URL for performance reasons.'):$t(this,jD,r.split("#",1)[0]))}return`url(${pe(this,jD)}#${n})`},lUt=function(n){const r=pe(this,Xy).createElementNS(F4,"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)},x$e=function(n){const r=pe(this,Xy).createElementNS(F4,"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)},_9=function(n){const r=pe(this,Xy).createElementNS(F4,"filter");return r.setAttribute("color-interpolation-filters","sRGB"),r.setAttribute("id",n),pe(this,qi,v9).append(r),r},zW=function(n,r,a){const i=pe(this,Xy).createElementNS(F4,r);i.setAttribute("type","discrete"),i.setAttribute("tableValues",a),n.append(i)},BW=function(n,r,a,i){const l=pe(this,Xy).createElementNS(F4,"feComponentTransfer");i.append(l),Kt(this,qi,zW).call(this,l,"feFuncR",n),Kt(this,qi,zW).call(this,l,"feFuncG",r),Kt(this,qi,zW).call(this,l,"feFuncB",a)},g$e=function(n,r){const a=pe(this,Xy).createElementNS(F4,"feComponentTransfer");r.append(a),Kt(this,qi,zW).call(this,a,"feFuncA",n)},$W=function(n){return pe(this,qi,v9).style.color=n,ZZe(getComputedStyle(pe(this,qi,v9)).getPropertyValue("color"))};class cUt{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){km("Abstract method `_fetch` called.")}}class dUt extends cUt{async _fetch(t){const n=await STe(t,"arraybuffer");return new Uint8Array(n)}}if(lv){var y$e=Promise.withResolvers(),rZ=null;(async()=>{const t=await mi(()=>import("./__vite-browser-external-BIHI7g3E.js"),[]),n=await mi(()=>import("./__vite-browser-external-BIHI7g3E.js"),[]),r=await mi(()=>import("./__vite-browser-external-BIHI7g3E.js"),[]),a=await mi(()=>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=>{rZ=t,y$e.resolve()},t=>{Pc(`loadPackages: ${t}`),rZ=new Map,y$e.resolve()})}class p6{static get promise(){return y$e.promise}static get(t){return rZ==null?void 0:rZ.get(t)}}async function uUt(s){const n=await p6.get("fs").promises.readFile(s);return new Uint8Array(n)}class p6n extends oUt{}class f6n extends rUt{_createCanvas(t,n){return p6.get("canvas").createCanvas(t,n)}}class x6n extends aUt{async _fetch(t){return uUt(t)}}class g6n extends cUt{async _fetch(t){return uUt(t)}}const s1={FILL:"Fill",STROKE:"Stroke",SHADING:"Shading"};function v$e(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 QZe{getPattern(){km("Abstract method `getPattern` called.")}}class y6n extends QZe{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===s1.STROKE||a===s1.FILL){const l=n.current.getClippedPathBoundingBox(a,kp(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=ko.transform(r,[1,0,0,1,l[0],l[1]]),u.transform(...n.baseTransform),this.matrix&&u.transform(...this.matrix),v$e(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 v$e(t,this._bbox),i=this._createGradient(t);return i}}function hDe(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,x=(c[n+1]+t.offsetY)*t.scaleY,g=(c[r]+t.offsetX)*t.scaleX,y=(c[r+1]+t.offsetY)*t.scaleY,b=(c[a]+t.offsetX)*t.scaleX,v=(c[a+1]+t.offsetY)*t.scaleY;if(x>=v)return;const N=d[i],C=d[i+1],A=d[i+2],T=d[l],P=d[l+1],M=d[l+2],I=d[o],D=d[o+1],B=d[o+2],q=Math.round(x),W=Math.round(v);let V,K,Q,J,ce,ue,ne,ee;for(let le=q;le<=W;le++){if(lev?je=1:y===v?je=0:je=(y-le)/(y-v),V=g-(g-b)*je,K=T-(T-I)*je,Q=P-(P-D)*je,J=M-(M-B)*je}let he;lev?he=1:he=(x-le)/(x-v),ce=p-(p-b)*he,ue=N-(N-I)*he,ne=C-(C-D)*he,ee=A-(A-B)*he;const ve=Math.round(Math.min(V,ce)),ge=Math.round(Math.max(V,ce));let fe=h*le+ve*4;for(let je=ve;je<=ge;je++)he=(V-je)/(V-ce),he<0?he=0:he>1&&(he=1),u[fe++]=K-(K-ue)*he|0,u[fe++]=Q-(Q-ne)*he|0,u[fe++]=J-(J-ee)*he|0,u[fe++]=255}}function v6n(s,t,n){const r=t.coords,a=t.colors;let i,l;switch(t.type){case"lattice":const o=t.verticesPerRow,c=Math.floor(r.length/o)-1,d=o-1;for(i=0;i=D?C=c:T=!0,I>=B?A=d:P=!0;const q=this.getSizeAndScale(C,this.ctx.canvas.width,v),W=this.getSizeAndScale(A,this.ctx.canvas.height,N),V=t.cachedCanvases.getCanvas("pattern",q.size,W.size),K=V.context,Q=o.createCanvasGraphics(K);if(Q.groupLevel=t.groupLevel,this.setFillAndStrokeStyleToContext(Q,a,l),K.translate(-q.scale*u,-W.scale*h),Q.transform(q.scale,0,0,W.scale,0,0),K.save(),this.clipBbox(Q,u,h,m,p),Q.baseTransform=kp(Q.ctx),Q.executeOperatorList(r),Q.endDrawing(),K.restore(),T||P){const J=V.canvas;T&&(C=c),P&&(A=d);const ce=this.getSizeAndScale(C,this.ctx.canvas.width,v),ue=this.getSizeAndScale(A,this.ctx.canvas.height,N),ne=ce.size,ee=ue.size,le=t.cachedCanvases.getCanvas("pattern-workaround",ne,ee),he=le.context,ve=T?Math.floor(x/c):0,ge=P?Math.floor(g/d):0;for(let fe=0;fe<=ve;fe++)for(let je=0;je<=ge;je++)he.drawImage(J,ne*fe,ee*je,ne,ee,0,0,ne,ee);return{canvas:le.canvas,scaleX:ce.scale,scaleY:ue.scale,offsetX:u,offsetY:h}}return{canvas:V.canvas,scaleX:q.scale,scaleY:W.scale,offsetX:u,offsetY:h}}getSizeAndScale(t,n,r){const a=Math.max(c3e.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(kp(t.ctx),[n,r,a,i]),t.clip(),t.endPath()}setFillAndStrokeStyleToContext(t,n,r){const a=t.ctx,i=t.current;switch(n){case Kyt.COLORED:const l=this.ctx;a.fillStyle=l.fillStyle,a.strokeStyle=l.strokeStyle,i.fillColor=l.fillStyle,i.strokeColor=l.strokeStyle;break;case Kyt.UNCOLORED:const o=ko.makeHexColor(r[0],r[1],r[2]);a.fillStyle=o,a.strokeStyle=o,i.fillColor=o,i.strokeColor=o;break;default:throw new WTn(`Unsupported paint type: ${n}`)}}getPattern(t,n,r,a){let i=r;a!==s1.SHADING&&(i=ko.transform(i,n.baseTransform),this.matrix&&(i=ko.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(c3e,"MAX_PATTERN_SIZE",3e3);let b$e=c3e;function j6n({src:s,srcPos:t=0,dest:n,width:r,height:a,nonBlackColor:i=4294967295,inverseDecode:l=!1}){const o=b1.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 x=0;x{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 S6n{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 lae(s,t,n,r,a,i,l,o,c,d){const[u,h,m,p,x,g]=kp(s);if(h===0&&m===0){const v=l*u+x,N=Math.round(v),C=o*p+g,A=Math.round(C),T=(l+c)*u+x,P=Math.abs(Math.round(T)-N)||1,M=(o+d)*p+g,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,P,I),s.setTransform(u,h,m,p,x,g),[P,I]}if(u===0&&p===0){const v=o*m+x,N=Math.round(v),C=l*h+g,A=Math.round(C),T=(o+d)*m+x,P=Math.abs(Math.round(T)-N)||1,M=(l+c)*h+g,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,P),s.setTransform(u,h,m,p,x,g),[I,P]}s.drawImage(t,n,r,a,i,l,o,c,d);const y=Math.hypot(u,h),b=Math.hypot(m,p);return[y*c,b*d]}function C6n(s){const{width:t,height:n}=s;if(t>Qyt||n>Qyt)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 b of s.data){let v=128;for(;v>0;)h[m++]=b&v?0:255,v>>=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[b]&&(l[d+c]=a[b],++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 x=new Int32Array([0,i,-1,0,-i,0,0,0,1]),g=new Path2D;for(o=0;p&&o<=n;o++){let b=o*i;const v=b+t;for(;b>4,l[b]&=C>>2|C<<2),g.lineTo(b%i,b/i|0),l[b]||--p}while(N!==b);--o}return h=null,l=null,function(b){b.save(),b.scale(1/t,-1/n),b.translate(0,-n),b.fill(g),b.beginPath(),b.restore()}}class Jyt{constructor(t,n){this.alphaIsShape=!1,this.fontSize=0,this.fontSizeScale=1,this.textMatrix=A$t,this.textMatrixScale=1,this.fontMatrix=GBe,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=Wy.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]=ko.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=ko.applyTransform(n,t),a=ko.applyTransform(n.slice(2),t),i=ko.applyTransform([n[0],n[3]],t),l=ko.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){ko.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=ko.bezierBoundingBox(n,r,a,i,l,o,c,d,u);u||this.updateRectMinMax(t,h)}getPathBoundingBox(t=s1.FILL,n=null){const r=[this.minX,this.minY,this.maxX,this.maxY];if(t===s1.STROKE){n||km("Stroke bounding box must include transform.");const a=ko.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=ko.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=s1.FILL,n=null){return ko.intersect(this.clipBox,this.getPathBoundingBox(t,n))}}function evt(s,t){if(typeof ImageData<"u"&&t instanceof ImageData){s.putImageData(t,0,0);return}const n=t.height,r=t.width,a=n%fb,i=(n-a)/fb,l=a===0?i:i+1,o=s.createImageData(r,fb);let c=0,d;const u=t.data,h=o.data;let m,p,x,g;if(t.kind===eNe.GRAYSCALE_1BPP){const y=u.byteLength,b=new Uint32Array(h.buffer,0,h.byteLength>>2),v=b.length,N=r+7>>3,C=4294967295,A=b1.isLittleEndian?4278190080:255;for(m=0;mN?r:T*8-7,I=M&-8;let D=0,B=0;for(;P>=1}for(;d=i&&(x=a,g=r*x),d=0,p=g;p--;)h[d++]=u[c++],h[d++]=u[c++],h[d++]=u[c++],h[d++]=255;s.putImageData(o,0,m*fb)}else throw new Error(`bad image kind: ${t.kind}`)}function tvt(s,t){if(t.bitmap){s.drawImage(t.bitmap,0,0);return}const n=t.height,r=t.width,a=n%fb,i=(n-a)/fb,l=a===0?i:i+1,o=s.createImageData(r,fb);let c=0;const d=t.data,u=o.data;for(let h=0;hXyt&&typeof r=="function",u=d?Date.now()+N6n:0;let h=0;const m=this.commonObjs,p=this.objs;let x;for(;;){if(a!==void 0&&o===a.nextBreakPoint)return a.breakIt(o,r),o;if(x=l[o],x!==Q2.dependency)this[x].apply(this,i[o]);else for(const g of i[o]){const y=g.startsWith("g_")?m:p;if(!y.has(g))return y.get(g,r),o}if(o++,o===c)return o;if(d&&++h>Xyt){if(Date.now()>u)return r(),o;h=0}}}endDrawing(){Kt(this,v6,_$e).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(),Kt(this,v6,w$e).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=kp(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 D=Math.round(Math.min(o[0],o[2])+o[4]),B=Math.round(Math.min(o[1],o[3])+o[5]);return{canvas:I,offsetX:D,offsetY:B}}u=I}u||(h=this.cachedCanvases.getCanvas("maskCanvas",r,a),tvt(h.context,t));let m=ko.transform(o,[1/r,0,0,-1/a,0,0]);m=ko.transform(m,[1,0,0,1,0,-a]);const[p,x,g,y]=ko.getAxialAlignedBoundingBox([0,0,r,a],m),b=Math.round(g-p)||1,v=Math.round(y-x)||1,N=this.cachedCanvases.getCanvas("fillCanvas",b,v),C=N.context,A=p,T=x;C.translate(-A,-T),C.transform(...m),u||(u=this._scaleImage(h.canvas,E4(C)),u=u.img,c&&l&&c.set(d,u)),C.imageSmoothingEnabled=svt(kp(C),t.interpolate),lae(C,u,0,0,u.width,u.height,0,0,r,a),C.globalCompositeOperation="source-in";const P=ko.transform(E4(C),[1,0,0,1,-A,-T]);return C.fillStyle=l?i.getPattern(n,this,P,s1.FILL):i,C.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=A6n[t]}setLineJoin(t){this.ctx.lineJoin=E6n[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(...kp(this.suspendedCtx)),DG(this.suspendedCtx,i),k6n(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(),DG(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,x=d-h;if(l){const y=ko.makeHexColor(...l);if(p<0||x<0||p+r>m.width||x+a>m.height){const b=this.cachedCanvases.getCanvas("maskExtension",r,a),v=b.context;v.drawImage(m,-p,-x),v.globalCompositeOperation="destination-atop",v.fillStyle=y,v.fillRect(0,0,r,a),v.globalCompositeOperation="source-over",m=b.canvas,p=x=0}else{t.save(),t.globalAlpha=1,t.setTransform(1,0,0,1,0,0);const b=new Path2D;b.rect(p,x,r,a),t.clip(b),t.globalCompositeOperation="destination-atop",t.fillStyle=y,t.fillRect(p,x,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 g=new Path2D;g.rect(c,d,r,a),n.clip(g),n.globalCompositeOperation="destination-in",n.drawImage(m,p,x,r,a,c,d,r,a),n.restore()}save(){this.inSMaskMode?(DG(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(),DG(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=kp(a),h=u[0]===0&&u[3]===0||u[1]===0&&u[2]===0,m=h?r.slice(0):null;for(let p=0,x=0,g=t.length;pZyt&&(d=Zyt),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&Wy.FILL_STROKE_MASK,h=!!(c&Wy.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===Wy.FILL||u===Wy.FILL_STROKE)&&i.fill(),(u===Wy.STROKE||u===Wy.FILL_STROKE)&&i.stroke(),i.restore()):((u===Wy.FILL||u===Wy.FILL_STROKE)&&i.fillText(t,n,r),(u===Wy.STROKE||u===Wy.FILL_STROKE)&&i.strokeText(t,n,r)),h&&(this.pendingTextPaths||(this.pendingTextPaths=[])).push({transform:kp(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 xd(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,x=r.defaultVMetrics,g=a*n.fontMatrix[0],y=n.textRenderingMode===Wy.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 b;if(n.patternFill){i.save();const T=n.fillColor.getPattern(i,this,E4(i),s1.FILL);b=kp(i),i.restore(),i.fillStyle=T}let v=n.lineWidth;const N=n.textMatrixScale;if(N===0||v===0){const T=n.textRenderingMode&Wy.FILL_STROKE_MASK;(T===Wy.STROKE||T===Wy.FILL_STROKE)&&(v=this.getSinglePixelWidth())}else v/=N;if(l!==1&&(i.scale(l,l),v/=l),i.lineWidth=v,r.isInvalidPDFjsFont){const T=[];let P=0;for(const M of t)T.push(M.unicode),P+=M.width;i.fillText(T.join(""),0,0),n.x+=P*g*u,i.restore(),this.compose();return}let C=0,A;for(A=0;A0){const K=i.measureText(I).width*1e3/a*l;if(Wnew yQe(l,this.commonObjs,this.objs,this.canvasFactory,this.filterFactory,{optionalContentConfig:this.optionalContentConfig,markedContentStack:this.markedContentStack})};n=new b$e(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=ko.makeHexColor(t,n,r)}setStrokeTransparent(){this.ctx.strokeStyle=this.current.strokeColor="transparent"}setFillRGBColor(t,n,r){this.ctx.fillStyle=this.current.fillColor=ko.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=w6n(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,E4(n),s1.SHADING);const a=E4(n);if(a){const{width:i,height:l}=n.canvas,[o,c,d,u]=ko.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(){km("Should not call beginInlineImage")}beginImageData(){km("Should not call beginImageData")}paintFormXObjectBegin(t,n){if(this.contentVisible&&(this.save(),this.baseTransformStack.push(this.baseTransform),t&&this.transform(...t),this.baseTransform=kp(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(kp(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||jTe("TODO: Support non-isolated groups."),t.knockout&&Pc("Knockout groups not supported.");const r=kp(n);if(t.matrix&&n.transform(...t.matrix),!t.bbox)throw new Error("Bounding box is required.");let a=ko.getAxialAlignedBoundingBox(t.bbox,kp(n));const i=[0,0,n.canvas.width,n.canvas.height];a=ko.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()),DG(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=kp(this.ctx);this.restore(),this.ctx.save(),this.ctx.setTransform(...a);const i=ko.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(Kt(this,v6,_$e).call(this),cae(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]=ko.singularValueDecompose2dScale(kp(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:x}=this.annotationCanvas;this.annotationCanvasMap.set(t,p),this.annotationCanvas.savedCtx=this.ctx,this.ctx=x,this.ctx.save(),this.ctx.setTransform(c,0,0,-d,0,o*d),cae(this.ctx)}else cae(this.ctx),this.endPath(),this.ctx.rect(n[0],n[1],l,o),this.ctx.clip(),this.ctx.beginPath()}this.current=new Jyt(this.ctx.canvas.width,this.ctx.canvas.height),this.transform(...r),this.transform(...a)}endAnnotation(){this.annotationCanvas&&(this.ctx.restore(),Kt(this,v6,w$e).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=C6n(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=kp(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}};v6=new WeakSet,_$e=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)},w$e=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 vB=yQe;for(const s in Q2)vB.prototype[s]!==void 0&&(vB.prototype[Q2[s]]=vB.prototype[s]);var WQ,KQ;class E3{static get workerPort(){return pe(this,WQ)}static set workerPort(t){if(!(typeof Worker<"u"&&t instanceof Worker)&&t!==null)throw new Error("Invalid `workerPort` type.");$t(this,WQ,t)}static get workerSrc(){return pe(this,KQ)}static set workerSrc(t){if(typeof t!="string")throw new Error("Invalid `workerSrc` type.");$t(this,KQ,t)}}WQ=new WeakMap,KQ=new WeakMap,rs(E3,WQ,null),rs(E3,KQ,"");const dae={UNKNOWN:0,DATA:1,ERROR:2},bx={UNKNOWN:0,CANCEL:1,CANCEL_COMPLETE:2,CLOSE:3,ENQUEUE:4,ERROR:5,PULL:6,PULL_COMPLETE:7,START_COMPLETE:8};function y_(s){switch(s instanceof Error||typeof s=="object"&&s!==null||km('wrapReason: Expected "reason" to be a (possibly cloned) Error.'),s.name){case"AbortException":return new wF(s.message);case"MissingPDFException":return new _F(s.message);case"PasswordException":return new WBe(s.message,s.code);case"UnexpectedResponseException":return new NTe(s.message,s.status);case"UnknownErrorException":return new KBe(s.message,s.details);default:return new KBe(s.message,s.toString())}}var e$,t2,hUt,mUt,pUt,lNe;class UW{constructor(t,n,r){rs(this,t2);rs(this,e$,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",Kt(this,t2,hUt).bind(this),{signal:pe(this,e$).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:bx.PULL,streamId:i,desiredSize:d.desiredSize}),u.promise},cancel:d=>{fg(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:bx.CANCEL,streamId:i,reason:y_(d)}),u.promise}},r)}destroy(){var t;(t=pe(this,e$))==null||t.abort(),$t(this,e$,null)}}e$=new WeakMap,t2=new WeakSet,hUt=function({data:t}){if(t.targetName!==this.sourceName)return;if(t.stream){Kt(this,t2,pUt).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===dae.DATA)a.resolve(t.data);else if(t.callback===dae.ERROR)a.reject(y_(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:dae.DATA,callbackId:t.callbackId,data:l})},function(l){i.postMessage({sourceName:r,targetName:a,callback:dae.ERROR,callbackId:t.callbackId,reason:y_(l)})});return}if(t.streamId){Kt(this,t2,mUt).call(this,t);return}n(t.data)},mUt=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:bx.ENQUEUE,streamId:n,chunk:d},h)},close(){this.isCancelled||(this.isCancelled=!0,i.postMessage({sourceName:r,targetName:a,stream:bx.CLOSE,streamId:n}),delete l.streamSinks[n])},error(d){fg(d instanceof Error,"error must have a valid reason"),!this.isCancelled&&(this.isCancelled=!0,i.postMessage({sourceName:r,targetName:a,stream:bx.ERROR,streamId:n,reason:y_(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:bx.START_COMPLETE,streamId:n,success:!0})},function(d){i.postMessage({sourceName:r,targetName:a,stream:bx.START_COMPLETE,streamId:n,reason:y_(d)})})},pUt=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 bx.START_COMPLETE:t.success?l.startCall.resolve():l.startCall.reject(y_(t.reason));break;case bx.PULL_COMPLETE:t.success?l.pullCall.resolve():l.pullCall.reject(y_(t.reason));break;case bx.PULL:if(!o){i.postMessage({sourceName:r,targetName:a,stream:bx.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:bx.PULL_COMPLETE,streamId:n,success:!0})},function(c){i.postMessage({sourceName:r,targetName:a,stream:bx.PULL_COMPLETE,streamId:n,reason:y_(c)})});break;case bx.ENQUEUE:if(fg(l,"enqueue should have stream controller"),l.isClosed)break;l.controller.enqueue(t.chunk);break;case bx.CLOSE:if(fg(l,"close should have stream controller"),l.isClosed)break;l.isClosed=!0,l.controller.close(),Kt(this,t2,lNe).call(this,l,n);break;case bx.ERROR:fg(l,"error should have stream controller"),l.controller.error(y_(t.reason)),Kt(this,t2,lNe).call(this,l,n);break;case bx.CANCEL_COMPLETE:t.success?l.cancelCall.resolve():l.cancelCall.reject(y_(t.reason)),Kt(this,t2,lNe).call(this,l,n);break;case bx.CANCEL:if(!o)break;new Promise(function(c){var d;c((d=o.onCancel)==null?void 0:d.call(o,y_(t.reason)))}).then(function(){i.postMessage({sourceName:r,targetName:a,stream:bx.CANCEL_COMPLETE,streamId:n,success:!0})},function(c){i.postMessage({sourceName:r,targetName:a,stream:bx.CANCEL_COMPLETE,streamId:n,reason:y_(c)})}),o.sinkCapability.reject(y_(t.reason)),o.isCancelled=!0,delete this.streamSinks[n];break;default:throw new Error("Unexpected stream case")}},lNe=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 SD,YQ;class M6n{constructor({parsedData:t,rawData:n}){rs(this,SD);rs(this,YQ);$t(this,SD,t),$t(this,YQ,n)}getRaw(){return pe(this,YQ)}get(t){return pe(this,SD).get(t)??null}getAll(){return HZe(pe(this,SD))}has(t){return pe(this,SD).has(t)}}SD=new WeakMap,YQ=new WeakMap;const w9=Symbol("INTERNAL");var ZQ,XQ,QQ,t$;class L6n{constructor(t,{name:n,intent:r,usage:a,rbGroups:i}){rs(this,ZQ,!1);rs(this,XQ,!1);rs(this,QQ,!1);rs(this,t$,!0);$t(this,ZQ,!!(t&O_.DISPLAY)),$t(this,XQ,!!(t&O_.PRINT)),this.name=n,this.intent=r,this.usage=a,this.rbGroups=i}get visible(){if(pe(this,QQ))return pe(this,t$);if(!pe(this,t$))return!1;const{print:t,view:n}=this.usage;return pe(this,ZQ)?(n==null?void 0:n.viewState)!=="OFF":pe(this,XQ)?(t==null?void 0:t.printState)!=="OFF":!0}_setVisible(t,n,r=!1){t!==w9&&km("Internal method `_setVisible` called."),$t(this,QQ,r),$t(this,t$,n)}}ZQ=new WeakMap,XQ=new WeakMap,QQ=new WeakMap,t$=new WeakMap;var AE,Bu,s$,n$,JQ,j$e;class P6n{constructor(t,n=O_.DISPLAY){rs(this,JQ);rs(this,AE,null);rs(this,Bu,new Map);rs(this,s$,null);rs(this,n$,null);if(this.renderingIntent=n,this.name=null,this.creator=null,t!==null){this.name=t.name,this.creator=t.creator,$t(this,n$,t.order);for(const r of t.groups)pe(this,Bu).set(r.id,new L6n(n,r));if(t.baseState==="OFF")for(const r of pe(this,Bu).values())r._setVisible(w9,!1);for(const r of t.on)pe(this,Bu).get(r)._setVisible(w9,!0);for(const r of t.off)pe(this,Bu).get(r)._setVisible(w9,!1);$t(this,s$,this.getHash())}}isVisible(t){if(pe(this,Bu).size===0)return!0;if(!t)return jTe("Optional content group not defined."),!0;if(t.type==="OCG")return pe(this,Bu).has(t.id)?pe(this,Bu).get(t.id).visible:(Pc(`Optional content group not found: ${t.id}`),!0);if(t.type==="OCMD"){if(t.expression)return Kt(this,JQ,j$e).call(this,t.expression);if(!t.policy||t.policy==="AnyOn"){for(const n of t.ids){if(!pe(this,Bu).has(n))return Pc(`Optional content group not found: ${n}`),!0;if(pe(this,Bu).get(n).visible)return!0}return!1}else if(t.policy==="AllOn"){for(const n of t.ids){if(!pe(this,Bu).has(n))return Pc(`Optional content group not found: ${n}`),!0;if(!pe(this,Bu).get(n).visible)return!1}return!0}else if(t.policy==="AnyOff"){for(const n of t.ids){if(!pe(this,Bu).has(n))return Pc(`Optional content group not found: ${n}`),!0;if(!pe(this,Bu).get(n).visible)return!0}return!1}else if(t.policy==="AllOff"){for(const n of t.ids){if(!pe(this,Bu).has(n))return Pc(`Optional content group not found: ${n}`),!0;if(pe(this,Bu).get(n).visible)return!1}return!0}return Pc(`Unknown optional content policy ${t.policy}.`),!0}return Pc(`Unknown group type ${t.type}.`),!0}setVisibility(t,n=!0,r=!0){var i;const a=pe(this,Bu).get(t);if(!a){Pc(`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=pe(this,Bu).get(o))==null||i._setVisible(w9,!1,!0));a._setVisible(w9,!!n,!0),$t(this,AE,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=pe(this,Bu).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,AE,null)}get hasInitialVisibility(){return pe(this,s$)===null||this.getHash()===pe(this,s$)}getOrder(){return pe(this,Bu).size?pe(this,n$)?pe(this,n$).slice():[...pe(this,Bu).keys()]:null}getGroups(){return pe(this,Bu).size>0?HZe(pe(this,Bu)):null}getGroup(t){return pe(this,Bu).get(t)||null}getHash(){if(pe(this,AE)!==null)return pe(this,AE);const t=new tUt;for(const[n,r]of pe(this,Bu))t.update(`${n}:${r.visible}`);return $t(this,AE,t.hexdigest())}}AE=new WeakMap,Bu=new WeakMap,s$=new WeakMap,n$=new WeakMap,JQ=new WeakSet,j$e=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)});fg(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(){fg(!this._fullRequestReader,"PDFDataTransportStream.getFullReader can only be called once.");const t=this._queuedChunks;return this._queuedChunks=null,new D6n(this,t,this._progressiveDone,this._contentDispositionFilename)}getRangeReader(t,n){if(n<=this._progressiveDataLength)return null;const r=new R6n(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 D6n{constructor(t,n,r=!1,a=null){this._stream=t,this._done=r||!1,this._filename=KZe(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 R6n{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 O6n(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=kTe(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[,g,y,b]=m;if(g=parseInt(g,10),g in h){if(g===0)break;continue}h[g]=[y,b]}const x=[];for(let g=0;g{if(!fUt(i.status))throw ATe(i.status,a);this._reader=i.body.getReader(),this._headersCapability.resolve();const l=i.headers,{allowRangeRequests:o,suggestedLength:c}=eXe({responseHeaders:l,isHttp:t.isHttp,rangeChunkSize:this._rangeChunkSize,disableRange:this._disableRange});this._isRangeSupported=o,this._contentLength=c||this._contentLength,this._filename=tXe(l),!this._isStreamingSupported&&this._isRangeSupported&&this.cancel(new wF("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:gUt(t),done:!1})}cancel(t){var n;(n=this._reader)==null||n.cancel(t),this._abortController.abort()}}class z6n{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,xUt(i,this._withCredentials,this._abortController)).then(o=>{if(!fUt(o.status))throw ATe(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:gUt(t),done:!1})}cancel(t){var n;(n=this._reader)==null||n.cancel(t),this._abortController.abort()}}const mDe=200,pDe=206;function B6n(s){const t=s.response;return typeof t!="string"?t:kTe(t).buffer}class $6n{constructor({url:t,httpHeaders:n,withCredentials:r}){this.url=t,this.isHttp=/^https?:/i.test(t),this.headers=JZe(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=pDe):a.expectedStatus=mDe,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||mDe;if(!(i===mDe&&r.expectedStatus===pDe)&&i!==r.expectedStatus){(d=r.onError)==null||d.call(r,a.status);return}const o=B6n(a);if(i===pDe){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 U6n{constructor(t){this._source=t,this._manager=new $6n(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 fg(!this._fullRequestReader,"PDFNetworkStream.getFullReader can only be called once."),this._fullRequestReader=new q6n(this._manager,this._source),this._fullRequestReader}getRangeReader(t,n){const r=new V6n(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 q6n{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}=eXe({responseHeaders:r,isHttp:this._manager.isHttp,rangeChunkSize:this._rangeChunkSize,disableRange:this._disableRange});a&&(this._isRangeSupported=!0),this._contentLength=i||this._contentLength,this._filename=tXe(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=ATe(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 V6n{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=ATe(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 H6n=/^[a-z][a-z0-9\-+.]+:/i;function G6n(s){if(H6n.test(s))return new URL(s);const t=p6.get("url");return new URL(t.pathToFileURL(s))}function yUt(s,t,n){return s.protocol==="http:"?p6.get("http").request(s,{headers:t},n):p6.get("https").request(s,{headers:t},n)}class W6n{constructor(t){this.source=t,this.url=G6n(t.url),this.isHttp=this.url.protocol==="http:"||this.url.protocol==="https:",this.isFsUrl=this.url.protocol==="file:",this.headers=JZe(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 fg(!this._fullRequestReader,"PDFNodeStream.getFullReader can only be called once."),this._fullRequestReader=this.isFsUrl?new Z6n(this):new K6n(this),this._fullRequestReader}getRangeReader(t,n){if(n<=this._progressiveDataLength)return null;const r=this.isFsUrl?new X6n(this,t,n):new Y6n(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 vUt{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 wF("streaming is disabled")),this._storedError&&this._readableStream.destroy(this._storedError)}}class bUt{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 K6n extends vUt{constructor(t){super(t);const n=Object.fromEntries(t.headers),r=a=>{if(a.statusCode===404){const c=new _F(`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}=eXe({responseHeaders:i,isHttp:t.isHttp,rangeChunkSize:this._rangeChunkSize,disableRange:this._disableRange});this._isRangeSupported=l,this._contentLength=o||this._contentLength,this._filename=tXe(i)};this._request=yUt(this._url,n,r),this._request.on("error",a=>{this._storedError=a,this._headersCapability.reject(a)}),this._request.end()}}class Y6n extends bUt{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 _F(`Missing PDF "${this._url}".`);this._storedError=o;return}this._setReadableStream(l)};this._request=yUt(this._url,a,i),this._request.on("error",l=>{this._storedError=l}),this._request.end()}}class Z6n extends vUt{constructor(t){super(t);const n=p6.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 _F(`Missing PDF "${this._url}".`)),this._storedError=r,this._headersCapability.reject(r)})}}class X6n extends bUt{constructor(t,n,r){super(t);const a=p6.get("fs");this._setReadableStream(a.createReadStream(this._url,{start:n,end:r-1}))}}const Q6n=1e5,tb=30,J6n=.8;var jwt,EE,ub,eJ,tJ,CD,c3,sJ,nJ,AD,r$,a$,TE,i$,rJ,o$,ED,aJ,iJ,TD,MD,oJ,ME,l$,yC,_Ut,wUt,N$e,hw,cNe,k$e,jUt,NUt;const sg=class sg{constructor({textContentSource:t,container:n,viewport:r}){rs(this,yC);rs(this,EE,Promise.withResolvers());rs(this,ub,null);rs(this,eJ,!1);rs(this,tJ,!!((jwt=globalThis.FontInspector)!=null&&jwt.enabled));rs(this,CD,null);rs(this,c3,null);rs(this,sJ,0);rs(this,nJ,0);rs(this,AD,null);rs(this,r$,null);rs(this,a$,0);rs(this,TE,0);rs(this,i$,Object.create(null));rs(this,rJ,[]);rs(this,o$,null);rs(this,ED,[]);rs(this,aJ,new WeakMap);rs(this,iJ,null);var c;if(t instanceof ReadableStream)$t(this,o$,t);else if(typeof t=="object")$t(this,o$,new ReadableStream({start(d){d.enqueue(t),d.close()}}));else throw new Error('No "textContentSource" parameter specified.');$t(this,ub,$t(this,r$,n)),$t(this,TE,r.scale*(globalThis.devicePixelRatio||1)),$t(this,a$,r.rotation),$t(this,c3,{div:null,properties:null,ctx:null});const{pageWidth:a,pageHeight:i,pageX:l,pageY:o}=r.rawDims;$t(this,iJ,[1,0,0,-1,-l,o+i]),$t(this,nJ,a),$t(this,sJ,i),Kt(c=sg,hw,jUt).call(c),OO(n,r),pe(this,EE).promise.finally(()=>{pe(sg,l$).delete(this),$t(this,c3,null),$t(this,i$,null)}).catch(()=>{})}static get fontFamilyMap(){const{isWindows:t,isFirefox:n}=b1.platform;return xd(this,"fontFamilyMap",new Map([["sans-serif",`${t&&n?"Calibri, ":""}sans-serif`],["monospace",`${t&&n?"Lucida Console, ":""}monospace`]]))}render(){const t=()=>{pe(this,AD).read().then(({value:n,done:r})=>{if(r){pe(this,EE).resolve();return}pe(this,CD)??$t(this,CD,n.lang),Object.assign(pe(this,i$),n.styles),Kt(this,yC,_Ut).call(this,n.items),t()},pe(this,EE).reject)};return $t(this,AD,pe(this,o$).getReader()),pe(sg,l$).add(this),t(),pe(this,EE).promise}update({viewport:t,onBefore:n=null}){var i;const r=t.scale*(globalThis.devicePixelRatio||1),a=t.rotation;if(a!==pe(this,a$)&&(n==null||n(),$t(this,a$,a),OO(pe(this,r$),{rotation:a})),r!==pe(this,TE)){n==null||n(),$t(this,TE,r);const l={div:null,properties:null,ctx:Kt(i=sg,hw,cNe).call(i,pe(this,CD))};for(const o of pe(this,ED))l.properties=pe(this,aJ).get(o),l.div=o,Kt(this,yC,N$e).call(this,l)}}cancel(){var n;const t=new wF("TextLayer task cancelled.");(n=pe(this,AD))==null||n.cancel(t).catch(()=>{}),$t(this,AD,null),pe(this,EE).reject(t)}get textDivs(){return pe(this,ED)}get textContentItemsStr(){return pe(this,rJ)}static cleanup(){if(!(pe(this,l$).size>0)){pe(this,TD).clear();for(const{canvas:t}of pe(this,MD).values())t.remove();pe(this,MD).clear()}}};EE=new WeakMap,ub=new WeakMap,eJ=new WeakMap,tJ=new WeakMap,CD=new WeakMap,c3=new WeakMap,sJ=new WeakMap,nJ=new WeakMap,AD=new WeakMap,r$=new WeakMap,a$=new WeakMap,TE=new WeakMap,i$=new WeakMap,rJ=new WeakMap,o$=new WeakMap,ED=new WeakMap,aJ=new WeakMap,iJ=new WeakMap,TD=new WeakMap,MD=new WeakMap,oJ=new WeakMap,ME=new WeakMap,l$=new WeakMap,yC=new WeakSet,_Ut=function(t){var a,i;if(pe(this,eJ))return;(i=pe(this,c3)).ctx??(i.ctx=Kt(a=sg,hw,cNe).call(a,pe(this,CD)));const n=pe(this,ED),r=pe(this,rJ);for(const l of t){if(n.length>Q6n){Pc("Ignoring additional textDivs for performance reasons."),$t(this,eJ,!0);return}if(l.str===void 0){if(l.type==="beginMarkedContentProps"||l.type==="beginMarkedContent"){const o=pe(this,ub);$t(this,ub,document.createElement("span")),pe(this,ub).classList.add("markedContent"),l.id!==null&&pe(this,ub).setAttribute("id",`${l.id}`),o.append(pe(this,ub))}else l.type==="endMarkedContent"&&$t(this,ub,pe(this,ub).parentNode);continue}r.push(l.str),Kt(this,yC,wUt).call(this,l)}},wUt=function(t){var g;const n=document.createElement("span"),r={angle:0,canvasWidth:0,hasText:t.str!=="",hasEOL:t.hasEOL,fontSize:0};pe(this,ED).push(n);const a=ko.transform(pe(this,iJ),t.transform);let i=Math.atan2(a[1],a[0]);const l=pe(this,i$)[t.fontName];l.vertical&&(i+=Math.PI/2);let o=pe(this,tJ)&&l.fontSubstitution||l.fontFamily;o=sg.fontFamilyMap.get(o)||o;const c=Math.hypot(a[2],a[3]),d=c*Kt(g=sg,hw,NUt).call(g,o,pe(this,CD));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;pe(this,ub)===pe(this,r$)?(p.left=`${(100*u/pe(this,nJ)).toFixed(2)}%`,p.top=`${(100*h/pe(this,sJ)).toFixed(2)}%`):(p.left=`${m}${u.toFixed(2)}px)`,p.top=`${m}${h.toFixed(2)}px)`),p.fontSize=`${m}${(pe(sg,ME)*c).toFixed(2)}px)`,p.fontFamily=o,r.fontSize=c,n.setAttribute("role","presentation"),n.textContent=t.str,n.dir=t.dir,pe(this,tJ)&&(n.dataset.fontName=l.fontSubstitutionLoadedName||t.fontName),i!==0&&(r.angle=i*(180/Math.PI));let x=!1;if(t.str.length>1)x=!0;else if(t.str!==" "&&t.transform[0]!==t.transform[3]){const y=Math.abs(t.transform[0]),b=Math.abs(t.transform[3]);y!==b&&Math.max(y,b)/Math.min(y,b)>1.5&&(x=!0)}if(x&&(r.canvasWidth=l.vertical?t.height:t.width),pe(this,aJ).set(n,r),pe(this,c3).div=n,pe(this,c3).properties=r,Kt(this,yC,N$e).call(this,pe(this,c3)),r.hasText&&pe(this,ub).append(n),r.hasEOL){const y=document.createElement("br");y.setAttribute("role","presentation"),pe(this,ub).append(y)}},N$e=function(t){var o;const{div:n,properties:r,ctx:a}=t,{style:i}=n;let l="";if(pe(sg,ME)>1&&(l=`scale(${1/pe(sg,ME)})`),r.canvasWidth!==0&&r.hasText){const{fontFamily:c}=i,{canvasWidth:d,fontSize:u}=r;Kt(o=sg,hw,k$e).call(o,a,u*pe(this,TE),c);const{width:h}=a.measureText(n.textContent);h>0&&(l=`scaleX(${d*pe(this,TE)/h}) ${l}`)}r.angle!==0&&(l=`rotate(${r.angle}deg) ${l}`),l.length>0&&(i.transform=l)},hw=new WeakSet,cNe=function(t=null){let n=pe(this,MD).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}),pe(this,MD).set(t,n),pe(this,oJ).set(n,{size:0,family:""})}return n},k$e=function(t,n,r){const a=pe(this,oJ).get(t);n===a.size&&r===a.family||(t.font=`${n}px ${r}`,a.size=n,a.family=r)},jUt=function(){if(pe(this,ME)!==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,ME,t.getBoundingClientRect().height),t.remove()},NUt=function(t,n){const r=pe(this,TD).get(t);if(r)return r;const a=Kt(this,hw,cNe).call(this,n);a.canvas.width=a.canvas.height=tb,Kt(this,hw,k$e).call(this,a,tb,t);const i=a.measureText("");let l=i.fontBoundingBoxAscent,o=Math.abs(i.fontBoundingBoxDescent);if(l){const u=l/(l+o);return pe(this,TD).set(t,u),a.canvas.width=a.canvas.height=0,u}a.strokeStyle="red",a.clearRect(0,0,tb,tb),a.strokeText("g",0,0);let c=a.getImageData(0,0,tb,tb).data;o=0;for(let u=c.length-1-3;u>=0;u-=4)if(c[u]>0){o=Math.ceil(u/4/tb);break}a.clearRect(0,0,tb,tb),a.strokeText("A",0,tb),c=a.getImageData(0,0,tb,tb).data,l=0;for(let u=0,h=c.length;u0){l=tb-Math.floor(u/4/tb);break}a.canvas.width=a.canvas.height=0;const d=l?l/(l+o):J6n;return pe(this,TD).set(t,d),d},rs(sg,hw),rs(sg,TD,new Map),rs(sg,MD,new Map),rs(sg,oJ,new WeakMap),rs(sg,ME,null),rs(sg,l$,new Set);let uQ=sg;class hQ{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(hQ.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 eMn=65536,tMn=100,sMn=5e3,nMn=lv?f6n:h6n,rMn=lv?x6n:iUt,aMn=lv?p6n:m6n,iMn=lv?g6n:dUt;function oMn(s={}){typeof s=="string"||s instanceof URL?s={url:s}:(s instanceof ArrayBuffer||ArrayBuffer.isView(s))&&(s={data:s});const t=new S$e,{docId:n}=t,r=s.url?lMn(s.url):null,a=s.data?cMn(s.data):null,i=s.httpHeaders||null,l=s.withCredentials===!0,o=s.password??null,c=s.range instanceof kUt?s.range:null,d=Number.isInteger(s.rangeChunkSize)&&s.rangeChunkSize>0?s.rangeChunkSize:eMn;let u=s.worker instanceof bB?s.worker:null;const h=s.verbosity,m=typeof s.docBaseUrl=="string"&&!CTe(s.docBaseUrl)?s.docBaseUrl:null,p=typeof s.cMapUrl=="string"?s.cMapUrl:null,x=s.cMapPacked!==!1,g=s.CMapReaderFactory||rMn,y=typeof s.standardFontDataUrl=="string"?s.standardFontDataUrl:null,b=s.StandardFontDataFactory||iMn,v=s.stopAtErrors!==!0,N=Number.isInteger(s.maxImageSize)&&s.maxImageSize>-1?s.maxImageSize:-1,C=s.isEvalSupported!==!1,A=typeof s.isOffscreenCanvasSupported=="boolean"?s.isOffscreenCanvasSupported:!lv,T=typeof s.isChrome=="boolean"?s.isChrome:!b1.platform.isFirefox&&typeof window<"u"&&!!(window!=null&&window.chrome),P=Number.isInteger(s.canvasMaxAreaInBytes)?s.canvasMaxAreaInBytes:-1,M=typeof s.disableFontFace=="boolean"?s.disableFontFace:lv,I=s.fontExtraProperties===!0,D=s.enableXfa===!0,B=s.ownerDocument||globalThis.document,q=s.disableRange===!0,W=s.disableStream===!0,V=s.disableAutoFetch===!0,K=s.pdfBug===!0,Q=s.CanvasFactory||nMn,J=s.FilterFactory||aMn,ce=s.enableHWA===!0,ue=c?c.length:s.length??NaN,ne=typeof s.useSystemFonts=="boolean"?s.useSystemFonts:!lv&&!M,ee=typeof s.useWorkerFetch=="boolean"?s.useWorkerFetch:g===iUt&&b===dUt&&p&&y&&DW(p,document.baseURI)&&DW(y,document.baseURI);s.canvasFactory&&Gyt("`canvasFactory`-instance option, please use `CanvasFactory` instead."),s.filterFactory&&Gyt("`filterFactory`-instance option, please use `FilterFactory` instead.");const le=null;qTn(h);const he={canvasFactory:new Q({ownerDocument:B,enableHWA:ce}),filterFactory:new J({docId:n,ownerDocument:B}),cMapReaderFactory:ee?null:new g({baseUrl:p,isCompressed:x}),standardFontDataFactory:ee?null:new b({baseUrl:y})};if(!u){const fe={verbosity:h,port:E3.workerPort};u=fe.port?bB.fromPort(fe):new bB(fe),t._worker=u}const ve={docId:n,apiVersion:"4.8.69",data:a,password:o,disableAutoFetch:V,rangeChunkSize:d,length:ue,docBaseUrl:m,enableXfa:D,evaluatorOptions:{maxImageSize:N,disableFontFace:M,ignoreErrors:v,isEvalSupported:C,isOffscreenCanvasSupported:A,isChrome:T,canvasMaxAreaInBytes:P,fontExtraProperties:I,useSystemFonts:ne,cMapUrl:ee?p:null,standardFontDataUrl:ee?y:null}},ge={disableFontFace:M,fontExtraProperties:I,ownerDocument:B,pdfBug:K,styleElement:le,loadingParams:{disableAutoFetch:V,enableXfa:D}};return u.promise.then(function(){if(t.destroyed)throw new Error("Loading aborted");if(u.destroyed)throw new Error("Worker was destroyed");const fe=u.messageHandler.sendWithPromise("GetDocRequest",ve,a?[a.buffer]:null);let je;if(c)je=new I6n(c,{disableRange:q,disableStream:W});else if(!a){if(!r)throw new Error("getDocument - no `url` parameter provided.");let Ee;lv?Ee=typeof fetch<"u"&&typeof Response<"u"&&"body"in Response.prototype&&DW(r)?rvt:W6n:Ee=DW(r)?rvt:U6n,je=new Ee({url:r,length:ue,httpHeaders:i,withCredentials:l,rangeChunkSize:d,disableRange:q,disableStream:W})}return fe.then(Ee=>{if(t.destroyed)throw new Error("Loading aborted");if(u.destroyed)throw new Error("Worker was destroyed");const Me=new UW(n,Ee,u.port),De=new mMn(Me,t,je,ge,he);t._transport=De,Me.send("Ready",null)})}).catch(t._capability.reject),t}function lMn(s){if(s instanceof URL)return s.href;try{return new URL(s,window.location).href}catch{if(lv&&typeof s=="string")return s}throw new Error("Invalid PDF url data: either string or URL-object is expected in the url property.")}function cMn(s){if(lv&&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 kTe(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 avt(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 d3e;const u3e=class u3e{constructor(){this._capability=Promise.withResolvers(),this._transport=null,this._worker=null,this.docId=`d${Xg(u3e,d3e)._++}`,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)}};d3e=new WeakMap,rs(u3e,d3e,0);let S$e=u3e;class kUt{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){km("Abstract method PDFDataRangeTransport.requestDataRange")}abort(){}}class dMn{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 xd(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 LE,d3,Lj,j9,dNe;class uMn{constructor(t,n,r,a=!1){rs(this,Lj);rs(this,LE,null);rs(this,d3,!1);this._pageIndex=t,this._pageInfo=n,this._transport=r,this._stats=a?new Hyt:null,this._pdfBug=a,this.commonObjs=r.commonObjs,this.objs=new SUt,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 mte({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 xd(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=iE.ENABLE,transform:i=null,background:l=null,optionalContentConfigPromise:o=null,annotationCanvasMap:c=null,pageColors:d=null,printAnnotationStorage:u=null,isEditing:h=!1}){var C,A;(C=this._stats)==null||C.time("Overall");const m=this._transport.getRenderingIntent(r,a,u,h),{renderingIntent:p,cacheKey:x}=m;$t(this,d3,!1),Kt(this,Lj,dNe).call(this),o||(o=this._transport.getOptionalContentConfig(p));let g=this._intentStates.get(x);g||(g=Object.create(null),this._intentStates.set(x,g)),g.streamReaderCancelTimeout&&(clearTimeout(g.streamReaderCancelTimeout),g.streamReaderCancelTimeout=null);const y=!!(p&O_.PRINT);g.displayReadyCapability||(g.displayReadyCapability=Promise.withResolvers(),g.operatorList={fnArray:[],argsArray:[],lastChunk:!1,separateAnnots:null},(A=this._stats)==null||A.time("Page Request"),this._pumpOperatorList(m));const b=T=>{var P;g.renderTasks.delete(v),(this._maybeCleanupAfterRender||y)&&$t(this,d3,!0),Kt(this,Lj,j9).call(this,!y),T?(v.capability.reject(T),this._abortOperatorList({intentState:g,reason:T instanceof Error?T:new Error(T)})):v.capability.resolve(),this._stats&&(this._stats.timeEnd("Rendering"),this._stats.timeEnd("Overall"),(P=globalThis.Stats)!=null&&P.enabled&&globalThis.Stats.add(this.pageNumber,this._stats))},v=new A$e({callback:b,params:{canvasContext:t,viewport:n,transform:i,background:l},objs:this.objs,commonObjs:this.commonObjs,annotationCanvasMap:c,operatorList:g.operatorList,pageIndex:this._pageIndex,canvasFactory:this._transport.canvasFactory,filterFactory:this._transport.filterFactory,useRequestAnimationFrame:!y,pdfBug:this._pdfBug,pageColors:d});(g.renderTasks||(g.renderTasks=new Set)).add(v);const N=v.task;return Promise.all([g.displayReadyCapability.promise,o]).then(([T,P])=>{var M;if(this.destroyed){b();return}if((M=this._stats)==null||M.time("Rendering"),!(P.renderingIntent&p))throw new Error("Must use the same `intent`-argument when calling the `PDFPageProxy.render` and `PDFDocumentProxy.getOptionalContentConfig` methods.");v.initializeGraphics({transparency:T,optionalContentConfig:P}),v.operatorListChanged()}).catch(b),N}getOperatorList({intent:t="display",annotationMode:n=iE.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=>hQ.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,d3,!1),Kt(this,Lj,dNe).call(this),Promise.all(t)}cleanup(t=!1){$t(this,d3,!0);const n=Kt(this,Lj,j9).call(this,!1);return t&&n&&this._stats&&(this._stats=new Hyt),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();Kt(this,Lj,j9).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 WZe){let a=tMn;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 wF(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}}LE=new WeakMap,d3=new WeakMap,Lj=new WeakSet,j9=function(t=!1){if(Kt(this,Lj,dNe).call(this),!pe(this,d3)||this.destroyed)return!1;if(t)return $t(this,LE,setTimeout(()=>{$t(this,LE,null),Kt(this,Lj,j9).call(this,!1)},sMn)),!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,d3,!1),!0},dNe=function(){pe(this,LE)&&(clearTimeout(pe(this,LE)),$t(this,LE,null))};var u3,h3e;class hMn{constructor(){rs(this,u3,new Map);rs(this,h3e,Promise.resolve())}postMessage(t,n){const r={data:structuredClone(t,n?{transfer:n}:null)};pe(this,h3e).then(()=>{for(const[a]of pe(this,u3))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){Pc("LoopbackPort - cannot use an `aborted` signal.");return}const l=()=>this.removeEventListener(t,n);a=()=>i.removeEventListener("abort",l),i.addEventListener("abort",l)}pe(this,u3).set(n,a)}removeEventListener(t,n){const r=pe(this,u3).get(n);r==null||r(),pe(this,u3).delete(n)}terminate(){for(const[,t]of pe(this,u3))t==null||t();pe(this,u3).clear()}}u3=new WeakMap,h3e=new WeakMap;var m3e,LD,PD,c$,uNe,d$,hNe;const Wm=class Wm{constructor({name:t=null,port:n=null,verbosity:r=VTn()}={}){rs(this,c$);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=pe(Wm,PD))!=null&&a.has(n))throw new Error("Cannot use more than one PDFWorker per port.");(pe(Wm,PD)||$t(Wm,PD,new WeakMap)).set(n,this),this._initializeFromPort(n);return}this._initialize()}get promise(){return lv?Promise.all([p6.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 UW("main","worker",t),this._messageHandler.on("ready",function(){}),Kt(this,c$,uNe).call(this)}_initialize(){if(pe(Wm,LD)||pe(Wm,d$,hNe)){this._setupFakeWorker();return}let{workerSrc:t}=Wm;try{Wm._isSameOrigin(window.location.href,t)||(t=Wm._createCDNWrapper(new URL(t,window.location).href));const n=new Worker(t,{type:"module"}),r=new UW("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,Kt(this,c$,uNe).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{jTe("The worker has been disabled.")}this._setupFakeWorker()}_setupFakeWorker(){pe(Wm,LD)||(Pc("Setting up fake worker."),$t(Wm,LD,!0)),Wm._setupFakeWorkerGlobal.then(t=>{if(this.destroyed){this._readyCapability.reject(new Error("Worker was destroyed"));return}const n=new hMn;this._port=n;const r=`fake${Xg(Wm,m3e)._++}`,a=new UW(r+"_worker",r,n);t.setup(a,n),this._messageHandler=new UW(r,r+"_worker",n),Kt(this,c$,uNe).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=pe(Wm,PD))==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=pe(this,PD))==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 Wm(t)}static get workerSrc(){if(E3.workerSrc)return E3.workerSrc;throw new Error('No "GlobalWorkerOptions.workerSrc" specified.')}static get _setupFakeWorkerGlobal(){return xd(this,"_setupFakeWorkerGlobal",(async()=>pe(this,d$,hNe)?pe(this,d$,hNe):(await import(this.workerSrc)).WorkerMessageHandler)())}};m3e=new WeakMap,LD=new WeakMap,PD=new WeakMap,c$=new WeakSet,uNe=function(){this._readyCapability.resolve(),this._messageHandler.send("configure",{verbosity:this.verbosity})},d$=new WeakSet,hNe=function(){var t;try{return((t=globalThis.pdfjsWorker)==null?void 0:t.WorkerMessageHandler)||null}catch{return null}},rs(Wm,d$),rs(Wm,m3e,0),rs(Wm,LD,!1),rs(Wm,PD),lv&&($t(Wm,LD,!0),E3.workerSrc||(E3.workerSrc="./pdf.worker.mjs")),Wm._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},Wm._createCDNWrapper=t=>{const n=`await import("${t}");`;return URL.createObjectURL(new Blob([n],{type:"text/javascript"}))};let bB=Wm;var h3,_S,u$,h$,wS,ID,qW;class mMn{constructor(t,n,r,a,i){rs(this,ID);rs(this,h3,new Map);rs(this,_S,new Map);rs(this,u$,new Map);rs(this,h$,new Map);rs(this,wS,null);this.messageHandler=t,this.loadingTask=n,this.commonObjs=new SUt,this.fontLoader=new d6n({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 xd(this,"annotationStorage",new XZe)}getRenderingIntent(t,n=iE.ENABLE,r=null,a=!1,i=!1){let l=O_.DISPLAY,o=f$e;switch(t){case"any":l=O_.ANY;break;case"display":break;case"print":l=O_.PRINT;break;default:Pc(`getRenderingIntent - invalid intent: ${t}`)}const c=l&O_.PRINT&&r instanceof nUt?r:this.annotationStorage;switch(n){case iE.DISABLE:l+=O_.ANNOTATIONS_DISABLE;break;case iE.ENABLE:break;case iE.ENABLE_FORMS:l+=O_.ANNOTATIONS_FORMS;break;case iE.ENABLE_STORAGE:l+=O_.ANNOTATIONS_STORAGE,o=c.serializable;break;default:Pc(`getRenderingIntent - invalid annotationMode: ${n}`)}a&&(l+=O_.IS_EDITING),i&&(l+=O_.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=pe(this,wS))==null||r.reject(new Error("Worker was destroyed during onPassword callback"));const t=[];for(const a of pe(this,_S).values())t.push(a._destroy());pe(this,_S).clear(),pe(this,u$).clear(),pe(this,h$).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(),pe(this,h3).clear(),this.filterFactory.destroy(),uQ.cleanup(),(a=this._networkStream)==null||a.cancelAllRequests(new wF("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)=>{fg(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}fg(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)=>{fg(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}fg(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 dMn(r,this))}),t.on("DocException",function(r){let a;switch(r.name){case"PasswordException":a=new WBe(r.message,r.code);break;case"InvalidPDFException":a=new E$t(r.message);break;case"MissingPDFException":a=new _F(r.message);break;case"UnexpectedResponseException":a=new NTe(r.message,r.status);break;case"UnknownErrorException":a=new KBe(r.message,r.details);break;default:km("DocException - expected a valid Error.")}n._capability.reject(a)}),t.on("PasswordRequest",r=>{if($t(this,wS,Promise.withResolvers()),n.onPassword){const a=i=>{i instanceof Error?pe(this,wS).reject(i):pe(this,wS).resolve({password:i})};try{n.onPassword(a,r.code)}catch(i){pe(this,wS).reject(i)}}else pe(this,wS).reject(new WBe(r.message,r.code));return pe(this,wS).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;pe(this,_S).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;Pc(`Error during font loading: ${p}`),this.commonObjs.resolve(r,p);break}const u=d&&((l=globalThis.FontInspector)!=null&&l.enabled)?(p,x)=>globalThis.FontInspector.fontAdded(p,x):null,h=new u6n(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;fg(m,"The imageRef must be defined.");for(const p of pe(this,_S).values())for(const[,x]of p.objs)if((x==null?void 0:x.ref)===m)return x.dataLen?(this.commonObjs.resolve(r,structuredClone(x)),x.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=pe(this,_S).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)>zTn&&(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&&Pc("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=pe(this,u$).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&&pe(this,h$).set(i.refStr,t);const l=new uMn(n,i,this,this._params.pdfBug);return pe(this,_S).set(n,l),l});return pe(this,u$).set(n,a),a}getPageIndex(t){return avt(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 Kt(this,ID,qW).call(this,"GetFieldObjects")}hasJSActions(){return Kt(this,ID,qW).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 Kt(this,ID,qW).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 Kt(this,ID,qW).call(this,"GetOptionalContentConfig").then(n=>new P6n(n,t))}getPermissions(){return this.messageHandler.sendWithPromise("GetPermissions",null)}getMetadata(){const t="GetMetadata",n=pe(this,h3).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 M6n(a[1]):null,contentDispositionFilename:((i=this._fullReader)==null?void 0:i.filename)??null,contentLength:((l=this._fullReader)==null?void 0:l.contentLength)??null}});return pe(this,h3).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 pe(this,_S).values())if(!n.cleanup())throw new Error(`startCleanup: Page ${n.pageNumber} is currently rendering.`);this.commonObjs.clear(),t||this.fontLoader.clear(),pe(this,h3).clear(),this.filterFactory.destroy(!0),uQ.cleanup()}}cachedPageNumber(t){if(!avt(t))return null;const n=t.gen===0?`${t.num}R`:`${t.num}R${t.gen}`;return pe(this,h$).get(n)??null}}h3=new WeakMap,_S=new WeakMap,u$=new WeakMap,h$=new WeakMap,wS=new WeakMap,ID=new WeakSet,qW=function(t,n=null){const r=pe(this,h3).get(t);if(r)return r;const a=this.messageHandler.sendWithPromise(t,n);return pe(this,h3).set(t,a),a};const uae=Symbol("INITIAL_DATA");var iN,lJ,C$e;class SUt{constructor(){rs(this,lJ);rs(this,iN,Object.create(null))}get(t,n=null){if(n){const a=Kt(this,lJ,C$e).call(this,t);return a.promise.then(()=>n(a.data)),null}const r=pe(this,iN)[t];if(!r||r.data===uae)throw new Error(`Requesting object that isn't resolved yet ${t}.`);return r.data}has(t){const n=pe(this,iN)[t];return!!n&&n.data!==uae}resolve(t,n=null){const r=Kt(this,lJ,C$e).call(this,t);r.data=n,r.resolve()}clear(){var t;for(const n in pe(this,iN)){const{data:r}=pe(this,iN)[n];(t=r==null?void 0:r.bitmap)==null||t.close()}$t(this,iN,Object.create(null))}*[Symbol.iterator](){for(const t in pe(this,iN)){const{data:n}=pe(this,iN)[t];n!==uae&&(yield[t,n])}}}iN=new WeakMap,lJ=new WeakSet,C$e=function(t){var n;return(n=pe(this,iN))[t]||(n[t]={...Promise.withResolvers(),data:uae})};var PE;class pMn{constructor(t){rs(this,PE,null);$t(this,PE,t),this.onContinue=null}get promise(){return pe(this,PE).capability.promise}cancel(t=0){pe(this,PE).cancel(null,t)}get separateAnnots(){const{separateAnnots:t}=pe(this,PE).operatorList;if(!t)return!1;const{annotationCanvasMap:n}=pe(this,PE);return t.form||t.canvas&&(n==null?void 0:n.size)>0}}PE=new WeakMap;var IE,DD;const k8=class k8{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}){rs(this,IE,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 pMn(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(pe(k8,DD).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.");pe(k8,DD).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 vB(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(),pe(this,IE)&&(window.cancelAnimationFrame(pe(this,IE)),$t(this,IE,null)),pe(k8,DD).delete(this._canvas),this.callback(t||new WZe(`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,IE,window.requestAnimationFrame(()=>{$t(this,IE,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(),pe(k8,DD).delete(this._canvas),this.callback())))}};IE=new WeakMap,DD=new WeakMap,rs(k8,DD,new WeakSet);let A$e=k8;const fMn="4.8.69",xMn="3634dab10";function ivt(s){return Math.floor(Math.max(0,Math.min(1,s))*255).toString(16).padStart(2,"0")}function RG(s){return Math.max(0,Math.min(255,255*s))}class ovt{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=RG(t),[t,t,t]}static G_HTML([t]){const n=ivt(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(RG)}static RGB_HTML(t){return`#${t.map(ivt).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[RG(1-Math.min(1,t+a)),RG(1-Math.min(1,r+a)),RG(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 gMn{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){km("Abstract method `_createSVG` called.")}}class sXe extends gMn{_createSVG(t){return document.createElementNS(F4,t)}}class CUt{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&&hQ.shouldBuildText(a.name)&&d.push(p)}return{textDivs:d}}const u=[[a,-1,l]];for(;u.length>0;){const[p,x,g]=u.at(-1);if(x+1===p.children.length){u.pop();continue}const y=p.children[++u.at(-1)[1]];if(y===null)continue;const{name:b}=y;if(b==="#text"){const N=document.createTextNode(y.value);d.push(N),g.append(N);continue}const v=(h=y==null?void 0:y.attributes)!=null&&h.xmlns?document.createElementNS(y.attributes.xmlns,b):document.createElement(b);if(g.append(v),y.attributes&&this.setAttributes({html:v,element:y,storage:n,intent:i,linkService:r}),((m=y.children)==null?void 0:m.length)>0)u.push([y,-1,v]);else if(y.value){const N=document.createTextNode(y.value);o&&hQ.shouldBuildText(b)&&d.push(N),v.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 fte=1e3,yMn=9,zO=new WeakSet;function Q3(s){return{width:s[2]-s[0],height:s[3]-s[1]}}class vMn{static create(t){switch(t.data.annotationType){case eg.LINK:return new AUt(t);case eg.TEXT:return new bMn(t);case eg.WIDGET:switch(t.data.fieldType){case"Tx":return new _Mn(t);case"Btn":return t.data.radioButton?new MUt(t):t.data.checkBox?new jMn(t):new NMn(t);case"Ch":return new kMn(t);case"Sig":return new wMn(t)}return new jF(t);case eg.POPUP:return new T$e(t);case eg.FREETEXT:return new RUt(t);case eg.LINE:return new CMn(t);case eg.SQUARE:return new AMn(t);case eg.CIRCLE:return new EMn(t);case eg.POLYLINE:return new OUt(t);case eg.CARET:return new MMn(t);case eg.INK:return new nXe(t);case eg.POLYGON:return new TMn(t);case eg.HIGHLIGHT:return new FUt(t);case eg.UNDERLINE:return new LMn(t);case eg.SQUIGGLY:return new PMn(t);case eg.STRIKEOUT:return new IMn(t);case eg.STAMP:return new zUt(t);case eg.FILEATTACHMENT:return new DMn(t);default:return new cx(t)}}}var RD,m$,p$,cJ,E$e;const vQe=class vQe{constructor(t,{isRenderable:n=!1,ignoreBorder:r=!1,createQuadrilaterals:a=!1}={}){rs(this,cJ);rs(this,RD,null);rs(this,m$,!1);rs(this,p$,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 vQe._hasPopupData(this.data)}updateEdited(t){var r;if(!this.container)return;pe(this,RD)||$t(this,RD,{rect:this.data.rect.slice(0)});const{rect:n}=t;n&&Kt(this,cJ,E$e).call(this,n),(r=pe(this,p$))==null||r.popup.updateEdited(t)}resetEdited(){var t;pe(this,RD)&&(Kt(this,cJ,E$e).call(this,pe(this,RD).rect),(t=pe(this,p$))==null||t.popup.resetEdited(),$t(this,RD,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 jF||(i.tabIndex=fte);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 T$e){const{rotation:g}=n;return!n.hasOwnCanvas&&g!==0&&this.setRotation(g,i),i}const{width:o,height:c}=Q3(n.rect);if(!t&&n.borderStyle.width>0){l.borderWidth=`${n.borderStyle.width}px`;const g=n.borderStyle.horizontalCornerRadius,y=n.borderStyle.verticalCornerRadius;if(g>0||y>0){const v=`calc(${g}px * var(--scale-factor)) / calc(${y}px * var(--scale-factor))`;l.borderRadius=v}else if(this instanceof MUt){const v=`calc(${o}px * var(--scale-factor)) / calc(${c}px * var(--scale-factor))`;l.borderRadius=v}switch(n.borderStyle.style){case IG.SOLID:l.borderStyle="solid";break;case IG.DASHED:l.borderStyle="dashed";break;case IG.BEVELED:Pc("Unimplemented border style: beveled");break;case IG.INSET:Pc("Unimplemented border style: inset");break;case IG.UNDERLINE:l.borderBottomStyle="solid";break}const b=n.borderColor||null;b?($t(this,m$,!0),l.borderColor=ko.makeHexColor(b[0]|0,b[1]|0,b[2]|0)):l.borderWidth=0}const d=ko.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:x}=n;return n.hasOwnCanvas||x===0?(l.width=`${100*o/u}%`,l.height=`${100*c/h}%`):this.setRotation(x,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}=Q3(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]=ovt[`${l}_HTML`](o),this.annotationStorage.setValue(this.data.id,{[r]:ovt[`${l}_rgb`](o)})};return xd(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(g=>Math.fround(g));if(t.length===8){const[g,y,b,v]=t.subarray(2,6);if(a===g&&i===y&&n===b&&r===v)return}const{style:l}=this.container;let o;if(pe(this,m$)){const{borderColor:g,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"),x=`clippath_${this.data.id}`;p.setAttribute("id",x),p.setAttribute("clipPathUnits","objectBoundingBox"),m.append(p);for(let g=2,y=t.length;g`)}pe(this,m$)&&(o.push("')"),l.backgroundImage=o.join("")),this.container.append(h),this.container.style.clipPath=`url(#${x})`}_createPopup(){const{data:t}=this,n=$t(this,p$,new T$e({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(){km("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&&!zO.has(d)){Pc(`_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&&zO.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})})}};RD=new WeakMap,m$=new WeakMap,p$=new WeakMap,cJ=new WeakSet,E$e=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}=Q3(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 cx=vQe;var V_,h8,EUt,TUt;class AUt extends cx{constructor(n,r=null){super(n,{isRenderable:!0,ignoreBorder:!!(r!=null&&r.ignoreBorder),createQuadrilaterals:!0});rs(this,V_);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?(Kt(this,V_,EUt).call(this,a,n.attachment,n.attachmentDest),i=!0):n.setOCGState?(Kt(this,V_,TUt).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==="")&&Kt(this,V_,h8).call(this)}_bindNamedAction(n,r){n.href=this.linkService.getAnchorUrl(""),n.onclick=()=>(this.linkService.executeNamedAction(r),!1),Kt(this,V_,h8).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),Kt(this,V_,h8).call(this)}_bindResetFormAction(n,r){const a=n.onclick;if(a||(n.href=this.linkService.getAnchorUrl("")),Kt(this,V_,h8).call(this),!this._fieldObjects){Pc('_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 x=this._fieldObjects[p]||[];for(const{id:g}of x)m.add(g)}for(const p of Object.values(this._fieldObjects))for(const x of p)m.has(x.id)===o&&c.push(x)}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 g=m.defaultValue||"";d.setValue(p,{value:g});break}case"checkbox":case"radiobutton":{const g=m.defaultValue===m.exportValues;d.setValue(p,{value:g});break}case"combobox":case"listbox":{const g=m.defaultValue||"";d.setValue(p,{value:g});break}default:continue}const x=document.querySelector(`[data-element-id="${p}"]`);if(x){if(!zO.has(x)){Pc(`_bindResetFormAction - element not allowed: ${p}`);continue}}else continue;x.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}}}V_=new WeakSet,h8=function(){this.container.setAttribute("data-internal-link","")},EUt=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},Kt(this,V_,h8).call(this)},TUt=function(n,r){n.href=this.linkService.getAnchorUrl(""),n.onclick=()=>(this.linkService.executeSetOCGState(r),!1),Kt(this,V_,h8).call(this)};class bMn extends cx{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 jF extends cx{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 b1.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":ko.makeHexColor(n[0],n[1],n[2])}_setTextStyle(t){const n=["left","center","right"],{fontColor:r}=this.data.defaultAppearanceData,a=this.data.defaultAppearanceData.fontSize||yMn,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/(cDe*a))||1,h=d/u;l=Math.min(a,c(h/cDe))}else{const d=Math.abs(this.data.rect[3]-this.data.rect[1]-o);l=Math.min(a,c(d/cDe))}i.fontSize=`calc(${l}px * var(--scale-factor))`,i.color=ko.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 _Mn extends jF{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),zO.add(r),r.setAttribute("data-element-id",n),r.disabled=this.data.readOnly,r.name=this.data.fieldName,r.tabIndex=fte,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 g;if(u.focused)return;const{target:x}=p;u.userValue&&(x.value=u.userValue),u.lastCommittedValue=x.value,u.commitKey=1,(g=this.data.actions)!=null&&g.Focus||(u.focused=!0)}),r.addEventListener("updatefromsandbox",p=>{this.showElementAndHideCanvas(p.target);const x={value(g){u.userValue=g.detail.value??"",t.setValue(n,{value:u.userValue.toString()}),g.target.value=u.userValue},formattedValue(g){const{formattedValue:y}=g.detail;u.formattedValue=y,y!=null&&g.target!==document.activeElement&&(g.target.value=y),t.setValue(n,{formattedValue:y})},selRange(g){g.target.setSelectionRange(...g.detail.selRange)},charLimit:g=>{var N;const{charLimit:y}=g.detail,{target:b}=g;if(y===0){b.removeAttribute("maxLength");return}b.setAttribute("maxLength",y);let v=u.userValue;!v||v.length<=y||(v=v.slice(0,y),b.value=u.userValue=v,t.setValue(n,{value:v}),(N=this.linkService.eventBus)==null||N.dispatch("dispatcheventinsandbox",{source:this,detail:{id:n,name:"Keystroke",value:v,willCommit:!0,commitKey:1,selStart:b.selectionStart,selEnd:b.selectionEnd}}))}};this._dispatchEventFromSandbox(x,p)}),r.addEventListener("keydown",p=>{var y;u.commitKey=1;let x=-1;if(p.key==="Escape"?x=0:p.key==="Enter"&&!this.data.multiLine?x=2:p.key==="Tab"&&(u.commitKey=3),x===-1)return;const{value:g}=p.target;u.lastCommittedValue!==g&&(u.lastCommittedValue=g,u.userValue=g,(y=this.linkService.eventBus)==null||y.dispatch("dispatcheventinsandbox",{source:this,detail:{id:n,name:"Keystroke",value:g,willCommit:!0,commitKey:x,selStart:p.target.selectionStart,selEnd:p.target.selectionEnd}}))});const m=h;h=null,r.addEventListener("blur",p=>{var g,y;if(!u.focused||!p.relatedTarget)return;(g=this.data.actions)!=null&&g.Blur||(u.focused=!1);const{value:x}=p.target;u.userValue=x,u.lastCommittedValue!==x&&((y=this.linkService.eventBus)==null||y.dispatch("dispatcheventinsandbox",{source:this,detail:{id:n,name:"Keystroke",value:x,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:x,target:g}=p,{value:y,selectionStart:b,selectionEnd:v}=g;let N=b,C=v;switch(p.inputType){case"deleteWordBackward":{const T=y.substring(0,b).match(/\w*[^\w]*$/);T&&(N-=T[0].length);break}case"deleteWordForward":{const T=y.substring(b).match(/^[^\w]*\w*/);T&&(C+=T[0].length);break}case"deleteContentBackward":b===v&&(N-=1);break;case"deleteContentForward":b===v&&(C+=1);break}p.preventDefault(),(A=this.linkService.eventBus)==null||A.dispatch("dispatcheventinsandbox",{source:this,detail:{id:n,name:"Keystroke",value:y,change:x||"",willCommit:!1,selStart:N,selEnd:C}})}),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 wMn extends jF{constructor(t){super(t,{isRenderable:!!t.data.hasOwnCanvas})}}class jMn extends jF{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 zO.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=fte,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 MUt extends jF{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(zO.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=fte,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 NMn extends AUt{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 kMn extends jF{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");zO.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=fte;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,x=>x.selected).map(x=>x[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,x=new Set(Array.isArray(p)?p:[p]);for(const g of a.options)g.selected=x.has(g.value);t.setValue(n,{value:o(!0)}),c=o(!1)},multipleSelection(m){a.multiple=!0},remove(m){const p=a.options,x=m.detail.remove;p[x].selected=!1,a.remove(x),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:x,exportValue:g}=m.detail.insert,y=a.children[p],b=document.createElement("option");b.textContent=x,b.value=g,y?y.before(b):a.append(b),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 x of p){const{displayValue:g,exportValue:y}=x,b=document.createElement("option");b.textContent=g,b.value=y,a.append(b)}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 x of m.target.options)x.selected=p.has(x.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 T$e extends cx{constructor(t){const{data:n,elements:r}=t;super(t,{isRenderable:cx._hasPopupData(n)}),this.elements=r,this.popup=null}render(){this.container.classList.add("popupAnnotation");const t=this.popup=new SMn({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=>`${GZe}${r}`).join(",")),this.container}}var f$,p3e,f3e,x$,OD,hf,m3,g$,dJ,uJ,y$,p3,oN,f3,hJ,x3,mJ,FD,zD,uh,mNe,M$e,LUt,PUt,IUt,DUt,pNe,fNe,L$e;class SMn{constructor({container:t,color:n,elements:r,titleObj:a,modificationDate:i,contentsObj:l,richText:o,parent:c,rect:d,parentRect:u,open:h}){rs(this,uh);rs(this,f$,Kt(this,uh,IUt).bind(this));rs(this,p3e,Kt(this,uh,L$e).bind(this));rs(this,f3e,Kt(this,uh,fNe).bind(this));rs(this,x$,Kt(this,uh,pNe).bind(this));rs(this,OD,null);rs(this,hf,null);rs(this,m3,null);rs(this,g$,null);rs(this,dJ,null);rs(this,uJ,null);rs(this,y$,null);rs(this,p3,!1);rs(this,oN,null);rs(this,f3,null);rs(this,hJ,null);rs(this,x3,null);rs(this,mJ,null);rs(this,FD,null);rs(this,zD,!1);var m;$t(this,hf,t),$t(this,mJ,a),$t(this,m3,l),$t(this,x3,o),$t(this,uJ,c),$t(this,OD,n),$t(this,hJ,d),$t(this,y$,u),$t(this,dJ,r),$t(this,g$,YZe.toDateObject(i)),this.trigger=r.flatMap(p=>p.getElementsToTriggerPopup());for(const p of this.trigger)p.addEventListener("click",pe(this,x$)),p.addEventListener("mouseenter",pe(this,f3e)),p.addEventListener("mouseleave",pe(this,p3e)),p.classList.add("popupTriggerArea");for(const p of r)(m=p.container)==null||m.addEventListener("keydown",pe(this,f$));pe(this,hf).hidden=!0,h&&Kt(this,uh,pNe).call(this)}render(){if(pe(this,oN))return;const t=$t(this,oN,document.createElement("div"));if(t.className="popup",pe(this,OD)){const i=t.style.outlineColor=ko.makeHexColor(...pe(this,OD));CSS.supports("background-color","color-mix(in srgb, red 30%, white)")?t.style.backgroundColor=`color-mix(in srgb, ${i} 30%, white)`:t.style.backgroundColor=ko.makeHexColor(...pe(this,OD).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}=pe(this,mJ),t.append(n),pe(this,g$)){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:pe(this,g$).valueOf()})),n.append(i)}const a=pe(this,uh,mNe);if(a)CUt.render({xfaHtml:a,intent:"richText",div:t}),t.lastChild.classList.add("richText","popupContent");else{const i=this._formatContents(pe(this,m3));t.append(i)}pe(this,hf).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)&&Kt(this,bJ,P$e).call(this)}),!r.popupRef&&this.hasPopupData?this._createPopup():a.classList.add("popupTriggerArea"),n.append(a),n}getElementsToTriggerPopup(){return pe(this,vJ)}addHighlightArea(){this.container.classList.add("highlightArea")}}vJ=new WeakMap,bJ=new WeakSet,P$e=function(){var n;(n=this.downloadManager)==null||n.openOrDownloadData(this.content,this.filename)};var _J,BD,$D,wJ,UO,BUt,I$e;class RMn{constructor({div:t,accessibilityManager:n,annotationCanvasMap:r,annotationEditorUIManager:a,page:i,viewport:l,structTreeLayer:o}){rs(this,UO);rs(this,_J,null);rs(this,BD,null);rs(this,$D,new Map);rs(this,wJ,null);this.div=t,$t(this,_J,n),$t(this,BD,r),$t(this,wJ,o||null),this.page=i,this.viewport=l,this.zIndex=0,this._annotationEditorUIManager=a}hasEditableAnnotations(){return pe(this,$D).size>0}async render(t){var l;const{annotations:n}=t,r=this.div;OO(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 sXe,annotationStorage:t.annotationStorage||new XZe,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===eg.POPUP;if(c){const h=a.get(o.id);if(!h)continue;i.elements=h}else{const{width:h,height:m}=Q3(o.rect);if(h<=0||m<=0)continue}i.data=o;const d=vMn.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 Kt(this,UO,BUt).call(this,u,o.id),d._isEditable&&(pe(this,$D).set(d.data.id,d),(l=this._annotationEditorUIManager)==null||l.renderAnnotationElement(d))}Kt(this,UO,I$e).call(this)}update({viewport:t}){const n=this.div;this.viewport=t,OO(n,{rotation:t.rotation}),Kt(this,UO,I$e).call(this),n.hidden=!1}getEditableAnnotations(){return Array.from(pe(this,$D).values())}getEditableAnnotation(t){return pe(this,$D).get(t)}}_J=new WeakMap,BD=new WeakMap,$D=new WeakMap,wJ=new WeakMap,UO=new WeakSet,BUt=async function(t,n){var l,o;const r=t.firstChild||t,a=r.id=`${GZe}${n}`,i=await((l=pe(this,wJ))==null?void 0:l.getAriaAttributes(a));if(i)for(const[c,d]of i)r.setAttribute(c,d);this.div.append(t),(o=pe(this,_J))==null||o.moveElementInDOM(this.div,t,r,!1)},I$e=function(){if(!pe(this,BD))return;const t=this.div;for(const[n,r]of pe(this,BD)){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)}pe(this,BD).clear()};const hae=/\r\n?|\n/g;var lN,T_,jJ,UD,M_,$x,$Ut,UUt,qUt,xNe,sC,gNe,yNe,VUt,R$e,HUt;const qh=class qh extends Vu{constructor(n){super({...n,name:"freeTextEditor"});rs(this,$x);rs(this,lN);rs(this,T_,"");rs(this,jJ,`${this.id}-editor`);rs(this,UD,null);rs(this,M_);$t(this,lN,n.color||qh._defaultColor||Vu._defaultLineColor),$t(this,M_,n.fontSize||qh._defaultFontSize)}static get _keyboardManager(){const n=qh.prototype,r=l=>l.isEmpty(),a=FO.TRANSLATE_SMALL,i=FO.TRANSLATE_BIG;return xd(this,"_keyboardManager",new pte([[["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){Vu.initialize(n,r);const a=getComputedStyle(document.documentElement);this._internalPadding=parseFloat(a.getPropertyValue("--freetext-padding"))}static updateDefaultParams(n,r){switch(n){case zl.FREETEXT_SIZE:qh._defaultFontSize=r;break;case zl.FREETEXT_COLOR:qh._defaultColor=r;break}}updateParams(n,r){switch(n){case zl.FREETEXT_SIZE:Kt(this,$x,$Ut).call(this,r);break;case zl.FREETEXT_COLOR:Kt(this,$x,UUt).call(this,r);break}}static get defaultPropertiesToUpdate(){return[[zl.FREETEXT_SIZE,qh._defaultFontSize],[zl.FREETEXT_COLOR,qh._defaultColor||Vu._defaultLineColor]]}get propertiesToUpdate(){return[[zl.FREETEXT_SIZE,pe(this,M_)],[zl.FREETEXT_COLOR,pe(this,lN)]]}_translateEmpty(n,r){this._uiManager.translateSelectedEditors(n,r,!0)}getInitialTranslation(){const n=this.parentScale;return[-qh._internalPadding*n,-(qh._internalPadding+pe(this,M_))*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(hc.FREETEXT),super.enableEditMode(),this.overlayDiv.classList.remove("enabled"),this.editorDiv.contentEditable=!0,this._isDraggable=!1,this.div.removeAttribute("aria-activedescendant"),$t(this,UD,new AbortController);const n=this._uiManager.combinedSignal(pe(this,UD));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",pe(this,jJ)),this._isDraggable=!0,(n=pe(this,UD))==null||n.abort(),$t(this,UD,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=pe(this,T_),r=$t(this,T_,Kt(this,$x,qUt).call(this).trimEnd());if(n===r)return;const a=i=>{if($t(this,T_,i),!i){this.remove();return}Kt(this,$x,yNe).call(this),this._uiManager.rebuild(this),Kt(this,$x,xNe).call(this)};this.addCommands({cmd:()=>{a(r)},undo:()=>{a(n)},mustExec:!1}),Kt(this,$x,xNe).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){qh._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",pe(this,jJ)),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(${pe(this,M_)}px * var(--scale-factor))`,a.color=pe(this,lN),this.div.append(this.editorDiv),this.overlayDiv=document.createElement("div"),this.overlayDiv.classList.add("overlay","enabled"),this.div.append(this.overlayDiv),T4e(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 x,g;switch(this.rotation){case 0:x=n+(o[0]-m)/u,g=r+this.height-(o[1]-p)/h;break;case 90:x=n+(o[0]-m)/u,g=r-(o[1]-p)/h,[c,d]=[d,-c];break;case 180:x=n-this.width+(o[0]-m)/u,g=r-(o[1]-p)/h,[c,d]=[-c,-d];break;case 270:x=n+(o[0]-m-this.height*h)/u,g=r+(o[1]-p-this.width*u)/h,[c,d]=[-d,c];break}this.setAt(x*i,g*l,c,d)}else this.setAt(n*i,r*l,this.width*i,this.height*l);Kt(this,$x,yNe).call(this),this._isDraggable=!0,this.editorDiv.contentEditable=!1}else this._isDraggable=!1,this.editorDiv.contentEditable=!0;return this.div}editorDivPaste(n){var x,g,y;const r=n.clipboardData||window.clipboardData,{types:a}=r;if(a.length===1&&a[0]==="text/plain")return;n.preventDefault();const i=Kt(x=qh,sC,R$e).call(x,r.getData("text")||"").replaceAll(hae,` `);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 b=c.parentElement;if(h.push(c.nodeValue.slice(d).replaceAll(hae,"")),b!==this.editorDiv){let v=u;for(const N of this.editorDiv.childNodes){if(N===b){v=h;continue}v.push(Kt(g=qh,sC,gNe).call(g,N))}}u.push(c.nodeValue.slice(0,d).replaceAll(hae,""))}else if(c===this.editorDiv){let b=u,v=0;for(const N of this.editorDiv.childNodes)v++===d&&(b=h),b.push(Kt(y=qh,sC,gNe).call(y,N))}$t(this,T_,`${u.join(` `)}${i}${h.join(` `)}`),Kt(this,$x,yNe).call(this);const m=new Range;let p=u.reduce((b,v)=>b+v.length,0);for(const{firstChild:b}of this.editorDiv.childNodes)if(b.nodeType===Node.TEXT_NODE){const v=b.nodeValue.length;if(p<=v){m.setStart(b,p),m.setEnd(b,p);break}p-=v}l.removeAllRanges(),l.addRange(m)}get contentDiv(){return this.editorDiv}static async deserialize(n,r,a){var o;let i=null;if(n instanceof RUt){const{data:{defaultAppearanceData:{fontSize:c,fontColor:d},rect:u,rotation:h,id:m,popupRef:p},textContent:x,textPosition:g,parent:{page:{pageNumber:y}}}=n;if(!x||x.length===0)return null;i=n={annotationType:hc.FREETEXT,color:Array.from(d),fontSize:c,value:x.join(` `),position:g,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,M_,n.fontSize),$t(l,lN,ko.makeHexColor(...n.color)),$t(l,T_,Kt(o=qh,sC,R$e).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=qh._internalPadding*this.parentScale,a=this.getRect(r,r),i=Vu._colorManager.convert(this.isAttachedToDOM?getComputedStyle(this.editorDiv).color:pe(this,lN)),l={annotationType:hc.FREETEXT,color:i,fontSize:pe(this,M_),value:Kt(this,$x,VUt).call(this),pageIndex:this.pageIndex,rect:a,rotation:this.rotation,structTreeParentId:this._structTreeParentId};return n?l:this.annotationElementId&&!Kt(this,$x,HUt).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(${pe(this,M_)}px * var(--scale-factor))`,a.color=pe(this,lN),r.replaceChildren();for(const l of pe(this,T_).split(` `)){const o=document.createElement("div");o.append(l?document.createTextNode(l):document.createElement("br")),r.append(o)}const i=qh._internalPadding*this.parentScale;return n.updateEdited({rect:this.getRect(i,i),popupContent:pe(this,T_)}),r}resetAnnotationElement(n){super.resetAnnotationElement(n),n.resetEdited()}};lN=new WeakMap,T_=new WeakMap,jJ=new WeakMap,UD=new WeakMap,M_=new WeakMap,$x=new WeakSet,$Ut=function(n){const r=i=>{this.editorDiv.style.fontSize=`calc(${i}px * var(--scale-factor))`,this.translate(0,-(i-pe(this,M_))*this.parentScale),$t(this,M_,i),Kt(this,$x,xNe).call(this)},a=pe(this,M_);this.addCommands({cmd:r.bind(this,n),undo:r.bind(this,a),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:zl.FREETEXT_SIZE,overwriteIfSameType:!0,keepUndo:!0})},UUt=function(n){const r=i=>{$t(this,lN,this.editorDiv.style.color=i)},a=pe(this,lN);this.addCommands({cmd:r.bind(this,n),undo:r.bind(this,a),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:zl.FREETEXT_COLOR,overwriteIfSameType:!0,keepUndo:!0})},qUt=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(Kt(a=qh,sC,gNe).call(a,i)),r=i);return n.join(` `)},xNe=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()},sC=new WeakSet,gNe=function(n){return(n.nodeType===Node.TEXT_NODE?n.nodeValue:n.innerText).replaceAll(hae,"")},yNe=function(){if(this.editorDiv.replaceChildren(),!!pe(this,T_))for(const n of pe(this,T_).split(` `)){const r=document.createElement("div");r.append(n?document.createTextNode(n):document.createElement("br")),this.editorDiv.append(r)}},VUt=function(){return pe(this,T_).replaceAll(" "," ")},R$e=function(n){return n.replaceAll(" "," ")},HUt=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},rs(qh,sC),Lr(qh,"_freeTextDefaultContent",""),Lr(qh,"_internalPadding",0),Lr(qh,"_defaultColor",null),Lr(qh,"_defaultFontSize",10),Lr(qh,"_type","freetext"),Lr(qh,"_editorType",hc.FREETEXT);let D$e=qh;class GUt{toSVGPath(){km("Abstract method `toSVGPath` must be implemented.")}get box(){km("Abstract getter `box` must be implemented.")}serialize(t,n){km("Abstract method `serialize` must be implemented.")}get classNamesForDrawing(){km("Abstract getter `classNamesForDrawing` must be implemented.")}get classNamesForOutlining(){km("Abstract getter `classNamesForOutlining` must be implemented.")}get mustRemoveSelfIntersections(){return!1}}var L_,cN,v$,b$,jS,Bc,qD,VD,NJ,kJ,_$,w$,DE,SJ,x3e,g3e,bg,VW,WUt,KUt,YUt,ZUt,XUt,QUt;const K4=class K4{constructor({x:t,y:n},r,a,i,l,o=0){rs(this,bg);rs(this,L_);rs(this,cN,[]);rs(this,v$);rs(this,b$);rs(this,jS,[]);rs(this,Bc,new Float64Array(18));rs(this,qD);rs(this,VD);rs(this,NJ);rs(this,kJ);rs(this,_$);rs(this,w$);rs(this,DE,[]);$t(this,L_,r),$t(this,w$,i*a),$t(this,b$,l),pe(this,Bc).set([NaN,NaN,NaN,NaN,t,n],6),$t(this,v$,o),$t(this,kJ,pe(K4,SJ)*a),$t(this,NJ,pe(K4,g3e)*a),$t(this,_$,a),pe(this,DE).push(t,n)}isEmpty(){return isNaN(pe(this,Bc)[8])}add({x:t,y:n}){var I;$t(this,qD,t),$t(this,VD,n);const[r,a,i,l]=pe(this,L_);let[o,c,d,u]=pe(this,Bc).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 Kt(this,bg,KUt).call(this,r),r.join(" ")}newFreeDrawOutline(t,n,r,a,i,l){return new JUt(t,n,r,a,i,l)}getOutlines(){var h;const t=pe(this,jS),n=pe(this,cN),r=pe(this,Bc),[a,i,l,o]=pe(this,L_),c=new Float64Array((((h=pe(this,DE))==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 Kt(this,bg,XUt).call(this,d,u),this.newFreeDrawOutline(d,c,pe(this,L_),pe(this,_$),pe(this,v$),pe(this,b$))}};L_=new WeakMap,cN=new WeakMap,v$=new WeakMap,b$=new WeakMap,jS=new WeakMap,Bc=new WeakMap,qD=new WeakMap,VD=new WeakMap,NJ=new WeakMap,kJ=new WeakMap,_$=new WeakMap,w$=new WeakMap,DE=new WeakMap,SJ=new WeakMap,x3e=new WeakMap,g3e=new WeakMap,bg=new WeakSet,VW=function(){const t=pe(this,Bc).subarray(4,6),n=pe(this,Bc).subarray(16,18),[r,a,i,l]=pe(this,L_);return[(pe(this,qD)+(t[0]-n[0])/2-r)/i,(pe(this,VD)+(t[1]-n[1])/2-a)/l,(pe(this,qD)+(n[0]-t[0])/2-r)/i,(pe(this,VD)+(n[1]-t[1])/2-a)/l]},WUt=function(){const[t,n,r,a]=pe(this,L_),[i,l,o,c]=Kt(this,bg,VW).call(this);return`M${(pe(this,Bc)[2]-t)/r} ${(pe(this,Bc)[3]-n)/a} L${(pe(this,Bc)[4]-t)/r} ${(pe(this,Bc)[5]-n)/a} L${i} ${l} L${o} ${c} L${(pe(this,Bc)[16]-t)/r} ${(pe(this,Bc)[17]-n)/a} L${(pe(this,Bc)[14]-t)/r} ${(pe(this,Bc)[15]-n)/a} Z`},KUt=function(t){const n=pe(this,cN);t.push(`L${n[4]} ${n[5]} Z`)},YUt=function(t){const[n,r,a,i]=pe(this,L_),l=pe(this,Bc).subarray(4,6),o=pe(this,Bc).subarray(16,18),[c,d,u,h]=Kt(this,bg,VW).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}`)},ZUt=function(t){const n=pe(this,Bc),[r,a,i,l]=pe(this,L_),[o,c,d,u]=Kt(this,bg,VW).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,pe(this,L_),pe(this,_$),pe(this,v$),pe(this,b$))},XUt=function(t,n){const r=pe(this,cN);return t.set([NaN,NaN,NaN,NaN,r[4],r[5]],n),n+=6},QUt=function(t,n){const r=pe(this,Bc).subarray(4,6),a=pe(this,Bc).subarray(16,18),[i,l,o,c]=pe(this,L_),[d,u,h,m]=Kt(this,bg,VW).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},rs(K4,SJ,8),rs(K4,x3e,2),rs(K4,g3e,pe(K4,SJ)+pe(K4,x3e));let L4e=K4;var j$,HD,g3,CJ,P_,AJ,Hf,Sb,HW,GW,eqt;class JUt extends GUt{constructor(n,r,a,i,l,o){super();rs(this,Sb);rs(this,j$);rs(this,HD,null);rs(this,g3);rs(this,CJ);rs(this,P_);rs(this,AJ);rs(this,Hf);$t(this,Hf,n),$t(this,P_,r),$t(this,j$,a),$t(this,AJ,i),$t(this,g3,l),$t(this,CJ,o),Kt(this,Sb,eqt).call(this,o);const{x:c,y:d,width:u,height:h}=pe(this,HD);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 pe(this,RE))n[3]?(t.push(...Kt(this,w1,O$e).call(this,n)),Kt(this,w1,sqt).call(this,n)):(Kt(this,w1,nqt).call(this,n),t.push(...Kt(this,w1,O$e).call(this,n)));return Kt(this,w1,tqt).call(this,t)}}EJ=new WeakMap,RE=new WeakMap,dN=new WeakMap,w1=new WeakSet,tqt=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 x;if(r.has(u))x=u;else if(r.has(h))x=h;else break;r.delete(x),[o,c,d,u,h]=x,m!==o&&(i.push(m,p,o,p===c?c:d),m=o),p=p===c?d:c}i.push(m,p)}return new OMn(a,pe(this,EJ))},vNe=function(t){const n=pe(this,dN);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]=pe(this,dN)[a];if(i!==t)break;if(i===t&&l===n){pe(this,dN).splice(a,1);return}}},O$e=function(t){const[n,r,a]=t,i=[[n,r,a]],l=Kt(this,w1,vNe).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 TJ,N$;class OMn extends GUt{constructor(n,r){super();rs(this,TJ);rs(this,N$);$t(this,N$,n),$t(this,TJ,r)}toSVGPath(){const n=[];for(const r of pe(this,N$)){let[a,i]=r;n.push(`M${a} ${i}`);for(let l=2;l-1?($t(this,hb,!0),Kt(this,ic,bNe).call(this,n),Kt(this,ic,p8).call(this)):pe(this,y3)&&($t(this,A$,n.anchorNode),$t(this,DJ,n.anchorOffset),$t(this,RJ,n.focusNode),$t(this,OJ,n.focusOffset),Kt(this,ic,U$e).call(this),Kt(this,ic,p8).call(this),this.rotate(this.rotation))}static get _keyboardManager(){const n=lu.prototype;return xd(this,"_keyboardManager",new pte([[["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:pe(this,hb)?"free_highlight":"highlight",color:this._uiManager.highlightColorNames.get(this.color),thickness:pe(this,yj),methodOfCreation:pe(this,FJ)}}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;Vu.initialize(n,r),lu._defaultColor||(lu._defaultColor=((a=r.highlightColors)==null?void 0:a.values().next().value)||"#fff066")}static updateDefaultParams(n,r){switch(n){case zl.HIGHLIGHT_DEFAULT_COLOR:lu._defaultColor=r;break;case zl.HIGHLIGHT_THICKNESS:lu._defaultThickness=r;break}}translateInPage(n,r){}get toolbarPosition(){return pe(this,T$)}updateParams(n,r){switch(n){case zl.HIGHLIGHT_COLOR:Kt(this,ic,aqt).call(this,r);break;case zl.HIGHLIGHT_THICKNESS:Kt(this,ic,iqt).call(this,r);break}}static get defaultPropertiesToUpdate(){return[[zl.HIGHLIGHT_DEFAULT_COLOR,lu._defaultColor],[zl.HIGHLIGHT_THICKNESS,lu._defaultThickness]]}get propertiesToUpdate(){return[[zl.HIGHLIGHT_COLOR,this.color||lu._defaultColor],[zl.HIGHLIGHT_THICKNESS,pe(this,yj)||lu._defaultThickness],[zl.HIGHLIGHT_FREE,pe(this,hb)]]}async addEditToolbar(){const n=await super.addEditToolbar();return n?(this._uiManager.highlightColors&&($t(this,E$,new P4e({editor:this})),n.addColorPicker(pe(this,E$))),n):null}disableEditing(){super.disableEditing(),this.div.classList.toggle("disabled",!0)}enableEditing(){super.enableEditing(),this.div.classList.toggle("disabled",!1)}fixAndSetPosition(){return super.fixAndSetPosition(Kt(this,ic,WW).call(this))}getBaseTranslation(){return[0,0]}getRect(n,r){return super.getRect(n,r,Kt(this,ic,WW).call(this))}onceAdded(){this.annotationElementId||this.parent.addUndoableEditor(this),this.div.focus()}remove(){Kt(this,ic,q$e).call(this),this._reportTelemetry({action:"deleted"}),super.remove()}rebuild(){this.parent&&(super.rebuild(),this.div!==null&&(Kt(this,ic,p8).call(this),this.isAttachedToDOM||this.parent.add(this)))}setParent(n){var a;let r=!1;this.parent&&!n?Kt(this,ic,q$e).call(this):n&&(Kt(this,ic,p8).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;pe(this,hb)?(n=(n-this.rotation+360)%360,a=Kt(i=lu,Pj,N9).call(i,pe(this,mN).box,n)):a=Kt(l=lu,Pj,N9).call(l,this,n),r.rotate(pe(this,Qy),n),r.rotate(pe(this,ag),n),r.updateBox(pe(this,Qy),a),r.updateBox(pe(this,ag),Kt(o=lu,Pj,N9).call(o,pe(this,gj).box,n))}render(){if(this.div)return this.div;const n=super.render();pe(this,M$)&&(n.setAttribute("aria-label",pe(this,M$)),n.setAttribute("role","mark")),pe(this,hb)?n.classList.add("free"):this.div.addEventListener("keydown",Kt(this,ic,lqt).bind(this),{signal:this._uiManager._signal});const r=$t(this,KD,document.createElement("div"));n.append(r),r.setAttribute("aria-hidden","true"),r.className="internal",r.style.clipPath=pe(this,WD);const[a,i]=this.parentDimensions;return this.setDims(this.width*a,this.height*i),T4e(this,pe(this,KD),["pointerover","pointerleave"]),this.enableEditing(),n}pointerover(){this.isSelected||this.parent.drawLayer.addClass(pe(this,ag),"hovered")}pointerleave(){this.isSelected||this.parent.drawLayer.removeClass(pe(this,ag),"hovered")}_moveCaret(n){switch(this.parent.unselect(this),n){case 0:case 2:Kt(this,ic,_Ne).call(this,!0);break;case 1:case 3:Kt(this,ic,_Ne).call(this,!1);break}}select(){var n,r;super.select(),pe(this,ag)&&((n=this.parent)==null||n.drawLayer.removeClass(pe(this,ag),"hovered"),(r=this.parent)==null||r.drawLayer.addClass(pe(this,ag),"selected"))}unselect(){var n;super.unselect(),pe(this,ag)&&((n=this.parent)==null||n.drawLayer.removeClass(pe(this,ag),"selected"),pe(this,hb)||Kt(this,ic,_Ne).call(this,!1))}get _mustFixPosition(){return!pe(this,hb)}show(n=this._isVisible){super.show(n),this.parent&&(this.parent.drawLayer.show(pe(this,Qy),n),this.parent.drawLayer.show(pe(this,ag),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=g=>{g.preventDefault(),g.stopPropagation()},x=g=>{h.abort(),Kt(this,Pj,hqt).call(this,n,g)};window.addEventListener("blur",x,{signal:m}),window.addEventListener("pointerup",x,{signal:m}),window.addEventListener("pointerdown",p,{capture:!0,passive:!1,signal:m}),window.addEventListener("contextmenu",c2,{signal:m}),a.addEventListener("pointermove",Kt(this,Pj,uqt).bind(this,n),{signal:m}),this._freeHighlight=new F$e({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 g,y,b,v;let i=null;if(n instanceof FUt){const{data:{quadPoints:N,rect:C,rotation:A,id:T,color:P,opacity:M,popupRef:I},parent:{page:{pageNumber:D}}}=n;i=n={annotationType:hc.HIGHLIGHT,color:Array.from(P),opacity:M,quadPoints:N,boxes:null,pageIndex:D-1,rect:C.slice(0),rotation:A,id:T,deleted:!1,popupRef:I}}else if(n instanceof nXe){const{data:{inkLists:N,rect:C,rotation:A,id:T,color:P,borderStyle:{rawWidth:M},popupRef:I},parent:{page:{pageNumber:D}}}=n;i=n={annotationType:hc.HIGHLIGHT,color:Array.from(P),thickness:M,inkLists:N,boxes:null,pageIndex:D-1,rect:C.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=ko.makeHexColor(...l),$t(u,v3,d||1),c&&$t(u,yj,n.thickness),u.annotationElementId=n.id||null,u._initialData=i;const[h,m]=u.pageDimensions,[p,x]=u.pageTranslation;if(o){const N=$t(u,y3,[]);for(let C=0;C=0)$t(this,Qy,r),$t(this,WD,a),this.parent.drawLayer.finalizeLine(r,n),$t(this,ag,this.parent.drawLayer.drawOutline(pe(this,gj)));else if(this.parent){const p=this.parent.viewport.rotation;this.parent.drawLayer.updateLine(pe(this,Qy),n),this.parent.drawLayer.updateBox(pe(this,Qy),Kt(h=lu,Pj,N9).call(h,pe(this,mN).box,(p-this.rotation+360)%360)),this.parent.drawLayer.updateLine(pe(this,ag),pe(this,gj)),this.parent.drawLayer.updateBox(pe(this,ag),Kt(m=lu,Pj,N9).call(m,pe(this,gj).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,x]=this.parentDimensions;this.x=o,this.y=1-l,this.width=c*x/p,this.height=d*p/x;break}case 180:this.x=1-l,this.y=1-o,this.width=c,this.height=d;break;case 270:{const[p,x]=this.parentDimensions;this.x=1-o,this.y=l,this.width=c*x/p,this.height=d*p/x;break}}const{lastPoint:u}=pe(this,gj).box;$t(this,T$,[(u[0]-l)/c,(u[1]-o)/d])},aqt=function(n){const r=(l,o)=>{var c,d,u;this.color=l,(c=this.parent)==null||c.drawLayer.changeColor(pe(this,Qy),l),(d=pe(this,E$))==null||d.updateColor(l),$t(this,v3,o),(u=this.parent)==null||u.drawLayer.changeOpacity(pe(this,Qy),o)},a=this.color,i=pe(this,v3);this.addCommands({cmd:r.bind(this,n,lu._defaultOpacity),undo:r.bind(this,a,i),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:zl.HIGHLIGHT_COLOR,overwriteIfSameType:!0,keepUndo:!0}),this._reportTelemetry({action:"color_changed",color:this._uiManager.highlightColorNames.get(n)},!0)},iqt=function(n){const r=pe(this,yj),a=i=>{$t(this,yj,i),Kt(this,ic,oqt).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:zl.INK_THICKNESS,overwriteIfSameType:!0,keepUndo:!0}),this._reportTelemetry({action:"thickness_changed",thickness:n},!0)},oqt=function(n){if(!pe(this,hb))return;Kt(this,ic,bNe).call(this,{highlightOutlines:pe(this,mN).getNewOutline(n/2)}),this.fixAndSetPosition();const[r,a]=this.parentDimensions;this.setDims(this.width*r,this.height*a)},q$e=function(){pe(this,Qy)===null||!this.parent||(this.parent.drawLayer.remove(pe(this,Qy)),$t(this,Qy,null),this.parent.drawLayer.remove(pe(this,ag)),$t(this,ag,null))},p8=function(n=this.parent){pe(this,Qy)===null&&({id:Xg(this,Qy)._,clipPathId:Xg(this,WD)._}=n.drawLayer.draw(pe(this,mN),this.color,pe(this,v3)),$t(this,ag,n.drawLayer.drawOutline(pe(this,gj))),pe(this,KD)&&(pe(this,KD).style.clipPath=pe(this,WD)))},Pj=new WeakSet,N9=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}},lqt=function(n){lu._keyboardManager.exec(this,n)},_Ne=function(n){if(!pe(this,A$))return;const r=window.getSelection();n?r.setPosition(pe(this,A$),pe(this,DJ)):r.setPosition(pe(this,RJ),pe(this,OJ))},WW=function(){return pe(this,hb)?this.rotation:0},cqt=function(){if(pe(this,hb))return null;const[n,r]=this.pageDimensions,[a,i]=this.pageTranslation,l=pe(this,y3),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,x=(1-u-m)*r+i;o[c]=o[c+4]=p,o[c+1]=o[c+3]=x,o[c+2]=o[c+6]=p+h*n,o[c+5]=o[c+7]=x+m*r,c+=8}return o},dqt=function(n){return pe(this,mN).serialize(n,Kt(this,ic,WW).call(this))},uqt=function(n,r){this._freeHighlight.add(r)&&n.drawLayer.updatePath(this._freeHighlightId,this._freeHighlight)},hqt=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=""},mqt=function(n){const{color:r}=this._initialData;return n.color.some((a,i)=>a!==r[i])},rs(lu,Pj),Lr(lu,"_defaultColor",null),Lr(lu,"_defaultOpacity",1),Lr(lu,"_defaultThickness",12),Lr(lu,"_type","highlight"),Lr(lu,"_editorType",hc.HIGHLIGHT),Lr(lu,"_freeHighlightId",-1),Lr(lu,"_freeHighlight",null),Lr(lu,"_freeHighlightClipId","");let I4e=lu;var YD,ZD,NS,b3,vj,XD,QD,JD,_3,L$,eR,tR,FE,fi,pqt,fqt,xqt,gqt,H$e,yqt,G$e,vqt,bqt,_qt,wqt,jqt,f8,W$e,K$e,Y$e,wNe,jNe,k9,Z$e,NNe,vC,Nqt,X$e,kqt,Sqt,Q$e,kNe,KW;const wp=class wp extends Vu{constructor(n){super({...n,name:"inkEditor"});rs(this,fi);rs(this,YD,0);rs(this,ZD,0);rs(this,NS,null);rs(this,b3,new Path2D);rs(this,vj,!1);rs(this,XD,null);rs(this,QD,!1);rs(this,JD,!1);rs(this,_3,null);rs(this,L$,null);rs(this,eR,0);rs(this,tR,0);rs(this,FE,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){Vu.initialize(n,r)}static updateDefaultParams(n,r){switch(n){case zl.INK_THICKNESS:wp._defaultThickness=r;break;case zl.INK_COLOR:wp._defaultColor=r;break;case zl.INK_OPACITY:wp._defaultOpacity=r/100;break}}updateParams(n,r){switch(n){case zl.INK_THICKNESS:Kt(this,fi,pqt).call(this,r);break;case zl.INK_COLOR:Kt(this,fi,fqt).call(this,r);break;case zl.INK_OPACITY:Kt(this,fi,xqt).call(this,r);break}}static get defaultPropertiesToUpdate(){return[[zl.INK_THICKNESS,wp._defaultThickness],[zl.INK_COLOR,wp._defaultColor||Vu._defaultLineColor],[zl.INK_OPACITY,Math.round(wp._defaultOpacity*100)]]}get propertiesToUpdate(){return[[zl.INK_THICKNESS,this.thickness||wp._defaultThickness],[zl.INK_COLOR,this.color||wp._defaultColor||Vu._defaultLineColor],[zl.INK_OPACITY,Math.round(100*(this.opacity??wp._defaultOpacity))]]}rebuild(){this.parent&&(super.rebuild(),this.div!==null&&(this.canvas||(Kt(this,fi,wNe).call(this),Kt(this,fi,jNe).call(this)),this.isAttachedToDOM||(this.parent.add(this),Kt(this,fi,k9).call(this)),Kt(this,fi,KW).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,pe(this,NS)&&(clearTimeout(pe(this,NS)),$t(this,NS,null)),(n=pe(this,_3))==null||n.disconnect(),$t(this,_3,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(){pe(this,vj)||this.canvas===null||(super.enableEditMode(),this._isDraggable=!1,Kt(this,fi,W$e).call(this))}disableEditMode(){!this.isInEditMode()||this.canvas===null||(super.disableEditMode(),this._isDraggable=!this.isEmpty(),this.div.classList.remove("editing"),Kt(this,fi,K$e).call(this))}onceAdded(){this._isDraggable=!this.isEmpty()}isEmpty(){return this.paths.length===0||this.paths.length===1&&this.paths[0].length===0}commit(){pe(this,vj)||(super.commit(),this.isEditing=!1,this.disableEditMode(),this.setInForeground(),$t(this,vj,!0),this.div.classList.add("disabled"),Kt(this,fi,KW).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()||pe(this,vj)||(this.setInForeground(),n.preventDefault(),this.div.contains(document.activeElement)||this.div.focus({preventScroll:!0}),Kt(this,fi,yqt).call(this,n.offsetX,n.offsetY))}canvasPointermove(n){n.preventDefault(),Kt(this,fi,G$e).call(this,n.offsetX,n.offsetY)}canvasPointerup(n){n.preventDefault(),Kt(this,fi,Y$e).call(this,n)}canvasPointerleave(n){Kt(this,fi,Y$e).call(this,n)}get isResizable(){return!this.isEmpty()&&pe(this,vj)}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]=Kt(this,fi,gqt).call(this);if(this.setAt(a,i,0,0),this.setDims(l,o),Kt(this,fi,wNe).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,JD,!0),Kt(this,fi,k9).call(this),this.setDims(this.width*c,this.height*d),Kt(this,fi,f8).call(this),this.div.classList.add("disabled")}else this.div.classList.add("editing"),this.enableEditMode();return Kt(this,fi,jNe).call(this),this.div}setDimensions(n,r){const a=Math.round(n),i=Math.round(r);if(pe(this,eR)===a&&pe(this,tR)===i)return;$t(this,eR,a),$t(this,tR,i),this.canvas.style.visibility="hidden";const[l,o]=this.parentDimensions;this.width=n/l,this.height=r/o,this.fixAndSetPosition(),pe(this,vj)&&Kt(this,fi,Z$e).call(this,n,r),Kt(this,fi,k9).call(this),Kt(this,fi,f8).call(this),this.canvas.style.visibility="visible",this.fixDims()}static async deserialize(n,r,a){var y,b,v;if(n instanceof nXe)return null;const i=await super.deserialize(n,r,a);i.thickness=n.thickness,i.color=ko.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,vj,!0),$t(i,eR,Math.round(c)),$t(i,tR,Math.round(d));const{paths:m,rect:p,rotation:x}=n;for(let{bezier:N}of m){N=Kt(y=wp,vC,kqt).call(y,N,p,x);const C=[];i.paths.push(C);let A=u*(N[0]-h),T=u*(N[1]-h);for(let M=2,I=N.length;M{this.thickness=i,Kt(this,fi,KW).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:zl.INK_THICKNESS,overwriteIfSameType:!0,keepUndo:!0})},fqt=function(n){const r=i=>{this.color=i,Kt(this,fi,f8).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:zl.INK_COLOR,overwriteIfSameType:!0,keepUndo:!0})},xqt=function(n){const r=i=>{this.opacity=i,Kt(this,fi,f8).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:zl.INK_OPACITY,overwriteIfSameType:!0,keepUndo:!0})},gqt=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]}},H$e=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}${i6n(a)}`},yqt=function(n,r){this.canvas.addEventListener("contextmenu",c2,{signal:this._uiManager._signal}),Kt(this,fi,K$e).call(this),$t(this,XD,new AbortController);const a=this._uiManager.combinedSignal(pe(this,XD));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,pe(this,JD)||($t(this,JD,!0),Kt(this,fi,k9).call(this),this.thickness||(this.thickness=wp._defaultThickness),this.color||(this.color=wp._defaultColor||Vu._defaultLineColor),this.opacity??(this.opacity=wp._defaultOpacity)),this.currentPath.push([n,r]),$t(this,QD,!1),Kt(this,fi,H$e).call(this),$t(this,FE,()=>{Kt(this,fi,_qt).call(this),pe(this,FE)&&window.requestAnimationFrame(pe(this,FE))}),window.requestAnimationFrame(pe(this,FE))},G$e=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=pe(this,b3);if(l.push([n,r]),$t(this,QD,!0),l.length<=2){o.moveTo(...l[0]),o.lineTo(n,r);return}l.length===3&&($t(this,b3,o=new Path2D),o.moveTo(...l[0])),Kt(this,fi,wqt).call(this,o,...l.at(-3),...l.at(-2),n,r)},vqt=function(){if(this.currentPath.length===0)return;const n=this.currentPath.at(-1);pe(this,b3).lineTo(...n)},bqt=function(n,r){$t(this,FE,null),n=Math.min(Math.max(n,0),this.canvas.width),r=Math.min(Math.max(r,0),this.canvas.height),Kt(this,fi,G$e).call(this,n,r),Kt(this,fi,vqt).call(this);let a;if(this.currentPath.length!==1)a=Kt(this,fi,jqt).call(this);else{const d=[n,r];a=[[d,d.slice(),d.slice(),d]]}const i=pe(this,b3),l=this.currentPath;this.currentPath=[],$t(this,b3,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||(Kt(this,fi,wNe).call(this),Kt(this,fi,jNe).call(this)),Kt(this,fi,KW).call(this))};this.addCommands({cmd:o,undo:c,mustExec:!0})},_qt=function(){if(!pe(this,QD))return;$t(this,QD,!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(pe(this,b3)),l.restore()},wqt=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)},jqt=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,NS,null),this.canvas.removeEventListener("contextmenu",c2)},10)),Kt(this,fi,bqt).call(this,n.offsetX,n.offsetY),this.addToAnnotationStorage(),this.setInBackground()},wNe=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")},jNe=function(){$t(this,_3,new ResizeObserver(n=>{const r=n[0].contentRect;r.width&&r.height&&this.setDimensions(r.width,r.height)})),pe(this,_3).observe(this.div),this._uiManager._signal.addEventListener("abort",()=>{var n;(n=pe(this,_3))==null||n.disconnect(),$t(this,_3,null)},{once:!0})},k9=function(){if(!pe(this,JD))return;const[n,r]=this.parentDimensions;this.canvas.width=Math.ceil(this.width*n),this.canvas.height=Math.ceil(this.height*r),Kt(this,fi,NNe).call(this)},Z$e=function(n,r){const a=Kt(this,fi,kNe).call(this),i=(n-a)/pe(this,ZD),l=(r-a)/pe(this,YD);this.scaleFactor=Math.min(i,l)},NNe=function(){const n=Kt(this,fi,kNe).call(this)/2;this.ctx.setTransform(this.scaleFactor,0,0,this.scaleFactor,this.translationX*this.scaleFactor+n,this.translationY*this.scaleFactor+n)},vC=new WeakSet,Nqt=function(n){const r=new Path2D;for(let a=0,i=n.length;a`image/${r}`))}static get supportedTypesStr(){return xd(this,"supportedTypesStr",this.supportedTypes.join(","))}static isHandlingMimeForPasting(n){return this.supportedTypes.includes(n)}static paste(n,r){r.pasteEditor(hc.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;pe(this,ty)&&($t(this,Np,null),this._uiManager.imageManager.deleteId(pe(this,ty)),(n=pe(this,kS))==null||n.remove(),$t(this,kS,null),(r=pe(this,j3))==null||r.disconnect(),$t(this,j3,null),pe(this,SS)&&(clearTimeout(pe(this,SS)),$t(this,SS,null))),super.remove()}rebuild(){if(!this.parent){pe(this,ty)&&Kt(this,rd,SNe).call(this);return}super.rebuild(),this.div!==null&&(pe(this,ty)&&pe(this,kS)===null&&Kt(this,rd,SNe).call(this),this.isAttachedToDOM||this.parent.add(this))}onceAdded(){this._isDraggable=!0,this.div.focus()}isEmpty(){return!(pe(this,zE)||pe(this,Np)||pe(this,w3)||pe(this,BE)||pe(this,ty))}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(),pe(this,Np)?Kt(this,rd,eUe).call(this):Kt(this,rd,SNe).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}=pe(this,Np),o=new ZBe;let c=pe(this,Np),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 x=h.width=Math.ceil(d*o.sx),g=h.height=Math.ceil(u*o.sy);pe(this,I_)||(c=Kt(this,rd,CNe).call(this,x,g));const y=h.getContext("2d");y.filter=this._uiManager.hcmFilter;let b="white",v="#cfcfd8";this._uiManager.hcmFilter!=="none"?v="black":(p=window.matchMedia)!=null&&p.call(window,"(prefers-color-scheme: dark)").matches&&(b="#8f8f9d",v="#42414d");const N=15,C=N*o.sx,A=N*o.sy,T=new OffscreenCanvas(C*2,A*2),P=T.getContext("2d");P.fillStyle=b,P.fillRect(0,0,C*2,A*2),P.fillStyle=v,P.fillRect(0,0,C,A),P.fillRect(C,A,C,A),y.fillStyle=y.createPattern(T,"repeat"),y.fillRect(0,0,x,g),y.drawImage(c,0,0,c.width,c.height,0,0,x,g)}let m=null;if(a){let x,g;if(o.symmetric&&c.widthn||l>n){const v=Math.min(n/i,n/l);x=Math.floor(i*v),g=Math.floor(l*v),pe(this,I_)||(c=Kt(this,rd,CNe).call(this,x,g))}const b=new OffscreenCanvas(x,g).getContext("2d",{willReadFrequently:!0});b.drawImage(c,0,0,c.width,c.height,0,0,x,g),m={width:x,height:g,data:b.getImageData(0,0,x,g).data}}return{canvas:h,width:d,height:u,imageData:m}}getImageForAltText(){return pe(this,kS)}static async deserialize(n,r,a){var g;let i=null;if(n instanceof zUt){const{data:{rect:y,rotation:b,id:v,structParent:N,popupRef:C},container:A,parent:{page:{pageNumber:T}}}=n,P=A.querySelector("canvas"),M=a.imageManager.getFromCanvas(A.id,P);P.remove();const I=((g=await r._structTree.getAriaAttributes(`${GZe}${v}`))==null?void 0:g.get("aria-label"))||"";i=n={annotationType:hc.STAMP,bitmapId:M.id,bitmap:M.bitmap,pageIndex:T-1,rect:y.slice(0),rotation:b,id:v,deleted:!1,accessibilityData:{decorative:!1,altText:I},isSvg:!1,structParent:N,popupRef:C}}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,ty,u),c&&$t(l,Np,c)):$t(l,w3,d),$t(l,I_,h);const[p,x]=l.pageDimensions;return l.width=(o[2]-o[0])/p,l.height=(o[3]-o[1])/x,l.annotationElementId=n.id||null,m&&(l.altTextData=m),l._initialData=i,$t(l,I$,!!i),l}serialize(n=!1,r=null){if(this.isEmpty())return null;if(this.deleted)return this.serializeDeleted();const a={annotationType:hc.STAMP,bitmapId:pe(this,ty),pageIndex:this.pageIndex,rect:this.getRect(0,0),rotation:this.rotation,isSvg:pe(this,I_),structTreeParentId:this._structTreeParentId};if(n)return a.bitmapUrl=Kt(this,rd,ANe).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=Kt(this,rd,Eqt).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=pe(this,I_)?(a.rect[2]-a.rect[0])*(a.rect[3]-a.rect[1]):null;if(!r.stamps.has(pe(this,ty)))r.stamps.set(pe(this,ty),{area:o,serialized:a}),a.bitmap=Kt(this,rd,ANe).call(this,!1);else if(pe(this,I_)){const c=r.stamps.get(pe(this,ty));o>c.area&&(c.area=o,c.serialized.bitmap.close(),c.serialized.bitmap=Kt(this,rd,ANe).call(this,!1))}return a}renderAnnotationElement(n){return n.updateEdited({rect:this.getRect(0,0)}),null}};Np=new WeakMap,ty=new WeakMap,zE=new WeakMap,w3=new WeakMap,BE=new WeakMap,P$=new WeakMap,kS=new WeakMap,j3=new WeakMap,SS=new WeakMap,I_=new WeakMap,I$=new WeakMap,rd=new WeakSet,YW=function(n,r=!1){if(!n){this.remove();return}$t(this,Np,n.bitmap),r||($t(this,ty,n.id),$t(this,I_,n.isSvg)),n.file&&$t(this,P$,n.file.name),Kt(this,rd,eUe).call(this)},ZW=function(){if($t(this,zE,null),this._uiManager.enableWaiting(!1),!!pe(this,kS)){if(this._uiManager.useNewAltTextWhenAddingImage&&this._uiManager.useNewAltTextFlow&&pe(this,Np)){this._editToolbar.hide(),this._uiManager.editAltText(this,!0);return}if(!this._uiManager.useNewAltTextWhenAddingImage&&this._uiManager.useNewAltTextFlow&&pe(this,Np)){this._reportTelemetry({action:"pdfjs.image.image_added",data:{alt_text_modal:!1,alt_text_type:"empty"}});try{this.mlGuessAltText()}catch{}}this.div.focus()}},SNe=function(){if(pe(this,ty)){this._uiManager.enableWaiting(!0),this._uiManager.imageManager.getFromId(pe(this,ty)).then(a=>Kt(this,rd,YW).call(this,a,!0)).finally(()=>Kt(this,rd,ZW).call(this));return}if(pe(this,w3)){const a=pe(this,w3);$t(this,w3,null),this._uiManager.enableWaiting(!0),$t(this,zE,this._uiManager.imageManager.getFromUrl(a).then(i=>Kt(this,rd,YW).call(this,i)).finally(()=>Kt(this,rd,ZW).call(this)));return}if(pe(this,BE)){const a=pe(this,BE);$t(this,BE,null),this._uiManager.enableWaiting(!0),$t(this,zE,this._uiManager.imageManager.getFromFile(a).then(i=>Kt(this,rd,YW).call(this,i)).finally(()=>Kt(this,rd,ZW).call(this)));return}const n=document.createElement("input");n.type="file",n.accept=uZ.supportedTypesStr;const r=this._uiManager._signal;$t(this,zE,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}}),Kt(this,rd,YW).call(this,i)}a()},{signal:r}),n.addEventListener("cancel",()=>{this.remove(),a()},{signal:r})}).finally(()=>Kt(this,rd,ZW).call(this))),n.click()},eUe=function(){const{div:n}=this;let{width:r,height:a}=pe(this,Np);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,kS,document.createElement("canvas"));u.setAttribute("role","img"),this.addContainer(u),(!this._uiManager.useNewAltTextWhenAddingImage||!this._uiManager.useNewAltTextFlow||this.annotationElementId)&&(n.hidden=!1),Kt(this,rd,tUe).call(this,r,a),Kt(this,rd,Aqt).call(this),pe(this,I$)||(this.parent.addUndoableEditor(this),$t(this,I$,!0)),this._reportTelemetry({action:"inserted_image"}),pe(this,P$)&&u.setAttribute("aria-label",pe(this,P$))},Cqt=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,pe(this,SS)!==null&&clearTimeout(pe(this,SS)),$t(this,SS,setTimeout(()=>{$t(this,SS,null),Kt(this,rd,tUe).call(this,n,r)},200))},CNe=function(n,r){const{width:a,height:i}=pe(this,Np);let l=a,o=i,c=pe(this,Np);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},tUe=function(n,r){const a=new ZBe,i=Math.ceil(n*a.sx),l=Math.ceil(r*a.sy),o=pe(this,kS);if(!o||o.width===i&&o.height===l)return;o.width=i,o.height=l;const c=pe(this,I_)?pe(this,Np):Kt(this,rd,CNe).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)},ANe=function(n){if(n){if(pe(this,I_)){const i=this._uiManager.imageManager.getSvgUrl(pe(this,ty));if(i)return i}const r=document.createElement("canvas");return{width:r.width,height:r.height}=pe(this,Np),r.getContext("2d").drawImage(pe(this,Np),0,0),r.toDataURL()}if(pe(this,I_)){const[r,a]=this.pageDimensions,i=Math.round(this.width*r*m6.PDF_TO_CSS_UNITS),l=Math.round(this.height*a*m6.PDF_TO_CSS_UNITS),o=new OffscreenCanvas(i,l);return o.getContext("2d").drawImage(pe(this,Np),0,0,pe(this,Np).width,pe(this,Np).height,0,0,i,l),o.transferToImageBitmap()}return structuredClone(pe(this,Np))},Aqt=function(){this._uiManager._signal&&($t(this,j3,new ResizeObserver(n=>{const r=n[0].contentRect;r.width&&r.height&&Kt(this,rd,Cqt).call(this,r.width,r.height)})),pe(this,j3).observe(this.div),this._uiManager._signal.addEventListener("abort",()=>{var n;(n=pe(this,j3))==null||n.disconnect(),$t(this,j3,null)},{once:!0}))},Eqt=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(uZ,"_type","stamp"),Lr(uZ,"_editorType",hc.STAMP);let J$e=uZ;var sR,D$,CS,$E,N3,D_,UE,R$,O$,Jy,k3,Uo,qE,wy,Tqt,nUe,rUe,aUe,ENe;const Z2=class Z2{constructor({uiManager:t,pageIndex:n,div:r,structTreeLayer:a,accessibilityManager:i,annotationLayer:l,drawLayer:o,textLayer:c,viewport:d,l10n:u}){rs(this,wy);rs(this,sR);rs(this,D$,!1);rs(this,CS,null);rs(this,$E,null);rs(this,N3,null);rs(this,D_,new Map);rs(this,UE,!1);rs(this,R$,!1);rs(this,O$,!1);rs(this,Jy,null);rs(this,k3,null);rs(this,Uo);const h=[...pe(Z2,qE).values()];if(!Z2._initialized){Z2._initialized=!0;for(const m of h)m.initialize(u,t)}t.registerEditorTypes(h),$t(this,Uo,t),this.pageIndex=n,this.div=r,$t(this,sR,i),$t(this,CS,l),this.viewport=d,$t(this,Jy,c),this.drawLayer=o,this._structTree=a,pe(this,Uo).addLayer(this)}get isEmpty(){return pe(this,D_).size===0}get isInvisible(){return this.isEmpty&&pe(this,Uo).getMode()===hc.NONE}updateToolbar(t){pe(this,Uo).updateToolbar(t)}updateMode(t=pe(this,Uo).getMode()){switch(Kt(this,wy,ENe).call(this),t){case hc.NONE:this.disableTextSelection(),this.togglePointerEvents(!1),this.toggleAnnotationLayerPointerEvents(!0),this.disableClick();return;case hc.INK:this.addInkEditorIfNeeded(!1),this.disableTextSelection(),this.togglePointerEvents(!0),this.disableClick();break;case hc.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 pe(Z2,qE).values())n.toggle(`${r._type}Editing`,t===r._editorType);this.div.hidden=!1}hasTextLayer(t){var n;return t===((n=pe(this,Jy))==null?void 0:n.div)}addInkEditorIfNeeded(t){if(pe(this,Uo).getMode()!==hc.INK)return;if(!t){for(const r of pe(this,D_).values())if(r.isEmpty()){r.setInBackground();return}}this.createAndAddNewEditor({offsetX:0,offsetY:0},!1).setInBackground()}setEditingState(t){pe(this,Uo).setEditingState(t)}addCommands(t){pe(this,Uo).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=pe(this,CS))==null||n.div.classList.toggle("disabled",!t)}async enable(){this.div.tabIndex=0,this.togglePointerEvents(!0);const t=new Set;for(const r of pe(this,D_).values())r.enableEditing(),r.show(!0),r.annotationElementId&&(pe(this,Uo).removeChangedExistingAnnotation(r),t.add(r.annotationElementId));if(!pe(this,CS))return;const n=pe(this,CS).getEditableAnnotations();for(const r of n){if(r.hide(),pe(this,Uo).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,O$,!0),this.div.tabIndex=-1,this.togglePointerEvents(!1);const t=new Map,n=new Map;for(const i of pe(this,D_).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(pe(this,CS)){const i=pe(this,CS).getEditableAnnotations();for(const l of i){const{id:o}=l.data;if(pe(this,Uo).isDeletedAnnotationElement(o))continue;let c=n.get(o);if(c){c.resetAnnotationElement(l),c.show(!1),l.show();continue}c=t.get(o),c&&(pe(this,Uo).addChangedExistingAnnotation(c),c.renderAnnotationElement(l)&&c.show(!1)),l.show()}}Kt(this,wy,ENe).call(this),this.isEmpty&&(this.div.hidden=!0);const{classList:r}=this.div;for(const i of pe(Z2,qE).values())r.remove(`${i._type}Editing`);this.disableTextSelection(),this.toggleAnnotationLayerPointerEvents(!0),$t(this,O$,!1)}getEditableAnnotation(t){var n;return((n=pe(this,CS))==null?void 0:n.getEditableAnnotation(t))||null}setActiveEditor(t){pe(this,Uo).getActive()!==t&&pe(this,Uo).setActiveEditor(t)}enableTextSelection(){var t;if(this.div.tabIndex=-1,(t=pe(this,Jy))!=null&&t.div&&!pe(this,k3)){$t(this,k3,new AbortController);const n=pe(this,Uo).combinedSignal(pe(this,k3));pe(this,Jy).div.addEventListener("pointerdown",Kt(this,wy,Tqt).bind(this),{signal:n}),pe(this,Jy).div.classList.add("highlighting")}}disableTextSelection(){var t;this.div.tabIndex=0,(t=pe(this,Jy))!=null&&t.div&&pe(this,k3)&&(pe(this,k3).abort(),$t(this,k3,null),pe(this,Jy).div.classList.remove("highlighting"))}enableClick(){if(pe(this,$E))return;$t(this,$E,new AbortController);const t=pe(this,Uo).combinedSignal(pe(this,$E));this.div.addEventListener("pointerdown",this.pointerdown.bind(this),{signal:t}),this.div.addEventListener("pointerup",this.pointerup.bind(this),{signal:t})}disableClick(){var t;(t=pe(this,$E))==null||t.abort(),$t(this,$E,null)}attach(t){pe(this,D_).set(t.id,t);const{annotationElementId:n}=t;n&&pe(this,Uo).isDeletedAnnotationElement(n)&&pe(this,Uo).removeDeletedAnnotationElement(t)}detach(t){var n;pe(this,D_).delete(t.id),(n=pe(this,sR))==null||n.removePointerInTextLayer(t.contentDiv),!pe(this,O$)&&t.annotationElementId&&pe(this,Uo).addDeletedAnnotationElement(t)}remove(t){this.detach(t),pe(this,Uo).removeEditor(t),t.div.remove(),t.isAttachedToDOM=!1,pe(this,R$)||this.addInkEditorIfNeeded(!1)}changeParent(t){var n;t.parent!==this&&(t.parent&&t.annotationElementId&&(pe(this,Uo).addDeletedAnnotationElement(t.annotationElementId),Vu.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),pe(this,Uo).addEditor(t),this.attach(t),!t.isAttachedToDOM){const n=t.render();this.div.append(n),t.isAttachedToDOM=!0}t.fixAndSetPosition(),t.onceAdded(),pe(this,Uo).addToAnnotationStorage(t),t._reportTelemetry(t.telemetryInitialData)}}moveEditorInDOM(t){var r;if(!t.isAttachedToDOM)return;const{activeElement:n}=document;t.div.contains(n)&&!pe(this,N3)&&(t._focusEventsAllowed=!1,$t(this,N3,setTimeout(()=>{$t(this,N3,null),t.div.contains(document.activeElement)?t._focusEventsAllowed=!0:(t.div.addEventListener("focusin",()=>{t._focusEventsAllowed=!0},{once:!0,signal:pe(this,Uo)._signal}),n.focus())},0))),t._structTreeParentId=(r=pe(this,sR))==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 pe(this,Uo).getId()}combinedSignal(t){return pe(this,Uo).combinedSignal(t)}canCreateNewEmptyEditor(){var t;return(t=pe(this,wy,nUe))==null?void 0:t.canCreateNewEmptyEditor()}pasteEditor(t,n){pe(this,Uo).updateToolbar(t),pe(this,Uo).updateMode(t);const{offsetX:r,offsetY:a}=Kt(this,wy,aUe).call(this),i=this.getNextId(),l=Kt(this,wy,rUe).call(this,{parent:this,id:i,x:r,y:a,uiManager:pe(this,Uo),isCentered:!0,...n});l&&this.add(l)}async deserialize(t){var n;return await((n=pe(Z2,qE).get(t.annotationType??t.annotationEditorType))==null?void 0:n.deserialize(t,this,pe(this,Uo)))||null}createAndAddNewEditor(t,n,r={}){const a=this.getNextId(),i=Kt(this,wy,rUe).call(this,{parent:this,id:a,x:t.offsetX,y:t.offsetY,uiManager:pe(this,Uo),isCentered:n,...r});return i&&this.add(i),i}addNewEditor(){this.createAndAddNewEditor(Kt(this,wy,aUe).call(this),!0)}setSelected(t){pe(this,Uo).setSelected(t)}toggleSelected(t){pe(this,Uo).toggleSelected(t)}unselect(t){pe(this,Uo).unselect(t)}pointerup(t){const{isMac:n}=b1.platform;if(!(t.button!==0||t.ctrlKey&&n)&&t.target===this.div&&pe(this,UE)){if($t(this,UE,!1),!pe(this,D$)){$t(this,D$,!0);return}if(pe(this,Uo).getMode()===hc.STAMP){pe(this,Uo).unselectAll();return}this.createAndAddNewEditor(t,!1)}}pointerdown(t){if(pe(this,Uo).getMode()===hc.HIGHLIGHT&&this.enableTextSelection(),pe(this,UE)){$t(this,UE,!1);return}const{isMac:n}=b1.platform;if(t.button!==0||t.ctrlKey&&n||t.target!==this.div)return;$t(this,UE,!0);const r=pe(this,Uo).getActive();$t(this,D$,!r||r.isEmpty())}findNewParent(t,n,r){const a=pe(this,Uo).findParent(n,r);return a===null||a===this?!1:(a.changeParent(t),!0)}destroy(){var t,n;((t=pe(this,Uo).getActive())==null?void 0:t.parent)===this&&(pe(this,Uo).commitOrRemove(),pe(this,Uo).setActiveEditor(null)),pe(this,N3)&&(clearTimeout(pe(this,N3)),$t(this,N3,null));for(const r of pe(this,D_).values())(n=pe(this,sR))==null||n.removePointerInTextLayer(r.contentDiv),r.setParent(null),r.isAttachedToDOM=!1,r.div.remove();this.div=null,pe(this,D_).clear(),pe(this,Uo).removeLayer(this)}render({viewport:t}){this.viewport=t,OO(this.div,t);for(const n of pe(this,Uo).getEditors(this.pageIndex))this.add(n),n.rebuild();this.updateMode()}update({viewport:t}){pe(this,Uo).commitOrRemove(),Kt(this,wy,ENe).call(this);const n=this.viewport.rotation,r=t.rotation;if(this.viewport=t,OO(this.div,{rotation:r}),n!==r)for(const a of pe(this,D_).values())a.rotate(r);this.addInkEditorIfNeeded(!1)}get pageDimensions(){const{pageWidth:t,pageHeight:n}=this.viewport.rawDims;return[t,n]}get scale(){return pe(this,Uo).viewParameters.realScale}};sR=new WeakMap,D$=new WeakMap,CS=new WeakMap,$E=new WeakMap,N3=new WeakMap,D_=new WeakMap,UE=new WeakMap,R$=new WeakMap,O$=new WeakMap,Jy=new WeakMap,k3=new WeakMap,Uo=new WeakMap,qE=new WeakMap,wy=new WeakSet,Tqt=function(t){pe(this,Uo).unselectAll();const{target:n}=t;if(n===pe(this,Jy).div||(n.getAttribute("role")==="img"||n.classList.contains("endOfContent"))&&pe(this,Jy).div.contains(n)){const{isMac:r}=b1.platform;if(t.button!==0||t.ctrlKey&&r)return;pe(this,Uo).showAllEditors("highlight",!0,!0),pe(this,Jy).div.classList.add("free"),this.toggleDrawing(),I4e.startHighlighting(this,pe(this,Uo).direction==="ltr",{target:pe(this,Jy).div,x:t.x,y:t.y}),pe(this,Jy).div.addEventListener("pointerup",()=>{pe(this,Jy).div.classList.remove("free"),this.toggleDrawing(!0)},{once:!0,signal:pe(this,Uo)._signal}),t.preventDefault()}},nUe=function(){return pe(Z2,qE).get(pe(this,Uo).getMode())},rUe=function(t){const n=pe(this,wy,nUe);return n?new n.prototype.constructor(t):null},aUe=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}},ENe=function(){$t(this,R$,!0);for(const t of pe(this,D_).values())t.isEmpty()&&t.remove();$t(this,R$,!1)},Lr(Z2,"_initialized",!1),rs(Z2,qE,new Map([D$e,V$e,J$e,I4e].map(t=>[t._editorType,t])));let sUe=Z2;var AS,zJ,wx,S3,BJ,oUe,qO,lUe,Mqt;const Q0=class Q0{constructor({pageIndex:t}){rs(this,qO);rs(this,AS,null);rs(this,zJ,0);rs(this,wx,new Map);rs(this,S3,new Map);this.pageIndex=t}setParent(t){if(!pe(this,AS)){$t(this,AS,t);return}if(pe(this,AS)!==t){if(pe(this,wx).size>0)for(const n of pe(this,wx).values())n.remove(),t.append(n);$t(this,AS,t)}}static get _svgFactory(){return xd(this,"_svgFactory",new sXe)}draw(t,n,r,a=!1){const i=Xg(this,zJ)._++,l=Kt(this,qO,lUe).call(this,t.box);l.classList.add(...t.classNamesForDrawing);const o=Q0._svgFactory.createElement("defs");l.append(o);const c=Q0._svgFactory.createElement("path");o.append(c);const d=`path_p${this.pageIndex}_${i}`;c.setAttribute("id",d),c.setAttribute("d",t.toSVGPath()),a&&pe(this,S3).set(i,c);const u=Kt(this,qO,Mqt).call(this,o,d),h=Q0._svgFactory.createElement("use");return l.append(h),l.setAttribute("fill",n),l.setAttribute("fill-opacity",r),h.setAttribute("href",`#${d}`),pe(this,wx).set(i,l),{id:i,clipPathId:`url(#${u})`}}drawOutline(t){const n=Xg(this,zJ)._++,r=Kt(this,qO,lUe).call(this,t.box);r.classList.add(...t.classNamesForOutlining);const a=Q0._svgFactory.createElement("defs");r.append(a);const i=Q0._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=Q0._svgFactory.createElement("mask");a.append(u),o=`mask_p${this.pageIndex}_${n}`,u.setAttribute("id",o),u.setAttribute("maskUnits","objectBoundingBox");const h=Q0._svgFactory.createElement("rect");u.append(h),h.setAttribute("width","1"),h.setAttribute("height","1"),h.setAttribute("fill","white");const m=Q0._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=Q0._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"),pe(this,wx).set(n,r),n}finalizeLine(t,n){const r=pe(this,S3).get(t);pe(this,S3).delete(t),this.updateBox(t,n.box),r.setAttribute("d",n.toSVGPath())}updateLine(t,n){pe(this,wx).get(t).firstChild.firstChild.setAttribute("d",n.toSVGPath())}updatePath(t,n){pe(this,S3).get(t).setAttribute("d",n.toSVGPath())}updateBox(t,n){var r;Kt(r=Q0,BJ,oUe).call(r,pe(this,wx).get(t),n)}show(t,n){pe(this,wx).get(t).classList.toggle("hidden",!n)}rotate(t,n){pe(this,wx).get(t).setAttribute("data-main-rotation",n)}changeColor(t,n){pe(this,wx).get(t).setAttribute("fill",n)}changeOpacity(t,n){pe(this,wx).get(t).setAttribute("fill-opacity",n)}addClass(t,n){pe(this,wx).get(t).classList.add(n)}removeClass(t,n){pe(this,wx).get(t).classList.remove(n)}getSVGRoot(t){return pe(this,wx).get(t)}remove(t){pe(this,S3).delete(t),pe(this,AS)!==null&&(pe(this,wx).get(t).remove(),pe(this,wx).delete(t))}destroy(){$t(this,AS,null);for(const t of pe(this,wx).values())t.remove();pe(this,wx).clear(),pe(this,S3).clear()}};AS=new WeakMap,zJ=new WeakMap,wx=new WeakMap,S3=new WeakMap,BJ=new WeakSet,oUe=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}%`},qO=new WeakSet,lUe=function(t){var r;const n=Q0._svgFactory.create(1,1,!0);return pe(this,AS).append(n),n.setAttribute("aria-hidden",!0),Kt(r=Q0,BJ,oUe).call(r,n,t),n},Mqt=function(t,n){const r=Q0._svgFactory.createElement("clipPath");t.append(r);const a=`clip_${n}`;r.setAttribute("id",a),r.setAttribute("clipPathUnits","objectBoundingBox");const i=Q0._svgFactory.createElement("use");return r.append(i),i.setAttribute("href",`#${n}`),i.classList.add("clip"),a},rs(Q0,BJ);let iUe=Q0;Wl.AbortException;Wl.AnnotationEditorLayer;Wl.AnnotationEditorParamsType;Wl.AnnotationEditorType;Wl.AnnotationEditorUIManager;Wl.AnnotationLayer;Wl.AnnotationMode;Wl.ColorPicker;Wl.DOMSVGFactory;Wl.DrawLayer;Wl.FeatureTest;var zMn=Wl.GlobalWorkerOptions;Wl.ImageKind;Wl.InvalidPDFException;Wl.MissingPDFException;Wl.OPS;Wl.OutputScale;Wl.PDFDataRangeTransport;Wl.PDFDateString;Wl.PDFWorker;Wl.PasswordResponses;Wl.PermissionFlag;Wl.PixelsPerInch;Wl.RenderingCancelledException;Wl.TextLayer;Wl.UnexpectedResponseException;Wl.Util;Wl.VerbosityLevel;Wl.XfaLayer;Wl.build;Wl.createValidAbsoluteUrl;Wl.fetchData;var BMn=Wl.getDocument;Wl.getFilenameFromUrl;Wl.getPdfFilenameFromUrl;Wl.getXfaPageViewport;Wl.isDataScheme;Wl.isPdfFile;Wl.noContextMenu;Wl.normalizeUnicode;Wl.setLayerDimensions;Wl.shadow;Wl.version;const $Mn="/assets/pdf.worker.min-GB3t0DcA.mjs";zMn.workerSrc=$Mn;const UMn=({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 BMn({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 x=p.getViewport({scale:t}),g=document.createElement("canvas");g.width=Math.floor(x.width),g.height=Math.floor(x.height),g.className="mx-auto w-full max-w-[900px] rounded-md border border-border bg-white shadow-sm";const y=g.getContext("2d");y&&(c.appendChild(g),await p.render({canvasContext:y,viewport:x}).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(Ht,{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 xte({label:s,value:t,onChange:n,prefix:r="presentation",hint:a,urlPlaceholder:i="…or paste an image URL",round:l=!1,className:o}){const{user:c}=_s(),d=j.useRef(null),[u,h]=j.useState(!1),m=async p=>{if(!(!p||!c)){if(!p.type.startsWith("image/")){ae.error("Please choose an image file");return}if(p.size>20*1024*1024){ae.error("That photo is larger than 20 MB");return}h(!0);try{const x=await RTn(c.id,p,r);n(x),ae.success("Photo uploaded")}catch(x){ae.error((x==null?void 0:x.message)||"Upload failed")}finally{h(!1),d.current&&(d.current.value="")}}};return e.jsxs("div",{className:Tt("space-y-2",o),children:[e.jsx(se,{className:"text-xs",children:s}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:Tt("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(Jl,{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 x;return m((x=p.target.files)==null?void 0:x[0])}}),e.jsxs($,{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(Ht,{className:"h-4 w-4 animate-spin"}):e.jsx(x1,{className:"h-4 w-4"}),t?"Replace photo":"Upload photo"]}),t&&e.jsxs($,{type:"button",variant:"ghost",size:"sm",className:"gap-1 text-muted-foreground",onClick:()=>n(null),children:[e.jsx(pr,{className:"h-4 w-4"})," Remove"]})]})]}),e.jsx(be,{value:t||"",onChange:p=>n(p.target.value||null),placeholder:i}),a&&e.jsx("p",{className:"text-xs text-muted-foreground",children:a})]})}function qMn({value:s,onChange:t}){return e.jsxs(_e,{children:[e.jsxs(Bt,{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(qn,{className:"h-4 w-4 text-muted-foreground"}),e.jsx(Ut,{className:"text-base",children:"Co-listing agent"})]}),e.jsx(Tn,{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(Oe,{className:"space-y-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:"Name"}),e.jsx(be,{value:s.name,onChange:n=>t({name:n.target.value}),placeholder:"Jordan Ellis"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:"Title"}),e.jsx(be,{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(se,{children:"Phone"}),e.jsx(be,{value:s.phone||"",onChange:n=>t({phone:n.target.value})})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:"Email"}),e.jsx(be,{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(se,{children:"Brokerage"}),e.jsx(be,{value:s.brokerageName||"",onChange:n=>t({brokerageName:n.target.value})})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:"License #"}),e.jsx(be,{value:s.licenseNumber||"",onChange:n=>t({licenseNumber:n.target.value})})]})]}),e.jsx(xte,{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(se,{children:"Shared bio (optional)"}),e.jsx(Is,{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 VMn({value:s,onChange:t}){return e.jsxs(_e,{children:[e.jsxs(Bt,{className:"pb-3",children:[e.jsx(Ut,{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(Oe,{className:"grid gap-2 sm:grid-cols-2",children:HBe.map(n=>{const r=n.id===s;return e.jsxs("button",{type:"button",onClick:()=>t(n.id),className:Tt("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(oa,{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 HMn={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}]},GMn=["cover","welcome","agent","overview","closing"];function WMn({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(_e,{children:[e.jsxs(Bt,{className:"pb-3",children:[e.jsx(Ut,{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(Oe,{children:e.jsx(JO,{type:"multiple",className:"w-full",children:GMn.filter(i=>i==="cover"||!n.has(i)).map(i=>{const l=sBt(s,i);return e.jsxs(D6,{value:i,children:[e.jsx(R6,{className:"text-sm",children:H4n[i]}),e.jsxs(O6,{className:"space-y-3 pt-1",children:[HMn[i].map(o=>e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{className:"text-xs",children:o.label}),o.long?e.jsx(Is,{rows:2,value:l[o.key]||"",placeholder:NBe[i][o.key],onChange:c=>r(i,o.key,c.target.value)}):e.jsx(be,{value:l[o.key]||"",placeholder:NBe[i][o.key],onChange:c=>r(i,o.key,c.target.value)})]},o.key)),e.jsxs($,{variant:"ghost",size:"sm",className:"gap-2",onClick:()=>a(i),children:[e.jsx(Ih,{className:"h-3.5 w-3.5"})," Reset to default wording"]})]})]},i)})})})]})}function KMn({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,AZe(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(_e,{children:[e.jsxs(Bt,{className:"pb-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(nw,{className:"h-4 w-4 text-muted-foreground"}),e.jsx(Ut,{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(Oe,{className:"space-y-4",children:[e.jsx("div",{className:"grid gap-2 sm:grid-cols-2",children:I8e.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(sn,{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(Hl,{}),e.jsx(JO,{type:"multiple",className:"w-full",children:n.map((o,c)=>{var d,u,h;return e.jsxs(D6,{value:o.id,children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Tn,{checked:o.enabled,onCheckedChange:m=>r(o.id,{enabled:m})}),e.jsx(R6,{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=I8e.find(m=>m.layout===o.layout))==null?void 0:u.name),e.jsx($e,{variant:"secondary",className:"text-[10px]",children:(h=I8e.find(m=>m.layout===o.layout))==null?void 0:h.name})]})}),e.jsx($,{variant:"ghost",size:"icon",className:"h-7 w-7",disabled:c===0,onClick:()=>l(o.id,-1),children:e.jsx(sp,{className:"h-3.5 w-3.5"})}),e.jsx($,{variant:"ghost",size:"icon",className:"h-7 w-7",disabled:c===n.length-1,onClick:()=>l(o.id,1),children:e.jsx(ax,{className:"h-3.5 w-3.5"})}),e.jsx($,{variant:"ghost",size:"icon",className:"h-7 w-7 text-destructive",onClick:()=>i(o.id),children:e.jsx(Pn,{className:"h-3.5 w-3.5"})})]}),e.jsxs(O6,{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(se,{className:"text-xs",children:"Placement"}),e.jsxs(vs,{value:o.placement,onValueChange:m=>r(o.id,{placement:m}),children:[e.jsx(gs,{children:e.jsx(bs,{})}),e.jsxs(ys,{children:[e.jsx(Ye,{value:"after-agent",children:'After "About your agent"'}),e.jsx(Ye,{value:"end",children:"Before the closing page"})]})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{className:"text-xs",children:"Style"}),e.jsxs("div",{className:"flex h-10 items-center gap-2 rounded-md border px-3",children:[e.jsx(Tn,{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(se,{className:"text-xs",children:"Eyebrow"}),e.jsx(be,{value:o.kicker,onChange:m=>r(o.id,{kicker:m.target.value})})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{className:"text-xs",children:"Headline"}),e.jsx(be,{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(se,{className:"text-xs",children:"Subhead"}),e.jsx(be,{value:o.subhead,onChange:m=>r(o.id,{subhead:m.target.value})})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{className:"text-xs",children:"Body copy"}),e.jsx(Is,{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(xte,{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(se,{className:"text-xs",children:"Photo side"}),e.jsxs(vs,{value:o.imageSide,onValueChange:m=>r(o.id,{imageSide:m}),children:[e.jsx(gs,{children:e.jsx(bs,{})}),e.jsxs(ys,{children:[e.jsx(Ye,{value:"right",children:"Right"}),e.jsx(Ye,{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(se,{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(be,{value:m,onChange:x=>{const g=[...o.bullets];g[p]=x.target.value,r(o.id,{bullets:g})}}),e.jsx($,{variant:"ghost",size:"icon",className:"h-8 w-8 text-destructive",onClick:()=>r(o.id,{bullets:o.bullets.filter((x,g)=>g!==p)}),children:e.jsx(Pn,{className:"h-3.5 w-3.5"})})]},p)),e.jsxs($,{variant:"outline",size:"sm",className:"gap-2",disabled:o.bullets.length>=7,onClick:()=>r(o.id,{bullets:[...o.bullets,""]}),children:[e.jsx(sn,{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(se,{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(Is,{rows:3,value:m.quote,placeholder:"Client quote",onChange:x=>{const g=[...o.testimonials];g[p]={...m,quote:x.target.value},r(o.id,{testimonials:g})}}),e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsx(be,{value:m.name,placeholder:"Name",onChange:x=>{const g=[...o.testimonials];g[p]={...m,name:x.target.value},r(o.id,{testimonials:g})}}),e.jsx(be,{value:m.detail,placeholder:"Neighborhood or year",onChange:x=>{const g=[...o.testimonials];g[p]={...m,detail:x.target.value},r(o.id,{testimonials:g})}})]}),e.jsxs($,{variant:"ghost",size:"sm",className:"gap-2 text-destructive",onClick:()=>r(o.id,{testimonials:o.testimonials.filter((x,g)=>g!==p)}),children:[e.jsx(Pn,{className:"h-3.5 w-3.5"})," Remove"]})]},p)),e.jsxs($,{variant:"outline",size:"sm",className:"gap-2",disabled:o.testimonials.length>=4,onClick:()=>r(o.id,{testimonials:[...o.testimonials,{quote:"",name:"",detail:""}]}),children:[e.jsx(sn,{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(se,{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(be,{className:"w-28",value:m.value,placeholder:"27",onChange:x=>{const g=[...o.stats];g[p]={...m,value:x.target.value},r(o.id,{stats:g})}}),e.jsx(be,{value:m.label,placeholder:"Homes sold",onChange:x=>{const g=[...o.stats];g[p]={...m,label:x.target.value},r(o.id,{stats:g})}}),e.jsx($,{variant:"ghost",size:"icon",className:"h-8 w-8 text-destructive",onClick:()=>r(o.id,{stats:o.stats.filter((x,g)=>g!==p)}),children:e.jsx(Pn,{className:"h-3.5 w-3.5"})})]},p)),e.jsxs($,{variant:"outline",size:"sm",className:"gap-2",disabled:o.stats.length>=4,onClick:()=>r(o.id,{stats:[...o.stats,{value:"",label:""}]}),children:[e.jsx(sn,{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 YMn({open:s,onOpenChange:t,defaultName:n,saving:r,onSave:a}){const[i,l]=j.useState(""),[o,c]=j.useState("");return j.useEffect(()=>{s&&(l((n==null?void 0:n.trim())||"My listing presentation"),c(""))},[s,n]),e.jsx(Os,{open:s,onOpenChange:t,children:e.jsxs(Rs,{className:"sm:max-w-md",children:[e.jsxs(Us,{children:[e.jsx(zs,{children:"Save as a reusable template"}),e.jsx(Sr,{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(se,{children:"Template name"}),e.jsx(be,{value:i,onChange:d=>l(d.target.value),autoFocus:!0})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:"Notes (optional)"}),e.jsx(Is,{rows:2,value:o,onChange:d=>c(d.target.value),placeholder:"Luxury version with co-listing agent and testimonials"})]})]}),e.jsxs(kr,{children:[e.jsx($,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsxs($,{disabled:!i.trim()||r,onClick:async()=>{await a(i.trim(),o.trim()),t(!1)},className:"gap-2",children:[r&&e.jsx(Ht,{className:"h-4 w-4 animate-spin"})," Save template"]})]})]})})}const cvt=["welcome","agent","overview","closing"],ZMn=()=>{const{id:s}=Vi(),t=Vn(),{user:n}=_s(),{data:r}=tBt(),{data:a,isLoading:i,refetch:l}=$4n(s),{update:o}=eBt(),{save:c}=Jzt(),[d,u]=j.useState(null),[h,m]=j.useState(null),[p,x]=j.useState(CBe(null)),[g,y]=j.useState(nBt),[b,v]=j.useState([]),[N,C]=j.useState(kBe),[A,T]=j.useState(SBe),[P,M]=j.useState(null),[I,D]=j.useState(null),[B,q]=j.useState(!1),[W,V]=j.useState(!1),[K,Q]=j.useState(null),[J,ce]=j.useState(!1),[ue,ne]=j.useState(!1),[ee,le]=j.useState(!1),[he,ve]=j.useState(!1),[ge,fe]=j.useState(!0),[je,Ee]=j.useState(!1),Me=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||{}}),x(CBe(a.services)),y(rBt(a.co_agent)),v(iBt(a.custom_pages)),C(a.page_settings&&Object.keys(a.page_settings).length?a.page_settings:kBe),T(a.photo_focal||SBe),M(a.property_photo_path)},[a,r,d]),j.useEffect(()=>{let Ue=!1;return P?A4e(P).then(et=>{Ue||D(et)}):D(null),()=>{Ue=!0}},[P]);const De=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:g,custom_pages:b,services:p,page_settings:N,photo_focal:A,property_photo_path:P},[a,d,h,g,b,p,N,A,P]),ze=Ue=>u(et=>et&&{...et,...Ue}),ke=Ue=>m(et=>et&&{...et,...Ue}),Xe=Ue=>(N.hidden||[]).includes(Ue),Se=(Ue,et)=>C(Qe=>{const Ge=new Set(Qe.hidden||[]);return et?Ge.delete(Ue):Ge.add(Ue),{...Qe,hidden:Array.from(Ge)}}),Re=p.filter(Ue=>Ue.enabled),Ae=1+cvt.filter(Ue=>!Xe(Ue)&&Ue!=="overview").length+(Xe("overview")?0:1)+Re.filter(Ue=>Ue.key!=="communication").length+b.filter(Ue=>Ue.enabled).length,Be=async(Ue=!1)=>{if(De){ve(!0);try{await o.mutateAsync({id:De.id,title:De.title||"Untitled Presentation",property_address_line1:De.property_address_line1,city:De.city,state:De.state,postal_code:De.postal_code,list_price:De.list_price,beds:De.beds,baths:De.baths,sqft:De.sqft,agent_snapshot:De.agent_snapshot,co_agent:De.co_agent,custom_pages:De.custom_pages,services:De.services,page_settings:De.page_settings,photo_focal:De.photo_focal,property_photo_path:De.property_photo_path}),Ue||ae.success("Presentation saved")}finally{ve(!1)}}},qe=async Ue=>{if(!(!n||!s)){if(!Ue.type.startsWith("image/")){ae.error("Please choose a JPG or PNG photo");return}if(Ue.size>25*1024*1024){ae.error("That photo is larger than 25 MB");return}q(!0);try{const et=await DTn(n.id,s,Ue);M(et);const Qe=await A4e(et);D(Qe?`${Qe}${Qe.includes("?")?"&":"?"}v=${Date.now()}`:null),await o.mutateAsync({id:s,property_photo_path:et}),ae.success("Photo uploaded")}catch(et){ae.error((et==null?void 0:et.message)||"Upload failed")}finally{q(!1)}}},Ke=async()=>{if(De){ce(!0);try{const Ue=await j$t(E4e(De,r,I),De.template_id,P);Q(Ue)}catch(Ue){ae.error((Ue==null?void 0:Ue.message)||"Could not build the preview")}finally{ce(!1)}}};j.useEffect(()=>{if(!ge||!De)return;const Ue=setTimeout(()=>{Ke()},900);return()=>clearTimeout(Ue)},[ge,De]);const Ze=async()=>{if(!(!De||!n)){if(!De.property_photo_path){ae.error("Add the primary exterior photo before generating the PDF");return}ne(!0);try{await Be(!0);const Ue=await N$t(E4e(De,r,I),De.template_id,"print",P);await k$t(n.id,De.id,Ue),await l(),ae.success("Presentation downloaded")}catch(Ue){ae.error((Ue==null?void 0:Ue.message)||"Could not build the PDF")}finally{ne(!1)}}};return i||!d||!a?e.jsx(Ks,{children:e.jsxs("div",{className:"space-y-4",children:[e.jsx(on,{className:"h-10 w-64"}),e.jsx(on,{className:"h-[60vh] w-full rounded-xl"})]})}):e.jsxs(Ks,{children:[e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx($,{variant:"ghost",size:"icon",onClick:()=>t("/apps/listing-presentation-studio"),children:e.jsx(ka,{className:"h-4 w-4"})}),e.jsxs("div",{children:[e.jsx(be,{value:d.title,onChange:Ue=>ze({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:[Re.length," services selected · ",Ae," pages"]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs($,{variant:"outline",onClick:()=>Be(),disabled:he,className:"gap-2",children:[he?e.jsx(Ht,{className:"h-4 w-4 animate-spin"}):e.jsx(Jo,{className:"h-4 w-4"})," Save"]}),e.jsxs($,{variant:"outline",onClick:()=>Ee(!0),className:"gap-2",children:[e.jsx(fT,{className:"h-4 w-4"})," Save as template"]}),e.jsxs($,{variant:"outline",onClick:Ke,disabled:J,className:"gap-2",children:[J?e.jsx(Ht,{className:"h-4 w-4 animate-spin"}):e.jsx(ga,{className:"h-4 w-4"})," Preview"]}),e.jsxs($,{variant:"outline",onClick:async()=>{await Be(!0),le(!0)},className:"gap-2",children:[e.jsx(nn,{className:"h-4 w-4"})," Email"]}),e.jsxs($,{onClick:Ze,disabled:ue,className:"gap-2",children:[ue?e.jsx(Ht,{className:"h-4 w-4 animate-spin"}):e.jsx(di,{className:"h-4 w-4"}),"Generate PDF"]})]})]}),e.jsxs("div",{className:"grid gap-6 lg:grid-cols-[minmax(0,440px)_minmax(0,1fr)]",children:[e.jsxs(ua,{defaultValue:"property",className:"space-y-4",children:[e.jsxs(ha,{className:"grid w-full grid-cols-4",children:[e.jsx(Qt,{value:"property",children:"Property"}),e.jsx(Qt,{value:"branding",children:"Branding"}),e.jsx(Qt,{value:"plan",children:"Plan"}),e.jsx(Qt,{value:"pages",children:"Pages"})]}),e.jsxs(Jt,{value:"property",className:"space-y-4",children:[e.jsxs(_e,{children:[e.jsx(Bt,{className:"pb-3",children:e.jsx(Ut,{className:"text-base",children:"Property address"})}),e.jsxs(Oe,{className:"space-y-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:"Street address"}),e.jsx(be,{value:d.addressLine1,onChange:Ue=>ze({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(se,{children:"City"}),e.jsx(be,{value:d.city,onChange:Ue=>ze({city:Ue.target.value})})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:"State"}),e.jsx(be,{value:d.state,onChange:Ue=>ze({state:Ue.target.value})})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:"ZIP"}),e.jsx(be,{value:d.postalCode,onChange:Ue=>ze({postalCode:Ue.target.value})})]}),e.jsx(Hl,{}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:"List price (optional)"}),e.jsx(be,{inputMode:"numeric",value:d.listPrice,onChange:Ue=>ze({listPrice:Ue.target.value.replace(/[^0-9.]/g,"")}),placeholder:"649000"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:"Square feet"}),e.jsx(be,{inputMode:"numeric",value:d.sqft,onChange:Ue=>ze({sqft:Ue.target.value.replace(/[^0-9]/g,"")})})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:"Beds"}),e.jsx(be,{inputMode:"numeric",value:d.beds,onChange:Ue=>ze({beds:Ue.target.value.replace(/[^0-9.]/g,"")})})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:"Baths"}),e.jsx(be,{inputMode:"numeric",value:d.baths,onChange:Ue=>ze({baths:Ue.target.value.replace(/[^0-9.]/g,"")})})]})]})]})]}),e.jsxs(_e,{children:[e.jsx(Bt,{className:"pb-3",children:e.jsxs(Ut,{className:"text-base",children:["Primary exterior photo ",e.jsx("span",{className:"text-destructive",children:"*"})]})}),e.jsxs(Oe,{className:"space-y-3",children:[e.jsx("div",{role:"button",tabIndex:0,onClick:()=>{var Ue;return(Ue=Me.current)==null?void 0:Ue.click()},onKeyDown:Ue=>{var et;return Ue.key==="Enter"&&((et=Me.current)==null?void 0:et.click())},onDragOver:Ue=>{Ue.preventDefault(),V(!0)},onDragLeave:()=>V(!1),onDrop:Ue=>{var Qe;Ue.preventDefault(),V(!1);const et=(Qe=Ue.dataTransfer.files)==null?void 0:Qe[0];et&&qe(et)},className:Tt("relative flex h-48 w-full cursor-pointer items-center justify-center overflow-hidden rounded-lg border border-dashed bg-muted/40 transition-colors hover:bg-muted",W&&"border-primary bg-primary/10"),children: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:[B?e.jsx(Ht,{className:"h-6 w-6 animate-spin"}):e.jsx(x1,{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:Me,type:"file",accept:"image/*",className:"hidden",onChange:Ue=>{var Qe;const et=(Qe=Ue.target.files)==null?void 0:Qe[0];et&&qe(et),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(DK,{className:"h-3.5 w-3.5"})," Reposition crop"]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{className:"text-xs",children:"Horizontal"}),e.jsx(rx,{value:[A.x*100],min:0,max:100,step:1,onValueChange:([Ue])=>T(et=>({...et,x:Ue/100}))})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{className:"text-xs",children:"Vertical"}),e.jsx(rx,{value:[A.y*100],min:0,max:100,step:1,onValueChange:([Ue])=>T(et=>({...et,y:Ue/100}))})]})]}),e.jsxs($,{variant:"outline",size:"sm",className:"w-full gap-2",onClick:()=>{var Ue;return(Ue=Me.current)==null?void 0:Ue.click()},disabled:B,children:[e.jsx(Wi,{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(Jt,{value:"branding",className:"space-y-4",children:[e.jsx(VMn,{value:N.theme||XEn,onChange:Ue=>C(et=>({...et,theme:Ue}))}),e.jsxs(_e,{children:[e.jsx(Bt,{className:"pb-3",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(Ut,{className:"text-base",children:"Your details"}),e.jsx($e,{variant:"secondary",className:"text-[10px]",children:"Loaded from your LevelUp profile"})]})}),e.jsx(Oe,{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(se,{children:"Name"}),e.jsx(be,{value:h.name,onChange:Ue=>ke({name:Ue.target.value})})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:"Tagline"}),e.jsx(be,{value:h.tagline||"",onChange:Ue=>ke({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(se,{children:"Phone"}),e.jsx(be,{value:h.phone||"",onChange:Ue=>ke({phone:Ue.target.value})})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:"Email"}),e.jsx(be,{value:h.email||"",onChange:Ue=>ke({email:Ue.target.value})})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:"Website"}),e.jsx(be,{value:h.website||"",onChange:Ue=>ke({website:Ue.target.value})})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:"Brokerage"}),e.jsx(be,{value:h.brokerageName||"",onChange:Ue=>ke({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(se,{children:"License #"}),e.jsx(be,{value:h.licenseNumber||"",onChange:Ue=>ke({licenseNumber:Ue.target.value})})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:"License state"}),e.jsx(be,{value:h.licenseState||"",onChange:Ue=>ke({licenseState:Ue.target.value})})]})]}),e.jsx(Hl,{}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:"Primary color"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("input",{type:"color",value:h.brandColor,onChange:Ue=>ke({brandColor:Ue.target.value}),className:"h-9 w-12 cursor-pointer rounded border bg-transparent"}),e.jsx(be,{value:h.brandColor,onChange:Ue=>ke({brandColor:Ue.target.value})})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:"Accent color"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("input",{type:"color",value:h.accentColor,onChange:Ue=>ke({accentColor:Ue.target.value}),className:"h-9 w-12 cursor-pointer rounded border bg-transparent"}),e.jsx(be,{value:h.accentColor,onChange:Ue=>ke({accentColor:Ue.target.value})})]})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:"Headshot URL"}),e.jsx(be,{value:h.headshotUrl||"",onChange:Ue=>ke({headshotUrl:Ue.target.value}),placeholder:"Pulled from your profile photo"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:"Brokerage logo URL"}),e.jsx(be,{value:h.brokerageLogoUrl||"",onChange:Ue=>ke({brokerageLogoUrl:Ue.target.value})})]}),r&&e.jsxs($,{variant:"outline",size:"sm",className:"w-full gap-2",onClick:()=>m({...r}),children:[e.jsx(Wi,{className:"h-4 w-4"})," Reset to my LevelUp profile"]})]})})]}),e.jsx(qMn,{value:g,onChange:Ue=>y(et=>({...et,...Ue}))})]}),e.jsx(Jt,{value:"plan",className:"space-y-4",children:e.jsxs(_e,{children:[e.jsxs(Bt,{className:"pb-3",children:[e.jsx(Ut,{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(Oe,{children:e.jsx(JO,{type:"multiple",className:"w-full",children:p.slice().sort((Ue,et)=>Ue.order-et.order).map(Ue=>{var et;return e.jsxs(D6,{value:Ue.key,children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(Tn,{checked:Ue.enabled,onCheckedChange:Qe=>x(Ge=>Ge.map(nt=>nt.key===Ue.key?{...nt,enabled:Qe}:nt))}),e.jsx(R6,{className:"flex-1 text-left text-sm",children:Ue.title})]}),e.jsxs(O6,{className:"space-y-3 pt-2",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:"Headline"}),e.jsx(be,{value:Ue.title,onChange:Qe=>x(Ge=>Ge.map(nt=>nt.key===Ue.key?{...nt,title:Qe.target.value}:nt))})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:"Description"}),e.jsx(Is,{rows:4,value:Ue.body,onChange:Qe=>x(Ge=>Ge.map(nt=>nt.key===Ue.key?{...nt,body:Qe.target.value}:nt))})]}),!!((et=Ue.options)!=null&&et.length)&&e.jsxs("div",{className:"space-y-2 rounded-lg border bg-muted/30 p-3",children:[e.jsx(se,{className:"text-xs uppercase tracking-wide text-muted-foreground",children:"Included in this page"}),Ue.options.map(Qe=>e.jsxs("label",{className:"flex items-start gap-2 text-sm",children:[e.jsx(ui,{className:"mt-0.5",checked:Qe.enabled,onCheckedChange:Ge=>x(nt=>nt.map(ft=>{var lt;return ft.key===Ue.key?{...ft,options:(lt=ft.options)==null?void 0:lt.map(Mt=>Mt.key===Qe.key?{...Mt,enabled:!!Ge}:Mt)}:ft}))}),e.jsx("span",{className:"leading-snug",children:Qe.label})]},Qe.key))]})]})]},Ue.key)})})})]})}),e.jsxs(Jt,{value:"pages",className:"space-y-4",children:[e.jsxs(_e,{children:[e.jsxs(Bt,{className:"pb-3",children:[e.jsx(Ut,{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(Oe,{className:"space-y-3",children:[cvt.map(Ue=>e.jsxs("div",{className:"flex items-center justify-between rounded-lg border p-3",children:[e.jsx("span",{className:"text-sm",children:W4n[Ue]}),e.jsx(Tn,{checked:!Xe(Ue),onCheckedChange:et=>Se(Ue,et)})]},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"}),!Xe("welcome")&&e.jsx("li",{children:"Marketing commitment"}),!Xe("agent")&&e.jsx("li",{children:"About your agent"}),b.filter(Ue=>Ue.enabled&&Ue.placement!=="end").sort((Ue,et)=>Ue.order-et.order).map(Ue=>e.jsx("li",{children:Ue.headline||"Custom page"},Ue.id)),!Xe("overview")&&e.jsx("li",{children:"Marketing plan overview"}),Re.filter(Ue=>Ue.key!=="communication").map(Ue=>e.jsx("li",{children:Ue.title},Ue.key)),b.filter(Ue=>Ue.enabled&&Ue.placement==="end").sort((Ue,et)=>Ue.order-et.order).map(Ue=>e.jsx("li",{children:Ue.headline||"Custom page"},Ue.id)),!Xe("closing")&&e.jsx("li",{children:"Communication & closing commitment"})]})]})]})]}),e.jsx(WMn,{pages:N,onChange:C}),e.jsxs(_e,{children:[e.jsxs(Bt,{className:"pb-3",children:[e.jsx(Ut,{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(Oe,{children:e.jsx($,{variant:"outline",size:"sm",className:"w-full",onClick:()=>v(Ue=>[...Ue,{...AZe("testimonials",Ue.length),placement:"end"}]),children:`Add a "What they're saying" page`})})]}),e.jsx(KMn,{pages:b,onChange:v})]})]}),e.jsxs(_e,{className:"min-h-[70vh] overflow-hidden",children:[e.jsxs(Bt,{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(Ut,{className:"text-base",children:"Live preview"}),e.jsxs("label",{className:"flex items-center gap-1.5 text-xs text-muted-foreground",children:[e.jsx(Tn,{checked:ge,onCheckedChange:fe}),"Auto-update"]})]}),e.jsxs($,{variant:"ghost",size:"sm",onClick:Ke,disabled:J,className:"gap-2",children:[J?e.jsx(Ht,{className:"h-4 w-4 animate-spin"}):e.jsx(Wi,{className:"h-4 w-4"}),"Refresh"]})]}),e.jsx(Oe,{className:"h-[calc(70vh-60px)] p-0",children:K?e.jsx(UMn,{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(ga,{className:"h-8 w-8 text-muted-foreground"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Fill in the address, upload the photo, then generate the preview."}),e.jsxs($,{onClick:Ke,disabled:J,className:"gap-2",children:[J?e.jsx(Ht,{className:"h-4 w-4 animate-spin"}):e.jsx(ga,{className:"h-4 w-4"}),"Generate preview"]})]})})]})]})]}),e.jsx(YMn,{open:je,onOpenChange:Ee,defaultName:d.title,saving:c.isPending,onSave:async(Ue,et)=>{await c.mutateAsync({name:Ue,description:et||null,template_id:a.template_id,agent_snapshot:h||{},co_agent:g,custom_pages:b,services:p,page_settings:N})}}),e.jsx(C$t,{open:ee,onOpenChange:le,row:De,brand:r,photoUrl:I})]})};function XMn(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 Lqt="popby_geocode_cache_v1";function QMn(){try{return JSON.parse(localStorage.getItem(Lqt)||"{}")}catch{return{}}}function JMn(s){try{localStorage.setItem(Lqt,JSON.stringify(s))}catch{}}function eLn({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:v}=await U.from("settings").select("value").eq("key","mapbox_public_token").maybeSingle();v!=null&&v.value&&d(v.value)})()},[]);const x=j.useMemo(()=>s.filter(v=>v.isDue&&(v.address||v.city&&v.state||v.zip)),[s]),g=()=>{if(!("geolocation"in navigator)){i("unavailable");return}i("loading"),navigator.geolocation.getCurrentPosition(v=>{r({lat:v.coords.latitude,lng:v.coords.longitude}),i("ok")},()=>{i("denied")},{enableHighAccuracy:!0,timeout:1e4,maximumAge:6e4})};j.useEffect(()=>{if(!c||!n||x.length===0)return;let v=!1;const N=QMn(),C=new Map;x.forEach(T=>{const P=[T.address,T.city,T.state,T.zip].filter(Boolean).join("|").toLowerCase();N[P]&&C.set(T.id,N[P])}),h(new Map(C));const A=x.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],P=async()=>{var M,I;for(;T.length&&!v;){const D=T.shift(),B=[D.address,D.city,D.state,D.zip].filter(Boolean),q=B.join("|").toLowerCase(),W=B.join(", ");try{const K=await(await fetch(`https://api.mapbox.com/geocoding/v5/mapbox.places/${encodeURIComponent(W)}.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[Q,J]=K.features[0].center;N[q]={lat:J,lng:Q},C.set(D.id,{lat:J,lng:Q})}else N[q]=null}catch{}}};await Promise.all([P(),P(),P(),P()]),v||(JMn(N),h(new Map(C)),p(!1))})(),()=>{v=!0}},[c,n,x]);const y=j.useMemo(()=>{if(!n)return[];const v=[];return x.forEach(N=>{const C=u.get(N.id);if(!C)return;const A=XMn(n.lat,n.lng,C.lat,C.lng);A<=l&&v.push({...N,distanceMiles:A,lat:C.lat,lng:C.lng})}),v.sort((N,C)=>N.distanceMiles-C.distanceMiles)},[n,x,u,l]),b=v=>{const C=/iPad|iPhone|iPod/.test(navigator.userAgent)?`https://maps.apple.com/?daddr=${v.lat},${v.lng}`:`https://www.google.com/maps/dir/?api=1&destination=${v.lat},${v.lng}`;window.open(C,"_blank","noopener")};return e.jsxs(_e,{className:"border-primary/30 bg-gradient-to-br from-primary/5 to-transparent",children:[e.jsx(Bt,{className:"pb-3",children:e.jsxs("div",{className:"flex items-start justify-between gap-3 flex-wrap",children:[e.jsxs("div",{children:[e.jsxs(Ut,{className:"flex items-center gap-2 text-lg",children:[e.jsx(kz,{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(vs,{value:String(l),onValueChange:v=>o(Number(v)),children:[e.jsx(gs,{className:"w-[110px] h-9",children:e.jsx(bs,{})}),e.jsxs(ys,{children:[e.jsx(Ye,{value:"2",children:"2 miles"}),e.jsx(Ye,{value:"5",children:"5 miles"}),e.jsx(Ye,{value:"10",children:"10 miles"}),e.jsx(Ye,{value:"25",children:"25 miles"})]})]}),e.jsxs($,{size:"sm",variant:a==="ok"?"outline":"default",onClick:g,disabled:a==="loading",children:[a==="loading"?e.jsx(Wi,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(kz,{className:"h-4 w-4 mr-1"}),a==="ok"?"Refresh":"Use my location"]})]})]})}),e.jsxs(Oe,{className:"space-y-3",children:[a==="idle"&&e.jsxs("div",{className:"text-center py-6 text-sm text-muted-foreground",children:[e.jsx(ai,{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(xo,{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&&x.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&&x.length>0&&m&&y.length===0&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(on,{className:"h-14 w-full"}),e.jsx(on,{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&&x.length>0&&e.jsxs("div",{className:"text-center py-6 text-sm text-muted-foreground",children:["No due contacts within ",l," miles. Try widening the radius."]}),y.length>0&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs($e,{variant:"secondary",className:"font-medium",children:[y.length," nearby"]}),m&&e.jsxs("span",{className:"text-xs text-muted-foreground flex items-center gap-1",children:[e.jsx(Wi,{className:"h-3 w-3 animate-spin"})," still locating…"]})]}),e.jsx("div",{className:"space-y-2",children:y.map(v=>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:[v.first_name," ",v.last_name]}),e.jsx($e,{variant:"outline",className:"text-xs",children:v.distanceMiles<1?`${(v.distanceMiles*5280).toFixed(0)} ft`:`${v.distanceMiles.toFixed(1)} mi`}),v.daysOverdue>0&&e.jsxs($e,{variant:"destructive",className:"text-xs",children:[v.daysOverdue,"d overdue"]})]}),e.jsx("p",{className:"text-xs text-muted-foreground truncate mt-0.5",children:[v.address,v.city,v.state].filter(Boolean).join(", ")})]}),e.jsxs("div",{className:"flex items-center gap-1 shrink-0",children:[v.phone&&e.jsx($,{size:"icon",variant:"ghost",asChild:!0,className:"h-9 w-9",title:"Call",children:e.jsx("a",{href:`tel:${v.phone}`,children:e.jsx(ya,{className:"h-4 w-4"})})}),e.jsx($,{size:"icon",variant:"ghost",onClick:()=>b(v),className:"h-9 w-9",title:"Directions",children:e.jsx(RK,{className:"h-4 w-4"})}),e.jsxs($,{size:"sm",onClick:()=>t(v),children:[e.jsx(Co,{className:"h-4 w-4 mr-1"}),"Log"]})]})]},v.id))})]})]})]})}const tLn="0dde5abb-0005-4c8c-a471-30d0cbc9e280",sLn=[{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 nLn(){const s=Vn(),t=C7t(),{data:n}=fNn(),{data:r}=Hb(),{data:a}=EYe(),{data:i}=HEe(90),{data:l}=M1(),o=bNn(),c=yNn(),d=gNn(),u=vNn(),{data:h=[],isLoading:m}=ht({queryKey:["popby-templates"],queryFn:async()=>{const{data:K,error:Q}=await U.from("canva_templates").select(` *, category:template_categories(id, name), type:template_types(id, name) `).eq("category_id",tLn).order("publish_date",{ascending:!1});if(Q)throw Q;const{data:J}=await U.from("template_likes").select("template_id"),{data:ce}=await U.from("template_comments").select("template_id"),ue=new Map;J==null||J.forEach(ee=>{ue.set(ee.template_id,(ue.get(ee.template_id)||0)+1)});const ne=new Map;return ce==null||ce.forEach(ee=>{ne.set(ee.template_id,(ne.get(ee.template_id)||0)+1)}),(K||[]).map(ee=>({...ee,likesCount:ue.get(ee.id)||0,commentsCount:ne.get(ee.id)||0}))}}),p=K=>{const Q=l==null?void 0:l.find(J=>J.id===K);return Q?`${Q.first_name} ${Q.last_name||""}`.trim():"Unknown"},x=K=>{if(!K)return null;const Q=n==null?void 0:n.find(J=>J.id===K);return(Q==null?void 0:Q.name)||null},[g,y]=j.useState(null),[b,v]=j.useState(!1),[N,C]=j.useState(!1),[A,T]=j.useState(!1),[P,M]=j.useState({popby_item_id:"",notes:""}),[I,D]=j.useState({name:"",description:""}),B=async()=>{g&&(await c.mutateAsync({contact_id:g.id,popby_item_id:P.popby_item_id||void 0,notes:P.notes||void 0}),v(!1),y(null),M({popby_item_id:"",notes:""}))},q=async()=>{I.name.trim()&&(await d.mutateAsync({name:I.name.trim(),description:I.description.trim()||void 0}),T(!1),D({name:"",description:""}))},W=async(K,Q)=>{await u.mutateAsync({relationship_type_id:K,frequency_days:parseInt(Q)})},V=K=>{var J;const Q=a==null?void 0:a.find(ce=>ce.relationship_type_id===K);return((J=Q==null?void 0:Q.frequency_days)==null?void 0:J.toString())||"90"};return e.jsx(Ks,{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(_e,{children:e.jsxs(Oe,{className:"p-4 text-center",children:[e.jsx("div",{className:"text-3xl font-bold text-primary",children:o.thisWeekCount}),e.jsx("div",{className:"text-sm text-muted-foreground",children:"This Week"})]})}),e.jsx(_e,{children:e.jsxs(Oe,{className:"p-4 text-center",children:[e.jsx("div",{className:"text-3xl font-bold text-emerald-500",children:o.thisMonthCount}),e.jsx("div",{className:"text-sm text-muted-foreground",children:"This Month"})]})}),e.jsx(_e,{children:e.jsxs(Oe,{className:"p-4 text-center",children:[e.jsx("div",{className:"text-3xl font-bold text-amber-500",children:o.dueCount}),e.jsx("div",{className:"text-sm text-muted-foreground",children:"Due Now"})]})})]}),e.jsxs("div",{className:"flex gap-2 flex-wrap",children:[e.jsxs($,{onClick:()=>s("/mission-control/popbys/map"),children:[e.jsx(ai,{className:"h-4 w-4 mr-2"}),"View Map"]}),e.jsxs($,{variant:"outline",onClick:()=>C(!0),children:[e.jsx(pc,{className:"h-4 w-4 mr-2"}),"Frequency Settings"]}),e.jsxs($,{variant:"outline",onClick:()=>T(!0),children:[e.jsx(sn,{className:"h-4 w-4 mr-2"}),"Add Popby Idea"]})]}),e.jsxs(ua,{defaultValue:"due",children:[e.jsxs(ha,{children:[e.jsx(Qt,{value:"due",children:"Due for Popby"}),e.jsx(Qt,{value:"activity",children:"Recent Activity"}),e.jsx(Qt,{value:"library",children:"Popby Library"}),e.jsx(Qt,{value:"templates",children:"Popby Templates"})]}),e.jsxs(Jt,{value:"due",className:"space-y-4 mt-4",children:[e.jsx(eLn,{contacts:t||[],onLogPopby:K=>{y(K),v(!0)}}),!t||t.length===0?e.jsx(_e,{children:e.jsxs(Oe,{className:"p-8 text-center text-muted-foreground",children:[e.jsx(Co,{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(_e,{className:"hover:shadow-md transition-shadow",children:e.jsx(Oe,{className:"p-4",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("span",{className:"font-medium",children:[K.first_name," ",K.last_name]}),K.daysOverdue>0&&e.jsxs($e,{variant:"destructive",className:"text-xs",children:[K.daysOverdue,"+ days overdue"]}),K.daysSinceLastPopby===null&&e.jsx($e,{variant:"outline",className:"text-xs",children:"Never visited"})]}),e.jsxs("div",{className:"flex items-center gap-4 mt-1 text-sm text-muted-foreground",children:[K.address&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(ai,{className:"h-3 w-3"}),K.city||K.address]}),K.tags&&K.tags.length>0&&e.jsx("span",{children:K.tags.map(Q=>{var J;return(J=Q.relationship_type)==null?void 0:J.name}).join(", ")})]}),K.lastPopby&&e.jsxs("p",{className:"text-xs text-muted-foreground mt-1",children:["Last popby: ",Hs(new Date(K.lastPopby),"MMM d, yyyy")]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[K.phone&&e.jsx($,{size:"sm",variant:"ghost",asChild:!0,children:e.jsx("a",{href:`tel:${K.phone}`,children:e.jsx(ya,{className:"h-4 w-4"})})}),e.jsxs($,{size:"sm",onClick:()=>{y(K),v(!0)},children:[e.jsx(Ro,{className:"h-4 w-4 mr-1"}),"Log Popby"]})]})]})})},K.id))})]}),e.jsx(Jt,{value:"activity",className:"space-y-4 mt-4",children:!i||i.length===0?e.jsx(_e,{children:e.jsxs(Oe,{className:"p-8 text-center text-muted-foreground",children:[e.jsx(Hr,{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(_e,{children:[e.jsx(Bt,{children:e.jsx(Ut,{className:"text-lg",children:"Recent Popby Log"})}),e.jsx(Oe,{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(Co,{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)}),x(K.popby_item_id)&&e.jsx($e,{variant:"secondary",className:"text-xs",children:x(K.popby_item_id)})]}),e.jsx("div",{className:"text-sm text-muted-foreground",children:Hs(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(Jt,{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(_e,{children:e.jsx(Oe,{className:"p-4",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:"p-2 bg-primary/10 rounded-lg",children:e.jsx(Co,{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($e,{variant:"secondary",className:"mt-2 text-xs",children:"Shared"})]})]})})},K.id)),e.jsx(_e,{className:"border-dashed cursor-pointer hover:bg-muted/50 transition-colors",onClick:()=>T(!0),children:e.jsx(Oe,{className:"p-4 flex items-center justify-center h-full min-h-[100px]",children:e.jsxs("div",{className:"text-center text-muted-foreground",children:[e.jsx(sn,{className:"h-8 w-8 mx-auto mb-2"}),e.jsx("p",{children:"Add New Popby Idea"})]})})})]})}),e.jsxs(Jt,{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,Q)=>e.jsx(_e,{children:e.jsxs(Oe,{className:"p-4",children:[e.jsx(on,{className:"aspect-[3/2] w-full rounded-lg mb-4"}),e.jsx(on,{className:"h-5 w-3/4 mb-2"}),e.jsx(on,{className:"h-4 w-full mb-4"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(on,{className:"h-5 w-16"}),e.jsx(on,{className:"h-5 w-20"})]})]})},Q))}),!m&&h.length===0&&e.jsx(_e,{children:e.jsxs(Oe,{className:"p-8 text-center text-muted-foreground",children:[e.jsx(Tu,{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(_e,{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(Oe,{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:EZ(K.description)}),e.jsx("div",{className:"flex flex-wrap gap-2 mb-3",children:e.jsx($e,{variant:"secondary",className:"text-xs",children:"PopBys"})}),e.jsxs("div",{className:"flex items-center gap-4 text-sm text-muted-foreground mb-3",children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Ox,{className:"h-3.5 w-3.5"}),K.likesCount]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Ed,{className:"h-3.5 w-3.5"}),K.commentsCount]})]}),e.jsxs($,{size:"sm",className:"w-full gap-2",onClick:Q=>{Q.stopPropagation(),s(`/templates/${K.id}`)},children:[e.jsx(Tr,{className:"h-4 w-4"}),"View Template"]})]})]},K.id))})]})]}),e.jsx(Os,{open:b,onOpenChange:v,children:e.jsxs(Rs,{children:[e.jsx(Us,{children:e.jsxs(zs,{children:["Log Popby for ",g==null?void 0:g.first_name," ",g==null?void 0:g.last_name]})}),e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Popby Item (optional)"}),e.jsxs(vs,{value:P.popby_item_id,onValueChange:K=>M(Q=>({...Q,popby_item_id:K})),children:[e.jsx(gs,{children:e.jsx(bs,{placeholder:"Select a popby item..."})}),e.jsx(ys,{children:n==null?void 0:n.map(K=>e.jsx(Ye,{value:K.id,children:K.name},K.id))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Notes (optional)"}),e.jsx(Is,{placeholder:"Any notes about this popby...",value:P.notes,onChange:K=>M(Q=>({...Q,notes:K.target.value}))})]})]}),e.jsxs(kr,{children:[e.jsx($,{variant:"outline",onClick:()=>v(!1),children:"Cancel"}),e.jsx($,{onClick:B,disabled:c.isPending,children:"Log Popby"})]})]})}),e.jsx(Os,{open:N,onOpenChange:C,children:e.jsxs(Rs,{className:"max-w-md",children:[e.jsx(Us,{children:e.jsx(zs,{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(se,{className:"font-medium",children:K.name}),e.jsxs(vs,{value:V(K.id),onValueChange:Q=>W(K.id,Q),children:[e.jsx(gs,{className:"w-[180px]",children:e.jsx(bs,{})}),e.jsx(ys,{children:sLn.map(Q=>e.jsx(Ye,{value:Q.value,children:Q.label},Q.value))})]})]},K.id))]}),e.jsx(kr,{children:e.jsx($,{onClick:()=>C(!1),children:"Done"})})]})}),e.jsx(Os,{open:A,onOpenChange:T,children:e.jsxs(Rs,{children:[e.jsx(Us,{children:e.jsx(zs,{children:"Add Popby Idea"})}),e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Name *"}),e.jsx(be,{placeholder:"e.g., Homemade cookies",value:I.name,onChange:K=>D(Q=>({...Q,name:K.target.value}))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Description"}),e.jsx(Is,{placeholder:"Optional description...",value:I.description,onChange:K=>D(Q=>({...Q,description:K.target.value}))})]})]}),e.jsxs(kr,{children:[e.jsx($,{variant:"outline",onClick:()=>T(!1),children:"Cancel"}),e.jsx($,{onClick:q,disabled:!I.name.trim()||d.isPending,children:"Add Item"})]})]})})]})})}const rLn=tk({property_address:rl().min(1,"Property address is required"),city:rl().optional(),state:rl().optional(),zip:rl().optional(),transaction_type:aHe(["buyer","seller"]),close_date:rl().min(1,"Close date is required"),sale_price:pY().min(0,"Sale price must be positive"),commission_amount:pY().optional(),lead_source_id:rl().optional(),client_type_id:rl().optional(),contact_id:rl().optional(),notes:rl().optional(),is_win:Ags()});function Pqt({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=tAe(),m=vAs(),{data:p}=XO(),{data:x}=Hb(),{data:g}=M1(),y=QCe(),b=gGe(),{data:v}=sAe(),N=(v==null?void 0:v.show_commission)??!0,C=xCe({resolver:gCe(rLn),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?C.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}):C.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,C]);const A=async I=>{const D={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,...D}):await h.mutateAsync(D),t(!1)},T=async()=>{if(!i.trim())return;const[I,...D]=i.trim().split(" "),B=D.join(" ")||null,q=await y.mutateAsync({first_name:I,last_name:B,tagIds:[]});q&&(C.setValue("contact_id",q.id),l(""),c(!1),a(!1))},P=async()=>{if(!d.trim())return;const I=await b.mutateAsync(d.trim());I&&(C.setValue("lead_source_id",I.id),u(""))},M=g==null?void 0:g.find(I=>I.id===C.watch("contact_id"));return e.jsx(Os,{open:s,onOpenChange:t,children:e.jsxs(Rs,{className:"max-w-lg max-h-[90vh]",children:[e.jsx(Us,{children:e.jsx(zs,{children:n?"Edit Transaction":"Add Transaction"})}),e.jsx(Oi,{className:"max-h-[70vh] pr-4",children:e.jsx(_Ce,{...C,children:e.jsxs("form",{onSubmit:C.handleSubmit(A),className:"space-y-4",children:[e.jsx(Cp,{control:C.control,name:"property_address",render:({field:I})=>e.jsxs(Ym,{children:[e.jsx(Zm,{children:"Property Address *"}),e.jsx(Xm,{children:e.jsx(be,{placeholder:"123 Main St",...I})}),e.jsx(a1,{})]})}),e.jsxs("div",{className:"grid grid-cols-3 gap-2",children:[e.jsx(Cp,{control:C.control,name:"city",render:({field:I})=>e.jsxs(Ym,{children:[e.jsx(Zm,{children:"City"}),e.jsx(Xm,{children:e.jsx(be,{placeholder:"City",...I})})]})}),e.jsx(Cp,{control:C.control,name:"state",render:({field:I})=>e.jsxs(Ym,{children:[e.jsx(Zm,{children:"State"}),e.jsx(Xm,{children:e.jsx(be,{placeholder:"TX",...I})})]})}),e.jsx(Cp,{control:C.control,name:"zip",render:({field:I})=>e.jsxs(Ym,{children:[e.jsx(Zm,{children:"Zip"}),e.jsx(Xm,{children:e.jsx(be,{placeholder:"75001",...I})})]})})]}),e.jsx(Cp,{control:C.control,name:"transaction_type",render:({field:I})=>e.jsxs(Ym,{children:[e.jsx(Zm,{children:"Transaction Type *"}),e.jsxs(vs,{onValueChange:I.onChange,value:I.value,children:[e.jsx(Xm,{children:e.jsx(gs,{children:e.jsx(bs,{placeholder:"Select type"})})}),e.jsxs(ys,{children:[e.jsx(Ye,{value:"buyer",children:"Buyer"}),e.jsx(Ye,{value:"seller",children:"Seller"})]})]}),e.jsx(a1,{})]})}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsx(Cp,{control:C.control,name:"close_date",render:({field:I})=>e.jsxs(Ym,{children:[e.jsx(Zm,{children:"Close Date *"}),e.jsx(Xm,{children:e.jsx(be,{type:"date",...I})}),e.jsx(a1,{})]})}),e.jsx(Cp,{control:C.control,name:"sale_price",render:({field:I})=>e.jsxs(Ym,{children:[e.jsx(Zm,{children:"Sale Price *"}),e.jsx(Xm,{children:e.jsx(be,{type:"number",placeholder:"0",...I,onChange:D=>I.onChange(Number(D.target.value))})}),e.jsx(a1,{})]})})]}),N&&e.jsx(Cp,{control:C.control,name:"commission_amount",render:({field:I})=>e.jsxs(Ym,{children:[e.jsx(Zm,{children:"Commission"}),e.jsx(Xm,{children:e.jsx(be,{type:"number",placeholder:"0",...I,value:I.value??"",onChange:D=>I.onChange(D.target.value?Number(D.target.value):void 0)})})]})}),e.jsx(Cp,{control:C.control,name:"lead_source_id",render:({field:I})=>e.jsxs(Ym,{children:[e.jsx(Zm,{children:"Lead Source"}),e.jsxs(vs,{onValueChange:I.onChange,value:I.value||"",children:[e.jsx(Xm,{children:e.jsx(gs,{children:e.jsx(bs,{placeholder:"Select source"})})}),e.jsx(ys,{children:p==null?void 0:p.map(D=>e.jsx(Ye,{value:D.id,children:D.name},D.id))})]})]})}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(be,{placeholder:"Add custom source...",value:d,onChange:I=>u(I.target.value),className:"flex-1"}),e.jsx($,{type:"button",variant:"outline",size:"icon",onClick:P,disabled:!d.trim(),children:e.jsx(sn,{className:"h-4 w-4"})})]}),e.jsx(Cp,{control:C.control,name:"client_type_id",render:({field:I})=>e.jsxs(Ym,{children:[e.jsx(Zm,{children:"Client Type"}),e.jsxs(vs,{onValueChange:I.onChange,value:I.value||"",children:[e.jsx(Xm,{children:e.jsx(gs,{children:e.jsx(bs,{placeholder:"Select client type"})})}),e.jsx(ys,{children:x==null?void 0:x.map(D=>e.jsx(Ye,{value:D.id,children:D.name},D.id))})]})]})}),e.jsx(Cp,{control:C.control,name:"contact_id",render:({field:I})=>e.jsxs(Ym,{children:[e.jsx(Zm,{children:"Client Contact"}),e.jsxs(Sc,{open:r,onOpenChange:a,children:[e.jsx(Cc,{asChild:!0,children:e.jsx(Xm,{children:e.jsxs($,{variant:"outline",role:"combobox",className:Tt("w-full justify-between",!I.value&&"text-muted-foreground"),children:[M?`${M.first_name} ${M.last_name||""}`.trim():"Select contact",e.jsx(sw,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})})}),e.jsxs(xc,{className:"w-full p-0",align:"start",children:[e.jsxs(pw,{children:[e.jsx(fw,{placeholder:"Search contacts..."}),e.jsxs(xw,{children:[e.jsx(gw,{children:e.jsxs("div",{className:"p-2 space-y-2",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"No contact found."}),!o&&e.jsxs($,{variant:"outline",size:"sm",className:"w-full",onClick:()=>c(!0),children:[e.jsx(sn,{className:"h-4 w-4 mr-2"}),"Add New Contact"]})]})}),e.jsx($b,{children:g==null?void 0:g.map(D=>e.jsxs(iv,{value:`${D.first_name} ${D.last_name||""}`,onSelect:()=>{I.onChange(D.id),a(!1)},children:[e.jsx(oa,{className:Tt("mr-2 h-4 w-4",D.id===I.value?"opacity-100":"opacity-0")}),D.first_name," ",D.last_name||""]},D.id))})]})]}),o&&e.jsxs("div",{className:"p-2 border-t space-y-2",children:[e.jsx(be,{placeholder:"Enter contact name...",value:i,onChange:D=>l(D.target.value)}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx($,{size:"sm",onClick:T,disabled:!i.trim()||y.isPending,children:"Add Contact"}),e.jsx($,{size:"sm",variant:"outline",onClick:()=>{c(!1),l("")},children:"Cancel"})]})]})]})]})]})}),e.jsx(Cp,{control:C.control,name:"notes",render:({field:I})=>e.jsxs(Ym,{children:[e.jsx(Zm,{children:"Notes"}),e.jsx(Xm,{children:e.jsx(Is,{placeholder:"Any notes about this transaction...",...I})})]})}),e.jsx(Cp,{control:C.control,name:"is_win",render:({field:I})=>e.jsxs(Ym,{className:"flex items-center justify-between rounded-lg border p-3",children:[e.jsxs("div",{className:"space-y-0.5",children:[e.jsx(Zm,{children:"Mark as Win 🏆"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Highlight this as a notable success"})]}),e.jsx(Xm,{children:e.jsx(Tn,{checked:I.value,onCheckedChange:I.onChange})})]})}),e.jsxs("div",{className:"flex justify-end gap-2 pt-4",children:[e.jsx($,{type:"button",variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsxs($,{type:"submit",disabled:h.isPending||m.isPending,children:[n?"Update":"Add"," Transaction"]})]})]})})})]})})}function rXe({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,x]=j.useState("all"),[g,y]=j.useState("all"),[b,v]=j.useState(!1),N=bAs(),C=tAe(),{data:A}=XO();Hb();const T=dV(),P=D=>{const{id:B,created_at:q,updated_at:W,lead_source:V,client_type:K,contact:Q,...J}=D;C.mutate(J)},M=()=>{o&&(N.mutate(o),c(null))},I=s.filter(D=>{var Q,J,ce,ue;const B=d===""||D.property_address.toLowerCase().includes(d.toLowerCase())||((J=(Q=D.contact)==null?void 0:Q.first_name)==null?void 0:J.toLowerCase().includes(d.toLowerCase()))||((ue=(ce=D.contact)==null?void 0:ce.last_name)==null?void 0:ue.toLowerCase().includes(d.toLowerCase())),q=h==="all"||D.transaction_type===h,W=p==="all"||D.lead_source_id===p,V=g==="all"||D.client_type_id===g,K=!b||D.is_win;return B&&q&&W&&V&&K});return n?e.jsx(_e,{children:e.jsx(Oe,{className:"p-6 space-y-4",children:[1,2,3].map(D=>e.jsx(on,{className:"h-16 w-full"},D))})}):e.jsxs(e.Fragment,{children:[e.jsxs(_e,{children:[e.jsx(Bt,{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(Ut,{children:["Transactions (",I.length,")"]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs("div",{className:"relative",children:[e.jsx(Vr,{className:"absolute left-2.5 top-2.5 h-4 w-4 text-muted-foreground"}),e.jsx(be,{placeholder:"Search...",value:d,onChange:D=>u(D.target.value),className:"pl-8 w-[150px]"})]}),e.jsxs(vs,{value:h,onValueChange:m,children:[e.jsx(gs,{className:"w-[100px]",children:e.jsx(bs,{placeholder:"Type"})}),e.jsxs(ys,{children:[e.jsx(Ye,{value:"all",children:"All Types"}),e.jsx(Ye,{value:"buyer",children:"Buyer"}),e.jsx(Ye,{value:"seller",children:"Seller"})]})]}),e.jsxs(vs,{value:p,onValueChange:x,children:[e.jsx(gs,{className:"w-[130px]",children:e.jsx(bs,{placeholder:"Lead Source"})}),e.jsxs(ys,{children:[e.jsx(Ye,{value:"all",children:"All Sources"}),A==null?void 0:A.map(D=>e.jsx(Ye,{value:D.id,children:D.name},D.id))]})]}),e.jsxs($,{variant:b?"default":"outline",size:"sm",onClick:()=>v(!b),children:[e.jsx(pu,{className:"h-4 w-4 mr-1"}),"Wins"]})]})]})}),e.jsx(Oe,{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(D=>e.jsxs(_e,{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:D.property_address}),D.is_win&&e.jsx(pu,{className:"h-4 w-4 text-yellow-500 flex-shrink-0"})]}),e.jsxs("div",{className:"text-sm text-muted-foreground",children:[D.city,D.state?`, ${D.state}`:""]})]}),e.jsx($e,{variant:D.transaction_type==="buyer"?"default":"secondary",children:D.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: "}),ert(D.close_date)]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Price: "}),Au(D.sale_price)]}),t&&D.commission_amount&&e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Commission: "}),Au(D.commission_amount)]}),D.lead_source&&e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Source: "}),D.lead_source.name]}),D.contact&&e.jsxs("div",{className:"col-span-2",children:[e.jsx("span",{className:"text-muted-foreground",children:"Client: "}),D.contact.first_name," ",D.contact.last_name]}),r&&e.jsxs("div",{className:"col-span-2",children:[e.jsx("span",{className:"text-muted-foreground",children:"Agent: "}),r[D.owner_user_id]||"Unknown"]})]}),!a&&e.jsxs("div",{className:"flex justify-end gap-2 mt-3 pt-3 border-t",children:[e.jsx($,{variant:"ghost",size:"sm",onClick:()=>l(D),children:e.jsx(bm,{className:"h-4 w-4"})}),e.jsx($,{variant:"ghost",size:"sm",onClick:()=>P(D),children:e.jsx(Ca,{className:"h-4 w-4"})}),e.jsx($,{variant:"ghost",size:"sm",onClick:()=>c(D.id),children:e.jsx(Pn,{className:"h-4 w-4 text-destructive"})})]})]},D.id))}):e.jsx("div",{className:"overflow-x-auto",children:e.jsxs(Va,{children:[e.jsx(Ha,{children:e.jsxs(hn,{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(Ga,{children:I.map(D=>{var B;return e.jsxs(hn,{children:[r&&e.jsx(gt,{className:"font-medium text-sm",children:r[D.owner_user_id]||"Unknown"}),e.jsx(gt,{children:e.jsxs("div",{className:"flex items-center gap-2",children:[D.is_win&&e.jsx(pu,{className:"h-4 w-4 text-yellow-500"}),e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:D.property_address}),e.jsxs("div",{className:"text-sm text-muted-foreground",children:[D.city,D.state?`, ${D.state}`:""]})]})]})}),e.jsx(gt,{children:e.jsx($e,{variant:D.transaction_type==="buyer"?"default":"secondary",children:D.transaction_type})}),e.jsx(gt,{children:ert(D.close_date)}),e.jsx(gt,{children:Au(D.sale_price)}),t&&e.jsx(gt,{children:D.commission_amount?Au(D.commission_amount):"-"}),e.jsx(gt,{children:((B=D.lead_source)==null?void 0:B.name)||"-"}),e.jsx(gt,{children:D.contact?`${D.contact.first_name} ${D.contact.last_name||""}`.trim():"-"}),!a&&e.jsx(gt,{children:e.jsxs(Hd,{children:[e.jsx(Gd,{asChild:!0,children:e.jsx($,{variant:"ghost",size:"icon",children:e.jsx(cy,{className:"h-4 w-4"})})}),e.jsxs(Md,{align:"end",children:[e.jsxs(Na,{onClick:()=>l(D),children:[e.jsx(bm,{className:"h-4 w-4 mr-2"}),"Edit"]}),e.jsxs(Na,{onClick:()=>P(D),children:[e.jsx(Ca,{className:"h-4 w-4 mr-2"}),"Duplicate"]}),e.jsxs(Na,{onClick:()=>c(D.id),className:"text-destructive",children:[e.jsx(Pn,{className:"h-4 w-4 mr-2"}),"Delete"]})]})]})})]},D.id)})})]})})})]}),e.jsx(Pqt,{open:!!i,onOpenChange:D=>!D&&l(null),transaction:i||void 0}),e.jsx(Ll,{open:!!o,onOpenChange:D=>!D&&c(null),children:e.jsxs(yl,{children:[e.jsxs(vl,{children:[e.jsx(_l,{children:"Delete Transaction?"}),e.jsx(wl,{children:"This action cannot be undone. This will permanently delete this transaction."})]}),e.jsxs(bl,{children:[e.jsx(jl,{children:"Cancel"}),e.jsx(fl,{onClick:M,className:"bg-destructive text-destructive-foreground",children:"Delete"})]})]})})]})}function Iqt({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 x=Math.min(m/p*100,100),g=Math.max(p-m,0),y=l>0?g/l:0,b=i/12*100,v=x>=b?"ahead":x>=b*.8?"on-track":"behind";return{percent:x,remaining:g,pace:y,status:v}},c=o(t.totalTransactions,s.transactions_goal),d=o(t.totalVolume,s.volume_goal),u=r?o(t.totalCommission,s.gci_goal):null,h=m=>{switch(m){case"ahead":return e.jsxs($e,{className:"bg-green-500 text-white",children:[e.jsx(Il,{className:"h-3 w-3 mr-1"}),"Ahead"]});case"on-track":return e.jsxs($e,{variant:"secondary",children:[e.jsx(DN,{className:"h-3 w-3 mr-1"}),"On Track"]});case"behind":return e.jsxs($e,{variant:"destructive",children:[e.jsx(FN,{className:"h-3 w-3 mr-1"}),"Behind"]});default:return null}};return!s.transactions_goal&&!s.volume_goal&&!s.gci_goal?null:e.jsxs(_e,{children:[e.jsx(Bt,{className:"pb-3",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Mu,{className:"h-5 w-5 text-primary"}),e.jsxs(Ut,{children:[n," Goals Progress"]})]})}),e.jsx(Oe,{children:e.jsxs("div",{className:"grid md:grid-cols-3 gap-6",children:[s.transactions_goal&&c&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-sm font-medium",children:"Transactions"}),h(c.status)]}),e.jsx(Ki,{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(Ki,{value:d.percent,className:"h-2"}),e.jsxs("div",{className:"flex justify-between text-sm text-muted-foreground",children:[e.jsxs("span",{children:[Au(t.totalVolume,!0)," of ",Au(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 ",Au(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(Ki,{value:u.percent,className:"h-2"}),e.jsxs("div",{className:"flex justify-between text-sm text-muted-foreground",children:[e.jsxs("span",{children:[Au(t.totalCommission,!0)," of ",Au(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 ",Au(u.pace,!0),"/month"]})]})]})})]})}const aLn={light:"",dark:".dark"},Dqt=j.createContext(null);function Rqt(){const s=j.useContext(Dqt);if(!s)throw new Error("useChart must be used within a ");return s}const Oqt=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(Dqt.Provider,{value:{config:r},children:e.jsxs("div",{"data-chart":o,ref:i,className:Tt("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(iLn,{id:o,config:r}),e.jsx(Ob,{children:n})]})})});Oqt.displayName="Chart";const iLn=({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(aLn).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},Fqt=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:x}=Rqt(),g=j.useMemo(()=>{var A;if(a||!(t!=null&&t.length))return null;const[b]=t,v=`${m||b.dataKey||b.name||"value"}`,N=cUe(x,b,v),C=!m&&typeof l=="string"?((A=x[l])==null?void 0:A.label)||l:N==null?void 0:N.label;return o?e.jsx("div",{className:Tt("font-medium",c),children:o(C,t)}):C?e.jsx("div",{className:Tt("font-medium",c),children:C}):null},[l,o,t,a,c,x,m]);if(!s||!(t!=null&&t.length))return null;const y=t.length===1&&r!=="dot";return e.jsxs("div",{ref:p,className:Tt("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:g,e.jsx("div",{className:"grid gap-1.5",children:t.map((b,v)=>{const N=`${h||b.name||b.dataKey||"value"}`,C=cUe(x,b,N),A=u||b.payload.fill||b.color;return e.jsx("div",{className:Tt("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&&(b==null?void 0:b.value)!==void 0&&b.name?d(b.value,b.name,b,v,b.payload):e.jsxs(e.Fragment,{children:[C!=null&&C.icon?e.jsx(C.icon,{}):!i&&e.jsx("div",{className:Tt("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:Tt("flex flex-1 justify-between leading-none",y?"items-end":"items-center"),children:[e.jsxs("div",{className:"grid gap-1.5",children:[y?g:null,e.jsx("span",{className:"text-muted-foreground",children:(C==null?void 0:C.label)||b.name})]}),b.value&&e.jsx("span",{className:"font-mono font-medium tabular-nums text-foreground",children:b.value.toLocaleString()})]})]})},b.dataKey)})})]})});Fqt.displayName="ChartTooltip";const oLn=j.forwardRef(({className:s,hideIcon:t=!1,payload:n,verticalAlign:r="bottom",nameKey:a},i)=>{const{config:l}=Rqt();return n!=null&&n.length?e.jsx("div",{ref:i,className:Tt("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=cUe(l,o,c);return e.jsxs("div",{className:Tt("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});oLn.displayName="ChartLegend";function cUe(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 mae=["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 aXe({stats:s,year:t}){const n=s.transactionsByMonth.some(a=>a.count>0),r=s.leadSourceBreakdown.length>0;return!n&&!r?e.jsx(_e,{children:e.jsx(Oe,{className:"py-12 text-center text-muted-foreground",children:"Add transactions to see your performance charts"})}):e.jsxs("div",{className:"grid gap-6",children:[n&&e.jsxs(_e,{className:"overflow-hidden",children:[e.jsx(Bt,{children:e.jsx(Ut,{className:"text-base",children:"Transactions by Month"})}),e.jsx(Oe,{className:"overflow-hidden",children:e.jsx(Oqt,{config:{count:{label:"Transactions",color:"hsl(var(--primary))"}},className:"h-[250px]",children:e.jsx(Ob,{width:"100%",height:"100%",children:e.jsxs(REe,{data:s.transactionsByMonth,margin:{top:5,right:10,left:0,bottom:5},children:[e.jsx(AO,{strokeDasharray:"3 3",className:"stroke-muted"}),e.jsx(k1,{dataKey:"month",tick:{fontSize:11},className:"fill-muted-foreground",interval:0}),e.jsx(S1,{allowDecimals:!1,tick:{fontSize:12},className:"fill-muted-foreground",width:30}),e.jsx(yf,{content:e.jsx(Fqt,{})}),e.jsx(i2,{dataKey:"count",fill:"hsl(var(--primary))",radius:[4,4,0,0],name:"Transactions"})]})})})})]}),r&&e.jsxs(_e,{children:[e.jsx(Bt,{children:e.jsx(Ut,{className:"text-base",children:"Lead Sources"})}),e.jsxs(Oe,{children:[e.jsx("div",{className:"h-[250px]",children:e.jsx(Ob,{width:"100%",height:"100%",children:e.jsxs(oYe,{children:[e.jsx(ok,{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(eV,{fill:mae[i%mae.length]},`cell-${i}`))}),e.jsx(yf,{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:mae[i%mae.length]}}),e.jsx("span",{className:"text-muted-foreground",children:a.name})]},a.name))})]})]})]})}function lLn(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=pHe(t,r,new Date);if(EFe(a))return Hs(a,"yyyy-MM-dd")}catch{}try{const r=new Date(t);if(EFe(r))return Hs(r,"yyyy-MM-dd")}catch{}return null}const cLn=["property_address","city","state","zip","transaction_type","close_date","sale_price","commission_amount","lead_source","client_type","is_win","notes"];function dLn({open:s,onOpenChange:t}){const[n,r]=j.useState([]),[a,i]=j.useState(!1),[l,o]=j.useState(0),{data:c}=XO(),{data:d}=Hb(),u=tAe(),h=()=>{const b=cLn.join(","),v=["123 Main St","Dallas","TX","75001","buyer","2024-06-15","450000","13500","Referral","Past Client","yes","Great transaction!"].join(","),N=`${b} ${v}`,C=new Blob([N],{type:"text/csv"}),A=URL.createObjectURL(C),T=document.createElement("a");T.href=A,T.download="transaction-import-template.csv",T.click(),URL.revokeObjectURL(A)},m=b=>{const v=b.split(` `).filter(C=>C.trim());if(v.length<2)return[];const N=v[0].split(",").map(C=>C.trim().toLowerCase().replace(/['"]/g,""));return v.slice(1).map((C,A)=>{var J,ce,ue,ne;const T=[];let P="",M=!1;for(const ee of C)ee==='"'?M=!M:ee===","&&!M?(T.push(P.trim()),P=""):P+=ee;T.push(P.trim());const I=ee=>{var he;const le=N.indexOf(ee);return le>=0?(he=T[le])==null?void 0:he.replace(/^["']|["']$/g,"").trim():""},D=(J=I("transaction_type"))==null?void 0:J.toLowerCase(),B=(ce=I("sale_price"))==null?void 0:ce.replace(/[$,]/g,""),q=(ue=I("commission_amount"))==null?void 0:ue.replace(/[$,]/g,""),W=(ne=I("is_win"))==null?void 0:ne.toLowerCase(),V=I("close_date"),K=lLn(V);let Q;return I("property_address")?["buyer","seller"].includes(D)?K?(!B||isNaN(Number(B)))&&(Q="Invalid sale price"):Q=`Invalid date format: "${V}" - use MM/DD/YYYY or YYYY-MM-DD`:Q='Transaction type must be "buyer" or "seller"':Q="Missing property address",{property_address:I("property_address"),city:I("city"),state:I("state"),zip:I("zip"),transaction_type:D==="seller"?"seller":"buyer",close_date:K||"",sale_price:Number(B)||0,commission_amount:q?Number(q):null,lead_source_name:I("lead_source"),client_type_name:I("client_type"),is_win:["yes","true","1"].includes(W),notes:I("notes"),error:Q}})},p=b=>{var C;const v=(C=b.target.files)==null?void 0:C[0];if(!v)return;const N=new FileReader;N.onload=A=>{var M;const T=(M=A.target)==null?void 0:M.result,P=m(T);r(P)},N.readAsText(v)},x=async()=>{const b=n.filter(C=>!C.error);if(b.length===0){ae.error("No valid transactions to import");return}i(!0),o(0);let v=0,N=0;for(let C=0;CM.name.toLowerCase()===A.lead_source_name.toLowerCase()),P=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:(P==null?void 0:P.id)||null,contact_id:null,notes:A.notes||null,is_win:A.is_win}),v++}catch(T){N++,console.error("Failed to import transaction:",T)}o(Math.round((C+1)/b.length*100))}i(!1),v>0&&ae.success(`Imported ${v} transaction${v>1?"s":""}`),N>0&&ae.error(`Failed to import ${N} transaction${N>1?"s":""}`),r([]),t(!1)},g=n.filter(b=>!b.error).length,y=n.filter(b=>b.error).length;return e.jsx(Os,{open:s,onOpenChange:t,children:e.jsxs(Rs,{className:"max-w-2xl max-h-[90vh]",children:[e.jsxs(Us,{children:[e.jsx(zs,{children:"Import Transactions"}),e.jsx(Sr,{children:"Upload a CSV file with your past transactions"})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between p-3 border rounded-lg bg-muted/50",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:"Download Template"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Get a CSV template with the correct format"})]}),e.jsxs($,{variant:"outline",onClick:h,children:[e.jsx(di,{className:"h-4 w-4 mr-2"}),"Template"]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"csv-file",children:"Upload CSV File"}),e.jsx(be,{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($e,{variant:"outline",children:[n.length," rows found"]}),g>0&&e.jsxs($e,{className:"bg-green-500 text-white",children:[e.jsx(oa,{className:"h-3 w-3 mr-1"}),g," valid"]}),y>0&&e.jsxs($e,{variant:"destructive",children:[e.jsx(xo,{className:"h-3 w-3 mr-1"}),y," errors"]})]}),e.jsx(Oi,{className:"h-[200px] border rounded-lg",children:e.jsxs("div",{className:"p-2 space-y-2",children:[n.slice(0,10).map((b,v)=>e.jsxs("div",{className:`p-2 rounded text-sm ${b.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:b.property_address||"(no address)"}),e.jsx($e,{variant:b.transaction_type==="buyer"?"default":"secondary",children:b.transaction_type})]}),e.jsxs("div",{className:"text-muted-foreground",children:[b.close_date," • $",b.sale_price.toLocaleString()]}),b.error&&e.jsx(dX,{variant:"destructive",className:"mt-1 py-1",children:e.jsx(uX,{className:"text-xs",children:b.error})})]},v)),n.length>10&&e.jsxs("p",{className:"text-center text-sm text-muted-foreground",children:["...and ",n.length-10," more"]})]})}),a&&e.jsxs("div",{className:"space-y-2",children:[e.jsx("div",{className:"w-full bg-muted rounded-full h-2",children:e.jsx("div",{className:"bg-primary h-2 rounded-full transition-all",style:{width:`${l}%`}})}),e.jsxs("p",{className:"text-sm text-center text-muted-foreground",children:["Importing... ",l,"%"]})]})]}),e.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[e.jsx($,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsxs($,{onClick:x,disabled:g===0||a,children:[e.jsx(si,{className:"h-4 w-4 mr-2"}),"Import ",g," Transaction",g!==1?"s":""]})]})]})]})})}const uLn=tk({transactions_goal:pY().min(0).optional(),volume_goal:pY().min(0).optional(),gci_goal:pY().min(0).optional()});function hLn({open:s,onOpenChange:t,year:n,existingGoals:r}){const a=_As(),{data:i}=sAe(),l=(i==null?void 0:i.show_commission)??!0,o=xCe({resolver:gCe(uLn),defaultValues:{transactions_goal:void 0,volume_goal:void 0,gci_goal:void 0}});j.useEffect(()=>{r?o.reset({transactions_goal:r.transactions_goal??void 0,volume_goal:r.volume_goal?Number(r.volume_goal):void 0,gci_goal:r.gci_goal?Number(r.gci_goal):void 0}):o.reset({transactions_goal:void 0,volume_goal:void 0,gci_goal:void 0})},[r,o,s]);const c=async d=>{await a.mutateAsync({year:n,transactions_goal:d.transactions_goal??null,volume_goal:d.volume_goal??null,gci_goal:l?d.gci_goal??null:null}),t(!1)};return e.jsx(Os,{open:s,onOpenChange:t,children:e.jsxs(Rs,{className:"max-w-md",children:[e.jsxs(Us,{children:[e.jsxs(zs,{children:[n," Goals"]}),e.jsx(Sr,{children:"Set your annual targets to track your progress throughout the year."})]}),e.jsx(_Ce,{...o,children:e.jsxs("form",{onSubmit:o.handleSubmit(c),className:"space-y-4",children:[e.jsx(Cp,{control:o.control,name:"transactions_goal",render:({field:d})=>e.jsxs(Ym,{children:[e.jsx(Zm,{children:"Transactions Goal"}),e.jsx(Xm,{children:e.jsx(be,{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(g2e,{children:"Total number of deals you want to close"}),e.jsx(a1,{})]})}),e.jsx(Cp,{control:o.control,name:"volume_goal",render:({field:d})=>e.jsxs(Ym,{children:[e.jsx(Zm,{children:"Volume Goal ($)"}),e.jsx(Xm,{children:e.jsx(be,{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(g2e,{children:"Total sales volume you want to achieve"}),e.jsx(a1,{})]})}),l&&e.jsx(Cp,{control:o.control,name:"gci_goal",render:({field:d})=>e.jsxs(Ym,{children:[e.jsx(Zm,{children:"GCI Goal ($)"}),e.jsx(Xm,{children:e.jsx(be,{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(g2e,{children:"Gross commission income target"}),e.jsx(a1,{})]})}),e.jsxs("div",{className:"flex justify-end gap-2 pt-4",children:[e.jsx($,{type:"button",variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsx($,{type:"submit",disabled:a.isPending,children:"Save Goals"})]})]})})]})})}function iXe({transactions:s,isLoading:t}){const n=j.useRef(null),r=j.useRef(null),a=j.useRef([]),i=j.useRef(null),{isAdmin:l}=_s(),[o,c]=j.useState(""),[d,u]=j.useState(!0),[h,m]=j.useState(0),[p,x]=j.useState(!1),g=s.filter(b=>b.latitude!=null&&b.longitude!=null),y=s.filter(b=>b.latitude==null||b.longitude==null);return j.useEffect(()=>{(async()=>{u(!0);try{const{data:v}=await U.from("settings").select("value").eq("key","mapbox_public_token").maybeSingle();v!=null&&v.value&&c(v.value)}catch(v){console.error("Error fetching mapbox token:",v)}u(!1)})()},[]),j.useEffect(()=>{if(!o||y.length===0||p)return;(async()=>{var N;x(!0);let v=0;for(const C of y){const A=[C.property_address,C.city,C.state,C.zip].filter(Boolean).join(", ");if(A)try{const P=await(await fetch(`https://api.mapbox.com/geocoding/v5/mapbox.places/${encodeURIComponent(A)}.json?access_token=${o}&limit=1`)).json();if((N=P.features)!=null&&N[0]){const[M,I]=P.features[0].center;await U.from("scorecard_transactions").update({latitude:I,longitude:M}).eq("id",C.id),C.latitude=I,C.longitude=M,v++}}catch(T){console.error("Geocode error:",T)}}m(v),x(!1)})()},[o,s]),j.useEffect(()=>{if(!n.current||!o||r.current)return;Wc.accessToken=o;const b=s.filter(C=>C.latitude!=null&&C.longitude!=null);let v=[-98.5795,39.8283],N=4;if(b.length>0){const C=b.reduce((T,P)=>T+P.longitude,0)/b.length,A=b.reduce((T,P)=>T+P.latitude,0)/b.length;v=[C,A],N=b.length===1?12:10}return r.current=new Wc.Map({container:n.current,style:"mapbox://styles/mapbox/light-v11",zoom:N,center:v}),r.current.addControl(new Wc.NavigationControl,"top-right"),()=>{var C;(C=r.current)==null||C.remove(),r.current=null}},[o]),j.useEffect(()=>{var v;if(!r.current||!o)return;a.current.forEach(N=>N.remove()),a.current=[],(v=i.current)==null||v.remove();const b=s.filter(N=>N.latitude!=null&&N.longitude!=null);if(b.forEach(N=>{var I;const C=N.transaction_type==="buyer",A=C?"#3B82F6":"#10B981",T=document.createElement("div");T.className="cursor-pointer",T.innerHTML=`
${C?'':''}
`;const P=new Wc.Popup({offset:25,closeButton:!0}).setHTML(`
${N.property_address}
${N.city?`
${N.city}${N.state?", "+N.state:""} ${N.zip||""}
`:""}
${C?"Buyer":"Seller"} $${Number(N.sale_price).toLocaleString()}
Closed: ${mu(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 Wc.Marker(T).setLngLat([N.longitude,N.latitude]).setPopup(P).addTo(r.current);a.current.push(M)}),b.length>1){const N=new Wc.LngLatBounds;b.forEach(C=>N.extend([C.longitude,C.latitude])),r.current.fitBounds(N,{padding:60,maxZoom:13})}else b.length===1&&r.current.flyTo({center:[b[0].longitude,b[0].latitude],zoom:12})},[s,o,p]),d||t?e.jsx(_e,{children:e.jsx(Oe,{className:"flex items-center justify-center h-[50vh]",children:e.jsx("div",{className:"animate-spin rounded-full h-8 w-8 border-b-2 border-primary"})})}):o?s.length===0?e.jsx(_e,{children:e.jsxs(Oe,{className:"flex flex-col items-center justify-center h-[50vh] text-center gap-3",children:[e.jsx(ai,{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:[g.length," of ",s.length," mapped",p&&" · Geocoding..."]})]}),e.jsx("div",{ref:n,className:"w-full h-[55vh] rounded-lg shadow-lg border"})]}):e.jsx(_e,{children:e.jsxs(Oe,{className:"flex flex-col items-center justify-center h-[50vh] text-center gap-3",children:[e.jsx(xo,{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 zqt=()=>{const{data:s}=Nw();return ht({queryKey:["team-scorecard-members",s==null?void 0:s.teamId],queryFn:async()=>{const{data:t,error:n}=await U.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 U.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"})},mLn=s=>{const{data:t}=Nw(),{data:n}=zqt();return ht({queryKey:["team-scorecard-transactions",t==null?void 0:t.teamId,s],queryFn:async()=>{const r=n.map(o=>o.id);let a=U.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 pLn(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 fLn(s,t){return s?s.split(" ").map(n=>n[0]).join("").toUpperCase().slice(0,2):t[0].toUpperCase()}function xLn({year:s}){var m;const{data:t,isLoading:n}=zqt(),{data:r,isLoading:a}=mLn(s),i=Vn(),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(D=>pLn(D,r));p.sort((D,B)=>B.totalVolume-D.totalVolume);const x={};t.forEach(D=>{x[D.id]=D.name||D.email});const g=r.length,y=r.reduce((D,B)=>D+Number(B.sale_price),0),b=r.reduce((D,B)=>D+(Number(B.commission_amount)||0),0),v=r.filter(D=>D.transaction_type==="buyer").length,N=r.filter(D=>D.transaction_type==="seller").length,C={};r.forEach(D=>{var q;const B=((q=D.lead_source)==null?void 0:q.name)||"Unknown";C[B]=(C[B]||0)+1});const A=Object.entries(C).sort((D,B)=>B[1]-D[1])[0],T={};r.forEach(D=>{const B=mu(D.close_date).toLocaleString("default",{month:"short"});T[B]=(T[B]||0)+1});const M=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"].map(D=>({month:D,count:T[D]||0})),I=Object.entries(C).map(([D,B])=>({name:D,count:B})).sort((D,B)=>B.count-D.count);return{aggregate:{totalTxns:g,buyerCount:v,sellerCount:N,totalVolume:y,avgPrice:g>0?y/g:0,totalGCI:b,topSource:A?{name:A[0],count:A[1]}:null,memberCount:t.length},memberStats:p,topPerformer:p[0]||null,agentNameMap:x,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(on,{className:"h-24"},p))}),e.jsx(on,{className:"h-64"})]}):!o||c.length===0?e.jsx(_e,{className:"py-12",children:e.jsxs(Oe,{className:"text-center space-y-2",children:[e.jsx(qn,{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(_e,{children:e.jsxs(Oe,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(qn,{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(_e,{children:e.jsxs(Oe,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(sa,{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(_e,{children:e.jsxs(Oe,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(qd,{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:Au(o.totalVolume,!0)})]})}),e.jsx(_e,{children:e.jsxs(Oe,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(Il,{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:Au(o.avgPrice,!0)})]})}),e.jsx(_e,{children:e.jsxs(Oe,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(qd,{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:Au(o.totalGCI,!0)})]})}),e.jsx(_e,{children:e.jsxs(Oe,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(pu,{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(_e,{className:"border-primary/30 bg-primary/5",children:e.jsxs(Oe,{className:"pt-4 flex items-center gap-4",children:[e.jsx("div",{className:"flex items-center justify-center h-10 w-10 rounded-full bg-primary/10",children:e.jsx(pl,{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:Au(d.totalVolume,!0)})]})]})}),e.jsxs(_e,{children:[e.jsx(Bt,{children:e.jsx(Ut,{className:"text-lg",children:"Member Performance"})}),e.jsx(Oe,{children:e.jsx("div",{className:"overflow-x-auto",children:e.jsxs(Va,{children:[e.jsx(Ha,{children:e.jsxs(hn,{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(Ga,{children:c.map((p,x)=>e.jsxs(hn,{children:[e.jsx(gt,{children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("div",{className:"relative",children:[x===0&&p.totalTransactions>0&&e.jsx(pl,{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(ki,{src:p.member.avatar_url||void 0}),e.jsx(Ta,{className:"text-xs",children:fLn(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:Au(p.totalVolume,!0)}),e.jsx(gt,{className:"text-right text-sm",children:Au(p.averagePrice,!0)}),e.jsx(gt,{className:"text-right font-medium",children:Au(p.totalGCI,!0)}),e.jsx(gt,{className:"text-right",children:e.jsx($,{variant:"ghost",size:"sm",onClick:()=>i(`/mission-control/scorecard/${p.member.id}`),children:e.jsx(ga,{className:"h-4 w-4"})})})]},p.member.id))})]})})})]}),e.jsxs(ua,{defaultValue:"transactions",className:"space-y-4",children:[e.jsxs(ha,{children:[e.jsxs(Qt,{value:"transactions",children:[e.jsx(Sg,{className:"h-4 w-4 mr-1"}),"All Transactions"]}),e.jsxs(Qt,{value:"charts",children:[e.jsx(ml,{className:"h-4 w-4 mr-1"}),"Charts"]}),e.jsxs(Qt,{value:"map",children:[e.jsx(ai,{className:"h-4 w-4 mr-1"}),"Map"]})]}),e.jsx(Jt,{value:"transactions",children:e.jsx(rXe,{transactions:r||[],showCommission:!0,isLoading:a,agentNameMap:u,readOnly:!0})}),e.jsx(Jt,{value:"charts",children:h&&e.jsx(aXe,{stats:h,year:s})}),e.jsx(Jt,{value:"map",children:e.jsx(iXe,{transactions:r||[],isLoading:a})})]})]})}const TNe=new Date().getFullYear(),dvt=Array.from({length:10},(s,t)=>TNe-t),pae="all";function gLn(){var q;const[s,t]=j.useState(TNe),n=s===null?pae:String(s),r=W=>t(W===pae?null:Number(W)),[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:x}=Nw(),g=(x==null?void 0:x.role)==="team_leader",{data:y,isLoading:b}=yGe(s??void 0),{yearStats:v,lifetimeStats:N,isLoading:C,showCommission:A}=R6t(s??void 0),{data:T,isLoading:P}=D6t(s??TNe),{data:M}=sAe(),I=wAs(),D=()=>{if(!y||y.length===0)return;const W=["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 ne,ee;return[ue.property_address,ue.city||"",ue.state||"",ue.zip||"",ue.transaction_type,ue.close_date,ue.sale_price,...A?[ue.commission_amount||""]:[],((ne=ue.lead_source)==null?void 0:ne.name)||"",((ee=ue.client_type)==null?void 0:ee.name)||"",ue.contact?`${ue.contact.first_name} ${ue.contact.last_name||""}`.trim():"",ue.is_win?"Yes":"No",ue.notes||""]}),K=[W,...V].map(ue=>ue.map(ne=>`"${String(ne).replace(/"/g,'""')}"`).join(",")).join(` `),Q=new Blob([K],{type:"text/csv"}),J=URL.createObjectURL(Q),ce=document.createElement("a");ce.href=J,ce.download=s===null?"transactions-all.csv":`transactions-${s}.csv`,ce.click(),URL.revokeObjectURL(J)},B=!y||y.length===0;return e.jsxs(Ks,{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"})]}),g&&e.jsxs("div",{className:"flex items-center gap-1 bg-muted rounded-lg p-1 w-fit",children:[e.jsx($,{variant:m==="my"?"default":"ghost",size:"sm",onClick:()=>p("my"),className:"h-8",children:"My Scorecard"}),e.jsxs($,{variant:m==="team"?"default":"ghost",size:"sm",onClick:()=>p("team"),className:"h-8",children:[e.jsx(qn,{className:"h-4 w-4 mr-1.5"}),"Team"]})]}),m==="team"&&g?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(vs,{value:n,onValueChange:r,children:[e.jsx(gs,{className:"w-[140px]",children:e.jsx(bs,{})}),e.jsxs(ys,{children:[e.jsx(Ye,{value:pae,children:"All Years"}),dvt.map(W=>e.jsx(Ye,{value:String(W),children:W},W))]})]})]}),e.jsx(xLn,{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(vs,{value:n,onValueChange:r,children:[e.jsx(gs,{className:"w-[140px]",children:e.jsx(bs,{})}),e.jsxs(ys,{children:[e.jsx(Ye,{value:pae,children:"All Years"}),dvt.map(W=>e.jsx(Ye,{value:String(W),children:W},W))]})]}),e.jsx($,{variant:"outline",size:"icon",onClick:()=>h(!u),children:e.jsx(pc,{className:"h-4 w-4"})})]})]}),u&&e.jsxs(_e,{children:[e.jsx(Bt,{className:"pb-3",children:e.jsx(Ut,{className:"text-lg",children:"Settings"})}),e.jsx(Oe,{children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"space-y-0.5",children:[e.jsx(se,{children:"Show Commission"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Display commission fields and include in stats"})]}),e.jsx(Tn,{checked:(M==null?void 0:M.show_commission)??!0,onCheckedChange:W=>I.mutate({show_commission:W})})]})})]}),B&&!b?e.jsx(_e,{className:"py-12",children:e.jsxs(Oe,{className:"text-center space-y-4",children:[e.jsx("div",{className:"w-16 h-16 mx-auto rounded-full bg-primary/10 flex items-center justify-center",children:e.jsx(ml,{className:"h-8 w-8 text-primary"})}),e.jsxs("div",{children:[e.jsx("h3",{className:"text-lg font-semibold",children:"Start Tracking Your Success"}),e.jsx("p",{className:"text-muted-foreground max-w-md mx-auto mt-1",children:"Add your past transactions to see your performance metrics, track your goals, and celebrate your wins."})]}),e.jsxs("div",{className:"flex flex-wrap justify-center gap-2 pt-2",children:[e.jsxs($,{onClick:()=>i(!0),children:[e.jsx(sn,{className:"h-4 w-4 mr-2"}),"Add Your First Transaction"]}),e.jsxs($,{variant:"outline",onClick:()=>o(!0),children:[e.jsx(si,{className:"h-4 w-4 mr-2"}),"Import CSV"]})]}),e.jsxs("div",{className:"pt-4 border-t mt-4",children:[e.jsx("p",{className:"text-sm text-muted-foreground mb-2",children:"Need help formatting your data?"}),e.jsx($,{variant:"link",className:"h-auto p-0",asChild:!0,children:e.jsxs("a",{href:"/templates/transaction-import-template.csv",download:!0,children:[e.jsx(di,{className:"h-4 w-4 mr-2"}),"Download CSV Template"]})})]})]})}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs($,{onClick:()=>i(!0),children:[e.jsx(sn,{className:"h-4 w-4 mr-2"}),"Add Transaction"]}),e.jsxs($,{variant:"outline",onClick:()=>d(!0),children:[e.jsx(Mu,{className:"h-4 w-4 mr-2"}),"Set Goals"]}),e.jsxs($,{variant:"outline",onClick:()=>o(!0),children:[e.jsx(si,{className:"h-4 w-4 mr-2"}),"Import"]}),e.jsxs($,{variant:"outline",onClick:D,disabled:B,children:[e.jsx(di,{className:"h-4 w-4 mr-2"}),"Export"]}),e.jsx($,{variant:"ghost",size:"sm",asChild:!0,children:e.jsxs("a",{href:"/templates/transaction-import-template.csv",download:!0,children:[e.jsx(di,{className:"h-4 w-4 mr-2"}),"CSV Template"]})})]}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 lg:grid-cols-7 gap-4",children:[e.jsx(_e,{children:e.jsxs(Oe,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(sa,{className:"h-4 w-4"}),e.jsx("span",{className:"text-xs font-medium",children:"Transactions"})]}),e.jsx("p",{className:"text-2xl font-bold",children:v.totalTransactions}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[N.totalTransactions," lifetime"]})]})}),e.jsx(_e,{children:e.jsxs(Oe,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(qn,{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:[v.buyerCount,"/",v.sellerCount]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"B/S split"})]})}),e.jsx(_e,{children:e.jsxs(Oe,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(qd,{className:"h-4 w-4"}),e.jsx("span",{className:"text-xs font-medium",children:"Volume"})]}),e.jsx("p",{className:"text-2xl font-bold",children:Au(v.totalVolume,!0)}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[Au(N.totalVolume,!0)," lifetime"]})]})}),e.jsx(_e,{children:e.jsxs(Oe,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(Il,{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:Au(v.averagePrice,!0)})]})}),e.jsx(_e,{children:e.jsxs(Oe,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(pu,{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:((q=v.topLeadSource)==null?void 0:q.name)||"-"}),v.topLeadSource&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:[v.topLeadSource.count," deals"]})]})}),A&&e.jsx(_e,{children:e.jsxs(Oe,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(qd,{className:"h-4 w-4"}),e.jsx("span",{className:"text-xs font-medium",children:"GCI"})]}),e.jsx("p",{className:"text-2xl font-bold",children:Au(v.totalCommission,!0)}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[Au(N.totalCommission,!0)," lifetime"]})]})}),A&&v.totalNetToAgent>0&&v.totalNetToAgent!==v.totalCommission&&e.jsx(_e,{children:e.jsxs(Oe,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-teal-600 dark:text-teal-400 mb-1",children:[e.jsx(qd,{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:Au(v.totalNetToAgent,!0)}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[Au(N.totalNetToAgent,!0)," lifetime"]})]})})]}),s!==null&&T&&e.jsx(Iqt,{goals:T,stats:v,year:s,showCommission:A}),e.jsxs(ua,{defaultValue:"transactions",className:"space-y-4",children:[e.jsxs(ha,{children:[e.jsx(Qt,{value:"transactions",children:"Transactions"}),e.jsx(Qt,{value:"charts",children:"Charts"}),e.jsxs(Qt,{value:"map",children:[e.jsx(ai,{className:"h-4 w-4 mr-1"}),"Map"]})]}),e.jsx(Jt,{value:"transactions",children:e.jsx(rXe,{transactions:y||[],showCommission:A,isLoading:b})}),e.jsx(Jt,{value:"charts",children:e.jsx(aXe,{stats:v,year:s??void 0})}),e.jsx(Jt,{value:"map",children:e.jsx(iXe,{transactions:y||[],isLoading:b})})]})]})]})]}),e.jsx(Pqt,{open:a,onOpenChange:i}),e.jsx(dLn,{open:l,onOpenChange:o}),e.jsx(hLn,{open:c,onOpenChange:d,year:s??TNe,existingGoals:T})]})}function Bqt({open:s,onOpenChange:t,listingId:n,listingSlug:r,listingTitle:a}){const{user:i}=_s(),[l,o]=j.useState(null),[c,d]=j.useState(!1),[u,h]=j.useState(!1);j.useEffect(()=>{(async()=>{if(!(!s||!i)){d(!0);try{const{data:y,error:b}=await U.from("listing_shares").select("id, share_token, click_count, lead_count").eq("listing_id",n).eq("sharing_agent_id",i.id).order("created_at",{ascending:!1}).limit(1).maybeSingle();if(b)throw b;if(y&&y.share_token)o(y);else if(y&&!y.share_token){const{data:v,error:N}=await U.from("listing_shares").update({share_type:"referral_link"}).eq("id",y.id).select("id, share_token, click_count, lead_count").single();if(N)throw N;o(v)}else{const{data:v,error:N}=await U.from("listing_shares").insert({listing_id:n,sharing_agent_id:i.id,share_type:"referral_link"}).select("id, share_token, click_count, lead_count").single();if(N)throw N;o(v)}}catch(y){console.error("Error creating share link:",y),ae.error("Failed to generate share link")}finally{d(!1)}}})()},[s,i,n]);const m=l!=null&&l.share_token?`https://listings.relevelup.com/${r||n}?ref=${l.share_token}`:"",p=async()=>{try{await navigator.clipboard.writeText(m),h(!0),ae.success("Link copied to clipboard!"),setTimeout(()=>h(!1),2e3)}catch{ae.error("Failed to copy link")}},x=g=>{const y=encodeURIComponent(m),b=encodeURIComponent(`Check out this listing: ${a}`);switch(g){case"email":window.open(`mailto:?subject=${b}&body=${y}`);break;case"text":window.open(`sms:?body=${b}%20${y}`);break;case"facebook":window.open(`https://www.facebook.com/sharer/sharer.php?u=${y}`,"_blank");break}};return e.jsx(Os,{open:s,onOpenChange:t,children:e.jsxs(Rs,{className:"sm:max-w-md",children:[e.jsxs(Us,{children:[e.jsxs(zs,{className:"flex items-center gap-2",children:[e.jsx(dn,{className:"h-5 w-5 text-amber-500"}),"Share & Earn Leads"]}),e.jsx(Sr,{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(se,{children:"Your Referral Link"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(be,{value:c?"Generating...":m,readOnly:!0,className:"font-mono text-sm"}),e.jsx($,{onClick:p,disabled:c||!m,variant:u?"default":"outline",children:u?e.jsx(oa,{className:"h-4 w-4"}):e.jsx(Ca,{className:"h-4 w-4"})})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Share via"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs($,{variant:"outline",className:"flex-1",onClick:()=>x("email"),disabled:c,children:[e.jsx(nn,{className:"h-4 w-4 mr-2"}),"Email"]}),e.jsxs($,{variant:"outline",className:"flex-1",onClick:()=>x("text"),disabled:c,children:[e.jsx(Ji,{className:"h-4 w-4 mr-2"}),"Text"]}),e.jsxs($,{variant:"outline",className:"flex-1",onClick:()=>x("facebook"),disabled:c,children:[e.jsx(jf,{className:"h-4 w-4 mr-2"}),"Facebook"]})]})]}),l&&(l.click_count>0||l.lead_count>0)&&e.jsxs("div",{className:"pt-4 border-t",children:[e.jsx(se,{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(ga,{className:"h-4 w-4"}),e.jsx("span",{className:"text-xs",children:"Clicks"})]}),e.jsx("p",{className:"text-2xl font-bold",children:l.click_count})]}),e.jsxs("div",{className:"bg-primary/10 rounded-lg p-3 text-center",children:[e.jsxs("div",{className:"flex items-center justify-center gap-1 text-primary mb-1",children:[e.jsx(qn,{className:"h-4 w-4"}),e.jsx("span",{className:"text-xs",children:"Leads"})]}),e.jsx("p",{className:"text-2xl font-bold text-primary",children:l.lead_count})]})]})]})]})]})})}const yLn={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"},vLn={active:"Active",coming_soon:"Coming Soon",office_exclusive:"Office Exclusive",pre_market:"Pre-Market",price_improvement:"Price Improvement",under_contract:"Under Contract",sold:"Sold"},bLn={single_family:"Single Family",condo:"Condo",townhouse:"Townhouse",land:"Land",multi_family:"Multi-Family",luxury:"Luxury",commercial:"Commercial",other:"Other"};function _Ln({listing:s,onClick:t,onEdit:n,onDelete:r,onCreateMusicVideo:a,showActions:i}){var y,b;const{user:l}=_s(),{data:o}=j6t(s.id),c=w6t(),[d,u]=j.useState(!1),h=v=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(v),m=((y=s.photos)==null?void 0:y.find(v=>v.is_primary))||((b=s.photos)==null?void 0:b[0]),p=(l==null?void 0:l.id)===s.agent_id,x=async v=>{v.stopPropagation();try{const N=await c.mutateAsync(s.id);ae.success(N.saved?"Listing saved!":"Listing removed from saved")}catch{ae.error("Failed to save listing")}},g=v=>{if(v.stopPropagation(),l)u(!0);else{const N=`https://listings.relevelup.com/${s.slug||s.id}`;navigator.clipboard.writeText(N),ae.success("Link copied to clipboard!")}};return e.jsxs(_e,{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(Lb,{className:"h-12 w-12"})}),e.jsx($e,{className:`absolute top-2 left-2 ${yLn[s.status]} text-white border-0`,children:vLn[s.status]}),s.is_featured&&e.jsx("div",{className:"absolute top-2 right-2 p-1.5 bg-amber-500 rounded-full",children:e.jsx(Qa,{className:"h-4 w-4 text-white fill-white"})}),e.jsxs("div",{className:"absolute bottom-2 right-2 flex gap-1 opacity-0 group-hover:opacity-100 transition-opacity",children:[e.jsx($,{size:"icon",variant:"secondary",className:"h-8 w-8",onClick:x,children:e.jsx(fo,{className:`h-4 w-4 ${o?"fill-pink-500 text-pink-500":""}`})}),e.jsx($,{size:"icon",variant:"secondary",className:"h-8 w-8",onClick:g,title:p?"Copy link":"Share & earn leads",children:p?e.jsx(vd,{className:"h-4 w-4"}):e.jsx(dn,{className:"h-4 w-4 text-amber-500"})})]})]}),e.jsx(Bqt,{open:d,onOpenChange:u,listingId:s.id,listingSlug:s.slug||null,listingTitle:s.property_address||`${s.city}, ${s.state}`}),e.jsxs(Oe,{className:"p-4 space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("p",{className:"text-xl font-bold text-primary",children:h(s.price)}),s.open_to_referrals&&e.jsxs($e,{variant:"outline",className:"text-xs",children:[e.jsx(qn,{className:"h-3 w-3 mr-1"}),"Referrals"]})]}),e.jsxs("div",{children:[s.property_address&&e.jsx("p",{className:"font-medium truncate",children:s.property_address}),e.jsxs("p",{className:"text-sm text-muted-foreground flex items-center gap-1",children:[e.jsx(ai,{className:"h-3 w-3"}),s.city,", ",s.state,s.neighborhood&&` • ${s.neighborhood}`]})]}),e.jsxs("div",{className:"flex items-center gap-4 text-sm text-muted-foreground",children:[s.bedrooms&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(tw,{className:"h-4 w-4"}),s.bedrooms," bd"]}),s.bathrooms&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(_g,{className:"h-4 w-4"}),s.bathrooms," ba"]}),s.square_footage&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Lb,{className:"h-4 w-4"}),s.square_footage.toLocaleString()," sqft"]})]}),e.jsxs("div",{className:"flex items-center justify-between pt-2 border-t",children:[e.jsx($e,{variant:"secondary",className:"text-xs",children:bLn[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(ga,{className:"h-3 w-3"}),s.view_count]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(vd,{className:"h-3 w-3"}),s.share_count]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(fo,{className:"h-3 w-3"}),s.save_count]})]}),i&&(n||r||a)&&e.jsxs("div",{className:"flex flex-wrap gap-2",children:[a&&e.jsxs($,{variant:"outline",size:"sm",className:"flex-1 min-w-[140px] gap-1.5 border-violet-500/60 text-violet-600 hover:bg-violet-50",onClick:v=>{v.stopPropagation(),a()},children:[e.jsx(Pz,{className:"h-4 w-4"}),"Music Video"]}),n&&e.jsxs($,{variant:"outline",size:"sm",className:"flex-1",onClick:v=>{v.stopPropagation(),n()},children:[e.jsx(bm,{className:"h-4 w-4 mr-2"}),"Edit"]}),r&&e.jsx($,{variant:"destructive",size:"sm",onClick:v=>{v.stopPropagation(),r()},children:e.jsx(Pn,{className:"h-4 w-4"})})]})]})]})}const oXe="lu_listing_selection_v1",D4e=24,R4e=new Set;function $qt(){try{return JSON.parse(sessionStorage.getItem(oXe)||"{}")}catch{return{}}}function fDe(s){try{sessionStorage.setItem(oXe,JSON.stringify(s))}catch{}R4e.forEach(t=>t())}let z4=$qt();function wLn(){z4=$qt(),R4e.forEach(s=>s())}typeof window<"u"&&window.addEventListener("storage",s=>{s.key===oXe&&wLn()});const GA={getSnapshot:()=>z4,subscribe(s){return R4e.add(s),()=>R4e.delete(s)},toggle(s){const t={...z4};if(t[s.mlsNumber])delete t[s.mlsNumber];else{if(Object.keys(t).length>=D4e)return!1;t[s.mlsNumber]=s}return z4=t,fDe(t),!0},remove(s){const t={...z4};delete t[s],z4=t,fDe(t)},clear(){z4={},fDe({})},has(s){return!!z4[s]},all(){return Object.values(z4)}};function Uqt(){const s=j.useSyncExternalStore(GA.subscribe,GA.getSnapshot,GA.getSnapshot);return{selected:Object.values(s),selectedIds:new Set(Object.keys(s)),count:Object.keys(s).length,has:t=>!!s[t],toggle:GA.toggle,remove:GA.remove,clear:GA.clear}}const jLn=new Set(["office_exclusive","coming_soon","pre_market"]);function NLn(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=jLn.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 fae(s){const{has:t}=Uqt(),n=`lx-${s.listing.id}`,r=t(n);return e.jsxs("div",{className:"relative",children:[e.jsx(_Ln,{...s}),e.jsx("button",{type:"button",onClick:a=>{a.stopPropagation(),GA.toggle(NLn(s.listing))||ae.error(`You can select up to ${D4e} 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(oa,{className:"h-4 w-4"}):e.jsx(nn,{className:"h-4 w-4"})})]})}function kLn({open:s,onOpenChange:t,listings:n}){const{user:r}=_s(),{leadSite:a}=Mf(),[i,l]=j.useState("grid"),[o,c]=j.useState(""),[d,u]=j.useState(""),[h,m]=j.useState(""),[p,x]=j.useState(new Set),[g,y]=j.useState(!1),[b,v]=j.useState(!1),{data:N}=Kee(),[C,A]=j.useState(!1);j.useEffect(()=>{!s||!(r!=null&&r.id)||U.from("gmail_integrations").select("gmail_email").eq("user_id",r.id).maybeSingle().then(({data:K})=>v(!!(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(J=>J.city).filter(Boolean))),Q=K.length===1?` in ${K[0]}`:"";c(n.length===1?`New listing for you${Q}`:`${n.length} hand-picked listings${Q}`)}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:P}=ht({queryKey:["send-listings-contacts",r==null?void 0:r.id],queryFn:async()=>{const{data:K}=await U.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}=ht({queryKey:["send-listings-suggestions",n.map(K=>K.mlsNumber).join(",")],queryFn:async()=>{const{data:K,error:Q}=await U.functions.invoke("listing-email-suggestions",{body:{listings:n.map(J=>({mlsNumber:J.mlsNumber,city:J.city,state:J.state,price:J.price,bedrooms:J.bedrooms,bathrooms:J.bathrooms}))}});if(Q)throw Q;return K},enabled:s&&n.length>0}),I=(M==null?void 0:M.suggestions)||[],D=j.useMemo(()=>{const K=h.trim().toLowerCase();return K?T.filter(Q=>`${Q.first_name??""} ${Q.last_name??""} ${Q.email} ${Q.city??""}`.toLowerCase().includes(K)):T},[T,h]),B=K=>{x(Q=>{const J=new Set(Q);return J.has(K)?J.delete(K):J.add(K),J})},q=()=>{x(K=>{const Q=new Set(K);return I.forEach(J=>Q.add(J.contact_id)),Q})},W=n.length>0&&n.every(K=>K.mlsNumber.startsWith("lx-")),V=async()=>{if(!W&&!(a!=null&&a.id)){ae.error("You need an active lead site to send listings.");return}if(!o.trim())return ae.error("Subject is required");if(p.size===0)return ae.error("Pick at least one recipient");if(!b&&N&&!N.hasVerifiedSes){A(!0);return}const K=T.filter(Q=>p.has(Q.id)).map(Q=>({contact_id:Q.id,email:Q.email,first_name:Q.first_name,last_name:Q.last_name}));y(!0);try{const{data:Q,error:J}=await U.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(ce=>({mlsNumber:ce.mlsNumber,address:ce.address,city:ce.city,state:ce.state,zip:ce.zip,price:ce.price,bedrooms:ce.bedrooms,bathrooms:ce.bathrooms,sqft:ce.sqft,status:ce.status,photos:(ce.photos||[]).slice(0,1),description:ce.description||"",external_url:ce.externalUrl||null,is_private:ce.is_private===!0})),recipients:K}});if(J)throw J;if(!(Q!=null&&Q.success))throw new Error((Q==null?void 0:Q.error)||"Send failed");ae.success(`Sent ${Q.sent}/${K.length} via ${b?"Gmail":"Amazon SES"}${Q.failed?` · ${Q.failed} failed`:""}`),GA.clear(),x(new Set),t(!1)}catch(Q){ae.error((Q==null?void 0:Q.message)||"Failed to send")}finally{y(!1)}};return e.jsxs(Os,{open:s,onOpenChange:t,children:[e.jsxs(Rs,{className:"max-w-5xl max-h-[92vh] overflow-hidden p-0 flex flex-col",children:[e.jsxs(Us,{className:"px-6 pt-6 pb-2",children:[e.jsxs(zs,{className:"flex items-center gap-2",children:[e.jsx(nn,{className:"h-5 w-5 text-primary"}),"Email ",n.length," ",n.length===1?"Listing":"Listings"]}),e.jsx(Sr,{children:W?"Send your Listing Exchange properties. Recipients land on listings.relevelup.com and clicks track back to the contact.":"Drive traffic to your site. Recipients land on your lead site and clicks show up on Mission Control."})]}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-0 flex-1 overflow-hidden",children:[e.jsxs("div",{className:"overflow-y-auto px-6 pb-4 space-y-4 border-r",children:[e.jsxs("div",{children:[e.jsx(se,{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 Q;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:((Q=K.photos)==null?void 0:Q[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(se,{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(_0,{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(Jl,{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(se,{htmlFor:"subject",children:"Subject"}),e.jsx(be,{id:"subject",value:o,onChange:K=>c(K.target.value),placeholder:"Subject line",className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx(se,{htmlFor:"intro",children:"Personal message"}),e.jsx(Is,{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:b?"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(_e,{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(dn,{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($,{size:"sm",variant:"outline",onClick:q,children:"Add all"})]}),e.jsx(Oi,{className:"max-h-32 mt-2",children:e.jsx("div",{className:"space-y-1",children:I.slice(0,12).map(K=>{const Q=p.has(K.contact_id);return e.jsxs("label",{className:"flex items-start gap-2 text-xs py-1 cursor-pointer",children:[e.jsx(ui,{checked:Q,onCheckedChange:()=>B(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(se,{className:"text-xs uppercase tracking-wide text-muted-foreground",children:["All contacts (",D.length,")"]}),p.size>0&&e.jsxs($e,{variant:"secondary",children:[p.size," selected"]})]}),e.jsx(be,{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(Oi,{className:"h-full",children:P?e.jsx("div",{className:"p-4 text-sm text-muted-foreground",children:"Loading…"}):D.length===0?e.jsx("div",{className:"p-4 text-sm text-muted-foreground text-center",children:"No contacts found"}):e.jsx("div",{className:"divide-y",children:D.map(K=>{const Q=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(ui,{checked:Q,onCheckedChange:()=>B(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($,{variant:"ghost",size:"sm",className:"h-7 text-xs",onClick:()=>x(new Set),children:[e.jsx(pr,{className:"h-3 w-3 mr-1"}),"Clear"]})]})]})]}),e.jsxs(kr,{className:"px-6 py-4 border-t bg-muted/30",children:[e.jsx($,{variant:"outline",onClick:()=>t(!1),disabled:g,children:"Cancel"}),e.jsx($,{onClick:V,disabled:g||p.size===0,children:g?e.jsxs(e.Fragment,{children:[e.jsx(Ht,{className:"h-4 w-4 mr-2 animate-spin"}),"Sending…"]}):e.jsxs(e.Fragment,{children:[e.jsx(Br,{className:"h-4 w-4 mr-2"}),"Send to ",p.size," ",p.size===1?"contact":"contacts"]})})]})]}),e.jsx(OEe,{open:C,onOpenChange:A,hasPending:!!(N!=null&&N.hasPendingSes),pendingEmails:N==null?void 0:N.pendingEmails})]})}function SLn(){const{selected:s,count:t,remove:n,clear:r}=Uqt(),[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>=D4e?"Max reached":`Pick up to ${D4e}`})]})]}),e.jsx("div",{className:"flex-1 overflow-x-auto hidden sm:block",children:e.jsxs("div",{className:"flex items-center gap-2",children:[s.slice(0,6).map(l=>{var o;return e.jsxs("div",{className:"group relative shrink-0 h-12 w-16 rounded-md overflow-hidden border bg-muted",title:l.address,children:[(o=l.photos)!=null&&o[0]?e.jsx("img",{src:l.photos[0],alt:"",className:"h-full w-full object-cover"}):e.jsx("div",{className:"h-full w-full"}),e.jsx("button",{"aria-label":"Remove",onClick:()=>n(l.mlsNumber),className:"absolute inset-0 bg-black/50 opacity-0 group-hover:opacity-100 flex items-center justify-center transition",children:e.jsx(pr,{className:"h-4 w-4 text-white"})})]},l.mlsNumber)}),t>6&&e.jsxs("div",{className:"shrink-0 h-12 w-12 rounded-md border bg-muted flex items-center justify-center text-xs font-medium text-muted-foreground",children:["+",t-6]})]})}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs($,{variant:"ghost",size:"sm",onClick:r,className:"gap-1.5",children:[e.jsx(Pn,{className:"h-4 w-4"})," Clear"]}),e.jsxs($,{size:"sm",className:"gap-1.5",onClick:()=>i(!0),children:[e.jsx(Br,{className:"h-4 w-4"}),"Email these ",t===1?"listing":"listings"]})]})]})}),e.jsx(kLn,{open:a,onOpenChange:i,listings:s})]})}const CLn=[{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"}],ALn=[{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 ELn({filters:s,onFiltersChange:t,onClose:n}){const r=()=>{t({sortBy:"newest"})};return e.jsxs(_e,{children:[e.jsxs(Bt,{className:"flex flex-row items-center justify-between pb-3",children:[e.jsx(Ut,{className:"text-lg",children:"Filters"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx($,{variant:"ghost",size:"sm",onClick:r,children:"Clear All"}),e.jsx($,{variant:"ghost",size:"icon",onClick:n,children:e.jsx(pr,{className:"h-4 w-4"})})]})]}),e.jsxs(Oe,{children:[e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Status"}),e.jsxs(vs,{value:s.status||"all",onValueChange:a=>t({...s,status:a==="all"?void 0:a}),children:[e.jsx(gs,{children:e.jsx(bs,{placeholder:"All statuses"})}),e.jsxs(ys,{children:[e.jsx(Ye,{value:"all",children:"All Statuses"}),CLn.map(a=>e.jsx(Ye,{value:a.value,children:a.label},a.value))]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Property Type"}),e.jsxs(vs,{value:s.propertyType||"all",onValueChange:a=>t({...s,propertyType:a==="all"?void 0:a}),children:[e.jsx(gs,{children:e.jsx(bs,{placeholder:"All types"})}),e.jsxs(ys,{children:[e.jsx(Ye,{value:"all",children:"All Types"}),ALn.map(a=>e.jsx(Ye,{value:a.value,children:a.label},a.value))]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Min Price"}),e.jsx(be,{type:"number",placeholder:"No minimum",value:s.minPrice||"",onChange:a=>t({...s,minPrice:a.target.value?Number(a.target.value):void 0})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Max Price"}),e.jsx(be,{type:"number",placeholder:"No maximum",value:s.maxPrice||"",onChange:a=>t({...s,maxPrice:a.target.value?Number(a.target.value):void 0})})]})]}),e.jsxs("div",{className:"flex items-center justify-between mt-4 pt-4 border-t",children:[e.jsxs("div",{children:[e.jsx(se,{children:"Open to Referrals Only"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Show only listings accepting buyer referrals"})]}),e.jsx(Tn,{checked:s.openToReferrals||!1,onCheckedChange:a=>t({...s,openToReferrals:a||void 0})})]})]})]})}function TLn({leaderboard:s}){const t=r=>{switch(r){case 0:return e.jsx(pl,{className:"h-5 w-5 text-amber-500"});case 1:return e.jsx(V3,{className:"h-5 w-5 text-gray-400"});case 2:return e.jsx(pu,{className:"h-5 w-5 text-amber-700"});default:return e.jsx("span",{className:"text-sm font-medium text-muted-foreground w-5 text-center",children:r+1})}},n=(r,a)=>!r||r.length===0?e.jsx("div",{className:"py-8 text-center text-muted-foreground",children:"No data yet. Start sharing to climb the leaderboard!"}):e.jsx("div",{className:"space-y-2",children:r.map((i,l)=>e.jsxs("div",{className:`flex items-center gap-4 p-3 rounded-lg ${l===0?"bg-gradient-to-r from-amber-500/10 to-amber-500/5 border border-amber-500/20":"bg-muted/50"}`,children:[e.jsx("div",{className:"flex items-center justify-center w-8",children:t(l)}),e.jsx("div",{className:"flex-1 min-w-0",children:e.jsx("p",{className:"font-medium truncate",children:i.name})}),e.jsxs($e,{variant:l===0?"default":"secondary",children:[i.count," ",a]})]},i.agentId))});return e.jsxs("div",{className:"space-y-6",children:[e.jsxs(_e,{children:[e.jsx(Bt,{children:e.jsxs(Ut,{className:"flex items-center gap-2",children:[e.jsx(pl,{className:"h-5 w-5 text-amber-500"}),"Community Badges"]})}),e.jsx(Oe,{children:e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[e.jsxs("div",{className:"text-center p-4 rounded-lg bg-gradient-to-br from-emerald-500/10 to-emerald-500/5 border border-emerald-500/20",children:[e.jsx("div",{className:"w-12 h-12 mx-auto mb-2 rounded-full bg-emerald-500/20 flex items-center justify-center",children:e.jsx(vd,{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(sa,{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(V3,{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(pl,{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(_e,{children:[e.jsx(Bt,{children:e.jsx(Ut,{children:"Community Leaderboard"})}),e.jsx(Oe,{children:e.jsxs(ua,{defaultValue:"sharers",children:[e.jsxs(ha,{className:"w-full",children:[e.jsxs(Qt,{value:"sharers",className:"flex-1",children:[e.jsx(vd,{className:"h-4 w-4 mr-2"}),"Top Sharers"]}),e.jsxs(Qt,{value:"listers",className:"flex-1",children:[e.jsx(sa,{className:"h-4 w-4 mr-2"}),"Top Contributors"]})]}),e.jsx(Jt,{value:"sharers",className:"mt-4",children:n(s==null?void 0:s.topSharers,"shares")}),e.jsx(Jt,{value:"listers",className:"mt-4",children:n(s==null?void 0:s.topListers,"listings")})]})})]})]})}const uvt={coming_soon:"#F59E0B",office_exclusive:"#6366F1",pre_market:"#06B6D4",active:"#10B981",price_improvement:"#8B5CF6",under_contract:"#3B82F6",sold:"#A855F7"},hvt={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 MLn(s){return s>=1e6?`$${(s/1e6).toFixed(1)}M`:`$${(s/1e3).toFixed(0)}K`}function LLn({listings:s,isLoading:t}){const n=Vn(),r=j.useRef(null),a=j.useRef(null),i=j.useRef([]),{isAdmin:l}=_s(),[o,c]=j.useState(""),[d,u]=j.useState(!0),[h,m]=j.useState(!1),p=s.filter(g=>g.latitude!=null&&g.longitude!=null),x=s.filter(g=>(g.latitude==null||g.longitude==null)&&(g.property_address||g.city));return j.useEffect(()=>{(async()=>{u(!0);try{const{data:y}=await U.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||x.length===0||h)return;(async()=>{var y;m(!0);for(const b of x){const v=[b.property_address,b.city,b.state].filter(Boolean).join(", ");if(v)try{const C=await(await fetch(`https://api.mapbox.com/geocoding/v5/mapbox.places/${encodeURIComponent(v)}.json?access_token=${o}&limit=1`)).json();if((y=C.features)!=null&&y[0]){const[A,T]=C.features[0].center;await U.from("listings").update({latitude:T,longitude:A}).eq("id",b.id),b.latitude=T,b.longitude=A}}catch(N){console.error("Geocode error:",N)}}m(!1)})()},[o,s]),j.useEffect(()=>{if(!r.current||!o||a.current)return;Wc.accessToken=o;const g=s.filter(v=>v.latitude!=null&&v.longitude!=null);let y=[-98.5795,39.8283],b=4;if(g.length>0){const v=g.reduce((C,A)=>C+A.longitude,0)/g.length,N=g.reduce((C,A)=>C+A.latitude,0)/g.length;y=[v,N],b=g.length===1?12:10}return a.current=new Wc.Map({container:r.current,style:"mapbox://styles/mapbox/light-v11",zoom:b,center:y}),a.current.addControl(new Wc.NavigationControl,"top-right"),()=>{var v;(v=a.current)==null||v.remove(),a.current=null}},[o]),j.useEffect(()=>{if(!a.current||!o)return;i.current.forEach(y=>y.remove()),i.current=[];const g=s.filter(y=>y.latitude!=null&&y.longitude!=null);if(g.forEach(y=>{var T,P,M;const b=uvt[y.status]||"#10B981",v=((T=y.photos)==null?void 0:T.find(I=>I.is_primary))||((P=y.photos)==null?void 0:P[0]),N=document.createElement("div");N.className="cursor-pointer",N.innerHTML=`
`;const C=new Wc.Popup({offset:25,closeButton:!0,maxWidth:"280px"}).setHTML(`
${v!=null&&v.photo_url?``:""}
${MLn(y.price)}
${y.property_address||""}
${y.city}, ${y.state}
${hvt[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 Wc.Marker(N).setLngLat([y.longitude,y.latitude]).setPopup(C).addTo(a.current);i.current.push(A)}),g.length>1){const y=new Wc.LngLatBounds;g.forEach(b=>y.extend([b.longitude,b.latitude])),a.current.fitBounds(y,{padding:60,maxZoom:13})}else g.length===1&&a.current.flyTo({center:[g[0].longitude,g[0].latitude],zoom:12})},[s,o,h]),j.useEffect(()=>(window.__navigateToListing__=g=>{n(`/mission-control/listings/${g}`)},()=>{delete window.__navigateToListing__}),[n]),d||t?e.jsx(_e,{children:e.jsx(Oe,{className:"flex items-center justify-center h-[60vh]",children:e.jsx("div",{className:"animate-spin rounded-full h-8 w-8 border-b-2 border-primary"})})}):o?s.length===0?e.jsx(_e,{children:e.jsxs(Oe,{className:"flex flex-col items-center justify-center h-[60vh] text-center gap-3",children:[e.jsx(ai,{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(uvt).map(([g,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:hvt[g]})]},g)),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(_e,{children:e.jsxs(Oe,{className:"flex flex-col items-center justify-center h-[60vh] text-center gap-3",children:[e.jsx(xo,{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 dUe="homereel_mv_prefill",uUe="homereel_mv_badge_default";function qqt(s){try{sessionStorage.setItem(dUe,JSON.stringify(s)),s.badge&&s.badge.type!=="none"&&sessionStorage.setItem(uUe,JSON.stringify(s.badge))}catch{}}function AQn(){try{const s=sessionStorage.getItem(dUe);return s?(sessionStorage.removeItem(dUe),JSON.parse(s)):null}catch{return null}}function EQn(){try{const s=sessionStorage.getItem(uUe);return s?(sessionStorage.removeItem(uUe),JSON.parse(s)):null}catch{return null}}function Vqt(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 PLn(){var I,D,B,q,W,V,K,Q;const s=Vn(),{brokerageId:t}=_s(),{data:n,isLoading:r}=y6t(),[a,i]=j.useState("feed"),[l,o]=j.useState(!1),[c,d]=j.useState(""),[u,h]=j.useState({sortBy:"newest"}),{data:m,isLoading:p}=v6t({...u,city:c||u.city}),{data:x,isLoading:g}=qCs(),{data:y,isLoading:b}=b6t(),{data:v,isLoading:N}=WCs(),{data:C,isLoading:A}=ZCs(),{data:T}=YCs(),P=_6t(),M=async J=>{if(await Yi("Are you sure you want to delete this listing? This action cannot be undone."))try{await P.mutateAsync(J),ae.success("Listing deleted successfully")}catch{ae.error("Failed to delete listing")}};return r?e.jsx(Ks,{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(Ks,{title:"Listing Exchange",description:"Community-powered listing collaboration",children:[e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center justify-between gap-4",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("h1",{className:"text-2xl font-bold",children:"Listing Exchange"}),e.jsx("span",{className:"text-[10px] font-semibold uppercase tracking-wide px-1.5 py-0.5 rounded border border-amber-500 text-amber-600 dark:text-amber-400 bg-amber-500/10",children:"Beta"})]}),e.jsxs($,{onClick:()=>s("/mission-control/listings/new"),children:[e.jsx(sn,{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(_e,{children:e.jsxs(Oe,{className:"p-4 flex items-center gap-3",children:[e.jsx("div",{className:"p-2 bg-primary/10 rounded-lg",children:e.jsx(sa,{className:"h-5 w-5 text-primary"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-bold",children:(m==null?void 0:m.length)||0}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Active Listings"})]})]})}),e.jsx(_e,{children:e.jsxs(Oe,{className:"p-4 flex items-center gap-3",children:[e.jsx("div",{className:"p-2 bg-pink-500/10 rounded-lg",children:e.jsx(fo,{className:"h-5 w-5 text-pink-500"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-bold",children:(x==null?void 0:x.length)||0}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Saved"})]})]})}),e.jsx(_e,{children:e.jsxs(Oe,{className:"p-4 flex items-center gap-3",children:[e.jsx("div",{className:"p-2 bg-emerald-500/10 rounded-lg",children:e.jsx(lR,{className:"h-5 w-5 text-emerald-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:"My Listings"})]})]})}),e.jsx(_e,{children:e.jsxs(Oe,{className:"p-4 flex items-center gap-3",children:[e.jsx("div",{className:"p-2 bg-sky-500/10 rounded-lg",children:e.jsx(qn,{className:"h-5 w-5 text-sky-500"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-bold",children:(((I=v==null?void 0:v.sent)==null?void 0:I.length)||0)+(((D=v==null?void 0:v.received)==null?void 0:D.length)||0)}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Referrals"})]})]})})]}),e.jsxs(ua,{value:a,onValueChange:i,children:[e.jsxs(ha,{className:"w-full justify-start overflow-x-auto",children:[e.jsx(Qt,{value:"feed",children:"Community Feed"}),t&&e.jsx(Qt,{value:"brokerage",children:"Brokerage"}),e.jsx(Qt,{value:"my-listings",children:"My Listings"}),e.jsx(Qt,{value:"saved",children:"Saved"}),e.jsx(Qt,{value:"referrals",children:"Referrals"}),e.jsx(Qt,{value:"map",children:"Map"}),e.jsx(Qt,{value:"leaderboard",children:"Leaderboard"})]}),e.jsxs(Jt,{value:"feed",className:"space-y-4",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row gap-3",children:[e.jsxs("div",{className:"relative flex-1",children:[e.jsx(Vr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(be,{placeholder:"Search by city or neighborhood...",value:c,onChange:J=>d(J.target.value),className:"pl-9"})]}),e.jsxs(vs,{value:u.sortBy,onValueChange:J=>h({...u,sortBy:J}),children:[e.jsx(gs,{className:"w-[180px]",children:e.jsx(bs,{placeholder:"Sort by"})}),e.jsxs(ys,{children:[e.jsx(Ye,{value:"newest",children:"Newest First"}),e.jsx(Ye,{value:"updated",children:"Recently Updated"}),e.jsx(Ye,{value:"price_asc",children:"Price: Low to High"}),e.jsx(Ye,{value:"price_desc",children:"Price: High to Low"})]})]}),e.jsxs($,{variant:"outline",onClick:()=>o(!l),children:[e.jsx($j,{className:"h-4 w-4 mr-2"}),"Filters"]})]}),l&&e.jsx(ELn,{filters:u,onFiltersChange:h,onClose:()=>o(!1)}),p?e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:[...Array(6)].map((J,ce)=>e.jsxs(_e,{children:[e.jsx(on,{className:"h-48 w-full"}),e.jsxs(Oe,{className:"p-4 space-y-2",children:[e.jsx(on,{className:"h-5 w-3/4"}),e.jsx(on,{className:"h-4 w-1/2"}),e.jsx(on,{className:"h-4 w-1/4"})]})]},ce))}):(m==null?void 0:m.length)===0?e.jsx(_e,{children:e.jsxs(Oe,{className:"py-12 text-center",children:[e.jsx(sa,{className:"h-12 w-12 mx-auto text-muted-foreground mb-4"}),e.jsx("h3",{className:"text-lg font-medium mb-2",children:"No listings found"}),e.jsx("p",{className:"text-muted-foreground mb-4",children:"Be the first to share a listing with the community!"}),e.jsxs($,{onClick:()=>s("/mission-control/listings/new"),children:[e.jsx(sn,{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:m==null?void 0:m.map(J=>e.jsx(fae,{listing:J,onClick:()=>s(`/mission-control/listings/${J.id}`)},J.id))})]}),e.jsx(Jt,{value:"my-listings",className:"space-y-4",children:b?e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:[...Array(3)].map((J,ce)=>e.jsxs(_e,{children:[e.jsx(on,{className:"h-48 w-full"}),e.jsxs(Oe,{className:"p-4 space-y-2",children:[e.jsx(on,{className:"h-5 w-3/4"}),e.jsx(on,{className:"h-4 w-1/2"})]})]},ce))}):(y==null?void 0:y.length)===0?e.jsx(_e,{children:e.jsxs(Oe,{className:"py-12 text-center",children:[e.jsx(lR,{className:"h-12 w-12 mx-auto text-muted-foreground mb-4"}),e.jsx("h3",{className:"text-lg font-medium mb-2",children:"No listings yet"}),e.jsx("p",{className:"text-muted-foreground mb-4",children:"Share your listings with the LevelUp community!"}),e.jsxs($,{onClick:()=>s("/mission-control/listings/new"),children:[e.jsx(sn,{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:y==null?void 0:y.map(J=>e.jsx(fae,{listing:J,showActions:!0,onClick:()=>s(`/mission-control/listings/${J.id}`),onEdit:()=>s(`/mission-control/listings/${J.id}/edit`),onDelete:()=>M(J.id),onCreateMusicVideo:()=>{const ce=(J.photos??[]).slice().sort((ue,ne)=>(ne.is_primary?1:0)-(ue.is_primary?1:0)||(ue.sort_order??0)-(ne.sort_order??0)).map(ue=>ue.photo_url).filter(Boolean);if(ce.length===0){ae.error("Add photos to this listing first.");return}qqt({photos:ce,details:{address:J.property_address||`${J.city??""} ${J.state??""}`.trim(),beds:J.bedrooms?String(J.bedrooms):"",baths:J.bathrooms?String(J.bathrooms):"",sqft:J.square_footage?String(J.square_footage):"",price:J.price?String(J.price):"",highlights:J.description||""},sourceLabel:"My Listings",badge:Vqt(J.status,J.price)}),s("/admin/beta/homereel?tab=music-video")}},J.id))})}),e.jsx(Jt,{value:"saved",className:"space-y-4",children:g?e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:[...Array(3)].map((J,ce)=>e.jsxs(_e,{children:[e.jsx(on,{className:"h-48 w-full"}),e.jsxs(Oe,{className:"p-4 space-y-2",children:[e.jsx(on,{className:"h-5 w-3/4"}),e.jsx(on,{className:"h-4 w-1/2"})]})]},ce))}):(x==null?void 0:x.length)===0?e.jsx(_e,{children:e.jsxs(Oe,{className:"py-12 text-center",children:[e.jsx(fo,{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:x==null?void 0:x.map(J=>e.jsx(fae,{listing:J.listing,onClick:()=>s(`/mission-control/listings/${J.listing.id}`)},J.id))})}),e.jsx(Jt,{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(vd,{className:"h-4 w-4"}),"Referrals Sent (",((B=v==null?void 0:v.sent)==null?void 0:B.length)||0,")"]}),((q=v==null?void 0:v.sent)==null?void 0:q.length)===0?e.jsx(_e,{children:e.jsx(Oe,{className:"py-8 text-center text-muted-foreground",children:"No referrals sent yet"})}):e.jsx("div",{className:"space-y-3",children:(W=v==null?void 0:v.sent)==null?void 0:W.map(J=>{var ce,ue;return e.jsx(_e,{children:e.jsx(Oe,{className:"p-4",children:e.jsxs("div",{className:"flex justify-between items-start mb-2",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:J.buyer_name}),e.jsx("p",{className:"text-sm text-muted-foreground",children:((ce=J.listing)==null?void 0:ce.property_address)||((ue=J.listing)==null?void 0:ue.city)})]}),e.jsx($e,{variant:J.status==="closed"?"default":"secondary",children:J.status.replace("_"," ")})]})})},J.id)})})]}),e.jsxs("div",{children:[e.jsxs("h3",{className:"font-semibold mb-3 flex items-center gap-2",children:[e.jsx(qn,{className:"h-4 w-4"}),"Referrals Received (",((V=v==null?void 0:v.received)==null?void 0:V.length)||0,")"]}),((K=v==null?void 0:v.received)==null?void 0:K.length)===0?e.jsx(_e,{children:e.jsx(Oe,{className:"py-8 text-center text-muted-foreground",children:"No referrals received yet"})}):e.jsx("div",{className:"space-y-3",children:(Q=v==null?void 0:v.received)==null?void 0:Q.map(J=>{var ce;return e.jsx(_e,{children:e.jsxs(Oe,{className:"p-4",children:[e.jsxs("div",{className:"flex justify-between items-start mb-2",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:J.buyer_name}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:["From: ",(ce=J.sender)==null?void 0:ce.name]})]}),e.jsx($e,{variant:J.status==="closed"?"default":"secondary",children:J.status.replace("_"," ")})]}),e.jsx($,{size:"sm",variant:"outline",className:"w-full mt-2",onClick:()=>s(`/mission-control/listings/${J.listing_id}`),children:"View Listing"})]})},J.id)})})]})]})}),t&&e.jsx(Jt,{value:"brokerage",className:"space-y-4",children:A?e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:[...Array(3)].map((J,ce)=>e.jsxs(_e,{children:[e.jsx(on,{className:"h-48 w-full"}),e.jsxs(Oe,{className:"p-4 space-y-2",children:[e.jsx(on,{className:"h-5 w-3/4"}),e.jsx(on,{className:"h-4 w-1/2"})]})]},ce))}):(C==null?void 0:C.length)===0?e.jsx(_e,{children:e.jsxs(Oe,{className:"py-12 text-center",children:[e.jsx(lR,{className:"h-12 w-12 mx-auto text-muted-foreground mb-4"}),e.jsx("h3",{className:"text-lg font-medium mb-2",children:"No brokerage listings yet"}),e.jsx("p",{className:"text-muted-foreground mb-4",children:"No agents in your brokerage have added listings yet."}),e.jsxs($,{onClick:()=>s("/mission-control/listings/new"),children:[e.jsx(sn,{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:C==null?void 0:C.map(J=>e.jsx(fae,{listing:J,onClick:()=>s(`/mission-control/listings/${J.id}`)},J.id))})}),e.jsx(Jt,{value:"map",children:e.jsx(LLn,{listings:m||[],isLoading:p})}),e.jsx(Jt,{value:"leaderboard",children:e.jsx(TLn,{leaderboard:T})})]})]}),e.jsx(SLn,{})]}):e.jsx(Ks,{title:"Listing Exchange",description:"Community-powered listing collaboration",children:e.jsx(_e,{children:e.jsxs(Oe,{className:"py-12 text-center",children:[e.jsx(sa,{className:"h-12 w-12 mx-auto text-muted-foreground mb-4"}),e.jsx("h2",{className:"text-xl font-semibold mb-2",children:"Coming Soon"}),e.jsx("p",{className:"text-muted-foreground",children:"Listing Exchange is currently in development. Check back soon!"})]})})})}function Hqt(s){return ht({queryKey:["listing-documents",s],queryFn:async()=>{const{data:t,error:n}=await U.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 ILn(){const{user:s}=_s(),t=ts();return yt({mutationFn:async({listingId:n,file:r})=>{if(!(s!=null&&s.id))throw new Error("Not authenticated");const a=r.name.split(".").pop(),i=`${s.id}/${n}/${crypto.randomUUID()}.${a}`,{error:l}=await U.storage.from("listing-documents").upload(i,r,{contentType:r.type||void 0});if(l)throw l;const{data:o,error:c}=await U.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:i}).select().single();if(c)throw c;return o},onSuccess:(n,r)=>{t.invalidateQueries({queryKey:["listing-documents",r.listingId]})}})}function DLn(){const s=ts();return yt({mutationFn:async({id:t,storage_path:n,listingId:r})=>{await U.storage.from("listing-documents").remove([n]);const{error:a}=await U.from("listing_documents").delete().eq("id",t);if(a)throw a;return r},onSuccess:t=>{s.invalidateQueries({queryKey:["listing-documents",t]})}})}function RLn(){const s=ts();return yt({mutationFn:async({id:t,visible:n,listingId:r})=>{const{error:a}=await U.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 Gqt(s){const{data:t,error:n}=await U.storage.from("listing-documents").createSignedUrl(s,3600);if(n)throw n;return t.signedUrl}const OLn=s=>s<1024?`${s} B`:s<1024*1024?`${(s/1024).toFixed(0)} KB`:`${(s/(1024*1024)).toFixed(1)} MB`;function FLn({listingId:s,ownerOnly:t=!1}){const{data:n=[]}=Hqt(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 Gqt(i);window.open(l,"_blank")}catch{ae.error("Failed to open document")}};return e.jsxs(_e,{children:[e.jsx(Bt,{children:e.jsxs(Ut,{className:"text-lg flex items-center gap-2",children:[e.jsx(Wr,{className:"h-5 w-5"}),"Documents & Disclosures (",r.length,")"]})}),e.jsx(Oe,{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(Wr,{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:OLn(i.file_size)})]}),e.jsx(di,{className:"h-4 w-4 text-muted-foreground group-hover:text-primary"})]},i.id))})})]})}var zLn=Object.defineProperty,O4e=Object.getOwnPropertySymbols,Wqt=Object.prototype.hasOwnProperty,Kqt=Object.prototype.propertyIsEnumerable,mvt=(s,t,n)=>t in s?zLn(s,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):s[t]=n,hUe=(s,t)=>{for(var n in t||(t={}))Wqt.call(t,n)&&mvt(s,n,t[n]);if(O4e)for(var n of O4e(t))Kqt.call(t,n)&&mvt(s,n,t[n]);return s},mUe=(s,t)=>{var n={};for(var r in s)Wqt.call(s,r)&&t.indexOf(r)<0&&(n[r]=s[r]);if(s!=null&&O4e)for(var r of O4e(s))t.indexOf(r)<0&&Kqt.call(s,r)&&(n[r]=s[r]);return n};/** * @license QR Code generator library (TypeScript) * Copyright (c) Project Nayuki. * SPDX-License-Identifier: MIT */var BO;(s=>{const t=class Gc{constructor(c,d,u,h){if(this.version=c,this.errorCorrectionLevel=d,this.modules=[],this.isFunction=[],cGc.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 x=0;x7)throw new RangeError("Invalid value");let x,g;for(x=u;;x++){const N=Gc.getNumDataCodewords(x,d)*8,C=l.getTotalBits(c,x);if(C<=N){g=C;break}if(x>=h)throw new RangeError("Data too long")}for(const N of[Gc.Ecc.MEDIUM,Gc.Ecc.QUARTILE,Gc.Ecc.HIGH])p&&g<=Gc.getNumDataCodewords(x,N)*8&&(d=N);let y=[];for(const N of c){n(N.mode.modeBits,4,y),n(N.numChars,N.mode.numCharCountBits(x),y);for(const C of N.getData())y.push(C)}a(y.length==g);const b=Gc.getNumDataCodewords(x,d)*8;a(y.length<=b),n(0,Math.min(4,b-y.length),y),n(0,(8-y.length%8)%8,y),a(y.length%8==0);for(let N=236;y.lengthv[C>>>3]|=N<<7-(C&7)),new Gc(x,d,v,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,x=d+u;0<=p&&p{(N!=g-m||A>=x)&&v.push(C[N])});return a(v.length==p),v}drawCodewords(c){if(c.length!=Math.floor(Gc.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(x,g),p||(c+=this.finderPenaltyCountPatterns(g)*Gc.PENALTY_N3),p=this.modules[m][y],x=1);c+=this.finderPenaltyTerminateAndCount(p,x,g)*Gc.PENALTY_N3}for(let m=0;m5&&c++):(this.finderPenaltyAddHistory(x,g),p||(c+=this.finderPenaltyCountPatterns(g)*Gc.PENALTY_N3),p=this.modules[y][m],x=1);c+=this.finderPenaltyTerminateAndCount(p,x,g)*Gc.PENALTY_N3}for(let m=0;mp+(x?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*Gc.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.lengthGc.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(Gc.getNumRawDataModules(c)/8)-Gc.ECC_CODEWORDS_PER_BLOCK[d.ordinal][c]*Gc.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,x)=>u[x]^=Gc.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 cf{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 cf(cf.Mode.BYTE,c.length,d)}static makeNumeric(c){if(!cf.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={}))})(BO||(BO={}));(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={}))})(BO||(BO={}));var nz=BO;/** * @license qrcode.react * Copyright (c) Paul O'Shannessy * SPDX-License-Identifier: ISC */var BLn={L:nz.QrCode.Ecc.LOW,M:nz.QrCode.Ecc.MEDIUM,Q:nz.QrCode.Ecc.QUARTILE,H:nz.QrCode.Ecc.HIGH},Yqt=128,Zqt="L",Xqt="#FFFFFF",Qqt="#000000",Jqt=!1,eVt=1,$Ln=4,ULn=0,qLn=.1;function tVt(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 sVt(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 VLn(s,t,n,r){if(r==null)return null;const a=s.length+n*2,i=Math.floor(t*qLn),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 x=Math.floor(d),g=Math.floor(u),y=Math.ceil(o+d-x),b=Math.ceil(c+u-g);m={x,y:g,w:y,h:b}}const p=r.crossOrigin;return{x:d,y:u,h:c,w:o,excavation:m,opacity:h,crossOrigin:p}}function HLn(s,t){return t!=null?Math.max(Math.floor(t),0):s?$Ln:ULn}function nVt({value:s,level:t,minVersion:n,includeMargin:r,marginSize:a,imageSettings:i,size:l,boostLevel:o}){let c=It.useMemo(()=>{const x=(Array.isArray(s)?s:[s]).reduce((g,y)=>(g.push(...nz.QrSegment.makeSegments(y)),g),[]);return nz.QrCode.encodeSegments(x,BLn[t],n,void 0,void 0,o)},[s,t,n,o]);const{cells:d,margin:u,numCells:h,calculatedImageSettings:m}=It.useMemo(()=>{let p=c.getModules();const x=HLn(r,a),g=p.length+x*2,y=VLn(p,l,x,i);return{cells:p,margin:x,numCells:g,calculatedImageSettings:y}},[c,l,i,r,a]);return{qrcode:c,margin:u,cells:d,numCells:h,calculatedImageSettings:m}}var GLn=function(){try{new Path2D().addPath(new Path2D)}catch{return!1}return!0}(),WLn=It.forwardRef(function(t,n){const r=t,{value:a,size:i=Yqt,level:l=Zqt,bgColor:o=Xqt,fgColor:c=Qqt,includeMargin:d=Jqt,minVersion:u=eVt,boostLevel:h,marginSize:m,imageSettings:p}=r,g=mUe(r,["value","size","level","bgColor","fgColor","includeMargin","minVersion","boostLevel","marginSize","imageSettings"]),{style:y}=g,b=mUe(g,["style"]),v=p==null?void 0:p.src,N=It.useRef(null),C=It.useRef(null),A=It.useCallback(V=>{N.current=V,typeof n=="function"?n(V):n&&(n.current=V)},[n]),[T,P]=It.useState(!1),{margin:M,cells:I,numCells:D,calculatedImageSettings:B}=nVt({value:a,level:l,minVersion:u,boostLevel:h,includeMargin:d,marginSize:m,imageSettings:p,size:i});It.useEffect(()=>{if(N.current!=null){const V=N.current,K=V.getContext("2d");if(!K)return;let Q=I;const J=C.current,ce=B!=null&&J!==null&&J.complete&&J.naturalHeight!==0&&J.naturalWidth!==0;ce&&B.excavation!=null&&(Q=sVt(I,B.excavation));const ue=window.devicePixelRatio||1;V.height=V.width=i*ue;const ne=i/D*ue;K.scale(ne,ne),K.fillStyle=o,K.fillRect(0,0,D,D),K.fillStyle=c,GLn?K.fill(new Path2D(tVt(Q,M))):I.forEach(function(ee,le){ee.forEach(function(he,ve){he&&K.fillRect(ve+M,le+M,1,1)})}),B&&(K.globalAlpha=B.opacity),ce&&K.drawImage(J,B.x+M,B.y+M,B.w,B.h)}}),It.useEffect(()=>{P(!1)},[v]);const q=hUe({height:i,width:i},y);let W=null;return v!=null&&(W=It.createElement("img",{src:v,key:v,style:{display:"none"},onLoad:()=>{P(!0)},ref:C,crossOrigin:B==null?void 0:B.crossOrigin})),It.createElement(It.Fragment,null,It.createElement("canvas",hUe({style:q,height:i,width:i,ref:A,role:"img"},b)),W)});WLn.displayName="QRCodeCanvas";var XN=It.forwardRef(function(t,n){const r=t,{value:a,size:i=Yqt,level:l=Zqt,bgColor:o=Xqt,fgColor:c=Qqt,includeMargin:d=Jqt,minVersion:u=eVt,boostLevel:h,title:m,marginSize:p,imageSettings:x}=r,g=mUe(r,["value","size","level","bgColor","fgColor","includeMargin","minVersion","boostLevel","title","marginSize","imageSettings"]),{margin:y,cells:b,numCells:v,calculatedImageSettings:N}=nVt({value:a,level:l,minVersion:u,boostLevel:h,includeMargin:d,marginSize:p,imageSettings:x,size:i});let C=b,A=null;x!=null&&N!=null&&(N.excavation!=null&&(C=sVt(b,N.excavation)),A=It.createElement("image",{href:x.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=tVt(C,y);return It.createElement("svg",hUe({height:i,width:i,viewBox:`0 0 ${v} ${v}`,ref:n,role:"img"},g),!!m&&It.createElement("title",null,m),It.createElement("path",{fill:o,d:`M0,0 h${v}v${v}H0z`,shapeRendering:"crispEdges"}),It.createElement("path",{fill:c,d:T,shapeRendering:"crispEdges"}),A)});XN.displayName="QRCodeSVG";function KLn({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,x=new Blob([m],{type:"image/svg+xml;charset=utf-8"}),g=URL.createObjectURL(x);p.onload=()=>{const y=document.createElement("canvas");y.width=h,y.height=h;const b=y.getContext("2d");b&&(b.fillStyle="#ffffff",b.fillRect(0,0,h,h),b.drawImage(p,0,0,h,h),URL.revokeObjectURL(g),y.toBlob(v=>{if(!v)return;const N=document.createElement("a");N.href=URL.createObjectURL(v),N.download=`${o}.png`,N.click(),URL.revokeObjectURL(N.href)},"image/png"))},p.src=g};return e.jsx(Os,{open:s,onOpenChange:t,children:e.jsxs(Rs,{className:"sm:max-w-md",children:[e.jsxs(Us,{children:[e.jsx(zs,{children:"Listing QR Code"}),e.jsx(Sr,{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(XN,{value:n,size:220,level:"H",includeMargin:!0})}),e.jsx("p",{className:"text-xs text-muted-foreground break-all text-center",children:n})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-3 gap-2 pt-2",children:[e.jsxs($,{onClick:()=>u(),className:"gap-2",children:[e.jsx(di,{className:"h-4 w-4"}),"PNG"]}),e.jsxs($,{variant:"outline",onClick:d,className:"gap-2",children:[e.jsx(di,{className:"h-4 w-4"}),"SVG"]}),e.jsxs($,{variant:"outline",onClick:async()=>{await navigator.clipboard.writeText(n),ae.success("Link copied")},className:"gap-2",children:[e.jsx(Ca,{className:"h-4 w-4"}),"Copy link"]})]})]})})}const YLn=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)}`},pvt=s=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(s),qM="#D4AF37",fvt="#0F172A",xvt=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}),gvt=(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)},XW=(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()}…`},ZLn=(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},QLn=s=>s instanceof DOMException||s instanceof Error?s.name:null;function rVt({listingId:s,open:t,onOpenChange:n}){var A,T;const{data:r}=mGe(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((P,M)=>P.is_primary&&!M.is_primary?-1:!P.is_primary&&M.is_primary?1:(P.sort_order??0)-(M.sort_order??0));j.useEffect(()=>{var M;if(!t)return;const P=((M=m[0])==null?void 0:M.photo_url)||null;h(I=>I||P)},[t,r==null?void 0:r.id,m.length]),j.useEffect(()=>{let P=!1;if(!(!t||!(r!=null&&r.agent_id)))return(async()=>{var B,q,W,V;const{data:M}=await U.from("profiles").select("name, phone, phone_e164, avatar_url, brokerage:brokerages!profiles_brokerage_id_fkey(name)").eq("id",r.agent_id).maybeSingle();if(P)return;const I=M,D=((B=I==null?void 0:I.brokerage)==null?void 0:B.name)||((W=(q=r.agent)==null?void 0:q.brokerage)==null?void 0:W.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:D})})(),()=>{P=!0}},[t,r==null?void 0:r.agent_id]),j.useEffect(()=>{if(!t){d(null),h(null);return}if(!r||!a)return;const P=setTimeout(()=>{p()},350);return()=>clearTimeout(P)},[t,r==null?void 0:r.id,a==null?void 0:a.name,u]);const p=async()=>{if(!(!r||!a)){o(!0);try{const P=document.createElement("canvas");P.width=1080,P.height=1080;const M=P.getContext("2d");if(!M)throw new Error("Canvas unavailable");if(M.fillStyle=fvt,M.fillRect(0,0,1080,1080),v){const V=await xvt(v);gvt(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=qM,M.fillRect(56,62,72,2),M.font="600 22px Arial, sans-serif",XLn(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 D=ZLn(M,r.property_address||`${r.city||""}, ${r.state||""}`.trim(),952,2);let B=D.length>1?590:654;D.forEach(V=>{M.fillText(V,64,B),B+=70}),M.restore();const q=[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(XW(M,q.toUpperCase(),952),64,B+8),M.fillStyle=qM,M.font="700 56px Arial, sans-serif",M.fillText(pvt(r.price),64,B+58),C.length>0&&(M.fillStyle="rgba(248,250,252,0.86)",M.font="600 22px Arial, sans-serif",M.fillText(XW(M,C.join(" · "),430),360,B+78));const W=M.createLinearGradient(0,880,0,1080);if(W.addColorStop(0,"rgba(15,23,42,0.96)"),W.addColorStop(1,"#0B1322"),M.fillStyle=W,M.fillRect(0,880,1080,200),M.fillStyle=qM,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=qM,M.stroke(),M.clip(),a.avatar_url)try{const V=await xvt(a.avatar_url);gvt(M,V,64,920,120,120)}catch{M.fillStyle=qM,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=qM,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(XW(M,a.name,N?430:820),212,970),a.brokerage&&(M.fillStyle=qM,M.font="600 20px Arial, sans-serif",M.fillText(XW(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(P.toDataURL("image/png"))}catch(P){console.error("Generate graphic error",P),ae.error("Could not generate graphic")}finally{o(!1)}}},x=async P=>(await fetch(P)).blob(),g=async()=>{if(!c)return;const P=document.createElement("a");P.href=c,P.download=`just-listed-${(r==null?void 0:r.slug)||(r==null?void 0:r.id)||"graphic"}.png`,P.click(),ae.success("Downloaded!")},y=async()=>{if(c)try{const P=await x(c);await navigator.clipboard.write([new ClipboardItem({"image/png":P})]),ae.success("Copied to clipboard")}catch{ae.error("Copy not supported in this browser")}},b=async()=>{if(c)try{const P=await x(c),M=new File([P],"just-listed.png",{type:"image/png"});navigator.canShare&&navigator.canShare({files:[M]})?await navigator.share({files:[M],title:"Just Listed"}):g()}catch(P){QLn(P)!=="AbortError"&&ae.error("Share failed")}},v=u||((A=m[0])==null?void 0:A.photo_url)||null,N=YLn(a==null?void 0:a.phone),C=[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(Os,{open:t,onOpenChange:n,children:e.jsx(Rs,{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(Us,{className:"px-5 pt-5 pb-3 shrink-0",children:[e.jsxs(zs,{className:"flex items-center gap-2 pr-8",children:[e.jsx(dn,{className:"h-5 w-5 text-amber-500 shrink-0"}),e.jsx("span",{className:"truncate",children:"Your Just Listed Graphic"})]}),e.jsx(Sr,{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:fvt},children:[v&&e.jsx("img",{src:v,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?pvt(r.price):""}),C.length>0&&e.jsx("span",{className:"truncate text-[8px] font-semibold uppercase tracking-[0.14em] text-white/80",children:C.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(Ht,{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(P=>{const M=u===P.photo_url;return e.jsx("button",{type:"button",onClick:()=>h(P.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:P.photo_url,alt:"",className:"w-full h-full object-cover"})},P.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($,{variant:"outline",size:"sm",onClick:()=>void p(),disabled:l||!r||!a,children:"Regenerate"}),e.jsxs($,{variant:"outline",size:"sm",onClick:y,disabled:!c,className:"gap-1.5",children:[e.jsx(Ca,{className:"h-3.5 w-3.5"})," Copy"]}),e.jsxs($,{variant:"outline",size:"sm",onClick:b,disabled:!c,className:"gap-1.5",children:[e.jsx(vd,{className:"h-3.5 w-3.5"})," Share"]}),e.jsxs($,{size:"sm",onClick:g,disabled:!c,className:"gap-1.5",children:[e.jsx(di,{className:"h-3.5 w-3.5"})," Download"]})]})]})})})}function JLn(s){return new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(s)}const ePn={single_family:"Single Family Home",condo:"Condo",townhouse:"Townhouse",land:"Land",multi_family:"Multi-Family",luxury:"Luxury Home",commercial:"Commercial",other:"Property"};function tPn({open:s,onOpenChange:t,listing:n}){const{user:r}=_s(),{data:a=[],isLoading:i}=M1(),{data:l=[]}=Hb(),[o,c]=j.useState(""),[d,u]=j.useState("all"),[h,m]=j.useState(new Set),[p,x]=j.useState(!1),[g,y]=j.useState(null);j.useEffect(()=>{s||(c(""),u("all"),m(new Set),x(!1))},[s]),j.useEffect(()=>{!s||!r||(async()=>{const{data:M}=await U.from("gmail_integrations").select("gmail_email").eq("user_id",r.id).maybeSingle();y((M==null?void 0:M.gmail_email)||null)})()},[s,r]);const b=j.useMemo(()=>a.filter(M=>M.email),[a]),v=j.useMemo(()=>{let M=b;if(d!=="all"&&(M=M.filter(I=>{var D;return(D=I.tags)==null?void 0:D.some(B=>B.relationship_type_id===d)})),o.trim()){const I=o.toLowerCase();M=M.filter(D=>`${D.first_name||""} ${D.last_name||""}`.toLowerCase().includes(I)||(D.email||"").toLowerCase().includes(I))}return M},[b,o,d]),N=()=>{h.size===v.length?m(new Set):m(new Set(v.map(M=>M.id)))},C=M=>{const I=new Set(h);I.has(M)?I.delete(M):I.add(M),m(I)},A=j.useMemo(()=>b.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})),[b,h]),{defaultSubject:T,defaultBody:P}=j.useMemo(()=>{var ee,le,he,ve;const M=n.property_address||`${n.city}, ${n.state}`,I=JLn(n.price),D=ePn[n.property_type]||"home",B=n.bedrooms?`${n.bedrooms} bed`:"",q=n.bathrooms?`${n.bathrooms} bath`:"",W=n.square_footage?`${n.square_footage.toLocaleString()} sqft`:"",V=[B,q,W].filter(Boolean).join(" • "),K=`https://listings.relevelup.com/${n.slug||n.id}`,Q=((le=(ee=n.photos)==null?void 0:ee.find(ge=>ge.is_primary))==null?void 0:le.photo_url)||((ve=(he=n.photos)==null?void 0:he[0])==null?void 0:ve.photo_url)||"",ce={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=`${ce}: ${M} — ${I}`,ne=`

Hi {{first_name}},

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

${Q?` ${M} `:""}
${ce}

${I}

${M}

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

${V?`

${V} • ${D}

`:""} View Photos & Details →

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

Talk soon,

`;return{defaultSubject:ue,defaultBody:ne}},[n]);return p?e.jsx(x2,{open:p,onOpenChange:M=>{x(M),M||t(!1)},bulkContacts:A,defaultSubject:T,defaultBody:P,gmailEmail:g}):e.jsx(Os,{open:s,onOpenChange:t,children:e.jsxs(Rs,{className:"sm:max-w-[640px] max-h-[90vh] flex flex-col",children:[e.jsxs(Us,{children:[e.jsxs(zs,{className:"flex items-center gap-2",children:[e.jsx(dn,{className:"h-5 w-5 text-amber-500"}),"Email this listing to your sphere"]}),e.jsx(Sr,{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(Vr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(be,{placeholder:"Search contacts...",value:o,onChange:M=>c(M.target.value),className:"pl-9"})]}),e.jsxs(vs,{value:d,onValueChange:u,children:[e.jsx(gs,{className:"sm:w-[180px]",children:e.jsx(bs,{placeholder:"Filter by tag"})}),e.jsxs(ys,{children:[e.jsx(Ye,{value:"all",children:"All contacts"}),l.map(M=>e.jsx(Ye,{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(ui,{checked:v.length>0&&h.size===v.length,className:"pointer-events-none"}),e.jsx("span",{children:h.size===v.length&&v.length>0?"Deselect all":`Select all (${v.length})`})]}),e.jsxs($e,{variant:"secondary",className:"gap-1",children:[e.jsx(qn,{className:"h-3 w-3"}),h.size," selected"]})]}),e.jsx(Oi,{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(Ht,{className:"h-5 w-5 animate-spin mr-2"}),"Loading your contacts..."]}):v.length===0?e.jsx("div",{className:"text-center py-12 text-muted-foreground text-sm",children:b.length===0?"No contacts with email addresses yet.":"No contacts match your search."}):e.jsx("div",{className:"space-y-1 py-2",children:v.map(M=>e.jsxs("label",{className:"flex items-center gap-3 p-2 rounded-md hover:bg-muted/50 cursor-pointer",children:[e.jsx(ui,{checked:h.has(M.id),onCheckedChange:()=>C(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 D;return e.jsx($e,{variant:"outline",className:"text-[10px] px-1.5 py-0",children:(D=I.relationship_type)==null?void 0:D.name},I.id)})})]},M.id))})}),e.jsx(Hl,{}),e.jsxs("div",{className:"flex justify-between items-center gap-3",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:g?`Sending from ${g}`:"Connect Gmail in Settings to send"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx($,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsxs($,{onClick:()=>x(!0),disabled:h.size===0,className:"gap-2",children:[e.jsx(nn,{className:"h-4 w-4"}),"Compose Email (",h.size,")"]})]})]})]})})}function bb(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 gte(){const s=Za();return ht({queryKey:["deal-pipeline-stages",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await U.from("deal_pipeline_stages").select("*").eq("owner_user_id",s).order("sort_order",{ascending:!0});if(n)throw n;return t},enabled:!!s})}function aVt(){const s=Za(),t=ts();return yt({mutationFn:async()=>{if(!s)throw new Error("Not authenticated");const{error:n}=await U.rpc("initialize_deal_pipeline_stages",{p_user_id:s});if(n)throw n},onSuccess:()=>{t.invalidateQueries({queryKey:["deal-pipeline-stages"]})}})}function ETe(){const s=Za();return ht({queryKey:["deal-pipeline-deals",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await U.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 iVt(){const s=Za(),t=ts();return yt({mutationFn:async n=>{if(!s)throw new Error("Not authenticated");const{data:r,error:a}=await U.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 U.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 oVt(){const s=ts();return yt({mutationFn:async({id:t,...n})=>{const{data:r,error:a}=await U.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 sPn(){const s=ts();return yt({mutationFn:async({dealId:t,stageId:n,stageName:r})=>{const{data:a}=await U.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 U.from("deal_pipeline").update(i).eq("id",t).select().single();if(o)throw o;return await U.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 nPn(){const s=ts();return yt({mutationFn:async t=>{const{error:n}=await U.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 rPn(s){return ht({queryKey:["deal-activities",s],queryFn:async()=>{const{data:t,error:n}=await U.from("deal_activities").select("*").eq("deal_id",s).order("created_at",{ascending:!1});if(n)throw n;return t},enabled:!!s})}function aPn(){const s=ts();return yt({mutationFn:async t=>{const{data:n,error:r}=await U.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 iPn(s){return ht({queryKey:["deal-checklist",s],queryFn:async()=>{const{data:t,error:n}=await U.from("deal_checklist_items").select("*").eq("deal_id",s).order("sort_order",{ascending:!0});if(n)throw n;return t},enabled:!!s})}function oPn(){const s=ts();return yt({mutationFn:async({id:t,is_completed:n,deal_id:r})=>{const{data:a,error:i}=await U.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 lPn(){const s=ts();return yt({mutationFn:async t=>{const{data:n,error:r}=await U.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 cPn(){const s=Za();return ht({queryKey:["deal-pipeline-stats",s],queryFn:async()=>{if(!s)return null;const{data:t,error:n}=await U.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+(bb(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+(bb(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+(bb(c)||0),0),projectedAnnualNet:l.reduce((o,c)=>o+(bb(c)||0),0)+r.reduce((o,c)=>{const d=(c.probability??50)/100;return o+(bb(c)||0)*d},0)}},enabled:!!s})}function dPn(s){const t=Za();return ht({queryKey:["deal-by-listing",s,t],queryFn:async()=>{if(!t||!s)return null;const{data:n,error:r}=await U.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 uPn(){const s=ts();return yt({mutationFn:async({dealId:t,listingId:n})=>{const{data:r,error:a}=await U.from("deal_pipeline").update({listing_id:n}).eq("id",t).select().single();if(a)throw a;return await U.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 hPn(){const s=ts();return yt({mutationFn:async({dealId:t,listingId:n})=>{const{data:r,error:a}=await U.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 mPn({listing:s}){const t=Vn(),[n,r]=j.useState(""),[a,i]=j.useState(!1),{data:l,isLoading:o}=dPn(s.id),{data:c,isLoading:d}=gte(),{data:u,isLoading:h}=ETe(),m=aVt(),p=uPn(),x=hPn(),g=iVt(),y=(u==null?void 0:u.filter(A=>!A.listing_id))||[],b=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")}},v=async()=>{i(!0);try{c!=null&&c.length||await m.mutateAsync();const A=b(s.status);await g.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}),ae.success("Deal created and linked to listing!")}catch(A){console.error("Failed to create deal:",A),ae.error("Failed to create deal")}finally{i(!1)}},N=async()=>{if(!n){ae.error("Please select a deal");return}try{await p.mutateAsync({dealId:n,listingId:s.id}),ae.success("Listing linked to deal!"),r("")}catch{ae.error("Failed to link listing")}},C=async()=>{if(l)try{await x.mutateAsync({dealId:l.id,listingId:s.id}),ae.success("Listing unlinked from deal")}catch{ae.error("Failed to unlink listing")}};return o||d?e.jsxs(_e,{children:[e.jsx(Bt,{children:e.jsxs(Ut,{className:"flex items-center gap-2 text-base",children:[e.jsx(a5,{className:"h-4 w-4"}),"Deal Pipeline"]})}),e.jsx(Oe,{children:e.jsx("div",{className:"flex items-center justify-center py-4",children:e.jsx(Ht,{className:"h-5 w-5 animate-spin text-muted-foreground"})})})]}):l?e.jsxs(_e,{className:"border-primary/20 bg-primary/5",children:[e.jsx(Bt,{className:"pb-2",children:e.jsxs(Ut,{className:"flex items-center gap-2 text-base",children:[e.jsx(Dc,{className:"h-4 w-4 text-primary"}),"Linked to Pipeline"]})}),e.jsxs(Oe,{className:"space-y-3",children:[e.jsx("div",{className:"flex items-center justify-between",children:e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-sm",children:l.deal_name}),e.jsx("div",{className:"flex items-center gap-2 mt-1",children:l.deal_pipeline_stages&&e.jsx($e,{variant:"secondary",className:"text-xs",style:{backgroundColor:`${l.deal_pipeline_stages.color}20`,color:l.deal_pipeline_stages.color},children:l.deal_pipeline_stages.name})})]})}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Status changes sync automatically between the listing and pipeline."}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs($,{variant:"outline",size:"sm",className:"flex-1",onClick:()=>t("/mission-control/pipeline"),children:["View Pipeline",e.jsx(ni,{className:"h-3 w-3 ml-1"})]}),e.jsx($,{variant:"ghost",size:"sm",onClick:C,disabled:x.isPending,children:x.isPending?e.jsx(Ht,{className:"h-4 w-4 animate-spin"}):e.jsx(AR,{className:"h-4 w-4"})})]})]})]}):e.jsxs(_e,{children:[e.jsx(Bt,{className:"pb-2",children:e.jsxs(Ut,{className:"flex items-center gap-2 text-base",children:[e.jsx(a5,{className:"h-4 w-4"}),"Deal Pipeline"]})}),e.jsxs(Oe,{className:"space-y-4",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Link this listing to your pipeline to track the deal and sync status changes."}),e.jsxs($,{onClick:v,disabled:a||g.isPending,className:"w-full",size:"sm",children:[a||g.isPending?e.jsx(Ht,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(sn,{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(vs,{value:n,onValueChange:r,children:[e.jsx(gs,{className:"flex-1 text-sm",children:e.jsx(bs,{placeholder:"Link to existing deal..."})}),e.jsx(ys,{children:y.map(A=>e.jsx(Ye,{value:A.id,children:A.deal_name},A.id))})]}),e.jsx($,{variant:"secondary",size:"icon",onClick:N,disabled:!n||p.isPending,children:p.isPending?e.jsx(Ht,{className:"h-4 w-4 animate-spin"}):e.jsx(Dc,{className:"h-4 w-4"})})]})]})]})]})}const pPn={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"},fPn={active:"Active",coming_soon:"Coming Soon",office_exclusive:"Office Exclusive",pre_market:"Pre-Market",price_improvement:"Price Improvement",under_contract:"Under Contract",sold:"Sold"},yvt={single_family:"Single Family",condo:"Condo",townhouse:"Townhouse",land:"Land",multi_family:"Multi-Family",luxury:"Luxury",commercial:"Commercial",other:"Other"};function xPn(){var ue,ne,ee,le,he,ve,ge,fe,je;const{listingId:s}=Vi(),t=Vn(),{user:n}=_s(),{data:r,isLoading:a}=mGe(s||""),{data:i}=j6t(s||""),{data:l}=HCs(s||""),o=w6t(),c=VCs(),d=GCs(),u=_6t(),h=KCs(),[m,p]=j.useState(!1),[x,g]=j.useState(!1),[y,b]=j.useState(!1),[v,N]=j.useState(!1),[C,A]=j.useState(!1),[T,P]=j.useState(!1),[M,I]=j.useState(null),[D,B]=j.useState({buyerName:"",buyerType:"",notes:""}),q=(n==null?void 0:n.id)===(r==null?void 0:r.agent_id),W=Ee=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(Ee),V=async Ee=>{const Me=`https://listings.relevelup.com/${(r==null?void 0:r.slug)||(r==null?void 0:r.id)}`,De=`Check out this listing: ${(r==null?void 0:r.property_address)||(r==null?void 0:r.city)}`;d.mutate({listingId:r.id,shareType:Ee});try{switch(Ee){case"facebook":window.open(`https://www.facebook.com/sharer/sharer.php?u=${encodeURIComponent(Me)}`,"_blank");break;case"copy":await navigator.clipboard.writeText(Me),ae.success("Link copied to clipboard!");break;case"text":window.open(`sms:?body=${encodeURIComponent(`${De} ${Me}`)}`);break;case"email":window.open(`mailto:?subject=${encodeURIComponent(De)}&body=${encodeURIComponent(`Check out this listing: ${Me}`)}`);break}}catch(ze){console.error("Share error:",ze),ae.error("Failed to share")}},K=async()=>{try{await u.mutateAsync(r.id),ae.success("Listing deleted"),t("/mission-control/listings")}catch{ae.error("Failed to delete listing")}},Q=async()=>{if(!D.buyerName.trim()){ae.error("Please enter buyer name");return}try{await h.mutateAsync({listingId:r.id,listingAgentId:r.agent_id,buyerName:D.buyerName,buyerType:D.buyerType||void 0,notes:D.notes||void 0}),ae.success("Referral sent successfully!"),g(!1),B({buyerName:"",buyerType:"",notes:""})}catch{ae.error("Failed to send referral")}},J=Ee=>{var Re,Ae;const Me=(r==null?void 0:r.property_address)||`${r==null?void 0:r.city}, ${r==null?void 0:r.state}`,De=W((r==null?void 0:r.price)||0),ze=r!=null&&r.bedrooms?`${r.bedrooms}BD`:"",ke=r!=null&&r.bathrooms?`${r.bathrooms}BA`:"",Xe=r!=null&&r.square_footage?`${r.square_footage.toLocaleString()}SF`:"",Se=[ze,ke,Xe].filter(Boolean).join(" | ");switch(Ee){case"just_listed":return`🏡 JUST LISTED! ${Me} ${De} ${Se} ${(r==null?void 0:r.description)||"Schedule your showing today!"} #JustListed #RealEstate #HomeForSale #${(Re=r==null?void 0:r.city)==null?void 0:Re.replace(/\s/g,"")}`;case"price_improvement":return`📣 PRICE IMPROVEMENT! ${Me} Now ${De}! ${Se} Don't miss this opportunity! #PriceReduced #RealEstate #HomeForSale`;case"teaser":return`Looking for a ${yvt[(r==null?void 0:r.property_type)||"single_family"].toLowerCase()} in ${r==null?void 0:r.city}? 👀 I've got just the one for you! ${Se} DM me for details! 📩 #ComingSoon #RealEstate #${(Ae=r==null?void 0:r.city)==null?void 0:Ae.replace(/\s/g,"")}`;default:return""}};if(a)return e.jsx(Ks,{title:"Listing",description:"",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(on,{className:"h-10 w-32"}),e.jsx(on,{className:"h-[400px] w-full"}),e.jsxs("div",{className:"grid md:grid-cols-3 gap-6",children:[e.jsx(on,{className:"h-48"}),e.jsx(on,{className:"h-48"}),e.jsx(on,{className:"h-48"})]})]})});if(!r)return e.jsx(Ks,{title:"Listing Not Found",description:"",children:e.jsx(_e,{children:e.jsxs(Oe,{className:"py-12 text-center",children:[e.jsx("p",{className:"text-muted-foreground mb-4",children:"This listing could not be found."}),e.jsx($,{onClick:()=>t("/mission-control/listings"),children:"Back to Listings"})]})})});const ce=((ue=r.photos)==null?void 0:ue.find(Ee=>Ee.is_primary))||((ne=r.photos)==null?void 0:ne[0]);return e.jsxs(Ks,{title:"",description:"",children:[e.jsxs("div",{className:"space-y-6",children:[e.jsxs($,{variant:"ghost",onClick:()=>t("/mission-control/listings"),children:[e.jsx(ka,{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:()=>ce&&I(ce.photo_url),children:ce?e.jsx("img",{src:ce.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:(ee=r.photos)==null?void 0:ee.slice(1,5).map((Ee,Me)=>e.jsx("div",{className:"aspect-square rounded-lg overflow-hidden bg-muted cursor-pointer",onClick:()=>I(Ee.photo_url),children:e.jsx("img",{src:Ee.photo_url,alt:`Photo ${Me+2}`,className:"w-full h-full object-cover"})},Ee.id))})]}),e.jsxs("div",{className:"grid md:grid-cols-3 gap-6",children:[e.jsxs("div",{className:"md:col-span-2 space-y-6",children:[e.jsx(_e,{children:e.jsxs(Oe,{className:"p-6",children:[e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-4 mb-6",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx($e,{className:`${pPn[r.status]} text-white border-0`,children:fPn[r.status]}),r.is_featured&&e.jsxs($e,{variant:"outline",className:"border-amber-500 text-amber-500",children:[e.jsx(Qa,{className:"h-3 w-3 mr-1 fill-amber-500"}),"Featured"]}),r.open_to_referrals&&e.jsxs($e,{variant:"outline",children:[e.jsx(qn,{className:"h-3 w-3 mr-1"}),"Open to Referrals"]})]}),e.jsx("h1",{className:"text-3xl font-bold text-primary mb-2",children:W(r.price)}),r.property_address&&e.jsx("p",{className:"text-xl font-medium",children:r.property_address}),e.jsxs("p",{className:"text-muted-foreground flex items-center gap-1",children:[e.jsx(ai,{className:"h-4 w-4"}),r.city,", ",r.state,r.neighborhood&&` • ${r.neighborhood}`]})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx($,{variant:"outline",size:"icon",onClick:()=>o.mutate(r.id),children:e.jsx(fo,{className:`h-4 w-4 ${i?"fill-pink-500 text-pink-500":""}`})}),e.jsx($,{variant:"outline",size:"icon",onClick:()=>c.mutate(r.id),children:l?e.jsx(e5,{className:"h-4 w-4"}):e.jsx(Dx,{className:"h-4 w-4"})}),!q&&e.jsxs($,{variant:"outline",className:"border-amber-500 text-amber-600 hover:bg-amber-50",onClick:()=>b(!0),children:[e.jsx(dn,{className:"h-4 w-4 mr-2"}),"Share & Earn Leads"]}),e.jsxs(Hd,{children:[e.jsx(Gd,{asChild:!0,children:e.jsxs($,{variant:"outline",children:[e.jsx(vd,{className:"h-4 w-4 mr-2"}),"Share"]})}),e.jsxs(Md,{children:[e.jsxs(Na,{onClick:()=>V("copy"),children:[e.jsx(Ca,{className:"h-4 w-4 mr-2"}),"Copy Link"]}),e.jsxs(Na,{onClick:()=>V("facebook"),children:[e.jsx(jf,{className:"h-4 w-4 mr-2"}),"Facebook"]}),e.jsxs(Na,{onClick:()=>V("text"),children:[e.jsx(Ji,{className:"h-4 w-4 mr-2"}),"Text"]}),e.jsxs(Na,{onClick:()=>V("email"),children:[e.jsx(nn,{className:"h-4 w-4 mr-2"}),"Email"]})]})]}),q&&e.jsxs(e.Fragment,{children:[e.jsxs($,{variant:"outline",onClick:()=>{const Ee=(r.photos??[]).slice().sort((Me,De)=>(De.is_primary?1:0)-(Me.is_primary?1:0)||(Me.sort_order??0)-(De.sort_order??0)).map(Me=>Me.photo_url).filter(Boolean);if(Ee.length===0){ae.error("Add photos to this listing first.");return}qqt({photos:Ee,details:{address:r.property_address||`${r.city??""} ${r.state??""}`.trim(),beds:r.bedrooms?String(r.bedrooms):"",baths:r.bathrooms?String(r.bathrooms):"",sqft:r.square_footage?String(r.square_footage):"",price:r.price?String(r.price):"",highlights:r.description||""},sourceLabel:"Listing Exchange",badge:Vqt(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(Pz,{className:"h-4 w-4"}),"Create Music Video"]}),e.jsxs($,{variant:"outline",onClick:()=>A(!0),className:"gap-2 border-amber-500/60 text-amber-600 hover:bg-amber-50",children:[e.jsx(dn,{className:"h-4 w-4"}),"Just Listed Graphic"]}),e.jsxs($,{variant:"outline",onClick:()=>P(!0),className:"gap-2",children:[e.jsx(Rx,{className:"h-4 w-4"}),"QR Code"]}),e.jsxs($,{variant:"outline",onClick:()=>N(!0),className:"gap-2",children:[e.jsx(nn,{className:"h-4 w-4"}),"Email My Sphere"]}),e.jsxs($,{onClick:()=>t(`/mission-control/listings/${r.id}/customize`),className:"gap-2 bg-gradient-to-r from-primary to-primary/80 hover:opacity-95 text-primary-foreground shadow-md",children:[e.jsx(dn,{className:"h-4 w-4"}),"Customize Public Page"]}),e.jsxs($,{variant:"outline",onClick:()=>t(`/mission-control/listings/${r.id}/edit`),children:[e.jsx(bm,{className:"h-4 w-4 mr-2"}),"Edit"]}),e.jsx($,{variant:"destructive",size:"icon",onClick:()=>p(!0),children:e.jsx(Pn,{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(tw,{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(_g,{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(Lb,{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(ia,{className:"h-5 w-5 mx-auto mb-1 text-muted-foreground"}),e.jsx("p",{className:"font-semibold",children:r.year_built}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Built"})]})]}),e.jsxs("div",{className:"pt-4 space-y-4",children:[e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs($e,{variant:"secondary",children:[e.jsx(Ai,{className:"h-3 w-3 mr-1"}),yvt[r.property_type]]}),r.lot_size&&e.jsxs($e,{variant:"secondary",children:["Lot: ",r.lot_size]}),r.has_hoa&&e.jsx($e,{variant:"secondary",children:"HOA"})]}),r.description&&e.jsxs("div",{children:[e.jsx("h3",{className:"font-medium mb-2",children:"Description"}),e.jsx("p",{className:"text-muted-foreground whitespace-pre-wrap",children:r.description})]}),r.agent_notes&&r.agent_notes_public&&e.jsxs("div",{children:[e.jsx("h3",{className:"font-medium mb-2",children:"Agent Notes"}),e.jsx("p",{className:"text-muted-foreground whitespace-pre-wrap",children:r.agent_notes})]}),r.co_agent_name&&e.jsxs("div",{children:[e.jsx("h3",{className:"font-medium mb-2",children:"Co-Listing Agent"}),e.jsxs("div",{className:"flex items-center gap-3 rounded-lg border p-3",children:[r.co_agent_photo_url?e.jsx("img",{src:r.co_agent_photo_url,alt:r.co_agent_name,className:"h-12 w-12 rounded-full object-cover"}):e.jsx("div",{className:"h-12 w-12 rounded-full bg-muted flex items-center justify-center text-sm font-medium",children:r.co_agent_name.charAt(0)}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"font-medium truncate",children:r.co_agent_name}),r.co_agent_brokerage&&e.jsx("p",{className:"text-sm text-muted-foreground truncate",children:r.co_agent_brokerage}),e.jsx("p",{className:"text-sm text-muted-foreground truncate",children:[r.co_agent_email,r.co_agent_phone].filter(Boolean).join(" · ")})]})]})]}),r.mls_link&&e.jsx($,{variant:"outline",asChild:!0,children:e.jsxs("a",{href:r.mls_link,target:"_blank",rel:"noopener noreferrer",children:[e.jsx(Tr,{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(ga,{className:"h-4 w-4"}),r.view_count," views"]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(vd,{className:"h-4 w-4"}),r.share_count," shares"]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(fo,{className:"h-4 w-4"}),r.save_count," saves"]})]})]})}),r.allow_sharing&&e.jsxs(_e,{children:[e.jsx(Bt,{children:e.jsx(Ut,{className:"text-lg",children:"Share Content"})}),e.jsx(Oe,{className:"space-y-4",children:["just_listed","price_improvement","teaser"].map(Ee=>e.jsxs("div",{className:"p-3 bg-muted rounded-lg",children:[e.jsxs("div",{className:"flex justify-between items-start mb-2",children:[e.jsxs("p",{className:"font-medium text-sm capitalize",children:[Ee.replace("_"," ")," Caption"]}),e.jsx($,{size:"sm",variant:"ghost",onClick:()=>{navigator.clipboard.writeText(J(Ee)),ae.success("Caption copied!")},children:e.jsx(Ca,{className:"h-3 w-3"})})]}),e.jsx("p",{className:"text-xs text-muted-foreground whitespace-pre-wrap",children:J(Ee)})]},Ee))})]}),e.jsx(FLn,{listingId:r.id,ownerOnly:q})]}),e.jsxs("div",{className:"space-y-6",children:[e.jsxs(_e,{children:[e.jsx(Bt,{children:e.jsx(Ut,{className:"text-lg",children:"Listing Agent"})}),e.jsxs(Oe,{children:[e.jsxs("div",{className:"flex items-center gap-3 mb-4",children:[e.jsx("div",{className:"w-12 h-12 rounded-full bg-primary/10 flex items-center justify-center",children:e.jsx("span",{className:"text-lg font-semibold text-primary",children:((he=(le=r.agent)==null?void 0:le.name)==null?void 0:he.charAt(0))||"?"})}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:((ve=r.agent)==null?void 0:ve.name)||"Unknown"}),((fe=(ge=r.agent)==null?void 0:ge.brokerage)==null?void 0:fe.name)&&e.jsx("p",{className:"text-sm text-muted-foreground",children:r.agent.brokerage.name})]})]}),!q&&e.jsx("div",{className:"space-y-2",children:((je=r.agent)==null?void 0:je.email)&&e.jsx($,{variant:"outline",className:"w-full",asChild:!0,children:e.jsxs("a",{href:`mailto:${r.agent.email}`,children:[e.jsx(nn,{className:"h-4 w-4 mr-2"}),"Email Agent"]})})})]})]}),q&&e.jsx(mPn,{listing:r}),!q&&r.open_to_referrals&&e.jsxs(_e,{children:[e.jsx(Bt,{children:e.jsxs(Ut,{className:"text-lg flex items-center gap-2",children:[e.jsx(qn,{className:"h-5 w-5"}),"Send a Buyer"]})}),e.jsxs(Oe,{children:[e.jsx("p",{className:"text-sm text-muted-foreground mb-4",children:"Have a buyer interested in this property? Send a referral to the listing agent."}),e.jsx($,{className:"w-full",onClick:()=>g(!0),children:"Send Referral"})]})]})]})]})]}),e.jsx(Os,{open:!!M,onOpenChange:()=>I(null),children:e.jsx(Rs,{className:"max-w-4xl",children:e.jsx("img",{src:M||"",alt:"Full size",className:"w-full h-auto"})})}),e.jsx(Os,{open:m,onOpenChange:p,children:e.jsxs(Rs,{children:[e.jsxs(Us,{children:[e.jsx(zs,{children:"Delete Listing"}),e.jsx(Sr,{children:"Are you sure you want to delete this listing? This action cannot be undone."})]}),e.jsxs(kr,{children:[e.jsx($,{variant:"outline",onClick:()=>p(!1),children:"Cancel"}),e.jsx($,{variant:"destructive",onClick:K,disabled:u.isPending,children:u.isPending?"Deleting...":"Delete"})]})]})}),e.jsx(Os,{open:x,onOpenChange:g,children:e.jsxs(Rs,{children:[e.jsxs(Us,{children:[e.jsx(zs,{children:"Send Buyer Referral"}),e.jsx(Sr,{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(se,{children:"Buyer Name *"}),e.jsx(be,{value:D.buyerName,onChange:Ee=>B({...D,buyerName:Ee.target.value}),placeholder:"Enter buyer's name"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Buyer Type"}),e.jsxs(vs,{value:D.buyerType,onValueChange:Ee=>B({...D,buyerType:Ee}),children:[e.jsx(gs,{children:e.jsx(bs,{placeholder:"Select type"})}),e.jsxs(ys,{children:[e.jsx(Ye,{value:"first_time",children:"First-Time Buyer"}),e.jsx(Ye,{value:"investor",children:"Investor"}),e.jsx(Ye,{value:"relocating",children:"Relocating"}),e.jsx(Ye,{value:"upgrade",children:"Upgrading"}),e.jsx(Ye,{value:"downsize",children:"Downsizing"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Notes"}),e.jsx(Is,{value:D.notes,onChange:Ee=>B({...D,notes:Ee.target.value}),placeholder:"Any additional information..."})]})]}),e.jsxs(kr,{children:[e.jsx($,{variant:"outline",onClick:()=>g(!1),children:"Cancel"}),e.jsx($,{onClick:Q,disabled:h.isPending,children:h.isPending?"Sending...":"Send Referral"})]})]})}),e.jsx(KLn,{open:T,onOpenChange:P,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(Bqt,{open:y,onOpenChange:b,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(tPn,{open:v,onOpenChange:N,listing:r}),e.jsx(rVt,{listingId:(r==null?void 0:r.id)||null,open:C,onOpenChange:A})]})}function gPn({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 v=N=>{m.current&&!m.current.contains(N.target)&&c(!1)};return document.addEventListener("mousedown",v),()=>document.removeEventListener("mousedown",v)},[]);const p=async v=>{if(v.trim().length<3){a([]),c(!1);return}l(!0);try{const{data:N,error:C}=await U.functions.invoke("mls-listing-search",{body:{query:v}});if(C)throw C;a((N==null?void 0:N.listings)||[]),c(!0)}catch(N){console.error("MLS search error:",N),a([])}finally{l(!1)}},x=v=>{n(v),h.current&&clearTimeout(h.current),h.current=setTimeout(()=>p(v),400)},g=v=>{u(v.mlsNumber),s(v),c(!1),n(`${v.address}, ${v.city}`),ae.success(`Imported: ${v.address}`,{description:"Property details and photos have been auto-filled."}),u(null)},y=v=>v?`$${v.toLocaleString()}`:"",b=v=>{const N=(v||"").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":v||"Other"};return e.jsxs(_e,{className:"border-primary/30 bg-primary/5",children:[e.jsxs(Bt,{className:"pb-3",children:[e.jsxs(Ut,{className:"text-base flex items-center gap-2",children:[e.jsx(di,{className:"h-4 w-4 text-primary"}),"Import from MLS"]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Search by address to auto-fill property details and photos from MLS"})]}),e.jsx(Oe,{children:e.jsxs("div",{ref:m,className:"relative",children:[e.jsxs("div",{className:"relative",children:[e.jsx(Vr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(be,{value:t,onChange:v=>x(v.target.value),onFocus:()=>r.length>0&&c(!0),placeholder:"Start typing a property address...",className:"pl-9 pr-9"}),i&&e.jsx(Ht,{className:"absolute right-3 top-1/2 -translate-y-1/2 h-4 w-4 animate-spin text-muted-foreground"}),t&&!i&&e.jsx("button",{type:"button",onClick:()=>{n(""),a([]),c(!1)},className:"absolute right-3 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground",children:e.jsx(pr,{className:"h-4 w-4"})})]}),o&&e.jsx("div",{className:"absolute z-50 w-full mt-1 bg-popover border rounded-lg shadow-lg max-h-[400px] overflow-y-auto",children:r.length===0&&!i?e.jsx("div",{className:"p-4 text-center text-sm text-muted-foreground",children:"No properties found. Try a different address."}):r.map(v=>e.jsxs("button",{type:"button",onClick:()=>g(v),disabled:d===v.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:[v.photos[0]?e.jsx("img",{src:v.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(ai,{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:v.address}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[v.city,", ",v.state," ",v.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(v.price)}),v.bedrooms>0&&e.jsxs("span",{className:"flex items-center gap-0.5",children:[e.jsx(tw,{className:"h-3 w-3"})," ",v.bedrooms]}),v.bathrooms>0&&e.jsxs("span",{className:"flex items-center gap-0.5",children:[e.jsx(_g,{className:"h-3 w-3"})," ",v.bathrooms]}),v.sqft>0&&e.jsxs("span",{className:"flex items-center gap-0.5",children:[e.jsx(o5,{className:"h-3 w-3"})," ",v.sqft.toLocaleString()]})]})]}),e.jsxs("div",{className:"flex-shrink-0 flex flex-col items-end gap-1",children:[e.jsx($e,{variant:"outline",className:"text-[10px]",children:b(v.propertyType)}),v.photos.length>0&&e.jsxs("span",{className:"text-[10px] text-muted-foreground",children:[v.photos.length," photos"]})]})]},v.mlsNumber))})]})})]})}function yPn({photo:s,isPrimary:t,onRemove:n,onSetPrimary:r}){const{attributes:a,listeners:i,setNodeRef:l,transform:o,transition:c,isDragging:d}=VAe({id:s.id}),u={transform:l6.Transform.toString(o),transition:c};return e.jsxs("div",{ref:l,style:u,className:Tt("relative aspect-square rounded-lg overflow-hidden bg-muted group",d&&"opacity-50 ring-2 ring-primary z-50"),children:[e.jsx("img",{src:s.photo_url,alt:"",className:"w-full h-full object-cover"}),e.jsx("button",{type:"button",...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($p,{className:"h-3.5 w-3.5"})}),e.jsx("button",{type:"button",onClick:()=>n(s.id),className:"absolute top-1 right-1 p-1 bg-destructive text-destructive-foreground rounded-full hover:bg-destructive/90 opacity-0 group-hover:opacity-100 transition-opacity",children:e.jsx(pr,{className:"h-3 w-3"})}),t?e.jsxs("span",{className:"absolute bottom-1 left-1 text-[10px] bg-primary text-primary-foreground px-1.5 py-0.5 rounded flex items-center gap-0.5",children:[e.jsx(Qa,{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 vPn({photos:s,uploading:t,onUpload:n,onRemove:r,onReorder:a,onSetPrimary:i}){var u,h;const l=DAe(pU(Vq,{activationConstraint:{distance:5}})),o=[...s].sort((m,p)=>(m.sort_order??0)-(p.sort_order??0)),c=((u=o.find(m=>m.is_primary))==null?void 0:u.id)??((h=o[0])==null?void 0:h.id),d=m=>{const{active:p,over:x}=m;if(!x||p.id===x.id)return;const g=o.findIndex(C=>C.id===p.id),y=o.findIndex(C=>C.id===x.id),b=[...o],[v]=b.splice(g,1);b.splice(y,0,v);const N=b.map((C,A)=>({...C,sort_order:A}));a(N)};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($Ae,{sensors:l,collisionDetection:RAe,onDragEnd:d,children:e.jsx(qAe,{items:o.map(m=>m.id),strategy:zee,children:e.jsxs("div",{className:"grid grid-cols-3 sm:grid-cols-4 gap-4",children:[o.map(m=>e.jsx(yPn,{photo:m,isPrimary:m.id===c,onRemove:r,onSetPrimary:i},m.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(Ht,{className:"h-8 w-8 animate-spin"}):e.jsxs(e.Fragment,{children:[e.jsx(si,{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:m=>n(m.target.files),disabled:t})]})]})})})]})}function bPn({selectedVideoId:s,onVideoSelect:t,listingId:n}){const r=Vn(),{user:a}=_s(),[i,l]=j.useState(!1),[o,c]=j.useState([]),[d,u]=j.useState(!1),[h,m]=j.useState(null),[p,x]=j.useState({});j.useEffect(()=>{s&&a?g():m(null)},[s,a]);const g=async()=>{if(!s)return;const{data:I,error:D}=await U.from("agent_videos").select("id, bunny_video_id, title, thumbnail_url, preview_url, playback_url, duration_seconds, status, created_at").eq("id",s).eq("is_deleted",!1).single();!D&&I&&(m(I),y(I))},y=async I=>{try{const{data:D,error:B}=await U.functions.invoke("bunny-upload",{body:{action:"asset-urls",videoId:I.bunny_video_id,isAgentVideo:!0}});!B&&(D!=null&&D.thumbnailUrl)&&x(q=>({...q,[I.id]:{thumbnailUrl:D.thumbnailUrl}}))}catch(D){console.warn("Failed to get signed URL",D)}},b=async()=>{if(a){u(!0);try{const{data:I,error:D}=await U.from("agent_videos").select("id, bunny_video_id, title, thumbnail_url, preview_url, playback_url, duration_seconds, status, created_at").eq("owner_user_id",a.id).eq("is_deleted",!1).eq("status","ready").order("created_at",{ascending:!1});if(D)throw D;c(I||[]),I!=null&&I.length&&v(I)}catch(I){console.error("Error fetching videos:",I),ae.error("Failed to load videos")}finally{u(!1)}}},v=async I=>{var D;try{const B=I.map(Q=>Q.bunny_video_id),{data:q,error:W}=await U.functions.invoke("bunny-upload",{body:{action:"bulk-asset-urls",videoIds:B,isAgentVideo:!0}});if(W)throw W;const V=(q==null?void 0:q.assets)||{},K={};for(const Q of I)(D=V[Q.bunny_video_id])!=null&&D.thumbnailUrl&&(K[Q.id]={thumbnailUrl:V[Q.bunny_video_id].thumbnailUrl});x(Q=>({...Q,...K}))}catch(B){console.warn("Failed to bulk-fetch signed URLs",B)}},N=()=>{l(!0),b()},C=I=>{t(I.id),m(I),l(!1),ae.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)}`)},P=I=>{if(!I)return"0:00";const D=Math.floor(I/60),B=I%60;return`${D}:${B.toString().padStart(2,"0")}`},M=I=>{var D;return((D=p[I.id])==null?void 0:D.thumbnailUrl)||I.thumbnail_url};return e.jsxs("div",{className:"space-y-3",children:[h?e.jsx(_e,{className:"overflow-hidden",children:e.jsx(Oe,{className:"p-0",children:e.jsxs("div",{className:"flex items-start gap-4 p-4",children:[e.jsxs("div",{className:"relative w-32 h-20 bg-muted rounded-lg overflow-hidden flex-shrink-0",children:[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(Xr,{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(Td,{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:P(h.duration_seconds)})]}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"font-medium text-sm truncate",children:h.title||"Untitled Video"}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"Property Video Tour"})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx($,{type:"button",variant:"outline",size:"sm",onClick:N,children:"Change"}),e.jsx($,{type:"button",variant:"ghost",size:"sm",onClick:A,className:"text-destructive hover:text-destructive",children:e.jsx(pr,{className:"h-4 w-4"})})]})]})})}):e.jsx(_e,{className:"border-dashed",children:e.jsx(Oe,{className:"p-6",children:e.jsxs("div",{className:"text-center",children:[e.jsx(Xr,{className:"h-10 w-10 mx-auto text-muted-foreground mb-3"}),e.jsx("p",{className:"text-sm text-muted-foreground mb-4",children:"Add a video walkthrough to showcase this property"}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-2 justify-center",children:[e.jsxs($,{type:"button",variant:"outline",onClick:N,className:"gap-2",children:[e.jsx(g1,{className:"h-4 w-4"}),"Select from Library"]}),e.jsxs($,{type:"button",variant:"outline",onClick:T,className:"gap-2",children:[e.jsx(y0,{className:"h-4 w-4"}),"Record New Video"]})]})]})})}),e.jsx(Os,{open:i,onOpenChange:l,children:e.jsxs(Rs,{className:"max-w-2xl max-h-[80vh] overflow-hidden flex flex-col",children:[e.jsx(Us,{children:e.jsxs(zs,{className:"flex items-center gap-2",children:[e.jsx(g1,{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(Ht,{className:"h-8 w-8 animate-spin text-muted-foreground"})}):o.length===0?e.jsxs("div",{className:"text-center py-12",children:[e.jsx(Xr,{className:"h-12 w-12 mx-auto text-muted-foreground mb-3"}),e.jsx("p",{className:"text-muted-foreground mb-4",children:"No videos in your library yet"}),e.jsxs($,{onClick:T,className:"gap-2",children:[e.jsx(y0,{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:()=>C(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(Xr,{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(Td,{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:P(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($,{type:"button",variant:"ghost",onClick:T,className:"gap-2",children:[e.jsx(y0,{className:"h-4 w-4"}),"Record New Video"]}),e.jsx($,{type:"button",variant:"outline",onClick:()=>l(!1),children:"Cancel"})]})]})})]})}const _Pn=s=>s<1024?`${s} B`:s<1024*1024?`${(s/1024).toFixed(0)} KB`:`${(s/(1024*1024)).toFixed(1)} MB`;function wPn({listingId:s}){const t=j.useRef(null),{data:n=[],isLoading:r}=Hqt(s),a=ILn(),i=DLn(),l=RLn(),o=async d=>{if(!(!d||d.length===0)){for(const u of Array.from(d)){if(u.size>25*1024*1024){ae.error(`${u.name} exceeds 25MB limit`);continue}try{await a.mutateAsync({listingId:s,file:u})}catch(h){ae.error(`Failed to upload ${u.name}: ${h.message}`)}}t.current&&(t.current.value=""),ae.success("Documents uploaded")}},c=async d=>{try{const u=await Gqt(d);window.open(u,"_blank")}catch{ae.error("Failed to open document")}};return e.jsxs("div",{className:"space-y-3",children:[e.jsx("input",{ref:t,type:"file",multiple:!0,accept:".pdf,application/pdf",className:"hidden",onChange:d=>o(d.target.files)}),e.jsxs($,{type:"button",variant:"outline",onClick:()=>{var d;return(d=t.current)==null?void 0:d.click()},disabled:a.isPending,className:"w-full",children:[a.isPending?e.jsx(Ht,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(si,{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(_e,{className:"p-3 flex items-center gap-3",children:[e.jsx("div",{className:"p-2 rounded-md bg-primary/10",children:e.jsx(Wr,{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:_Pn(d.file_size)})]}),e.jsxs("div",{className:"flex items-center gap-1 text-xs text-muted-foreground",children:[d.visible_on_exchange?e.jsx(ga,{className:"h-3 w-3"}):e.jsx(b0,{className:"h-3 w-3"}),e.jsx("span",{className:"hidden sm:inline",children:d.visible_on_exchange?"Visible":"Hidden"}),e.jsx(Tn,{checked:d.visible_on_exchange,onCheckedChange:u=>l.mutate({id:d.id,visible:u,listingId:s}),className:"ml-1"})]}),e.jsx($,{type:"button",variant:"ghost",size:"icon",onClick:()=>c(d.storage_path),children:e.jsx(di,{className:"h-4 w-4"})}),e.jsx($,{type:"button",variant:"ghost",size:"icon",onClick:async()=>{await Yi(`Delete ${d.file_name}?`)&&i.mutate({id:d.id,storage_path:d.storage_path,listingId:s})},children:e.jsx(pr,{className:"h-4 w-4 text-destructive"})})]},d.id))})]})}const jPn=[{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"}],NPn=[{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 kPn({id:s,url:t,index:n,onRemove:r}){const{attributes:a,listeners:i,setNodeRef:l,transform:o,transition:c,isDragging:d}=VAe({id:s}),u={transform:l6.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($p,{className:"h-3.5 w-3.5"})}),e.jsx("button",{type:"button",onClick:()=>r(n),className:"absolute top-1 right-1 p-1 bg-destructive text-destructive-foreground rounded-full hover:bg-destructive/90 opacity-0 group-hover:opacity-100 transition-opacity",children:e.jsx(pr,{className:"h-3 w-3"})}),n===0&&e.jsxs("span",{className:"absolute bottom-1 left-1 text-[10px] bg-primary text-primary-foreground px-1.5 py-0.5 rounded flex items-center gap-0.5",children:[e.jsx(Qa,{className:"h-2.5 w-2.5 fill-current"})," Primary"]})]})}function SPn({photoUrls:s,pendingPhotos:t,onRemove:n,onReorder:r,uploading:a,onUpload:i}){const l=DAe(pU(Vq,{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),x=[...s],g=[...t],[y]=x.splice(m,1),[b]=g.splice(m,1);x.splice(p,0,y),g.splice(p,0,b),r(x,g)};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($Ae,{sensors:l,collisionDetection:RAe,onDragEnd:c,children:e.jsx(qAe,{items:o,strategy:zee,children:e.jsxs("div",{className:"grid grid-cols-3 sm:grid-cols-4 gap-4",children:[s.map((d,u)=>e.jsx(kPn,{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(Ht,{className:"h-8 w-8 animate-spin"}):e.jsxs(e.Fragment,{children:[e.jsx(si,{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 vvt(){const{listingId:s}=Vi(),[t]=oc(),n=t.get("brokerage"),r=Vn(),{user:a}=_s(),{hasLeadSite:i}=Mf(),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}=mGe(l?s:""),x=RCs(),g=OCs(),y=FCs(),b=zCs(),v=BCs(),N=$Cs(),C=UCs(),{data:A=[]}=ht({queryKey:["brokerage-agents",n],queryFn:async()=>{if(!n)return[];const{data:fe,error:je}=await U.from("profiles").select("id, name, email").eq("brokerage_id",n).order("name");if(je)throw je;return fe||[]},enabled:o}),[T,P]=j.useState(""),[M,I]=j.useState(!1),[D,B]=j.useState([]),[q,W]=j.useState([]),[V,K]=j.useState(!1),Q=async fe=>{if(fe.size>5*1024*1024){ae.error("Image must be under 5MB");return}K(!0);try{const je=fe.name.split(".").pop()||"jpg",Ee=`${(a==null?void 0:a.id)||"anon"}/co-agents/${Date.now()}.${je}`,{error:Me}=await U.storage.from("listing-photos").upload(Ee,fe,{upsert:!0});if(Me)throw Me;const{data:De}=U.storage.from("listing-photos").getPublicUrl(Ee);ce(ze=>({...ze,co_agent_photo_url:De.publicUrl})),ae.success("Headshot uploaded")}catch(je){ae.error((je==null?void 0:je.message)||"Failed to upload headshot")}finally{K(!1)}},[J,ce]=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 fe,je,Ee,Me,De;m&&l&&ce({property_address:m.property_address||"",city:m.city||"",state:m.state||"",neighborhood:m.neighborhood||"",price:((fe=m.price)==null?void 0:fe.toString())||"",property_type:m.property_type,status:m.status,bedrooms:((je=m.bedrooms)==null?void 0:je.toString())||"",bathrooms:((Ee=m.bathrooms)==null?void 0:Ee.toString())||"",square_footage:((Me=m.square_footage)==null?void 0:Me.toString())||"",lot_size:m.lot_size||"",year_built:((De=m.year_built)==null?void 0:De.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=fe=>{var De,ze;const je={"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"},Ee=(fe.propertyType||"").toLowerCase(),Me=((De=Object.entries(je).find(([ke])=>Ee.includes(ke)))==null?void 0:De[1])||"other";ce(ke=>({...ke,property_address:fe.address||ke.property_address,city:fe.city||ke.city,state:fe.state||ke.state,price:fe.price?String(fe.price):ke.price,property_type:Me,bedrooms:fe.bedrooms?String(fe.bedrooms):ke.bedrooms,bathrooms:fe.bathrooms?String(fe.bathrooms):ke.bathrooms,square_footage:fe.sqft?String(fe.sqft):ke.square_footage,lot_size:fe.lotSize?String(fe.lotSize):ke.lot_size,year_built:fe.yearBuilt?String(fe.yearBuilt):ke.year_built,description:fe.description||ke.description})),((ze=fe.photos)==null?void 0:ze.length)>0&&(d(fe.photos),q.forEach(ke=>URL.revokeObjectURL(ke)),B([]),W([]))},ne=fe=>{if(!fe)return;const je=Array.from(fe);B(Me=>[...Me,...je]);const Ee=je.map(Me=>URL.createObjectURL(Me));W(Me=>[...Me,...Ee])},ee=fe=>{URL.revokeObjectURL(q[fe]),B(je=>je.filter((Ee,Me)=>Me!==fe)),W(je=>je.filter((Ee,Me)=>Me!==fe))},le=async fe=>{var je;if(!(!fe||!m)){I(!0);try{for(const Ee of Array.from(fe)){const Me=Ee.name.split(".").pop(),De=`${a==null?void 0:a.id}/${m.id}/${Date.now()}.${Me}`,{error:ze}=await U.storage.from("listing-photos").upload(De,Ee);if(ze)throw ze;const{data:{publicUrl:ke}}=U.storage.from("listing-photos").getPublicUrl(De);await b.mutateAsync({listingId:m.id,photoUrl:ke,isPrimary:!((je=m.photos)!=null&&je.length)})}ae.success("Photos uploaded!")}catch(Ee){console.error("Upload error:",Ee),ae.error("Failed to upload photos")}finally{I(!1)}}},he=async fe=>{for(let je=0;je{if(m)try{await v.mutateAsync({photoId:fe,listingId:m.id}),ae.success("Photo removed")}catch{ae.error("Failed to remove photo")}},ge=async fe=>{if(fe.preventDefault(),!J.city.trim()||!J.state.trim()||!J.price){ae.error("Please fill in required fields (City, State, Price)");return}if(o&&!T){ae.error("Please select an agent to assign this listing to");return}try{const je={property_address:J.property_address||null,city:J.city,state:J.state,neighborhood:J.neighborhood||null,price:Number(J.price),property_type:J.property_type,status:J.status,bedrooms:J.bedrooms?Number(J.bedrooms):null,bathrooms:J.bathrooms?Number(J.bathrooms):null,square_footage:J.square_footage?Number(J.square_footage):null,lot_size:J.lot_size||null,year_built:J.year_built?Number(J.year_built):null,has_hoa:J.has_hoa,description:J.description||null,agent_notes:J.agent_notes||null,agent_notes_public:J.agent_notes_public,mls_link:J.mls_link||null,video_link:J.video_link||null,video_id:J.video_id||null,co_agent_name:J.co_agent_name||null,co_agent_email:J.co_agent_email||null,co_agent_phone:J.co_agent_phone||null,co_agent_brokerage:J.co_agent_brokerage||null,co_agent_photo_url:J.co_agent_photo_url||null,allow_sharing:J.allow_sharing,open_to_referrals:J.open_to_referrals,open_to_social_promotion:J.open_to_social_promotion,share_with_brokerage:J.share_with_brokerage,is_public:J.site_only?!1:J.is_public,site_only:J.site_only,show_on_lead_site:J.site_only?!0:J.show_on_lead_site};if(l)await y.mutateAsync({id:s,...je}),ae.success("Listing updated!"),r(`/mission-control/listings/${s}`);else{I(!0);let Ee;if(o&&T?Ee=await g.mutateAsync({agentId:T,...je}):Ee=await x.mutateAsync(je),D.length>0)try{await he(Ee.id),q.forEach(De=>URL.revokeObjectURL(De)),B([]),W([])}catch(De){console.error("Photo upload error:",De),ae.error("Listing created but some photos failed to upload")}if(c.length>0)try{for(let De=0;Der(o?"/my-brokerage":"/mission-control/listings"),children:[e.jsx(ka,{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(_e,{children:[e.jsx(Bt,{children:e.jsx(Ut,{children:"Assign to Agent *"})}),e.jsxs(Oe,{children:[e.jsxs(vs,{value:T,onValueChange:P,children:[e.jsx(gs,{children:e.jsx(bs,{placeholder:"Select an agent..."})}),e.jsx(ys,{children:A.map(fe=>e.jsx(Ye,{value:fe.id,children:fe.name||fe.email},fe.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(gPn,{onImport:ue}),c.length>0&&e.jsxs(_e,{className:"border-primary/30 bg-primary/5",children:[e.jsxs(Bt,{className:"pb-3",children:[e.jsxs(Ut,{className:"text-base flex items-center gap-2",children:[e.jsx(di,{className:"h-4 w-4 text-primary"}),"MLS Photos (",c.length,")"]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"These photos will be imported when you save the listing."})]}),e.jsxs(Oe,{children:[e.jsxs("div",{className:"grid grid-cols-4 sm:grid-cols-6 gap-2",children:[c.slice(0,12).map((fe,je)=>e.jsx("div",{className:"aspect-square rounded overflow-hidden bg-muted",children:e.jsx("img",{src:fe,alt:"",className:"w-full h-full object-cover"})},je)),c.length>12&&e.jsxs("div",{className:"aspect-square rounded bg-muted flex items-center justify-center text-sm text-muted-foreground font-medium",children:["+",c.length-12]})]}),e.jsxs($,{type:"button",variant:"ghost",size:"sm",className:"mt-2 text-destructive",onClick:()=>d([]),children:[e.jsx(pr,{className:"h-3 w-3 mr-1"})," Clear MLS photos"]})]})]}),e.jsxs(_e,{children:[e.jsx(Bt,{children:e.jsx(Ut,{children:"Property Details"})}),e.jsx(Oe,{className:"space-y-4",children:e.jsxs("div",{className:"grid sm:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"sm:col-span-2 space-y-2",children:[e.jsx(se,{children:"Property Address"}),e.jsx(be,{value:J.property_address,onChange:fe=>ce({...J,property_address:fe.target.value}),placeholder:"123 Main St"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"City *"}),e.jsx(be,{value:J.city,onChange:fe=>ce({...J,city:fe.target.value}),placeholder:"City",required:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"State *"}),e.jsx(be,{value:J.state,onChange:fe=>ce({...J,state:fe.target.value}),placeholder:"State",required:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Neighborhood"}),e.jsx(be,{value:J.neighborhood,onChange:fe=>ce({...J,neighborhood:fe.target.value}),placeholder:"Neighborhood"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Price *"}),e.jsx(be,{type:"number",value:J.price,onChange:fe=>ce({...J,price:fe.target.value}),placeholder:"500000",required:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Property Type"}),e.jsxs(vs,{value:J.property_type,onValueChange:fe=>ce({...J,property_type:fe}),children:[e.jsx(gs,{children:e.jsx(bs,{})}),e.jsx(ys,{children:NPn.map(fe=>e.jsx(Ye,{value:fe.value,children:fe.label},fe.value))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Status"}),e.jsxs(vs,{value:J.status,onValueChange:fe=>ce({...J,status:fe}),children:[e.jsx(gs,{children:e.jsx(bs,{})}),e.jsx(ys,{children:jPn.map(fe=>e.jsx(Ye,{value:fe.value,children:fe.label},fe.value))})]})]})]})})]}),e.jsxs(_e,{children:[e.jsx(Bt,{children:e.jsx(Ut,{children:"Property Specs (Optional)"})}),e.jsx(Oe,{children:e.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-3 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Bedrooms"}),e.jsx(be,{type:"number",value:J.bedrooms,onChange:fe=>ce({...J,bedrooms:fe.target.value}),placeholder:"3"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Bathrooms"}),e.jsx(be,{type:"number",step:"0.5",value:J.bathrooms,onChange:fe=>ce({...J,bathrooms:fe.target.value}),placeholder:"2"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Sq Ft"}),e.jsx(be,{type:"number",value:J.square_footage,onChange:fe=>ce({...J,square_footage:fe.target.value}),placeholder:"2000"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Lot Size"}),e.jsx(be,{value:J.lot_size,onChange:fe=>ce({...J,lot_size:fe.target.value}),placeholder:"0.25 acres"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Year Built"}),e.jsx(be,{type:"number",value:J.year_built,onChange:fe=>ce({...J,year_built:fe.target.value}),placeholder:"2005"})]}),e.jsxs("div",{className:"flex items-center gap-2 pt-6",children:[e.jsx(Tn,{checked:J.has_hoa,onCheckedChange:fe=>ce({...J,has_hoa:fe})}),e.jsx(se,{children:"Has HOA"})]})]})})]}),e.jsxs(_e,{children:[e.jsx(Bt,{children:e.jsx(Ut,{children:"Description & Links"})}),e.jsxs(Oe,{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Description"}),e.jsx(Is,{value:J.description,onChange:fe=>ce({...J,description:fe.target.value}),placeholder:"Tell the story of this property...",rows:4})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Agent Notes"}),e.jsx(Is,{value:J.agent_notes,onChange:fe=>ce({...J,agent_notes:fe.target.value}),placeholder:"Notes for other agents...",rows:2}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Tn,{checked:J.agent_notes_public,onCheckedChange:fe=>ce({...J,agent_notes_public:fe})}),e.jsx(se,{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(se,{children:"MLS Link"}),e.jsx(be,{value:J.mls_link,onChange:fe=>ce({...J,mls_link:fe.target.value}),placeholder:"https://..."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Video Link"}),e.jsx(be,{value:J.video_link,onChange:fe=>ce({...J,video_link:fe.target.value}),placeholder:"YouTube or Vimeo URL"})]})]})]})]}),e.jsxs(_e,{children:[e.jsx(Bt,{children:e.jsx(Ut,{children:"Co-Listing Agent (optional)"})}),e.jsxs(Oe,{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(se,{children:"Name"}),e.jsx(be,{value:J.co_agent_name,onChange:fe=>ce({...J,co_agent_name:fe.target.value}),placeholder:"Jordan Ellis"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Brokerage"}),e.jsx(be,{value:J.co_agent_brokerage,onChange:fe=>ce({...J,co_agent_brokerage:fe.target.value}),placeholder:"Brokerage name"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Email"}),e.jsx(be,{type:"email",value:J.co_agent_email,onChange:fe=>ce({...J,co_agent_email:fe.target.value}),placeholder:"agent@email.com"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Phone"}),e.jsx(be,{value:J.co_agent_phone,onChange:fe=>ce({...J,co_agent_phone:fe.target.value}),placeholder:"(555) 123-4567"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Headshot"}),e.jsxs("div",{className:"flex items-center gap-4",children:[J.co_agent_photo_url?e.jsx("img",{src:J.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(si,{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:fe=>{var Ee;const je=(Ee=fe.target.files)==null?void 0:Ee[0];fe.target.value="",je&&Q(je)}}),e.jsx($,{type:"button",variant:"outline",disabled:V,onClick:()=>{var fe;return(fe=document.getElementById("co-agent-headshot"))==null?void 0:fe.click()},children:V?e.jsxs(e.Fragment,{children:[e.jsx(Ht,{className:"h-4 w-4 mr-2 animate-spin"})," Uploading…"]}):e.jsxs(e.Fragment,{children:[e.jsx(si,{className:"h-4 w-4 mr-2"})," ",J.co_agent_photo_url?"Replace photo":"Upload photo"]})}),J.co_agent_photo_url&&e.jsxs($,{type:"button",variant:"ghost",onClick:()=>ce(fe=>({...fe,co_agent_photo_url:""})),children:[e.jsx(pr,{className:"h-4 w-4 mr-1"})," Remove"]})]})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"JPG or PNG, up to 5MB."})]})]})]}),e.jsxs(_e,{children:[e.jsx(Bt,{children:e.jsxs(Ut,{className:"flex items-center gap-2",children:[e.jsx(Xr,{className:"h-5 w-5"}),"Property Video"]})}),e.jsx(Oe,{children:e.jsx(bPn,{selectedVideoId:J.video_id,onVideoSelect:fe=>ce({...J,video_id:fe}),listingId:l?s:void 0})})]}),e.jsxs(_e,{children:[e.jsx(Bt,{children:e.jsx(Ut,{children:"Photos"})}),e.jsx(Oe,{children:l&&(m!=null&&m.photos)?e.jsx(vPn,{photos:m.photos,uploading:M,onUpload:fe=>le(fe),onRemove:fe=>ve(fe),onReorder:fe=>{N.mutate({photos:fe.map(je=>({id:je.id,sort_order:je.sort_order,is_primary:je.is_primary}))})},onSetPrimary:fe=>{m&&C.mutate({photoId:fe,listingId:m.id})}}):e.jsx(SPn,{photoUrls:q,onRemove:ee,onReorder:(fe,je)=>{W(fe),B(je)},pendingPhotos:D,uploading:M,onUpload:ne})})]}),e.jsxs(_e,{children:[e.jsx(Bt,{children:e.jsxs(Ut,{className:"flex items-center gap-2",children:[e.jsx(di,{className:"h-5 w-5"}),"Documents & Disclosures"]})}),e.jsx(Oe,{children:l&&s?e.jsx(wPn,{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(_e,{children:[e.jsx(Bt,{children:e.jsx(Ut,{children:"Sharing & Collaboration"})}),e.jsxs(Oe,{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(se,{children:"Allow Sharing"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Other agents can share this listing"})]}),e.jsx(Tn,{checked:J.allow_sharing,onCheckedChange:fe=>ce({...J,allow_sharing:fe})})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(se,{children:"Open to Referrals"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Accept buyer referrals"})]}),e.jsx(Tn,{checked:J.open_to_referrals,onCheckedChange:fe=>ce({...J,open_to_referrals:fe})})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(se,{children:"Social Promotion"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Can be promoted on social media"})]}),e.jsx(Tn,{checked:J.open_to_social_promotion,onCheckedChange:fe=>ce({...J,open_to_social_promotion:fe})})]}),e.jsxs("div",{className:"flex items-center justify-between pt-2 border-t",children:[e.jsxs("div",{children:[e.jsx(se,{children:"Share with Brokerage"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Visible to agents in your brokerage"})]}),e.jsx(Tn,{checked:J.share_with_brokerage,onCheckedChange:fe=>ce({...J,share_with_brokerage:fe})})]}),i&&e.jsxs("div",{className:"flex items-center justify-between pt-2 border-t",children:[e.jsxs("div",{children:[e.jsx(se,{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(Tn,{checked:J.site_only,onCheckedChange:fe=>ce({...J,site_only:fe,is_public:fe?!1:J.is_public,show_on_lead_site:fe?!0:J.show_on_lead_site,share_with_brokerage:fe?!1:J.share_with_brokerage})})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(se,{children:"Make Public"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Publish on listings.relevelup.com to get leads"})]}),e.jsx(Tn,{checked:J.is_public,disabled:J.site_only,onCheckedChange:fe=>ce({...J,is_public:fe})})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(se,{children:"Show on My Website"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Feature this listing on your lead site homepage"})]}),e.jsx(Tn,{checked:J.show_on_lead_site,onCheckedChange:fe=>ce({...J,show_on_lead_site:fe})})]})]})]}),e.jsx($,{type:"submit",className:"w-full",size:"lg",disabled:x.isPending||y.isPending,children:x.isPending||y.isPending?e.jsxs(e.Fragment,{children:[e.jsx(Ht,{className:"h-4 w-4 mr-2 animate-spin"}),"Saving..."]}):l?"Update Listing":"Create Listing"})]})]})]}),e.jsx(rVt,{listingId:u.listingId,open:u.open,onOpenChange:fe=>{if(!fe){const{nextPath:je}=u;h({open:!1,listingId:null,nextPath:je}),r(je)}}})]})}const pUe=[{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"}],lVt=[{type:"extra_video",label:"Extra Video / Reel",icon:Xr,desc:"Add a YouTube, Vimeo, or MP4 embed",accent:"from-rose-500/20 to-rose-500/5"},{type:"tour_3d",label:"3D Tour",icon:gK,desc:"Matterport, iGuide, or Kuula embed",accent:"from-indigo-500/20 to-indigo-500/5"},{type:"floor_plans",label:"Floor Plans",icon:Jl,desc:"Upload floor plan images",accent:"from-sky-500/20 to-sky-500/5"},{type:"testimonial",label:"Testimonial",icon:RN,desc:"A quote from a past client",accent:"from-amber-500/20 to-amber-500/5"},{type:"countdown",label:"Offer Countdown",icon:Hr,desc:'"Offers due Friday 5pm"',accent:"from-emerald-500/20 to-emerald-500/5"},{type:"custom_cta",label:"Custom CTA Button",icon:kc,desc:"Link to a brochure or booking page",accent:"from-violet-500/20 to-violet-500/5"}],CPn=["#0f172a","#406E71","#c9a84c","#b91c1c","#0d7a5f","#4f46e5","#e85d3a","#111827"],xDe={sections:Object.fromEntries(pUe.map(s=>[s.key,!0])),hero_style:"photo",accent_color:null,custom_note:"",addons:[]},APn=()=>Math.random().toString(36).slice(2,10);function EPn(){const{listingId:s}=Vi(),t=Vn(),{user:n}=_s(),r=ts(),[a,i]=j.useState("desktop"),[l,o]=j.useState(xDe),[c,d]=j.useState(!1),[u,h]=j.useState(0),{data:m,isLoading:p}=ht({queryKey:["listing-customize",s],queryFn:async()=>{const{data:D,error:B}=await U.from("listings").select("id, agent_id, slug, property_address, city, state, price, page_config, page_theme").eq("id",s).single();if(B)throw B;return D},enabled:!!s});j.useEffect(()=>{var D,B;m!=null&&m.page_config&&o({...xDe,...m.page_config||{},sections:{...xDe.sections,...((D=m.page_config)==null?void 0:D.sections)||{}},addons:((B=m.page_config)==null?void 0:B.addons)||[]})},[m==null?void 0:m.id]);const x=!!n&&!!m&&n.id===m.agent_id,g=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]),b=yt({mutationFn:async()=>{const{error:D}=await U.from("listings").update({page_config:l}).eq("id",s);if(D)throw D},onSuccess:()=>{ae.success("Saved. Your public page is live."),d(!1),r.invalidateQueries({queryKey:["listing-customize",s]}),r.invalidateQueries({queryKey:["public-listing"]}),h(D=>D+1)},onError:D=>ae.error(`Save failed: ${D.message||"Try again"}`)}),v=D=>{o(B=>({...B,...D})),d(!0)},N=(D,B)=>v({sections:{...l.sections||{},[D]:B}}),C=D=>v({addons:[...l.addons||[],{id:APn(),type:D,data:{}}]}),A=(D,B)=>v({addons:(l.addons||[]).map(q=>q.id===D?{...q,data:{...q.data,...B}}:q)}),T=D=>v({addons:(l.addons||[]).filter(B=>B.id!==D)}),P=(D,B)=>{const q=[...l.addons||[]],W=q.findIndex(K=>K.id===D);if(W<0)return;const V=W+B;V<0||V>=q.length||([q[W],q[V]]=[q[V],q[W]],v({addons:q}))};if(p)return e.jsx(Ks,{title:"",description:"",children:e.jsx("div",{className:"p-8 text-sm text-muted-foreground",children:"Loading…"})});if(!m)return e.jsx(Ks,{title:"",description:"",children:e.jsx("div",{className:"p-8",children:"Listing not found."})});if(!x)return e.jsx(Ks,{title:"",description:"",children:e.jsxs("div",{className:"p-8",children:[e.jsx("p",{children:"You can only customize your own listing pages."}),e.jsx($,{className:"mt-3",onClick:()=>t(`/mission-control/listings/${m.id}`),children:"Back"})]})});const M=(l.addons||[]).length,I=Object.values(l.sections||{}).filter(Boolean).length;return e.jsxs(Ks,{title:"",description:"",children:[e.jsxs("div",{className:"sticky top-0 z-30 -mx-4 sm:-mx-6 px-4 sm:px-6 py-3 bg-background/85 backdrop-blur border-b flex items-center gap-3",children:[e.jsxs($,{variant:"ghost",size:"sm",onClick:()=>t(`/mission-control/listings/${m.id}`),children:[e.jsx(ka,{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(Hj,{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(dv,{className:"h-3.5 w-3.5"})," Mobile"]})]}),e.jsxs($,{variant:"outline",size:"sm",onClick:()=>h(D=>D+1),children:[e.jsx(Wi,{className:"h-3.5 w-3.5 mr-1.5"})," Refresh"]}),e.jsx($,{variant:"outline",size:"sm",asChild:!0,children:e.jsxs("a",{href:y,target:"_blank",rel:"noopener noreferrer",children:[e.jsx(Tr,{className:"h-3.5 w-3.5 mr-1.5"})," Open live"]})}),e.jsx($,{size:"sm",onClick:()=>b.mutate(),disabled:!c||b.isPending,children:b.isPending?"Saving…":e.jsxs(e.Fragment,{children:[e.jsx(Jo,{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(Oi,{className:"lg:h-[calc(100vh-140px)] pr-2",children:e.jsxs("div",{className:"space-y-6 pb-16",children:[e.jsx(OG,{icon:e.jsx(dn,{className:"h-4 w-4"}),title:"Hero",desc:"What visitors see first",children:e.jsxs("div",{children:[e.jsx(se,{className:"text-xs",children:"Hero style"}),e.jsx("div",{className:"mt-2 grid grid-cols-3 gap-2",children:["photo","video","slideshow"].map(D=>e.jsx("button",{onClick:()=>v({hero_style:D}),className:`text-xs rounded-lg border py-3 capitalize transition ${l.hero_style===D?"border-primary bg-primary/5 text-primary font-medium":"border-border hover:bg-muted"}`,children:D},D))})]})}),e.jsx(OG,{icon:e.jsx(Rc,{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:()=>v({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"}),CPn.map(D=>e.jsx("button",{onClick:()=>v({accent_color:D}),className:`h-9 w-9 rounded-full border-2 transition ${l.accent_color===D?"ring-2 ring-offset-2 ring-primary border-white":"border-white/20"}`,style:{background:D},"aria-label":D},D))]})}),e.jsx(OG,{icon:e.jsx(wm,{className:"h-4 w-4"}),title:"Personal note",desc:"Shows in a beautiful callout on the public page",children:e.jsx(Is,{value:l.custom_note||"",onChange:D=>v({custom_note:D.target.value}),placeholder:"Why we love this home… (optional)",rows:3})}),e.jsx(OG,{icon:e.jsx(Q4,{className:"h-4 w-4"}),title:"Page sections",desc:"Toggle any default section on or off",rightLabel:`${I} of ${pUe.length} on`,children:e.jsx("div",{className:"divide-y rounded-xl border",children:pUe.map(D=>{var q;const B=((q=l.sections)==null?void 0:q[D.key])!==!1;return e.jsxs("div",{className:"flex items-center justify-between p-3.5",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-sm font-medium",children:D.label}),e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:D.hint})]}),e.jsx(Tn,{checked:B,onCheckedChange:W=>N(D.key,W)})]},D.key)})})}),e.jsxs(OG,{icon:e.jsx(sn,{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:lVt.map(D=>e.jsxs("button",{onClick:()=>C(D.type),className:`group text-left rounded-xl border p-3 hover:shadow-md transition bg-gradient-to-br ${D.accent}`,children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx("div",{className:"h-7 w-7 rounded-md bg-background border flex items-center justify-center",children:e.jsx(D.icon,{className:"h-3.5 w-3.5"})}),e.jsx("span",{className:"text-sm font-medium",children:D.label})]}),e.jsx("p",{className:"text-[11px] text-muted-foreground leading-snug",children:D.desc})]},D.type))}),(l.addons||[]).length>0&&e.jsxs("div",{className:"mt-4 space-y-3",children:[e.jsx("p",{className:"text-[10px] uppercase tracking-widest text-muted-foreground",children:"On this page · drag to reorder"}),(l.addons||[]).map((D,B)=>e.jsx(TPn,{addon:D,onChange:q=>A(D.id,q),onRemove:()=>T(D.id),onMoveUp:B>0?()=>P(D.id,-1):void 0,onMoveDown:BP(D.id,1):void 0},D.id))]})]}),e.jsx("div",{className:"lg:hidden",children:e.jsx($,{className:"w-full",onClick:()=>b.mutate(),disabled:!c||b.isPending,children:b.isPending?"Saving…":e.jsxs(e.Fragment,{children:[e.jsx(Jo,{className:"h-4 w-4 mr-1.5"})," Save & Publish"]})})})]})}),e.jsx("div",{className:"lg:h-[calc(100vh-140px)]",children:e.jsxs(_e,{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(ga,{className:"h-3.5 w-3.5"}),"Live preview",c&&e.jsx($e,{variant:"outline",className:"text-[10px] border-amber-400 text-amber-700 bg-amber-50 ml-1",children:"Save to update"}),!c&&e.jsxs("span",{className:"inline-flex items-center gap-1 text-emerald-600 ml-1",children:[e.jsx(oa,{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(Hj,{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(dv,{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:g,title:"Preview",className:"w-full h-full border-0"},u)})})]})})]})]})}function OG({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 TPn({addon:s,onChange:t,onRemove:n,onMoveUp:r,onMoveDown:a}){const i=lVt.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($p,{className:"h-3.5 w-3.5"})})}),e.jsx("div",{className:"h-7 w-7 rounded-md bg-primary/10 text-primary flex items-center justify-center",children:e.jsx(l,{className:"h-3.5 w-3.5"})}),e.jsx("p",{className:"text-sm font-medium flex-1",children:i.label}),e.jsxs("div",{className:"flex items-center gap-1",children:[a&&e.jsx($,{size:"icon",variant:"ghost",className:"h-7 w-7",onClick:a,"aria-label":"Move down",children:e.jsx($p,{className:"h-3.5 w-3.5 rotate-180"})}),e.jsx($,{size:"icon",variant:"ghost",className:"h-7 w-7 text-destructive hover:text-destructive",onClick:n,"aria-label":"Remove",children:e.jsx(Pn,{className:"h-3.5 w-3.5"})})]})]}),s.type==="extra_video"&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{className:"text-xs",children:"Video URL"}),e.jsx(be,{placeholder:"https://youtu.be/…",value:s.data.url||"",onChange:o=>t({url:o.target.value})}),e.jsx(se,{className:"text-xs",children:"Title (optional)"}),e.jsx(be,{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(se,{className:"text-xs",children:"3D tour embed URL"}),e.jsx(be,{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(se,{className:"text-xs",children:"Floor plan image URLs (one per line)"}),e.jsx(Is,{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(se,{className:"text-xs",children:"Quote"}),e.jsx(Is,{rows:3,placeholder:`"Best home-buying experience we've ever had."`,value:s.data.quote||"",onChange:o=>t({quote:o.target.value})}),e.jsx(se,{className:"text-xs",children:"Attribution"}),e.jsx(be,{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(se,{className:"text-xs",children:"Headline"}),e.jsx(be,{placeholder:"Offers due",value:s.data.headline||"",onChange:o=>t({headline:o.target.value})}),e.jsx(se,{className:"text-xs",children:"Deadline (date & time)"}),e.jsx(be,{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(se,{className:"text-xs",children:"Button label"}),e.jsx(be,{placeholder:"Download brochure",value:s.data.label||"",onChange:o=>t({label:o.target.value})}),e.jsx(se,{className:"text-xs",children:"Link URL"}),e.jsx(be,{placeholder:"https://…",value:s.data.url||"",onChange:o=>t({url:o.target.value})})]})]})}const cVt="teleprompter_settings",gDe={scrollSpeed:30,fontSize:24,lineHeight:1.6,opacity:.85,position:"top",isMirrored:!1};function MPn(){try{const s=localStorage.getItem(cVt);return s?{...gDe,...JSON.parse(s)}:gDe}catch{return gDe}}function LPn(s){try{localStorage.setItem(cVt,JSON.stringify(s))}catch{}}function lXe({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(MPn),{scrollSpeed:p,fontSize:x,lineHeight:g,opacity:y,position:b,isMirrored:v}=h,N=j.useCallback((q,W)=>{m(V=>{const K={...V,[q]:W};return LPn(K),K})},[]),[C,A]=j.useState(!1),[T,P]=j.useState(null),M=j.useCallback(q=>{if(!o.current)return;d.current===0&&(d.current=q);const W=q-d.current;d.current=q,u.current+=p*W/1e3;const V=Math.floor(u.current);V>0&&(o.current.scrollTop+=V,u.current-=V);const{scrollTop:K,scrollHeight:Q,clientHeight:J}=o.current;if(K+J>=Q){A(!1);return}c.current=requestAnimationFrame(M)},[p]);j.useEffect(()=>(C?(d.current=0,u.current=0,c.current=requestAnimationFrame(M)):c.current&&cancelAnimationFrame(c.current),()=>{c.current&&cancelAnimationFrame(c.current)}),[C,M]),j.useEffect(()=>{if(r&&t)if(o.current&&(o.current.scrollTop=0),a){P(3);let q=3;const W=setInterval(()=>{q-=1,q<=0?(clearInterval(W),P(null),i==null||i(),A(!0)):P(q)},1e3);return()=>clearInterval(W)}else setTimeout(()=>A(!0),100);else r||(A(!1),P(null))},[r,t,a,i]);const I=j.useCallback(()=>{o.current&&(o.current.scrollTop=0),A(!1)},[]),D=j.useCallback(()=>{A(q=>!q)},[]);if(!t)return e.jsx("div",{className:Tt("absolute top-4 right-4 pointer-events-auto z-10",l),children:e.jsxs($,{variant:"secondary",size:"sm",onClick:n,className:"bg-black/50 hover:bg-black/70 text-white border-0",children:[e.jsx(ga,{className:"h-4 w-4 mr-2"}),"Show Script"]})});const B={top:"top-0 pt-16",center:"top-1/2 -translate-y-1/2",bottom:"bottom-0 pb-24"};return e.jsxs("div",{className:Tt("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:Tt("absolute left-0 right-0 h-[60%] overflow-hidden pointer-events-auto",B[b],T!==null&&"opacity-30"),style:{opacity:T!==null?.3:y},children:e.jsxs("div",{ref:o,className:Tt("mx-auto max-w-2xl px-6 overflow-y-auto scrollbar-hide h-full",v&&"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:`${x}px`,lineHeight:g,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(Sc,{children:[e.jsx(Cc,{asChild:!0,children:e.jsx($,{variant:"secondary",size:"icon",className:"h-9 w-9 bg-black/50 hover:bg-black/70 text-white border-0",children:e.jsx(pc,{className:"h-4 w-4"})})}),e.jsx(xc,{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(se,{className:"text-xs",children:"Scroll Speed"}),e.jsx("span",{className:"text-xs text-muted-foreground",children:p})]}),e.jsx(rx,{value:[p],onValueChange:([q])=>N("scrollSpeed",q),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(se,{className:"text-xs",children:"Font Size"}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:[x,"px"]})]}),e.jsx(rx,{value:[x],onValueChange:([q])=>N("fontSize",q),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(se,{className:"text-xs",children:"Line Spacing"}),e.jsx("span",{className:"text-xs text-muted-foreground",children:g.toFixed(1)})]}),e.jsx(rx,{value:[g*10],onValueChange:([q])=>N("lineHeight",q/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(se,{className:"text-xs",children:"Opacity"}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:[Math.round(y*100),"%"]})]}),e.jsx(rx,{value:[y*100],onValueChange:([q])=>N("opacity",q/100),min:30,max:100,step:5})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{className:"text-xs",children:"Position"}),e.jsxs("div",{className:"flex gap-1",children:[e.jsx($,{variant:b==="top"?"default":"outline",size:"sm",onClick:()=>N("position","top"),children:e.jsx(jg,{className:"h-4 w-4"})}),e.jsx($,{variant:b==="center"?"default":"outline",size:"sm",onClick:()=>N("position","center"),children:e.jsx(DN,{className:"h-4 w-4"})}),e.jsx($,{variant:b==="bottom"?"default":"outline",size:"sm",onClick:()=>N("position","bottom"),children:e.jsx(_o,{className:"h-4 w-4"})})]})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(se,{className:"text-xs",children:"Mirror Mode"}),e.jsx(Tn,{checked:v,onCheckedChange:q=>N("isMirrored",q)})]})]})})]}),e.jsx($,{variant:"secondary",size:"icon",onClick:D,className:"h-9 w-9 bg-black/50 hover:bg-black/70 text-white border-0",children:C?e.jsx(vy,{className:"h-4 w-4"}):e.jsx(Td,{className:"h-4 w-4"})}),e.jsx($,{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(Ih,{className:"h-4 w-4"})}),e.jsxs($,{variant:"secondary",size:"sm",onClick:n,className:"bg-black/50 hover:bg-black/70 text-white border-0",children:[e.jsx(b0,{className:"h-4 w-4 mr-2"}),"Hide"]})]})]})}function PPn({onSelectScript:s,onCreateNew:t,selectedScriptId:n,className:r}){const{toast:a}=gi(),[i,l]=j.useState(""),[o,c]=j.useState(null),[d,u]=j.useState("levelup"),{data:h,isLoading:m}=KNn(),{data:p,isLoading:x}=YNn(),{data:g,isLoading:y}=ZNn(),b=XNn(),v=j.useMemo(()=>p?p.filter(P=>{const M=!i||P.title.toLowerCase().includes(i.toLowerCase())||P.script_text.toLowerCase().includes(i.toLowerCase())||P.tags.some(D=>D.toLowerCase().includes(i.toLowerCase())),I=!o||P.category_id===o;return M&&I}):[],[p,i,o]),N=j.useMemo(()=>g?g.filter(P=>!i||P.title.toLowerCase().includes(i.toLowerCase())||P.script_text.toLowerCase().includes(i.toLowerCase())):[],[g,i]),C=P=>{s({title:P.title,text:P.script_text})},A=async P=>{try{await b.mutateAsync(P),a({title:"Script saved to My Scripts"})}catch{a({title:"Failed to save script",variant:"destructive"})}},T=m||x||y;return e.jsxs("div",{className:Tt("flex flex-col h-full",r),children:[e.jsx("div",{className:"p-4 border-b",children:e.jsxs("div",{className:"relative",children:[e.jsx(Vr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(be,{placeholder:"Search scripts...",value:i,onChange:P=>l(P.target.value),className:"pl-9"})]})}),e.jsxs(ua,{value:d,onValueChange:P=>u(P),className:"flex-1 flex flex-col",children:[e.jsxs(ha,{className:"mx-4 mt-4 grid grid-cols-2",children:[e.jsxs(Qt,{value:"levelup",children:[e.jsx(Wr,{className:"h-4 w-4 mr-2"}),"LevelUp Scripts"]}),e.jsxs(Qt,{value:"my-scripts",children:[e.jsx(wg,{className:"h-4 w-4 mr-2"}),"My Scripts"]})]}),e.jsxs(Jt,{value:"levelup",className:"flex-1 flex flex-col mt-0 p-4",children:[e.jsxs("div",{className:"flex flex-wrap gap-2 mb-4",children:[e.jsx($e,{variant:o?"outline":"default",className:"cursor-pointer",onClick:()=>c(null),children:"All"}),h==null?void 0:h.map(P=>e.jsx($e,{variant:o===P.id?"default":"outline",className:"cursor-pointer",onClick:()=>c(P.id),children:P.name},P.id))]}),e.jsx(Oi,{className:"flex-1 max-h-[50vh]",children:T?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx(Ht,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):v.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-2 opacity-50"}),e.jsx("p",{children:"No scripts found"})]}):e.jsx("div",{className:"space-y-2",children:v.map(P=>e.jsxs(_e,{className:Tt("cursor-pointer hover:bg-accent/50 transition-colors",n===P.id&&"ring-2 ring-primary"),onClick:()=>C(P),children:[e.jsx(Bt,{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(Ut,{className:"text-sm font-medium truncate",children:P.title}),P.category&&e.jsx($e,{variant:"secondary",className:"mt-1 text-xs",children:P.category.name})]}),e.jsxs("div",{className:"flex items-center gap-1 ml-2",children:[e.jsx($,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:M=>{M.stopPropagation(),A(P)},children:e.jsx(wg,{className:"h-4 w-4"})}),e.jsx(Ja,{className:"h-4 w-4 text-muted-foreground"})]})]})}),e.jsx(Oe,{className:"p-3 pt-0",children:e.jsx("p",{className:"text-xs text-muted-foreground line-clamp-2",children:P.script_text})})]},P.id))})})]}),e.jsxs(Jt,{value:"my-scripts",className:"flex-1 flex flex-col mt-0 p-4",children:[t&&e.jsxs($,{variant:"outline",className:"mb-4",onClick:t,children:[e.jsx(sn,{className:"h-4 w-4 mr-2"}),"Create New Script"]}),e.jsx(Oi,{className:"flex-1 max-h-[50vh]",children:y?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx(Ht,{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(wg,{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(P=>e.jsxs(_e,{className:Tt("cursor-pointer hover:bg-accent/50 transition-colors",n===P.id&&"ring-2 ring-primary"),onClick:()=>C(P),children:[e.jsx(Bt,{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(Ut,{className:"text-sm font-medium truncate",children:P.title}),e.jsx("div",{className:"flex items-center gap-2 mt-1",children:P.is_custom?e.jsx($e,{variant:"outline",className:"text-xs",children:"Custom"}):e.jsx($e,{variant:"secondary",className:"text-xs",children:"Saved"})})]}),e.jsx(Ja,{className:"h-4 w-4 text-muted-foreground ml-2"})]})}),e.jsx(Oe,{className:"p-3 pt-0",children:e.jsx("p",{className:"text-xs text-muted-foreground line-clamp-2",children:P.script_text})})]},P.id))})})]})]})]})}function IPn({selectedTemplate:s,onSelect:t,contactName:n,saving:r=!1}){const[a,i]=j.useState(()=>{const o=sB(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(se,{className:"text-sm font-medium",children:"Share Page Template"}),r&&e.jsx(Ht,{className:"h-3 w-3 animate-spin text-muted-foreground"})]}),e.jsx("div",{className:"space-y-3",children:_3s.map(o=>{const c=w3s(o.id),d=a.has(o.id),u=c.some(h=>h.id===s);return e.jsxs(uv,{open:d,onOpenChange:()=>l(o.id),children:[e.jsxs(hv,{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(_o,{className:Tt("h-4 w-4 text-muted-foreground transition-transform",d&&"rotate-180")})]}),e.jsx(mv,{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:Tt("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(oa,{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: "',sB(s).headerText(n),'"']})]})}function dVt({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,x]=j.useState([]),[g,y]=j.useState(n.contact_id&&r?{id:n.contact_id,name:r,email:null}:null),[b,v]=j.useState(!1),[N,C]=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()=>{C(!0);try{const{data:K,error:Q}=await U.from("innercircle_contacts").select("id, first_name, last_name, email").order("first_name",{ascending:!0}).limit(500);if(Q)throw Q;const J=(K||[]).map(ce=>({id:ce.id,name:[ce.first_name,ce.last_name].filter(Boolean).join(" ")||"Unnamed",email:ce.email||null}));x(J)}catch(K){console.error("Failed to fetch contacts:",K)}finally{C(!1)}},P=async K=>{y(K),v(!1),c(!0);try{const{error:Q}=await U.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(Q)throw Q;ae.success(K?`Assigned to ${K.name}`:"Contact removed"),a==null||a()}catch(Q){console.error("Failed to update contact:",Q),ae.error("Failed to update contact")}finally{c(!1)}},M=async K=>{l(K),c(!0);try{const{error:Q}=await U.from("agent_videos").update({page_template:K}).eq("id",n.id);if(Q)throw Q;m(K),ae.success("Template saved!"),a==null||a()}catch(Q){console.error("Failed to save template:",Q),ae.error("Failed to save template"),l(h)}finally{c(!1)}},I=(g==null?void 0:g.name)||null,D=()=>{const K=n.title||"Video Message",Q=n.share_token?`https://video.relevelup.com/thumb/${n.share_token}`:n.thumbnail_url||"";return``},B=async()=>{if(!n.thumbnail_url){ae.error("Video thumbnail not available yet");return}const K=D(),Q=`Watch: ${n.title||"Video Message"} ${A}`;try{const J=new Blob([K],{type:"text/html"}),ce=new Blob([Q],{type:"text/plain"}),ue=new ClipboardItem({"text/html":J,"text/plain":ce});await navigator.clipboard.write([ue]),ae.success("Copied! Paste into Gmail - the thumbnail will appear after sending.")}catch{await navigator.clipboard.writeText(Q+` `+K),ae.success("Copied! Paste into your email.")}},q=async()=>{await navigator.clipboard.writeText(A),u(!0),ae.success("Share link copied!"),setTimeout(()=>u(!1),2e3)},W=()=>{const Q=sB(i).headerText(I),J=i==="default"?`Check out this video: ${A}`:`${Q} Check out this special video: ${A}`;window.open(`sms:?body=${encodeURIComponent(J)}`,"_self")},V=()=>{const K=sB(i),Q=K.headerText(I),J=i==="default"?n.title||"Video Message":Q,ce=`${K.subText} Watch the video: ${A}`,ue=g!=null&&g.email?encodeURIComponent(g.email):"";window.open(`mailto:${ue}?subject=${encodeURIComponent(J)}&body=${encodeURIComponent(ce)}`,"_self")};return e.jsx(Os,{open:s,onOpenChange:t,children:e.jsxs(Rs,{className:"max-w-lg max-h-[90vh] overflow-y-auto",children:[e.jsxs(Us,{children:[e.jsxs(zs,{className:"flex items-center gap-2",children:[e.jsx(kc,{className:"h-5 w-5"}),"Share Video"]}),e.jsx(Sr,{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(se,{className:"text-sm font-medium",children:"Personalize for Contact (Optional)"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(Sc,{open:b,onOpenChange:v,children:[e.jsx(Cc,{asChild:!0,children:e.jsxs($,{variant:"outline",role:"combobox","aria-expanded":b,className:"flex-1 justify-between",disabled:o,children:[g?e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(Lo,{className:"h-4 w-4 text-muted-foreground"}),g.name]}):e.jsx("span",{className:"text-muted-foreground",children:"Select a contact..."}),e.jsx(sw,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(xc,{className:"w-[300px] p-0",align:"start",children:e.jsxs(pw,{children:[e.jsx(fw,{placeholder:"Search contacts..."}),e.jsxs(xw,{children:[e.jsx(gw,{children:N?"Loading...":"No contacts found."}),e.jsx($b,{children:p.map(K=>e.jsxs(iv,{value:K.name,onSelect:()=>P(K),children:[e.jsx(oa,{className:Tt("mr-2 h-4 w-4",(g==null?void 0:g.id)===K.id?"opacity-100":"opacity-0")}),K.name]},K.id))})]})]})})]}),g&&e.jsx($,{variant:"ghost",size:"icon",onClick:()=>P(null),disabled:o,className:"shrink-0",children:e.jsx(pr,{className:"h-4 w-4"})})]}),g&&i!=="default"&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:['Page will show: "',sB(i).headerText(g.name),'"']})]}),e.jsx(IPn,{selectedTemplate:i,onSelect:M,contactName:I,saving:o}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Share Link"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(be,{value:A,readOnly:!0,className:"font-mono text-sm"}),e.jsx($,{onClick:q,variant:d?"default":"outline",className:"shrink-0 gap-2",children:d?e.jsxs(e.Fragment,{children:[e.jsx(oa,{className:"h-4 w-4"}),"Copied"]}):e.jsxs(e.Fragment,{children:[e.jsx(Ca,{className:"h-4 w-4"}),"Copy"]})})]})]}),n.thumbnail_url&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Share for Email"}),e.jsxs($,{variant:"outline",className:"w-full gap-2",onClick:B,children:[e.jsx(Jl,{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(se,{children:"Quick Share"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs($,{variant:"outline",className:"flex-1 gap-2",onClick:W,children:[e.jsx(Ji,{className:"h-4 w-4"}),"Text"]}),e.jsxs($,{variant:"outline",className:"flex-1 gap-2",onClick:V,children:[e.jsx(nn,{className:"h-4 w-4"}),"Email"]})]})]})]}),e.jsx(kr,{children:e.jsx($,{variant:"outline",onClick:()=>t(!1),children:"Done"})})]})})}function DPn(){var qe;const s=Vn(),[t]=oc(),{toast:n}=gi(),r=t.get("contact_id"),a=t.get("task_id"),{canRecord:i,remainingMb:l,usagePercent:o,isNearLimit:c,storage:d}=I7t(),{data:u}=M1(),h=F5(),m=skn(),[p,x]=j.useState("record"),[g,y]=j.useState(""),[b,v]=j.useState(!1),[N,C]=j.useState(!1),[A,T]=j.useState(!1),[P,M]=j.useState(null),[I,D]=j.useState(0),[B,q]=j.useState(0),[W,V]=j.useState(null),[K,Q]=j.useState(null),[J,ce]=j.useState(r||""),[ue,ne]=j.useState(""),[ee,le]=j.useState(""),[he,ve]=j.useState(null),[ge,fe]=j.useState(null),[je,Ee]=j.useState(null),[Me,De]=j.useState(!1),ze=j.useCallback(async(Ke,Ze)=>{M(Ke),x("uploading");try{const{videoId:Ue,uploadUrl:et}=await Z6(ue||"Quick Video Touch");V(Ue);const{apiKey:Qe}=await X6(Ue),Ge=new XMLHttpRequest;Ge.upload.onprogress=Mt=>{Mt.lengthComputable&&D(Mt.loaded/Mt.total*100)},await new Promise((Mt,Ft)=>{Ge.onload=()=>{Ge.status>=200&&Ge.status<300?Mt():Ft(new Error(`Upload failed: ${Ge.status}`))},Ge.onerror=()=>Ft(new Error("Upload failed")),Ge.open("PUT",et),Ge.setRequestHeader("AccessKey",Qe),Ge.send(Ke)}),x("processing");let nt=0;const ft=Date.now(),lt=90*1e3;for(;nt<4;){if(await new Promise(Ft=>setTimeout(Ft,3e3)),Date.now()-ft>lt){const Ft=Ke.size/1048576,Ts=`https://iframe.mediadelivery.net/play/${Ue}/${Ue}`;await h.mutateAsync({bunny_video_id:Ue,playback_url:Ts,file_size_mb:Ft,title:ue||"Quick Video Touch",notes:ee||void 0,contact_id:J&&J!=="none"?J: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 Mt=await o2(Ue);if(nt=Mt.status,q(Mt.encodeProgress||0),nt===4)Q({playbackUrl:Mt.directPlayUrl,thumbnailUrl:Mt.thumbnailUrl,previewUrl:Mt.previewUrl||null,duration:Mt.length||Ze,fileSizeMb:(Mt.storageSize||Ke.size)/(1024*1024)});else if(nt===5||nt===6)throw new Error("Video processing failed")}x("details")}catch(Ue){console.error("Upload error:",Ue),n({title:"Upload failed",description:"Please try recording again.",variant:"destructive"}),x("record")}},[ue,n]),ke=async()=>{if(!(!W||!K))try{const Ke=J&&J!=="none"?J:null,Ze=await h.mutateAsync({bunny_video_id:W,contact_id:Ke,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:ee,task_id:a||null,status:"ready"});ve(Ze.id),fe(Ze.share_token||null),Ke&&await m.mutateAsync({contactId:Ke,videoId:Ze.id,notes:ee}),n({title:"Video saved successfully!"}),x("share")}catch(Ke){console.error("Save video error:",Ke),n({title:"Failed to save video",description:(Ke==null?void 0:Ke.message)||"Please try again.",variant:"destructive"})}},Xe=(Ke,Ze)=>{navigator.clipboard.writeText(Ze),Ee(Ke),setTimeout(()=>Ee(null),2e3),n({title:"Copied to clipboard!"})},Se=()=>ge?`https://video.relevelup.com/${ge}`:(K==null?void 0:K.playbackUrl)||"",Re=()=>{const Ke=u==null?void 0:u.find(Ge=>Ge.id===J),Ze=Ke?`${Ke.first_name}`:"",Ue=(Ke==null?void 0:Ke.phone)||"",et=(Ke==null?void 0:Ke.email)||"",Qe=Se();return{text:`Hey${Ze?` ${Ze}`:""}! I recorded a quick video for you: ${Qe}`,link:Qe,contactPhone:Ue,contactEmail:et}},Ae=()=>{const{text:Ke,contactPhone:Ze}=Re(),Ue=Ze?`sms:${Ze}?body=${encodeURIComponent(Ke)}`:`sms:?body=${encodeURIComponent(Ke)}`;window.open(Ue,"_self")},Be=()=>{const{link:Ke,contactEmail:Ze}=Re(),Ue="Check out this video",et=`I recorded a quick video for you: ${Ke}`,Qe=Ze?`mailto:${Ze}?subject=${encodeURIComponent(Ue)}&body=${encodeURIComponent(et)}`:`mailto:?subject=${encodeURIComponent(Ue)}&body=${encodeURIComponent(et)}`;window.open(Qe,"_self")};return i?e.jsx(Ks,{title:"QuickVid",children:e.jsxs("div",{className:"max-w-4xl mx-auto space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx($,{variant:"ghost",size:"icon",onClick:()=>s(-1),children:e.jsx(ka,{className:"h-5 w-5"})}),e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold",children:"QuickVid"}),e.jsx("p",{className:"text-muted-foreground",children:"Record a personal video message"})]})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs($,{variant:"outline",size:"sm",onClick:()=>s("/mission-control/video-library"),className:"gap-1.5",children:[e.jsx(Wr,{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(J6,{maxDurationSeconds:600,onRecordingComplete:ze,onRecordingStateChange:T,className:"w-full",teleprompterContent:b&&g&&e.jsx(lXe,{text:g,isVisible:b,onToggleVisibility:()=>v(!1),isRecording:A,startCountdown:!1})}),!b&&g&&e.jsxs($,{variant:"outline",className:"mt-4",onClick:()=>v(!0),children:[e.jsx(Wr,{className:"h-4 w-4 mr-2"}),"Show Teleprompter"]})]}),e.jsxs(_e,{className:"lg:col-span-1",children:[e.jsx(Bt,{className:"pb-2",children:e.jsx(Ut,{className:"text-lg",children:"Teleprompter Script"})}),e.jsxs(Oe,{className:"space-y-4",children:[e.jsx(Is,{placeholder:"Type or paste your script here...",value:g,onChange:Ke=>y(Ke.target.value),rows:6}),e.jsxs(Ub,{open:N,onOpenChange:C,children:[e.jsx(cee,{asChild:!0,children:e.jsxs($,{variant:"outline",className:"w-full",children:[e.jsx(Wr,{className:"h-4 w-4 mr-2"}),"Browse Scripts"]})}),e.jsxs(T1,{side:"right",className:"w-[400px] sm:w-[540px] p-0",children:[e.jsx(kw,{className:"p-4 border-b",children:e.jsx(Sw,{children:"Select a Script"})}),e.jsx(PPn,{onSelectScript:Ke=>{y(Ke.text),C(!1),v(!0)},className:"h-[calc(100vh-80px)]"})]})]}),g&&e.jsx($,{className:"w-full",onClick:()=>v(!0),children:"Use Script"})]})]})]}),p==="uploading"&&e.jsx(_e,{className:"max-w-md mx-auto",children:e.jsxs(Oe,{className:"pt-6 text-center",children:[e.jsx(si,{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(Ki,{value:I,className:"mb-2"}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[I.toFixed(0),"%"]})]})}),p==="processing"&&e.jsx(_e,{className:"max-w-md mx-auto",children:e.jsxs(Oe,{className:"pt-6 text-center space-y-4",children:[e.jsx(Ht,{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(Ki,{value:B,className:"mb-2"}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[B.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(_e,{className:"max-w-lg mx-auto",children:[e.jsx(Bt,{children:e.jsx(Ut,{children:"Video Details"})}),e.jsxs(Oe,{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(se,{children:"Title"}),e.jsx(be,{value:ue,onChange:Ke=>ne(Ke.target.value),placeholder:"Quick Video Touch"})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Attach to Contact (Optional)"}),e.jsxs(vs,{value:J,onValueChange:ce,children:[e.jsx(gs,{children:e.jsx(bs,{placeholder:"No contact - use anywhere"})}),e.jsxs(ys,{children:[e.jsx(Ye,{value:"none",children:e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground",children:[e.jsx(kc,{className:"h-4 w-4"}),"No contact - use anywhere"]})}),u==null?void 0:u.map(Ke=>e.jsx(Ye,{value:Ke.id,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Lo,{className:"h-4 w-4"}),Ke.first_name," ",Ke.last_name]})},Ke.id))]})]})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Notes"}),e.jsx(Is,{value:ee,onChange:Ke=>le(Ke.target.value),placeholder:"Add notes about this video...",rows:3})]}),e.jsxs($,{className:"w-full",onClick:ke,disabled:h.isPending,children:[h.isPending&&e.jsx(Ht,{className:"h-4 w-4 mr-2 animate-spin"}),"Save Video"]})]})]}),p==="share"&&e.jsxs(_e,{className:"max-w-lg mx-auto",children:[e.jsx(Bt,{children:e.jsxs(Ut,{className:"flex items-center gap-2",children:[e.jsx(oa,{className:"h-5 w-5 text-green-500"}),"Video Saved!"]})}),e.jsxs(Oe,{className:"space-y-4",children:[e.jsx("p",{className:"text-muted-foreground",children:"Share your video with one click:"}),e.jsxs("div",{className:"grid gap-3",children:[e.jsxs($,{variant:"outline",className:"justify-start",onClick:Ae,children:[e.jsx(Ji,{className:"h-4 w-4 mr-2"}),"Text Contact Video"]}),e.jsxs($,{variant:"outline",className:"justify-start",onClick:Be,children:[e.jsx(nn,{className:"h-4 w-4 mr-2"}),"Email Contact Video"]}),e.jsxs($,{variant:"outline",className:"justify-start",onClick:()=>Xe("link",Re().link),children:[e.jsx(kc,{className:"h-4 w-4 mr-2"}),"Copy Video Link",je==="link"&&e.jsx(oa,{className:"h-4 w-4 ml-auto text-green-500"})]}),e.jsxs($,{variant:"outline",className:"justify-start",onClick:()=>De(!0),children:[e.jsx(Rc,{className:"h-4 w-4 mr-2"}),"Send with Page Template"]})]}),e.jsxs("div",{className:"flex gap-3 pt-4",children:[e.jsx($,{variant:"outline",onClick:()=>s("/mission-control/video-library"),children:"View Library"}),e.jsx($,{onClick:()=>{x("record"),M(null),V(null),Q(null)},children:"Record Another"})]})]})]}),he&&ge&&e.jsx(dVt,{open:Me,onOpenChange:De,video:{id:he,share_token:ge,title:ue||null,contact_id:J||null,thumbnail_url:(K==null?void 0:K.thumbnailUrl)||null},contactName:((qe=u==null?void 0:u.find(Ke=>Ke.id===J))==null?void 0:qe.first_name)||null})]})}):e.jsx(Ks,{title:"QuickVid",children:e.jsxs("div",{className:"max-w-2xl mx-auto text-center py-12",children:[e.jsx(mc,{className:"h-16 w-16 text-destructive mx-auto mb-4"}),e.jsx("h1",{className:"text-2xl font-bold mb-2",children:"Storage Limit Reached"}),e.jsx("p",{className:"text-muted-foreground mb-6",children:"You've reached your video storage limit. Delete videos from your library to record more."}),e.jsx($,{onClick:()=>s("/mission-control/video-library"),children:"Open Video Library"})]})})}function RPn({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),[x,g]=j.useState(""),[y,b]=j.useState(""),[v,N]=j.useState(""),[C,A]=j.useState(!1),T=E7t(),P=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&&D()},[s]),j.useEffect(()=>{if(s&&(b(`I recorded a video for you — ${I}`),N("Hey! I recorded a quick video just for you. Click below to watch it:"),d(null),g(""),n.contact_id)){const Q=l.find(J=>J.id===n.contact_id);Q&&(d(Q),g(Q.email||""))}},[s,n.contact_id,l]);const D=async()=>{p(!0);try{const{data:Q,error:J}=await U.from("innercircle_contacts").select("id, first_name, last_name, email").order("first_name",{ascending:!0}).limit(500);if(J)throw J;o(Q||[])}catch{console.error("Failed to fetch contacts")}finally{p(!1)}},B=Q=>{d(Q),h(!1),g(Q.email||""),N(`Hey ${Q.first_name}! I recorded a quick video just for you. Click below to watch it:`),b(`I recorded a video for you — ${I}`)},q=()=>{d(null),g(""),N("Hey! I recorded a quick video just for you. Click below to watch it:")},W=Q=>{const J=`${Q.first_name||""} ${Q.last_name||""}`.replace(/<[^>]*>/g," ").replace(/\s+/g," ").trim();return J?J.length>60?`${J.slice(0,60)}…`:J:Q.email||"Unnamed contact"},V=Q=>{const J=v.split(/\n\n+/).map(ne=>`

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

`).join(""),ce=Q?M7t(Q):P,ue=Q?``:"";return`
${J}

▶ Watch Video

${ue}
`},K=async()=>{var Q;if(!x){ae.error("Please enter a recipient email");return}if(!P){ae.error("Video does not have a share link");return}A(!0);try{let J;try{const le=c?W(c):x.split("@")[0];J=(await T.mutateAsync({video_id:n.id,recipient_email:x,recipient_name:le,contact_id:(c==null?void 0:c.id)||null,sent_via:"gmail"})).share_token}catch(le){console.warn("Failed to create tracking record, sending without tracking:",le)}const ce=V(J),{data:ue,error:ne}=await U.functions.invoke("gmail-send",{body:{to:x,subject:y,body:ce,contactId:(c==null?void 0:c.id)||null}});let ee=null;if(ne&&((Q=ne.context)!=null&&Q.json))try{ee=await ne.context.json()}catch{}if((ee==null?void 0:ee.error)==="insufficient_scope"||(ue==null?void 0:ue.error)==="insufficient_scope"){ae.error((ee==null?void 0:ee.message)||"Gmail is missing send permission. Please disconnect and reconnect Gmail, allowing 'Send email on your behalf'.",{duration:1e4});return}if(ne)throw new Error((ee==null?void 0:ee.message)||ne.message);if(!(ue!=null&&ue.success))throw new Error((ue==null?void 0:ue.error)||"Failed to send");ae.success("Video email sent!"),t(!1),i==null||i()}catch(J){console.error("Gmail send error:",J),ae.error("Failed to send: "+(J instanceof Error?J.message:"Unknown error"))}finally{A(!1)}};return e.jsx(Os,{open:s,onOpenChange:t,children:e.jsxs(Rs,{className:"sm:max-w-[560px] max-h-[90vh] overflow-y-auto",children:[e.jsxs(Us,{children:[e.jsxs(zs,{className:"flex items-center gap-2",children:[e.jsx(nn,{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(se,{children:"Send to Contact"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(Sc,{open:u,onOpenChange:h,children:[e.jsx(Cc,{asChild:!0,children:e.jsxs($,{variant:"outline",role:"combobox",className:"flex-1 justify-between",children:[c?e.jsxs("span",{className:"flex items-center gap-2 min-w-0",children:[e.jsx(Lo,{className:"h-4 w-4 shrink-0 text-muted-foreground"}),e.jsx("span",{className:"truncate",children:W(c)}),c.email&&e.jsxs("span",{className:"text-muted-foreground text-xs truncate",children:["(",c.email,")"]})]}):e.jsx("span",{className:"text-muted-foreground",children:"Select a contact..."}),e.jsx(sw,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(xc,{className:"w-[350px] p-0",align:"start",children:e.jsxs(pw,{children:[e.jsx(fw,{placeholder:"Search contacts..."}),e.jsxs(xw,{children:[e.jsx(gw,{children:m?"Loading...":"No contacts found."}),e.jsx($b,{children:l.filter(Q=>Q.email).map(Q=>e.jsxs(iv,{value:`${W(Q)} ${Q.email||""}`,onSelect:()=>B(Q),children:[e.jsx(oa,{className:Tt("mr-2 h-4 w-4",(c==null?void 0:c.id)===Q.id?"opacity-100":"opacity-0")}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("div",{className:"font-medium truncate",children:W(Q)}),e.jsx("div",{className:"text-xs text-muted-foreground truncate",children:Q.email})]})]},Q.id))})]})]})})]}),c&&e.jsx($,{variant:"ghost",size:"icon",onClick:q,className:"shrink-0",children:e.jsx(pr,{className:"h-4 w-4"})})]})]}),!c&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{htmlFor:"video-to",children:"Or type email address"}),e.jsx(be,{id:"video-to",value:x,onChange:Q=>g(Q.target.value),placeholder:"recipient@example.com",type:"email"})]}),e.jsx(Hl,{}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{htmlFor:"video-subject",children:"Subject"}),e.jsx(be,{id:"video-subject",value:y,onChange:Q=>b(Q.target.value)})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{htmlFor:"video-message",children:"Personal Message"}),e.jsx(Is,{id:"video-message",value:v,onChange:Q=>N(Q.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(se,{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(Td,{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(Td,{className:"h-5 w-5 text-primary ml-0.5"})})})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Recipients will see the thumbnail with a play button. Clicking opens the video page."})]}),e.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[e.jsx($,{variant:"outline",onClick:()=>t(!1),disabled:C,children:"Cancel"}),e.jsxs($,{onClick:K,disabled:C||!x||!y,className:"gap-2",children:[C?e.jsx(Ht,{className:"h-4 w-4 animate-spin"}):e.jsx(Br,{className:"h-4 w-4"}),C?"Sending...":"Send Video Email"]})]})]})]})})}const OPn=()=>{const{user:s}=_s();return ht({queryKey:["team-videos",s==null?void 0:s.id],queryFn:async()=>{const{data:t,error:n}=await U.rpc("get_team_videos",{_user_id:s.id});if(n)throw n;return t||[]},enabled:!!s})};function FPn({recipient:s}){return s.watched_at?e.jsxs($e,{className:"bg-emerald-100 text-emerald-800 text-[10px]",children:[e.jsx(Td,{className:"h-2.5 w-2.5 mr-0.5"}),"Watched"]}):s.clicked_at?e.jsxs($e,{className:"bg-blue-100 text-blue-800 text-[10px]",children:[e.jsx(pg,{className:"h-2.5 w-2.5 mr-0.5"}),"Clicked"]}):s.opened_at?e.jsxs($e,{className:"bg-amber-100 text-amber-800 text-[10px]",children:[e.jsx(ga,{className:"h-2.5 w-2.5 mr-0.5"}),"Opened"]}):e.jsxs($e,{variant:"outline",className:"text-[10px]",children:[e.jsx(Br,{className:"h-2.5 w-2.5 mr-0.5"}),"Sent"]})}function zPn({open:s,onOpenChange:t,videoId:n,videoTitle:r}){const{data:a=[],isLoading:i}=MNn(n);return e.jsx(Os,{open:s,onOpenChange:t,children:e.jsxs(Rs,{className:"max-w-2xl max-h-[80vh]",children:[e.jsx(Us,{children:e.jsxs(zs,{className:"flex items-center gap-2",children:[e.jsx(ml,{className:"h-5 w-5"}),"Send Analytics: ",r]})}),i?e.jsx("div",{className:"space-y-2",children:[...Array(3)].map((l,o)=>e.jsx(on,{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(Oi,{className:"h-[400px]",children:e.jsxs(Va,{children:[e.jsx(Ha,{children:e.jsxs(hn,{children:[e.jsx(Lt,{children:"Recipient"}),e.jsx(Lt,{children:"Status"}),e.jsx(Lt,{children:"Sent"}),e.jsx(Lt,{children:"Last Activity"})]})}),e.jsx(Ga,{children:a.map(l=>e.jsxs(hn,{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(FPn,{recipient:l})}),e.jsx(gt,{className:"text-xs text-muted-foreground",children:Hs(new Date(l.sent_at),"MMM d, h:mm a")}),e.jsx(gt,{className:"text-xs text-muted-foreground",children:l.last_activity_at?fc(new Date(l.last_activity_at),{addSuffix:!0}):"—"})]},l.id))})]})})]})]})})}function BPn(){const{data:s,isLoading:t}=LNn(),{data:n=[],isLoading:r}=PNn(),[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(_e,{children:[e.jsx(Bt,{className:"pb-2",children:e.jsx(on,{className:"h-4 w-20"})}),e.jsx(Oe,{children:e.jsx(on,{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(_e,{children:[e.jsxs(Bt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Ut,{className:"text-sm font-medium",children:"Total Sent"}),e.jsx(Br,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsx(Oe,{children:e.jsx("div",{className:"text-2xl font-bold",children:(s==null?void 0:s.totalSent)||0})})]}),e.jsxs(_e,{children:[e.jsxs(Bt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Ut,{className:"text-sm font-medium",children:"Open Rate"}),e.jsx(ga,{className:"h-4 w-4 text-amber-500"})]}),e.jsxs(Oe,{children:[e.jsxs("div",{className:"text-2xl font-bold",children:[(s==null?void 0:s.openRate)||0,"%"]}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[(s==null?void 0:s.totalOpened)||0," opened"]})]})]}),e.jsxs(_e,{children:[e.jsxs(Bt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Ut,{className:"text-sm font-medium",children:"Click Rate"}),e.jsx(pg,{className:"h-4 w-4 text-blue-500"})]}),e.jsxs(Oe,{children:[e.jsxs("div",{className:"text-2xl font-bold",children:[(s==null?void 0:s.clickRate)||0,"%"]}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[(s==null?void 0:s.totalClicked)||0," clicked"]})]})]})]}),e.jsxs(_e,{children:[e.jsxs(Bt,{children:[e.jsx(Ut,{className:"text-sm font-medium",children:"Send History by Video"}),e.jsx(vr,{children:"Click a video to see individual recipient tracking"})]}),e.jsx(Oe,{children:Object.keys(o).length===0?e.jsx("p",{className:"text-sm text-muted-foreground text-center py-6",children:"No tracked sends yet. Send a video via Gmail to start tracking."}):e.jsx("div",{className:"space-y-2",children:Object.values(o).map(c=>{const d=c.recipients.filter(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(Xr,{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(Br,{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(ga,{className:"h-3 w-3"})," ",d]}),e.jsxs("span",{className:"text-xs text-blue-600 flex items-center gap-1",children:[e.jsx(pg,{className:"h-3 w-3"})," ",u]})]})]}),e.jsx(Il,{className:"h-4 w-4 text-muted-foreground"})]},c.videoId)})})})]}),e.jsx(zPn,{open:!!a,onOpenChange:c=>!c&&i(null),videoId:(a==null?void 0:a.id)||null,videoTitle:(a==null?void 0:a.title)||""})]})}function $Pn({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(Xr,{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 UPn({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:x,copyToClipboard:g,formatDuration:y}){const[b,v]=j.useState(!1);return e.jsxs(_e,{className:"overflow-hidden group cursor-pointer",onClick:r,onMouseEnter:()=>v(!0),onMouseLeave:()=>v(!1),children:[e.jsxs("div",{className:"relative aspect-video bg-muted overflow-hidden",children:[e.jsx($Pn,{previewSrc:t,thumbnailSrc:n,alt:s.title||"Video preview",isHovered:b}),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(Td,{className:"h-6 w-6 text-primary ml-1"})})}),e.jsx("div",{className:"absolute bottom-2 right-2 bg-black/70 text-white text-xs px-1.5 py-0.5 rounded",children:y(s.duration_seconds)}),s.status!=="ready"&&e.jsx($e,{variant:s.status==="processing"?"secondary":"destructive",className:"absolute top-2 left-2",children:s.status})]}),e.jsx(Oe,{className:"p-3",children:e.jsxs("div",{className:"flex items-start justify-between gap-2",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("h3",{className:"font-medium truncate",children:s.title||"Untitled Video"}),e.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground mt-1",children:[e.jsx(Lo,{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(Hr,{className:"h-3 w-3"}),e.jsx("span",{children:Hs(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(ga,{className:"h-3 w-3"}),e.jsxs("span",{children:[s.view_count," ",s.view_count===1?"view":"views"]})]})]}),m&&s.share_token&&e.jsxs($,{variant:"outline",size:"sm",className:"mt-2 gap-1.5 text-xs h-7",onClick:N=>{N.stopPropagation(),h==null||h()},children:[e.jsx(nn,{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(Lo,{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(Hr,{className:"h-3 w-3"}),e.jsx("span",{children:Hs(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(ga,{className:"h-3 w-3"}),e.jsxs("span",{children:[s.view_count," ",s.view_count===1?"view":"views"]})]})]})]}),e.jsxs(Hd,{children:[e.jsx(Gd,{asChild:!0,children:e.jsx($,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:N=>N.stopPropagation(),children:e.jsx(cy,{className:"h-4 w-4"})})}),e.jsxs(Md,{align:"end",className:"bg-popover",children:[e.jsxs(Na,{onClick:N=>{N.stopPropagation(),r()},children:[e.jsx(ga,{className:"h-4 w-4 mr-2"}),"Watch"]}),e.jsx(S0,{}),e.jsxs(Na,{onClick:N=>{N.stopPropagation(),u()},children:[e.jsx(Rc,{className:"h-4 w-4 mr-2"}),"Share with Template"]}),e.jsxs(Na,{onClick:N=>{N.stopPropagation(),g(x(s),"Share link")},children:[e.jsx(kc,{className:"h-4 w-4 mr-2"}),"Copy Share Link"]}),e.jsxs(Na,{onClick:N=>{N.stopPropagation(),o()},children:[e.jsx(xT,{className:"h-4 w-4 mr-2"}),"Get Embed Code"]}),e.jsxs(Na,{onClick:N=>{N.stopPropagation(),c()},children:[e.jsx(nn,{className:"h-4 w-4 mr-2"}),"Copy HTML for Email"]}),e.jsxs(Na,{onClick:N=>{N.stopPropagation(),d()},children:[e.jsx(Tr,{className:"h-4 w-4 mr-2"}),"Embed to CRM"]}),m&&s.share_token&&e.jsxs(Na,{onClick:N=>{N.stopPropagation(),h==null||h()},children:[e.jsx(Br,{className:"h-4 w-4 mr-2"}),"Send via Gmail"]}),e.jsxs(Na,{onClick:N=>{N.stopPropagation(),i()},children:[e.jsx(Ya,{className:"h-4 w-4 mr-2"}),"Rename"]}),e.jsx(S0,{}),s.contact_id&&e.jsxs(Na,{onClick:N=>{N.stopPropagation(),l()},children:[e.jsx(Lo,{className:"h-4 w-4 mr-2"}),"View Contact"]}),e.jsxs(Na,{onClick:N=>{N.stopPropagation(),a()},className:"text-destructive",children:[e.jsx(Pn,{className:"h-4 w-4 mr-2"}),"Delete"]})]})]})]})})]})}function qPn(){var Ts,js;const s=Vn(),{data:t,isLoading:n,refetch:r}=QNn(),{data:a}=WEe(),{data:i}=M1(),l=tkn(),o=ekn(),{isGmailConnected:c,gmailEmail:d}=ux(),{data:u}=Nw(),{data:h=[],isLoading:m}=OPn(),[p,x]=j.useState("my"),[g,y]=j.useState(""),[b,v]=j.useState(null),[N,C]=j.useState(!1),[A,T]=j.useState(!1),[P,M]=j.useState(!1),[I,D]=j.useState(!1),[B,q]=j.useState(!1),[W,V]=j.useState(""),[K,Q]=j.useState(!1),[J,ce]=j.useState(!1),[ue,ne]=j.useState(!1),[ee,le]=j.useState(!1),[he,ve]=j.useState(""),[ge,fe]=j.useState({}),je=zt=>{if(!zt)return"Unassigned";const Nt=i==null?void 0:i.find(Ds=>Ds.id===zt);return Nt?`${Nt.first_name} ${Nt.last_name||""}`.trim():"Unknown"},Ee=zt=>{if(!zt)return"0:00";const Nt=Math.floor(zt/60),Ds=zt%60;return`${Nt}:${Ds.toString().padStart(2,"0")}`},[Me,De]=j.useState("all"),ze=t==null?void 0:t.filter(zt=>{const Nt=zt.category||"general";if(Me==="general"&&Nt!=="general"||Me==="open_house"&&Nt!=="open_house")return!1;if(!g)return!0;const Ds=je(zt.contact_id).toLowerCase(),_t=(zt.title||"").toLowerCase(),Xs=(zt.notes||"").toLowerCase();return Ds.includes(g.toLowerCase())||_t.includes(g.toLowerCase())||Xs.includes(g.toLowerCase())}),ke=(t==null?void 0:t.filter(zt=>(zt.category||"general")==="open_house").length)||0,Xe=(t==null?void 0:t.filter(zt=>(zt.category||"general")==="general").length)||0,Se=(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 Nt=t.filter(_t=>_t.status==="processing"&&_t.bunny_video_id);if(!Nt.length)return;let Ds=!1;for(const _t of Nt)try{const{data:Xs,error:rn}=await U.functions.invoke("bunny-upload",{body:{action:"status",videoId:_t.bunny_video_id,isAgentVideo:!0}});if(rn||!Xs)continue;Xs.status===4&&(await U.from("agent_videos").update({status:"ready",playback_url:Xs.directPlayUrl,thumbnail_url:Xs.thumbnailUrl,preview_url:Xs.previewUrl,duration_seconds:Xs.length||_t.duration_seconds,updated_at:new Date().toISOString()}).eq("id",_t.id),Ds=!0)}catch(Xs){console.warn("Reconcile check failed for video",_t.id,Xs)}Ds&&r()})()},[Se,r]),j.useEffect(()=>{(async()=>{if(!(t!=null&&t.length))return;const Nt=t.filter(Ps=>(Ps==null?void 0:Ps.bunny_video_id)&&!ge[Ps.id]);if(!Nt.length)return;const Ds=Nt.map(Ps=>Ps.bunny_video_id),{data:_t,error:Xs}=await U.functions.invoke("bunny-upload",{body:{action:"bulk-asset-urls",videoIds:Ds,isAgentVideo:!0}});if(Xs)throw Xs;const rn=(_t==null?void 0:_t.assets)||{};fe(Ps=>{const _n={...Ps};for(const Zs of Nt)rn[Zs.bunny_video_id]&&(_n[Zs.id]={previewUrl:rn[Zs.bunny_video_id].previewUrl,thumbnailUrl:rn[Zs.bunny_video_id].thumbnailUrl});return _n})})().catch(Nt=>console.warn("Failed to load signed Bunny asset URLs",Nt))},[t,ge]);const Re=(a==null?void 0:a.total_storage_mb)||0,Ae=(a==null?void 0:a.max_storage_mb)||1024,Be=Re/Ae*100,qe=Be>=80,Ke=Be>=100,Ze=async(zt,Nt)=>{await navigator.clipboard.writeText(zt),ae.success(`${Nt} copied to clipboard`)},Ue=zt=>zt.share_token?`https://video.relevelup.com/${zt.share_token}`:zt.playback_url||"",et=zt=>{const Nt=Ue(zt),Ds=i==null?void 0:i.find(Zs=>Zs.id===zt.contact_id),_t=je(zt.contact_id),Xs=_t!=="Unassigned"?_t.split(" ")[0]:"",rn=(Ds==null?void 0:Ds.phone)||"",Ps=`Hey${Xs?` ${Xs}`:""}! I recorded a quick video message for you. Check it out: ${Nt}`,_n=rn?`sms:${rn}?body=${encodeURIComponent(Ps)}`:`sms:?body=${encodeURIComponent(Ps)}`;window.open(_n,"_self")},Qe=zt=>{const Nt=i==null?void 0:i.find(_n=>_n.id===zt.contact_id),Ds=(Nt==null?void 0:Nt.email)||"",_t=Ue(zt),Xs="Check out this video",rn=`I recorded a quick video for you: ${_t}`,Ps=Ds?`mailto:${Ds}?subject=${encodeURIComponent(Xs)}&body=${encodeURIComponent(rn)}`:`mailto:?subject=${encodeURIComponent(Xs)}&body=${encodeURIComponent(rn)}`;window.open(Ps,"_self")},Ge=zt=>{var Xs;const Nt=Ue(zt),Ds=zt.title||"Video Message",_t=zt.share_token?`https://video.relevelup.com/thumb/${zt.share_token}`:((Xs=ge[zt.id])==null?void 0:Xs.thumbnailUrl)||zt.thumbnail_url||"";return``},nt=async zt=>{if(!zt.thumbnail_url&&!zt.share_token){ae.error("Video thumbnail not available yet");return}const Nt=Ge(zt),Ds=Ue(zt),_t=`Watch: ${zt.title||"Video Message"} ${Ds}`;try{const Xs=new Blob([Nt],{type:"text/html"}),rn=new Blob([_t],{type:"text/plain"}),Ps=new ClipboardItem({"text/html":Xs,"text/plain":rn});await navigator.clipboard.write([Ps]),ae.success("Copied! Paste into Gmail - the thumbnail will appear after sending.")}catch{await navigator.clipboard.writeText(_t+` `+Nt),ae.success("Copied! Paste into your email.")}},ft=async zt=>{try{ae.loading("Preparing download...",{id:"download"});const{data:Nt,error:Ds}=await U.functions.invoke("bunny-upload",{body:{action:"download-url",videoId:zt.bunny_video_id,isAgentVideo:!0}});if(Ds||!(Nt!=null&&Nt.downloadUrl))throw new Error((Ds==null?void 0:Ds.message)||"Failed to get download URL");const Xs=`${((zt.title||"video").toString().trim()||"video").replace(/[\\/:*?"<>|]+/g,"-")}.mp4`,rn=await fetch(Nt.downloadUrl);if(!rn.ok)throw new Error("Failed to fetch video file");const Ps=await rn.blob(),_n=URL.createObjectURL(Ps),Zs=document.createElement("a");Zs.href=_n,Zs.download=Xs,Zs.rel="noreferrer",document.body.appendChild(Zs),Zs.click(),Zs.remove(),URL.revokeObjectURL(_n),ae.success("Download started",{id:"download"})}catch(Nt){console.error("Download error:",Nt),ae.error("Could not force download (your browser may block it).",{id:"download"})}},lt=async zt=>{v(zt),Q(!0),V(""),q(!0);try{const{data:Nt,error:Ds}=await U.functions.invoke("bunny-upload",{body:{action:"crm-embed",videoId:zt.bunny_video_id,title:zt.title,isAgentVideo:!0,shareToken:zt.share_token}});if(Ds||!(Nt!=null&&Nt.html))throw new Error("Failed to generate CRM embed code");V(Nt.html)}catch(Nt){console.error("CRM embed error:",Nt),ae.error("Failed to generate CRM embed code"),q(!1)}finally{Q(!1)}},Mt=zt=>{v(zt),C(!0)},Ft=async()=>{if(b)try{await l.mutateAsync({id:b.id,bunnyVideoId:b.bunny_video_id,hardDelete:!0}),T(!1),v(null),ae.success("Video deleted successfully")}catch{ae.error("Failed to delete video")}};return e.jsx(Ks,{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:()=>x("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&&((Ts=u.team)==null?void 0:Ts.shared_videos_enabled)&&e.jsxs("button",{onClick:()=>x("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(qn,{className:"h-3.5 w-3.5"}),"Team"]}),e.jsxs("button",{onClick:()=>x("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(ml,{className:"h-3.5 w-3.5"}),"Analytics"]})]})]}),p==="my"&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs($,{variant:"outline",onClick:()=>M(!0),children:[e.jsx(si,{className:"h-4 w-4 mr-2"}),"Upload Video"]}),e.jsxs($,{onClick:()=>s("/mission-control/video/record"),children:[e.jsx(sn,{className:"h-4 w-4 mr-2"}),"Record New Video"]})]})]}),p==="team"?e.jsx(VPn,{videos:h,isLoading:m,searchTerm:g,setSearchTerm:y}):p==="analytics"?e.jsx(BPn,{}):e.jsxs(e.Fragment,{children:[e.jsx(_e,{className:qe?"border-amber-500":Ke?"border-destructive":"",children:e.jsxs(Oe,{className:"py-4",children:[e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx(AK,{className:`h-5 w-5 ${Ke?"text-destructive":qe?"text-amber-500":"text-muted-foreground"}`}),e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center justify-between mb-1",children:[e.jsx("span",{className:"text-sm font-medium",children:"Storage Used"}),e.jsxs("span",{className:"text-sm text-muted-foreground",children:[Re.toFixed(1)," MB / ",Ae>=1024?`${(Ae/1024).toFixed(0)} GB`:`${Ae} MB`]})]}),e.jsx(Ki,{value:Math.min(Be,100),className:`h-2 ${Ke?"[&>div]:bg-destructive":qe?"[&>div]:bg-amber-500":""}`})]}),qe&&!Ke&&e.jsxs($e,{variant:"outline",className:"border-amber-500 text-amber-600",children:[e.jsx(xo,{className:"h-3 w-3 mr-1"}),"Near Limit"]}),Ke&&e.jsxs($e,{variant:"destructive",children:[e.jsx(xo,{className:"h-3 w-3 mr-1"}),"At Limit"]})]}),Ke&&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:Xe},{id:"open_house",label:"Open House Tours",count:ke}].map(zt=>e.jsxs("button",{onClick:()=>De(zt.id),className:`px-3 py-1.5 rounded-md text-sm font-medium transition-colors ${Me===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(Vr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(be,{placeholder:"Search videos by contact, title, or notes...",value:g,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"})}):(ze==null?void 0:ze.length)===0?e.jsx(_e,{children:e.jsxs(Oe,{className:"py-12 text-center",children:[e.jsx(Xr,{className:"h-12 w-12 mx-auto text-muted-foreground mb-4"}),e.jsx("h3",{className:"font-semibold mb-2",children:"No videos yet"}),e.jsx("p",{className:"text-muted-foreground mb-4",children:"Record your first video touch to get started"}),e.jsxs($,{onClick:()=>s("/mission-control/video/record"),children:[e.jsx(sn,{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:ze==null?void 0:ze.map(zt=>{var Nt,Ds;return e.jsx(UPn,{video:zt,previewSrc:(Nt=ge[zt.id])==null?void 0:Nt.previewUrl,thumbnailSrc:(Ds=ge[zt.id])==null?void 0:Ds.thumbnailUrl,onOpen:()=>Mt(zt),onDelete:()=>{v(zt),T(!0)},onRename:()=>{v(zt),ve(zt.title||""),le(!0)},onNavigateToContact:()=>s(`/mission-control/contacts/${zt.contact_id}`),onGetEmbedCode:()=>{v(zt),D(!0)},onCopyEmailHtml:()=>nt(zt),onEmbedToCrm:()=>lt(zt),onShareWithTemplate:()=>{v(zt),ce(!0)},onSendViaGmail:()=>{v(zt),ne(!0)},isGmailConnected:c,getContactName:je,getShareUrl:Ue,copyToClipboard:Ze,formatDuration:Ee},zt.id)})}),e.jsx(Os,{open:N,onOpenChange:C,children:e.jsxs(Rs,{className:"max-w-2xl",children:[e.jsxs(Us,{children:[e.jsx(zs,{children:(b==null?void 0:b.title)||"Video Preview"}),e.jsx(Sr,{children:(b==null?void 0:b.contact_id)&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Lo,{className:"h-3 w-3"}),je(b.contact_id)]})})]}),b&&e.jsxs("div",{className:"space-y-4",children:[b.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(Ht,{className:"h-8 w-8 text-primary animate-spin"})})}),e.jsxs("div",{className:"space-y-1",children:[e.jsx("h3",{className:"font-semibold text-lg",children:"Video is still processing"}),e.jsx("p",{className:"text-muted-foreground text-sm max-w-sm",children:"Your video is being encoded and will be ready shortly. This usually takes 1–3 minutes. Check back soon!"})]}),e.jsxs($,{variant:"outline",size:"sm",onClick:()=>{C(!1),r()},children:[e.jsx(Wi,{className:"h-4 w-4 mr-2"}),"Refresh Library"]})]}):e.jsx("div",{className:"relative w-full",style:{paddingBottom:"56.25%"},children:b.playback_url?(()=>{let zt=b.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:b.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:b.playback_url,controls:!0,playsInline:!0,preload:"metadata",poster:b.thumbnail_url||void 0,className:"absolute top-0 left-0 w-full h-full rounded-lg object-cover",onError:()=>ae.error("Video preview failed to load")},b.playback_url)})():e.jsxs("div",{className:"absolute inset-0 flex items-center justify-center bg-muted rounded-lg",children:[e.jsx(Xr,{className:"h-12 w-12 text-muted-foreground"}),e.jsx("p",{className:"text-muted-foreground ml-2",children:"Video not available"})]})}),e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsxs($,{variant:"outline",onClick:()=>et(b),children:[e.jsx(Ji,{className:"h-4 w-4 mr-2"}),"Text Contact Video"]}),!c&&e.jsxs($,{variant:"outline",onClick:()=>Qe(b),children:[e.jsx(nn,{className:"h-4 w-4 mr-2"}),"Email Contact Video"]}),e.jsxs($,{variant:"outline",onClick:()=>Ze(Ue(b),"Share link"),children:[e.jsx(Ca,{className:"h-4 w-4 mr-2"}),"Copy Share Link"]}),e.jsxs($,{variant:"outline",onClick:()=>nt(b),children:[e.jsx(nn,{className:"h-4 w-4 mr-2"}),"Copy HTML for Email"]}),e.jsxs($,{variant:"outline",onClick:()=>ft(b),children:[e.jsx(di,{className:"h-4 w-4 mr-2"}),"Download Video"]}),e.jsxs($,{variant:"outline",onClick:()=>{C(!1),lt(b)},children:[e.jsx(Tr,{className:"h-4 w-4 mr-2"}),"Embed to CRM"]}),e.jsxs($,{variant:"outline",onClick:()=>{C(!1),ce(!0)},children:[e.jsx(Rc,{className:"h-4 w-4 mr-2"}),"Send with Page Template"]}),c&&(b==null?void 0:b.share_token)&&e.jsxs($,{variant:"outline",onClick:()=>{C(!1),ne(!0)},children:[e.jsx(Br,{className:"h-4 w-4 mr-2"}),"Send via Gmail"]})]}),e.jsx("div",{className:"flex justify-end pt-2 border-t",children:e.jsxs($,{variant:"destructive",onClick:()=>{C(!1),T(!0)},children:[e.jsx(Pn,{className:"h-4 w-4 mr-2"}),"Delete Video"]})})]})]})}),e.jsx(Os,{open:A,onOpenChange:T,children:e.jsxs(Rs,{children:[e.jsxs(Us,{children:[e.jsx(zs,{children:"Delete Video"}),e.jsx(Sr,{children:"Are you sure you want to delete this video? This action cannot be undone."})]}),e.jsxs(kr,{children:[e.jsx($,{variant:"outline",onClick:()=>T(!1),children:"Cancel"}),e.jsx($,{variant:"destructive",onClick:Ft,disabled:l.isPending,children:l.isPending?"Deleting...":"Delete"})]})]})}),e.jsx(D7t,{open:P,onOpenChange:M}),e.jsx(Os,{open:I,onOpenChange:D,children:e.jsxs(Rs,{className:"sm:max-w-lg",children:[e.jsxs(Us,{children:[e.jsx(zs,{children:"Embed Video"}),e.jsx(Sr,{children:"Copy this code to embed the video on your website."})]}),b&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Embed Code"}),e.jsx(Is,{readOnly:!0,rows:5,value:``,className:"font-mono text-xs"})]}),e.jsx("div",{className:"flex gap-2",children:e.jsxs($,{className:"flex-1",onClick:()=>{const zt=``;Ze(zt,"Embed code")},children:[e.jsx(Ca,{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."})]})]})}),b&&e.jsx(dVt,{open:J,onOpenChange:ce,video:b,contactName:je(b.contact_id)}),b&&e.jsx(RPn,{open:ue,onOpenChange:ne,video:b,gmailEmail:d,signedThumbnailUrl:(js=ge[b.id])==null?void 0:js.thumbnailUrl}),e.jsx(Os,{open:ee,onOpenChange:le,children:e.jsxs(Rs,{className:"max-w-sm",children:[e.jsxs(Us,{children:[e.jsx(zs,{children:"Rename Video"}),e.jsx(Sr,{children:"Enter a new title for this video."})]}),e.jsx(be,{value:he,onChange:zt=>ve(zt.target.value),placeholder:"Video title",autoFocus:!0,onKeyDown:zt=>{zt.key==="Enter"&&he.trim()&&o.mutate({id:b.id,title:he.trim()},{onSuccess:()=>{ae.success("Video renamed"),le(!1)}})}}),e.jsxs(kr,{children:[e.jsx($,{variant:"outline",onClick:()=>le(!1),children:"Cancel"}),e.jsx($,{disabled:!he.trim()||o.isPending,onClick:()=>{o.mutate({id:b.id,title:he.trim()},{onSuccess:()=>{ae.success("Video renamed"),le(!1)}})},children:o.isPending?"Saving...":"Save"})]})]})}),e.jsx(Os,{open:B,onOpenChange:q,children:e.jsxs(Rs,{className:"sm:max-w-lg",children:[e.jsxs(Us,{children:[e.jsxs(zs,{className:"flex items-center gap-2",children:[e.jsx(Tr,{className:"h-5 w-5"}),"Embed to CRM"]}),e.jsx(Sr,{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(Ht,{className:"h-8 w-8 animate-spin text-muted-foreground"})}):W?e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"CRM Email HTML"}),e.jsx(Is,{readOnly:!0,rows:12,value:W,className:"font-mono text-xs"})]}),e.jsxs($,{className:"w-full",onClick:()=>{Ze(W,"CRM embed code")},children:[e.jsx(Ca,{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 VPn({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(Vr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(be,{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(_e,{children:e.jsxs(Oe,{className:"py-12 text-center",children:[e.jsx(qn,{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(ki,{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($e,{variant:"secondary",className:"text-xs",children:c.videos.length})]}),e.jsx("div",{className:"grid gap-4 sm:grid-cols-2 lg:grid-cols-3",children:c.videos.map(d=>e.jsxs(_e,{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(Xr,{className:"h-10 w-10 text-muted-foreground"}),d.duration_seconds&&e.jsx("span",{className:"absolute bottom-2 right-2 bg-black/70 text-white text-xs px-1.5 py-0.5 rounded",children:l(d.duration_seconds)})]}),e.jsxs(Oe,{className:"p-3",children:[e.jsx("p",{className:"font-medium text-sm truncate",children:d.title||"Untitled"}),e.jsxs("div",{className:"flex items-center gap-3 mt-1 text-xs text-muted-foreground",children:[d.recipient_name&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Lo,{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(ga,{className:"h-3 w-3"}),d.view_count]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Hr,{className:"h-3 w-3"}),Hs(new Date(d.created_at),"MMM d")]})]})]})]},d.id))})]},o))})]})}const HPn=()=>{const{user:s}=_s();return ht({queryKey:["team-deals",s==null?void 0:s.id],queryFn:async()=>{const{data:t,error:n}=await U.rpc("get_team_deals",{_user_id:s.id});if(n)throw n;return t||[]},enabled:!!s})},bvt=["#8B5CF6","#EC4899","#F59E0B","#10B981","#3B82F6","#EF4444","#06B6D4","#F97316"];function GPn({open:s,onOpenChange:t}){const{data:n,isLoading:r}=HPn(),[a,i]=j.useState(""),[l,o]=j.useState("all"),c=j.useMemo(()=>{if(!n)return new Map;const x=new Map;let g=0;return n.forEach(y=>{x.has(y.owner_user_id)||(x.set(y.owner_user_id,{name:y.owner_name||"Unknown",avatar:y.owner_avatar_url,color:bvt[g%bvt.length]}),g++)}),x},[n]),d=j.useMemo(()=>Array.from(c.entries()).map(([x,g])=>({id:x,...g})),[c]),u=j.useMemo(()=>{if(!n)return[];let x=n;if(l!=="all"&&(x=x.filter(g=>g.owner_user_id===l)),a.trim()){const g=a.toLowerCase();x=x.filter(y=>{var b,v,N,C;return y.deal_name.toLowerCase().includes(g)||((b=y.contact_name)==null?void 0:b.toLowerCase().includes(g))||((v=y.property_address)==null?void 0:v.toLowerCase().includes(g))||((N=y.city)==null?void 0:N.toLowerCase().includes(g))||((C=y.owner_name)==null?void 0:C.toLowerCase().includes(g))})}return x},[n,a,l]),h=j.useMemo(()=>{const x=new Map;return u.forEach(g=>{const y=g.stage_name||"Unknown";x.has(y)||x.set(y,{name:y,color:g.stage_color,icon:g.stage_icon,deals:[],totalValue:0});const b=x.get(y);b.deals.push(g),b.totalValue+=g.sale_price||0}),Array.from(x.values())},[u]),m=x=>x>=1e6?`$${(x/1e6).toFixed(1)}M`:x>=1e3?`$${(x/1e3).toFixed(0)}K`:`$${x.toFixed(0)}`,p=x=>x?new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(x):null;return e.jsx(Os,{open:s,onOpenChange:t,children:e.jsxs(Rs,{className:"max-w-[95vw] w-full max-h-[90vh] flex flex-col",children:[e.jsx(Us,{children:e.jsxs(zs,{className:"flex items-center gap-2",children:[e.jsx(qn,{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(Vr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(be,{placeholder:"Search deals...",value:a,onChange:x=>i(x.target.value),className:"pl-9"})]}),e.jsxs(vs,{value:l,onValueChange:o,children:[e.jsx(gs,{className:"w-[180px]",children:e.jsx(bs,{placeholder:"All Members"})}),e.jsxs(ys,{children:[e.jsx(Ye,{value:"all",children:"All Members"}),d.map(x=>e.jsx(Ye,{value:x.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:x.color}}),x.name]})},x.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(x=>e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx("span",{className:"h-2 w-2 rounded-full",style:{backgroundColor:x.color}}),x.name.split(" ")[0]]},x.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(x=>e.jsxs("div",{className:"min-w-[260px] flex-1",children:[e.jsx(on,{className:"h-12 w-full mb-2 rounded-lg"}),e.jsx(on,{className:"h-24 w-full mb-2 rounded-lg"}),e.jsx(on,{className:"h-24 w-full rounded-lg"})]},x))}):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(qn,{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(x=>{const g=x.icon&&R3e[x.icon]||Bp;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:x.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:x.color?`${x.color}20`:void 0},children:e.jsx(g,{className:"h-3.5 w-3.5",style:{color:x.color||void 0}})}),e.jsx("h3",{className:"font-semibold text-sm",children:x.name})]}),e.jsx($e,{variant:"secondary",className:"text-xs px-2",children:x.deals.length})]}),x.totalValue>0&&e.jsx("p",{className:"text-xs text-muted-foreground ml-8",children:m(x.totalValue)})]}),e.jsx(Oi,{className:"flex-1 p-2",children:e.jsx("div",{className:"space-y-2",children:x.deals.map(y=>{const b=c.get(y.owner_user_id);return e.jsx(WPn,{deal:y,ownerColor:(b==null?void 0:b.color)||"#888",ownerName:(b==null?void 0:b.name)||"Unknown",ownerAvatar:(b==null?void 0:b.avatar)||null,formatPrice:p},y.id)})})})]},x.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 WPn({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(ki,{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($e,{variant:"outline",className:Tt("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(sa,{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(qd,{className:"h-3 w-3 text-emerald-500 shrink-0"}),e.jsx("span",{className:"font-semibold text-foreground",children:a(s.sale_price)})]})]})}function KPn({members:s,enabledMembers:t,onToggleMember:n,isOpen:r,onToggleOpen:a}){const i=t.size;return e.jsxs("div",{className:Tt("shrink-0 border-r border-border/50 bg-muted/20 transition-all duration-300 flex flex-col",r?"w-[220px]":"w-[48px]"),children:[e.jsx("div",{className:"p-2 border-b border-border/50 shrink-0",children:e.jsxs($,{variant:"ghost",size:"sm",className:"w-full justify-start gap-2 px-2",onClick:a,children:[e.jsx(qn,{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(Ic,{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(Oi,{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:Tt("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(ki,{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:Tt("text-xs truncate flex-1",o?"font-medium text-foreground":"text-muted-foreground"),children:l.name}),e.jsx(Tn,{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:Tt("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(ki,{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 _vt=["#8B5CF6","#EC4899","#F59E0B","#10B981","#3B82F6","#EF4444","#06B6D4","#F97316"];function YPn(){const s=Za(),{data:t}=Nw(),n=(t==null?void 0:t.role)==="team_leader",r=t==null?void 0:t.teamId,a=ht({queryKey:["team-pipeline-members",r,s],queryFn:async()=>{const{data:i,error:l}=await U.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 U.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:_vt[h%_vt.length]}))},enabled:!!r&&!!s&&n,staleTime:5*60*1e3});return{isTeamLeader:n,teamMembers:a.data||[],isLoadingMembers:a.isLoading}}function ZPn(s){return ht({queryKey:["team-member-deals",s],queryFn:async()=>{if(s.length===0)return[];const{data:t,error:n}=await U.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 XPn(){const s=Za();return ht({queryKey:["all-deal-tags-map",s],queryFn:async()=>{if(!s)return{tags:[],byDeal:{},unique:[]};const{data:t,error:n}=await U.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 uVt({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(Hd,{open:a,onOpenChange:i,children:[e.jsx(Gd,{asChild:!0,children:e.jsxs($,{variant:"outline",size:"sm",className:"h-7 text-xs gap-1.5",disabled:r,onClick:c=>c.stopPropagation(),children:[l&&e.jsx("div",{className:"w-2 h-2 rounded-full shrink-0",style:{backgroundColor:l.color}}),e.jsx("span",{className:"max-w-[80px] truncate",children:(l==null?void 0:l.name)||"Move"}),e.jsx(Ja,{className:"h-3 w-3 shrink-0"})]})}),e.jsx(Md,{align:"end",className:"w-48 z-50 bg-popover",onClick:c=>c.stopPropagation(),children:s.map(c=>{const d=c.icon&&R3e[c.icon]||Bp,u=c.id===t;return e.jsxs(Na,{onClick:()=>o(c),className:Tt("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(oa,{className:"h-4 w-4 text-primary"})]},c.id)})})]})}const QPn={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"}},JPn={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 hVt({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 C,A;const u=dV(),h=QPn[s.deal_type],m=JPn[s.priority],p=j.useMemo(()=>s.target_close_date?r2(mu(s.target_close_date),new Date):null,[s.target_close_date]),x=p!==null&&p<0,g=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 P=s.contract_date?mu(s.contract_date):new Date;return r2(P,mu(T))},[s]),b=l&&!s.scorecard_transaction_id,v=!!s.scorecard_transaction_id,N=T=>T?new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(T):null;return e.jsxs(_e,{className:Tt("cursor-pointer transition-all duration-200 hover:shadow-md hover:border-primary/30 group overflow-hidden",n&&"opacity-50 rotate-2 shadow-xl",x&&"border-red-200 bg-red-50/30",b&&"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:Tt("h-1 w-full",m.stripe),"aria-hidden":!0}),e.jsxs(Oe,{className:"p-3 space-y-2.5",children:[o&&e.jsxs("div",{className:"flex items-center gap-1.5 -mt-0.5 mb-1",children:[e.jsxs(Ea,{className:"h-4 w-4",children:[e.jsx(ki,{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($e,{variant:"outline",className:Tt("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:[(C=s.contact.first_name)==null?void 0:C[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(Dc,{className:"h-3 w-3 text-primary shrink-0"}),e.jsx("span",{className:"text-primary truncate",children:"Linked to Listing Exchange"})]}),b&&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(pl,{className:"h-3 w-3 shrink-0"}),e.jsx("span",{className:"truncate font-medium",children:"Add to Scorecard"})]}),v&&l&&e.jsxs("div",{className:"flex items-center gap-1.5 text-xs text-green-600 dark:text-green-400",children:[e.jsx(Fr,{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(Xu,{className:"h-3 w-3 text-muted-foreground shrink-0"}),e.jsxs("span",{className:Tt("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(sa,{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(qd,{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=bb(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(Jh,{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(z7t,{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:Tt("flex items-center gap-1 px-1.5 py-0.5 rounded text-[10px]",m.color),children:[e.jsx("div",{className:Tt("w-1.5 h-1.5 rounded-full",m.dot)}),e.jsx("span",{className:"capitalize",children:s.priority})]})}),i&&u&&r&&a?e.jsx(uVt,{stages:r,currentStageId:s.stage_id||"",onStageSelect:(T,P)=>a(s.id,T,P)}):s.target_close_date?e.jsxs("div",{className:Tt("flex items-center gap-1 text-[10px]",x&&"text-red-600",g&&!x&&"text-amber-600",!x&&!g&&"text-muted-foreground"),children:[x?e.jsx(xo,{className:"h-3 w-3"}):e.jsx(ia,{className:"h-3 w-3"}),e.jsx("span",{children:x?`${Math.abs(p)}d overdue`:g?`${p}d left`:Hs(mu(s.target_close_date),"MMM d")})]}):null]})]})]})}function eIn({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,x]=j.useState(!1),g=t.reduce((C,A)=>C+(A.expected_price||0),0),y=t.reduce((C,A)=>C+(A.expected_commission||0),0),b=t.reduce((C,A)=>C+(bb(A)||0),0),v=C=>C>=1e6?`$${(C/1e6).toFixed(1)}M`:C>=1e3?`$${(C/1e3).toFixed(0)}K`:`$${C.toFixed(0)}`,N=s.icon&&R3e[s.icon]||Bp;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:()=>x(!1),"aria-label":`Expand ${s.name}`,className:"text-muted-foreground transition-colors hover:text-foreground",children:e.jsx(Ja,{className:"h-4 w-4"})}),e.jsx($e,{variant:"secondary",className:"px-1.5 text-[10px]",children:t.length}),e.jsx("span",{className:"mt-1 whitespace-nowrap text-xs font-semibold",style:{writingMode:"vertical-rl",color:s.color},children:s.name})]}):e.jsxs("div",{ref:m,className:Tt("flex flex-col h-full min-w-[280px] max-w-[320px] bg-muted/30 rounded-xl border border-border/50 transition-all duration-200",o&&"border-primary/50 bg-primary/5 ring-2 ring-primary/20"),onDragOver:C=>i(C,s.id),onDrop:C=>l(C,s.id),children:[e.jsxs("div",{className:"p-3 border-b border-border/50 shrink-0",style:{borderTopColor:s.color,borderTopWidth:3},children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"w-7 h-7 rounded-lg flex items-center justify-center",style:{backgroundColor:`${s.color}20`},children:e.jsx(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($e,{variant:"secondary",className:"text-xs font-medium px-2",children:t.length}),e.jsx("button",{onClick:()=>x(!0),"aria-label":`Collapse ${s.name}`,className:"rounded p-0.5 text-muted-foreground transition-colors hover:bg-accent hover:text-foreground",children:e.jsx(Ic,{className:"h-3.5 w-3.5"})})]})]}),g>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:v(g)}),e.jsx("span",{children:"•"}),e.jsxs("span",{children:[v(y)," GCI"]}),b>0&&b!==y&&e.jsxs(e.Fragment,{children:[e.jsx("span",{children:"•"}),e.jsxs("span",{className:"text-teal-600 dark:text-teal-400",children:[v(b)," Net"]})]})]})]}),e.jsx(Oi,{className:"flex-1 p-2",children:e.jsxs("div",{className:"space-y-2",children:[t.map(C=>e.jsx("div",{draggable:!0,onDragStart:A=>{A.dataTransfer.effectAllowed="move",a(C.id,s.id)},children:e.jsx(hVt,{deal:C,onClick:()=>n(C),isWonStage:c,ownerInfo:(d==null?void 0:d(C))||null,tags:u[C.id]||[],overdueTaskCount:h[C.id]||0})},C.id)),t.length===0&&e.jsxs("div",{className:"py-8 px-4 text-center text-muted-foreground text-sm",children:[e.jsx("p",{className:"mb-2",children:"No deals yet"}),e.jsx("p",{className:"text-xs",children:"Drag deals here or add new"})]})]})}),e.jsx("div",{className:"p-2 border-t border-border/50 shrink-0",children:e.jsxs($,{variant:"ghost",size:"sm",className:"w-full justify-start text-muted-foreground hover:text-foreground",onClick:()=>r(s.id),children:[e.jsx(sn,{className:"h-4 w-4 mr-2"}),"Add Deal"]})})]})}function tIn({formData:s,onChange:t,isEditing:n}){const{isAdmin:r}=_s(),[a,i]=j.useState(s.portal_enabled);if(!r)return e.jsxs("div",{className:"border rounded-lg p-4 opacity-60",children:[e.jsx("div",{className:"flex items-center justify-between",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(dn,{className:"h-4 w-4 text-primary"}),e.jsx("h4",{className:"font-medium text-sm",children:"Client Portal"}),e.jsx($e,{variant:"secondary",className:"text-xs",children:"Coming Soon"})]})}),e.jsx("p",{className:"text-xs text-muted-foreground mt-2",children:"Give your clients a premium, real-time view of their transaction — coming soon!"})]});const l=o=>{t({...s,...o})};return e.jsx(uv,{open:a,onOpenChange:i,children:e.jsxs("div",{className:"border rounded-lg",children:[e.jsxs(hv,{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(dn,{className:"h-4 w-4 text-primary"}),e.jsx("h4",{className:"font-medium text-sm",children:"Client Portal"}),s.portal_enabled&&e.jsx($e,{className:"text-xs bg-emerald-500/10 text-emerald-600 border-emerald-200",variant:"outline",children:"Enabled"})]}),e.jsx(_o,{className:Tt("h-4 w-4 text-muted-foreground transition-transform",a&&"rotate-180")})]}),e.jsx(mv,{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(se,{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(Tn,{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(se,{className:"text-sm font-medium",children:"Portal Visibility"}),e.jsxs(wb,{value:s.visibility,onValueChange:o=>l({visibility:o}),className:"grid grid-cols-2 gap-3",children:[e.jsxs("label",{className:Tt("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(rh,{value:"private"}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(Ad,{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:Tt("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(rh,{value:"public"}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(Gl,{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(ui,{id:"require_onboarding",checked:s.require_onboarding,onCheckedChange:o=>l({require_onboarding:!!o}),className:"mt-0.5"}),e.jsxs("div",{children:[e.jsx(se,{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(ui,{id:"allow_spouse",checked:s.allow_spouse,onCheckedChange:o=>l({allow_spouse:!!o})}),e.jsx(se,{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(se,{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(se,{className:"text-xs text-muted-foreground",children:"Client Full Name"}),e.jsx(be,{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(se,{className:"text-xs text-muted-foreground",children:"Email"}),e.jsx(be,{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(se,{className:"text-xs text-muted-foreground",children:"Phone"}),e.jsx(be,{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(se,{className:"text-xs text-muted-foreground",children:"Preferred Invite Method"}),e.jsxs(vs,{value:s.invite_method,onValueChange:o=>l({invite_method:o}),children:[e.jsx(gs,{children:e.jsx(bs,{})}),e.jsxs(ys,{children:[e.jsx(Ye,{value:"email",children:"Email"}),e.jsxs(Ye,{value:"sms",disabled:!s.client_phone,children:["SMS ",!s.client_phone&&"(add phone first)"]})]})]})]})]})]})]})]})})]})})}const sIn=[{value:"buyer",label:"Buyer"},{value:"seller",label:"Seller"},{value:"dual",label:"Dual Agency"},{value:"referral",label:"Referral"},{value:"lease",label:"Lease"}],nIn=[{value:"low",label:"Low"},{value:"medium",label:"Medium"},{value:"high",label:"High"},{value:"urgent",label:"Urgent"}];function rIn({open:s,onOpenChange:t,deal:n,defaultStageId:r}){const{data:a}=gte(),{data:i}=M1(),{data:l}=b6t(),o=QCe(),c=iVt(),d=oVt(),u=LYe(),[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,x]=j.useState(""),[g,y]=j.useState(!1),[b,v]=j.useState(!1),[N,C]=j.useState({first_name:"",last_name:"",email:"",phone:""}),A=(l==null?void 0:l.filter(W=>((n==null?void 0:n.listing_id)===W.id,!0)))||[],[T,P]=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 W,V,K,Q,J,ce,ue,ne,ee,le;s&&(n?(P({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:((W=n.expected_price)==null?void 0:W.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:((Q=n.team_split_pct)==null?void 0:Q.toString())||"",referral_fee_pct:((J=n.referral_fee_pct)==null?void 0:J.toString())||"",franchise_fee_pct:((ce=n.franchise_fee_pct)==null?void 0:ce.toString())||"",transaction_fee:((ue=n.transaction_fee)==null?void 0:ue.toString())||"",bonus_amount:((ne=n.bonus_amount)==null?void 0:ne.toString())||"",commission_calc_method:n.commission_calc_method||"standard",target_close_date:n.target_close_date?mu(n.target_close_date):void 0,contract_date:n.contract_date?mu(n.contract_date):void 0,listing_date:n.listing_date?mu(n.listing_date):void 0,priority:n.priority,probability:n.probability.toString(),notes:n.notes||""}),n.contact&&x(`${n.contact.first_name} ${n.contact.last_name}`)):(P({deal_name:"",deal_type:"buyer",stage_id:r||((ee=a==null?void 0:a[0])==null?void 0:ee.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(((le=a==null?void 0:a.find(he=>{var ve;return he.id===(r||((ve=a==null?void 0:a[0])==null?void 0:ve.id))}))==null?void 0:le.default_probability)??50),notes:""}),x(""),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(W=>{var le,he,ve,ge,fe;const V=p.toLowerCase().trim();if(!V)return!0;const K=((le=W.first_name)==null?void 0:le.toLowerCase())||"",Q=((he=W.last_name)==null?void 0:he.toLowerCase())||"",J=((ve=W.email)==null?void 0:ve.toLowerCase())||"",ce=((fe=(ge=W.phone)==null?void 0:ge.toLowerCase)==null?void 0:fe.call(ge))||"",ue=`${K} ${Q}`.trim(),ne=`${Q} ${K}`.trim();if(ue.includes(V)||ne.includes(V)||K.includes(V)||Q.includes(V)||J.includes(V)||ce.includes(V))return!0;const ee=V.split(/\s+/).filter(Boolean);return ee.length>1?ee.every(je=>K.includes(je)||Q.includes(je)||J.includes(je)||ce.includes(je)):!1}).slice(0,8),I=()=>{const W=parseFloat(T.expected_price)||0,V=parseFloat(T.commission_percentage)||0;return W*(V/100)},D=()=>{const W=I(),V=parseFloat(T.bonus_amount)||0;if(!W)return V>0?V:null;const K=parseFloat(T.brokerage_split_pct)||0,Q=parseFloat(T.team_split_pct)||0,J=parseFloat(T.referral_fee_pct)||0,ce=parseFloat(T.franchise_fee_pct)||0,ue=parseFloat(T.transaction_fee)||0,ne=parseFloat(T.bonus_amount)||0;if(T.commission_calc_method==="referral_first"){let le=W;J&&(le-=W*J/100);let he=le;return K&&(he-=le*K/100),Q&&(he-=W*Q/100),ce&&(he-=W*ce/100),ue&&(he-=ue),Math.max(0,he)+ne}let ee=W;return K&&(ee=ee*((100-K)/100)),Q&&(ee=ee*((100-Q)/100)),J&&(ee=ee-W*J/100),ce&&(ee=ee-W*ce/100),ue&&(ee=ee-ue),Math.max(0,ee)+ne},B=async W=>{var V,K,Q;if(W.preventDefault(),!T.deal_name.trim()){ae.error("Please enter a deal name");return}try{const J={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:((Q=T.listing_date)==null?void 0:Q.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,...J}),ae.success("Deal updated successfully");else{const ce=await c.mutateAsync(J);if(ae.success("Deal created successfully"),h.portal_enabled&&(ce!=null&&ce.id))try{await u.mutateAsync({deal_id:ce.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}),ae.success("Client portal created!")}catch{ae.error("Deal created, but portal setup failed")}}t(!1)}catch{ae.error("Failed to save deal")}},q=c.isPending||d.isPending;return e.jsx(Os,{open:s,onOpenChange:t,children:e.jsxs(Rs,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsxs(Us,{children:[e.jsx(zs,{children:n?"Edit Deal":"Add New Deal"}),e.jsx(Sr,{children:n?"Update the deal details below.":"Enter the details for your new deal."})]}),e.jsxs("form",{onSubmit:B,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(se,{htmlFor:"deal_name",children:"Deal Name *"}),e.jsx(be,{id:"deal_name",value:T.deal_name,onChange:W=>P(V=>({...V,deal_name:W.target.value})),placeholder:"e.g., Smith Family - 123 Main St"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Deal Type"}),e.jsxs(vs,{value:T.deal_type,onValueChange:W=>P(V=>({...V,deal_type:W})),children:[e.jsx(gs,{children:e.jsx(bs,{})}),e.jsx(ys,{children:sIn.map(W=>e.jsx(Ye,{value:W.value,children:W.label},W.value))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Stage"}),e.jsxs(vs,{value:T.stage_id||"none",onValueChange:W=>{const V=W==="none"?"":W,K=a==null?void 0:a.find(Q=>Q.id===V);P(Q=>({...Q,stage_id:V,probability:typeof(K==null?void 0:K.default_probability)=="number"?String(K.default_probability):Q.probability}))},children:[e.jsx(gs,{children:e.jsx(bs,{placeholder:"Select stage"})}),e.jsxs(ys,{children:[e.jsx(Ye,{value:"none",children:"No Stage"}),a==null?void 0:a.map(W=>e.jsx(Ye,{value:W.id,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"w-2 h-2 rounded-full",style:{backgroundColor:W.color}}),W.name]})},W.id))]})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Link to Contact"}),e.jsxs("div",{className:"relative",children:[e.jsx(Vr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(be,{value:p,onChange:W=>{x(W.target.value),y(!0),v(!1),W.target.value||P(V=>({...V,contact_id:""}))},onFocus:()=>y(!0),placeholder:"Search contacts...",className:"pl-9"}),g&&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(W=>e.jsxs("button",{type:"button",className:"w-full px-3 py-2 text-left hover:bg-muted flex items-center gap-2",onClick:()=>{P(V=>({...V,contact_id:W.id})),x(`${W.first_name} ${W.last_name}`),y(!1)},children:[e.jsx(Lo,{className:"h-4 w-4 text-muted-foreground"}),e.jsxs("span",{children:[W.first_name," ",W.last_name]}),W.email&&e.jsx("span",{className:"text-xs text-muted-foreground ml-auto",children:W.email})]},W.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 W=p.trim().split(/\s+/);C({first_name:W[0]||"",last_name:W.slice(1).join(" ")||"",email:"",phone:""}),v(!0),y(!1)},children:[e.jsx(il,{className:"h-4 w-4"}),e.jsxs("span",{children:['Create new contact "',p.trim(),'"']})]})]})]}),b&&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(il,{className:"h-3.5 w-3.5"}),"Quick Add Contact"]}),e.jsx($,{type:"button",variant:"ghost",size:"sm",className:"h-6 px-2 text-xs",onClick:()=>v(!1),children:"Cancel"})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsx(be,{placeholder:"First name *",value:N.first_name,onChange:W=>C(V=>({...V,first_name:W.target.value})),className:"h-8 text-sm"}),e.jsx(be,{placeholder:"Last name",value:N.last_name,onChange:W=>C(V=>({...V,last_name:W.target.value})),className:"h-8 text-sm"}),e.jsx(be,{placeholder:"Email",type:"email",value:N.email,onChange:W=>C(V=>({...V,email:W.target.value})),className:"h-8 text-sm"}),e.jsx(be,{placeholder:"Phone",type:"tel",value:N.phone,onChange:W=>C(V=>({...V,phone:W.target.value})),className:"h-8 text-sm"})]}),e.jsx($,{type:"button",size:"sm",className:"w-full h-8",disabled:!N.first_name.trim()||o.isPending,onClick:async()=>{try{const W=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});W&&(P(V=>({...V,contact_id:W.id})),x(`${W.first_name} ${W.last_name||""}`.trim()),v(!1))}catch{}},children:o.isPending?e.jsxs(e.Fragment,{children:[e.jsx(Ht,{className:"h-3.5 w-3.5 mr-1 animate-spin"})," Creating..."]}):e.jsxs(e.Fragment,{children:[e.jsx(il,{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(se,{className:"flex items-center gap-2",children:[e.jsx(Dc,{className:"h-4 w-4"}),"Link to Listing Exchange"]}),e.jsxs(vs,{value:T.listing_id||"none",onValueChange:W=>{const V=W==="none"?"":W,K=A.find(Q=>Q.id===V);P(K?Q=>{var J;return{...Q,listing_id:V,deal_type:"seller",property_address:K.property_address||Q.property_address,city:K.city||Q.city,state:K.state||Q.state,expected_price:((J=K.price)==null?void 0:J.toString())||Q.expected_price}}:Q=>({...Q,listing_id:V}))},children:[e.jsx(gs,{children:e.jsx(bs,{placeholder:"Select a listing to sync status..."})}),e.jsxs(ys,{children:[e.jsx(Ye,{value:"none",children:"None"}),A.map(W=>e.jsx(Ye,{value:W.id,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{children:W.property_address||`${W.city}, ${W.state}`}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:["$",(W.price/1e3).toFixed(0),"K"]})]})},W.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(se,{htmlFor:"property_address",children:"Address"}),e.jsx(be,{id:"property_address",value:T.property_address,onChange:W=>P(V=>({...V,property_address:W.target.value})),placeholder:"123 Main Street"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"city",children:"City"}),e.jsx(be,{id:"city",value:T.city,onChange:W=>P(V=>({...V,city:W.target.value}))})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"state",children:"State"}),e.jsx(be,{id:"state",value:T.state,onChange:W=>P(V=>({...V,state:W.target.value})),maxLength:2,placeholder:"TX"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"zip_code",children:"ZIP"}),e.jsx(be,{id:"zip_code",value:T.zip_code,onChange:W=>P(V=>({...V,zip_code:W.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(se,{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(be,{id:"expected_price",type:"number",value:T.expected_price,onChange:W=>P(V=>({...V,expected_price:W.target.value})),className:"pl-7",placeholder:"500000"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"commission_percentage",children:"Commission %"}),e.jsxs("div",{className:"relative",children:[e.jsx(be,{id:"commission_percentage",type:"number",step:"0.1",value:T.commission_percentage,onChange:W=>P(V=>({...V,commission_percentage:W.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(se,{children:"Expected GCI"}),e.jsx(be,{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(se,{className:"text-xs whitespace-nowrap",children:"Calculation Method:"}),e.jsxs(vs,{value:T.commission_calc_method,onValueChange:W=>P(V=>({...V,commission_calc_method:W})),children:[e.jsx(gs,{className:"h-7 text-xs",children:e.jsx(bs,{})}),e.jsxs(ys,{children:[e.jsx(Ye,{value:"standard",children:"Standard (all splits on GCI)"}),e.jsx(Ye,{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(se,{className:"text-xs",children:"Brokerage Split"}),e.jsxs("div",{className:"relative",children:[e.jsx(be,{type:"number",step:"1",min:"0",max:"100",value:T.brokerage_split_pct,onChange:W=>P(V=>({...V,brokerage_split_pct:W.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(se,{className:"text-xs",children:"Team Split"}),e.jsxs("div",{className:"relative",children:[e.jsx(be,{type:"number",step:"1",min:"0",max:"100",value:T.team_split_pct,onChange:W=>P(V=>({...V,team_split_pct:W.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(se,{className:"text-xs",children:"Referral Fee"}),e.jsxs("div",{className:"relative",children:[e.jsx(be,{type:"number",step:"1",min:"0",max:"100",value:T.referral_fee_pct,onChange:W=>P(V=>({...V,referral_fee_pct:W.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(se,{className:"text-xs",children:"Franchise Fee"}),e.jsxs("div",{className:"relative",children:[e.jsx(be,{type:"number",step:"1",min:"0",max:"100",value:T.franchise_fee_pct,onChange:W=>P(V=>({...V,franchise_fee_pct:W.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(se,{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(be,{type:"number",step:"1",min:"0",value:T.transaction_fee,onChange:W=>P(V=>({...V,transaction_fee:W.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(se,{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(be,{type:"number",step:"1",min:"0",value:T.bonus_amount,onChange:W=>P(V=>({...V,bonus_amount:W.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(se,{className:"text-xs",children:"Net to Agent"}),e.jsx(be,{value:D()?`$${Math.round(D()).toLocaleString()}`:"-",disabled:!0,className:"bg-muted h-8 text-sm font-semibold"})]})]})]})]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsx("h4",{className:"font-medium text-sm",children:"Dates & Status"}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Target Close Date"}),e.jsxs(Sc,{children:[e.jsx(Cc,{asChild:!0,children:e.jsxs($,{variant:"outline",className:Tt("w-full justify-start text-left font-normal",!T.target_close_date&&"text-muted-foreground"),children:[e.jsx(ia,{className:"mr-2 h-4 w-4"}),T.target_close_date?Hs(T.target_close_date,"PPP"):"Pick a date"]})}),e.jsx(xc,{className:"w-auto p-0",align:"start",children:e.jsx(y1,{mode:"single",selected:T.target_close_date,onSelect:W=>P(V=>({...V,target_close_date:W})),initialFocus:!0,className:"pointer-events-auto"})})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Contract Date"}),e.jsxs(Sc,{children:[e.jsx(Cc,{asChild:!0,children:e.jsxs($,{variant:"outline",className:Tt("w-full justify-start text-left font-normal",!T.contract_date&&"text-muted-foreground"),children:[e.jsx(ia,{className:"mr-2 h-4 w-4"}),T.contract_date?Hs(T.contract_date,"PPP"):"Pick a date"]})}),e.jsx(xc,{className:"w-auto p-0",align:"start",children:e.jsx(y1,{mode:"single",selected:T.contract_date,onSelect:W=>P(V=>({...V,contract_date:W})),initialFocus:!0,className:"pointer-events-auto"})})]})]}),(T.deal_type==="seller"||T.deal_type==="dual")&&!T.listing_id&&e.jsxs("div",{className:"space-y-2 col-span-2",children:[e.jsx(se,{children:"Listing Date (for Days on Market)"}),e.jsxs(Sc,{children:[e.jsx(Cc,{asChild:!0,children:e.jsxs($,{variant:"outline",className:Tt("w-full justify-start text-left font-normal",!T.listing_date&&"text-muted-foreground"),children:[e.jsx(ia,{className:"mr-2 h-4 w-4"}),T.listing_date?Hs(T.listing_date,"PPP"):"Pick a date"]})}),e.jsx(xc,{className:"w-auto p-0",align:"start",children:e.jsx(y1,{mode:"single",selected:T.listing_date,onSelect:W=>P(V=>({...V,listing_date:W})),initialFocus:!0,className:"pointer-events-auto"})})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Used to calculate Days on Market. Auto-filled for linked listings."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Priority"}),e.jsxs(vs,{value:T.priority,onValueChange:W=>P(V=>({...V,priority:W})),children:[e.jsx(gs,{children:e.jsx(bs,{})}),e.jsx(ys,{children:nIn.map(W=>e.jsx(Ye,{value:W.value,children:W.label},W.value))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Win Probability"}),e.jsxs("div",{className:"relative",children:[e.jsx(be,{type:"number",min:"0",max:"100",value:T.probability,onChange:W=>P(V=>({...V,probability:W.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(se,{htmlFor:"notes",children:"Notes"}),e.jsx(Is,{id:"notes",value:T.notes,onChange:W=>P(V=>({...V,notes:W.target.value})),placeholder:"Add any additional notes about this deal...",rows:3})]}),!n&&e.jsx(tIn,{formData:h,onChange:m}),e.jsxs("div",{className:"flex justify-end gap-3 pt-4 border-t",children:[e.jsx($,{type:"button",variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsxs($,{type:"submit",disabled:q,children:[q&&e.jsx(Ht,{className:"h-4 w-4 mr-2 animate-spin"}),n?"Update Deal":"Create Deal"]})]})]})]})})}function aIn({dealId:s}){const t=Za(),n=ts(),[r,a]=j.useState(""),[i,l]=j.useState(!1),{data:o=[]}=ht({queryKey:["deal-tags",s],queryFn:async()=>{const{data:x,error:g}=await U.from("deal_tags").select("*").eq("deal_id",s).order("created_at");if(g)throw g;return x},enabled:!!s}),{data:c=[]}=ht({queryKey:["all-deal-tags",t],queryFn:async()=>{if(!t)return[];const{data:x,error:g}=await U.from("deal_tags").select("tag").eq("owner_user_id",t);if(g)throw g;return[...new Set(x.map(b=>b.tag))].sort()},enabled:!!t}),d=yt({mutationFn:async x=>{if(!t)throw new Error("Not authenticated");const{error:g}=await U.from("deal_tags").insert({deal_id:s,owner_user_id:t,tag:x.trim()});if(g)throw g},onSuccess:()=>{n.invalidateQueries({queryKey:["deal-tags",s]}),n.invalidateQueries({queryKey:["all-deal-tags"]}),a("")}}),u=yt({mutationFn:async x=>{const{error:g}=await U.from("deal_tags").delete().eq("id",x);if(g)throw g},onSuccess:()=>{n.invalidateQueries({queryKey:["deal-tags",s]})}}),h=()=>{const x=r.trim();x&&(o.some(g=>g.tag.toLowerCase()===x.toLowerCase())||d.mutate(x))},m=o.map(x=>x.tag.toLowerCase()),p=c.filter(x=>x.toLowerCase().includes(r.toLowerCase())&&!m.includes(x.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(x=>e.jsxs($e,{variant:"secondary",className:"gap-1 text-xs",children:[x.tag,e.jsx("button",{type:"button",onClick:()=>u.mutate(x.id),className:"ml-0.5 hover:text-destructive",children:e.jsx(pr,{className:"h-3 w-3"})})]},x.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(sn,{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(be,{value:r,onChange:x=>a(x.target.value),onKeyDown:x=>{x.key==="Enter"&&(x.preventDefault(),h()),x.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(x=>e.jsx("button",{type:"button",className:"w-full px-3 py-2 text-left text-xs hover:bg-muted active:bg-muted",onClick:g=>{g.preventDefault(),d.mutate(x)},children:x},x))})]})]})}function iIn(s){return ht({queryKey:["deal-files",s],queryFn:async()=>{const{data:t,error:n}=await U.from("deal_files").select("*").eq("deal_id",s).order("created_at",{ascending:!1});if(n)throw n;return t},enabled:!!s})}function oIn(){const s=Za(),t=ts();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 U.storage.from("deal-files").upload(i,r);if(l)throw l;const{data:o,error:c}=await U.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 lIn(){const s=ts();return yt({mutationFn:async({fileId:t,storagePath:n,dealId:r})=>{await U.storage.from("deal-files").remove([n]);const{error:a}=await U.from("deal_files").delete().eq("id",t);if(a)throw a;return r},onSuccess:t=>{s.invalidateQueries({queryKey:["deal-files",t]})}})}function cIn(){const s=ts();return yt({mutationFn:async({fileId:t,visible:n,dealId:r})=>{const{error:a}=await U.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 dIn(s){const{data:t,error:n}=await U.storage.from("deal-files").createSignedUrl(s,3600);if(n)throw n;return t.signedUrl}const wvt={text:"Short Text",textarea:"Long Text",dropdown:"Dropdown",toggle:"Yes / No"};function mVt({open:s,onOpenChange:t}){const{data:n,isLoading:r}=lSn(),a=cSn(),i=dSn(),l=uSn(),[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),ae.success("Question added")}catch{ae.error("Failed to add question")}},x=async v=>{try{await l.mutateAsync(v),ae.success("Question removed")}catch{ae.error("Failed to remove question")}},g=async(v,N)=>{try{await i.mutateAsync({id:v,is_required:N})}catch{ae.error("Failed to update question")}},y=()=>{h.trim()&&(u(v=>({...v,options:[...v.options,h.trim()]})),m(""))},b=v=>{u(N=>({...N,options:N.options.filter((C,A)=>A!==v)}))};return e.jsx(Os,{open:s,onOpenChange:t,children:e.jsxs(Rs,{className:"max-w-md max-h-[85vh] flex flex-col",children:[e.jsxs(Us,{children:[e.jsx(zs,{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(Oi,{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(Ht,{className:"h-5 w-5 animate-spin text-muted-foreground"})}),n==null?void 0:n.map(v=>{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($p,{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:v.question_text}),e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[e.jsx($e,{variant:"secondary",className:"text-xs",children:wvt[v.field_type]||v.field_type}),v.is_required&&e.jsx($e,{variant:"outline",className:"text-xs",children:"Required"})]}),v.field_type==="dropdown"&&((N=v.options)==null?void 0:N.length)>0&&e.jsxs("p",{className:"text-xs text-muted-foreground mt-1",children:["Options: ",v.options.join(", ")]})]}),e.jsxs("div",{className:"flex items-center gap-1 flex-shrink-0",children:[e.jsx(Tn,{checked:v.is_required,onCheckedChange:C=>g(v.id,C),className:"scale-75"}),e.jsx($,{variant:"ghost",size:"icon",className:"h-7 w-7 text-muted-foreground hover:text-destructive",onClick:()=>x(v.id),children:e.jsx(Pn,{className:"h-3.5 w-3.5"})})]})]})},v.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(se,{className:"text-sm font-medium",children:"Question"}),e.jsx(be,{value:d.question_text,onChange:v=>u(N=>({...N,question_text:v.target.value})),className:"mt-1",placeholder:"e.g., Do you have a home to sell first?",autoFocus:!0})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-sm font-medium",children:"Answer Type"}),e.jsx("div",{className:"flex flex-wrap gap-1.5 mt-1.5",children:Object.entries(wvt).map(([v,N])=>e.jsx("button",{type:"button",onClick:()=>u(C=>({...C,field_type:v,options:[]})),className:`px-3 py-1.5 rounded-full text-xs font-medium border transition-colors ${d.field_type===v?"bg-primary text-primary-foreground border-primary":"bg-background text-muted-foreground border-input hover:border-primary/50"}`,children:N},v))})]}),d.field_type==="dropdown"&&e.jsxs("div",{children:[e.jsx(se,{className:"text-sm font-medium",children:"Options"}),e.jsxs("div",{className:"space-y-1.5 mt-1.5",children:[d.options.map((v,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:v}),e.jsx("button",{onClick:()=>b(N),className:"text-muted-foreground hover:text-destructive",children:e.jsx(pr,{className:"h-3.5 w-3.5"})})]},N)),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(be,{value:h,onChange:v=>m(v.target.value),onKeyDown:v=>v.key==="Enter"&&(v.preventDefault(),y()),placeholder:"Add option...",className:"h-8 text-sm"}),e.jsx($,{variant:"outline",size:"sm",onClick:y,disabled:!h.trim(),className:"h-8",children:e.jsx(sn,{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(Tn,{checked:d.is_required,onCheckedChange:v=>u(N=>({...N,is_required:v}))}),e.jsx(se,{className:"text-xs text-muted-foreground",children:"Required"})]})}),e.jsxs("div",{className:"flex gap-2 pt-1",children:[e.jsx($,{variant:"outline",size:"sm",onClick:()=>c(!1),className:"flex-1",children:"Cancel"}),e.jsxs($,{size:"sm",onClick:p,disabled:!d.question_text.trim()||a.isPending,className:"flex-1",children:[a.isPending?e.jsx(Ht,{className:"h-3 w-3 mr-1 animate-spin"}):null,"Add Question"]})]})]})]})}),e.jsxs("div",{className:"flex justify-between pt-4 border-t shrink-0",children:[o?e.jsx("div",{}):e.jsxs($,{variant:"outline",size:"sm",onClick:()=>c(!0),children:[e.jsx(sn,{className:"h-4 w-4 mr-1"})," Add Question"]}),e.jsx($,{variant:"ghost",size:"sm",onClick:()=>t(!1),children:"Done"})]})]})})}function uIn({override:s,onChange:t}){const n=Za(),{data:r}=qTt(),[a,i]=j.useState(null),l=d=>t({...s,...d}),o=async(d,u)=>{if(n){if(d.size>5*1024*1024){ae.error("Image must be under 5MB");return}i(u);try{const h=await VTt(n,d,`${u}`);l(u==="logo"?{logo_url:h}:{cover_photo_url:h})}catch(h){ae.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(dn,{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(jvt,{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(jvt,{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(Nvt,{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(Nvt,{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(se,{className:"text-sm font-medium",children:"Tagline"}),e.jsx(be,{value:s.tagline||"",onChange:d=>l({tagline:d.target.value||null}),placeholder:(r==null?void 0:r.tagline)||"Your trusted real estate advisor",maxLength:80,className:"mt-1"})]}),c&&e.jsxs($,{variant:"ghost",size:"sm",onClick:()=>t({}),className:"text-xs text-muted-foreground hover:text-destructive",children:[e.jsx(Pn,{className:"h-3 w-3 mr-1"}),"Clear all overrides"]})]})}function jvt({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(se,{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:Tt("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(Jl,{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(Ht,{className:"h-3.5 w-3.5 animate-spin"}):e.jsx(si,{className:"h-3.5 w-3.5"}),t?"Replace":"Override"]})]}),t&&e.jsx($,{variant:"ghost",size:"sm",onClick:i,className:"text-muted-foreground hover:text-destructive",children:e.jsx(Pn,{className:"h-3.5 w-3.5"})})]})]})]})}function Nvt({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(se,{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:Tt("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(be,{value:t||"",onChange:l=>r(l.target.value||null),placeholder:n||"#406E71",className:"border-0 h-7 px-1 focus-visible:ring-0 text-xs font-mono"}),t&&e.jsx($,{variant:"ghost",size:"sm",onClick:()=>r(null),className:"h-6 w-6 p-0 text-muted-foreground hover:text-destructive",children:e.jsx(Pn,{className:"h-3 w-3"})})]})]})}function hIn({portalId:s,agentUserId:t}){const n=ts(),{data:r,isLoading:a}=ht({queryKey:["portal-vendor-manage",s,t],queryFn:async()=>{const{data:h}=await U.from("profiles").select("brokerage_id").eq("id",t).maybeSingle(),m=h==null?void 0:h.brokerage_id,p=U.from("vendors").select("*").eq("is_active",!0),x=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:g,error:y},{data:b},{data:v}]=await Promise.all([x.order("sort_order",{ascending:!0}).order("name",{ascending:!0}),U.from("agent_vendor_selections").select("vendor_id, is_visible").eq("agent_user_id",t),U.from("portal_vendor_overrides").select("vendor_id, is_visible").eq("portal_id",s)]);if(y)throw y;const N=new Map;(b||[]).forEach(A=>N.set(A.vendor_id,A.is_visible));const C=new Map;return(v||[]).forEach(A=>C.set(A.vendor_id,A.is_visible)),{vendors:g||[],selMap:N,overrideMap:C}}}),i=yt({mutationFn:async({vendorId:h,isVisible:m})=>{const{data:p}=await U.from("portal_vendor_overrides").select("id").eq("portal_id",s).eq("vendor_id",h).maybeSingle();if(p){const{error:x}=await U.from("portal_vendor_overrides").update({is_visible:m}).eq("id",p.id);if(x)throw x}else{const{error:x}=await U.from("portal_vendor_overrides").insert({portal_id:s,vendor_id:h,is_visible:m});if(x)throw x}},onSuccess:()=>{n.invalidateQueries({queryKey:["portal-vendor-manage",s,t]}),n.invalidateQueries({queryKey:["portal-vendors",s]})},onError:h=>ae.error(h.message)});if(a)return e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx(Ht,{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(IN,{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=Pq.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(Oi,{className:"h-[400px] rounded-lg border",children:e.jsx("div",{className:"divide-y",children:l.map(h=>{const m=d(h);return e.jsxs("div",{className:"flex items-center gap-3 p-3",children:[e.jsx("div",{className:"w-10 h-10 rounded-lg bg-muted border flex items-center justify-center overflow-hidden shrink-0",children:h.logo_url?e.jsx("img",{src:h.logo_url,alt:h.name,className:"w-full h-full object-cover"}):e.jsx("span",{className:"text-sm font-semibold text-muted-foreground",children:h.name.charAt(0)})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("p",{className:"font-medium text-sm truncate",children:h.company||h.name}),e.jsx($e,{variant:"outline",className:"text-[10px] shrink-0",children:u(h.category)}),h.owner_type==="brokerage"&&e.jsx($e,{variant:"secondary",className:"text-[10px] shrink-0",children:"Brokerage"}),h.is_required&&e.jsx($e,{className:"text-[10px] shrink-0",children:"Required"})]}),h.company&&h.name&&e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:h.name})]}),e.jsx(Tn,{checked:m,disabled:h.is_required||i.isPending,onCheckedChange:p=>i.mutate({vendorId:h.id,isVisible:p})})]},h.id)})})})]})}function mIn({portalId:s,ownerId:t,clientEmail:n,linkedPortalId:r,onLink:a}){const[i,l]=j.useState(""),[o,c]=j.useState(!1),{data:d,isLoading:u}=ht({queryKey:["all-owner-portals",t],queryFn:async()=>{const{data:x,error:g}=await U.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(g)throw g;return x},enabled:o||!!r}),h=j.useMemo(()=>!r||!d?null:d.find(x=>x.id===r),[r,d]),m=j.useMemo(()=>!d||!n?[]:d.filter(x=>{var g;return((g=x.client_email)==null?void 0:g.toLowerCase())===n.toLowerCase()&&x.id!==s}),[d,n,s]),p=j.useMemo(()=>{if(!d||!i.trim())return[];const x=i.toLowerCase();return d.filter(g=>{var b,v,N,C;const y=g.deal_pipeline;return((b=g.client_name)==null?void 0:b.toLowerCase().includes(x))||((v=g.client_email)==null?void 0:v.toLowerCase().includes(x))||((N=y==null?void 0:y.deal_name)==null?void 0:N.toLowerCase().includes(x))||((C=y==null?void 0:y.property_address)==null?void 0:C.toLowerCase().includes(x))})},[d,i]);if(r){const x=h==null?void 0:h.deal_pipeline;return e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{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(Dc,{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)||(x==null?void 0:x.deal_name)||"Linked Portal"}),e.jsxs("p",{className:"text-xs text-muted-foreground truncate",children:[(x==null?void 0:x.deal_type)==="listing"?"🏠 Listing":"🔑 Purchase"," · ",(x==null?void 0:x.property_address)||"No address"]})]}),e.jsxs($,{variant:"ghost",size:"sm",className:"text-xs text-destructive hover:text-destructive shrink-0",onClick:()=>a(null),children:[e.jsx(AR,{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(se,{className:"text-sm font-medium",children:"Link Another Transaction"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Combine buy + sell into one portal"})]}),e.jsxs($,{variant:"outline",size:"sm",className:"text-xs",onClick:()=>c(!o),children:[e.jsx(Dc,{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(x=>{const g=x.deal_pipeline;return e.jsxs("button",{onClick:()=>a(x.id),className:"w-full flex items-center gap-2 bg-amber-50 border border-amber-200 rounded-lg p-2.5 hover:bg-amber-100 transition-colors text-left",children:[e.jsx($e,{variant:"outline",className:"text-[10px] shrink-0 bg-amber-100 border-amber-300 text-amber-700",children:(g==null?void 0:g.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:(g==null?void 0:g.deal_name)||x.client_name}),e.jsx("p",{className:"text-[11px] text-muted-foreground truncate",children:g==null?void 0:g.property_address})]}),e.jsx(Dc,{className:"h-3.5 w-3.5 text-amber-600 shrink-0"})]},x.id)})]}),o&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"relative",children:[e.jsx(Vr,{className:"absolute left-2.5 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-muted-foreground"}),e.jsx(be,{value:i,onChange:x=>l(x.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(Ht,{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(x=>{const g=x.deal_pipeline;return e.jsxs("button",{onClick:()=>{a(x.id),c(!1),l("")},className:"w-full flex items-center gap-2 border rounded-lg p-2 hover:bg-muted/50 transition-colors text-left",children:[e.jsx($e,{variant:"outline",className:"text-[10px] shrink-0",children:(g==null?void 0:g.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:(g==null?void 0:g.deal_name)||x.client_name}),e.jsx("p",{className:"text-[11px] text-muted-foreground truncate",children:x.client_email})]})]},x.id)})}),i&&p.length===0&&!u&&e.jsx("p",{className:"text-xs text-muted-foreground text-center py-3",children:"No portals found"})]})]})}function cXe({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=F5(),h=()=>{i("record"),o(0),d(0)},m=x=>{!x&&(a==="uploading"||a==="processing")||(r(x),x||h())},p=j.useCallback(async(x,g)=>{i("uploading");try{const y="Card Video",{videoId:b,libraryId:v}=await Z6(y),{uploadUrl:N,apiKey:C}=await X6(b),A=new XMLHttpRequest;A.upload.onprogress=q=>{q.lengthComputable&&o(q.loaded/q.total*100)},await new Promise((q,W)=>{A.onload=()=>A.status>=200&&A.status<300?q():W(new Error("Upload failed")),A.onerror=()=>W(new Error("Upload failed")),A.open("PUT",N),A.setRequestHeader("AccessKey",C),A.send(x)}),i("processing");let T=0;const P=Date.now(),M=9e4,I=`https://iframe.mediadelivery.net/embed/${v}/${b}`;for(;T<4;){if(await new Promise(W=>setTimeout(W,3e3)),Date.now()-P>M){const W=x.size/1048576;await u.mutateAsync({bunny_video_id:b,playback_url:`https://iframe.mediadelivery.net/play/${v}/${b}`,file_size_mb:W,title:y,contact_id:s||void 0,status:"processing",touch_type:"video"}),t(I),ae.success("Video saved — still encoding. It will be ready shortly."),i("done"),setTimeout(()=>{r(!1),h()},1500);return}const q=await o2(b);if(T=q.status,d(q.encodeProgress||0),T===5||T===6)throw new Error("Video processing failed")}const D=await o2(b),B=(D.storageSize||x.size)/(1024*1024);await u.mutateAsync({bunny_video_id:b,contact_id:s||void 0,playback_url:D.directPlayUrl||I,thumbnail_url:D.thumbnailUrl,preview_url:D.previewUrl||null,duration_seconds:D.length||g,file_size_mb:B,title:y,status:"ready",touch_type:"video"}),t(I),ae.success("Video recorded & added to your library!"),i("done"),setTimeout(()=>{r(!1),h()},1500)}catch(y){console.error("Recording upload error:",y),ae.error("Failed to process video. Please try again."),i("record")}},[s,t,u]);return e.jsxs(Os,{open:n,onOpenChange:m,children:[e.jsx(Ko,{asChild:!0,children:e.jsxs($,{variant:"outline",size:"sm",className:"gap-1.5 w-full",children:[e.jsx(Xr,{className:"h-3.5 w-3.5"}),"Record Video"]})}),e.jsxs(Rs,{className:"sm:max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsx(Us,{children:e.jsx(zs,{children:"Record a Video for Your Card"})}),a==="record"&&e.jsx(J6,{maxDurationSeconds:600,onRecordingComplete:p,onError:x=>ae.error(x)}),a==="uploading"&&e.jsxs("div",{className:"flex flex-col items-center gap-4 py-12",children:[e.jsx(Ht,{className:"h-10 w-10 animate-spin text-primary"}),e.jsx("p",{className:"text-sm font-medium",children:"Uploading video..."}),e.jsx(Ki,{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(Ht,{className:"h-10 w-10 animate-spin text-primary"}),e.jsx("p",{className:"text-sm font-medium",children:"Processing video..."}),e.jsx(Ki,{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(Ro,{className:"h-12 w-12 text-emerald-500"}),e.jsx("p",{className:"text-sm font-medium",children:"Video attached to your card!"})]})]})]})}const pIn=s=>`portal-settings-draft:${s}`;function dXe({open:s,onOpenChange:t,portal:n,dealOwnerId:r}){const a=uV(),[i,l]=j.useState(!1),o=j.useMemo(()=>pIn(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||""),[x,g]=j.useState(n.inspection_date||""),[y,b]=j.useState(n.appraisal_date||""),[v,N]=j.useState(n.welcome_message||""),[C,A]=j.useState(n.review_url||""),[T,P]=j.useState(n.show_post_close_tips),[M,I]=j.useState(n.notify_client),[D,B]=j.useState(n.require_onboarding),[q,W]=j.useState(n.allow_spouse),[V,K]=j.useState(n.visibility),[Q,J]=j.useState(n.stage_mapping||[]),[ce,ue]=j.useState(null),[ne,ee]=j.useState(n.linked_portal_id||null),[le,he]=j.useState(n.referral_enabled??!0),[ve,ge]=j.useState(n.referral_reward_text||""),[fe,je]=j.useState(n.referral_cta_headline||""),[Ee,Me]=j.useState(n.homeowner_hub_video_url||""),[De,ze]=j.useState(n.branding_override||{}),ke=()=>{h(n.next_step_text||""),p(n.next_step_video_url||""),g(n.inspection_date||""),b(n.appraisal_date||""),N(n.welcome_message||""),A(n.review_url||""),P(n.show_post_close_tips),I(n.notify_client),B(n.require_onboarding),W(n.allow_spouse),K(n.visibility),J(n.stage_mapping||[]),ee(n.linked_portal_id||null),he(n.referral_enabled??!0),ge(n.referral_reward_text||""),je(n.referral_cta_headline||""),Me(n.homeowner_hub_video_url||""),ze(n.branding_override||{})};j.useEffect(()=>{d(!1);const Ke=localStorage.getItem(o);if(Ke)try{const Ze=JSON.parse(Ke);h(Ze.nextStepText||""),p(Ze.nextStepVideo||""),g(Ze.inspectionDate||""),b(Ze.appraisalDate||""),N(Ze.welcomeMessage||""),A(Ze.reviewUrl||""),P(!!Ze.showPostClose),I(!!Ze.notifyClient),B(!!Ze.requireOnboarding),W(!!Ze.allowSpouse),K(Ze.visibility||n.visibility),J(Ze.stageMapping||[]),ee(Ze.linkedPortalId??null),he(Ze.referralEnabled??!0),ge(Ze.referralRewardText||""),je(Ze.referralCtaHeadline||""),Me(Ze.homeownerHubVideoUrl||""),ze(Ze.brandingOverride||{}),d(!0);return}catch{localStorage.removeItem(o)}ke(),d(!0)},[o,n]),j.useEffect(()=>{if(!c)return;const Ke={nextStepText:u,nextStepVideo:m,inspectionDate:x,appraisalDate:y,welcomeMessage:v,reviewUrl:C,showPostClose:T,notifyClient:M,requireOnboarding:D,allowSpouse:q,visibility:V,stageMapping:Q,linkedPortalId:ne,referralEnabled:le,referralRewardText:ve,referralCtaHeadline:fe,homeownerHubVideoUrl:Ee,brandingOverride:De};u!==(n.next_step_text||"")||m!==(n.next_step_video_url||"")||x!==(n.inspection_date||"")||y!==(n.appraisal_date||"")||v!==(n.welcome_message||"")||C!==(n.review_url||"")||T!==n.show_post_close_tips||M!==n.notify_client||D!==n.require_onboarding||q!==n.allow_spouse||V!==n.visibility||JSON.stringify(Q)!==JSON.stringify(n.stage_mapping||[])||ne!==(n.linked_portal_id||null)||le!==(n.referral_enabled??!0)||ve!==(n.referral_reward_text||"")||fe!==(n.referral_cta_headline||"")||Ee!==(n.homeowner_hub_video_url||"")||JSON.stringify(De)!==JSON.stringify(n.branding_override||{})?localStorage.setItem(o,JSON.stringify(Ke)):localStorage.removeItem(o)},[u,m,x,y,v,C,T,M,D,q,V,Q,ne,le,ve,fe,Ee,De,o,c,n]);const Xe=()=>{localStorage.removeItem(o),ke()},Se=async()=>{try{await a.mutateAsync({id:n.id,next_step_text:u||null,next_step_video_url:m||null,inspection_date:x||null,appraisal_date:y||null,welcome_message:v||null,review_url:C||null,show_post_close_tips:T,notify_client:M,require_onboarding:D,allow_spouse:q,visibility:V,stage_mapping:Q.length>0?Q:null,linked_portal_id:ne,referral_enabled:le,referral_reward_text:ve||null,referral_cta_headline:fe||null,homeowner_hub_video_url:Ee||null,branding_override:Object.values(De).some(Ze=>Ze!=null&&Ze!=="")?De:null});const Ke=n.linked_portal_id;ne&&ne!==Ke&&await U.from("client_portals").update({linked_portal_id:n.id}).eq("id",ne),!ne&&Ke&&await U.from("client_portals").update({linked_portal_id:null}).eq("id",Ke),localStorage.removeItem(o),ae.success("Portal settings saved"),t(!1)}catch{ae.error("Failed to save settings")}},Re=()=>{J([...Q,{label:""}])},Ae=Ke=>{J(Q.filter((Ze,Ue)=>Ue!==Ke)),ce===Ke&&ue(null)},Be=(Ke,Ze,Ue)=>{const et=[...Q];et[Ke]={...et[Ke],[Ze]:Ue},J(et)},qe=()=>{const Ze=ZCe(null).map(Ue=>({label:Ue.label,description:Ue.description,stageId:void 0}));J(Ze)};return e.jsxs(e.Fragment,{children:[e.jsx(Os,{open:s,onOpenChange:t,children:e.jsxs(Rs,{className:"max-w-lg max-h-[85vh] flex flex-col",children:[e.jsx(Us,{children:e.jsx(zs,{children:"Portal Settings"})}),e.jsxs(ua,{defaultValue:"general",className:"flex-1 overflow-hidden flex flex-col",children:[e.jsxs(ha,{className:"grid grid-cols-5 shrink-0",children:[e.jsx(Qt,{value:"general",children:"General"}),e.jsx(Qt,{value:"timeline",children:"Timeline"}),e.jsx(Qt,{value:"content",children:"Content"}),e.jsx(Qt,{value:"vendors",children:"Vendors"}),e.jsx(Qt,{value:"branding",children:"Branding"})]}),e.jsxs("div",{className:"flex-1 overflow-y-auto mt-4 min-h-0",children:[e.jsxs(Jt,{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(se,{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(Ke=>e.jsx("button",{onClick:()=>K(Ke),className:`px-3 py-1.5 rounded-full text-xs font-medium border transition-colors ${V===Ke?"bg-primary text-primary-foreground border-primary":"bg-background text-muted-foreground border-input hover:border-primary/50"}`,children:Ke.charAt(0).toUpperCase()+Ke.slice(1)},Ke))})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(se,{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(Tn,{checked:D,onCheckedChange:B})]}),D&&e.jsxs("div",{className:"flex items-center justify-between pl-4 border-l-2 border-primary/20",children:[e.jsxs("div",{children:[e.jsx(se,{className:"text-sm font-medium",children:"Custom Questions"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Manage intake form questions"})]}),e.jsx($,{variant:"outline",size:"sm",onClick:()=>l(!0),className:"text-xs",children:"Manage"})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(se,{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(Tn,{checked:q,onCheckedChange:W})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(se,{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(Tn,{checked:T,onCheckedChange:P})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(se,{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(Tn,{checked:M,onCheckedChange:I})]}),e.jsx("div",{className:"border-t pt-4",children:e.jsx(mIn,{portalId:n.id,ownerId:r,clientEmail:n.client_email,linkedPortalId:ne,onLink:ee})}),e.jsx("div",{children:e.jsx(be,{type:"date",value:x,onChange:Ke=>g(Ke.target.value),className:"mt-1"})}),e.jsxs("div",{children:[e.jsx(se,{className:"text-sm font-medium",children:"Appraisal Date"}),e.jsx(be,{type:"date",value:y,onChange:Ke=>b(Ke.target.value),className:"mt-1"})]})]}),e.jsx(Jt,{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(se,{className:"text-sm font-medium",children:"Client-Facing Stages"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Customize the client-friendly stage labels shown on the portal timeline"})]}),e.jsx($,{variant:"outline",size:"sm",onClick:qe,className:"text-xs",children:"Auto-map"})]}),e.jsx("p",{className:"text-[11px] text-muted-foreground bg-muted/50 rounded-md p-2",children:'💡 These labels are what clients see. Click "More" on any stage to customize its description and add a video link. Internal pipeline stages are automatically translated to friendly names.'}),Q.length===0&&e.jsxs("div",{className:"border border-dashed rounded-lg p-4 text-center",children:[e.jsx("p",{className:"text-xs text-muted-foreground mb-2",children:"No custom mapping — using default client-friendly journey stages"}),e.jsx($,{variant:"outline",size:"sm",onClick:qe,children:"Customize journey labels"})]}),e.jsx("div",{className:"space-y-2 mt-2",children:Q.map((Ke,Ze)=>e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx($p,{className:"h-4 w-4 text-muted-foreground/50 flex-shrink-0"}),e.jsx(be,{value:Ke.label,onChange:Ue=>Be(Ze,"label",Ue.target.value),placeholder:`Stage ${Ze+1} label`,className:"flex-1 h-9 text-sm"}),e.jsx($,{variant:"ghost",size:"sm",className:"h-9 px-2 text-xs text-muted-foreground hover:text-primary",onClick:()=>ue(ce===Ze?null:Ze),children:ce===Ze?"Less":"More"}),e.jsx($,{variant:"ghost",size:"icon",className:"h-9 w-9 text-muted-foreground hover:text-destructive",onClick:()=>Ae(Ze),children:e.jsx(Pn,{className:"h-3.5 w-3.5"})})]}),ce===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(se,{className:"text-xs text-muted-foreground",children:"Description"}),e.jsx("textarea",{value:Ke.description||"",onChange:Ue=>Be(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(se,{className:"text-xs text-muted-foreground",children:"Video"}),Ke.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:Ke.video_url.length>40?Ke.video_url.slice(0,40)+"...":Ke.video_url}),e.jsx($,{variant:"ghost",size:"sm",className:"h-7 text-xs text-destructive hover:text-destructive",onClick:()=>Be(Ze,"video_url",""),children:"Remove"})]}):e.jsxs("div",{className:"mt-1 flex items-center gap-1.5",children:[e.jsx(cXe,{onVideoReady:Ue=>Be(Ze,"video_url",Ue)}),e.jsx(hF,{userId:r,onSelect:Ue=>Be(Ze,"video_url",Ue),triggerSize:"sm",triggerClassName:"gap-1.5 shrink-0 flex-1"}),e.jsxs($,{variant:"ghost",size:"sm",className:"gap-1 text-xs text-muted-foreground flex-1",onClick:()=>{const Ue=prompt("Paste a YouTube or Loom URL:");Ue&&Be(Ze,"video_url",Ue)},children:[e.jsx(kc,{className:"h-3 w-3"}),"Paste URL"]})]})]})]})]},Ze))}),Q.length>0&&e.jsxs($,{variant:"outline",size:"sm",onClick:Re,className:"mt-2 text-xs w-full",children:[e.jsx(sn,{className:"h-3 w-3 mr-1"})," Add Stage"]})]})}),e.jsxs(Jt,{value:"content",className:"space-y-4 mt-0 px-1",children:[e.jsxs("div",{children:[e.jsx(se,{className:"text-sm font-medium",children:"Welcome Message"}),e.jsx("textarea",{value:v,onChange:Ke=>N(Ke.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(se,{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:Ke=>h(Ke.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(se,{className:"text-sm font-medium",children:"Next Step Video (optional)"}),e.jsx(be,{value:m,onChange:Ke=>p(Ke.target.value),className:"mt-1",placeholder:"YouTube or Loom URL"})]}),e.jsxs("div",{children:[e.jsx(se,{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(be,{value:C,onChange:Ke=>A(Ke.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(se,{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(se,{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(Tn,{checked:le,onCheckedChange:he})]}),le&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{children:[e.jsx(se,{className:"text-sm font-medium",children:"Headline"}),e.jsx(be,{value:fe,onChange:Ke=>je(Ke.target.value),className:"mt-1",placeholder:"Know someone buying or selling?"})]}),e.jsxs("div",{children:[e.jsx(se,{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(be,{value:ve,onChange:Ke=>ge(Ke.target.value),className:"mt-1",placeholder:"$250 gift card • Donation to your charity • Closing gift"})]}),e.jsxs("div",{children:[e.jsx(se,{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(be,{value:Ee,onChange:Ke=>Me(Ke.target.value),className:"mt-1",placeholder:"YouTube, Loom, or direct video URL"})]})]})]})]}),e.jsx(Jt,{value:"vendors",className:"space-y-4 mt-0 px-1",children:e.jsx(hIn,{portalId:n.id,agentUserId:r})}),e.jsx(Jt,{value:"branding",className:"space-y-4 mt-0 px-1",children:e.jsx(uIn,{override:De,onChange:ze})})]})]}),e.jsxs("div",{className:"flex justify-between gap-2 pt-4 border-t shrink-0",children:[e.jsx($,{variant:"ghost",onClick:Xe,children:"Reset Draft"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx($,{variant:"outline",onClick:()=>t(!1),children:"Close"}),e.jsxs($,{onClick:Se,disabled:a.isPending,children:[a.isPending?e.jsx(Ht,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(Jo,{className:"h-4 w-4 mr-2"}),"Save Settings"]})]})]})]})}),e.jsx(mVt,{open:i,onOpenChange:l})]})}const fIn=s=>`portal-update-draft:${s}`;function uXe({open:s,onOpenChange:t,portalId:n,portalSlug:r,notifyClient:a}){const i=j.useMemo(()=>fIn(n),[n]),[l,o]=j.useState(""),[c,d]=j.useState(""),[u,h]=j.useState(""),[m,p]=j.useState(!1),[x,g]=j.useState(a??!1),[y,b]=j.useState(!1),v=W7t();j.useEffect(()=>{b(!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),g(typeof T.sendNotification=="boolean"?T.sendNotification:a??!1),b(!0);return}catch{localStorage.removeItem(i)}o(""),d(""),h(""),p(!1),g(a??!1),b(!0)},[i,a]),j.useEffect(()=>{if(!y)return;const A={title:l,content:c,videoUrl:u,isStageChange:m,sendNotification:x};l.trim()||c.trim()||u.trim()||m||x!==(a??!1)?localStorage.setItem(i,JSON.stringify(A)):localStorage.removeItem(i)},[l,c,u,m,x,y,i,a]);const N=()=>{localStorage.removeItem(i),o(""),d(""),h(""),p(!1),g(a??!1)},C=async()=>{if(l.trim())try{if(await v.mutateAsync({portal_id:n,title:l.trim(),content:c.trim()||void 0,video_url:u.trim()||void 0,is_stage_change:m}),x&&r)try{const A=f5(r);await U.functions.invoke("send-portal-notification",{body:{portal_id:n,update_title:l.trim(),update_content:c.trim()||null,portal_url:A}}),ae.success("Update posted & client notified")}catch(A){console.error("Notification failed:",A),ae.success("Update posted (notification failed to send)")}else ae.success("Update posted to portal");N(),t(!1)}catch{ae.error("Failed to post update")}};return e.jsx(Os,{open:s,onOpenChange:t,children:e.jsxs(Rs,{className:"max-w-md",children:[e.jsx(Us,{children:e.jsx(zs,{children:"Post Portal Update"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(se,{className:"text-sm font-medium",children:"Title *"}),e.jsx(be,{value:l,onChange:A=>o(A.target.value),className:"mt-1",placeholder:"Inspection cleared!"})]}),e.jsxs("div",{children:[e.jsx(se,{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(se,{className:"text-sm font-medium",children:"Video URL (optional)"}),e.jsxs("div",{className:"relative mt-1",children:[e.jsx(be,{value:u,onChange:A=>h(A.target.value),className:"pl-9",placeholder:"YouTube or Loom link"}),e.jsx(Xr,{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:()=>g(!x),className:`px-3 py-1.5 rounded-full text-xs font-medium border transition-colors flex items-center gap-1.5 ${x?"bg-blue-500/10 text-blue-700 border-blue-200":"bg-background text-muted-foreground border-input"}`,children:[x?e.jsx(Dx,{className:"h-3 w-3"}):e.jsx(e5,{className:"h-3 w-3"}),x?"Notify Client":"No Notification"]})]})]}),e.jsxs("div",{className:"flex justify-between gap-2 pt-2",children:[e.jsx($,{variant:"ghost",onClick:N,children:"Clear Draft"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx($,{variant:"outline",onClick:()=>t(!1),children:"Close"}),e.jsxs($,{onClick:C,disabled:!l.trim()||v.isPending,children:[v.isPending?e.jsx(Ht,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(Br,{className:"h-4 w-4 mr-2"}),"Post Update"]})]})]})]})})}function hXe({open:s,onOpenChange:t,portal:n,dealName:r}){const a=uV(),{isGmailConnected:i,gmailEmail:l}=ux(),[o,c]=j.useState(n.client_name||""),[d,u]=j.useState(n.client_email||""),[h,m]=j.useState(!1),[p,x]=j.useState(!1),g=f5(n.slug),y=o.split(" ")[0]||"there",b=`Your Transaction Portal – ${r}`,v=`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: ${g} 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(g),x(!0),setTimeout(()=>x(!1),2e3),ae.success("Portal link copied!")},C=async()=>{if(!d.trim()){ae.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 U.functions.invoke("gmail-send",{body:{to:d,subject:b,body:v.replace(/\n/g,"
")}});if(T){let P="";try{const M=T==null?void 0:T.context;if(M&&typeof M.json=="function"){const I=await M.json();P=(I==null?void 0:I.message)||(I==null?void 0:I.error)||""}}catch{}throw new Error(P||T.message||"Failed to send invite")}ae.success(`Invite sent to ${d}`),t(!1)}catch(T){ae.error(T.message||"Failed to send invite")}finally{m(!1)}},A=()=>{const T=encodeURIComponent(b),P=encodeURIComponent(v);window.open(`mailto:${d}?subject=${T}&body=${P}`,"_blank"),a.mutateAsync({id:n.id,client_name:o||null,client_email:d||null,invite_sent_at:new Date().toISOString(),invite_method:"email"}).catch(()=>{})};return e.jsx(Os,{open:s,onOpenChange:t,children:e.jsxs(Rs,{className:"max-w-md",children:[e.jsx(Us,{children:e.jsx(zs,{children:"Invite Client to Portal"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(se,{className:"text-sm font-medium",children:"Client Name"}),e.jsx(be,{value:o,onChange:T=>c(T.target.value),className:"mt-1",placeholder:"John Doe"})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-sm font-medium",children:"Client Email"}),e.jsx(be,{type:"email",value:d,onChange:T=>u(T.target.value),className:"mt-1",placeholder:"john@example.com"})]}),e.jsxs("div",{children:[e.jsx(se,{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:g})}),e.jsx($,{variant:"outline",size:"icon",onClick:N,className:"shrink-0",children:p?e.jsx(oa,{className:"h-4 w-4 text-emerald-600"}):e.jsx(Ca,{className:"h-4 w-4"})})]})]}),e.jsxs("div",{className:"space-y-2 pt-2 border-t",children:[i?e.jsxs($,{onClick:C,disabled:h||!d.trim(),className:"w-full",children:[h?e.jsx(Ht,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(nn,{className:"h-4 w-4 mr-2"}),"Send via Gmail (",l,")"]}):e.jsxs($,{onClick:A,disabled:!d.trim(),className:"w-full",variant:"outline",children:[e.jsx(Tr,{className:"h-4 w-4 mr-2"}),"Open in Email App"]}),e.jsxs($,{variant:"ghost",onClick:N,className:"w-full text-muted-foreground",children:[e.jsx(Ca,{className:"h-4 w-4 mr-2"}),"Just Copy Link"]})]})]})]})})}function xIn({deal:s}){const{isAdmin:t,user:n}=_s(),{data:r,isLoading:a}=iSn(s.id),i=LYe(),l=uV(),[o,c]=j.useState(!1),[d,u]=j.useState(!1),[h,m]=j.useState(!1),[p,x]=j.useState(!1),g=`portal-management-ui:${s.id}`;if(j.useEffect(()=>{const T=sessionStorage.getItem(g);if(T)try{const P=JSON.parse(T);u(!!P.settingsOpen),m(!!P.composerOpen),x(!!P.inviteOpen)}catch{sessionStorage.removeItem(g)}},[g]),j.useEffect(()=>{d||h||p?sessionStorage.setItem(g,JSON.stringify({settingsOpen:d,composerOpen:h,inviteOpen:p})):sessionStorage.removeItem(g)},[d,h,p,g]),a)return e.jsx("div",{className:"border rounded-lg p-4",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(dn,{className:"h-4 w-4 text-primary"}),e.jsx("span",{className:"font-medium text-sm",children:"Client Portal"}),e.jsx(Ht,{className:"h-3 w-3 animate-spin ml-auto"})]})});const y=async()=>{var T,P;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:((P=s.contact)==null?void 0:P.phone)||void 0}),ae.success("Client portal enabled!")}catch{ae.error("Failed to create portal")}finally{c(!1)}},b=async T=>{if(r)try{await l.mutateAsync({id:r.id,is_enabled:T}),ae.success(T?"Portal enabled":"Portal disabled")}catch{ae.error("Failed to update portal")}},v=()=>{if(!r)return;const T=f5(r.slug);navigator.clipboard.writeText(T),ae.success("Portal link copied!")},N=()=>{if(!r)return;const T=f5(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(dn,{className:"h-4 w-4 text-primary"}),e.jsx("span",{className:"font-medium text-sm",children:"Client Portal"})]})}),e.jsx("p",{className:"text-xs text-muted-foreground mb-3",children:"Create a beautiful portal so your client can track their deal progress in real-time."}),e.jsxs($,{onClick:y,disabled:o,size:"sm",className:"w-full",children:[o?e.jsx(Ht,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(dn,{className:"h-4 w-4 mr-2"}),"Enable Client Portal"]})]});const C=f5(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(dn,{className:"h-4 w-4 text-primary"}),e.jsx("span",{className:"font-medium text-sm",children:"Client Portal"}),e.jsx($e,{variant:"outline",className:r.is_enabled?"text-xs bg-emerald-500/10 text-emerald-600 border-emerald-200":"text-xs bg-muted text-muted-foreground",children:r.is_enabled?"Active":"Disabled"})]}),e.jsx(Tn,{checked:r.is_enabled,onCheckedChange:b})]}),e.jsxs("div",{className:"space-y-1.5 mb-3",children:[e.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground",children:[e.jsx("span",{children:"Visibility:"}),e.jsx($e,{variant:"outline",className:"text-[10px] px-1.5 py-0",children:r.visibility==="private"?"Private":"Public"})]}),e.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground",children:[e.jsx("span",{children:"Onboarding:"}),e.jsx("span",{className:"text-foreground",children:r.require_onboarding?"Required":"Disabled"})]}),r.client_name&&e.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground",children:[e.jsx("span",{children:"Client:"}),e.jsx("span",{className:"text-foreground",children:r.client_name})]})]}),e.jsx("div",{className:"bg-muted/50 rounded-md p-2 mb-3",children:e.jsx("p",{className:"text-xs font-mono text-muted-foreground truncate",children:C})}),e.jsxs("div",{className:"grid grid-cols-3 gap-2 mb-2 w-full",children:[e.jsxs($,{variant:"outline",size:"sm",onClick:v,className:"text-xs w-full min-w-0 px-2",children:[e.jsx(Ca,{className:"h-3 w-3 mr-1 shrink-0"}),e.jsx("span",{className:"truncate",children:"Copy"})]}),e.jsxs($,{variant:"outline",size:"sm",onClick:N,className:"text-xs w-full min-w-0 px-2",children:[e.jsx(Tr,{className:"h-3 w-3 mr-1 shrink-0"}),e.jsx("span",{className:"truncate",children:"Preview"})]}),e.jsxs($,{variant:"outline",size:"sm",onClick:()=>x(!0),className:"text-xs w-full min-w-0 px-2",children:[e.jsx(Br,{className:"h-3 w-3 mr-1 shrink-0"}),e.jsx("span",{className:"truncate",children:"Invite"})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-2 w-full",children:[e.jsxs($,{variant:"ghost",size:"sm",onClick:()=>m(!0),className:"text-xs text-muted-foreground w-full min-w-0 px-2",children:[e.jsx(BS,{className:"h-3 w-3 mr-1 shrink-0"}),e.jsx("span",{className:"truncate",children:"Post Update"})]}),e.jsxs($,{variant:"ghost",size:"sm",onClick:()=>u(!0),className:"text-xs text-muted-foreground w-full min-w-0 px-2",children:[e.jsx(pc,{className:"h-3 w-3 mr-1 shrink-0"}),e.jsx("span",{className:"truncate",children:"Settings"})]})]}),e.jsxs(Wn,{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(Co,{className:"h-3 w-3"}),"View incoming referrals"]})]}),e.jsx(dXe,{open:d,onOpenChange:u,portal:r,dealOwnerId:A}),e.jsx(uXe,{open:h,onOpenChange:m,portalId:r.id,portalSlug:r.slug,notifyClient:r.notify_client}),e.jsx(hXe,{open:p,onOpenChange:x,portal:r,dealName:s.deal_name})]})}const gIn=["Client","Co-Buyer","Co-Seller","Spouse","Lender","Title Company","Inspector","Appraiser","Attorney","Contractor","Other"];function yIn(s){return ht({queryKey:["deal-contacts",s],queryFn:async()=>{const{data:t,error:n}=await U.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 vIn(){const s=ts();return yt({mutationFn:async({dealId:t,contactId:n,role:r})=>{const{data:a,error:i}=await U.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]}),ae.success("Contact linked to deal")},onError:t=>{var n;(n=t.message)!=null&&n.includes("duplicate")?ae.error("This contact is already linked to this deal"):ae.error("Failed to link contact")}})}function bIn(){const s=ts();return yt({mutationFn:async({id:t,dealId:n})=>{const{error:r}=await U.from("deal_contacts").delete().eq("id",t);if(r)throw r},onSuccess:(t,n)=>{s.invalidateQueries({queryKey:["deal-contacts",n.dealId]}),ae.success("Contact removed from deal")},onError:()=>{ae.error("Failed to remove contact")}})}function _In({dealId:s,primaryContactId:t}){const n=Vn(),{data:r,isLoading:a}=yIn(s),{data:i}=M1(),l=vIn(),o=bIn(),[c,d]=j.useState(!1),[u,h]=j.useState(""),[m,p]=j.useState("Client"),x=new Set((r==null?void 0:r.map(N=>N.contact_id))||[]);t&&x.add(t);const g=i==null?void 0:i.filter(N=>{var A,T,P;if(x.has(N.id))return!1;if(!u.trim())return!0;const C=u.toLowerCase();return((A=N.first_name)==null?void 0:A.toLowerCase().includes(C))||((T=N.last_name)==null?void 0:T.toLowerCase().includes(C))||((P=N.email)==null?void 0:P.toLowerCase().includes(C))}).slice(0,8),y=N=>{l.mutate({dealId:s,contactId:N,role:m}),d(!1),h("")},b=N=>{o.mutate({id:N,dealId:s})},v={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(qn,{className:"h-4 w-4"}),"Additional Contacts"]})}),e.jsxs(Sc,{open:c,onOpenChange:d,children:[e.jsx(Cc,{asChild:!0,children:e.jsxs($,{variant:"outline",size:"sm",className:"w-full text-muted-foreground",children:[e.jsx(sn,{className:"h-3.5 w-3.5 mr-1"}),"Link a contact (lender, spouse, vendor...)"]})}),e.jsx(xc,{className:"w-80 p-3",align:"start",children:e.jsx(kvt,{search:u,setSearch:h,selectedRole:m,setSelectedRole:p,filteredContacts:g,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(qn,{className:"h-4 w-4"}),"Linked Contacts",r&&r.length>0&&e.jsx($e,{variant:"secondary",className:"text-[10px] px-1.5",children:r.length})]}),e.jsxs(Sc,{open:c,onOpenChange:d,children:[e.jsx(Cc,{asChild:!0,children:e.jsx($,{variant:"ghost",size:"sm",className:"h-7 px-2",children:e.jsx(sn,{className:"h-3.5 w-3.5"})})}),e.jsx(xc,{className:"w-80 p-3",align:"end",children:e.jsx(kvt,{search:u,setSearch:h,selectedRole:m,setSelectedRole:p,filteredContacts:g,onAdd:y})})]})]}),e.jsx("div",{className:"space-y-1.5",children:r==null?void 0:r.map(N=>{var C,A,T,P,M,I,D,B;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=(C=N.contact)==null?void 0:C.first_name)==null?void 0:A[0],(P=(T=N.contact)==null?void 0:T.last_name)==null?void 0:P[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($e,{variant:"outline",className:`text-[10px] px-1.5 py-0 shrink-0 ${v[N.role]||v.Other}`,children:N.role}),e.jsxs("div",{className:"flex gap-0.5 opacity-0 group-hover:opacity-100 transition-opacity",children:[((D=N.contact)==null?void 0:D.phone)&&e.jsx($,{variant:"ghost",size:"icon",className:"h-6 w-6",asChild:!0,children:e.jsx("a",{href:`tel:${N.contact.phone}`,children:e.jsx(ya,{className:"h-3 w-3"})})}),((B=N.contact)==null?void 0:B.email)&&e.jsx($,{variant:"ghost",size:"icon",className:"h-6 w-6",asChild:!0,children:e.jsx("a",{href:`mailto:${N.contact.email}`,children:e.jsx(nn,{className:"h-3 w-3"})})}),e.jsx($,{variant:"ghost",size:"icon",className:"h-6 w-6 text-destructive",onClick:()=>b(N.id),children:e.jsx(Pn,{className:"h-3 w-3"})})]})]},N.id)})})]})}function kvt({search:s,setSearch:t,selectedRole:n,setSelectedRole:r,filteredContacts:a,onAdd:i}){return e.jsxs("div",{className:"space-y-3",children:[e.jsxs(vs,{value:n,onValueChange:r,children:[e.jsx(gs,{className:"h-8 text-sm",children:e.jsx(bs,{placeholder:"Role"})}),e.jsx(ys,{children:gIn.map(l=>e.jsx(Ye,{value:l,children:l},l))})]}),e.jsxs("div",{className:"relative",children:[e.jsx(Vr,{className:"absolute left-2 top-2.5 h-3.5 w-3.5 text-muted-foreground"}),e.jsx(be,{value:s,onChange:l=>t(l.target.value),placeholder:"Search contacts...",className:"pl-7 h-8 text-sm",autoFocus:!0})]}),e.jsx(Oi,{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 QW=[{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"}],wIn=[{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 jIn(){const s=ts();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 U.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 NIn(){const s=ts();return yt({mutationFn:async({dealId:t,completed:n})=>{const{error:r}=await U.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 kIn(){return ht({queryKey:["tc-playbooks"],queryFn:async()=>{const{data:s,error:t}=await U.from("tc_playbooks").select("*").eq("is_active",!0).order("sort_order");if(t)throw t;const{data:n,error:r}=await U.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 SIn(){const s=Za(),t=ts();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([U.from("deal_pipeline").select("*").eq("id",r).single(),U.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 U.from("deal_tasks").select("title").eq("deal_id",r),d=new Set((c||[]).map(x=>String(x.title).toLowerCase())),u=a,h=(x,g)=>{const y=x==="stage_entry"?null:u[x],b=y?new Date(`${y}T12:00:00`):new Date;return b.setDate(b.getDate()+(g||0)),b.toISOString().split("T")[0]},m=l.filter(x=>!d.has(String(x.title).toLowerCase())).map((x,g)=>({owner_user_id:s,deal_id:r,contact_id:u.contact_id,stage_id:u.stage_id,title:x.title,description:x.description,priority:x.priority,status:"todo",due_date:h(x.due_anchor,x.due_offset_days),sort_order:g}));if(m.length===0)return 0;const{error:p}=await U.from("deal_tasks").insert(m);if(p)throw p;return m.length},onSuccess:()=>{t.invalidateQueries({queryKey:["deal-tasks"]}),t.invalidateQueries({queryKey:["tc-dashboard"]})}})}function CIn(){const s=Za(),t=ts();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([U.from("tc_playbooks").select("deal_type").eq("id",n).single(),U.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 U.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 U.from("deal_task_templates").insert(d);if(u)throw u;return d.length},onSuccess:()=>{t.invalidateQueries({queryKey:["deal-task-templates"]})}})}function AIn(){const s=Za();return ht({queryKey:["tc-dashboard",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await U.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 U.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 mXe(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 aS(s){const t=mXe(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 EIn(s){return s===null?"none":s<0?"overdue":s===0?"today":s<=3?"soon":"upcoming"}const TIn={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 MIn(s){const t=mXe(s);return t?t.toLocaleDateString("en-US",{month:"short",day:"numeric"}):null}function Svt(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 LIn({deal:s,compact:t=!1}){const n=jIn(),r=NIn(),[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,x=()=>{const I={};QW.forEach(D=>{I[D.key]=(s==null?void 0:s[D.key])??""}),o(I),i(!0)},g=async()=>{try{await n.mutateAsync({dealId:s.id,dates:l}),ae.success("Transaction dates updated"),i(!1)}catch(I){ae.error((I==null?void 0:I.message)||"Could not save dates")}},y=async(I,D)=>{const B=p;u(I);try{await r.mutateAsync({dealId:s.id,completed:I}),ae.success(D)}catch(q){u(B),ae.error((q==null?void 0:q.message)||"Could not update milestone")}},b=j.useMemo(()=>QW.map(I=>{const D=(s==null?void 0:s[I.key])??null,B=aS(D),q=p.includes(I.key),W=D?q?"done":EIn(B):"none";return{...I,value:D,days:B,isDone:q,state:W}}),[s,p.join(",")]),v=b.filter(I=>I.value).length,N=b.filter(I=>I.state==="done").length,C=aS(s==null?void 0:s.target_close_date),A=b.filter(I=>I.value&&!I.isDone&&I.days!==null&&I.days>=0).sort((I,D)=>(I.days??0)-(D.days??0))[0],T=b.filter(I=>I.state==="overdue"),P=()=>{const I=Array.from(new Set([...p,...T.map(D=>D.key)]));y(I,"Past milestones marked complete")},M=(I,D)=>{const B=D?p.filter(q=>q!==I):[...p,I];y(B,D?"Marked as not complete":"Milestone completed")};return e.jsx(JN,{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(Xu,{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:C!==null?C>=0?`${C} day${C===1?"":"s"} to closing · ${N}/${v} milestones done`:`Closing was ${Math.abs(C)} day${Math.abs(C)===1?"":"s"} ago`:`${v} of ${QW.length} key dates set`})]})]}),e.jsxs(Sc,{open:a,onOpenChange:I=>I?x():i(!1),children:[e.jsx(Cc,{asChild:!0,children:e.jsxs($,{variant:"outline",size:"sm",className:"shrink-0 gap-1.5",children:[e.jsx(Ya,{className:"h-3.5 w-3.5"}),t?"":"Edit dates"]})}),e.jsxs(xc,{className:"w-80 p-4 max-h-[70vh] overflow-y-auto",align:"end",children:[e.jsx("p",{className:"text-sm font-semibold mb-3",children:"Key transaction dates"}),e.jsx("div",{className:"space-y-3",children:QW.map(I=>e.jsxs("div",{className:"space-y-1",children:[e.jsx(se,{htmlFor:`kd-${I.key}`,className:"text-xs text-muted-foreground",children:I.label}),e.jsx(be,{id:`kd-${I.key}`,type:"date",value:l[I.key]??"",onChange:D=>o(B=>({...B,[I.key]:D.target.value})),className:"h-9"})]},I.key))}),e.jsxs("div",{className:"flex justify-end gap-2 mt-4",children:[e.jsx($,{variant:"ghost",size:"sm",onClick:()=>i(!1),children:"Cancel"}),e.jsxs($,{size:"sm",onClick:g,disabled:n.isPending,children:[n.isPending?e.jsx(Ht,{className:"h-3.5 w-3.5 mr-1 animate-spin"}):e.jsx(oa,{className:"h-3.5 w-3.5 mr-1"}),"Save"]})]})]})]})]}),e.jsxs("div",{className:"p-3",children:[e.jsx("div",{className:"grid grid-cols-3 sm:grid-cols-3 gap-2",children:b.map(I=>{const D=!!I.value;return e.jsxs(Mx,{children:[e.jsx(Lx,{asChild:!0,children:e.jsxs("button",{type:"button",disabled:!D||r.isPending,onClick:()=>D&&M(I.key,I.isDone),className:Tt("relative text-left rounded-lg border px-2.5 py-2 transition-colors w-full",TIn[I.state],D&&"hover:brightness-105 cursor-pointer"),children:[e.jsx("p",{className:"text-[10px] uppercase tracking-wide opacity-70 truncate pr-4",children:I.short}),e.jsx("p",{className:"text-sm font-semibold leading-tight truncate",children:MIn(I.value)??"—"}),I.value&&e.jsx("p",{className:"text-[10px] opacity-80 truncate",children:Svt(I.state,I.days)}),D&&e.jsx("span",{className:Tt("absolute top-1.5 right-1.5 h-4 w-4 rounded-full border flex items-center justify-center",I.isDone?"bg-emerald-500 border-emerald-500 text-white":"border-current opacity-40"),children:I.isDone&&e.jsx(oa,{className:"h-2.5 w-2.5"})})]})}),e.jsx(tx,{side:"top",children:I.value?I.isDone?`${I.label} completed — click to reopen`:`Click to mark ${I.label} complete`:`${I.label} — not set`})]},I.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(cR,{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(mc,{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," · ",Svt(A.state,A.days)]}),T.length>0&&e.jsxs("button",{type:"button",onClick:P,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(cR,{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."}),v===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 PIn={Home:sa,FileSignature:RA,Handshake:IN,CalendarClock:Xu,Sparkles:dn,ClipboardCheck:n5},IIn={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 DIn(s,t){var a;const n=((a=wIn.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 pVt({open:s,onOpenChange:t,dealId:n,dealName:r}){const{data:a,isLoading:i}=kIn(),{data:l}=gte(),o=SIn(),c=CIn(),[d,u]=j.useState(null),[h,m]=j.useState({}),p=y=>{if(h[y.id])return h[y.id];const b=l==null?void 0:l.find(v=>{var N,C;return((N=v.name)==null?void 0:N.toLowerCase())===((C=y.target_stage_name)==null?void 0:C.toLowerCase())});return(b==null?void 0:b.id)??""},x=async y=>{if(n){u(y.id);try{const b=await o.mutateAsync({playbookId:y.id,dealId:n});ae.success(b>0?`Added ${b} task${b===1?"":"s"} to this deal`:"All tasks already exist on this deal"),b>0&&t(!1)}catch(b){ae.error((b==null?void 0:b.message)||"Could not apply playbook")}finally{u(null)}}},g=async y=>{const b=p(y);if(!b){ae.error("Pick which stage this playbook should trigger on");return}u(`install-${y.id}`);try{const v=await c.mutateAsync({playbookId:y.id,stageId:b});ae.success(v>0?`Automated — ${v} task${v===1?"":"s"} will now be created every time a deal reaches this stage`:"This playbook is already automated for that stage")}catch(v){ae.error((v==null?void 0:v.message)||"Could not automate playbook")}finally{u(null)}};return e.jsx(Os,{open:s,onOpenChange:t,children:e.jsxs(Rs,{className:"sm:max-w-2xl max-h-[85vh] flex flex-col p-0",children:[e.jsx(Us,{className:"p-6 pb-4 border-b",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"h-9 w-9 rounded-lg bg-primary/10 flex items-center justify-center",children:e.jsx(wf,{className:"h-4.5 w-4.5 text-primary"})}),e.jsxs("div",{children:[e.jsx(zs,{children:"Transaction Playbooks"}),e.jsx(Sr,{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(Oi,{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(Ht,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):e.jsx(JO,{type:"single",collapsible:!0,className:"space-y-3",children:(a||[]).map(y=>{const b=PIn[y.icon||"ClipboardCheck"]||n5,v=y.accent_color||"hsl(var(--primary))";return e.jsxs(D6,{value:y.id,className:"border rounded-xl px-0 overflow-hidden bg-card",children:[e.jsx(R6,{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:`${v}1a`},children:e.jsx(b,{className:"h-5 w-5",style:{color:v}})}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx("span",{className:"font-semibold text-sm",children:y.name}),e.jsxs($e,{variant:"secondary",className:"text-[10px]",children:[y.tasks.length," steps"]}),y.deal_type&&e.jsx($e,{variant:"outline",className:"text-[10px] capitalize",children:y.deal_type})]}),e.jsx("p",{className:"text-xs text-muted-foreground mt-0.5 line-clamp-1",children:y.description})]})]})}),e.jsxs(O6,{className:"px-4 pb-4",children:[e.jsx("div",{className:"space-y-1.5 mb-4",children:y.tasks.map((N,C)=>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:C+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:DIn(N.due_anchor,N.due_offset_days)})]}),e.jsx("span",{className:Tt("text-[10px] px-1.5 py-0.5 rounded-full shrink-0 capitalize",IIn[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($,{size:"sm",className:"gap-1.5",onClick:()=>x(y),disabled:d===y.id,children:[d===y.id?e.jsx(Ht,{className:"h-3.5 w-3.5 animate-spin"}):e.jsx(ox,{className:"h-3.5 w-3.5"}),"Add to this deal"]}),e.jsxs("div",{className:"flex gap-2 flex-1",children:[e.jsxs(vs,{value:p(y),onValueChange:N=>m(C=>({...C,[y.id]:N})),children:[e.jsx(gs,{className:"h-9 text-xs flex-1",children:e.jsx(bs,{placeholder:"Trigger stage"})}),e.jsx(ys,{children:(l||[]).map(N=>e.jsx(Ye,{value:N.id,children:N.name},N.id))})]}),e.jsxs($,{size:"sm",variant:"outline",className:"gap-1.5 shrink-0",onClick:()=>g(y),disabled:d===`install-${y.id}`,children:[d===`install-${y.id}`?e.jsx(Ht,{className:"h-3.5 w-3.5 animate-spin"}):e.jsx(Oz,{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(Fr,{className:"h-3 w-3"}),"Automating adds these steps to every future deal that reaches that stage."]})]})]},y.id)})})})})]})})}const RIn={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"}},OIn={note:Ji,call:ya,email:nn,meeting:ia,stage_change:Tr,task_completed:Fr,document:sa,system:Hr};function FIn({deal:s,open:t,onOpenChange:n,onEdit:r,onAddToScorecard:a,isWonStage:i}){var De,ze;const l=Vn(),{data:o,isLoading:c}=rPn((s==null?void 0:s.id)||""),{data:d,isLoading:u}=iPn((s==null?void 0:s.id)||""),h=aPn(),m=lPn(),p=oPn(),x=nPn(),{data:g,isLoading:y}=iIn((s==null?void 0:s.id)||""),b=oIn(),v=lIn(),N=cIn(),C=j.useRef(null),[A,T]=j.useState(""),[P,M]=j.useState(""),[I,D]=j.useState(!1),[B,q]=j.useState(!1),[W,V]=j.useState(!1);if(!s)return null;const K=RIn[s.deal_type],Q=(()=>{var Se;if(s.deal_type!=="seller"&&s.deal_type!=="dual")return null;const ke=((Se=s.listing)==null?void 0:Se.created_at)||s.listing_date;if(!ke)return null;const Xe=s.contract_date?mu(s.contract_date):new Date;return r2(Xe,mu(ke))})(),J=ke=>ke?new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(ke):"-",ce=async()=>{if(A.trim())try{await h.mutateAsync({deal_id:s.id,activity_type:"note",title:"Note added",description:A}),T(""),ae.success("Note added")}catch{ae.error("Failed to add note")}},ue=async()=>{if(P.trim())try{await m.mutateAsync({deal_id:s.id,title:P,sort_order:((d==null?void 0:d.length)||0)+1}),M(""),ae.success("Task added")}catch{ae.error("Failed to add task")}},ne=async(ke,Xe)=>{try{await p.mutateAsync({id:ke,is_completed:Xe,deal_id:s.id})}catch{ae.error("Failed to update task")}},ee=async()=>{try{await x.mutateAsync(s.id),ae.success("Deal deleted"),n(!1)}catch{ae.error("Failed to delete deal")}},le=(d==null?void 0:d.filter(ke=>ke.is_completed).length)||0,he=(d==null?void 0:d.length)||0,ve=(g==null?void 0:g.length)||0,ge=ke=>ke<1024?`${ke} B`:ke<1024*1024?`${(ke/1024).toFixed(1)} KB`:`${(ke/(1024*1024)).toFixed(1)} MB`,fe=ke=>ke?ke.startsWith("image/")?Jl:ke.includes("pdf")?Wr:vz:vz,je=async ke=>{const Xe=ke.target.files;if(!(!Xe||!s)){V(!0);try{for(const Se of Array.from(Xe)){if(Se.size>20*1024*1024){ae.error(`${Se.name} exceeds 20MB limit`);continue}await b.mutateAsync({dealId:s.id,file:Se})}ae.success("File(s) uploaded")}catch{ae.error("Failed to upload file")}finally{V(!1),C.current&&(C.current.value="")}}},Ee=async(ke,Xe)=>{if(s)try{await v.mutateAsync({fileId:ke,storagePath:Xe,dealId:s.id}),ae.success("File deleted")}catch{ae.error("Failed to delete file")}},Me=async(ke,Xe)=>{try{const Se=await dIn(ke),Re=document.createElement("a");Re.href=Se,Re.download=Xe,Re.target="_blank",document.body.appendChild(Re),Re.click(),document.body.removeChild(Re)}catch{ae.error("Failed to download file")}};return e.jsxs(e.Fragment,{children:[e.jsx(Ub,{open:t,onOpenChange:n,children:e.jsxs(T1,{className:"w-full sm:max-w-xl p-0 flex flex-col",children:[e.jsx(kw,{className:"p-6 pb-4 border-b shrink-0",children:e.jsxs("div",{className:"flex items-start justify-between",children:[e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx($e,{variant:"outline",className:Tt("text-xs",K.color),children:K.label}),e.jsxs($e,{variant:"secondary",className:"text-xs capitalize",children:[s.priority," priority"]})]}),e.jsx(Sw,{className:"text-xl",children:s.deal_name}),e.jsx("div",{className:"mt-2",children:e.jsx(aIn,{dealId:s.id})})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx($,{variant:"outline",size:"icon",onClick:()=>r(s),children:e.jsx(bm,{className:"h-4 w-4"})}),e.jsx($,{variant:"outline",size:"icon",className:"text-destructive hover:bg-destructive/10",onClick:()=>q(!0),children:e.jsx(Pn,{className:"h-4 w-4"})})]})]})}),e.jsx(Oi,{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:[(De=s.contact.first_name)==null?void 0:De[0],(ze=s.contact.last_name)==null?void 0:ze[0]]})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("p",{className:"font-medium group-hover:text-primary group-hover:underline truncate",children:[s.contact.first_name," ",s.contact.last_name]}),s.contact.email&&e.jsx("p",{className:"text-sm text-muted-foreground truncate",children:s.contact.email})]})]}),e.jsxs("div",{className:"flex gap-2 shrink-0",children:[s.contact.phone&&e.jsx($,{variant:"outline",size:"icon",asChild:!0,children:e.jsx("a",{href:`tel:${s.contact.phone}`,children:e.jsx(ya,{className:"h-4 w-4"})})}),s.contact.email&&e.jsx($,{variant:"outline",size:"icon",asChild:!0,children:e.jsx("a",{href:`mailto:${s.contact.email}`,children:e.jsx(nn,{className:"h-4 w-4"})})}),e.jsx($,{variant:"outline",size:"icon",title:"Open contact record",onClick:()=>{n(!1),l(`/mission-control/contacts/${s.contact_id}`)},children:e.jsx(Tr,{className:"h-4 w-4"})})]})]}),e.jsx(_In,{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(sa,{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:J(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:J(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?` (${J(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:J(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:["+",J(s.bonus_amount)]})]}),bb(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:J(bb(s))})]})})]}),i&&!s.scorecard_transaction_id&&a&&e.jsxs($,{onClick:()=>a(s),className:"w-full bg-green-600 hover:bg-green-700",children:[e.jsx(pl,{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(Fr,{className:"h-4 w-4 text-green-600"}),e.jsx("span",{children:"Synced to Scorecard"})]}),Q!==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:Tt("text-lg font-bold",Q>90?"text-red-600":Q>60?"text-amber-600":"text-foreground"),children:[Q," ",s.contract_date?"(final)":"days"]})]}),s.target_close_date&&e.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[e.jsx(ia,{className:"h-4 w-4 text-muted-foreground"}),e.jsxs("span",{children:["Close: ",Hs(mu(s.target_close_date),"MMM d, yyyy")]})]}),e.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[e.jsx(qd,{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(LIn,{deal:s}),e.jsx(xIn,{deal:s}),e.jsxs(ua,{defaultValue:"tasks",className:"w-full",children:[e.jsxs(ha,{className:"w-full grid grid-cols-3",children:[e.jsxs(Qt,{value:"tasks",className:"gap-1",children:[e.jsx(Fr,{className:"h-4 w-4"}),"Tasks ",he>0&&`(${le}/${he})`]}),e.jsxs(Qt,{value:"files",className:"gap-1",children:[e.jsx(NT,{className:"h-4 w-4"}),"Files ",ve>0&&`(${ve})`]}),e.jsxs(Qt,{value:"activity",className:"gap-1",children:[e.jsx(Hr,{className:"h-4 w-4"}),"Activity"]})]}),e.jsxs(Jt,{value:"tasks",className:"mt-4 space-y-3",children:[e.jsxs("div",{className:"flex gap-2",children:[e.jsx(be,{placeholder:"Add a new task...",value:P,onChange:ke=>M(ke.target.value),onKeyDown:ke=>ke.key==="Enter"&&ue()}),e.jsx($,{onClick:ue,disabled:!P.trim(),children:e.jsx(sn,{className:"h-4 w-4"})}),e.jsxs($,{variant:"outline",className:"gap-1.5 shrink-0",onClick:()=>D(!0),children:[e.jsx(wf,{className:"h-4 w-4"}),"Playbooks"]})]}),e.jsxs("div",{className:"space-y-2",children:[d==null?void 0:d.map(ke=>e.jsxs("div",{className:Tt("flex items-center gap-3 p-3 rounded-lg border transition-colors",ke.is_completed?"bg-muted/50 border-border":"bg-background"),children:[e.jsx(ui,{checked:ke.is_completed,onCheckedChange:Xe=>ne(ke.id,!!Xe)}),e.jsx("span",{className:Tt("flex-1 text-sm",ke.is_completed&&"line-through text-muted-foreground"),children:ke.title}),ke.due_date&&e.jsx("span",{className:"text-xs text-muted-foreground",children:Hs(new Date(ke.due_date),"MMM d")})]},ke.id)),(d==null?void 0:d.length)===0&&e.jsx("p",{className:"text-center text-muted-foreground text-sm py-4",children:"No tasks yet. Add one above!"})]})]}),e.jsxs(Jt,{value:"files",className:"mt-4 space-y-3",children:[e.jsx("input",{type:"file",ref:C,className:"hidden",multiple:!0,onChange:je,accept:".pdf,.doc,.docx,.xls,.xlsx,.jpg,.jpeg,.png,.webp,.gif,.txt,.csv"}),e.jsxs($,{variant:"outline",className:"w-full border-dashed",onClick:()=>{var ke;return(ke=C.current)==null?void 0:ke.click()},disabled:W,children:[W?e.jsx(Ht,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(si,{className:"h-4 w-4 mr-2"}),W?"Uploading...":"Upload Files"]}),e.jsxs("div",{className:"space-y-2",children:[g==null?void 0:g.map(ke=>{const Xe=fe(ke.file_type);return e.jsxs("div",{className:"flex items-center gap-3 p-3 rounded-lg border bg-background",children:[e.jsx("div",{className:"w-8 h-8 rounded bg-muted flex items-center justify-center shrink-0",children:e.jsx(Xe,{className:"h-4 w-4 text-muted-foreground"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium truncate",children:ke.file_name}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[ge(ke.file_size)," · ",Hs(new Date(ke.created_at),"MMM d, yyyy")]})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(JN,{children:e.jsxs(Mx,{children:[e.jsx(Lx,{asChild:!0,children:e.jsx($,{variant:"ghost",size:"icon",className:`h-8 w-8 transition-colors ${ke.visible_on_portal?"text-primary bg-primary/10 hover:bg-primary/20":"text-muted-foreground/40 hover:text-muted-foreground"}`,onClick:()=>N.mutate({fileId:ke.id,visible:!ke.visible_on_portal,dealId:s.id}),children:ke.visible_on_portal?e.jsx(ga,{className:"h-4 w-4"}):e.jsx(b0,{className:"h-4 w-4"})})}),e.jsx(tx,{side:"top",children:ke.visible_on_portal?"Visible on client portal":"Hidden from client portal"})]})}),e.jsx($,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:()=>Me(ke.storage_path,ke.file_name),children:e.jsx(di,{className:"h-4 w-4"})}),e.jsx($,{variant:"ghost",size:"icon",className:"h-8 w-8 text-destructive hover:text-destructive",onClick:()=>Ee(ke.id,ke.storage_path),children:e.jsx(pr,{className:"h-4 w-4"})})]})]},ke.id)}),(g==null?void 0:g.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(Jt,{value:"activity",className:"mt-4 space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(Is,{placeholder:"Add a note...",value:A,onChange:ke=>T(ke.target.value),rows:2}),e.jsxs($,{onClick:ce,disabled:!A.trim(),size:"sm",className:"w-full",children:[e.jsx(Br,{className:"h-4 w-4 mr-2"}),"Add Note"]})]}),e.jsxs("div",{className:"space-y-3",children:[o==null?void 0:o.map(ke=>{const Xe=OIn[ke.activity_type]||Hr;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(Xe,{className:"h-4 w-4 text-muted-foreground"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium",children:ke.title}),ke.description&&e.jsx("p",{className:"text-sm text-muted-foreground mt-0.5",children:ke.description}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:fc(new Date(ke.created_at),{addSuffix:!0})})]})]},ke.id)}),(o==null?void 0:o.length)===0&&e.jsx("p",{className:"text-center text-muted-foreground text-sm py-4",children:"No activity yet"})]})]})]})]})})]})}),e.jsx(pVt,{open:I,onOpenChange:D,dealId:s==null?void 0:s.id,dealName:s==null?void 0:s.deal_name}),e.jsx(Ll,{open:B,onOpenChange:q,children:e.jsxs(yl,{children:[e.jsxs(vl,{children:[e.jsx(_l,{children:"Delete Deal?"}),e.jsxs(wl,{children:['This will permanently delete "',s.deal_name,'" and all associated data. This action cannot be undone.']})]}),e.jsxs(bl,{children:[e.jsx(jl,{children:"Cancel"}),e.jsx(fl,{onClick:ee,className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Delete"})]})]})})]})}function zIn({open:s,onOpenChange:t,deal:n,onComplete:r}){const a=tAe(),i=oVt(),{data:l}=XO(),{data:o}=Hb(),[c,d]=j.useState({property_address:"",city:"",state:"",zip:"",transaction_type:"buyer",close_date:Hs(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,x=n.commission_percentage||3,g=n.expected_commission||p*x/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||Hs(new Date,"yyyy-MM-dd"),sale_price:p,commission_amount:g,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}),ae.success("Deal added to Scorecard! 🎉"),t(!1),r==null||r()}catch(p){console.error("Error syncing to scorecard:",p),ae.error("Failed to add to scorecard")}},h=m=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",minimumFractionDigits:0,maximumFractionDigits:0}).format(m);return e.jsx(Os,{open:s,onOpenChange:t,children:e.jsxs(Rs,{className:"sm:max-w-[550px] max-h-[90vh] overflow-y-auto",children:[e.jsxs(Us,{className:"space-y-3",children:[e.jsx("div",{className:"mx-auto flex h-12 w-12 items-center justify-center rounded-full bg-green-100 dark:bg-green-900/20",children:e.jsx(pl,{className:"h-6 w-6 text-green-600 dark:text-green-400"})}),e.jsx(zs,{className:"text-center text-xl",children:"Congratulations on Closing! 🎉"}),e.jsx(Sr,{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(se,{htmlFor:"property_address",className:"flex items-center gap-2",children:[e.jsx(sa,{className:"h-4 w-4 text-muted-foreground"}),"Property Address *"]}),e.jsx(be,{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(se,{htmlFor:"city",children:"City"}),e.jsx(be,{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(se,{htmlFor:"state",children:"State"}),e.jsx(be,{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(se,{htmlFor:"zip",children:"Zip"}),e.jsx(be,{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(se,{children:"Transaction Type *"}),e.jsxs(vs,{value:c.transaction_type,onValueChange:m=>d(p=>({...p,transaction_type:m})),children:[e.jsx(gs,{children:e.jsx(bs,{})}),e.jsxs(ys,{children:[e.jsx(Ye,{value:"buyer",children:"Buyer"}),e.jsx(Ye,{value:"seller",children:"Seller"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(se,{htmlFor:"close_date",className:"flex items-center gap-2",children:[e.jsx(ia,{className:"h-4 w-4 text-muted-foreground"}),"Close Date *"]}),e.jsx(be,{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(se,{htmlFor:"sale_price",className:"flex items-center gap-2",children:[e.jsx(qd,{className:"h-4 w-4 text-muted-foreground"}),"Sale Price *"]}),e.jsx(be,{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(se,{htmlFor:"commission_amount",className:"flex items-center gap-2",children:[e.jsx(ST,{className:"h-4 w-4 text-muted-foreground"}),"GCI (Commission)"]}),e.jsx(be,{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(se,{children:"Lead Source"}),e.jsxs(vs,{value:c.lead_source_id,onValueChange:m=>d(p=>({...p,lead_source_id:m})),children:[e.jsx(gs,{children:e.jsx(bs,{placeholder:"Select source"})}),e.jsx(ys,{children:l==null?void 0:l.map(m=>e.jsx(Ye,{value:m.id,children:m.name},m.id))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Client Type"}),e.jsxs(vs,{value:c.client_type_id,onValueChange:m=>d(p=>({...p,client_type_id:m})),children:[e.jsx(gs,{children:e.jsx(bs,{placeholder:"Select type"})}),e.jsx(ys,{children:o==null?void 0:o.map(m=>e.jsx(Ye,{value:m.id,children:m.name},m.id))})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"notes",children:"Notes"}),e.jsx(Is,{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(kr,{className:"gap-2 sm:gap-0 pt-4",children:[e.jsx($,{type:"button",variant:"outline",onClick:()=>t(!1),children:"Skip for now"}),e.jsx($,{type:"submit",disabled:a.isPending||i.isPending,className:"bg-green-600 hover:bg-green-700",children:a.isPending?"Adding...":e.jsxs(e.Fragment,{children:["Add to Scorecard",e.jsx(ni,{className:"ml-2 h-4 w-4"})]})})]})]})]})})}const BIn={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"}},Cvt={urgent:0,high:1,medium:2,low:3};function $In({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(x=>x==="asc"?"desc":"asc"):(i(p),o("asc"))},d=j.useMemo(()=>[...s].sort((p,x)=>{var y,b;let g=0;switch(a){case"deal_name":g=p.deal_name.localeCompare(x.deal_name);break;case"stage":{const v=((y=t.find(C=>C.id===p.stage_id))==null?void 0:y.sort_order)||0,N=((b=t.find(C=>C.id===x.stage_id))==null?void 0:b.sort_order)||0;g=v-N;break}case"expected_price":g=(p.expected_price||0)-(x.expected_price||0);break;case"expected_commission":g=(p.expected_commission||0)-(x.expected_commission||0);break;case"target_close_date":{const v=p.target_close_date?mu(p.target_close_date).getTime():1/0,N=x.target_close_date?mu(x.target_close_date).getTime():1/0;g=v-N;break}case"priority":g=Cvt[p.priority]-Cvt[x.priority];break}return l==="asc"?g:-g}),[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(x=>x.id===p):null,m=({field:p,children:x})=>e.jsxs($,{variant:"ghost",size:"sm",className:"h-8 -ml-3 font-medium",onClick:()=>c(p),children:[x,a===p?l==="asc"?e.jsx(sp,{className:"ml-2 h-4 w-4"}):e.jsx(ax,{className:"ml-2 h-4 w-4"}):e.jsx(Tx,{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(Va,{children:[e.jsx(Ha,{children:e.jsxs(hn,{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(Ga,{children:d.map(p=>{h(p.stage_id);const x=BIn[p.deal_type],g=p.target_close_date?r2(mu(p.target_close_date),new Date):null,y=g!==null&&g<0,b=g!==null&&g<=7&&g>=0;return e.jsxs(hn,{className:Tt("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:v=>v.stopPropagation(),children:e.jsx(uVt,{stages:t,currentStageId:p.stage_id||"",onStageSelect:(v,N)=>r(p.id,v,N)})}),e.jsx(gt,{children:e.jsx($e,{variant:"outline",className:Tt("text-xs",x.color),children:x.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:Tt("flex items-center gap-1 text-sm",y&&"text-red-600",b&&!y&&"text-amber-600"),children:[y&&e.jsx(xo,{className:"h-3.5 w-3.5"}),e.jsx("span",{children:Hs(mu(p.target_close_date),"MMM d, yyyy")})]}):e.jsx("span",{className:"text-muted-foreground",children:"—"})}),e.jsx(gt,{children:e.jsx($e,{variant:"outline",className:Tt("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 fVt(){const s=Za();return ht({queryKey:["deal-tasks",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await U.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 UIn(s){const t=Za();return ht({queryKey:["deal-tasks","deal",s,t],queryFn:async()=>{if(!t||!s)return[];const{data:n,error:r}=await U.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 qIn(){const s=Za(),t=ts();return yt({mutationFn:async n=>{if(!s)throw new Error("Not authenticated");const{data:r,error:a}=await U.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 VIn(){const s=ts();return yt({mutationFn:async({id:t,...n})=>{const{data:r,error:a}=await U.from("deal_tasks").update(n).eq("id",t).select().single();if(a)throw a;return r},onSuccess:()=>{s.invalidateQueries({queryKey:["deal-tasks"]})}})}function HIn(){const s=ts();return yt({mutationFn:async t=>{const{error:n}=await U.from("deal_tasks").delete().eq("id",t);if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["deal-tasks"]})}})}function TTe(){const s=ts();return yt({mutationFn:async({id:t,status:n})=>{const{data:r,error:a}=await U.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 GIn(){const s=ts();return yt({mutationFn:async t=>{if(t.length===0)return;const{error:n}=await U.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 WIn(s){const t=Za();return ht({queryKey:["deal-task-templates",t,s],queryFn:async()=>{if(!t)return[];let n=U.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 KIn(){const s=Za(),t=ts();return yt({mutationFn:async n=>{if(!s)throw new Error("Not authenticated");const{data:r,error:a}=await U.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 YIn(){const s=ts();return yt({mutationFn:async t=>{const{error:n}=await U.from("deal_task_templates").delete().eq("id",t);if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["deal-task-templates"]})}})}function ZIn(){const s=Za(),t=ts();return yt({mutationFn:async({dealId:n,stageId:r})=>{if(!s)throw new Error("Not authenticated");const{data:a,error:i}=await U.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 U.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 U.from("deal_tasks").insert(c).select();if(u)throw u;return d},onSuccess:()=>{t.invalidateQueries({queryKey:["deal-tasks"]})}})}const XIn={urgent:"🔴",high:"🟠",medium:"🟡",low:"🟢"};function QIn({open:s,onOpenChange:t,dealId:n,dealName:r,fromStageName:a,toStageName:i,toStageId:l,onConfirm:o}){const{data:c,isLoading:d}=UIn(s?n:void 0),u=GIn(),h=ZIn(),[m,p]=j.useState(new Set),[x,g]=j.useState(!1),y=(c||[]).filter(C=>C.status!=="done");j.useEffect(()=>{y.length>0&&p(new Set(y.map(C=>C.id)))},[c]);const b=C=>{p(A=>{const T=new Set(A);return T.has(C)?T.delete(C):T.add(C),T})},v=async()=>{g(!0);try{const C=Array.from(m);C.length>0&&await u.mutateAsync(C),await o(),await h.mutateAsync({dealId:n,stageId:l}),t(!1)}catch(C){console.error("Stage move failed:",C),ae.error((C==null?void 0:C.message)||"Failed to move deal. Please try again.")}finally{g(!1)}},N=async()=>{g(!0);try{await o(),await h.mutateAsync({dealId:n,stageId:l}),t(!1)}catch(C){console.error("Stage move (skip) failed:",C),ae.error((C==null?void 0:C.message)||"Failed to move deal. Please try again.")}finally{g(!1)}};return e.jsx(Os,{open:s,onOpenChange:t,children:e.jsxs(Rs,{className:"sm:max-w-[480px]",children:[e.jsxs(Us,{children:[e.jsx(zs,{children:"Move Deal"}),e.jsxs(Sr,{children:["Moving ",e.jsx("span",{className:"font-medium text-foreground",children:r})]})]}),e.jsxs("div",{className:"flex items-center justify-center gap-3 py-2",children:[e.jsx($e,{variant:"outline",className:"text-sm",children:a}),e.jsx(ni,{className:"h-4 w-4 text-muted-foreground"}),e.jsx($e,{className:"text-sm bg-primary",children:i})]}),d?e.jsx("div",{className:"flex justify-center py-8",children:e.jsx(Ht,{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(Oi,{className:"max-h-[250px]",children:e.jsx("div",{className:"space-y-1",children:y.map(C=>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(ui,{checked:m.has(C.id),onCheckedChange:()=>b(C.id)}),e.jsxs("span",{className:"text-sm flex-1",children:[XIn[C.priority]," ",C.title]}),C.stage&&e.jsx("span",{className:"text-[10px] px-1.5 py-0.5 rounded-full",style:{backgroundColor:C.stage.color+"20",color:C.stage.color},children:C.stage.name})]},C.id))})}),e.jsxs("div",{className:"flex items-center justify-between gap-2 pt-2",children:[e.jsx($,{variant:"ghost",size:"sm",onClick:()=>{m.size===y.length?p(new Set):p(new Set(y.map(C=>C.id)))},children:m.size===y.length?"Deselect All":"Select All"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx($,{variant:"outline",size:"sm",onClick:N,disabled:x,children:"Skip"}),e.jsxs($,{size:"sm",onClick:v,disabled:x,children:[x&&e.jsx(Ht,{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(Fr,{className:"h-8 w-8 text-emerald-500 mx-auto mb-2"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"All tasks completed! Ready to move."})]}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx($,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsxs($,{onClick:v,disabled:x,children:[x&&e.jsx(Ht,{className:"h-4 w-4 mr-1 animate-spin"}),"Move to ",i]})]})]})]})})}const JIn=[{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"}],e8n=[{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 xVt({open:s,onOpenChange:t}){const n=Za(),{data:r,isLoading:a}=qTt(),i=c5s(),[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(x=>({...x,...p})),h=async(p,x)=>{if(n){if(p.size>5*1024*1024){ae.error("Image must be under 5MB");return}d(x);try{const g=await VTt(n,p,x);u(x==="logo"?{logo_url:g}:{cover_photo_url:g})}catch(g){ae.error(`Upload failed: ${g.message||g}`)}finally{d(null)}}},m=async()=>{try{await i.mutateAsync(l),ae.success("Portal branding saved"),t(!1)}catch{ae.error("Failed to save branding")}};return e.jsx(Os,{open:s,onOpenChange:t,children:e.jsxs(Rs,{className:"max-w-lg max-h-[90vh] flex flex-col",children:[e.jsxs(Us,{children:[e.jsxs(zs,{className:"flex items-center gap-2",children:[e.jsx(Rc,{className:"h-5 w-5 text-primary"}),"Portal Branding"]}),e.jsx(Sr,{children:"Customize how your client portals look. These defaults apply to every portal — you can override them per deal."})]}),e.jsx(Oi,{className:"flex-1 pr-3 -mr-3",children:a?e.jsx("div",{className:"py-12 flex justify-center",children:e.jsx(Ht,{className:"h-5 w-5 animate-spin text-muted-foreground"})}):e.jsxs("div",{className:"space-y-6 py-2",children:[e.jsx(t8n,{draft:l}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx(se,{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:e8n.map(p=>{const x=(l.portal_theme??"noir")===p.id;return e.jsxs("button",{type:"button",onClick:()=>u({portal_theme:p.id}),className:Tt("rounded-xl border-2 p-3 text-left transition-all",x?"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(Avt,{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(Avt,{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(se,{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:JIn.map(p=>{const x=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:Tt("group relative rounded-lg border-2 p-2 text-left transition-all",x?"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(Evt,{label:"Brand",value:l.brand_color,onChange:p=>u({brand_color:p})}),e.jsx(Evt,{label:"Accent",value:l.accent_color,onChange:p=>u({accent_color:p})})]})]}),e.jsxs("div",{children:[e.jsx(se,{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(be,{value:l.tagline||"",onChange:p=>u({tagline:p.target.value}),placeholder:"Your trusted real estate advisor",maxLength:80})]}),e.jsxs("div",{children:[e.jsx(se,{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($,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsxs($,{onClick:m,disabled:i.isPending,children:[i.isPending?e.jsx(Ht,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(Jo,{className:"h-4 w-4 mr-2"}),"Save Branding"]})]})]})})}function t8n({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 Avt({label:s,hint:t,value:n,uploading:r,onUpload:a,onClear:i,aspect:l}){return e.jsxs("div",{children:[e.jsx(se,{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:Tt("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(Jl,{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(Ht,{className:"h-3.5 w-3.5 animate-spin"}):e.jsx(si,{className:"h-3.5 w-3.5"}),n?"Replace":"Upload"]})]}),n&&e.jsx($,{variant:"ghost",size:"sm",onClick:i,className:"text-muted-foreground hover:text-destructive",children:e.jsx(Pn,{className:"h-3.5 w-3.5"})})]})]})]})}function Evt({label:s,value:t,onChange:n}){const r=t||"#000000";return e.jsxs("div",{children:[e.jsx(se,{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(be,{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 s8n(){const s=Za();return ht({queryKey:["all-client-portals",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await U.from("client_portals").select("*").eq("owner_user_id",s);if(n)throw n;return t||[]},enabled:!!s})}function n8n({dealId:s,dealName:t,contactName:n,portal:r,onSettingsOpen:a,onComposerOpen:i,onInviteOpen:l,onDeleteConfirm:o}){const c=LYe(),d=uV(),u=V7t(),h=H7t(),[m,p]=j.useState(!1),x=!!(r!=null&&r.archived_at),g=async()=>{p(!0);try{await c.mutateAsync({deal_id:s,visibility:"private",require_onboarding:!0}),ae.success("Portal enabled!")}catch{ae.error("Failed to create portal")}finally{p(!1)}},y=async A=>{if(r)try{await d.mutateAsync({id:r.id,is_enabled:A}),ae.success(A?"Portal enabled":"Portal disabled")}catch{ae.error("Failed to update portal")}},b=()=>{r&&(navigator.clipboard.writeText(f5(r.slug)),ae.success("Link copied!"))},v=()=>{r&&window.open(f5(r.slug),"_blank")},N=async()=>{if(r)try{await u.mutateAsync(r.id),ae.success("Portal archived")}catch{ae.error("Failed to archive portal")}},C=async()=>{if(r)try{await h.mutateAsync(r.id),ae.success("Portal restored")}catch{ae.error("Failed to restore portal")}};return r?x?e.jsxs("div",{className:"flex items-center gap-4 p-4 border rounded-lg opacity-60 bg-muted/30",children:[e.jsxs(Wn,{to:`/mission-control/client-portals/${r.id}`,className:"flex-1 min-w-0 hover:opacity-80",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("p",{className:"font-medium text-sm truncate",children:t}),e.jsx($e,{variant:"outline",className:"text-[10px] bg-muted text-muted-foreground",children:"Archived"})]}),e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:r.client_name||n||"No client name"})]}),e.jsxs("div",{className:"flex items-center gap-1 shrink-0",children:[e.jsxs($,{variant:"ghost",size:"sm",onClick:C,className:"text-xs gap-1",children:[e.jsx(hT,{className:"h-3.5 w-3.5"}),"Restore"]}),e.jsxs($,{variant:"ghost",size:"sm",onClick:()=>o(r),className:"text-xs gap-1 text-destructive hover:text-destructive",children:[e.jsx(Pn,{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(Wn,{to:`/mission-control/client-portals/${r.id}`,className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("p",{className:"font-medium text-sm truncate group-hover:text-primary transition-colors",children:t}),e.jsx($e,{variant:"outline",className:r.is_enabled?"text-[10px] bg-emerald-500/10 text-emerald-600 border-emerald-200":"text-[10px] bg-muted text-muted-foreground",children:r.is_enabled?"Active":"Disabled"}),e.jsx(Ja,{className:"h-3.5 w-3.5 text-muted-foreground opacity-0 group-hover:opacity-100 transition-opacity"})]}),e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:r.client_name||n||"No client name"})]}),e.jsxs("div",{className:"flex items-center gap-1 shrink-0",children:[e.jsx($,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:b,title:"Copy link",children:e.jsx(Ca,{className:"h-3.5 w-3.5"})}),e.jsx($,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:v,title:"Preview",children:e.jsx(Tr,{className:"h-3.5 w-3.5"})}),e.jsx($,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:()=>l(r,t),title:"Invite client",children:e.jsx(Br,{className:"h-3.5 w-3.5"})}),e.jsx($,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:()=>i(r),title:"Post update",children:e.jsx(BS,{className:"h-3.5 w-3.5"})}),e.jsx($,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:()=>a(r),title:"Settings",children:e.jsx(pc,{className:"h-3.5 w-3.5"})}),e.jsxs(Hd,{children:[e.jsx(Gd,{asChild:!0,children:e.jsx($,{variant:"ghost",size:"icon",className:"h-8 w-8",children:e.jsx(p0,{className:"h-3.5 w-3.5"})})}),e.jsx(Md,{align:"end",children:e.jsxs(Na,{onClick:N,children:[e.jsx(Am,{className:"h-4 w-4 mr-2"}),"Archive Portal"]})})]}),e.jsx(Tn,{checked:r.is_enabled,onCheckedChange:y,className:"ml-1"})]})]}):e.jsxs("div",{className:"flex items-center justify-between p-4 border rounded-lg border-dashed bg-muted/20",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"font-medium text-sm truncate",children:t}),e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:n||"No contact"})]}),e.jsxs($,{size:"sm",onClick:g,disabled:m,className:"shrink-0 ml-4",children:[m?e.jsx(Ht,{className:"h-3 w-3 animate-spin mr-1"}):e.jsx(dn,{className:"h-3 w-3 mr-1"}),"Enable Portal"]})]})}function gVt(){const{data:s,isLoading:t}=ETe(),{data:n,isLoading:r}=s8n(),[a,i]=j.useState(""),[l,o]=j.useState("all"),c=G7t(),[d,u]=j.useState(null),[h,m]=j.useState(null),[p,x]=j.useState(null),[g,y]=j.useState(null),[b,v]=j.useState(!1),N=Za(),C=t||r,A=new Map;n==null||n.forEach(q=>A.set(q.deal_id,q));const P=[...(s||[]).filter(q=>{var J,ce,ue,ne,ee;const W=A.get(q.id),V=a.toLowerCase(),K=!V||q.deal_name.toLowerCase().includes(V)||((ce=(J=q.contact)==null?void 0:J.first_name)==null?void 0:ce.toLowerCase().includes(V))||((ne=(ue=q.contact)==null?void 0:ue.last_name)==null?void 0:ne.toLowerCase().includes(V))||((ee=W==null?void 0:W.client_name)==null?void 0:ee.toLowerCase().includes(V));let Q=!0;return l==="active"?Q=!!(W!=null&&W.is_enabled)&&!(W!=null&&W.archived_at):l==="disabled"?Q=!!W&&!W.is_enabled&&!W.archived_at:l==="archived"?Q=!!(W!=null&&W.archived_at):l==="none"?Q=!W:l==="all"&&(Q=!(W!=null&&W.archived_at)||!W),K&&Q})].sort((q,W)=>{const V=A.get(q.id),K=A.get(W.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(q=>!q.archived_at).length)||0,I=(n==null?void 0:n.filter(q=>q.is_enabled&&!q.archived_at).length)||0,D=(n==null?void 0:n.filter(q=>q.archived_at).length)||0,B=async()=>{if(g)try{await c.mutateAsync({id:g.id,dealId:g.deal_id}),ae.success("Portal permanently deleted"),y(null)}catch{ae.error("Failed to delete portal")}};return C?e.jsx("div",{className:"flex items-center justify-center py-16",children:e.jsx(Ht,{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(dn,{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",D>0&&` · ${D} archived`]})]}),e.jsxs($,{variant:"outline",size:"sm",onClick:()=>v(!0),className:"gap-1.5",children:[e.jsx(Rc,{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(Vr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(be,{placeholder:"Search deals or clients...",value:a,onChange:q=>i(q.target.value),className:"pl-9 pr-8"}),a&&e.jsx("button",{onClick:()=>i(""),className:"absolute right-2 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground",children:e.jsx(pr,{className:"h-4 w-4"})})]}),e.jsx("div",{className:"flex bg-muted rounded-lg p-1 gap-0.5",children:["all","active","disabled","archived","none"].map(q=>e.jsx($,{variant:l===q?"secondary":"ghost",size:"sm",onClick:()=>o(q),className:"text-xs px-3 capitalize",children:q==="none"?"No Portal":q},q))})]}),e.jsx(Oi,{className:"h-[calc(100vh-22rem)]",children:e.jsxs("div",{className:"space-y-2 pb-4",children:[P.map(q=>{const W=A.get(q.id)||null,V=q.contact?`${q.contact.first_name||""} ${q.contact.last_name||""}`.trim():"";return e.jsx(n8n,{dealId:q.id,dealName:q.deal_name,contactName:V,portal:W,onSettingsOpen:u,onComposerOpen:K=>m(K),onInviteOpen:(K,Q)=>x({portal:K,dealName:Q}),onDeleteConfirm:y},q.id)}),P.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(dn,{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(dXe,{open:!!d,onOpenChange:q=>!q&&u(null),portal:d,dealOwnerId:N||""}),h&&e.jsx(uXe,{open:!!h,onOpenChange:q=>!q&&m(null),portalId:h.id,portalSlug:h.slug,notifyClient:h.notify_client}),p&&e.jsx(hXe,{open:!!p,onOpenChange:q=>!q&&x(null),portal:p.portal,dealName:p.dealName}),e.jsx(xVt,{open:b,onOpenChange:v}),e.jsx(Ll,{open:!!g,onOpenChange:q=>!q&&y(null),children:e.jsxs(yl,{children:[e.jsxs(vl,{children:[e.jsx(_l,{children:"Permanently delete this portal?"}),e.jsx(wl,{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(bl,{children:[e.jsx(jl,{children:"Cancel"}),e.jsx(fl,{onClick:B,className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Delete Permanently"})]})]})})]})}function r8n({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(sn,{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(qn,{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(Wi,{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 x=p.onClick?"button":"div";return e.jsxs(x,{type:p.onClick?"button":void 0,onClick:p.onClick,title:p.hint,className:Tt("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(Vr,{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(pr,{className:"h-4 w-4"})})]}),c]}),(d.length>0||h)&&e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[d.map(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(pr,{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 a8n={closing_soon:{label:"Closing in 7 days",icon:Xu,tone:"text-primary"},past_due:{label:"Past close date",icon:mc,tone:"text-destructive"},overdue_tasks:{label:"Overdue tasks",icon:TS,tone:"text-amber-600 dark:text-amber-400"},stalled:{label:"Stalled 14+ days",icon:TK,tone:"text-muted-foreground"}};function i8n({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=a8n[a],o=l.icon,c=t===a;return e.jsxs("button",{onClick:()=>n(a),className:Tt("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:Tt("h-3.5 w-3.5",!c&&l.tone)}),l.label,e.jsx("span",{className:Tt("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 o8n 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(Ks,{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 FG="deal-pipeline-detail-sheet";function zG(s){return s>=1e6?`$${(s/1e6).toFixed(1)}M`:s>=1e3?`$${(s/1e3).toFixed(0)}K`:`$${Math.round(s).toLocaleString()}`}function l8n(){var Zn;const s=dV(),{data:t,isLoading:n}=gte(),{data:r,isLoading:a,refetch:i}=ETe(),{data:l,isLoading:o}=cPn(),c=aVt(),d=sPn(),[u,h]=j.useState("board"),[m,p]=j.useState(!1),[x,g]=j.useState(!1),[y,b]=j.useState(null),[v,N]=j.useState(null),[C,A]=j.useState(null),[T,P]=j.useState(null),[M,I]=j.useState(!1),[D,B]=j.useState(null),[q,W]=j.useState(""),[V,K]=j.useState("all"),[Q,J]=j.useState("all"),[ce,ue]=j.useState("all"),[ne,ee]=j.useState(null),{data:le}=fVt(),{data:he}=XPn(),[ve,ge]=j.useState(!1),[fe,je]=j.useState(!1),[Ee,Me]=j.useState(new Set),De=j.useRef(!1),[ze,ke]=j.useState(null),{data:Xe}=Nw(),{isTeamLeader:Se,teamMembers:Re}=YPn(),Ae=j.useMemo(()=>Array.from(Ee),[Ee]),{data:Be}=ZPn(Ae),qe=j.useMemo(()=>{const Xt=new Map;return Re.forEach(rr=>Xt.set(rr.id,{name:rr.name,avatar_url:rr.avatar_url,color:rr.color})),Xt},[Re]),Ke=j.useCallback(Xt=>Xt.owner_user_id&&qe.get(Xt.owner_user_id)||null,[qe]),Ze=j.useCallback(Xt=>{Me(rr=>{const Qn=new Set(rr);return Qn.has(Xt)?Qn.delete(Xt):Qn.add(Xt),Qn})},[]);j.useEffect(()=>{!n&&t&&t.length===0&&c.mutate()},[n,t]);const[Ue,et]=oc(),Qe=j.useRef(!1);j.useEffect(()=>{const Xt=Ue.get("deal");if(Xt&&r&&r.length>0&&!Qe.current){const rr=r.find(Qn=>Qn.id===Xt);rr&&(Qe.current=!0,b(rr),g(!0),Ue.delete("deal"),et(Ue,{replace:!0}))}},[r,Ue]);const Ge=j.useMemo(()=>{if(!Be||!t)return[];const Xt=new Map(t.map(rr=>[rr.name,rr.id]));return Be.map(rr=>{const Qn=rr._stage_name&&Xt.get(rr._stage_name)||null;return{...rr,stage_id:Qn||rr.stage_id}})},[Be,t]),nt=j.useMemo(()=>[...r||[],...Ge],[r,Ge]);j.useEffect(()=>{if(De.current||nt.length===0)return;De.current=!0;const Xt=sessionStorage.getItem(FG);if(Xt)try{const rr=JSON.parse(Xt);if(!rr.open||!rr.dealId)return;const Qn=nt.find(Sn=>Sn.id===rr.dealId);Qn&&(b(Qn),g(!0))}catch{sessionStorage.removeItem(FG)}},[nt]),j.useEffect(()=>{x&&(y!=null&&y.id)?sessionStorage.setItem(FG,JSON.stringify({dealId:y.id,open:!0})):sessionStorage.removeItem(FG)},[x,y==null?void 0:y.id]);const ft=j.useMemo(()=>{const Xt={},rr=new Date;return rr.setHours(0,0,0,0),(le||[]).forEach(Qn=>{!Qn.deal_id||Qn.status==="done"||!Qn.due_date||mu(Qn.due_date){const Xt=new Set((t||[]).filter(ln=>ln.is_won_stage).map(ln=>ln.id)),rr=new Set((t||[]).filter(ln=>ln.is_lost_stage).map(ln=>ln.id)),Qn=new Date;Qn.setHours(0,0,0,0);const Sn=new Date(Qn);Sn.setDate(Sn.getDate()+7);const $n=new Date(Qn);$n.setDate($n.getDate()-14);const tn={closing_soon:new Set,past_due:new Set,overdue_tasks:new Set,stalled:new Set};return nt.forEach(ln=>{if(!(ln.stage_id&&(Xt.has(ln.stage_id)||rr.has(ln.stage_id)))){if(ln.target_close_date){const ms=mu(ln.target_close_date);ms[{key:"closing_soon",count:Ft.closing_soon.size},{key:"past_due",count:Ft.past_due.size},{key:"overdue_tasks",count:Ft.overdue_tasks.size},{key:"stalled",count:Ft.stalled.size}],[Ft]),js=nt.filter(Xt=>{var pt,vt,At,Zt,as,Ls;const rr=q.toLowerCase(),Qn=lt[Xt.id]||[],Sn=!rr||Xt.deal_name.toLowerCase().includes(rr)||((vt=(pt=Xt.contact)==null?void 0:pt.first_name)==null?void 0:vt.toLowerCase().includes(rr))||((Zt=(At=Xt.contact)==null?void 0:At.last_name)==null?void 0:Zt.toLowerCase().includes(rr))||((as=Xt.property_address)==null?void 0:as.toLowerCase().includes(rr))||((Ls=Xt.city)==null?void 0:Ls.toLowerCase().includes(rr))||Qn.some(cs=>cs.toLowerCase().includes(rr)),$n=V==="all"||Xt.deal_type===V,tn=Q==="all"||Qn.includes(Q),ln=Xt.actual_close_date||Xt.target_close_date||Xt.contract_date||Xt.created_at,Cr=ln?String(ln).slice(0,4):null,ms=ce==="all"||Cr===ce,ot=!ne||Ft[ne].has(Xt.id);return Sn&&$n&&tn&&ms&&ot}),zt=j.useMemo(()=>{const Xt=new Set;return Xt.add(String(new Date().getFullYear())),nt.forEach(rr=>{const Qn=rr.actual_close_date||rr.target_close_date||rr.contract_date||rr.created_at;Qn&&Xt.add(String(Qn).slice(0,4))}),Array.from(Xt).sort((rr,Qn)=>Number(Qn)-Number(rr))},[nt]),Nt=j.useMemo(()=>{if(!t)return l||null;const Xt=new Set(t.filter(ln=>ln.is_won_stage).map(ln=>ln.id)),rr=new Set(t.filter(ln=>ln.is_lost_stage).map(ln=>ln.id)),Qn=nt.filter(ln=>ln.stage_id&&!Xt.has(ln.stage_id)&&!rr.has(ln.stage_id)),Sn=nt.filter(ln=>ln.stage_id&&Xt.has(ln.stage_id)),$n=new Date().getFullYear(),tn=Sn.filter(ln=>ln.actual_close_date?new Date(ln.actual_close_date).getFullYear()===$n:!0);return{totalDeals:nt.length,activeDeals:Qn.length,wonDeals:Sn.length,pipelineValue:Qn.reduce((ln,Cr)=>ln+(Cr.expected_price||0),0),expectedCommission:Qn.reduce((ln,Cr)=>ln+(Cr.expected_commission||0),0),expectedNetToAgent:Qn.reduce((ln,Cr)=>ln+(bb(Cr)||0),0),wonValue:Sn.reduce((ln,Cr)=>ln+(Cr.expected_price||0),0),weightedGCI:Qn.reduce((ln,Cr)=>ln+(Cr.expected_commission||0)*((Cr.probability??50)/100),0),weightedNet:Qn.reduce((ln,Cr)=>ln+(bb(Cr)||0)*((Cr.probability??50)/100),0),ytdWonDeals:tn.length,ytdWonGCI:tn.reduce((ln,Cr)=>ln+(Cr.expected_commission||0),0),ytdWonNet:tn.reduce((ln,Cr)=>ln+(bb(Cr)||0),0),projectedAnnualNet:tn.reduce((ln,Cr)=>ln+(bb(Cr)||0),0)+Qn.reduce((ln,Cr)=>ln+(bb(Cr)||0)*((Cr.probability??50)/100),0)}},[nt,t,l]),Ds=Xt=>{b(Xt),g(!0)},_t=Xt=>{N(Xt||null),b(null),p(!0)},Xs=Xt=>{b(Xt),g(!1),p(!0)},rn=Xt=>{g(Xt),Xt||sessionStorage.removeItem(FG)},Ps=(Xt,rr)=>{A(Xt)},_n=(Xt,rr)=>{Xt.preventDefault(),Xt.dataTransfer.dropEffect="move",P(rr)},Zs=async(Xt,rr)=>{if(Xt.preventDefault(),P(null),!C)return;const Qn=r==null?void 0:r.find(tn=>tn.id===C),Sn=t==null?void 0:t.find(tn=>tn.id===rr),$n=t==null?void 0:t.find(tn=>tn.id===(Qn==null?void 0:Qn.stage_id));if(!Qn||!Sn||Qn.stage_id===rr){A(null);return}ke({dealId:C,dealName:Qn.deal_name,fromStageName:($n==null?void 0:$n.name)||"Unknown",toStageName:Sn.name,toStageId:rr,isWonStage:Sn.is_won_stage,deal:Qn}),A(null)},gr=async()=>{if(!ze)return;const{dealId:Xt,toStageId:rr,toStageName:Qn,isWonStage:Sn,deal:$n}=ze;if(await d.mutateAsync({dealId:Xt,stageId:rr,stageName:Qn}),ae.success(`Moved to ${Qn}`),Sn&&!$n.scorecard_transaction_id){const tn={...$n,stage_id:rr};B(tn),I(!0)}},Un=j.useCallback(async(Xt,rr,Qn)=>{const Sn=r==null?void 0:r.find(ln=>ln.id===Xt),$n=t==null?void 0:t.find(ln=>ln.id===rr),tn=t==null?void 0:t.find(ln=>ln.id===(Sn==null?void 0:Sn.stage_id));!Sn||!$n||Sn.stage_id===rr||ke({dealId:Xt,dealName:Sn.deal_name,fromStageName:(tn==null?void 0:tn.name)||"Unknown",toStageName:Qn,toStageId:rr,isWonStage:$n.is_won_stage,deal:Sn})},[r,t]),In=Xt=>js.filter(rr=>rr.stage_id===Xt),Ar=n||a,or=s?"list":u,qs=[{label:"Active Deals",value:(Nt==null?void 0:Nt.activeDeals)||0,hint:"Deals still in play"},{label:"Weighted GCI",value:zG((Nt==null?void 0:Nt.weightedGCI)||0),hint:"GCI adjusted by each deal's win probability"},{label:"Weighted Net",value:zG((Nt==null?void 0:Nt.weightedNet)||0),hint:"Net to agent adjusted by each deal's win probability"},{label:"YTD Closed Net",value:zG((Nt==null?void 0:Nt.ytdWonNet)||0),subtitle:`${(Nt==null?void 0:Nt.ytdWonDeals)||0} deals`,hint:"Net commission from deals closed this year"},{label:"Projected Annual",value:zG((Nt==null?void 0:Nt.projectedAnnualNet)||0),hint:"YTD closed net + weighted active net"}],yr=[...V!=="all"?[{key:"type",label:`Type: ${V}`,onClear:()=>K("all")}]:[],...ce!=="all"?[{key:"year",label:`Year: ${ce}`,onClear:()=>ue("all")}]:[],...Q!=="all"?[{key:"tag",label:`Tag: ${Q}`,onClear:()=>J("all")}]:[],...q?[{key:"search",label:`"${q}"`,onClear:()=>W("")}]:[],...ne?[{key:"attention",label:"Needs attention",onClear:()=>ee(null)}]:[]],fn=()=>{W(""),K("all"),J("all"),ue("all"),ee(null)};return e.jsxs(Ks,{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(r8n,{summary:`${(Nt==null?void 0:Nt.activeDeals)||0} active deals • ${zG((Nt==null?void 0:Nt.weightedNet)||0)} weighted net`,stats:or==="portals"?[]:qs,search:q,onSearchChange:W,onAddDeal:()=>_t(),onRefresh:()=>i(),onTeam:Xe&&!Se?()=>ge(!0):void 0,showSearch:or!=="portals",activeFilters:yr,onClearAll:fn,resultLabel:yr.length>0?`${js.length} of ${nt.length} deals`:null,viewControls:s?null:e.jsx(JN,{children:e.jsx("div",{className:"hub-glass flex items-center gap-0.5 rounded-full p-1",children:[{mode:"board",icon:_0,label:"Board",hint:"Kanban board view"},{mode:"list",icon:Sg,label:"List",hint:"Grouped list view"},{mode:"table",icon:$z,label:"Table",hint:"Sortable table view"},{mode:"portals",icon:dn,label:"Portals",hint:"Client portal management"}].map(({mode:Xt,icon:rr,label:Qn,hint:Sn})=>e.jsxs(Mx,{children:[e.jsx(Lx,{asChild:!0,children:e.jsxs("button",{onClick:()=>h(Xt),className:Tt("inline-flex items-center gap-1.5 rounded-full px-3 py-1.5 text-xs font-medium transition-colors",u===Xt?"bg-background text-foreground shadow-sm":"opacity-80 hover:opacity-100"),children:[e.jsx(rr,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline",children:Qn})]})}),e.jsx(tx,{children:Sn})]},Xt))})}),filters:or!=="portals"?e.jsxs(e.Fragment,{children:[e.jsxs(vs,{value:V,onValueChange:K,children:[e.jsx(gs,{className:"hub-glass h-10 w-[130px] rounded-full border-0 text-sm",children:e.jsx(bs,{placeholder:"All Types"})}),e.jsxs(ys,{children:[e.jsx(Ye,{value:"all",children:"All Types"}),e.jsx(Ye,{value:"buyer",children:"Buyer"}),e.jsx(Ye,{value:"seller",children:"Seller"}),e.jsx(Ye,{value:"dual",children:"Dual"}),e.jsx(Ye,{value:"referral",children:"Referral"}),e.jsx(Ye,{value:"lease",children:"Lease"})]})]}),e.jsxs(vs,{value:ce,onValueChange:ue,children:[e.jsx(gs,{className:"hub-glass h-10 w-[110px] rounded-full border-0 text-sm",children:e.jsx(bs,{placeholder:"Year"})}),e.jsxs(ys,{children:[e.jsx(Ye,{value:"all",children:"All Years"}),zt.map(Xt=>e.jsx(Ye,{value:Xt,children:Xt},Xt))]})]}),e.jsxs(vs,{value:Q,onValueChange:J,children:[e.jsxs(gs,{className:"hub-glass h-10 w-[150px] rounded-full border-0 text-sm",children:[e.jsx(Up,{className:"mr-1.5 h-3.5 w-3.5 opacity-70"}),e.jsx(bs,{placeholder:"All Tags"})]}),e.jsxs(ys,{className:"max-h-[300px]",children:[e.jsx(Ye,{value:"all",children:"All Tags"}),Mt.length===0&&e.jsx("div",{className:"px-2 py-1.5 text-xs text-muted-foreground",children:"No tags yet"}),Mt.map(Xt=>e.jsx(Ye,{value:Xt,children:Xt},Xt))]})]})]}):null}),or!=="portals"&&e.jsx(i8n,{items:Ts,active:ne,onToggle:Xt=>ee(rr=>rr===Xt?null:Xt)})]}),e.jsxs("div",{className:"flex-1 min-h-0 flex",children:[Se&&!s&&Re.length>0&&e.jsx(KPn,{members:Re,enabledMembers:Ee,onToggleMember:Ze,isOpen:fe,onToggleOpen:()=>je(Xt=>!Xt)}),e.jsx("div",{className:"flex-1 min-w-0 min-h-0 p-4 md:p-6 pt-4",children:Ar?e.jsx("div",{className:"flex gap-4 h-full",children:[1,2,3,4].map(Xt=>e.jsx("div",{className:"min-w-[280px] max-w-[320px] flex-shrink-0",children:e.jsx(on,{className:"h-full rounded-xl"})},Xt))}):or==="board"?e.jsxs(Oi,{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(Xt=>e.jsx(eIn,{stage:Xt,deals:In(Xt.id),onDealClick:Ds,onAddDeal:_t,onDragStart:Ps,onDragOver:_n,onDrop:Zs,isDragOver:T===Xt.id,isWonStage:Xt.is_won_stage,getOwnerInfo:Ke,tagsByDeal:lt,overdueTasksByDeal:ft},Xt.id))}),e.jsx(Nq,{orientation:"horizontal"})]}):or==="table"?e.jsx(Oi,{className:"h-full",children:e.jsx($In,{deals:js,stages:t||[],onDealClick:Ds,onStageChange:Un})}):or==="portals"?e.jsx(gVt,{}):e.jsx(Oi,{className:"h-full",children:e.jsxs("div",{className:"space-y-6",children:[t==null?void 0:t.map(Xt=>{const rr=In(Xt.id);return rr.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:Xt.color}}),e.jsx("h3",{className:"font-semibold",children:Xt.name}),e.jsxs("span",{className:"text-muted-foreground text-sm",children:["(",rr.length,")"]})]}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-3",children:rr.map(Qn=>e.jsx(hVt,{deal:Qn,onClick:()=>Ds(Qn),stages:t,onStageChange:Un,showStagePicker:!0,isWonStage:Xt.is_won_stage,ownerInfo:Ke(Qn),tags:lt[Qn.id]||[],overdueTaskCount:ft[Qn.id]||0},Qn.id))})]},Xt.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(_0,{className:"h-8 w-8 text-muted-foreground"})}),e.jsx("h3",{className:"font-semibold text-lg mb-2",children:"No deals yet"}),e.jsx("p",{className:"text-muted-foreground mb-4",children:"Start tracking your opportunities by adding your first deal"}),e.jsxs($,{onClick:()=>_t(),children:[e.jsx(sn,{className:"h-4 w-4 mr-2"}),"Add Your First Deal"]})]}),((r==null?void 0:r.length)||0)>0&&js.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(Vr,{className:"h-8 w-8 text-muted-foreground"})}),e.jsx("h3",{className:"font-semibold text-lg mb-2",children:"No matching deals"}),e.jsx("p",{className:"text-muted-foreground mb-4",children:"Try adjusting your search or filters"}),e.jsx($,{variant:"outline",onClick:fn,children:"Clear Filters"})]})]})})})]})]}),e.jsx(rIn,{open:m,onOpenChange:p,deal:y,defaultStageId:v}),e.jsx(FIn,{deal:y,open:x,onOpenChange:rn,onEdit:Xs,isWonStage:y?(Zn=t==null?void 0:t.find(Xt=>Xt.id===y.stage_id))==null?void 0:Zn.is_won_stage:!1,onAddToScorecard:Xt=>{B(Xt),I(!0),g(!1)}}),e.jsx(zIn,{open:M,onOpenChange:I,deal:D,onComplete:()=>{i(),B(null)}}),ze&&e.jsx(QIn,{open:!!ze,onOpenChange:Xt=>{Xt||ke(null)},dealId:ze.dealId,dealName:ze.dealName,fromStageName:ze.fromStageName,toStageName:ze.toStageName,toStageId:ze.toStageId,onConfirm:gr}),e.jsx(GPn,{open:ve,onOpenChange:ge})]})}function c8n(){return e.jsx(o8n,{children:e.jsx(l8n,{})})}function yVt({open:s,onOpenChange:t,editTask:n,defaultDealId:r,defaultStageId:a}){var W;const i=qIn(),l=VIn(),{data:o}=ETe(),c=Za(),{data:d}=ht({queryKey:["contacts-for-tasks",c],queryFn:async()=>{if(!c)return[];const{data:V,error:K}=await U.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(""),[x,g]=j.useState("none"),[y,b]=j.useState("none"),[v,N]=j.useState("medium"),[C,A]=j.useState("todo"),[T,P]=j.useState(),[M,I]=j.useState(!1),[D,B]=j.useState(!1);j.useEffect(()=>{n?(h(n.title),p(n.description||""),g(n.deal_id||"none"),b(n.contact_id||"none"),N(n.priority),A(n.status),P(n.due_date?Lp(n.due_date):void 0)):(h(""),p(""),g(r||"none"),b("none"),N("medium"),A("todo"),P(void 0))},[n,s,r]);const q=async()=>{if(!u.trim()){ae.error("Task title is required");return}try{const V={title:u.trim(),description:m.trim()||null,deal_id:x==="none"?null:x,contact_id:y==="none"?null:y,stage_id:a||null,priority:v,status:C,due_date:T?Hs(T,"yyyy-MM-dd"):null};n?(await l.mutateAsync({id:n.id,...V}),ae.success("Task updated")):(await i.mutateAsync(V),ae.success("Task created")),t(!1)}catch{ae.error("Failed to save task")}};return e.jsx(Os,{open:s,onOpenChange:t,children:e.jsxs(Rs,{className:"sm:max-w-[480px]",children:[e.jsx(Us,{children:e.jsx(zs,{children:n?"Edit Task":"New Task"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(se,{children:"Title *"}),e.jsx(be,{value:u,onChange:V=>h(V.target.value),placeholder:"e.g., Send inspection report"})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Description"}),e.jsx(Is,{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(se,{children:"Priority"}),e.jsxs(vs,{value:v,onValueChange:V=>N(V),children:[e.jsx(gs,{children:e.jsx(bs,{})}),e.jsxs(ys,{children:[e.jsx(Ye,{value:"low",children:"🟢 Low"}),e.jsx(Ye,{value:"medium",children:"🟡 Medium"}),e.jsx(Ye,{value:"high",children:"🟠 High"}),e.jsx(Ye,{value:"urgent",children:"🔴 Urgent"})]})]})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Status"}),e.jsxs(vs,{value:C,onValueChange:V=>A(V),children:[e.jsx(gs,{children:e.jsx(bs,{})}),e.jsxs(ys,{children:[e.jsx(Ye,{value:"todo",children:"To Do"}),e.jsx(Ye,{value:"in_progress",children:"In Progress"}),e.jsx(Ye,{value:"done",children:"Done"})]})]})]})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Due Date"}),e.jsxs(Sc,{children:[e.jsx(Cc,{asChild:!0,children:e.jsxs($,{variant:"outline",className:Tt("w-full justify-start text-left font-normal",!T&&"text-muted-foreground"),children:[e.jsx(ia,{className:"mr-2 h-4 w-4"}),T?Hs(T,"PPP"):"Pick a date"]})}),e.jsx(xc,{className:"w-auto p-0",align:"start",children:e.jsx(y1,{mode:"single",selected:T,onSelect:P,initialFocus:!0,className:"p-3 pointer-events-auto"})})]})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Link to Deal"}),e.jsxs(Sc,{open:M,onOpenChange:I,children:[e.jsx(Cc,{asChild:!0,children:e.jsxs($,{variant:"outline",role:"combobox",className:"w-full justify-between font-normal",children:[e.jsxs("span",{className:"flex items-center gap-2 truncate",children:[e.jsx(Ai,{className:"h-3.5 w-3.5 text-muted-foreground shrink-0"}),x!=="none"?((W=o==null?void 0:o.find(V=>V.id===x))==null?void 0:W.deal_name)||"Select deal":"No Deal"]}),e.jsx(sw,{className:"h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(xc,{className:"w-[--radix-popover-trigger-width] p-0",align:"start",children:e.jsxs(pw,{children:[e.jsx(fw,{placeholder:"Search deals..."}),e.jsxs(xw,{children:[e.jsx(gw,{children:"No deals found."}),e.jsxs($b,{children:[e.jsxs(iv,{value:"no-deal",onSelect:()=>{g("none"),I(!1)},children:[e.jsx(oa,{className:Tt("mr-2 h-4 w-4",x==="none"?"opacity-100":"opacity-0")}),"No Deal"]}),o==null?void 0:o.map(V=>e.jsxs(iv,{value:V.deal_name,onSelect:()=>{g(V.id),I(!1)},children:[e.jsx(oa,{className:Tt("mr-2 h-4 w-4",x===V.id?"opacity-100":"opacity-0")}),V.deal_name]},V.id))]})]})]})})]})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Link to Contact"}),e.jsxs(Sc,{open:D,onOpenChange:B,children:[e.jsx(Cc,{asChild:!0,children:e.jsxs($,{variant:"outline",role:"combobox",className:"w-full justify-between font-normal",children:[e.jsxs("span",{className:"flex items-center gap-2 truncate",children:[e.jsx(Lo,{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(sw,{className:"h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(xc,{className:"w-[--radix-popover-trigger-width] p-0",align:"start",children:e.jsxs(pw,{children:[e.jsx(fw,{placeholder:"Search contacts..."}),e.jsxs(xw,{children:[e.jsx(gw,{children:"No contacts found."}),e.jsxs($b,{children:[e.jsxs(iv,{value:"no-contact",onSelect:()=>{b("none"),B(!1)},children:[e.jsx(oa,{className:Tt("mr-2 h-4 w-4",y==="none"?"opacity-100":"opacity-0")}),"No Contact"]}),d==null?void 0:d.map(V=>e.jsxs(iv,{value:`${V.first_name} ${V.last_name}`,onSelect:()=>{b(V.id),B(!1)},children:[e.jsx(oa,{className:Tt("mr-2 h-4 w-4",y===V.id?"opacity-100":"opacity-0")}),V.first_name," ",V.last_name]},V.id))]})]})]})})]})]}),e.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[e.jsx($,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsx($,{onClick:q,disabled:i.isPending||l.isPending,children:n?"Save Changes":"Create Task"})]})]})]})})}const d8n={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 u8n({tasks:s}){const t=TTe(),n=HIn(),r=Vn(),[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{ae.error("Failed to update task")}},o=async u=>{try{await n.mutateAsync(u),ae.success("Task deleted")}catch{ae.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(Fr,{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(Tvt,{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(Ai,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("h3",{className:"font-medium text-sm",children:h.dealName}),e.jsxs($e,{variant:"secondary",className:"ml-auto text-xs",children:[h.tasks.filter(m=>m.status==="done").length,"/",h.tasks.length]}),e.jsx(Ja,{className:"h-3.5 w-3.5 text-muted-foreground"})]}),h.tasks.map(m=>e.jsx(Tvt,{task:m,onToggle:l,onDelete:o,onEdit:i,onNavigateDeal:p=>r(`/mission-control/pipeline?deal=${p}`)},m.id))]},u)),a&&e.jsx(yVt,{open:!!a,onOpenChange:()=>i(null),editTask:a})]})}function Tvt({task:s,onToggle:t,onDelete:n,onEdit:r,onNavigateDeal:a}){const i=s.status==="done",l=!i&&s.due_date&&d5(Lp(s.due_date))&&!x0(Lp(s.due_date)),o=!i&&s.due_date&&x0(Lp(s.due_date)),c=d8n[s.priority];return e.jsxs("div",{className:Tt("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(Fr,{className:"h-5 w-5 text-emerald-500"}):e.jsx(Bp,{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:Tt("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(Lo,{className:"h-2.5 w-2.5"}),s.contact.first_name," ",s.contact.last_name]})]})]}),e.jsxs($e,{variant:"outline",className:Tt("text-[10px] shrink-0",c.color),children:[c.dot," ",c.label]}),s.due_date&&e.jsxs("span",{className:Tt("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(Hr,{className:"h-3 w-3"}),Hs(Lp(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(bm,{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(Pn,{className:"h-3.5 w-3.5 text-destructive"})})]})]})}const h8n=[{status:"todo",label:"To Do",icon:Bp,color:"border-t-slate-400"},{status:"in_progress",label:"In Progress",icon:Sh,color:"border-t-blue-500"},{status:"done",label:"Done",icon:Fr,color:"border-t-emerald-500"}],m8n={urgent:"🔴",high:"🟠",medium:"🟡",low:"🟢"};function p8n({tasks:s}){const t=TTe(),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{ae.error("Failed to move task")}};return e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4",children:h8n.map(i=>e.jsxs("div",{className:Tt("border rounded-lg border-t-4 bg-muted/20",i.color),onDragOver:l=>l.preventDefault(),onDrop:l=>a(l,i.status),children:[e.jsxs("div",{className:"px-4 py-3 flex items-center gap-2",children:[e.jsx(i.icon,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("h3",{className:"font-semibold text-sm",children:i.label}),e.jsx($e,{variant:"secondary",className:"ml-auto text-xs",children:n[i.status].length})]}),e.jsxs("div",{className:"p-2 space-y-2 min-h-[200px]",children:[n[i.status].map(l=>e.jsx(f8n,{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 f8n({task:s,onDragStart:t}){const n=s.status==="done",r=!n&&s.due_date&&d5(Lp(s.due_date))&&!x0(Lp(s.due_date)),a=!n&&s.due_date&&x0(Lp(s.due_date));return e.jsx("div",{draggable:!0,onDragStart:i=>t(i,s.id),className:Tt("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:m8n[s.priority]}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:Tt("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(Ai,{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(Lo,{className:"h-2.5 w-2.5"}),s.contact.first_name," ",s.contact.last_name]})]}),s.due_date&&e.jsxs("div",{className:Tt("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(Hr,{className:"h-2.5 w-2.5"}),r?"Overdue — ":a?"Due today — ":"",Hs(Lp(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 Mvt={urgent:"🔴",high:"🟠",medium:"🟡",low:"🟢"};function x8n({tasks:s}){const[t,n]=j.useState(new Date),r=TTe(),a=Hu(t),i=e1(t),l=Tg(a),o=eU(i),c=TFe({start:l,end:o}),d=j.useMemo(()=>{const m=new Map;return s.forEach(p=>{if(!p.due_date)return;const x=p.due_date,g=m.get(x)||[];g.push(p),m.set(x,g)}),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{ae.error("Failed to update task")}};return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx($,{variant:"ghost",size:"icon",onClick:()=>n(T8(t,1)),children:e.jsx(Ic,{className:"h-4 w-4"})}),e.jsx("h3",{className:"font-semibold",children:Hs(t,"MMMM yyyy")}),e.jsx($,{variant:"ghost",size:"icon",onClick:()=>n(zx(t,1)),children:e.jsx(Ja,{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=Hs(m,"yyyy-MM-dd"),x=d.get(p)||[],g=Cq(m,t),y=x0(m);return e.jsxs("div",{className:Tt("border-r border-b min-h-[100px] p-1",!g&&"bg-muted/30",y&&"bg-primary/5"),children:[e.jsx("div",{className:Tt("text-xs font-medium mb-1 text-right px-1",!g&&"text-muted-foreground/40",y&&"text-primary font-bold"),children:Hs(m,"d")}),e.jsxs("div",{className:"space-y-0.5",children:[x.slice(0,3).map(b=>e.jsxs("button",{onClick:()=>h(b),className:Tt("w-full text-left text-[10px] px-1 py-0.5 rounded truncate flex items-center gap-0.5 hover:bg-muted transition-colors",b.status==="done"?"text-muted-foreground line-through":"text-foreground"),children:[b.status==="done"?e.jsx(Fr,{className:"h-2.5 w-2.5 text-emerald-500 shrink-0"}):e.jsx(Bp,{className:"h-2.5 w-2.5 shrink-0"}),e.jsxs("span",{className:"truncate",children:[Mvt[b.priority]," ",b.title]})]},b.id)),x.length>3&&e.jsxs("p",{className:"text-[9px] text-muted-foreground text-center",children:["+",x.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:Tt("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(Fr,{className:"h-3.5 w-3.5 text-emerald-500 shrink-0"}):e.jsx(Bp,{className:"h-3.5 w-3.5 shrink-0"}),e.jsxs("span",{className:"truncate",children:[Mvt[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 g8n={urgent:"🔴",high:"🟠",medium:"🟡",low:"🟢"};function y8n({open:s,onOpenChange:t,stages:n}){var b;const[r,a]=j.useState(((b=n[0])==null?void 0:b.id)||""),{data:i,isLoading:l}=WIn(r||void 0),o=KIn(),c=YIn(),[d,u]=j.useState(""),[h,m]=j.useState("medium"),[p,x]=j.useState(""),g=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(""),x(""),ae.success("Template added")}catch{ae.error("Failed to add template")}},y=async v=>{try{await c.mutateAsync(v),ae.success("Template deleted")}catch{ae.error("Failed to delete template")}};return e.jsx(Os,{open:s,onOpenChange:t,children:e.jsxs(Rs,{className:"sm:max-w-[560px]",children:[e.jsx(Us,{children:e.jsxs(zs,{className:"flex items-center gap-2",children:[e.jsx(NK,{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(se,{children:"Pipeline Stage"}),e.jsx("div",{className:"flex flex-wrap gap-1.5 mt-1.5",children:n.filter(v=>!v.is_won_stage&&!v.is_lost_stage).map(v=>e.jsx("button",{onClick:()=>a(v.id),className:Tt("px-3 py-1.5 rounded-full text-xs font-medium border transition-colors",r===v.id?"border-primary bg-primary/10 text-primary":"border-border hover:bg-muted"),children:v.name},v.id))})]}),e.jsx(Oi,{className:"max-h-[250px]",children:e.jsxs("div",{className:"space-y-1.5",children:[i==null?void 0:i.map((v,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:g8n[v.priority]}),e.jsx("span",{className:"text-sm flex-1 truncate",children:v.title}),v.default_due_offset_days&&e.jsxs($e,{variant:"outline",className:"text-[10px]",children:["+",v.default_due_offset_days,"d"]}),e.jsx("button",{onClick:()=>y(v.id),className:"opacity-0 group-hover:opacity-100 p-1 hover:bg-destructive/10 rounded transition-opacity",children:e.jsx(Pn,{className:"h-3.5 w-3.5 text-destructive"})})]},v.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(se,{className:"text-xs text-muted-foreground",children:"Add Template Task"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(be,{placeholder:"Task title...",value:d,onChange:v=>u(v.target.value),className:"flex-1",onKeyDown:v=>v.key==="Enter"&&g()}),e.jsxs(vs,{value:h,onValueChange:v=>m(v),children:[e.jsx(gs,{className:"w-[100px]",children:e.jsx(bs,{})}),e.jsxs(ys,{children:[e.jsx(Ye,{value:"low",children:"🟢 Low"}),e.jsx(Ye,{value:"medium",children:"🟡 Med"}),e.jsx(Ye,{value:"high",children:"🟠 High"}),e.jsx(Ye,{value:"urgent",children:"🔴 Urgent"})]})]})]}),e.jsxs("div",{className:"flex gap-2 items-end",children:[e.jsxs("div",{className:"flex-1",children:[e.jsx(se,{className:"text-xs",children:"Due offset (days from entering stage)"}),e.jsx(be,{type:"number",placeholder:"e.g., 7",value:p,onChange:v=>x(v.target.value)})]}),e.jsxs($,{onClick:g,disabled:!d.trim()||o.isPending,children:[e.jsx(sn,{className:"h-4 w-4 mr-1"}),"Add"]})]})]})]})})}function v8n(){const{data:s,isLoading:t}=fVt(),{data:n}=gte(),[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,x]=j.useState(!1),[g,y]=j.useState(!1),b=j.useMemo(()=>{if(!s)return[];const C=new Map;return s.forEach(A=>{A.deal&&C.set(A.deal.id,A.deal.deal_name)}),Array.from(C,([A,T])=>({id:A,name:T}))},[s]),v=j.useMemo(()=>s?s.filter(C=>{var D,B,q,W;const A=i.toLowerCase(),T=!A||C.title.toLowerCase().includes(A)||((B=(D=C.deal)==null?void 0:D.deal_name)==null?void 0:B.toLowerCase().includes(A))||`${((q=C.contact)==null?void 0:q.first_name)||""} ${((W=C.contact)==null?void 0:W.last_name)||""}`.toLowerCase().includes(A),P=o==="all"||o==="active"&&C.status!=="done"||o==="todo"&&C.status==="todo"||o==="in_progress"&&C.status==="in_progress"||o==="done"&&C.status==="done"||o==="overdue"&&C.status!=="done"&&C.due_date&&d5(Lp(C.due_date))&&!x0(Lp(C.due_date)),M=d==="all"||C.priority===d,I=h==="all"||h==="no_deal"&&!C.deal_id||C.deal_id===h;return T&&P&&M&&I}):[],[s,i,o,d,h]),N=j.useMemo(()=>{if(!s)return{total:0,overdue:0,dueToday:0,dueThisWeek:0,completed:0};const C=s.filter(A=>A.status!=="done");return{total:C.length,overdue:C.filter(A=>A.due_date&&d5(Lp(A.due_date))&&!x0(Lp(A.due_date))).length,dueToday:C.filter(A=>A.due_date&&x0(Lp(A.due_date))).length,dueThisWeek:C.filter(A=>A.due_date&&Wvs(Lp(A.due_date))).length,completed:s.filter(A=>A.status==="done").length}},[s]);return e.jsx(Ks,{children:e.jsxs("div",{className:"space-y-6 p-4 md:p-6 max-w-[1600px] mx-auto",children:[e.jsxs("div",{className:"flex flex-col md:flex-row md:items-center justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold tracking-tight",children:"Tasks"}),e.jsx("p",{className:"text-muted-foreground text-sm",children:"Manage tasks across deals and contacts"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs($,{variant:"outline",size:"sm",onClick:()=>y(!0),children:[e.jsx($j,{className:"h-4 w-4 mr-1"}),"Templates"]}),e.jsxs($,{size:"sm",onClick:()=>x(!0),children:[e.jsx(sn,{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(Sg,{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(mc,{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(Hr,{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(Nl,{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(Fr,{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(Vr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(be,{placeholder:"Search tasks...",value:i,onChange:C=>l(C.target.value),className:"pl-9"})]}),e.jsxs(vs,{value:d,onValueChange:u,children:[e.jsx(gs,{className:"w-[130px]",children:e.jsx(bs,{placeholder:"Priority"})}),e.jsxs(ys,{children:[e.jsx(Ye,{value:"all",children:"All Priorities"}),e.jsx(Ye,{value:"urgent",children:"🔴 Urgent"}),e.jsx(Ye,{value:"high",children:"🟠 High"}),e.jsx(Ye,{value:"medium",children:"🟡 Medium"}),e.jsx(Ye,{value:"low",children:"🟢 Low"})]})]}),e.jsxs(vs,{value:h,onValueChange:m,children:[e.jsx(gs,{className:"w-[160px]",children:e.jsx(bs,{placeholder:"Deal"})}),e.jsxs(ys,{children:[e.jsx(Ye,{value:"all",children:"All Deals"}),e.jsx(Ye,{value:"no_deal",children:"No Deal"}),b.map(C=>e.jsx(Ye,{value:C.id,children:C.name},C.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(Sg,{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(a5,{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(Nl,{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(u8n,{tasks:v}),r==="kanban"&&e.jsx(p8n,{tasks:v}),r==="calendar"&&e.jsx(x8n,{tasks:v})]}),e.jsx(yVt,{open:p,onOpenChange:x}),e.jsx(y8n,{open:g,onOpenChange:y,stages:n||[]})]})})}function b8n(s){const t=mXe(s);return t?t.toLocaleDateString("en-US",{weekday:"short",month:"short",day:"numeric"}):""}function _8n({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 xae({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:Tt("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 w8n(){const s=Vn(),{data:t,isLoading:n}=AIn(),r=TTe(),[a,i]=j.useState(""),[l,o]=j.useState(!1),[c,d]=j.useState("all"),u=j.useMemo(()=>{let v=t||[];c==="contract"&&(v=v.filter(C=>!!C.contract_date));const N=a.trim().toLowerCase();return N&&(v=v.filter(C=>{var A,T,P,M;return((A=C.deal_name)==null?void 0:A.toLowerCase().includes(N))||((T=C.property_address)==null?void 0:T.toLowerCase().includes(N))||`${((P=C.contact)==null?void 0:P.first_name)??""} ${((M=C.contact)==null?void 0:M.last_name)??""}`.toLowerCase().includes(N)})),v},[t,a,c]),h=j.useMemo(()=>{const v=[];return(u||[]).forEach(N=>{QW.forEach(C=>{const A=N[C.key],T=aS(A);A&&T!==null&&T<=30&&v.push({id:`${N.id}-${C.key}`,kind:"date",label:C.label,dealId:N.id,dealName:N.deal_name,date:A,days:T})}),N.tasks.filter(C=>C.status!=="done"&&C.due_date).forEach(C=>{const A=aS(C.due_date);A!==null&&A<=30&&v.push({id:C.id,kind:"task",label:C.title,dealId:N.id,dealName:N.deal_name,date:C.due_date,days:A,priority:C.priority})})}),v.sort((N,C)=>N.days-C.days)},[u]),m=j.useMemo(()=>({overdue:h.filter(v=>v.days<0),today:h.filter(v=>v.days===0),week:h.filter(v=>v.days>0&&v.days<=7),later:h.filter(v=>v.days>7)}),[h]),p=j.useMemo(()=>{const v=t||[],N=v.filter(T=>{const P=aS(T.target_close_date);return P!==null&&P>=0&&P<=7}).length,C=v.reduce((T,P)=>T+P.tasks.filter(M=>{const I=aS(M.due_date);return M.status!=="done"&&I!==null&&I<0}).length,0),A=v.reduce((T,P)=>T+(Number(P.expected_price)||0),0);return{active:v.length,closingSoon:N,overdueTasks:C,volume:A}},[t]),x=v=>v.tasks.length===0?0:v.tasks.filter(N=>N.status==="done").length/v.tasks.length*100,g=v=>s(`/mission-control/pipeline?deal=${v}`),y=async v=>{try{await r.mutateAsync({id:v,status:"done"}),ae.success("Task completed")}catch{ae.error("Could not update task")}},b=({title:v,items:N,tone:C})=>{if(N.length===0)return null;const A=C==="danger"?"bg-destructive":C==="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:Tt("h-1.5 w-1.5 rounded-full",A)}),e.jsx("p",{className:"text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:v}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:["(",N.length,")"]})]}),N.slice(0,12).map(T=>e.jsxs("div",{className:Tt("group flex items-center gap-3 rounded-lg border px-3 py-2 transition-colors hover:bg-muted/50",C==="danger"&&"border-destructive/30 bg-destructive/5"),children:[T.kind==="task"?e.jsx(ui,{className:"shrink-0",onCheckedChange:()=>y(T.id),"aria-label":`Complete ${T.label}`}):e.jsx(Xu,{className:"h-4 w-4 text-muted-foreground shrink-0"}),e.jsxs("button",{type:"button",onClick:()=>g(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," · ",b8n(T.date)]})]}),e.jsx("span",{className:Tt("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(Ks,{children:[e.jsxs("div",{className:"p-4 sm:p-6 space-y-6 max-w-[1400px] mx-auto",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold tracking-tight",children:"Transaction Coordinator"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Every deadline, every checklist, one screen. Nothing slips."})]}),e.jsxs($,{onClick:()=>o(!0),className:"gap-2 shrink-0",children:[e.jsx(wf,{className:"h-4 w-4"}),"Playbooks"]})]}),e.jsxs("div",{className:"grid grid-cols-2 lg:grid-cols-4 gap-3",children:[e.jsx(xae,{icon:v0,label:"Active transactions",value:p.active}),e.jsx(xae,{icon:yd,label:"Closing within 7 days",value:p.closingSoon,tone:"warn"}),e.jsx(xae,{icon:mc,label:"Overdue tasks",value:p.overdueTasks,tone:p.overdueTasks>0?"danger":"good"}),e.jsx(xae,{icon:Il,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(Vr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(be,{placeholder:"Search transactions, addresses, or clients...",value:a,onChange:v=>i(v.target.value),className:"pl-9"})]}),e.jsxs("div",{className:"flex gap-1 rounded-lg border p-1 bg-card",children:[e.jsx($,{size:"sm",variant:c==="all"?"default":"ghost",onClick:()=>d("all"),className:"h-8",children:"All active"}),e.jsx($,{size:"sm",variant:c==="contract"?"default":"ghost",onClick:()=>d("contract"),className:"h-8",children:"Under contract"})]})]}),n?e.jsx("div",{className:"flex justify-center py-20",children:e.jsx(Ht,{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(Xu,{className:"h-4 w-4 text-primary"}),e.jsx("h2",{className:"text-sm font-semibold",children:"Deadline Radar"}),e.jsx($e,{variant:"secondary",className:"text-[10px] ml-auto",children:"next 30 days"})]}),h.length===0?e.jsxs("div",{className:"text-center py-10",children:[e.jsx(Fr,{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(b,{title:"Overdue",items:m.overdue,tone:"danger"}),e.jsx(b,{title:"Today",items:m.today,tone:"warn"}),e.jsx(b,{title:"This week",items:m.week,tone:"warn"}),e.jsx(b,{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(sa,{className:"h-8 w-8 text-muted-foreground mx-auto mb-3"}),e.jsx("p",{className:"font-medium",children:"No active transactions"}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:"Deals in progress will appear here with their full deadline chain."}),e.jsx($,{variant:"outline",className:"mt-4",onClick:()=>s("/mission-control/pipeline"),children:"Go to Deal Pipeline"})]}):u.map(v=>{const N=x(v),C=aS(v.target_close_date),A=v.tasks.filter(M=>M.status!=="done"),T=A.filter(M=>{const I=aS(M.due_date);return I!==null&&I<0}),P=A.filter(M=>M.due_date).sort((M,I)=>(aS(M.due_date)??0)-(aS(I.due_date)??0))[0];return e.jsx("button",{type:"button",onClick:()=>g(v.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(_8n,{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:v.deal_name}),e.jsxs("p",{className:"text-xs text-muted-foreground truncate",children:[v.property_address||"Address TBD",v.contact&&` · ${v.contact.first_name} ${v.contact.last_name}`]})]}),e.jsx(Ja,{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:[v.stage&&e.jsx("span",{className:"text-[10px] px-2 py-0.5 rounded-full font-medium",style:{backgroundColor:`${v.stage.color}1f`,color:v.stage.color},children:v.stage.name}),e.jsx($e,{variant:"outline",className:"text-[10px] capitalize",children:v.deal_type}),C!==null&&e.jsx($e,{variant:"secondary",className:Tt("text-[10px]",C<0&&"bg-destructive/10 text-destructive",C>=0&&C<=7&&"bg-amber-500/10 text-amber-700 dark:text-amber-400"),children:C<0?`Closing ${Math.abs(C)}d overdue`:`Closes in ${C}d`}),T.length>0&&e.jsxs($e,{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(Ki,{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:[v.tasks.filter(M=>M.status==="done").length," of"," ",v.tasks.length," steps complete"]}),P&&e.jsxs("p",{className:"text-[11px] text-muted-foreground truncate max-w-[55%]",children:["Next: ",P.title]})]})]}),v.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."})]})]})},v.id)})})]})]}),e.jsx(pVt,{open:l,onOpenChange:o})]})}function vVt(){const s=Za();return ht({queryKey:["portal-referrals",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await U.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 j8n(){const s=ts();return yt({mutationFn:async({id:t,...n})=>{const{data:r,error:a}=await U.from("portal_referrals").update(n).eq("id",t).select().single();if(a)throw a;return r},onSuccess:()=>{s.invalidateQueries({queryKey:["portal-referrals"]})}})}function N8n(){const s=ts();return yt({mutationFn:async t=>{const{error:n}=await U.from("portal_referrals").delete().eq("id",t);if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["portal-referrals"]})}})}const k8n=s=>new Intl.DateTimeFormat("en-US",{timeZone:"America/New_York",month:"short",day:"numeric",year:"numeric"}).format(new Date(s)),yDe=[{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"}],S8n={buying:"Buying",selling:"Selling",both:"Buying & Selling",unsure:"Not sure yet"};function bVt(){const{data:s=[],isLoading:t}=vVt(),n=j8n(),r=N8n(),[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,x)=>{n.mutate({id:p.id,status:x}),ae.success("Status updated")},h=p=>{const x=l[p.id];n.mutate({id:p.id,agent_notes:x}),o(g=>{const{[p.id]:y,...b}=g;return b}),ae.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(Ul,{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(Co,{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"},...yDe.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(Ht,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):c.length===0?e.jsx(_e,{children:e.jsxs(Oe,{className:"py-12 text-center",children:[e.jsx(Co,{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 b,v;const x=yDe.find(N=>N.value===p.status),g=(b=p.client_portals)==null?void 0:b.slug,y=p.referrer_name||((v=p.client_portals)==null?void 0:v.client_name)||"Anonymous client";return e.jsxs(_e,{children:[e.jsx(Bt,{className:"pb-3",children:e.jsxs("div",{className:"flex items-start justify-between flex-wrap gap-2",children:[e.jsxs("div",{children:[e.jsx(Ut,{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(ia,{className:"h-3 w-3"}),"Referred by ",e.jsx("span",{className:"font-medium text-foreground",children:y})," ·"," ",k8n(p.created_at)]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx($e,{variant:"outline",className:x==null?void 0:x.className,children:(x==null?void 0:x.label)||p.status}),e.jsxs(vs,{value:p.status,onValueChange:N=>u(p,N),children:[e.jsx(gs,{className:"h-8 w-[130px] text-xs",children:e.jsx(bs,{})}),e.jsx(ys,{children:yDe.map(N=>e.jsx(Ye,{value:N.value,className:"text-xs",children:N.label},N.value))})]})]})]})}),e.jsxs(Oe,{className:"space-y-3",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[p.friend_interest&&e.jsx($e,{variant:"secondary",className:"text-xs",children:S8n[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(nn,{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(ya,{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(Ed,{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(Is,{value:l[p.id],onChange:N=>o(C=>({...C,[p.id]:N.target.value})),rows:3,className:"text-sm"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx($,{size:"sm",onClick:()=>h(p),children:"Save"}),e.jsx($,{size:"sm",variant:"ghost",onClick:()=>o(N=>{const{[p.id]:C,...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:[g&&e.jsxs("a",{href:`/portal/${g}`,target:"_blank",rel:"noopener noreferrer",className:"text-xs text-muted-foreground hover:text-primary inline-flex items-center gap-1",children:[e.jsx(Tr,{className:"h-3 w-3"}),"View source portal"]}),e.jsx($,{variant:"ghost",size:"sm",onClick:()=>m(p),className:"text-destructive hover:text-destructive ml-auto h-8",children:e.jsx(Pn,{className:"h-3.5 w-3.5"})})]})]})]},p.id)})})]})}function _Vt({vendor:s,onEdit:t,onDelete:n,onToggleVisible:r,isVisible:a,showOwnerBadge:i,clickCount:l}){var c;const o=((c=Pq.find(d=>d.value===s.category))==null?void 0:c.label)||s.category;return e.jsxs(_e,{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(Ad,{className:"w-3.5 h-3.5 text-amber-600","aria-label":"Required"}),s.is_featured&&e.jsx(Qa,{className:"w-3.5 h-3.5 text-amber-500 fill-amber-500","aria-label":"Featured"})]}),s.company&&e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:s.company}),e.jsxs("div",{className:"flex items-center gap-1 mt-1 flex-wrap",children:[e.jsx($e,{variant:"secondary",className:"text-[10px]",children:o}),i==="brokerage"&&e.jsx($e,{variant:"outline",className:"text-[10px]",children:"Brokerage"}),i==="agent"&&e.jsx($e,{variant:"outline",className:"text-[10px]",children:"Personal"}),!s.is_active&&e.jsx($e,{variant:"destructive",className:"text-[10px]",children:"Inactive"}),typeof l=="number"&&l>0&&e.jsxs($e,{variant:"outline",className:"text-[10px]",children:[l," clicks"]})]})]})]}),s.description&&e.jsx("p",{className:"text-sm text-muted-foreground line-clamp-2",children:s.description}),e.jsxs("div",{className:"text-xs text-muted-foreground space-y-1",children:[s.phone&&e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(ya,{className:"w-3 h-3"}),s.phone]}),s.email&&e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(nn,{className:"w-3 h-3"}),e.jsx("span",{className:"truncate",children:s.email})]}),s.website&&e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(Gl,{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(ia,{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(ai,{className:"w-3 h-3"}),e.jsx("span",{className:"truncate",children:s.address})]})]}),e.jsxs("div",{className:"flex items-center gap-2 pt-2 border-t",children:[r&&e.jsxs($,{size:"sm",variant:a?"default":"outline",onClick:()=>r(!a),disabled:s.is_required&&!a,className:"flex-1",children:[a?e.jsx(ga,{className:"w-3.5 h-3.5 mr-1.5"}):e.jsx(b0,{className:"w-3.5 h-3.5 mr-1.5"}),a?"Showing in portals":"Hidden"]}),t&&e.jsx($,{size:"sm",variant:"ghost",onClick:t,children:e.jsx(bm,{className:"w-3.5 h-3.5"})}),n&&e.jsx($,{size:"sm",variant:"ghost",onClick:n,className:"text-destructive",children:e.jsx(Pn,{className:"w-3.5 h-3.5"})})]})]})}function wVt({open:s,onOpenChange:t,vendor:n,ownerType:r,brokerageId:a,agentUserId:i,showBrokerageOnlyFields:l}){const o=XSs(),[c,d]=j.useState({}),[u,h]=j.useState(!1),m=j.useRef(null),p=async y=>{if(!y.type.startsWith("image/")){ae.error("Please select an image");return}if(y.size>5*1024*1024){ae.error("Image must be under 5MB");return}h(!0);try{const b=y.name.split(".").pop()||"png",v=`${r}/${a||i||"misc"}/${Date.now()}.${b}`,{error:N}=await U.storage.from("vendor-logos").upload(v,y,{upsert:!0,contentType:y.type});if(N)throw N;const{data:C}=U.storage.from("vendor-logos").getPublicUrl(v);d(A=>({...A,logo_url:C.publicUrl})),ae.success("Logo uploaded")}catch(b){ae.error(b.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 x=(y,b)=>d(v=>({...v,[y]:b})),g=async()=>{var y;if(!((y=c.name)!=null&&y.trim())){ae.error("Name is required");return}try{await o.mutateAsync(c),ae.success(n?"Vendor updated":"Vendor added"),t(!1)}catch(b){ae.error(b.message||"Failed to save vendor")}};return e.jsx(Os,{open:s,onOpenChange:t,children:e.jsxs(Rs,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsx(Us,{children:e.jsx(zs,{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(se,{children:"Contact Name *"}),e.jsx(be,{value:c.name||"",onChange:y=>x("name",y.target.value),placeholder:"Bob Smith"})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Company"}),e.jsx(be,{value:c.company||"",onChange:y=>x("company",y.target.value),placeholder:"Smith Inspections"})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Category"}),e.jsxs(vs,{value:c.category,onValueChange:y=>x("category",y),children:[e.jsx(gs,{children:e.jsx(bs,{})}),e.jsx(ys,{children:Pq.map(y=>e.jsx(Ye,{value:y.value,children:y.label},y.value))})]})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Phone"}),e.jsx(be,{value:c.phone||"",onChange:y=>x("phone",y.target.value),placeholder:"(555) 123-4567"})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Email"}),e.jsx(be,{type:"email",value:c.email||"",onChange:y=>x("email",y.target.value),placeholder:"bob@smithinsp.com"})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Website"}),e.jsx(be,{value:c.website||"",onChange:y=>x("website",y.target.value),placeholder:"https://..."})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Logo"}),e.jsx("input",{ref:m,type:"file",accept:"image/*",className:"hidden",onChange:y=>{var v;const b=(v=y.target.files)==null?void 0:v[0];b&&p(b),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:()=>x("logo_url",""),className:"absolute -top-2 -right-2 bg-background border rounded-full p-0.5 shadow","aria-label":"Remove logo",children:e.jsx(pr,{className:"h-3 w-3"})})]}):e.jsx("div",{className:"h-14 w-14 rounded-md border border-dashed flex items-center justify-center text-muted-foreground",children:e.jsx(si,{className:"h-5 w-5"})}),e.jsxs($,{type:"button",variant:"outline",size:"sm",onClick:()=>{var y;return(y=m.current)==null?void 0:y.click()},disabled:u,children:[u?e.jsx(Ht,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(si,{className:"h-4 w-4 mr-2"}),c.logo_url?"Replace":"Upload Logo"]})]})]}),e.jsxs("div",{className:"md:col-span-2",children:[e.jsx(se,{children:"Address"}),e.jsx(be,{value:c.address||"",onChange:y=>x("address",y.target.value)})]}),e.jsxs("div",{className:"md:col-span-2",children:[e.jsx(se,{children:"Description"}),e.jsx(Is,{rows:3,value:c.description||"",onChange:y=>x("description",y.target.value),placeholder:"Why your clients should use this vendor..."})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Primary Action"}),e.jsxs(vs,{value:c.action_type,onValueChange:y=>x("action_type",y),children:[e.jsx(gs,{children:e.jsx(bs,{})}),e.jsx(ys,{children:KSs.map(y=>e.jsx(Ye,{value:y.value,children:y.label},y.value))})]})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Booking URL (Calendly etc.)"}),e.jsx(be,{value:c.booking_url||"",onChange:y=>x("booking_url",y.target.value),placeholder:"https://calendly.com/..."})]}),e.jsxs("div",{className:"md:col-span-2",children:[e.jsx(se,{children:"Compliance Disclosure (optional)"}),e.jsx(Is,{rows:2,value:c.disclosure_text||"",onChange:y=>x("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(se,{className:"font-medium",children:"Active"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Show this vendor in client portals"})]}),e.jsx(Tn,{checked:!!c.is_active,onCheckedChange:y=>x("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(se,{className:"font-medium",children:"Featured"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Highlight in agent library"})]}),e.jsx(Tn,{checked:!!c.is_featured,onCheckedChange:y=>x("is_featured",y)})]}),e.jsxs("div",{className:"flex items-center justify-between border rounded-lg p-3",children:[e.jsxs("div",{children:[e.jsx(se,{className:"font-medium",children:"Required"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Agents cannot hide"})]}),e.jsx(Tn,{checked:!!c.is_required,onCheckedChange:y=>x("is_required",y)})]})]})]}),e.jsxs(kr,{children:[e.jsx($,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsx($,{onClick:g,disabled:o.isPending,children:o.isPending?"Saving...":"Save Vendor"})]})]})})}function jVt({embedded:s=!1}={}){const t=Za(),{brokerageId:n}=_s(),{data:r,isLoading:a}=ZSs(),{data:i={}}=zTt("agent",t),l=OTt(),o=QSs(),[c,d]=j.useState(null),[u,h]=j.useState(!1),[m,p]=j.useState(""),[x,g]=j.useState("all"),y=(r==null?void 0:r.vendors)||[],b=(r==null?void 0:r.selections)||[],v=j.useMemo(()=>{const D=new Map;return b.forEach(B=>D.set(B.vendor_id,B.is_visible)),D},[b]),N=j.useMemo(()=>y.filter(D=>!(x!=="all"&&D.category!==x||m&&!`${D.name} ${D.company||""}`.toLowerCase().includes(m.toLowerCase()))),[y,m,x]),C=N.filter(D=>D.owner_type==="agent"),A=N.filter(D=>D.owner_type==="brokerage"),T=async D=>{if(await Yi("Delete this vendor?"))try{await l.mutateAsync(D),ae.success("Vendor deleted")}catch(B){ae.error(B.message)}},P=async(D,B)=>{try{await o.mutateAsync({vendorId:D,isVisible:B})}catch(q){ae.error(q.message)}},M=D=>D.is_required?!0:v.get(D.id)??D.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(ix,{className:"w-6 h-6 text-primary"}),"My Vendor Library"]}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:"Curate trusted partners that show up in your client portals — inspector, lender, movers and more."})]}),e.jsxs($,{onClick:()=>{d(null),h(!0)},children:[e.jsx(sn,{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(Vr,{className:"w-4 h-4 absolute left-3 top-1/2 -translate-y-1/2 text-muted-foreground"}),e.jsx(be,{className:"pl-9",placeholder:"Search vendors...",value:m,onChange:D=>p(D.target.value)})]}),e.jsxs("select",{value:x,onChange:D=>g(D.target.value),className:"border rounded-md px-3 py-2 text-sm bg-background",children:[e.jsx("option",{value:"all",children:"All categories"}),Pq.map(D=>e.jsx("option",{value:D.value,children:D.label},D.value))]})]}),a?e.jsx("div",{className:"text-center text-muted-foreground py-12",children:"Loading vendors..."}):e.jsxs(ua,{defaultValue:n?"all":"personal",children:[e.jsxs(ha,{children:[e.jsxs(Qt,{value:"all",children:["All (",N.length,")"]}),n&&e.jsxs(Qt,{value:"brokerage",children:["From Brokerage (",A.length,")"]}),e.jsxs(Qt,{value:"personal",children:["My Personal (",C.length,")"]})]}),e.jsx(Jt,{value:"all",className:"mt-4",children:e.jsx(vDe,{vendors:N,isVisibleInPortals:M,onToggle:P,onEdit:D=>{d(D),h(!0)},onDelete:T,userId:t,clicks:i})}),n&&e.jsx(Jt,{value:"brokerage",className:"mt-4",children:A.length===0?e.jsx(Lvt,{icon:e.jsx(dn,{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(vDe,{vendors:A,isVisibleInPortals:M,onToggle:P,userId:t,clicks:i})}),e.jsx(Jt,{value:"personal",className:"mt-4",children:C.length===0?e.jsx(Lvt,{icon:e.jsx(ix,{className:"w-12 h-12"}),title:"No personal vendors yet",desc:"Add your trusted inspector, lender, mover — they'll show in every client portal you create.",action:e.jsxs($,{onClick:()=>{d(null),h(!0)},children:[e.jsx(sn,{className:"w-4 h-4 mr-2"})," Add Your First Vendor"]})}):e.jsx(vDe,{vendors:C,isVisibleInPortals:M,onToggle:P,onEdit:D=>{d(D),h(!0)},onDelete:T,userId:t,clicks:i})})]}),e.jsx(wVt,{open:u,onOpenChange:h,vendor:c,ownerType:"agent",agentUserId:t})]});return s?I:e.jsx(Ks,{children:I})}function vDe({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(_Vt,{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 Lvt({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 C8n(){const{brokerageId:s,isBrokerageManager:t,isAdmin:n,loading:r}=_s(),{data:a=[],isLoading:i}=YSs(s),{data:l={}}=zTt("brokerage",s),o=OTt(),[c,d]=j.useState(null),[u,h]=j.useState(!1),[m,p]=j.useState(""),[x,g]=j.useState("all");if(r)return e.jsx(Ks,{children:e.jsx("div",{className:"p-8",children:"Loading..."})});if(!t&&!n)return e.jsx(Ks,{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(v=>!(x!=="all"&&v.category!==x||m&&!`${v.name} ${v.company||""}`.toLowerCase().includes(m.toLowerCase()))),b=async v=>{if(await Yi("Delete this vendor? This will remove it from all agent libraries."))try{await o.mutateAsync(v),ae.success("Vendor deleted")}catch(N){ae.error(N.message)}};return e.jsx(Ks,{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(Ai,{className:"w-6 h-6 text-primary"}),"Brokerage Vendor Library"]}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:"Manage preferred vendors that all agents in your brokerage can offer to their clients."})]}),e.jsxs($,{onClick:()=>{d(null),h(!0)},children:[e.jsx(sn,{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(Vr,{className:"w-4 h-4 absolute left-3 top-1/2 -translate-y-1/2 text-muted-foreground"}),e.jsx(be,{className:"pl-9",placeholder:"Search vendors...",value:m,onChange:v=>p(v.target.value)})]}),e.jsxs("select",{value:x,onChange:v=>g(v.target.value),className:"border rounded-md px-3 py-2 text-sm bg-background",children:[e.jsx("option",{value:"all",children:"All categories"}),Pq.map(v=>e.jsx("option",{value:v.value,children:v.label},v.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(Ai,{className:"w-12 h-12 text-muted-foreground mx-auto mb-3"}),e.jsx("h3",{className:"font-semibold",children:"No vendors yet"}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1 mb-4",children:"Add preferred lenders, inspectors, title companies, and more."}),e.jsxs($,{onClick:()=>{d(null),h(!0)},children:[e.jsx(sn,{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(v=>e.jsx(_Vt,{vendor:v,onEdit:()=>{d(v),h(!0)},onDelete:()=>b(v.id),clickCount:l[v.id]},v.id))}),e.jsx(wVt,{open:u,onOpenChange:h,vendor:c,ownerType:"brokerage",brokerageId:s,showBrokerageOnlyFields:!0})]})})}const A8n=[{value:"overview",label:"Portals",icon:_0},{value:"vendors",label:"Vendors",icon:IN},{value:"referrals",label:"Referrals",icon:Co},{value:"branding",label:"Branding",icon:Rc},{value:"questions",label:"Onboarding",icon:Jh}];function E8n(){const[s,t]=oc(),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(Ks,{children:[e.jsx(Ul,{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(dn,{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(oY,{className:"w-5 h-5 text-primary"})}),e.jsxs("div",{className:"flex-1",children:[e.jsx("h2",{className:"text-base font-semibold",children:"Create portals from Deal Pipeline"}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1 max-w-3xl",children:"This page is for managing portals after they’ve been created. To create a new client portal, open the deal inside Deal Pipeline and enable the portal from that deal."})]}),e.jsx($,{asChild:!0,variant:"outline",size:"sm",className:"shrink-0",children:e.jsx(Wn,{to:"/mission-control/pipeline",children:"Open Deal Pipeline"})})]})}),e.jsxs(ua,{value:r,onValueChange:a,className:"w-full",children:[e.jsx(ha,{className:"w-full justify-start overflow-x-auto h-auto flex-wrap",children:A8n.map(d=>e.jsxs(Qt,{value:d.value,className:"gap-2",children:[e.jsx(d.icon,{className:"w-4 h-4"}),d.label]},d.value))}),e.jsx(Jt,{value:"overview",className:"mt-6",children:e.jsx(gVt,{})}),e.jsx(Jt,{value:"vendors",className:"mt-6",children:e.jsx(T8n,{})}),e.jsx(Jt,{value:"referrals",className:"mt-6",children:e.jsx(M8n,{})}),e.jsx(Jt,{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(Rc,{className:"w-6 h-6 text-primary"})}),e.jsxs("div",{className:"flex-1",children:[e.jsx("h2",{className:"text-lg font-semibold",children:"Portal Branding Defaults"}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1 mb-4 max-w-xl",children:"Set the default logo, colors, cover photo and welcome message that appear at the top of every client portal you create. You can still override per-portal in any deal's settings."}),e.jsxs($,{onClick:()=>l(!0),children:[e.jsx(pc,{className:"w-4 h-4 mr-2"}),"Edit Branding Defaults"]})]})]})})}),e.jsx(Jt,{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(Jh,{className:"w-6 h-6 text-primary"})}),e.jsxs("div",{className:"flex-1",children:[e.jsx("h2",{className:"text-lg font-semibold",children:"Custom Onboarding Questions"}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1 mb-4 max-w-xl",children:"Questions you want every new client to answer when they first open their portal — preferred contact times, kids/pets, must-have features, and anything else that helps you serve them better."}),e.jsxs($,{onClick:()=>c(!0),children:[e.jsx(pc,{className:"w-4 h-4 mr-2"}),"Manage Questions"]})]})]})})})]})]}),e.jsx(xVt,{open:i,onOpenChange:l}),e.jsx(mVt,{open:o,onOpenChange:c})]})}function T8n(){return e.jsx(jVt,{embedded:!0})}function M8n(){return e.jsx(bVt,{})}const V7=s=>new Intl.DateTimeFormat("en-US",{timeZone:"America/New_York",month:"short",day:"numeric",year:"numeric"}).format(new Date(s));function L8n(s){return ht({queryKey:["client-portal-by-id",s],queryFn:async()=>{if(!s)return null;const{data:t,error:n}=await U.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 U.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 U.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 P8n(){const{portalId:s}=Vi(),t=Vn(),n=Za(),{data:r,isLoading:a}=L8n(s),{data:i=[]}=oSn(s),{data:l=[]}=vVt(),o=uV(),c=V7t(),d=H7t(),u=G7t(),[h,m]=j.useState(!1),[p,x]=j.useState(!1),[g,y]=j.useState(!1),[b,v]=j.useState(!1),N=(r==null?void 0:r.portal)??null,C=(r==null?void 0:r.deal)??null,A=j.useMemo(()=>N?l.filter(Q=>Q.portal_id===N.id):[],[l,N==null?void 0:N.id]);if(a)return e.jsx(Ks,{children:e.jsx("div",{className:"flex items-center justify-center py-24",children:e.jsx(Ht,{className:"h-6 w-6 animate-spin text-muted-foreground"})})});if(!N)return e.jsx(Ks,{children:e.jsxs("div",{className:"max-w-3xl mx-auto p-8 text-center",children:[e.jsx("h1",{className:"text-xl font-semibold mb-2",children:"Portal not found"}),e.jsx("p",{className:"text-sm text-muted-foreground mb-4",children:"This portal may have been deleted or you don't have access to it."}),e.jsx($,{asChild:!0,variant:"outline",children:e.jsxs(Wn,{to:"/mission-control/client-portals",children:[e.jsx(ka,{className:"w-4 h-4 mr-2"}),"Back to Portals"]})})]})});const T=f5(N.slug),P=(C==null?void 0:C.deal_name)||"Untitled deal",M=C==null?void 0:C.contact,I=M?`${M.first_name||""} ${M.last_name||""}`.trim():"",D=!!N.archived_at,B=()=>{navigator.clipboard.writeText(T),ae.success("Portal link copied!")},q=async Q=>{try{await o.mutateAsync({id:N.id,is_enabled:Q}),ae.success(Q?"Portal enabled":"Portal disabled")}catch{ae.error("Failed to update")}},W=async()=>{try{await c.mutateAsync(N.id),ae.success("Portal archived")}catch{ae.error("Failed to archive")}},V=async()=>{try{await d.mutateAsync(N.id),ae.success("Portal restored")}catch{ae.error("Failed to restore")}},K=async()=>{try{await u.mutateAsync({id:N.id,dealId:N.deal_id}),ae.success("Portal deleted"),t("/mission-control/client-portals")}catch{ae.error("Failed to delete")}};return e.jsxs(Ks,{children:[e.jsx(Ul,{children:e.jsxs("title",{children:[P," — Client Portal"]})}),e.jsxs("div",{className:"max-w-6xl mx-auto p-4 md:p-8 space-y-6",children:[e.jsx("div",{children:e.jsx($,{asChild:!0,variant:"ghost",size:"sm",className:"-ml-2 text-muted-foreground",children:e.jsxs(Wn,{to:"/mission-control/client-portals?tab=overview",children:[e.jsx(ka,{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(dn,{className:"w-5 h-5 text-primary"}),e.jsx("h1",{className:"text-2xl font-bold truncate",children:P}),e.jsx($e,{variant:"outline",className:D?"bg-muted text-muted-foreground":N.is_enabled?"bg-emerald-500/10 text-emerald-700 border-emerald-200":"bg-muted text-muted-foreground",children:D?"Archived":N.is_enabled?"Active":"Disabled"}),e.jsx($e,{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(Lo,{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(nn,{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(ya,{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})})]}),!D&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:"Live"}),e.jsx(Tn,{checked:N.is_enabled,onCheckedChange:q})]})]}),e.jsxs("div",{className:"mt-5 flex items-center gap-2 flex-wrap",children:[e.jsxs($,{onClick:B,variant:"outline",size:"sm",children:[e.jsx(Ca,{className:"w-4 h-4 mr-1.5"})," Copy Link"]}),e.jsxs($,{onClick:()=>window.open(T,"_blank"),variant:"outline",size:"sm",children:[e.jsx(Tr,{className:"w-4 h-4 mr-1.5"})," Preview"]}),e.jsxs($,{onClick:()=>y(!0),size:"sm",children:[e.jsx(Br,{className:"w-4 h-4 mr-1.5"})," Invite Client"]}),e.jsxs($,{onClick:()=>x(!0),variant:"outline",size:"sm",children:[e.jsx(BS,{className:"w-4 h-4 mr-1.5"})," Post Update"]}),e.jsxs($,{onClick:()=>m(!0),variant:"outline",size:"sm",children:[e.jsx(pc,{className:"w-4 h-4 mr-1.5"})," Settings"]}),e.jsxs("div",{className:"ml-auto flex items-center gap-2",children:[D?e.jsxs($,{onClick:V,variant:"outline",size:"sm",children:[e.jsx(hT,{className:"w-4 h-4 mr-1.5"})," Restore"]}):e.jsxs($,{onClick:W,variant:"ghost",size:"sm",children:[e.jsx(Am,{className:"w-4 h-4 mr-1.5"})," Archive"]}),e.jsx($,{onClick:()=>v(!0),variant:"ghost",size:"sm",className:"text-destructive hover:text-destructive",children:e.jsx(Pn,{className:"w-4 h-4"})})]})]})]}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-3",children:[e.jsx(gae,{icon:BS,label:"Updates Posted",value:i.length}),e.jsx(gae,{icon:Co,label:"Referrals",value:A.length}),e.jsx(gae,{icon:ia,label:"Inspection",value:N.inspection_date?V7(N.inspection_date):"—"}),e.jsx(gae,{icon:ia,label:"Appraisal",value:N.appraisal_date?V7(N.appraisal_date):"—"})]}),e.jsxs(ua,{defaultValue:"updates",className:"w-full",children:[e.jsxs(ha,{children:[e.jsxs(Qt,{value:"updates",children:["Updates (",i.length,")"]}),e.jsxs(Qt,{value:"referrals",children:["Referrals (",A.length,")"]}),e.jsx(Qt,{value:"branding",children:"Branding"}),e.jsx(Qt,{value:"details",children:"Details"})]}),e.jsx(Jt,{value:"updates",className:"mt-4",children:e.jsx(_e,{children:e.jsxs(Oe,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center justify-between mb-4",children:[e.jsx("h3",{className:"font-semibold",children:"Portal Update Feed"}),e.jsxs($,{size:"sm",onClick:()=>x(!0),children:[e.jsx(BS,{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(BS,{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(Q=>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:Q.title}),Q.is_stage_change&&e.jsx($e,{variant:"outline",className:"text-[10px] bg-emerald-500/10 text-emerald-700 border-emerald-200",children:"Stage Change"})]}),e.jsx("p",{className:"text-[11px] text-muted-foreground mt-0.5",children:V7(Q.created_at)}),Q.content&&e.jsx("p",{className:"text-sm text-muted-foreground mt-2 whitespace-pre-wrap",children:Q.content}),Q.video_url&&e.jsxs("a",{href:Q.video_url,target:"_blank",rel:"noreferrer",className:"inline-flex items-center gap-1 text-xs text-primary hover:underline mt-2",children:[e.jsx(Xr,{className:"w-3 h-3"})," View video"]})]})})},Q.id))})]})})}),e.jsx(Jt,{value:"referrals",className:"mt-4",children:e.jsx(_e,{children:e.jsxs(Oe,{className:"p-4",children:[e.jsx("h3",{className:"font-semibold mb-4",children:"Referrals from this Portal"}),A.length===0?e.jsxs("div",{className:"text-center py-12 border-2 border-dashed rounded-lg",children:[e.jsx(Co,{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(Q=>e.jsx(Wn,{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:Q.friend_name}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[Q.friend_email||Q.friend_phone||"No contact info"," · ",V7(Q.created_at)]})]}),e.jsx($e,{variant:"outline",className:"text-xs capitalize",children:Q.status})]})},Q.id))})]})})}),e.jsx(Jt,{value:"branding",className:"mt-4",children:e.jsx(_e,{children:e.jsx(Oe,{className:"p-6",children:e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsx("div",{className:"rounded-lg bg-primary/10 p-3",children:e.jsx(Rc,{className:"w-6 h-6 text-primary"})}),e.jsxs("div",{className:"flex-1",children:[e.jsx("h3",{className:"font-semibold mb-1",children:"Portal Branding"}),e.jsx("p",{className:"text-sm text-muted-foreground mb-4 max-w-xl",children:"Override your default branding for this specific portal — custom logo, colors, cover photo, and welcome message just for this client."}),e.jsxs($,{onClick:()=>m(!0),children:[e.jsx(pc,{className:"w-4 h-4 mr-2"}),"Edit Branding (in Settings)"]})]})]})})})}),e.jsx(Jt,{value:"details",className:"mt-4",children:e.jsx(_e,{children:e.jsxs(Oe,{className:"p-6 space-y-4",children:[e.jsx(hA,{label:"Visibility",value:N.visibility}),e.jsx(hA,{label:"Onboarding Required",value:N.require_onboarding?"Yes":"No"}),e.jsx(hA,{label:"Allow Spouse",value:N.allow_spouse?"Yes":"No"}),e.jsx(hA,{label:"Notify Client on Updates",value:N.notify_client?"Yes":"No"}),e.jsx(hA,{label:"Show Post-Close Tips",value:N.show_post_close_tips?"Yes":"No"}),e.jsx(hA,{label:"Slug",value:N.slug,mono:!0}),e.jsx(hA,{label:"Created",value:V7(N.created_at)}),e.jsx(hA,{label:"Last Updated",value:V7(N.updated_at)}),e.jsx("div",{className:"pt-2",children:e.jsxs($,{variant:"outline",onClick:()=>m(!0),children:[e.jsx(pc,{className:"w-4 h-4 mr-2"})," Edit All Settings"]})})]})})})]})]}),e.jsx(dXe,{open:h,onOpenChange:m,portal:N,dealOwnerId:n||""}),e.jsx(uXe,{open:p,onOpenChange:x,portalId:N.id,portalSlug:N.slug,notifyClient:N.notify_client}),e.jsx(hXe,{open:g,onOpenChange:y,portal:N,dealName:P}),e.jsx(Ll,{open:b,onOpenChange:v,children:e.jsxs(yl,{children:[e.jsxs(vl,{children:[e.jsx(_l,{children:"Permanently delete this portal?"}),e.jsx(wl,{children:"This removes the portal and all its updates. The client will lose access. This action cannot be undone."})]}),e.jsxs(bl,{children:[e.jsx(jl,{children:"Cancel"}),e.jsx(fl,{onClick:K,className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Delete Permanently"})]})]})})]})}function gae({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 hA({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 fUe=[{value:"video_intro",label:"Video Intro",icon:Xr,description:"Add an intro video"},{value:"testimonials",label:"Testimonials",icon:H3,description:"Client testimonials carousel"},{value:"specialties",label:"Specialties",icon:Up,description:"Tags for your specialties"},{value:"custom_links",label:"Custom Links",icon:Dc,description:"Custom CTA buttons"},{value:"social_media",label:"Social Media",icon:vd,description:"Links to your social profiles"}],I8n=["First-Time Buyers","Luxury Homes","Investment Properties","Relocation","New Construction","Condos & Townhomes","Waterfront","Commercial","Land & Lots","Senior Living","Military/VA","Short Sales & Foreclosures"],D8n={video_intro:{video_url:""},testimonials:{testimonials:[{name:"",quote:"",role:""}]},specialties:{tags:[]},custom_links:{links:[{label:"",url:""}]},social_media:{platforms:[]}};function NVt({cardId:s}){const{data:t,isLoading:n}=__s(s),r=w_s(),a=j_s(),i=N_s(),[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(on,{className:"h-16 w-full"}),e.jsx(on,{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:D8n[c]||{}},{onSuccess:()=>{o(!1),d("")}})},p=v=>{a.mutate({id:v.id,is_visible:!v.is_visible})},x=(v,N)=>{if(!t)return;const C=t.findIndex(P=>P.id===v.id),A=N==="up"?C-1:C+1;if(A<0||A>=t.length)return;const T=t[A];a.mutate({id:v.id,sort_order:T.sort_order}),a.mutate({id:T.id,sort_order:v.sort_order})},g=async v=>{await Yi("Remove this block from this card?")&&i.mutate(v.id)},y=(v,N)=>{a.mutate({id:v.id,config:N},{onSuccess:()=>h(null)})},b=v=>fUe.find(N=>N.value===v);return e.jsxs("div",{className:"space-y-3",children:[!t||t.length===0?e.jsxs("div",{className:"text-center py-8",children:[e.jsx("p",{className:"text-muted-foreground mb-4 text-sm",children:"No blocks yet. Add a block to customize this card."}),e.jsxs($,{size:"sm",onClick:()=>o(!0),children:[e.jsx(sn,{className:"h-4 w-4 mr-1"})," Add Block"]})]}):e.jsxs(e.Fragment,{children:[t.map((v,N)=>{const C=b(v.block_type),A=(C==null?void 0:C.icon)||Up;return e.jsx(_e,{className:v.is_visible?"":"opacity-50",children:e.jsx(Oe,{className:"p-3",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx($p,{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:(C==null?void 0:C.label)||v.block_type}),e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:R8n(v)})]}),e.jsxs("div",{className:"flex items-center gap-0.5",children:[e.jsx($,{variant:"ghost",size:"icon",className:"h-7 w-7",onClick:()=>x(v,"up"),disabled:N===0,children:e.jsx(sp,{className:"h-3 w-3"})}),e.jsx($,{variant:"ghost",size:"icon",className:"h-7 w-7",onClick:()=>x(v,"down"),disabled:N===t.length-1,children:e.jsx(ax,{className:"h-3 w-3"})}),e.jsx($,{variant:"ghost",size:"icon",className:"h-7 w-7",onClick:()=>p(v),children:v.is_visible?e.jsx(ga,{className:"h-3 w-3"}):e.jsx(b0,{className:"h-3 w-3"})}),e.jsx($,{variant:"ghost",size:"sm",className:"h-7 text-xs",onClick:()=>h(v),children:"Edit"}),e.jsx($,{variant:"ghost",size:"icon",className:"h-7 w-7 text-destructive",onClick:()=>g(v),children:e.jsx(Pn,{className:"h-3 w-3"})})]})]})})},v.id)}),e.jsxs($,{variant:"outline",size:"sm",className:"w-full",onClick:()=>o(!0),children:[e.jsx(sn,{className:"h-4 w-4 mr-1"})," Add Block"]})]}),e.jsx(Os,{open:l,onOpenChange:o,children:e.jsxs(Rs,{children:[e.jsx(Us,{children:e.jsx(zs,{children:"Add Block"})}),e.jsx("div",{className:"grid gap-3",children:fUe.map(v=>{const N=v.icon;return e.jsxs("button",{onClick:()=>d(v.value),className:`flex items-center gap-3 p-3 rounded-lg border text-left transition-colors ${c===v.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:v.label}),e.jsx("p",{className:"text-xs text-muted-foreground",children:v.description})]})]},v.value)})}),e.jsxs(kr,{children:[e.jsx($,{variant:"outline",onClick:()=>o(!1),children:"Cancel"}),e.jsx($,{onClick:m,disabled:!c||r.isPending,children:"Add Block"})]})]})}),u&&e.jsx(O8n,{block:u,onSave:v=>y(u,v),onClose:()=>h(null)})]})}function R8n(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 O8n({block:s,onSave:t,onClose:n}){const[r,a]=j.useState(s.config),i=fUe.find(l=>l.value===s.block_type);return e.jsx(Os,{open:!0,onOpenChange:n,children:e.jsxs(Rs,{className:"max-w-lg max-h-[80vh] overflow-y-auto",children:[e.jsx(Us,{children:e.jsxs(zs,{children:["Edit ",i==null?void 0:i.label]})}),s.block_type==="video_intro"&&e.jsx(F8n,{config:r,onChange:a,cardId:s.card_id}),s.block_type==="testimonials"&&e.jsx(z8n,{config:r,onChange:a}),s.block_type==="specialties"&&e.jsx(B8n,{config:r,onChange:a}),s.block_type==="custom_links"&&e.jsx($8n,{config:r,onChange:a}),s.block_type==="social_media"&&e.jsx(U8n,{config:r,onChange:a}),e.jsxs(kr,{children:[e.jsx($,{variant:"outline",onClick:n,children:"Cancel"}),e.jsx($,{onClick:()=>t(r),children:"Save"})]})]})})}function F8n({config:s,onChange:t,cardId:n}){var p,x;const[r,a]=j.useState(""),[i,l]=j.useState((p=s.video_url)!=null&&p.includes("youtube")||(x=s.video_url)!=null&&x.includes("youtu.be")?"youtube":"library"),{data:o}=ht({queryKey:["card-owner",n],queryFn:async()=>{const{data:g}=await U.from("agent_cards").select("user_id").eq("id",n).single();return g==null?void 0:g.user_id},enabled:!!n}),{data:c,isLoading:d}=ht({queryKey:["agent-videos-library",o],queryFn:async()=>{const{data:g,error:y}=await U.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 g||[]},enabled:!!o}),u=(c==null?void 0:c.filter(g=>!r||(g.title||"").toLowerCase().includes(r.toLowerCase())))||[],h=s.bunny_video_id,m=g=>{var N;const y=(N=g.playback_url)==null?void 0:N.match(/\/(?:play|embed)\/(\d+)\//),v=`https://iframe.mediadelivery.net/embed/${y?y[1]:"570924"}/${g.bunny_video_id}?autoplay=false&responsive=true`;t({...s,video_url:v,bunny_video_id:g.bunny_video_id,video_source:"library"})};return e.jsx("div",{className:"space-y-4",children:e.jsxs(ua,{value:i,onValueChange:l,children:[e.jsxs(ha,{className:"w-full",children:[e.jsx(Qt,{value:"library",className:"flex-1",children:"Video Library"}),e.jsx(Qt,{value:"youtube",className:"flex-1",children:"YouTube URL"})]}),e.jsxs(Jt,{value:"library",className:"space-y-3 mt-3",children:[e.jsxs("div",{className:"relative",children:[e.jsx(Vr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(be,{placeholder:"Search videos...",value:r,onChange:g=>a(g.target.value),className:"pl-9"})]}),e.jsx(Oi,{className:"h-[240px]",children:d?e.jsxs("div",{className:"space-y-2",children:[e.jsx(on,{className:"h-14 w-full"}),e.jsx(on,{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(g=>e.jsxs("button",{onClick:()=>m(g),className:`w-full flex items-center gap-3 p-2 rounded-lg border text-left transition-colors ${h===g.bunny_video_id?"border-primary bg-primary/5":"border-border hover:bg-muted"}`,children:[g.thumbnail_url?e.jsx("img",{src:g.thumbnail_url,alt:"",className:"h-10 w-16 rounded object-cover flex-shrink-0 bg-muted",onError:y=>{var b;y.currentTarget.style.display="none",(b=y.currentTarget.nextElementSibling)==null||b.classList.remove("hidden")}}):null,e.jsx("div",{className:`h-10 w-16 rounded bg-muted flex items-center justify-center flex-shrink-0 ${g.thumbnail_url?"hidden":""}`,children:e.jsx(Xr,{className:"h-4 w-4 text-muted-foreground"})}),e.jsx("span",{className:"text-sm font-medium truncate flex-1",children:g.title||"Untitled Video"}),h===g.bunny_video_id&&e.jsx(oa,{className:"h-4 w-4 text-primary flex-shrink-0"})]},g.id))})})]}),e.jsx(Jt,{value:"youtube",className:"space-y-3 mt-3",children:e.jsxs("div",{children:[e.jsx(se,{children:"YouTube URL"}),e.jsx(be,{placeholder:"https://www.youtube.com/watch?v=...",value:s.video_source==="youtube"&&s.video_url||"",onChange:g=>t({...s,video_url:g.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 z8n({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(_e,{children:e.jsxs(Oe,{className:"p-3 space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(se,{className:"text-xs font-medium",children:["Testimonial ",o+1]}),n.length>1&&e.jsx($,{variant:"ghost",size:"icon",className:"h-6 w-6 text-destructive",onClick:()=>i(o),children:e.jsx(Pn,{className:"h-3 w-3"})})]}),e.jsx(be,{placeholder:"Client name",value:l.name,onChange:c=>r(o,"name",c.target.value)}),e.jsx(be,{placeholder:"Role/title (optional)",value:l.role||"",onChange:c=>r(o,"role",c.target.value)}),e.jsx("textarea",{className:"w-full min-h-[60px] rounded-md border border-input bg-background px-3 py-2 text-sm",placeholder:"Their testimonial quote...",value:l.quote,onChange:c=>r(o,"quote",c.target.value)})]})},o)),e.jsxs($,{variant:"outline",size:"sm",onClick:a,className:"w-full",children:[e.jsx(sn,{className:"h-4 w-4 mr-1"})," Add Testimonial"]})]})}function B8n({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(se,{className:"text-sm mb-2 block",children:"Preset Specialties"}),e.jsx("div",{className:"flex flex-wrap gap-2",children:I8n.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(se,{className:"text-sm mb-2 block",children:"Custom Tag"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(be,{placeholder:"Add your own...",value:r,onChange:o=>a(o.target.value),onKeyDown:o=>o.key==="Enter"&&(o.preventDefault(),l())}),e.jsx($,{variant:"outline",size:"sm",onClick:l,children:"Add"})]})]}),n.length>0&&e.jsxs("div",{children:[e.jsxs(se,{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 $8n({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(be,{placeholder:"Button label",value:l.label,onChange:c=>r(o,"label",c.target.value)}),e.jsx(be,{placeholder:"https://...",value:l.url,onChange:c=>r(o,"url",c.target.value)})]}),n.length>1&&e.jsx($,{variant:"ghost",size:"icon",className:"h-8 w-8 mt-1 text-destructive",onClick:()=>i(o),children:e.jsx(Pn,{className:"h-3 w-3"})})]},o)),e.jsxs($,{variant:"outline",size:"sm",onClick:a,className:"w-full",children:[e.jsx(sn,{className:"h-4 w-4 mr-1"})," Add Link"]})]})}const Pvt=[{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 U8n({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=Pvt.filter(c=>!n.find(d=>d.platform===c.value)),o=c=>{const d=zFe[c],u=Pvt.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(be,{placeholder:`Your ${u.label} profile URL`,value:c.url,onChange:h=>a(d,h.target.value)})}),e.jsx($,{variant:"ghost",size:"icon",className:"h-8 w-8 text-destructive flex-shrink-0",onClick:()=>i(d),children:e.jsx(Pn,{className:"h-3.5 w-3.5"})})]},d)})}),l.length>0&&e.jsxs("div",{children:[e.jsx(se,{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=zFe[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 q8n({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(),ae.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(se,{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(XN,{value:r,size:120,level:"H",bgColor:"#ffffff",fgColor:"#000000"})}),e.jsxs("div",{className:"space-y-2 min-w-0",children:[e.jsx("p",{className:"text-xs text-muted-foreground leading-relaxed",children:"Download this QR code to use on business cards, flyers, signs, or any print materials. Scanning it opens your digital card instantly."}),e.jsxs($,{variant:"outline",size:"sm",onClick:a,className:"gap-1.5",children:[e.jsx(di,{className:"h-3.5 w-3.5"}),"Download PNG"]})]})]})]})}function bDe(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 V8n(){const{user:s}=_s(),{data:t,isLoading:n}=y_s(s==null?void 0:s.id),r=dV(),[a,i]=j.useState(null),l=j.useMemo(()=>a||(t?bDe(t):null),[a,t]);if(n)return e.jsx(Ks,{children:e.jsxs("div",{className:"max-w-2xl mx-auto p-4 space-y-4",children:[e.jsx(on,{className:"h-8 w-48"}),e.jsx(on,{className:"h-32 w-full"}),e.jsx(on,{className:"h-32 w-full"})]})});if(!t)return e.jsx(Ks,{children:e.jsx(G8n,{userId:s==null?void 0:s.id})});const o=l||bDe(t),c=d=>{i(u=>{const h=u||bDe(t);return typeof d=="function"?d(h):d})};return e.jsx(Ks,{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(W8n,{card:t}),e.jsx(X8n,{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(Hj,{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(H8n,{card:t,form:o})})]})})]})})}function H8n({card:s,form:t}){const{data:n}=ht({queryKey:["card-preview-profile",s.user_id],queryFn:async()=>{const{data:a}=await U.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 U.storage.from("avatars").list(`${s.user_id}`);if(l&&l.length>0){const{data:o}=U.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(CHe,{card:r})})}function G8n({userId:s}){var c;const[t,n]=j.useState(""),r=TAt(),{data:a}=ht({queryKey:["my-profile-for-card",s],queryFn:async()=>{if(!s)return null;const{data:d}=await U.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){ae.error("Please enter a URL slug for your card");return}r.mutate({user_id:s,slug:d,is_published:!0},{onSuccess:()=>ae.success("Your digital card has been created!")})},o=[{icon:Gl,title:"Shareable Link",desc:"One link that works everywhere"},{icon:ox,title:"Lead Capture",desc:"Collect leads automatically"},{icon:kf,title:"Always Up-to-Date",desc:"Edit anytime, changes are instant"},{icon:Rc,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(dn,{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(_e,{className:"shadow-lg border-2",children:[e.jsxs(Bt,{className:"text-center pb-2",children:[e.jsx(Ut,{className:"text-xl",children:"Set Up Your Card"}),e.jsx(vr,{children:"Choose a URL slug — this is the link you'll share with clients"})]}),e.jsxs(Oe,{className:"p-6 pt-2 space-y-5",children:[e.jsxs("div",{children:[e.jsx(se,{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(be,{value:t||i,onChange:d=>n(d.target.value),placeholder:"your-name",className:"rounded-l-none"})]})]}),e.jsxs($,{onClick:l,disabled:r.isPending,className:"w-full h-11 text-base font-semibold",size:"lg",children:[e.jsx(dn,{className:"h-4 w-4 mr-2"}),r.isPending?"Creating...":"Create My Card"]})]})]})]})}function W8n({card:s}){const n=`https://cards.relevelup.com/${s.slug}`,r=()=>{navigator.clipboard.writeText(n),ae.success("Card link copied!")};return e.jsx("div",{className:"rounded-xl border bg-card p-5",children:e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center justify-between gap-4",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("h1",{className:"text-xl font-bold",children:"My Digital Card"}),e.jsx($e,{variant:s.is_published?"default":"secondary",className:"text-[10px] uppercase tracking-wider",children:s.is_published?"Live":"Draft"})]}),e.jsxs("p",{className:"text-sm text-muted-foreground flex items-center gap-1",children:[e.jsx(Gl,{className:"h-3.5 w-3.5"}),"cards.relevelup.com/",s.slug]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs($,{variant:"outline",size:"sm",onClick:r,className:"gap-1.5",children:[e.jsx(Ca,{className:"h-3.5 w-3.5"})," Copy Link"]}),e.jsx($,{size:"sm",asChild:!0,className:"gap-1.5",children:e.jsxs("a",{href:n,target:"_blank",rel:"noopener noreferrer",children:[e.jsx(Tr,{className:"h-3.5 w-3.5"})," Preview"]})})]})]})})}function K8n({userId:s}){const t=ts(),n=j.useRef(null),[r,a]=j.useState(!1),[i,l]=j.useState(""),{data:o,isLoading:c}=ht({queryKey:["card-editor-profile",s],queryFn:async()=>{const{data:B}=await U.from("profiles").select("name, email, phone, avatar_url").eq("id",s).single();let q=(B==null?void 0:B.avatar_url)||null;if(!q){const{data:W}=await U.storage.from("avatars").list(`${s}`);if(W&&W.length>0){const{data:V}=U.storage.from("avatars").getPublicUrl(`${s}/${W[0].name}`);q=`${V.publicUrl}?t=${Date.now()}`,await U.from("profiles").update({avatar_url:q}).eq("id",s)}}return{...B,avatar_url:q}}}),[d,u]=j.useState(null),[h,m]=j.useState(null),[p,x]=j.useState(null),[g,y]=j.useState(!1),b=d??(o==null?void 0:o.name)??"",v=h??(o==null?void 0:o.phone)??"",N=p??(o==null?void 0:o.email)??"",C=o==null?void 0:o.avatar_url,A=((o==null?void 0:o.name)||"A").split(" ").map(B=>B[0]).join("").toUpperCase().slice(0,2),T=!(o!=null&&o.avatar_url)||!(o!=null&&o.phone),P=yt({mutationFn:async B=>{const{error:q}=await U.from("profiles").update(B).eq("id",s);if(q)throw q},onSuccess:()=>{t.invalidateQueries({queryKey:["card-editor-profile",s]}),t.invalidateQueries({queryKey:["card-preview-profile",s]}),t.invalidateQueries({queryKey:["agent-card-user"]}),ae.success("Profile updated!")},onError:()=>ae.error("Failed to update profile")}),M=()=>{const B={};if(d!==null&&d!==(o==null?void 0:o.name)&&(B.name=d),h!==null&&h!==(o==null?void 0:o.phone)&&(B.phone=h||null),p!==null&&p!==(o==null?void 0:o.email)&&(B.email=p),Object.keys(B).length===0){ae.info("No changes to save");return}P.mutate(B)},I=B=>{var V;const q=(V=B.target.files)==null?void 0:V[0];if(!q)return;if(!q.type.startsWith("image/")){ae.error("Please select an image file");return}const W=new FileReader;W.onloadend=()=>{l(W.result),a(!0)},W.readAsDataURL(q),B.target.value=""},D=async B=>{y(!0);try{const{data:q}=await U.storage.from("avatars").list(`${s}`);q&&q.length>0&&await U.storage.from("avatars").remove(q.map(J=>`${s}/${J.name}`));const W=`${s}/avatar.jpg`,{error:V}=await U.storage.from("avatars").upload(W,B,{upsert:!0,contentType:"image/jpeg"});if(V)throw V;const{data:K}=U.storage.from("avatars").getPublicUrl(W),Q=K.publicUrl+"?t="+Date.now();await U.from("profiles").update({avatar_url:Q}).eq("id",s),t.invalidateQueries({queryKey:["card-editor-profile",s]}),t.invalidateQueries({queryKey:["card-preview-profile",s]}),t.invalidateQueries({queryKey:["agent-card-user"]}),ae.success("Photo updated!")}catch{ae.error("Failed to upload photo")}finally{y(!1)}};return c?e.jsx(on,{className:"h-32 w-full rounded-xl"}):e.jsxs(e.Fragment,{children:[e.jsx(_e,{className:T?"border-amber-300 dark:border-amber-700":"",children:e.jsxs(Oe,{className:"p-5 space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx(se,{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(xo,{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 B;return(B=n.current)==null?void 0:B.click()},children:[e.jsxs(Ea,{className:"h-16 w-16 ring-2 ring-muted",children:[e.jsx(ki,{src:C||void 0,alt:b}),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(y0,{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:g?"Uploading...":C?"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(se,{className:"text-xs font-medium text-muted-foreground",children:"Full Name"}),e.jsx(be,{value:b,onChange:B=>u(B.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(se,{className:"text-xs font-medium text-muted-foreground",children:"Phone Number"}),e.jsx(be,{value:v,onChange:B=>m(B.target.value),placeholder:"(555) 123-4567",className:"h-10",type:"tel"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{className:"text-xs font-medium text-muted-foreground",children:"Email"}),e.jsx(be,{value:N,onChange:B=>x(B.target.value),placeholder:"you@example.com",className:"h-10",type:"email"})]})]})]}),e.jsx($,{variant:"outline",size:"sm",onClick:M,disabled:P.isPending,className:"w-full",children:P.isPending?"Saving...":"Update Profile Info"})]})}),e.jsx(lWe,{open:r,onClose:()=>a(!1),imageSrc:i,onCropComplete:D,aspectRatio:1})]})}function Y8n({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"?x=>({...x,brokerage_logo_url:""}):x=>({...x,brokerage_display_name:""}))},u=p=>{c(p),t(p==="name"?x=>({...x,team_logo_url:""}):x=>({...x,team_name:""}))},h=async(p,x)=>{var y;const g=(y=p.target.files)==null?void 0:y[0];if(g){if(!g.type.startsWith("image/")){ae.error("Please select an image file");return}a(x);try{const b=g.name.split(".").pop()||"png",N=`${n}/${x==="brokerage_logo_url"?"brokerage-logo":"team-logo"}.${b}`,{error:C}=await U.storage.from("card-logos").upload(N,g,{upsert:!0});if(C)throw C;const{data:A}=U.storage.from("card-logos").getPublicUrl(N),T=A.publicUrl+"?t="+Date.now();t(x==="brokerage_logo_url"?P=>({...P,[x]:T,brokerage_display_name:""}):P=>({...P,[x]:T,team_name:""})),ae.success("Logo uploaded!")}catch{ae.error("Failed to upload logo")}finally{a(null),p.target.value=""}}},m=p=>{t(x=>({...x,[p]:""}))};return e.jsx(_e,{children:e.jsxs(Oe,{className:"p-5 space-y-5",children:[e.jsxs("div",{children:[e.jsx(se,{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(se,{className:"text-xs font-semibold uppercase tracking-wider text-muted-foreground",children:"Brokerage"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx($,{type:"button",variant:i==="name"?"default":"outline",size:"sm",className:"text-xs",onClick:()=>d("name"),children:"Use Name"}),e.jsx($,{type:"button",variant:i==="logo"?"default":"outline",size:"sm",className:"text-xs",onClick:()=>d("logo"),children:"Use Logo"})]}),i==="name"?e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{className:"text-xs font-medium text-muted-foreground",children:"Brokerage Name"}),e.jsx(be,{value:s.brokerage_display_name,onChange:p=>t(x=>({...x,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(se,{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(y0,{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(se,{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(rx,{value:[s.brokerage_logo_size||56],onValueChange:([p])=>t(x=>({...x,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(se,{className:"text-xs font-semibold uppercase tracking-wider text-muted-foreground",children:"Team"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx($,{type:"button",variant:o==="name"?"default":"outline",size:"sm",className:"text-xs",onClick:()=>u("name"),children:"Use Name"}),e.jsx($,{type:"button",variant:o==="logo"?"default":"outline",size:"sm",className:"text-xs",onClick:()=>u("logo"),children:"Use Logo"})]}),o==="name"?e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{className:"text-xs font-medium text-muted-foreground",children:"Team Name"}),e.jsx(be,{value:s.team_name,onChange:p=>t(x=>({...x,team_name:p.target.value})),placeholder:"e.g. The Smith Group",className:"h-10"})]}):e.jsxs("div",{className:"space-y-3",children:[e.jsx(se,{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(y0,{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(se,{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(rx,{value:[s.team_logo_size||56],onValueChange:([p])=>t(x=>({...x,team_logo_size:p})),min:24,max:120,step:4})]})]})]})]})})}function Z8n({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(se,{className:"text-sm font-semibold flex items-center gap-1.5",children:[e.jsx(Rc,{className:"h-4 w-4"})," Brand Colors"]}),e.jsx("p",{className:"text-xs text-muted-foreground mt-0.5",children:"Customize colors to match your brand"})]}),e.jsx($,{variant:"ghost",size:"sm",className:"text-xs h-7",onClick:i,children:"Reset to Default"})]}),e.jsx("div",{className:"grid gap-3",children:l.map(({key:o,label:c,desc:d})=>e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("label",{className:"relative shrink-0",children:[e.jsx("input",{type:"color",value:r[o],onChange:u=>a(o,u.target.value),className:"sr-only"}),e.jsx("div",{className:"h-10 w-10 rounded-lg border-2 border-border cursor-pointer shadow-sm hover:scale-105 transition-transform",style:{backgroundColor:r[o]}})]}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium",children:c}),e.jsx("p",{className:"text-xs text-muted-foreground",children:d})]}),e.jsx(be,{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 X8n({card:s,form:t,setForm:n}){var g;const r=MAt(),a=ts(),{data:i}=LAt(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 x=async()=>{const y=l.trim().toLowerCase().replace(/[^a-z0-9-]/g,"-").replace(/-+/g,"-").replace(/(^-|-$)/g,"");if(!y){ae.error("Please enter a valid URL");return}if(y===s.slug){ae.info("No changes to save");return}d(!0);try{const{data:b}=await U.from("agent_cards").select("id").eq("slug",y).neq("id",s.id).maybeSingle();if(b){ae.error("This URL is already taken. Try another one.");return}const{error:v}=await U.from("agent_cards").update({slug:y}).eq("id",s.id);if(v)throw v;o(y),a.invalidateQueries({queryKey:["agent-card"]}),ae.success("Card address updated!")}catch{ae.error("Failed to update card address")}finally{d(!1)}};return e.jsxs("div",{className:"space-y-4",children:[e.jsxs(ua,{defaultValue:"content",children:[e.jsxs(ha,{className:"w-full h-11 p-1",children:[e.jsxs(Qt,{value:"content",className:"flex-1 gap-1.5 data-[state=active]:shadow-sm",children:[e.jsx(yy,{className:"h-3.5 w-3.5 hidden sm:inline"}),"Content"]}),e.jsxs(Qt,{value:"sections",className:"flex-1 gap-1.5 data-[state=active]:shadow-sm",children:[e.jsx(ga,{className:"h-3.5 w-3.5 hidden sm:inline"}),"Sections"]}),e.jsxs(Qt,{value:"blocks",className:"flex-1 gap-1.5 data-[state=active]:shadow-sm",children:[e.jsx(ox,{className:"h-3.5 w-3.5 hidden sm:inline"}),"Blocks"]}),e.jsxs(Qt,{value:"qrcode",className:"flex-1 gap-1.5 data-[state=active]:shadow-sm",children:[e.jsx(Rx,{className:"h-3.5 w-3.5 hidden sm:inline"}),"QR Code"]}),e.jsxs(Qt,{value:"analytics",className:"flex-1 gap-1.5 data-[state=active]:shadow-sm",children:[e.jsx(uu,{className:"h-3.5 w-3.5 hidden sm:inline"}),"Analytics"]})]}),e.jsxs(Jt,{value:"content",className:"mt-4 space-y-4",children:[e.jsx(K8n,{userId:s.user_id}),e.jsx(Y8n,{form:t,setForm:n,userId:s.user_id}),e.jsx(_e,{children:e.jsxs(Oe,{className:"p-5 space-y-5",children:[e.jsxs("div",{className:"flex items-center justify-between p-3 rounded-lg bg-muted/50",children:[e.jsxs("div",{children:[e.jsx(se,{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(Tn,{checked:t.is_published,onCheckedChange:y=>n(b=>({...b,is_published:y}))})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{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(be,{value:l,onChange:y=>o(y.target.value.toLowerCase().replace(/[^a-z0-9-]/g,"-")),placeholder:"your-name",className:"rounded-l-none h-10"})]}),e.jsx($,{variant:"outline",size:"sm",onClick:x,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(se,{className:"text-sm font-medium",children:"Card Email (Override)"}),e.jsx(be,{value:t.display_email,onChange:y=>n(b=>({...b,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(se,{className:"text-sm font-medium",children:"Theme"}),e.jsxs(vs,{value:t.theme,onValueChange:y=>n(b=>({...b,theme:y})),children:[e.jsx(gs,{className:"h-11",children:e.jsx(bs,{})}),e.jsxs(ys,{children:[e.jsx(Ye,{value:"standard",children:"✨ Standard — Modern & Clean"}),e.jsx(Ye,{value:"luxury",children:"🌙 Luxury — Dark & Gold"}),e.jsx(Ye,{value:"bold",children:"🔥 Bold — Vibrant & Punchy"}),e.jsx(Ye,{value:"classic",children:"📋 Classic — Professional"})]})]})]}),t.theme==="bold"&&e.jsx(Z8n,{form:t,setForm:n}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{className:"text-sm font-medium",children:"Title / Tagline"}),e.jsx(be,{value:t.title,onChange:y=>n(b=>({...b,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(se,{className:"text-sm font-medium",children:"Positioning Statement"}),e.jsx(be,{value:t.positioning_statement,onChange:y=>n(b=>({...b,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(se,{className:"text-sm font-medium",children:"Bio"}),e.jsx(Is,{value:t.bio,onChange:y=>n(b=>({...b,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(se,{className:"text-sm font-medium",children:"Review Snippet"}),e.jsx(be,{value:t.review_snippet,onChange:y=>n(b=>({...b,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(se,{className:"text-sm font-medium",children:"Review Source URL"}),e.jsx(be,{value:t.review_source_url,onChange:y=>n(b=>({...b,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(se,{className:"text-sm font-medium",children:"Booking URL"}),e.jsx(be,{value:t.booking_url,onChange:y=>n(b=>({...b,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(se,{className:"text-sm font-medium",children:"Custom CTA Label"}),e.jsx(be,{value:t.custom_cta_label,onChange:y=>n(b=>({...b,custom_cta_label:y.target.value})),placeholder:"Book a Call",className:"h-11"})]})]})})]}),e.jsx(Jt,{value:"sections",className:"mt-4",children:e.jsx(_e,{children:e.jsx(Oe,{className:"p-5 divide-y",children:[{key:"show_photo",label:"Photo",desc:"Uses the photo from your Profile Info above"},{key:"show_bio",label:"Bio Section",desc:"Display your bio on the card"},{key:"show_credentials",label:"Credentials",desc:"Show star rating and reviews"},{key:"show_social_links",label:"Social Links",desc:"Display your social media links"},{key:"show_save_contact",label:"Save Contact",desc:"Let visitors save you as a contact"},{key:"show_leave_review",label:"Leave Review",desc:"Link to your review page"},{key:"show_refer_friend",label:"Refer a Friend",desc:"Enable referral submissions"}].map(({key:y,label:b,desc:v})=>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(se,{className:"text-sm font-medium",children:b}),e.jsx("p",{className:"text-xs text-muted-foreground",children:v})]}),e.jsx(Tn,{checked:t[y],onCheckedChange:N=>n(C=>({...C,[y]:N}))})]},y))})})}),e.jsx(Jt,{value:"blocks",className:"mt-4",children:e.jsx(NVt,{cardId:s.id})}),e.jsx(Jt,{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:ga,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:uu,color:"text-amber-600 bg-amber-100 dark:text-amber-400 dark:bg-amber-900/30"},{label:"Leads",value:((g=i==null?void 0:i.leads)==null?void 0:g.length)??0,icon:il,color:"text-emerald-600 bg-emerald-100 dark:text-emerald-400 dark:bg-emerald-900/30"}].map(y=>e.jsx(_e,{className:"overflow-hidden",children:e.jsxs(Oe,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx("div",{className:`p-1.5 rounded-md ${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(_e,{children:[e.jsx(Bt,{className:"pb-3",children:e.jsx(Ut,{className:"text-base",children:"Recent Leads"})}),e.jsx(Oe,{className:"pt-0 space-y-2",children:i.leads.slice(0,5).map(y=>e.jsxs("div",{className:"flex items-center justify-between text-sm p-3 rounded-lg bg-muted/50",children:[e.jsxs("div",{children:[e.jsx("span",{className:"font-medium",children:y.name}),y.phone&&e.jsx("span",{className:"text-muted-foreground ml-2",children:y.phone})]}),y.intent&&e.jsx($e,{variant:"secondary",className:"text-xs",children:y.intent})]},y.id))})]}),(!i||i.leads.length===0)&&e.jsx(_e,{children:e.jsxs(Oe,{className:"p-8 text-center",children:[e.jsx(uu,{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(Jt,{value:"qrcode",className:"mt-4 space-y-4",children:e.jsx(_e,{children:e.jsx(Oe,{className:"p-6",children:e.jsx(q8n,{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 Q8n(){const s=ts(),[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,x]=j.useState(null),[g,y]=j.useState(null),[b,v]=j.useState(0),[N,C]=j.useState(""),[A,T]=j.useState(!1),{data:P,isLoading:M}=ht({queryKey:["boldtrail-status"],queryFn:async()=>{const{data:ue,error:ne}=await U.functions.invoke("boldtrail-sync",{body:{action:"status"}});if(ne)throw ne;return ue}}),I=yt({mutationFn:async ue=>{const{data:ne,error:ee}=await U.functions.invoke("boldtrail-sync",{body:{action:"save_token",api_token:ue}});if(ee)throw ee;if(ne!=null&&ne.error)throw new Error(ne.error);return ne},onSuccess:()=>{s.invalidateQueries({queryKey:["boldtrail-status"]}),n(""),ae.success("BoldTrail connected successfully!")},onError:ue=>{ae.error(ue.message||"Failed to connect BoldTrail")}}),D=yt({mutationFn:async()=>{const{data:ue,error:ne}=await U.functions.invoke("boldtrail-sync",{body:{action:"disconnect"}});if(ne)throw ne;return ue},onSuccess:()=>{s.invalidateQueries({queryKey:["boldtrail-status"]}),ae.success("BoldTrail disconnected")},onError:()=>ae.error("Failed to disconnect")}),B=yt({mutationFn:async ue=>{const{data:ne,error:ee}=await U.functions.invoke("boldtrail-sync",{body:{action:"save_direction",sync_direction:ue}});if(ee)throw ee;if(ne!=null&&ne.error)throw new Error(ne.error);return ne},onSuccess:()=>{s.invalidateQueries({queryKey:["boldtrail-status"]}),ae.success("Sync direction saved")},onError:ue=>{ae.error(ue.message||"Failed to save sync direction")}}),q=yt({mutationFn:async()=>{const{data:ue,error:ne}=await U.functions.invoke("boldtrail-sync",{body:{action:"detect_owner"}});if(ne)throw ne;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 ne=ue.detected_name||ue.detected_email||`ID ${ue.kvcore_user_id}`;ae.success(`Detected your BoldTrail account: ${ne}`)}else if(ue.candidates&&ue.candidates.length>0){const ne=ue.candidates.slice(0,5).map(ee=>`${ee.id} (${ee.count} contacts)`).join(", ");ae.warning(`Couldn't auto-detect your ID. Owner IDs found in your contacts: ${ne}. Pick yours and enter it below.`,{duration:12e3}),T(!0)}else ae.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=>ae.error(ue.message||"Detection failed")}),W=yt({mutationFn:async ue=>{const{data:ne,error:ee}=await U.functions.invoke("boldtrail-sync",{body:{action:"save_owner_settings",...ue}});if(ee)throw ee;if(ne!=null&&ne.error)throw new Error(ne.error);return ne},onSuccess:()=>{s.invalidateQueries({queryKey:["boldtrail-status"]}),ae.success("Settings saved"),T(!1)},onError:ue=>ae.error(ue.message||"Failed to save settings")}),V=yt({mutationFn:async()=>{const{data:ue,error:ne}=await U.functions.invoke("boldtrail-sync",{body:{action:"sync_preview"}});if(ne)throw ne;if(ue!=null&&ue.error)throw new Error(ue.error);return ue},onSuccess:ue=>{x(null),c(ue),a(!0)},onError:ue=>{ae.error(ue.message||"Failed to generate sync preview")}}),K=yt({mutationFn:async()=>{y("Initializing sync..."),v(5);const{data:ue,error:ne}=await U.functions.invoke("boldtrail-sync",{body:{action:"sync",phase:"init",sync_direction:ce}});if(ne)throw ne;if(ue!=null&&ue.error)throw new Error(ue.error);const ee=ue;let le=ee.sync_log_id,he=ee.next_phase,ve=ee.next_offset,ge=ee.push_total||0,fe=ee.pull_total||0,je=0,Ee=0;for(;he!=="finalize";){const ze=ge+fe;he==="fetch_bt"?y("Fetching BoldTrail contacts..."):he==="analyze"?(y("Analyzing contacts..."),v(15)):he==="push"?(y(`Pushing contacts to BoldTrail... (${je}/${ge})`),v(ze>0?je/ze*100:0)):he==="pull"&&(y(`Pulling contacts from BoldTrail... (${Ee}/${fe})`),v(ze>0?(ge+Ee)/ze*100:0));const{data:ke,error:Xe}=await U.functions.invoke("boldtrail-sync",{body:{action:"sync",phase:he,offset:ve,sync_log_id:le,sync_direction:ce}});if(Xe)throw Xe;if(ke!=null&&ke.error)throw new Error(ke.error);const Se=ke;je+=Se.chunk_pushed||0,Ee+=Se.chunk_pulled||0,Se.push_total!==void 0&&(ge=Se.push_total||0),Se.pull_total!==void 0&&(fe=Se.pull_total||0),Se.progress&&y(Se.progress),he==="pull"&&fe>0?v(Math.min(95,Ee/fe*100)):he==="push"&&ge>0&&v(Math.min(95,je/ge*100)),he=Se.next_phase,ve=Se.next_offset}y("Finalizing sync..."),v(95);const{data:Me,error:De}=await U.functions.invoke("boldtrail-sync",{body:{action:"sync",phase:"finalize",sync_log_id:le,sync_direction:ce}});if(De)throw De;return v(100),Me},onSuccess:ue=>{y(null),v(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"]}),ae.success(`Sync complete! Pushed ${ue.contacts_pushed||0}, pulled ${ue.contacts_pulled||0}, skipped ${ue.contacts_skipped||0} duplicates.`)},onError:ue=>{y(null),v(0),ae.error(ue.message||"Sync failed")}}),Q=P==null?void 0:P.connected,J=(P==null?void 0:P.sync_direction)||"bidirectional",ce=p??J;return e.jsxs(e.Fragment,{children:[e.jsxs(_e,{children:[e.jsx(Bt,{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(Tx,{className:"h-5 w-5 text-emerald-600"})}),e.jsxs("div",{children:[e.jsxs(Ut,{className:"text-lg flex items-center gap-2",children:["BoldTrail",Q&&e.jsx($e,{variant:"default",className:"text-xs bg-green-600",children:"Connected"}),e.jsxs("button",{onClick:()=>l(!0),className:"flex items-center gap-1 text-xs text-muted-foreground hover:text-foreground transition-colors",children:[e.jsx(Sh,{className:"h-3.5 w-3.5"}),"Learn More"]})]}),e.jsx(vr,{children:"Sync contacts bidirectionally between Agent OS and your BoldTrail (kvCORE) CRM."})]})]})}),e.jsx(Oe,{children:e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-start gap-2 text-sm text-muted-foreground",children:[e.jsx(Ro,{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(Ro,{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(Ro,{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"})]}),Q?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"}),(P==null?void 0:P.last_sync_at)&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Last sync: ",new Date(P.last_sync_at).toLocaleString(),P.last_sync_status&&e.jsx($e,{variant:P.last_sync_status==="success"?"default":"secondary",className:"ml-2 text-[10px]",children:P.last_sync_status})]}),(P==null?void 0:P.boldtrail_contact_count)!=null&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:[P.boldtrail_contact_count," contacts in BoldTrail"]}),(P==null?void 0:P.last_sync_message)&&e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:P.last_sync_message})]}),e.jsxs(Ll,{children:[e.jsx(_f,{asChild:!0,children:e.jsx($,{variant:"ghost",size:"icon",className:"text-destructive hover:text-destructive",children:e.jsx(Pn,{className:"h-4 w-4"})})}),e.jsxs(yl,{children:[e.jsxs(vl,{children:[e.jsx(_l,{children:"Disconnect BoldTrail?"}),e.jsx(wl,{children:"This will remove your API token. Previously synced contacts will remain in both systems."})]}),e.jsxs(bl,{children:[e.jsx(jl,{children:"Cancel"}),e.jsx(fl,{onClick:()=>D.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(Yj,{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(Tn,{checked:!!(P!=null&&P.sync_only_owned),onCheckedChange:ue=>W.mutate({sync_only_owned:ue}),disabled:W.isPending})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(se,{className:"text-xs",children:"Your BoldTrail Agent ID"}),A?e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(be,{type:"number",placeholder:"e.g. 12345",value:N,onChange:ue=>C(ue.target.value),className:"h-8 text-sm"}),e.jsx($,{size:"sm",onClick:()=>{const ue=N.trim()===""?null:Number(N);W.mutate({kvcore_user_id:ue})},disabled:W.isPending,children:"Save"}),e.jsx($,{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:(P==null?void 0:P.kvcore_user_id)??e.jsx("span",{className:"text-muted-foreground",children:"Not set"})}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs($,{size:"sm",variant:"outline",onClick:()=>q.mutate(),disabled:q.isPending,children:[q.isPending?e.jsx(Wi,{className:"h-3 w-3 mr-1 animate-spin"}):null,"Auto-detect"]}),e.jsx($,{size:"sm",variant:"ghost",onClick:()=>{var ue;C(((ue=P==null?void 0:P.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(h4e,{value:J,onChange:ue=>B.mutate(ue)})}),e.jsx("div",{className:"flex gap-2",children:e.jsxs($,{onClick:()=>V.mutate(),disabled:V.isPending||K.isPending,variant:"outline",className:"gap-2",children:[V.isPending?e.jsx(Wi,{className:"h-4 w-4 animate-spin"}):e.jsx(ga,{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(be,{type:"password",placeholder:"Paste your BoldTrail API token",value:t,onChange:ue=>n(ue.target.value),className:"flex-1"}),e.jsxs($,{onClick:()=>I.mutate(t),disabled:!t||t.length<10||I.isPending,children:[I.isPending?e.jsx(Wi,{className:"h-4 w-4 animate-spin mr-2"}):null,"Connect"]})]}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Find your API token in BoldTrail → Lead Engine → Lead Dropbox → My API Tokens. Generate a ",e.jsx("strong",{children:"Contacts"})," scope token."]})]})]})})]}),e.jsx(Os,{open:r,onOpenChange:ue=>{K.isPending||a(ue)},children:e.jsxs(Rs,{className:"sm:max-w-lg",children:[e.jsxs(Us,{children:[e.jsxs(zs,{className:"flex items-center gap-2",children:[e.jsx(Tx,{className:"h-5 w-5 text-emerald-600"}),"Sync Preview"]}),e.jsx(Sr,{children:"Review what will happen when you sync your contacts."})]}),o&&(()=>{const ue=ce==="pull_only"?0:o.to_push,ne=ce==="push_only"?0:o.to_pull;return e.jsxs("div",{className:"space-y-4",children:[e.jsx(h4e,{value:ce,onChange:x,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(Yj,{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 ${ce==="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(sp,{className:"h-3 w-3"})," Push to BoldTrail"]})]}),e.jsxs("div",{className:`rounded-lg border p-3 text-center ${ce==="push_only"?"opacity-40":""}`,children:[e.jsx("p",{className:"text-2xl font-bold text-blue-600",children:ne}),e.jsxs("p",{className:"text-xs text-muted-foreground flex items-center justify-center gap-1",children:[e.jsx(ax,{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(qn,{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(Ki,{value:b||10,className:"h-2"}),e.jsx("p",{className:"text-xs text-muted-foreground text-center",children:g||"Sync in progress..."})]}),ue>0&&e.jsxs(uv,{open:d,onOpenChange:u,children:[e.jsx(hv,{asChild:!0,children:e.jsxs($,{variant:"ghost",size:"sm",className:"w-full justify-between text-xs",children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(sp,{className:"h-3 w-3 text-emerald-600"}),ue," contacts to push to BoldTrail"]}),e.jsx(_o,{className:`h-3 w-3 transition-transform ${d?"rotate-180":""}`})]})}),e.jsx(mv,{children:e.jsxs("div",{className:"rounded border divide-y max-h-40 overflow-y-auto",children:[o.push_preview.map((ee,le)=>e.jsxs("div",{className:"px-3 py-1.5 text-xs flex justify-between",children:[e.jsx("span",{className:"font-medium",children:ee.name||"No name"}),e.jsx("span",{className:"text-muted-foreground",children:ee.email})]},le)),o.to_push>20&&e.jsxs("div",{className:"px-3 py-1.5 text-xs text-muted-foreground text-center",children:["...and ",o.to_push-20," more"]})]})})]}),ne>0&&e.jsxs(uv,{open:h,onOpenChange:m,children:[e.jsx(hv,{asChild:!0,children:e.jsxs($,{variant:"ghost",size:"sm",className:"w-full justify-between text-xs",children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(ax,{className:"h-3 w-3 text-blue-600"}),ne," contacts to pull from BoldTrail"]}),e.jsx(_o,{className:`h-3 w-3 transition-transform ${h?"rotate-180":""}`})]})}),e.jsx(mv,{children:e.jsxs("div",{className:"rounded border divide-y max-h-40 overflow-y-auto",children:[o.pull_preview.map((ee,le)=>e.jsxs("div",{className:"px-3 py-1.5 text-xs flex justify-between",children:[e.jsx("span",{className:"font-medium",children:ee.name||"No name"}),e.jsx("span",{className:"text-muted-foreground",children:ee.email})]},le)),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&&ne===0&&e.jsx("div",{className:"text-center py-4 text-sm text-muted-foreground",children:"✅ Everything is already in sync! No contacts to transfer."}),e.jsxs("div",{className:"flex gap-2 justify-end pt-2",children:[e.jsx($,{variant:"outline",onClick:()=>a(!1),disabled:K.isPending,children:"Cancel"}),e.jsxs($,{onClick:()=>K.mutate(),disabled:K.isPending||ue===0&&ne===0,className:"gap-2",children:[K.isPending?e.jsx(Wi,{className:"h-4 w-4 animate-spin"}):e.jsx(Tx,{className:"h-4 w-4"}),K.isPending?"Syncing...":"Sync Now"]})]})]})})()]})}),e.jsx(Os,{open:i,onOpenChange:l,children:e.jsxs(Rs,{className:"sm:max-w-2xl p-0 overflow-hidden",children:[e.jsx(Us,{className:"p-6 pb-0",children:e.jsxs(zs,{className:"flex items-center gap-2",children:[e.jsx(Tx,{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 H7=async s=>{const{data:t,error:n}=await U.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 J8n(){const s=ts(),[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:x}=ht({queryKey:["lofty-status"],queryFn:async()=>await H7({action:"status"})}),g=()=>s.invalidateQueries({queryKey:["lofty-status"]}),y=yt({mutationFn:async()=>H7({action:"save_token",api_token:t.trim()}),onSuccess:T=>{ae.success(T!=null&&T.contact_count?`Connected to Lofty — ${T.contact_count} contacts found`:"Connected to Lofty"),n(""),g()},onError:T=>ae.error(T.message)}),b=yt({mutationFn:async()=>H7({action:"disconnect"}),onSuccess:()=>{ae.success("Lofty disconnected"),g()},onError:T=>ae.error(T.message)}),v=yt({mutationFn:async T=>H7({action:"save_settings",...T}),onSuccess:()=>g(),onError:T=>ae.error(T.message)}),N=yt({mutationFn:async()=>H7({action:"detect_owner"}),onSuccess:T=>{const P=(T==null?void 0:T.candidates)||[];m(P),P.length===0?ae.info("No assigned-agent IDs found on your Lofty contacts."):P.length===1?(v.mutate({lofty_user_id:P[0].id}),ae.success(`Using Lofty agent ID ${P[0].id}`)):ae.success("Pick which Lofty agent ID is yours below.")},onError:T=>ae.error(T.message)}),C=async()=>{l(!0),c(2),u("Starting Lofty sync…");try{let T="start",P=0,M=null,I=0;for(;T&&I<400;){I++;const D=await H7({action:"sync",phase:T,offset:P,sync_log_id:M});M=D.sync_log_id||M,D.progress&&u(D.progress),c(B=>Math.min(95,B+4)),T=D.next_phase,P=D.next_offset||0,T||(c(100),u(D.message||"Sync complete"),ae.success(D.message||"Lofty sync complete"))}}catch(T){ae.error(T.message||"Lofty sync failed"),u(null)}finally{l(!1),setTimeout(()=>c(0),2500),g()}},A=!!(p!=null&&p.connected);return e.jsxs(_e,{children:[e.jsx(Bt,{children:e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsxs(Ut,{className:"flex items-center gap-2",children:["Lofty",A?e.jsxs($e,{variant:"secondary",className:"gap-1",children:[e.jsx(Ro,{className:"h-3 w-3"})," Connected"]}):e.jsx($e,{variant:"outline",children:"Not connected"})]}),e.jsx(vr,{children:"Sync your Lofty (formerly Chime) contacts — names, emails, phones, address, source, stage, tags and notes — into Agent OS."})]}),A&&e.jsxs(Ll,{children:[e.jsx(_f,{asChild:!0,children:e.jsx($,{variant:"ghost",size:"icon","aria-label":"Disconnect Lofty",children:e.jsx(Pn,{className:"h-4 w-4"})})}),e.jsxs(yl,{children:[e.jsxs(vl,{children:[e.jsx(_l,{children:"Disconnect Lofty?"}),e.jsx(wl,{children:"Your API key and sync settings will be removed. Contacts already imported into Agent OS stay put."})]}),e.jsxs(bl,{children:[e.jsx(jl,{children:"Cancel"}),e.jsx(fl,{onClick:()=>b.mutate(),children:"Disconnect"})]})]})]})]})}),e.jsx(Oe,{className:"space-y-5",children:x?e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(Ht,{className:"h-4 w-4 animate-spin"})," Loading…"]}):A?e.jsxs("div",{className:"space-y-5",children:[e.jsx(h4e,{value:(p==null?void 0:p.sync_direction)||"pull_only",onChange:T=>v.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(Tn,{checked:!!(p!=null&&p.sync_only_owned),onCheckedChange:T=>v.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($,{size:"sm",variant:"outline",onClick:()=>N.mutate(),disabled:N.isPending,children:[N.isPending?e.jsx(Ht,{className:"h-3.5 w-3.5 animate-spin"}):e.jsx(qn,{className:"h-3.5 w-3.5"}),"Detect my Lofty agent ID"]}),(p==null?void 0:p.lofty_user_id)&&e.jsxs($e,{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($,{size:"sm",variant:(p==null?void 0:p.lofty_user_id)===T.id?"default":"outline",onClick:()=>v.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(Tn,{checked:!!(p!=null&&p.import_notes),onCheckedChange:T=>v.mutate({import_notes:T})})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{htmlFor:"lofty-tags",className:"text-sm",children:"Tag filter (optional)"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(be,{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($,{variant:"outline",onClick:()=>v.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($,{onClick:C,disabled:i,children:[i?e.jsx(Ht,{className:"h-4 w-4 animate-spin"}):e.jsx(Wi,{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(Ki,{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($e,{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(se,{htmlFor:"lofty-key",children:"Lofty API Key"}),e.jsx(be,{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($,{onClick:()=>y.mutate(),disabled:t.trim().length<10||y.isPending,children:[y.isPending?e.jsx(Ht,{className:"h-4 w-4 animate-spin"}):e.jsx(Wj,{className:"h-4 w-4"}),"Connect Lofty"]}),e.jsx($,{variant:"ghost",size:"sm",asChild:!0,children:e.jsxs("a",{href:"https://developer.lofty.com/",target:"_blank",rel:"noreferrer",children:["Lofty API docs ",e.jsx(Tr,{className:"ml-1 h-3 w-3"})]})})]})]})})]})}function eDn(){const s=ts(),[t,n]=j.useState(""),[r,a]=j.useState(!1),[i,l]=j.useState(0),[o,c]=j.useState(null),{data:d,isLoading:u}=ht({queryKey:["fub-status"],queryFn:async()=>{const{data:g,error:y}=await U.functions.invoke("followupboss-sync",{body:{action:"status"}});if(y)throw y;return g}}),h=yt({mutationFn:async g=>{const{data:y,error:b}=await U.functions.invoke("followupboss-sync",{body:{action:"save_token",api_key:g}});if(b)throw b;if(y!=null&&y.error)throw new Error(y.error);return y},onSuccess:()=>{ae.success("Connected to Follow Up Boss"),n(""),s.invalidateQueries({queryKey:["fub-status"]})},onError:g=>ae.error(g.message)}),m=yt({mutationFn:async()=>{const{error:g}=await U.functions.invoke("followupboss-sync",{body:{action:"disconnect"}});if(g)throw g},onSuccess:()=>{ae.success("Disconnected"),s.invalidateQueries({queryKey:["fub-status"]})}}),p=yt({mutationFn:async g=>{const{error:y}=await U.functions.invoke("followupboss-sync",{body:{action:"set_direction",sync_direction:g}});if(y)throw y},onSuccess:()=>s.invalidateQueries({queryKey:["fub-status"]})}),x=async()=>{a(!0),l(0),c("Pulling from FUB…");let g=0,y=0,b=0,v=0;try{for(;;){const{data:T,error:P}=await U.functions.invoke("followupboss-sync",{body:{action:"sync",offset:g}});if(P)throw P;if(T!=null&&T.error)throw new Error(T.error);y+=T.chunk_created||0,b+=T.chunk_updated||0,v+=T.chunk_skipped||0,g=T.next_offset;const M=T.total?Math.min(100,Math.round(g/T.total*100)):100;if(l(M),c(`Pulling · ${g} / ${T.total||"?"}`),T.done)break;await new Promise(I=>setTimeout(I,400))}let N=0,C=0;if((d==null?void 0:d.sync_direction)==="bidirectional"){let T=0;for(l(0),c("Pushing to FUB…");;){const{data:P,error:M}=await U.functions.invoke("followupboss-sync",{body:{action:"push",offset:T}});if(M)throw M;if(P!=null&&P.error)throw new Error(P.error);N+=P.chunk_pushed||0,C+=P.chunk_failed||0,T=P.next_offset;const I=P.total?Math.min(100,Math.round(T/P.total*100)):100;if(l(I),c(`Pushing · ${T} / ${P.total||"?"}`),P.done)break;await new Promise(D=>setTimeout(D,400))}}const A=N||C?` · pushed ${N}${C?`, ${C} failed`:""}`:"";ae.success(`Sync complete · ${y} new, ${b} updated${v?`, ${v} skipped`:""}${A}`),s.invalidateQueries({queryKey:["fub-status"]})}catch(N){ae.error(N.message||"Sync failed")}finally{a(!1),setTimeout(()=>{l(0),c(null)},2500)}};return e.jsxs(_e,{children:[e.jsx(Bt,{children:e.jsx("div",{className:"flex items-start justify-between gap-3",children:e.jsxs("div",{children:[e.jsxs(Ut,{className:"flex items-center gap-2",children:[e.jsx(Wj,{className:"h-5 w-5 text-primary"}),"Follow Up Boss",(d==null?void 0:d.connected)&&e.jsxs($e,{variant:"default",className:"ml-1",children:[e.jsx(Ro,{className:"h-3 w-3 mr-1"})," Connected"]})]}),e.jsx(vr,{children:"Sync your Follow Up Boss contacts into Agent OS."})]})})}),e.jsx(Oe,{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(Tn,{checked:d.sync_direction==="bidirectional",onCheckedChange:g=>p.mutate(g?"bidirectional":"pull_only"),disabled:r||p.isPending})]}),o&&e.jsxs("div",{className:"space-y-1",children:[e.jsx(Ki,{value:i}),e.jsx("p",{className:"text-xs text-muted-foreground",children:o})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs($,{onClick:x,disabled:r,children:[e.jsx(Wi,{className:`h-4 w-4 mr-2 ${r?"animate-spin":""}`}),r?"Syncing…":"Sync Now"]}),e.jsxs(Ll,{children:[e.jsx(_f,{asChild:!0,children:e.jsxs($,{variant:"outline",disabled:r,children:[e.jsx(Pn,{className:"h-4 w-4 mr-2"})," Disconnect"]})}),e.jsxs(yl,{children:[e.jsxs(vl,{children:[e.jsx(_l,{children:"Disconnect Follow Up Boss?"}),e.jsx(wl,{children:"Your API key will be removed. Synced contacts stay in Agent OS."})]}),e.jsxs(bl,{children:[e.jsx(jl,{children:"Cancel"}),e.jsx(fl,{onClick:()=>m.mutate(),children:"Disconnect"})]})]})]})]})]}):e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx(se,{htmlFor:"fub-key",children:"Follow Up Boss API Key"}),e.jsx(be,{id:"fub-key",type:"password",placeholder:"fka_live_...",value:t,onChange:g=>n(g.target.value)}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-1 flex items-center gap-1",children:["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(Tr,{className:"h-3 w-3"})]})]})]}),e.jsx($,{onClick:()=>h.mutate(t),disabled:!t.trim()||h.isPending,children:h.isPending?"Connecting…":"Connect"})]})})]})}function tDn(){var V;const s=ts(),[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,x]=j.useState(null),[g,y]=j.useState(!1),[b,v]=j.useState(new Set),{data:N,isLoading:C}=ht({queryKey:["cloze-status"],queryFn:async()=>{const{data:K,error:Q}=await U.functions.invoke("cloze-sync",{body:{action:"status"}});if(Q)throw Q;return K}}),A=yt({mutationFn:async()=>{const{data:K,error:Q}=await U.functions.invoke("cloze-sync",{body:{action:"save_token",api_key:t.trim(),account_email:r.trim()}});if(Q)throw Q;if(K!=null&&K.error)throw new Error(K.error);return K},onSuccess:()=>{ae.success("Connected to Cloze"),n(""),a(""),s.invalidateQueries({queryKey:["cloze-status"]})},onError:K=>ae.error(K.message)}),T=yt({mutationFn:async()=>{const{error:K}=await U.functions.invoke("cloze-sync",{body:{action:"disconnect"}});if(K)throw K},onSuccess:()=>{ae.success("Cloze disconnected"),s.invalidateQueries({queryKey:["cloze-status"]})}}),P=yt({mutationFn:async K=>{const{error:Q}=await U.functions.invoke("cloze-sync",{body:{action:"set_direction",sync_direction:K}});if(Q)throw Q},onSuccess:()=>s.invalidateQueries({queryKey:["cloze-status"]})}),M=yt({mutationFn:async K=>{const{error:Q}=await U.functions.invoke("cloze-sync",{body:{action:"set_scope",...K}});if(Q)throw Q},onSuccess:()=>s.invalidateQueries({queryKey:["cloze-status"]})}),I=async()=>{y(!0);try{const{data:K,error:Q}=await U.functions.invoke("cloze-sync",{body:{action:"list_segments"}});if(Q)throw Q;if(K!=null&&K.error)throw new Error(K.error);x(K.segments||[]),v(new Set((N==null?void 0:N.selected_segments)||[])),m(!0)}catch(K){ae.error(K.message||"Failed to load segments")}finally{y(!1)}},D=async()=>{const K=Array.from(b);await M.mutateAsync({sync_scope:"segments",selected_segments:K}),ae.success(`Saved · ${K.length} segment(s) selected`),m(!1)},B=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 Q=0,J=0,ce=0;for(;;){const{data:ue,error:ne}=await U.functions.invoke("cloze-sync",{body:{action:"sync",offset:Q}});if(ne)throw ne;if(ue!=null&&ue.error)throw new Error(ue.error);if(J+=ue.chunk_created||0,ce+=ue.chunk_updated||0,Q=ue.next_offset,u(`Pulling · ${J+ce} contacts processed`),c(ue.done?100:Math.min(95,(J+ce)%200/2)),ue.done)break;await new Promise(ee=>setTimeout(ee,300))}ae.success(`Pulled · ${J} new, ${ce} updated`)}if(K==="push_only"||K==="bidirectional"){c(0),u("Pushing to Cloze…");let Q=0,J=0,ce=0;for(;;){const{data:ue,error:ne}=await U.functions.invoke("cloze-sync",{body:{action:"push",offset:Q}});if(ne)throw ne;if(ue!=null&&ue.error)throw new Error(ue.error);J+=ue.chunk_pushed||0,ce+=ue.chunk_failed||0,Q=ue.next_offset;const ee=ue.total?Math.min(100,Math.round(Q/ue.total*100)):100;if(c(ee),u(`Pushing · ${Q} / ${ue.total||"?"}`),ue.done)break;await new Promise(le=>setTimeout(le,300))}ae.success(`Pushed · ${J}${ce?`, ${ce} failed`:""}`)}s.invalidateQueries({queryKey:["cloze-status"]})}catch(Q){ae.error(Q.message||"Sync failed")}finally{l(!1),setTimeout(()=>{c(0),u(null)},2e3)}},q=(N==null?void 0:N.sync_scope)||"all",W=((V=N==null?void 0:N.selected_segments)==null?void 0:V.length)||0;return e.jsxs(_e,{children:[e.jsx(Bt,{children:e.jsx("div",{className:"flex items-start justify-between gap-3",children:e.jsxs("div",{children:[e.jsxs(Ut,{className:"flex items-center gap-2",children:[e.jsx(Wj,{className:"h-5 w-5 text-primary"}),"Cloze",(N==null?void 0:N.connected)&&e.jsxs($e,{variant:"default",className:"ml-1",children:[e.jsx(Ro,{className:"h-3 w-3 mr-1"})," Connected"]})]}),e.jsx(vr,{children:"Sync contacts between Cloze and Agent OS using your personal Cloze API key."})]})})}),e.jsx(Oe,{className:"space-y-4",children:C?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(vs,{value:N.sync_direction||"pull_only",onValueChange:K=>P.mutate(K),disabled:i||P.isPending,children:[e.jsx(gs,{className:"w-[180px]",children:e.jsx(bs,{})}),e.jsxs(ys,{children:[e.jsx(Ye,{value:"pull_only",children:"Pull from Cloze"}),e.jsx(Ye,{value:"push_only",children:"Push to Cloze"}),e.jsx(Ye,{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:q==="all"?"All Cloze contacts.":`${W} segment${W===1?"":"s"} selected.`})]}),e.jsxs(vs,{value:q,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(gs,{className:"w-[180px]",children:e.jsx(bs,{})}),e.jsxs(ys,{children:[e.jsx(Ye,{value:"all",children:"All contacts"}),e.jsx(Ye,{value:"segments",children:"Selected segments"})]})]})]}),q==="segments"&&e.jsxs("div",{children:[e.jsxs($,{variant:"outline",size:"sm",onClick:I,disabled:g,children:[e.jsx(ZK,{className:"h-4 w-4 mr-2"}),g?"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 Q=b.has(K.id);return e.jsxs("label",{className:"flex items-center gap-3 p-2 cursor-pointer hover:bg-muted/50",children:[e.jsx(ui,{checked:Q,onCheckedChange:J=>{const ce=new Set(b);J?ce.add(K.id):ce.delete(K.id),v(ce)}}),e.jsx("span",{className:"flex-1 text-sm",children:K.name}),K.count!=null&&e.jsx($e,{variant:"secondary",className:"text-xs",children:K.count})]},K.id)})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs($,{size:"sm",onClick:D,disabled:M.isPending,children:["Save selection (",b.size,")"]}),e.jsx($,{size:"sm",variant:"ghost",onClick:()=>m(!1),children:"Cancel"})]})]})]})]}),d&&e.jsxs("div",{className:"space-y-1",children:[e.jsx(Ki,{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(Ll,{children:[e.jsx(_f,{asChild:!0,children:e.jsxs($,{disabled:i,children:[e.jsx(Wi,{className:`h-4 w-4 mr-2 ${i?"animate-spin":""}`}),i?"Syncing…":"Sync Now"]})}),e.jsxs(yl,{children:[e.jsxs(vl,{children:[e.jsx(_l,{children:"Preview sync"}),e.jsx(wl,{asChild:!0,children:e.jsx(sDn,{segments:p})})]}),e.jsxs(bl,{children:[e.jsx(jl,{children:"Cancel"}),e.jsx(fl,{onClick:B,children:"Start Sync"})]})]})]}),e.jsxs(Ll,{children:[e.jsx(_f,{asChild:!0,children:e.jsxs($,{variant:"outline",disabled:i,children:[e.jsx(Pn,{className:"h-4 w-4 mr-2"})," Disconnect"]})}),e.jsxs(yl,{children:[e.jsxs(vl,{children:[e.jsx(_l,{children:"Disconnect Cloze?"}),e.jsx(wl,{children:"Your API key will be removed. Contacts already synced will remain."})]}),e.jsxs(bl,{children:[e.jsx(jl,{children:"Cancel"}),e.jsx(fl,{onClick:()=>T.mutate(),children:"Disconnect"})]})]})]})]})]}):e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx(se,{htmlFor:"cloze-email",children:"Cloze Account Email"}),e.jsx(be,{id:"cloze-email",type:"email",placeholder:"you@example.com",value:r,onChange:K=>a(K.target.value)})]}),e.jsxs("div",{children:[e.jsx(se,{htmlFor:"cloze-key",children:"Cloze API Key"}),e.jsx(be,{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(Tr,{className:"h-3 w-3"})]})]})]}),e.jsx($,{onClick:()=>A.mutate(),disabled:!t.trim()||!r.trim()||A.isPending,children:A.isPending?"Connecting…":"Connect Cloze"})]})})]})}function sDn({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 U.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 nDn(){const s=ts(),[t,n]=j.useState(""),[r,a]=j.useState(!1),[i,l]=j.useState(0),[o,c]=j.useState(null),{data:d,isLoading:u}=ht({queryKey:["boomtown-status"],queryFn:async()=>{const{data:g,error:y}=await U.functions.invoke("boomtown-sync",{body:{action:"status"}});if(y)throw y;return g}}),h=yt({mutationFn:async g=>{const{data:y,error:b}=await U.functions.invoke("boomtown-sync",{body:{action:"save_token",api_key:g}});if(b)throw b;if(y!=null&&y.error)throw new Error(y.error);return y},onSuccess:()=>{ae.success("Connected to Boomtown"),n(""),s.invalidateQueries({queryKey:["boomtown-status"]})},onError:g=>ae.error(g.message)}),m=yt({mutationFn:async()=>{const{error:g}=await U.functions.invoke("boomtown-sync",{body:{action:"disconnect"}});if(g)throw g},onSuccess:()=>{ae.success("Disconnected"),s.invalidateQueries({queryKey:["boomtown-status"]})}}),p=yt({mutationFn:async g=>{const{error:y}=await U.functions.invoke("boomtown-sync",{body:{action:"set_direction",sync_direction:g}});if(y)throw y},onSuccess:()=>s.invalidateQueries({queryKey:["boomtown-status"]})}),x=async()=>{a(!0),l(0),c("Pulling from Boomtown…");let g=0,y=0,b=0,v=0;try{for(;;){const{data:T,error:P}=await U.functions.invoke("boomtown-sync",{body:{action:"sync",offset:g}});if(P)throw P;if(T!=null&&T.error)throw new Error(T.error);y+=T.chunk_created||0,b+=T.chunk_updated||0,v+=T.chunk_skipped||0,g=T.next_offset;const M=T.total?Math.min(100,Math.round(g/T.total*100)):100;if(l(M),c(`Pulling · ${g} / ${T.total||"?"}`),T.done)break;await new Promise(I=>setTimeout(I,400))}let N=0,C=0;if((d==null?void 0:d.sync_direction)==="bidirectional"){let T=0;for(l(0),c("Pushing to Boomtown…");;){const{data:P,error:M}=await U.functions.invoke("boomtown-sync",{body:{action:"push",offset:T}});if(M)throw M;if(P!=null&&P.error)throw new Error(P.error);N+=P.chunk_pushed||0,C+=P.chunk_failed||0,T=P.next_offset;const I=P.total?Math.min(100,Math.round(T/P.total*100)):100;if(l(I),c(`Pushing · ${T} / ${P.total||"?"}`),P.done)break;await new Promise(D=>setTimeout(D,400))}}const A=N||C?` · pushed ${N}${C?`, ${C} failed`:""}`:"";ae.success(`Sync complete · ${y} new, ${b} updated${v?`, ${v} skipped`:""}${A}`),s.invalidateQueries({queryKey:["boomtown-status"]})}catch(N){ae.error(N.message||"Sync failed")}finally{a(!1),setTimeout(()=>{l(0),c(null)},2500)}};return e.jsxs(_e,{children:[e.jsx(Bt,{children:e.jsx("div",{className:"flex items-start justify-between gap-3",children:e.jsxs("div",{children:[e.jsxs(Ut,{className:"flex items-center gap-2",children:[e.jsx(Wj,{className:"h-5 w-5 text-primary"}),"Boomtown",(d==null?void 0:d.connected)&&e.jsxs($e,{variant:"default",className:"ml-1",children:[e.jsx(Ro,{className:"h-3 w-3 mr-1"})," Connected"]})]}),e.jsx(vr,{children:"Sync your Boomtown contacts into Agent OS."})]})})}),e.jsx(Oe,{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(Tn,{checked:d.sync_direction==="bidirectional",onCheckedChange:g=>p.mutate(g?"bidirectional":"pull_only"),disabled:r||p.isPending})]}),o&&e.jsxs("div",{className:"space-y-1",children:[e.jsx(Ki,{value:i}),e.jsx("p",{className:"text-xs text-muted-foreground",children:o})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs($,{onClick:x,disabled:r,children:[e.jsx(Wi,{className:`h-4 w-4 mr-2 ${r?"animate-spin":""}`}),r?"Syncing…":"Sync Now"]}),e.jsxs(Ll,{children:[e.jsx(_f,{asChild:!0,children:e.jsxs($,{variant:"outline",disabled:r,children:[e.jsx(Pn,{className:"h-4 w-4 mr-2"})," Disconnect"]})}),e.jsxs(yl,{children:[e.jsxs(vl,{children:[e.jsx(_l,{children:"Disconnect Boomtown?"}),e.jsx(wl,{children:"Your API key will be removed. Synced contacts stay in Agent OS."})]}),e.jsxs(bl,{children:[e.jsx(jl,{children:"Cancel"}),e.jsx(fl,{onClick:()=>m.mutate(),children:"Disconnect"})]})]})]})]})]}):e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx(se,{htmlFor:"boomtown-key",children:"Boomtown API Key"}),e.jsx(be,{id:"boomtown-key",type:"password",placeholder:"Paste your Boomtown Ambassador API key",value:t,onChange:g=>n(g.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(Tr,{className:"h-3 w-3"})]})]}),e.jsx($,{onClick:()=>h.mutate(t),disabled:!t.trim()||h.isPending,children:h.isPending?"Connecting…":"Connect"})]})})]})}function kVt(){const s=Vn(),[t,n]=j.useState(""),[r,a]=j.useState(""),[i,l]=j.useState("Test from ReLevelUp"),[o,c]=j.useState(!1),{data:d,isLoading:u}=ht({queryKey:["ses-config"],queryFn:async()=>{const p=await QX();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){ae.error("Please fill in From and To email addresses");return}c(!0);try{const p=await QX(),g=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();g.success?ae.success(`Test email sent! Message ID: ${g.messageId}`):ae.error(g.error||"Failed to send test email")}catch(p){ae.error(p.message||"Failed to send test email")}finally{c(!1)}},m=(d==null?void 0:d.configured)===!0;return e.jsxs(_e,{children:[e.jsx(Bt,{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(nn,{className:"h-5 w-5 text-orange-600"})}),e.jsxs("div",{children:[e.jsx(Ut,{className:"text-lg",children:"Amazon SES — Mass Email"}),e.jsx(vr,{children:"Send bulk email campaigns via Amazon SES"})]})]}),e.jsx($e,{variant:m?"default":"secondary",children:u?"Checking...":m?e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Ro,{className:"h-3 w-3"})," Connected"]}):e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(xo,{className:"h-3 w-3"})," Not Configured"]})})]})}),m&&e.jsxs(Oe,{className:"space-y-4",children:[e.jsxs("div",{className:"rounded-lg border p-4 space-y-3",children:[e.jsx("h4",{className:"font-medium text-sm",children:"Send Test Email"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:'Verify your SES setup by sending a test email. The "From" address must be verified in SES or belong to a verified domain.'}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-3",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(se,{className:"text-xs",children:"From Email"}),e.jsx(be,{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(se,{className:"text-xs",children:"To Email"}),e.jsx(be,{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(se,{className:"text-xs",children:"Subject"}),e.jsx(be,{value:i,onChange:p=>l(p.target.value),className:"text-sm"})]})]}),e.jsxs($,{onClick:h,disabled:o,size:"sm",children:[o?e.jsx(Ht,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(Br,{className:"h-4 w-4 mr-2"}),"Send Test"]})]}),e.jsxs($,{onClick:()=>s("/admin/email-campaigns"),className:"w-full",children:[e.jsx(Eh,{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(Oe,{children:e.jsxs("p",{className:"text-sm text-muted-foreground",children:["AWS SES credentials are not configured. Add ",e.jsx("code",{children:"AWS_SES_ACCESS_KEY_ID"}),", ",e.jsx("code",{children:"AWS_SES_SECRET_ACCESS_KEY"}),", and ",e.jsx("code",{children:"AWS_SES_REGION"})," as secrets to enable."]})})]})}async function _De(s){const t=await QX(),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 rDn({status:s}){return s==="verified"?e.jsxs($e,{className:"bg-green-500/10 text-green-700 hover:bg-green-500/20 border-green-500/20",children:[e.jsx(Fr,{className:"h-3 w-3 mr-1"})," Verified"]}):s==="pending"?e.jsxs($e,{variant:"secondary",children:[e.jsx(Hr,{className:"h-3 w-3 mr-1"})," Pending — check inbox"]}):s==="failed"||s==="temporary_failure"?e.jsxs($e,{variant:"destructive",children:[e.jsx(xo,{className:"h-3 w-3 mr-1"})," Failed"]}):e.jsxs($e,{variant:"outline",children:[e.jsx(xo,{className:"h-3 w-3 mr-1"})," Not started"]})}function SVt({brokerageId:s,onVerifiedSelect:t}){const n=ts(),[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:x}=ht({queryKey:["brokerage-verified-senders",s],queryFn:async()=>{const{data:v,error:N}=await U.from("brokerage_verified_senders").select("*").eq("brokerage_id",s).order("created_at",{ascending:!1});if(N)throw N;return v||[]}}),g=yt({mutationFn:async()=>_De({action:"request_verification",brokerage_id:s,email:r,display_name:i||void 0}),onSuccess:()=>{n.invalidateQueries({queryKey:["brokerage-verified-senders",s]}),ae.success("Verification email sent",{description:`Check ${r} and click the AWS verification link.`}),a(""),l(""),c(!1)},onError:v=>ae.error(v.message)}),y=async v=>{var N,C;u(v.id);try{const A=await _De({action:"check_status",sender_id:v.id});n.invalidateQueries({queryKey:["brokerage-verified-senders",s]}),((N=A.sender)==null?void 0:N.status)==="verified"?ae.success(`${v.email} is verified! 🎉`):ae.info(`Status: ${((C=A.sender)==null?void 0:C.status)||"unknown"}`)}catch(A){ae.error(A.message)}finally{u(null)}},b=yt({mutationFn:async v=>_De({action:"delete",sender_id:v}),onSuccess:()=>{n.invalidateQueries({queryKey:["brokerage-verified-senders",s]}),ae.success("Sender removed"),m(null)},onError:v=>ae.error(v.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."})]}),x?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(v=>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(nn,{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:v.email}),e.jsx(rDn,{status:v.status})]}),v.display_name&&e.jsxs("p",{className:"text-xs text-muted-foreground truncate",children:['"',v.display_name,'"']})]})]}),e.jsxs("div",{className:"flex items-center gap-1 shrink-0",children:[v.status==="verified"&&t&&e.jsx($,{size:"sm",variant:"outline",onClick:()=>t(v.email),children:"Use"}),v.status!=="verified"&&e.jsx($,{size:"sm",variant:"ghost",onClick:()=>y(v),disabled:d===v.id,title:"Refresh status from AWS",children:d===v.id?e.jsx(Ht,{className:"h-4 w-4 animate-spin"}):e.jsx(Wi,{className:"h-4 w-4"})}),e.jsx($,{size:"sm",variant:"ghost",onClick:()=>m(v),className:"text-destructive hover:text-destructive",children:e.jsx(Pn,{className:"h-4 w-4"})})]})]},v.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(se,{className:"text-xs",children:"Email Address *"}),e.jsx(be,{type:"email",value:r,onChange:v=>a(v.target.value),placeholder:"broker@yourbrokerage.com",className:"text-sm"})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(se,{className:"text-xs",children:"Display Name (optional)"}),e.jsx(be,{value:i,onChange:v=>l(v.target.value),placeholder:"John at Acme Realty",className:"text-sm"})]})]}),e.jsx("p",{className:"text-xs text-muted-foreground leading-relaxed",children:"We'll ask AWS to send a verification email to this address. The owner must click the link before this sender can be used."}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs($,{size:"sm",onClick:()=>g.mutate(),disabled:!r.trim()||g.isPending,children:[g.isPending?e.jsx(Ht,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(nn,{className:"h-4 w-4 mr-2"}),"Send Verification Email"]}),e.jsx($,{size:"sm",variant:"ghost",onClick:()=>{c(!1),a(""),l("")},children:"Cancel"})]})]}):e.jsxs($,{size:"sm",variant:"outline",onClick:()=>c(!0),children:[e.jsx(sn,{className:"h-4 w-4 mr-1"})," Add Sender Address"]}),e.jsx(Ll,{open:!!h,onOpenChange:v=>!v&&m(null),children:e.jsxs(yl,{children:[e.jsxs(vl,{children:[e.jsx(_l,{children:"Remove this sender?"}),e.jsxs(wl,{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(bl,{children:[e.jsx(jl,{children:"Cancel"}),e.jsx(fl,{onClick:()=>h&&b.mutate(h.id),className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Remove"})]})]})})]})}async function wDe(s){const t=await QX(),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 aDn({status:s}){return s==="verified"?e.jsxs($e,{className:"bg-green-500/10 text-green-700 hover:bg-green-500/20 border-green-500/20",children:[e.jsx(Fr,{className:"h-3 w-3 mr-1"})," Verified"]}):s==="pending"?e.jsxs($e,{variant:"secondary",children:[e.jsx(Hr,{className:"h-3 w-3 mr-1"})," Pending — check inbox"]}):s==="failed"||s==="temporary_failure"?e.jsxs($e,{variant:"destructive",children:[e.jsx(xo,{className:"h-3 w-3 mr-1"})," Failed"]}):e.jsxs($e,{variant:"outline",children:[e.jsx(xo,{className:"h-3 w-3 mr-1"})," Not started"]})}function iDn({userId:s,onVerifiedSelect:t}){const n=ts(),[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:x}=ht({queryKey:["user-verified-senders",s],queryFn:async()=>{const{data:v,error:N}=await U.from("user_verified_senders").select("*").eq("user_id",s).order("created_at",{ascending:!1});if(N)throw N;return v||[]}}),g=yt({mutationFn:async()=>wDe({action:"request_verification",scope:"user",email:r,display_name:i||void 0}),onSuccess:()=>{n.invalidateQueries({queryKey:["user-verified-senders",s]}),ae.success("Verification email sent",{description:`Check ${r} and click the AWS verification link.`}),a(""),l(""),c(!1)},onError:v=>ae.error(v.message)}),y=async v=>{var N,C;u(v.id);try{const A=await wDe({action:"check_status",sender_id:v.id});n.invalidateQueries({queryKey:["user-verified-senders",s]}),((N=A.sender)==null?void 0:N.status)==="verified"?ae.success(`${v.email} is verified! 🎉`):ae.info(`Status: ${((C=A.sender)==null?void 0:C.status)||"unknown"}`)}catch(A){ae.error(A.message)}finally{u(null)}},b=yt({mutationFn:async v=>wDe({action:"delete",sender_id:v}),onSuccess:()=>{n.invalidateQueries({queryKey:["user-verified-senders",s]}),ae.success("Sender removed"),m(null)},onError:v=>ae.error(v.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."]})]}),x?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(v=>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(nn,{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:v.email}),e.jsx(aDn,{status:v.status})]}),v.display_name&&e.jsxs("p",{className:"text-xs text-muted-foreground truncate",children:['"',v.display_name,'"']})]})]}),e.jsxs("div",{className:"flex items-center gap-1 shrink-0",children:[v.status==="verified"&&t&&e.jsx($,{size:"sm",variant:"outline",onClick:()=>t(v.email),children:"Use"}),v.status!=="verified"&&e.jsx($,{size:"sm",variant:"ghost",onClick:()=>y(v),disabled:d===v.id,title:"Refresh status from AWS",children:d===v.id?e.jsx(Ht,{className:"h-4 w-4 animate-spin"}):e.jsx(Wi,{className:"h-4 w-4"})}),e.jsx($,{size:"sm",variant:"ghost",onClick:()=>m(v),className:"text-destructive hover:text-destructive",children:e.jsx(Pn,{className:"h-4 w-4"})})]})]},v.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(se,{className:"text-xs",children:"Email Address *"}),e.jsx(be,{type:"email",value:r,onChange:v=>a(v.target.value),placeholder:"you@yourdomain.com",className:"text-sm"})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(se,{className:"text-xs",children:"Display Name (optional)"}),e.jsx(be,{value:i,onChange:v=>l(v.target.value),placeholder:"Jane at Acme Realty",className:"text-sm"})]})]}),e.jsx("p",{className:"text-xs text-muted-foreground leading-relaxed",children:"We'll ask Amazon to send a verification email to this address. You must click the link before this sender can be used in a campaign."}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs($,{size:"sm",onClick:()=>g.mutate(),disabled:!r.trim()||g.isPending,children:[g.isPending?e.jsx(Ht,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(nn,{className:"h-4 w-4 mr-2"}),"Send Verification Email"]}),e.jsx($,{size:"sm",variant:"ghost",onClick:()=>{c(!1),a(""),l("")},children:"Cancel"})]})]}):e.jsxs($,{size:"sm",variant:"outline",onClick:()=>c(!0),children:[e.jsx(sn,{className:"h-4 w-4 mr-1"})," Add Sender Address"]}),e.jsx(Ll,{open:!!h,onOpenChange:v=>!v&&m(null),children:e.jsxs(yl,{children:[e.jsxs(vl,{children:[e.jsx(_l,{children:"Remove this sender?"}),e.jsxs(wl,{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(bl,{children:[e.jsx(jl,{children:"Cancel"}),e.jsx(fl,{onClick:()=>h&&b.mutate(h.id),className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Remove"})]})]})})]})}function oDn(){var C,A,T,P,M;const{user:s,isBrokerageManager:t,isAdmin:n,managedBrokerages:r,selectedBrokerageId:a}=_s(),i=a||((C=r==null?void 0:r[0])==null?void 0:C.id)||null,l=(t||n)&&!!i,o=ts(),[c,d]=j.useState(!1),[u,h]=j.useState(""),[m,p]=j.useState(""),{data:x}=ht({queryKey:["mass-email-settings",s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:I,error:D}=await U.from("mass_email_settings").select("*").eq("user_id",s.id).maybeSingle();if(D)throw D;return I}}),{data:g}=ht({queryKey:["agent-profile-email",s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:I,error:D}=await U.from("profiles").select("email, name").eq("id",s.id).single();if(D)throw D;return I}}),y=((A=x==null?void 0:x.reply_to_email)==null?void 0:A.trim())||((T=g==null?void 0:g.email)==null?void 0:T.trim())||"",b=((P=x==null?void 0:x.display_name)==null?void 0:P.trim())||((M=g==null?void 0:g.name)==null?void 0:M.trim())||"";j.useEffect(()=>{c||(h(y),p(b))},[c,y,b]);const v=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(x){const{error:D}=await U.from("mass_email_settings").update(I).eq("user_id",s.id);if(D)throw D}else{const{error:D}=await U.from("mass_email_settings").insert({user_id:s.id,...I});if(D)throw D}},onSuccess:()=>{o.invalidateQueries({queryKey:["mass-email-settings",s==null?void 0:s.id]}),o.invalidateQueries({queryKey:["mass-email-ready",s==null?void 0:s.id]}),o.invalidateQueries({queryKey:["mass-email-settings-check",s==null?void 0:s.id]}),ae.success("Reply-to email saved!"),d(!1)},onError:I=>ae.error(I.message)}),N=!!y;return e.jsxs(_e,{children:[e.jsx(Bt,{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(Br,{className:"h-5 w-5 text-orange-600"})}),e.jsxs("div",{children:[e.jsxs(Ut,{className:"text-lg flex items-center gap-2",children:["Mass Email",N?e.jsxs($e,{variant:"default",className:"text-xs bg-green-600",children:[e.jsx(Ro,{className:"h-3 w-3 mr-1"})," Set Up"]}):e.jsx($e,{variant:"secondary",className:"text-xs",children:"Setup Required"})]}),e.jsx(vr,{children:"Set the email address where replies from your campaigns will be sent. If you haven't customized it yet, we'll use your profile email."})]})]})}),e.jsxs(Oe,{className:"space-y-3",children:[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:b||"No display name"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:y})]}),e.jsxs($,{variant:"ghost",size:"sm",onClick:()=>d(!0),children:[e.jsx(Ya,{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(se,{className:"text-xs",children:"Display Name"}),e.jsx(be,{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(se,{className:"text-xs",children:"Reply-To Email *"}),e.jsx(be,{type:"email",placeholder:"your@email.com",value:u,onChange:I=>h(I.target.value)})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs($,{size:"sm",onClick:()=>v.mutate(),disabled:v.isPending||!u.trim(),children:[e.jsx(Jo,{className:"h-4 w-4 mr-1"})," Save"]}),c&&e.jsxs($,{size:"sm",variant:"outline",onClick:()=>{d(!1),h(y),p(b)},children:[e.jsx(pr,{className:"h-4 w-4 mr-1"})," Cancel"]})]})]}),s&&e.jsxs(e.Fragment,{children:[e.jsx(Hl,{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(j0,{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(iDn,{userId:s.id,onVerifiedSelect:I=>{h(I),d(!0)}})]})]}),l&&e.jsxs(e.Fragment,{children:[e.jsx(Hl,{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(j0,{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(SVt,{brokerageId:i})]})]})]})]})}function lDn({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 cDn(){const s=Vn(),{isAdmin:t,user:n}=_s(),{actingAsAgent:r,effectiveUserId:a}=aee(),i=ts(),[l,o]=j.useState(!1),[c,d]=j.useState(!1),[u,h]=j.useState(!1),{scopeUserId:m,isDelegated:p}=lDn({authUserId:n==null?void 0:n.id,actingAsUserId:(r==null?void 0:r.id)??a}),{data:x,isLoading:g}=ht({queryKey:["gmail-integration",m],enabled:!!m&&!p,queryFn:async()=>{const{data:D,error:B}=await U.from("gmail_integrations").select("*").eq("user_id",m).maybeSingle();if(B)throw B;return D}}),{data:y}=ht({queryKey:["social-accounts",m],enabled:!!m&&!p,queryFn:async()=>{const{data:D,error:B}=await U.from("social_accounts").select("*").eq("user_id",m).order("created_at",{ascending:!1});if(B)throw B;return D}}),b=async()=>{if(p){ae.error("Account connections must be made by the agent from their own login.");return}o(!0);try{const{data:D,error:B}=await U.functions.invoke("gmail-oauth",{body:{action:"get_auth_url"}});if(B)throw B;if(D!=null&&D.authUrl)window.location.href=D.authUrl;else throw new Error("Failed to get authorization URL")}catch(D){console.error("Gmail OAuth error:",D),ae.error("Failed to start Gmail connection"),o(!1)}},v=async D=>{if(p){ae.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:B,error:q}=await U.functions.invoke("meta-oauth",{body:{action:"get_auth_url",callbackPath:"/social-connections/callback",authMode:D}});if(q)throw q;if(B!=null&&B.authUrl)window.location.href=B.authUrl;else throw new Error("Failed to get authorization URL")}catch(B){console.error("Meta OAuth error:",B),ae.error("Failed to start connection. Make sure Meta App credentials are configured."),d(!1)}},N=async()=>{if(p){ae.error("Account connections must be made by the agent from their own login.");return}h(!0);try{const{data:D,error:B}=await U.functions.invoke("linkedin-oauth",{body:{action:"get_auth_url",callbackPath:"/social-connections/linkedin-callback"}});if(B)throw B;if(D!=null&&D.authUrl)window.location.href=D.authUrl;else throw new Error("Failed to get LinkedIn authorization URL")}catch(D){console.error("LinkedIn OAuth error:",D),ae.error("Failed to start LinkedIn connection. Please try again."),h(!1)}},C=yt({mutationFn:async D=>{const{error:B}=await U.from("gmail_integrations").delete().eq("id",D).eq("user_id",m);if(B)throw B},onSuccess:()=>{i.invalidateQueries({queryKey:["gmail-integration",m]}),ae.success("Gmail disconnected")},onError:()=>{ae.error("Failed to disconnect Gmail")}}),A=yt({mutationFn:async D=>{const{error:B}=await U.from("social_accounts").delete().eq("id",D).eq("user_id",m);if(B)throw B},onSuccess:()=>{i.invalidateQueries({queryKey:["social-accounts",m]}),ae.success("Account disconnected")},onError:()=>{ae.error("Failed to disconnect account")}}),T=!p&&!!(x!=null&&x.is_active),P=(y==null?void 0:y.filter(D=>D.platform==="facebook"))||[],M=(y==null?void 0:y.filter(D=>D.platform==="instagram"))||[],I=(y==null?void 0:y.filter(D=>D.platform==="linkedin"))||[];return e.jsx(Ks,{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(_e,{className:"border-amber-500/40 bg-amber-500/5",children:e.jsxs(Bt,{className:"flex flex-row items-start gap-3 space-y-0",children:[e.jsx(Ad,{className:"h-5 w-5 text-amber-600 mt-0.5"}),e.jsxs("div",{children:[e.jsx(Ut,{className:"text-base",children:"Connected accounts are hidden"}),e.jsxs(vr,{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(_e,{children:[e.jsx(Bt,{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(t5,{className:"h-5 w-5 text-primary"})}),e.jsxs("div",{children:[e.jsx(Ut,{className:"text-lg",children:"ChatGPT"}),e.jsx(vr,{children:"Connect ChatGPT to LevelUp so it can use LevelUp tools on your behalf."})]})]})}),e.jsx(Oe,{children:e.jsxs($,{variant:"outline",onClick:()=>s("/connect-chatgpt"),children:["View connection instructions ",e.jsx(ni,{className:"h-4 w-4 ml-1"})]})})]}),e.jsxs(_e,{children:[e.jsx(Bt,{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(nn,{className:"h-5 w-5 text-destructive"})}),e.jsxs("div",{children:[e.jsxs(Ut,{className:"text-lg flex items-center gap-2",children:["Gmail",T&&e.jsx($e,{variant:"default",className:"text-xs bg-green-600",children:"Connected"})]}),e.jsx(vr,{children:"Send emails directly from your contact pages and auto-log them as touchpoints."})]})]})}),e.jsx(Oe,{children:e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-start gap-2 text-sm text-muted-foreground",children:[e.jsx(Ro,{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(Ro,{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(Ro,{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:x.gmail_email}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Connected Gmail account"})]}),e.jsxs(Ll,{children:[e.jsx(_f,{asChild:!0,children:e.jsx($,{variant:"ghost",size:"icon",className:"text-destructive hover:text-destructive",children:e.jsx(Pn,{className:"h-4 w-4"})})}),e.jsxs(yl,{children:[e.jsxs(vl,{children:[e.jsx(_l,{children:"Disconnect Gmail?"}),e.jsx(wl,{children:"This will remove your Gmail connection. You'll need to reconnect to send emails."})]}),e.jsxs(bl,{children:[e.jsx(jl,{children:"Cancel"}),e.jsx(fl,{onClick:()=>C.mutate(x.id),className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Disconnect"})]})]})]})]}):e.jsxs($,{className:"mt-4",onClick:b,disabled:l||g,children:[l?e.jsx(Wi,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(nn,{className:"h-4 w-4 mr-2"}),"Connect Gmail",e.jsx(ni,{className:"h-4 w-4 ml-2"})]})]})})]}),e.jsxs(_e,{children:[e.jsx(Bt,{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(jf,{className:"h-5 w-5 text-blue-600"})}),e.jsxs("div",{children:[e.jsxs(Ut,{className:"text-lg flex items-center gap-2",children:["Facebook",P.length>0&&e.jsx($e,{variant:"default",className:"text-xs bg-green-600",children:"Connected"})]}),e.jsx(vr,{children:"Connect Facebook Pages to post content and reach your audience."})]})]})}),e.jsxs(Oe,{className:"space-y-3",children:[P.length>0&&e.jsx("div",{className:"space-y-2",children:P.map(D=>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(ki,{src:D.profile_picture_url||""}),e.jsx(Ta,{children:e.jsx(jf,{className:"h-4 w-4"})})]}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-sm",children:D.page_name||D.platform_username||"Facebook Page"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Connected Facebook Page"})]})]}),e.jsxs(Ll,{children:[e.jsx(_f,{asChild:!0,children:e.jsx($,{variant:"ghost",size:"icon",className:"text-destructive hover:text-destructive",children:e.jsx(Pn,{className:"h-4 w-4"})})}),e.jsxs(yl,{children:[e.jsxs(vl,{children:[e.jsx(_l,{children:"Disconnect Facebook?"}),e.jsx(wl,{children:"This will remove the connection. You'll need to reconnect to post content."})]}),e.jsxs(bl,{children:[e.jsx(jl,{children:"Cancel"}),e.jsx(fl,{onClick:()=>A.mutate(D.id),className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Disconnect"})]})]})]})]},D.id))}),e.jsxs($,{onClick:()=>v("facebook"),disabled:c,variant:"outline",className:"gap-2",children:[c?e.jsx(Wi,{className:"h-4 w-4 animate-spin"}):e.jsx(sn,{className:"h-4 w-4"}),"Connect Facebook Page"]})]})]}),e.jsxs(_e,{children:[e.jsx(Bt,{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(Qh,{className:"h-5 w-5 text-pink-600"})}),e.jsxs("div",{children:[e.jsxs(Ut,{className:"text-lg flex items-center gap-2",children:["Instagram",M.length>0&&e.jsx($e,{variant:"default",className:"text-xs bg-green-600",children:"Connected"})]}),e.jsx(vr,{children:"Connect an Instagram Business or Creator account to schedule and publish posts. Personal accounts are not supported by Meta's API."})]})]})}),e.jsxs(Oe,{className:"space-y-3",children:[M.length>0&&e.jsx("div",{className:"space-y-2",children:M.map(D=>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(ki,{src:D.profile_picture_url||""}),e.jsx(Ta,{children:e.jsx(Qh,{className:"h-4 w-4"})})]}),e.jsxs("div",{children:[e.jsxs("p",{className:"font-medium text-sm",children:["@",D.platform_username||"Instagram Account"]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Connected Instagram account"})]})]}),e.jsxs(Ll,{children:[e.jsx(_f,{asChild:!0,children:e.jsx($,{variant:"ghost",size:"icon",className:"text-destructive hover:text-destructive",children:e.jsx(Pn,{className:"h-4 w-4"})})}),e.jsxs(yl,{children:[e.jsxs(vl,{children:[e.jsx(_l,{children:"Disconnect Instagram?"}),e.jsx(wl,{children:"This will remove the connection. You'll need to reconnect to post content."})]}),e.jsxs(bl,{children:[e.jsx(jl,{children:"Cancel"}),e.jsx(fl,{onClick:()=>A.mutate(D.id),className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Disconnect"})]})]})]})]},D.id))}),e.jsxs($,{onClick:()=>v("instagram"),disabled:c,variant:"outline",className:"gap-2",children:[c?e.jsx(Wi,{className:"h-4 w-4 animate-spin"}):e.jsx(sn,{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(_e,{children:[e.jsx(Bt,{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(kg,{className:"h-5 w-5 text-blue-700"})}),e.jsxs("div",{children:[e.jsxs(Ut,{className:"text-lg flex items-center gap-2",children:["LinkedIn",I.length>0&&e.jsx($e,{variant:"default",className:"text-xs bg-green-600",children:"Connected"})]}),e.jsx(vr,{children:"Connect your LinkedIn profile to share content and grow your professional network."})]})]})}),e.jsxs(Oe,{className:"space-y-3",children:[I.length>0&&e.jsx("div",{className:"space-y-2",children:I.map(D=>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(ki,{src:D.profile_picture_url||""}),e.jsx(Ta,{children:e.jsx(kg,{className:"h-4 w-4"})})]}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-sm",children:D.platform_username||"LinkedIn Account"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Connected LinkedIn profile"})]})]}),e.jsxs(Ll,{children:[e.jsx(_f,{asChild:!0,children:e.jsx($,{variant:"ghost",size:"icon",className:"text-destructive hover:text-destructive",children:e.jsx(Pn,{className:"h-4 w-4"})})}),e.jsxs(yl,{children:[e.jsxs(vl,{children:[e.jsx(_l,{children:"Disconnect LinkedIn?"}),e.jsx(wl,{children:"This will remove your LinkedIn connection. You'll need to reconnect to post content."})]}),e.jsxs(bl,{children:[e.jsx(jl,{children:"Cancel"}),e.jsx(fl,{onClick:()=>A.mutate(D.id),className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Disconnect"})]})]})]})]},D.id))}),e.jsxs($,{onClick:N,disabled:u,variant:"outline",className:"gap-2",children:[u?e.jsx(Wi,{className:"h-4 w-4 animate-spin"}):e.jsx(sn,{className:"h-4 w-4"}),"Connect LinkedIn"]})]})]}),e.jsx(Q8n,{}),e.jsx(J8n,{}),e.jsx(eDn,{}),e.jsx(tDn,{}),e.jsx(nDn,{}),e.jsx(oDn,{}),t&&e.jsx(kVt,{})]})})}const dDn="https://chromewebstore.google.com/detail/levelup-companion/lppakdeaencigddecnkcifdcemlfpkkk";function uDn(){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 b=new Uint8Array(await y.slice(0,4).arrayBuffer());return b[0]===80&&b[1]===75&&b[2]===3&&b[3]===4||b[0]===80&&b[1]===75&&b[2]===5&&b[3]===6||b[0]===80&&b[1]===75&&b[2]===7&&b[3]===8},m=y=>{const b=document.createElement("a");b.href=y,b.download="levelup-extension.zip",b.rel="noopener noreferrer",b.target="_blank",document.body.appendChild(b),b.click(),b.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 b=await y.blob();if(!await h(b)){m(`${d}?v=${Date.now()}`);return}const v=new Blob([b],{type:"application/zip"}),N=URL.createObjectURL(v),C=document.createElement("a");C.href=N,C.download="levelup-extension.zip",document.body.appendChild(C),C.click(),C.remove(),setTimeout(()=>URL.revokeObjectURL(N),1e3)}catch(y){ae.error(y.message||"Download failed")}finally{o(!1)}},x=async()=>{r(!0);try{await U.auth.refreshSession();const{data:y}=await U.auth.getSession();if(!y.session){ae.error("Your session has expired. Please sign in again.");return}const{data:b,error:v}=await U.functions.invoke("extension-pair-start",{headers:{Authorization:`Bearer ${y.session.access_token}`}});if(v)throw v;t(b.code),i(b.expires_in||300);const N=setInterval(()=>{i(C=>C<=1?(clearInterval(N),t(null),0):C-1)},1e3)}catch(y){console.error("generateCode error",y),ae.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)}},g=()=>{s&&(navigator.clipboard.writeText(s),ae.success("Copied"))};return e.jsx(Ks,{title:"Browser Extension",children:e.jsxs("div",{className:"container max-w-3xl mx-auto py-8 px-4 space-y-6",children:[e.jsxs(Ul,{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(dR,{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(_e,{className:"p-6 space-y-4 border-2 border-primary/20",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"w-6 h-6 rounded-full bg-primary text-primary-foreground flex items-center justify-center text-xs font-bold",children:"1"}),e.jsx("h2",{className:"text-lg font-semibold",children:"Install from the Chrome Web Store"})]}),e.jsxs("ul",{className:"text-sm text-muted-foreground space-y-1 list-disc list-inside",children:[e.jsx("li",{children:"Quick-add contacts from any webpage with one click or right-click"}),e.jsx("li",{children:"Import listings from Zillow, Realtor.com, and Redfin as drafts"}),e.jsx("li",{children:'"Add to LevelUp" button on Gmail threads and LinkedIn profiles'}),e.jsx("li",{children:"Toolbar launcher with shortcuts to Dashboard, ReelFlow, Card Studio, and more"})]}),e.jsxs($,{size:"lg",className:"w-full",onClick:()=>window.open(dDn,"_blank","noopener,noreferrer"),children:[e.jsx(dR,{className:"w-4 h-4 mr-2"}),"Add to Chrome",e.jsx(Tr,{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(_e,{className:"p-6 space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"w-6 h-6 rounded-full bg-primary text-primary-foreground flex items-center justify-center text-xs font-bold",children:"2"}),e.jsx("h2",{className:"text-lg font-semibold",children:"Pair the extension"})]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Generate a one-time pairing code, then enter it inside the extension popup."}),s?e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"bg-muted rounded-xl p-6 text-center",children:[e.jsx("div",{className:"text-4xl font-mono font-bold tracking-[0.4em] text-primary",children:s}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-3",children:["Expires in ",Math.floor(a/60),":",String(a%60).padStart(2,"0")]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs($,{onClick:g,variant:"outline",className:"flex-1",children:[e.jsx(Ca,{className:"w-4 h-4 mr-2"})," Copy"]}),e.jsxs($,{onClick:x,variant:"outline",className:"flex-1",children:[e.jsx(Wi,{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(oa,{className:"w-4 h-4 mt-0.5 text-primary"}),e.jsx("span",{children:"Click the LevelUp icon in your browser toolbar and paste this code. You only need to do this once per browser."})]})]}):e.jsx($,{onClick:x,disabled:n,size:"lg",className:"w-full",children:n?e.jsxs(e.Fragment,{children:[e.jsx(Wi,{className:"w-4 h-4 mr-2 animate-spin"}),"Generating…"]}):"Generate pairing code"})]}),e.jsxs(_e,{className:"p-6 space-y-4 bg-muted/30 border-dashed",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Tu,{className:"w-5 h-5 text-muted-foreground"}),e.jsx("h2",{className:"text-base font-semibold text-muted-foreground",children:"Manual install (advanced)"})]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"If you prefer to load the extension unpacked, or the Web Store is unavailable, download the ZIP below."}),e.jsxs("ol",{className:"text-sm space-y-2 list-decimal list-inside text-muted-foreground",children:[e.jsx("li",{children:e.jsx($,{variant:"link",className:"h-auto p-0 text-sm",onClick: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 hDn(){const[s]=oc(),t=Vn(),[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"),ae.error("Connection failed: "+(d||c));return}if(!o){r("error"),i("No authorization code received"),ae.error("No authorization code received");return}try{const{data:h,error:m}=await U.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!"),ae.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"),ae.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(_e,{className:"w-full max-w-md",children:[e.jsxs(Bt,{className:"text-center",children:[n==="loading"&&e.jsx(Ht,{className:"h-12 w-12 animate-spin mx-auto text-primary"}),n==="success"&&e.jsx(Ro,{className:"h-12 w-12 mx-auto text-green-500"}),n==="error"&&e.jsx($d,{className:"h-12 w-12 mx-auto text-destructive"}),e.jsxs(Ut,{className:"mt-4",children:[n==="loading"&&"Connecting...",n==="success"&&"Connected!",n==="error"&&"Connection Failed"]}),e.jsx(vr,{children:a})]}),e.jsx(Oe,{className:"flex justify-center",children:n!=="loading"&&e.jsx($,{onClick:()=>t("/mission-control/integrations"),children:n==="success"?"Back to Integrations":"Try Again"})})]})})}function mDn(){const s=Vn();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 pDn(){const[s]=oc(),t=Vn(),[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"),ae.error("Connection failed: "+(u||d));return}if(!c){r("error"),l("No authorization code received"),ae.error("No authorization code received");return}try{const{data:p,error:x}=await U.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(x){let g=x.message||"Failed to connect accounts";try{const y=x.context;if(y&&typeof y.json=="function"){const b=await y.json();b!=null&&b.error&&(g=b.error)}}catch{}throw new Error(g)}if(p!=null&&p.success)r("success"),l(`Successfully connected ${((m=p.accounts)==null?void 0:m.length)||0} account(s)!`),ae.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"),ae.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(_e,{className:"w-full max-w-md",children:[e.jsxs(Bt,{className:"text-center",children:[n==="loading"&&e.jsx(Ht,{className:"h-12 w-12 animate-spin mx-auto text-primary"}),n==="success"&&e.jsx(Ro,{className:"h-12 w-12 mx-auto text-green-500"}),n==="error"&&e.jsx($d,{className:"h-12 w-12 mx-auto text-destructive"}),e.jsxs(Ut,{className:"mt-4",children:[n==="loading"&&"Connecting...",n==="success"&&"Connected!",n==="error"&&"Connection Failed"]}),e.jsx(vr,{children:i})]}),e.jsx(Oe,{className:"flex justify-center",children:n!=="loading"&&e.jsx($,{onClick:()=>t("/mission-control/integrations"),children:n==="success"?"View Integrations":"Try Again"})})]})})}const CVt=new Date().getFullYear(),fDn=Array.from({length:5},(s,t)=>CVt-t);function xDn(){const[s,t]=j.useState(CVt),n=Vn(),{data:r,isLoading:a}=jAs();return a?e.jsx(Ks,{title:"Scorecard Admin",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(on,{className:"h-8 w-64"}),e.jsx("div",{className:"grid grid-cols-4 gap-4",children:[1,2,3,4].map(i=>e.jsx(on,{className:"h-24"},i))}),e.jsx(on,{className:"h-96"})]})}):e.jsx(Ks,{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(vs,{value:String(s),onValueChange:i=>t(Number(i)),children:[e.jsx(gs,{className:"w-[120px]",children:e.jsx(bs,{})}),e.jsx(ys,{children:fDn.map(i=>e.jsx(Ye,{value:String(i),children:i},i))})]})]}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[e.jsx(_e,{children:e.jsxs(Oe,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(qn,{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(_e,{children:e.jsxs(Oe,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(ml,{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(_e,{children:[e.jsxs(Bt,{children:[e.jsx(Ut,{children:"Agents with Scorecards"}),e.jsx(vr,{children:"Click to view individual agent scorecards"})]}),e.jsx(Oe,{children:!r||r.length===0?e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(ml,{className:"h-12 w-12 mx-auto mb-4 opacity-50"}),e.jsx("p",{children:"No agents have added transactions yet"})]}):e.jsxs(Va,{children:[e.jsx(Ha,{children:e.jsxs(hn,{children:[e.jsx(Lt,{children:"Agent"}),e.jsx(Lt,{children:"Email"}),e.jsx(Lt,{className:"text-right",children:"Actions"})]})}),e.jsx(Ga,{children:r.map(i=>e.jsxs(hn,{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($,{variant:"ghost",size:"sm",onClick:()=>n(`/admin/scorecard/${i.id}`),children:[e.jsx(ga,{className:"h-4 w-4 mr-2"}),"View Scorecard"]})})]},i.id))})]})})]})]})})}const AVt=new Date().getFullYear(),gDn=Array.from({length:10},(s,t)=>AVt-t);function Ivt(){var g;const{userId:s}=Vi(),t=Vn(),r=Wd().pathname.startsWith("/mission-control"),[a,i]=j.useState(AVt),{data:l,isLoading:o}=ht({queryKey:["agent-profile",s],queryFn:async()=>{const{data:y,error:b}=await U.from("profiles").select("id, name, email").eq("id",s).single();if(b)throw b;return y},enabled:!!s}),{data:c,isLoading:d}=yGe(a,s),{yearStats:u,lifetimeStats:h,isLoading:m,showCommission:p}=R6t(a,s),{data:x}=D6t(a,s);return o?e.jsx(Ks,{title:"Agent Scorecard",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(on,{className:"h-8 w-64"}),e.jsx("div",{className:"grid grid-cols-4 gap-4",children:[1,2,3,4].map(y=>e.jsx(on,{className:"h-24"},y))})]})}):e.jsx(Ks,{title:`${l==null?void 0:l.name}'s Scorecard`,children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4",children:[e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx($,{variant:"ghost",size:"icon",onClick:()=>t(r?"/mission-control/scorecard":"/admin/scorecard"),children:e.jsx(ka,{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(vs,{value:String(a),onValueChange:y=>i(Number(y)),children:[e.jsx(gs,{className:"w-[120px]",children:e.jsx(bs,{})}),e.jsx(ys,{children:gDn.map(y=>e.jsx(Ye,{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(_e,{children:e.jsxs(Oe,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(sa,{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(_e,{children:e.jsxs(Oe,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(qn,{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(_e,{children:e.jsxs(Oe,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(qd,{className:"h-4 w-4"}),e.jsx("span",{className:"text-xs font-medium",children:"Volume"})]}),e.jsx("p",{className:"text-2xl font-bold",children:Au(u.totalVolume,!0)})]})}),e.jsx(_e,{children:e.jsxs(Oe,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(Il,{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:Au(u.averagePrice,!0)})]})}),e.jsx(_e,{children:e.jsxs(Oe,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(pu,{className:"h-4 w-4"}),e.jsx("span",{className:"text-xs font-medium",children:"Top Source"})]}),e.jsx("p",{className:"text-lg font-bold truncate",children:((g=u.topLeadSource)==null?void 0:g.name)||"-"})]})})]}),x&&e.jsx(Iqt,{goals:x,stats:u,year:a,showCommission:p}),e.jsxs(ua,{defaultValue:"transactions",className:"space-y-4",children:[e.jsxs(ha,{children:[e.jsx(Qt,{value:"transactions",children:"Transactions"}),e.jsx(Qt,{value:"charts",children:"Charts"}),e.jsxs(Qt,{value:"map",children:[e.jsx(ai,{className:"h-4 w-4 mr-1"}),"Map"]})]}),e.jsx(Jt,{value:"transactions",children:e.jsx(rXe,{transactions:c||[],showCommission:p,isLoading:d})}),e.jsx(Jt,{value:"charts",children:e.jsx(aXe,{stats:u,year:a})}),e.jsx(Jt,{value:"map",children:e.jsx(iXe,{transactions:c||[],isLoading:d})})]})]})})}function yDn(){const s=ts(),[t,n]=j.useState(""),[r,a]=j.useState("all"),[i,l]=j.useState(null);zVe();const{data:o,refetch:c}=ht({queryKey:["listing-exchange-flag"],queryFn:async()=>{const{data:I}=await U.from("feature_flags").select("enabled").eq("key","listing_exchange_enabled").single();return(I==null?void 0:I.enabled)??!1}}),{data:d,isLoading:u}=ht({queryKey:["admin-listings"],queryFn:async()=>{const{data:I,error:D}=await U.from("listings").select(` *, agent:profiles!listings_agent_id_fkey(id, name, email), photos:listing_photos(id, photo_url, is_primary) `).order("created_at",{ascending:!1});if(D)throw D;return I}}),{data:h}=ht({queryKey:["admin-listing-stats"],queryFn:async()=>{const{data:I}=await U.from("listings").select("id, is_approved, status"),{data:D}=await U.from("listing_shares").select("id"),{data:B}=await U.from("listing_views").select("id"),{count:q}=await U.from("listing_leads").select("id",{count:"exact",head:!0}),W=new Date(Date.now()-7*24*60*60*1e3).toISOString(),{count:V}=await U.from("listing_leads").select("id",{count:"exact",head:!0}).gte("created_at",W);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:(D==null?void 0:D.length)||0,totalViews:(B==null?void 0:B.length)||0,totalLeads:q||0,leadsLast7:V||0}}}),{data:m}=ht({queryKey:["admin-listing-lead-counts"],queryFn:async()=>{const I={};let D=0;const B=1e3;for(;;){const{data:q,error:W}=await U.from("listing_leads").select("listing_id").range(D,D+B-1);if(W)throw W;if(!q||q.length===0)break;for(const V of q)V.listing_id&&(I[V.listing_id]=(I[V.listing_id]||0)+1);if(q.length{const{data:I,error:D}=await U.from("listing_leads").select("*").eq("listing_id",i.listingId).order("created_at",{ascending:!1});if(D)throw D;return I}}),g=async(I,D,B="submit_url")=>{try{const{data:{session:q}}=await U.auth.getSession();if(!q)return;const{data:W,error:V}=await U.functions.invoke("google-indexing",{body:{action:B,listing_id:I,listing_slug:D}});if(V)throw V;if((W==null?void 0:W.configured)===!1)return;W!=null&&W.success&&ae.success("Submitted to Google for indexing")}catch(q){console.error("Google indexing submission failed:",q)}},y=yt({mutationFn:async()=>{const{data:{session:I}}=await U.auth.getSession();if(!I)throw new Error("Not authenticated");const{data:D,error:B}=await U.functions.invoke("google-indexing",{body:{action:"submit_all"}});if(B)throw B;return D},onSuccess:I=>{if((I==null?void 0:I.configured)===!1){ae.error("Google Indexing API not configured. Add the GOOGLE_INDEXING_SERVICE_ACCOUNT secret.");return}ae.success(`Submitted ${(I==null?void 0:I.succeeded)||0} URLs to Google (${(I==null?void 0:I.failed)||0} failed)`)},onError:I=>{ae.error("Failed to submit to Google"),console.error(I)}}),b=yt({mutationFn:async({id:I,approved:D,slug:B})=>{const{error:q}=await U.from("listings").update({is_approved:D}).eq("id",I);if(q)throw q;return{id:I,approved:D,slug:B}},onSuccess:I=>{s.invalidateQueries({queryKey:["admin-listings"]}),s.invalidateQueries({queryKey:["admin-listing-stats"]}),ae.success(I.approved?"Listing approved":"Listing unapproved"),I.approved?g(I.id,I.slug||null,"submit_url"):g(I.id,I.slug||null,"remove_url")}}),v=yt({mutationFn:async({id:I,featured:D})=>{const{error:B}=await U.from("listings").update({is_featured:D}).eq("id",I);if(B)throw B},onSuccess:(I,{featured:D})=>{s.invalidateQueries({queryKey:["admin-listings"]}),ae.success(D?"Listing featured":"Listing unfeatured")}}),N=yt({mutationFn:async I=>{const{error:D}=await U.from("listings").delete().eq("id",I);if(D)throw D},onSuccess:()=>{s.invalidateQueries({queryKey:["admin-listings"]}),s.invalidateQueries({queryKey:["admin-listing-stats"]}),ae.success("Listing deleted")}}),C=yt({mutationFn:async I=>{const{error:D}=await U.from("feature_flags").update({enabled:I}).eq("key","listing_exchange_enabled");if(D)throw D},onSuccess:()=>{c(),ae.success("Feature flag updated")}}),A=o??!1,T=d==null?void 0:d.filter(I=>{var q,W,V,K;const D=((q=I.city)==null?void 0:q.toLowerCase().includes(t.toLowerCase()))||((V=(W=I.agent)==null?void 0:W.name)==null?void 0:V.toLowerCase().includes(t.toLowerCase()))||((K=I.property_address)==null?void 0:K.toLowerCase().includes(t.toLowerCase())),B=r==="all"||r==="pending"&&!I.is_approved||r==="approved"&&I.is_approved;return D&&B}),P=I=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(I),M=I=>{const D={active:"bg-green-500/10 text-green-600 border-green-200",coming_soon:"bg-blue-500/10 text-blue-600 border-blue-200",price_improvement:"bg-amber-500/10 text-amber-600 border-amber-200",under_contract:"bg-purple-500/10 text-purple-600 border-purple-200",sold:"bg-gray-500/10 text-gray-600 border-gray-200"};return D[I]||D.active};return e.jsxs(Ks,{title:"Listing Exchange Admin",children:[e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold",children:"Listing Exchange"}),e.jsx("p",{className:"text-muted-foreground",children:"Manage community listings"})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs($,{variant:"outline",size:"sm",onClick:()=>y.mutate(),disabled:y.isPending,className:"gap-2",children:[y.isPending?e.jsx(Ht,{className:"h-4 w-4 animate-spin"}):e.jsx(Gl,{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(Tn,{checked:A,onCheckedChange:I=>C.mutate(I)})]})]}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-6 gap-4",children:[e.jsx(_e,{children:e.jsxs(Oe,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ai,{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(_e,{children:e.jsxs(Oe,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Il,{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(_e,{children:e.jsxs(Oe,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(qn,{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(_e,{children:e.jsxs(Oe,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ga,{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(_e,{children:e.jsxs(Oe,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(vd,{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(_e,{children:e.jsxs(Oe,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(il,{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(_e,{children:e.jsx(Oe,{className:"p-4",children:e.jsxs("div",{className:"flex flex-col sm:flex-row gap-4",children:[e.jsxs("div",{className:"relative flex-1",children:[e.jsx(Vr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(be,{placeholder:"Search by city, address, or agent...",value:t,onChange:I=>n(I.target.value),className:"pl-9"})]}),e.jsx(ua,{value:r,onValueChange:I=>a(I),children:e.jsxs(ha,{children:[e.jsx(Qt,{value:"all",children:"All"}),e.jsx(Qt,{value:"pending",children:"Pending"}),e.jsx(Qt,{value:"approved",children:"Approved"})]})})]})})}),e.jsxs(_e,{children:[e.jsx(Bt,{children:e.jsxs(Ut,{children:["Listings (",(T==null?void 0:T.length)||0,")"]})}),e.jsx(Oe,{children:e.jsx("div",{className:"overflow-x-auto",children:e.jsxs(Va,{children:[e.jsx(Ha,{children:e.jsxs(hn,{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(Ga,{children:u?e.jsx(hn,{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(hn,{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 D,B,q,W,V;return e.jsxs(hn,{children:[e.jsx(gt,{children:e.jsxs("div",{className:"flex items-center gap-3",children:[(B=(D=I.photos)==null?void 0:D[0])!=null&&B.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(Ai,{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:(q=I.property_type)==null?void 0:q.replace("_"," ")})]})]})}),e.jsx(gt,{children:e.jsx("p",{className:"text-sm",children:((W=I.agent)==null?void 0:W.name)||"Unknown"})}),e.jsx(gt,{className:"font-medium",children:P(I.price)}),e.jsx(gt,{children:e.jsx($e,{variant:"outline",className:M(I.status),children:(V=I.status)==null?void 0:V.replace("_"," ")})}),e.jsx(gt,{className:"text-center",children:e.jsx(Tn,{checked:I.is_approved??!1,onCheckedChange:K=>b.mutate({id:I.id,approved:K,slug:I.slug})})}),e.jsx(gt,{className:"text-center",children:e.jsx(Tn,{checked:I.is_featured??!1,onCheckedChange:K=>v.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($,{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:Hs(new Date(I.created_at),"MMM d, yyyy")}),e.jsx(gt,{children:e.jsxs(Hd,{children:[e.jsx(Gd,{asChild:!0,children:e.jsx($,{variant:"ghost",size:"icon",children:e.jsx(p0,{className:"h-4 w-4"})})}),e.jsxs(Md,{align:"end",children:[e.jsxs(Na,{onClick:()=>window.open(`/mission-control/listings/${I.id}`,"_blank"),children:[e.jsx(ga,{className:"h-4 w-4 mr-2"}),"View Listing"]}),e.jsxs(Na,{onClick:()=>v.mutate({id:I.id,featured:!I.is_featured}),children:[e.jsx(Qa,{className:"h-4 w-4 mr-2"}),I.is_featured?"Unfeature":"Feature"]}),e.jsxs(Na,{className:"text-destructive",onClick:async()=>{await Yi("Are you sure you want to delete this listing?")&&N.mutate(I.id)},children:[e.jsx(pr,{className:"h-4 w-4 mr-2"}),"Delete"]})]})]})})]},I.id)})})]})})})]})]}),e.jsx(Os,{open:!!i,onOpenChange:I=>!I&&l(null),children:e.jsxs(Rs,{className:"max-w-3xl max-h-[80vh] overflow-y-auto",children:[e.jsxs(Us,{children:[e.jsx(zs,{children:"Leads from listing"}),e.jsx(Sr,{children:i==null?void 0:i.label})]}),x?e.jsxs("div",{className:"py-8 text-center text-muted-foreground",children:[e.jsx(Ht,{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(Va,{children:[e.jsx(Ha,{children:e.jsxs(hn,{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(Ga,{children:p.map(I=>{var D;return e.jsxs(hn,{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($e,{variant:"outline",children:(D=I.lead_type)==null?void 0:D.replace("_"," ")})}),e.jsx(gt,{className:"text-sm text-muted-foreground",children:Hs(new Date(I.created_at),"MMM d, yyyy h:mm a")})]},I.id)})})]})]})})]})}function vDn(s){return s?new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(s):"—"}function bDn(){const[s,t]=j.useState(""),[n,r]=j.useState("all"),[a,i]=j.useState("all"),{data:l,isLoading:o}=ht({queryKey:["admin-all-listing-leads"],queryFn:async()=>{const h=[];let m=0;const p=1e3;for(;;){const{data:x,error:g}=await U.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(g)throw g;if(!x||x.length===0||(h.push(...x),x.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 g,y,b,v,N,C;return h&&new Date(p.created_at).getTime(){const h=c.length,m=c.filter(g=>g.lead_type==="showing_request").length,p=new Set(c.map(g=>g.agent_id)).size,x=new Set(c.map(g=>g.listing_id)).size;return{total:h,showings:m,uniqueAgents:p,uniqueListings:x}},[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 b,v,N,C,A,T;return[Hs(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||""}`:"",((b=y.listing)==null?void 0:b.property_address)||"",((v=y.listing)==null?void 0:v.city)||"",(N=y.listing)!=null&&N.price?String(y.listing.price):"",((C=y.agent)==null?void 0:C.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(b=>`"${String(b).replace(/"/g,'""')}"`).join(",")).join(` `),p=new Blob([m],{type:"text/csv"}),x=URL.createObjectURL(p),g=document.createElement("a");g.href=x,g.download=`listing-leads-${Hs(new Date,"yyyy-MM-dd")}.csv`,g.click(),URL.revokeObjectURL(x)};return e.jsx(Ks,{title:"Listing Leads",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold",children:"Listing Leads"}),e.jsx("p",{className:"text-muted-foreground",children:"All leads submitted through the public listings site"})]}),e.jsxs($,{variant:"outline",onClick:u,disabled:!c.length,className:"gap-2",children:[e.jsx(di,{className:"h-4 w-4"}),"Export CSV"]})]}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[e.jsx(_e,{children:e.jsxs(Oe,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(il,{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(_e,{children:e.jsxs(Oe,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ia,{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(_e,{children:e.jsxs(Oe,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(sa,{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(_e,{children:e.jsxs(Oe,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(il,{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(_e,{children:e.jsx(Oe,{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(Vr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(be,{placeholder:"Search name, email, property, agent...",value:s,onChange:h=>t(h.target.value),className:"pl-9"})]}),e.jsxs(vs,{value:a,onValueChange:h=>i(h),children:[e.jsx(gs,{className:"w-full sm:w-48",children:e.jsx(bs,{})}),e.jsxs(ys,{children:[e.jsx(Ye,{value:"all",children:"All Types"}),e.jsx(Ye,{value:"info_request",children:"Info Request"}),e.jsx(Ye,{value:"showing_request",children:"Showing Request"})]})]}),e.jsxs(vs,{value:n,onValueChange:h=>r(h),children:[e.jsx(gs,{className:"w-full sm:w-40",children:e.jsx(bs,{})}),e.jsxs(ys,{children:[e.jsx(Ye,{value:"all",children:"All Time"}),e.jsx(Ye,{value:"7",children:"Last 7 days"}),e.jsx(Ye,{value:"30",children:"Last 30 days"}),e.jsx(Ye,{value:"90",children:"Last 90 days"})]})]})]})})}),e.jsxs(_e,{children:[e.jsx(Bt,{children:e.jsxs(Ut,{children:["Leads (",c.length,")"]})}),e.jsx(Oe,{children:e.jsx("div",{className:"overflow-x-auto",children:e.jsxs(Va,{children:[e.jsx(Ha,{children:e.jsxs(hn,{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(Ga,{children:o?e.jsx(hn,{children:e.jsx(gt,{colSpan:8,className:"text-center py-8 text-muted-foreground",children:"Loading..."})}):c.length===0?e.jsx(hn,{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(hn,{children:[e.jsxs(gt,{className:"whitespace-nowrap text-sm",children:[Hs(new Date(h.created_at),"MMM d, yyyy"),e.jsx("div",{className:"text-xs text-muted-foreground",children:Hs(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(nn,{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(ya,{className:"h-3 w-3"}),h.phone]})]})}),e.jsx(gt,{children:h.listing?e.jsxs(Wn,{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(Tr,{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(", ")," · ",vDn(h.listing.price)]})]}):e.jsx("span",{className:"text-muted-foreground text-sm",children:"—"})}),e.jsxs(gt,{children:[e.jsx($e,{variant:h.lead_type==="showing_request"?"default":"secondary",className:"text-xs",children:h.lead_type==="showing_request"?"Showing":"Info"}),h.preferred_date&&e.jsxs("div",{className:"text-xs text-muted-foreground mt-1",children:[h.preferred_date," ",h.preferred_time||""]}),h.showing_mode&&e.jsx("div",{className:"text-xs text-muted-foreground capitalize",children:h.showing_mode.replace("_"," ")})]}),e.jsxs(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(Ji,{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 G7={new_listing_alerts:{label:"New Listing Alerts",icon:Dx,color:"bg-amber-100 text-amber-800"},exit_intent:{label:"Exit Intent",icon:vR,color:"bg-rose-100 text-rose-800"},saved_listing:{label:"Saved Home",icon:fo,color:"bg-pink-100 text-pink-800"},saved_search:{label:"Saved Search",icon:Vr,color:"bg-blue-100 text-blue-800"},buyer_guide:{label:"Buyer's Guide",icon:wf,color:"bg-emerald-100 text-emerald-800"}},Dvt=[{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 Rvt(s){return new Date(s).toLocaleString("en-US",{timeZone:"America/New_York",month:"short",day:"numeric",year:"numeric",hour:"numeric",minute:"2-digit"})}function _Dn(){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 x=U.from("public_site_leads").select("*").order("created_at",{ascending:!1}).limit(2e3);const g=Dvt.find(v=>v.key===a);if(g&&g.days>0){const v=new Date(Date.now()-g.days*864e5).toISOString();x=x.gte("created_at",v)}const{data:y,error:b}=await x;p||(b?(console.error(b),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 x=c.toLowerCase();if(![p.email,p.first_name,p.last_name,p.phone,p.source_page,p.referrer].filter(Boolean).join(" ").toLowerCase().includes(x))return!1}return!0}),[s,l,c]),h=j.useMemo(()=>{const p=u.length,x=new Set(u.map(y=>y.email.toLowerCase())).size,g={};return u.forEach(y=>{g[y.lead_type]=(g[y.lead_type]||0)+1}),{total:p,uniqueEmails:x,byType:g}},[u]),m=()=>{const x=[["Date (ET)","Type","Email","First","Last","Phone","Listing ID","Source Page","Referrer","Criteria"].join(",")];u.forEach(v=>{var C;const N=[Rvt(v.created_at),((C=G7[v.lead_type])==null?void 0:C.label)||v.lead_type,v.email,v.first_name||"",v.last_name||"",v.phone||"",v.listing_id||"",v.source_page||"",v.referrer||"",v.criteria?JSON.stringify(v.criteria):""].map(A=>`"${String(A).replace(/"/g,'""')}"`);x.push(N.join(","))});const g=new Blob([x.join(` `)],{type:"text/csv"}),y=URL.createObjectURL(g),b=document.createElement("a");b.href=y,b.download=`public-site-leads-${new Date().toISOString().slice(0,10)}.csv`,b.click(),URL.revokeObjectURL(y)};return e.jsxs("div",{className:"min-h-screen bg-slate-50",children:[e.jsx(Ul,{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(Wn,{to:"/admin",children:e.jsxs($,{variant:"ghost",size:"sm",children:[e.jsx(ka,{className:"h-4 w-4 mr-1"}),"Admin"]})}),e.jsxs("div",{children:[e.jsx("h1",{className:"text-lg font-semibold",children:"Public Site Leads"}),e.jsx("p",{className:"text-xs text-slate-500",children:"listings.relevelup.com — alerts, exit intent & saved homes"})]})]}),e.jsxs($,{onClick:m,variant:"outline",size:"sm",children:[e.jsx(di,{className:"h-4 w-4 mr-1"})," Export CSV"]})]})}),e.jsxs("div",{className:"max-w-7xl mx-auto px-6 py-6 space-y-6",children:[e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-5 gap-3",children:[e.jsx(_e,{children:e.jsxs(Oe,{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(G7).map(p=>{const x=G7[p],g=x.icon;return e.jsx(_e,{children:e.jsxs(Oe,{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(g,{className:"h-3.5 w-3.5"}),x.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(vs,{value:a,onValueChange:p=>i(p),children:[e.jsx(gs,{className:"w-[160px] bg-white",children:e.jsx(bs,{})}),e.jsx(ys,{children:Dvt.map(p=>e.jsx(Ye,{value:p.key,children:p.label},p.key))})]}),e.jsxs(vs,{value:l,onValueChange:o,children:[e.jsx(gs,{className:"w-[200px] bg-white",children:e.jsx(bs,{})}),e.jsxs(ys,{children:[e.jsx(Ye,{value:"all",children:"All lead types"}),Object.keys(G7).map(p=>e.jsx(Ye,{value:p,children:G7[p].label},p))]})]}),e.jsxs("div",{className:"relative flex-1 min-w-[200px] max-w-md",children:[e.jsx(Vr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-slate-400"}),e.jsx(be,{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(_e,{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 x=G7[p.lead_type],g=x==null?void 0:x.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:Rvt(p.created_at)}),e.jsx("td",{className:"px-4 py-3 whitespace-nowrap",children:e.jsxs($e,{className:`${(x==null?void 0:x.color)||""} font-normal`,variant:"secondary",children:[g?e.jsx(g,{className:"h-3 w-3 mr-1"}):null,(x==null?void 0:x.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(nn,{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(ya,{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(([b,v])=>`${b}: ${v}`).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(Tr,{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 wDn=()=>{var h,m;const[s,t]=j.useState(""),[n,r]=j.useState(null),{data:a,isLoading:i}=ht({queryKey:["membership-reviews"],queryFn:async()=>{const{data:p,error:x}=await U.from("membership_reviews").select("*").order("created_at",{ascending:!1});if(x)throw x;const g=(p==null?void 0:p.map(v=>v.user_id))||[],{data:y}=await U.from("profiles").select("id, name, email").in("id",g);return p==null?void 0:p.map(v=>({...v,profiles:(y==null?void 0:y.find(N=>N.id===v.user_id))||null}))}}),l=a==null?void 0:a.filter(p=>{var g,y,b,v,N;const x=s.toLowerCase();return((y=(g=p.profiles)==null?void 0:g.name)==null?void 0:y.toLowerCase().includes(x))||((v=(b=p.profiles)==null?void 0:b.email)==null?void 0:v.toLowerCase().includes(x))||((N=p.review_text)==null?void 0:N.toLowerCase().includes(x))}),o=a!=null&&a.length?(a.reduce((p,x)=>p+x.rating,0)/a.length).toFixed(1):"0.0",c=a==null?void 0:a.reduce((p,x)=>(p[x.rating]=(p[x.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(x=>e.jsx(Qa,{className:Tt("h-4 w-4",p>=x?"fill-yellow-400 text-yellow-400":"text-muted-foreground")},x))});return e.jsx(Ks,{children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(hh,{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(_e,{children:e.jsxs(Bt,{className:"pb-2",children:[e.jsx(vr,{children:"Total Reviews"}),e.jsx(Ut,{className:"text-3xl",children:(a==null?void 0:a.length)||0})]})}),e.jsx(_e,{children:e.jsxs(Bt,{className:"pb-2",children:[e.jsx(vr,{children:"Average Rating"}),e.jsxs(Ut,{className:"flex items-center gap-2 text-3xl",children:[o,e.jsx(Qa,{className:"h-6 w-6 fill-yellow-400 text-yellow-400"})]})]})}),e.jsx(_e,{children:e.jsxs(Bt,{className:"pb-2",children:[e.jsx(vr,{children:"5-Star Reviews"}),e.jsx(Ut,{className:"text-3xl",children:(c==null?void 0:c[5])||0})]})}),e.jsx(_e,{children:e.jsxs(Bt,{className:"pb-2",children:[e.jsx(vr,{children:"Posted to Google"}),e.jsxs(Ut,{className:"flex items-center gap-2 text-3xl",children:[d,e.jsx(Tr,{className:"h-5 w-5 text-muted-foreground"})]})]})})]}),e.jsxs("div",{className:"relative max-w-sm",children:[e.jsx(Vr,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),e.jsx(be,{placeholder:"Search by name, email, or review...",value:s,onChange:p=>t(p.target.value),className:"pl-9"})]}),e.jsx(_e,{children:e.jsx(Oe,{className:"p-0",children:e.jsxs(Va,{children:[e.jsx(Ha,{children:e.jsxs(hn,{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(Ga,{children:i?e.jsx(hn,{children:e.jsx(gt,{colSpan:5,className:"text-center py-8",children:"Loading reviews..."})}):(l==null?void 0:l.length)===0?e.jsx(hn,{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 x,g;return e.jsxs(hn,{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:((x=p.profiles)==null?void 0:x.name)||"Unknown"}),e.jsx("div",{className:"text-sm text-muted-foreground",children:(g=p.profiles)==null?void 0:g.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($e,{variant:"secondary",className:"bg-green-100 text-green-800",children:"Posted"}):e.jsx($e,{variant:"outline",children:"No"})}),e.jsx(gt,{className:"text-sm text-muted-foreground",children:Hs(new Date(p.created_at),"MMM d, yyyy")})]},p.id)})})]})})}),e.jsx(Os,{open:!!n,onOpenChange:()=>r(null),children:e.jsxs(Rs,{className:"max-w-lg",children:[e.jsx(Us,{children:e.jsx(zs,{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(nn,{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(ia,{className:"h-4 w-4"}),Hs(new Date(n.created_at),"MMMM d, yyyy 'at' h:mm a")]}),n.posted_to_google?e.jsxs($e,{variant:"secondary",className:"bg-green-100 text-green-800",children:[e.jsx(Tr,{className:"h-3 w-3 mr-1"}),"Posted to Google"]}):e.jsx($e,{variant:"outline",children:"Not posted to Google"})]})]})]})})]})})},Ovt={agent_card:"Agent Card",listing:"Listing",lead_site:"Lead Site",guest_book:"Guest Book",landing_page:"Landing Page",connect_page:"Connect Page",booking:"Booking"},jDn={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 NDn(){const[s,t]=j.useState(""),[n,r]=j.useState("all"),[a,i]=j.useState("all"),[l,o]=j.useState("7"),{data:c,isLoading:d}=ht({queryKey:["lead-notification-log",l],queryFn:async()=>{const m=new Date(Date.now()-Number(l)*864e5).toISOString(),{data:p,error:x}=await U.from("lead_notification_log").select("*").gte("created_at",m).order("created_at",{ascending:!1}).limit(2e3);if(x)throw x;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(x=>(x||"").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,x=u.filter(y=>y.status==="failed").length,g=new Set(u.map(y=>y.agent_user_id).filter(Boolean)).size;return{total:m,sent:p,failed:x,agents:g}},[u]);return e.jsx(Ks,{children:e.jsxs("div",{className:"container mx-auto py-6 space-y-6",children:[e.jsx(hh,{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(_e,{children:e.jsxs(Oe,{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(_e,{children:e.jsxs(Oe,{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(_e,{children:e.jsxs(Oe,{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(_e,{children:e.jsxs(Oe,{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(Vr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(be,{placeholder:"Search agent or lead name, email, phone…",value:s,onChange:m=>t(m.target.value),className:"pl-9"})]}),e.jsxs(vs,{value:n,onValueChange:r,children:[e.jsx(gs,{className:"w-full md:w-48",children:e.jsx(bs,{placeholder:"Source"})}),e.jsxs(ys,{children:[e.jsx(Ye,{value:"all",children:"All Sources"}),Object.entries(Ovt).map(([m,p])=>e.jsx(Ye,{value:m,children:p},m))]})]}),e.jsxs(vs,{value:a,onValueChange:i,children:[e.jsx(gs,{className:"w-full md:w-40",children:e.jsx(bs,{placeholder:"Status"})}),e.jsxs(ys,{children:[e.jsx(Ye,{value:"all",children:"All Statuses"}),e.jsx(Ye,{value:"sent",children:"Sent"}),e.jsx(Ye,{value:"backfilled",children:"Backfilled"}),e.jsx(Ye,{value:"failed",children:"Failed"})]})]}),e.jsxs(vs,{value:l,onValueChange:o,children:[e.jsx(gs,{className:"w-full md:w-36",children:e.jsx(bs,{})}),e.jsxs(ys,{children:[e.jsx(Ye,{value:"1",children:"Last 24h"}),e.jsx(Ye,{value:"7",children:"Last 7 days"}),e.jsx(Ye,{value:"14",children:"Last 14 days"}),e.jsx(Ye,{value:"30",children:"Last 30 days"})]})]})]}),e.jsx(_e,{children:e.jsx(Oe,{className:"p-0",children:e.jsxs(Va,{children:[e.jsx(Ha,{children:e.jsxs(hn,{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(Ga,{children:d?e.jsx(hn,{children:e.jsx(gt,{colSpan:5,className:"text-center py-8 text-muted-foreground",children:"Loading…"})}):u.length===0?e.jsx(hn,{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(hn,{children:[e.jsx(gt,{className:"whitespace-nowrap text-sm",children:Hs(new Date(m.created_at),"MMM d, yyyy h:mm a")}),e.jsx(gt,{children:e.jsx($e,{variant:"secondary",children:Ovt[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(nn,{className:"h-3 w-3"}),m.lead_email]}),m.lead_phone&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(ya,{className:"h-3 w-3"}),m.lead_phone]})]})]}),e.jsxs(gt,{children:[e.jsx($e,{className:jDn[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 kDn=[{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"}],SDn=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 CDn(){const s=ts(),{user:t}=_s(),[n,r]=j.useState(!1),[a,i]=j.useState(!1),[l,o]=j.useState(!1),{data:c,isLoading:d}=ht({queryKey:["weekly-digest-settings"],queryFn:async()=>{const{data:M,error:I}=await U.from("weekly_digest_settings").select("*").single();if(I)throw I;return M}}),{data:u,isLoading:h}=ht({queryKey:["weekly-digest-logs"],queryFn:async()=>{const{data:M,error:I}=await U.from("weekly_digest_logs").select("*").order("sent_at",{ascending:!1}).limit(100);if(I)throw I;return M}}),{data:m}=ht({queryKey:["digest-subscriber-count"],queryFn:async()=>{const{count:M,error:I}=await U.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:x}=ht({queryKey:["digest-queue-status"],queryFn:async()=>{const M=new Date;M.setUTCHours(0,0,0,0);const[I,D,B,q]=await Promise.all([U.from("weekly_digest_send_queue").select("id",{count:"exact",head:!0}).eq("status","pending").gte("created_at",M.toISOString()),U.from("weekly_digest_send_queue").select("id",{count:"exact",head:!0}).eq("status","processing").gte("created_at",M.toISOString()),U.from("weekly_digest_send_queue").select("id",{count:"exact",head:!0}).eq("status","sent").gte("created_at",M.toISOString()),U.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:D.count||0,sent:B.count||0,failed:q.count||0,total:(I.count||0)+(D.count||0)+(B.count||0)+(q.count||0)}},refetchInterval:5e3});j.useEffect(()=>{if(p&&(p.pending>0||p.processing>0)){const M=setInterval(()=>{x(),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,x,s]);const{data:g=0}=ht({queryKey:["digest-today-failed-count"],queryFn:async()=>{const M=new Date;M.setUTCHours(0,0,0,0);const{count:I,error:D}=await U.from("weekly_digest_logs").select("id",{count:"exact",head:!0}).eq("delivery_status","failed").gte("sent_at",M.toISOString());if(D)throw D;return I||0}}),y=yt({mutationFn:async M=>{const{error:I}=await U.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"]}),ae.success("Settings updated")},onError:M=>{ae.error("Failed to update settings: "+M.message)}}),b=async()=>{r(!0);try{const{data:M,error:I}=await U.functions.invoke("send-weekly-digest",{body:{manual:!0}});if(I)throw I;M.queued?ae.success(`${M.queued.toLocaleString()} emails queued! They'll be sent automatically (~80/minute).`):M.sent!==void 0&&ae.success(`Digest sent! ${M.sent} emails delivered, ${M.failed} failed`),x(),s.invalidateQueries({queryKey:["weekly-digest-logs"]})}catch(M){ae.error("Failed to send digest: "+M.message)}finally{r(!1)}},v=async()=>{var M,I,D,B,q,W;if(!(t!=null&&t.email)){ae.error("No email found for your account");return}i(!0);try{const{data:V,error:K}=await U.functions.invoke("send-weekly-digest",{body:{preview:!0,previewEmail:t.email}});if(K)throw K;const Q=V==null?void 0:V.resendId,J=V==null?void 0:V.resendDetails,ce=J==null?void 0:J.status,ue=((M=J==null?void 0:J.body)==null?void 0:M.status)||((D=(I=J==null?void 0:J.body)==null?void 0:I.data)==null?void 0:D.status),ne=((q=(B=J==null?void 0:J.body)==null?void 0:B.error)==null?void 0:q.message)||((W=J==null?void 0:J.body)==null?void 0:W.message);ae.success(Q?`Preview accepted by email provider (id: ${Q})${ce?`, status check: ${ce}`:""}${ue?`, provider: ${ue}`:""}${ne?` (${ne})`:""}. Check spam/promotions—delivery can take a few minutes.`:"Preview accepted by email provider. Check spam/promotions—delivery can take a few minutes.")}catch(V){ae.error("Failed to send preview: "+V.message)}finally{i(!1)}},N=async()=>{o(!0);try{const{data:M,error:I}=await U.functions.invoke("send-weekly-digest",{body:{retryFailed:!0}});if(I)throw I;M.queued===0||M.sent===0&&M.failed===0&&!M.queued?ae.info("No failed emails to retry"):M.queued?ae.success(`${M.queued} emails queued for retry!`):ae.success(`Retry complete! ${M.sent} emails delivered, ${M.failed} failed`),x(),s.invalidateQueries({queryKey:["weekly-digest-logs"]}),s.invalidateQueries({queryKey:["digest-today-failed-count"]}),s.invalidateQueries({queryKey:["digest-today-missing-count"]})}catch(M){ae.error("Failed to retry: "+M.message)}finally{o(!1)}},C=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}=ht({queryKey:["digest-delivery-stats"],queryFn:async()=>{var W,V;const M=new Date;M.setUTCHours(0,0,0,0);const[I,D,B,q]=await Promise.all([U.from("weekly_digest_logs").select("id",{count:"exact",head:!0}).eq("delivery_status","sent").gte("sent_at",M.toISOString()),U.from("weekly_digest_logs").select("id",{count:"exact",head:!0}).eq("delivery_status","failed").gte("sent_at",M.toISOString()),U.from("weekly_digest_logs").select("id",{count:"exact",head:!0}).eq("has_agent_os_activity",!0).gte("sent_at",M.toISOString()),U.from("weekly_digest_logs").select("sent_at").order("sent_at",{ascending:!1}).limit(1)]);return{totalSent:I.count||0,totalFailed:D.count||0,agentOsEngaged:B.count||0,lastSent:((V=(W=q.data)==null?void 0:W[0])==null?void 0:V.sent_at)||null}},refetchInterval:A?5e3:!1}),P={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(Ks,{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(Ks,{title:"Weekly Digest",description:"Configure and manage automated weekly email digests for members",children:e.jsxs(ua,{defaultValue:"settings",className:"space-y-6",children:[e.jsxs(ha,{children:[e.jsxs(Qt,{value:"settings",className:"flex items-center gap-2",children:[e.jsx(pc,{className:"h-4 w-4"}),"Settings"]}),e.jsxs(Qt,{value:"stats",className:"flex items-center gap-2",children:[e.jsx(ml,{className:"h-4 w-4"}),"Delivery Stats"]})]}),e.jsxs(Jt,{value:"settings",className:"space-y-6",children:[A&&p&&e.jsx(_e,{className:"border-primary/50 bg-primary/5",children:e.jsxs(Oe,{className:"pt-6",children:[e.jsxs("div",{className:"flex items-center gap-4 mb-4",children:[e.jsx(Ht,{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:[C,"%"]})]}),e.jsx(Ki,{value:C,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(_e,{children:e.jsx(Oe,{className:"pt-6",children:e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx("div",{className:"p-3 rounded-full bg-primary/10",children:e.jsx(qn,{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(_e,{children:e.jsx(Oe,{className:"pt-6",children:e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx("div",{className:"p-3 rounded-full bg-emerald-500/10",children:e.jsx(Fr,{className:"h-5 w-5 text-emerald-500"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-bold",children:P.totalSent}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Delivered"})]})]})})}),e.jsx(_e,{children:e.jsx(Oe,{className:"pt-6",children:e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx("div",{className:"p-3 rounded-full bg-destructive/10",children:e.jsx($d,{className:"h-5 w-5 text-destructive"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-bold",children:P.totalFailed}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Failed"})]})]})})}),e.jsx(_e,{children:e.jsx(Oe,{className:"pt-6",children:e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx("div",{className:"p-3 rounded-full bg-primary/10",children:e.jsx(Hr,{className:"h-5 w-5 text-primary"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-bold",children:P.lastSent?Hs(new Date(P.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(_e,{children:[e.jsxs(Bt,{children:[e.jsxs(Ut,{className:"flex items-center gap-2",children:[e.jsx(Hr,{className:"h-5 w-5"}),"Schedule"]}),e.jsx(vr,{children:"Configure when the digest is sent"})]}),e.jsxs(Oe,{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(se,{children:"Enable Weekly Digest"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Send automated weekly emails to members"})]}),e.jsx(Tn,{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(se,{children:"Cron Frequency"}),e.jsxs(vs,{value:(c==null?void 0:c.cron_frequency)||"daily",onValueChange:M=>y.mutate({cron_frequency:M}),children:[e.jsx(gs,{children:e.jsx(bs,{})}),e.jsxs(ys,{children:[e.jsx(Ye,{value:"daily",children:"Daily (runs once at selected time)"}),e.jsx(Ye,{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(se,{children:"Day of Week"}),e.jsxs(vs,{value:String(c==null?void 0:c.send_day),onValueChange:M=>y.mutate({send_day:parseInt(M)}),children:[e.jsx(gs,{children:e.jsx(bs,{})}),e.jsx(ys,{children:kDn.map(M=>e.jsx(Ye,{value:M.value,children:M.label},M.value))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Time (UTC)"}),e.jsxs(vs,{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(gs,{children:e.jsx(bs,{})}),e.jsx(ys,{children:SDn.map(M=>e.jsx(Ye,{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($,{onClick:v,disabled:a,variant:"outline",className:"flex-1",children:[e.jsx(ga,{className:"h-4 w-4 mr-2"}),a?"Sending...":"Send Preview to Me"]}),e.jsxs($,{onClick:b,disabled:n,className:"flex-1",children:[e.jsx(Br,{className:"h-4 w-4 mr-2"}),n?"Sending...":"Send to All"]})]}),g>0&&e.jsxs($,{onClick:N,disabled:l,variant:"outline",className:"w-full",children:[e.jsx(Wi,{className:`h-4 w-4 mr-2 ${l?"animate-spin":""}`}),l?"Retrying...":`Retry ${g} Failed`]})]})]})]}),e.jsxs(_e,{children:[e.jsxs(Bt,{children:[e.jsxs(Ut,{className:"flex items-center gap-2",children:[e.jsx(Wr,{className:"h-5 w-5"}),"Content Sections"]}),e.jsx(vr,{children:"Choose what to include in the digest"})]}),e.jsxs(Oe,{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Wr,{className:"h-4 w-4 text-muted-foreground"}),e.jsx(se,{children:"New Resources"})]}),e.jsx(Tn,{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(qn,{className:"h-4 w-4 text-muted-foreground"}),e.jsx(se,{children:"Community Highlights"})]}),e.jsx(Tn,{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(ml,{className:"h-4 w-4 text-muted-foreground"}),e.jsx(se,{children:"Agent OS Stats"})]}),e.jsx(Tn,{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(ia,{className:"h-4 w-4 text-muted-foreground"}),e.jsx(se,{children:"Upcoming Events"})]}),e.jsx(Tn,{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(Mu,{className:"h-4 w-4 text-muted-foreground"}),e.jsx(se,{children:"Goals Progress"})]}),e.jsx(Tn,{checked:c==null?void 0:c.include_goals_progress,onCheckedChange:M=>y.mutate({include_goals_progress:M})})]})]})]})]}),e.jsxs(_e,{children:[e.jsxs(Bt,{children:[e.jsx(Ut,{children:"Custom Introduction"}),e.jsx(vr,{children:"Personalize the intro message (optional)"})]}),e.jsx(Oe,{children:e.jsx(Is,{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(Jt,{value:"stats",children:e.jsxs(_e,{children:[e.jsxs(Bt,{children:[e.jsxs(Ut,{className:"flex items-center gap-2",children:[e.jsx(nn,{className:"h-5 w-5"}),"Delivery History"]}),e.jsx(vr,{children:"Recent digest emails sent to members"})]}),e.jsx(Oe,{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(Va,{children:[e.jsx(Ha,{children:e.jsxs(hn,{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(Ga,{children:u.map(M=>e.jsxs(hn,{children:[e.jsx(gt,{className:"font-medium",children:M.email_sent_to}),e.jsx(gt,{children:Hs(new Date(M.sent_at),"MMM d, yyyy h:mm a")}),e.jsx(gt,{children:e.jsx($e,{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($e,{variant:"secondary",children:"Active"}):e.jsx($e,{variant:"outline",children:"Not Started"})})]},M.id))})]}):e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(nn,{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 ADn={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 EDn(){var le,he,ve;const s=ts(),[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,x]=j.useState(!0),[g,y]=j.useState(!1),[b,v]=j.useState(""),[N,C]=j.useState(null),{data:A,isLoading:T}=ht({queryKey:["admin-agent-points"],queryFn:async()=>{const{data:ge,error:fe}=await U.from("agent_attendance_stats").select("*").order("total_points",{ascending:!1});if(fe)throw fe;const je=(ge==null?void 0:ge.map(De=>De.user_id))||[],{data:Ee}=await U.from("profiles").select("id, name, email").in("id",je),Me=new Map((Ee==null?void 0:Ee.map(De=>[De.id,{name:De.name,email:De.email}]))||[]);return ge==null?void 0:ge.map(De=>({...De,profile:Me.get(De.user_id)||null}))}}),{data:P}=ht({queryKey:["all-profiles-for-points",A],queryFn:async()=>{const fe=[];let je=0;for(;;){const{data:Ee,error:Me}=await U.from("profiles").select("id, name, email").order("name").range(je,je+1e3-1);if(Me)throw Me;if(fe.push(...Ee),!Ee||Ee.length<1e3)break;je+=1e3}return fe}}),I=((P==null?void 0:P.filter(ge=>!(A!=null&&A.some(fe=>fe.user_id===ge.id))))||[]).filter(ge=>{var je,Ee;if(!b)return!0;const fe=b.toLowerCase();return((je=ge.name)==null?void 0:je.toLowerCase().includes(fe))||((Ee=ge.email)==null?void 0:Ee.toLowerCase().includes(fe))}),{data:D,isLoading:B}=ht({queryKey:["agent-point-history",r==null?void 0:r.user_id],queryFn:async()=>{if(!(r!=null&&r.user_id))return[];const{data:ge,error:fe}=await U.from("agent_points").select("*").eq("user_id",r.user_id).order("created_at",{ascending:!1});if(fe)throw fe;return ge},enabled:!!(r!=null&&r.user_id)&&o}),{data:q}=ht({queryKey:["agent-badges",r==null?void 0:r.user_id],queryFn:async()=>{if(!(r!=null&&r.user_id))return[];const{data:ge,error:fe}=await U.from("agent_badges").select("*").eq("user_id",r.user_id).order("earned_at",{ascending:!1});if(fe)throw fe;return ge},enabled:!!(r!=null&&r.user_id)}),W=yt({mutationFn:async({userId:ge,points:fe,reason:je})=>{const{error:Ee}=await U.from("agent_points").insert({user_id:ge,points:fe,reason:je});if(Ee)throw Ee;const{data:Me}=await U.from("agent_attendance_stats").select("total_points, spendable_points").eq("user_id",ge).maybeSingle(),De=((Me==null?void 0:Me.total_points)||0)+fe,ze=((Me==null?void 0:Me.spendable_points)||0)+fe,{error:ke}=await U.from("agent_attendance_stats").upsert({user_id:ge,total_points:Math.max(0,De),spendable_points:Math.max(0,ze),updated_at:new Date().toISOString()},{onConflict:"user_id"});if(ke)throw ke},onSuccess:()=>{s.invalidateQueries({queryKey:["admin-agent-points"]}),s.invalidateQueries({queryKey:["agent-point-history"]}),l(!1),u(""),m(""),ae.success(p?"Points awarded successfully!":"Points deducted successfully!")},onError:ge=>{console.error("Error modifying points:",ge),ae.error("Failed to modify points")}}),V=()=>{if(!r||!d||!h){ae.error("Please fill in all fields");return}const ge=parseInt(d);if(isNaN(ge)||ge<=0){ae.error("Please enter a valid positive number");return}W.mutate({userId:r.user_id,points:p?ge:-ge,reason:h})},K=()=>{if(!N||!d||!h){ae.error("Please fill in all fields");return}const ge=parseInt(d);if(isNaN(ge)||ge<=0){ae.error("Please enter a valid positive number");return}W.mutate({userId:N.id,points:ge,reason:h},{onSuccess:()=>{y(!1),C(null),v("")}})},Q=(ge,fe)=>{a(ge),x(fe),l(!0)},J=ge=>{a(ge),c(!0)},ce=A==null?void 0:A.filter(ge=>{var Me,De,ze,ke;const fe=((De=(Me=ge.profile)==null?void 0:Me.name)==null?void 0:De.toLowerCase())||"",je=((ke=(ze=ge.profile)==null?void 0:ze.email)==null?void 0:ke.toLowerCase())||"",Ee=t.toLowerCase();return fe.includes(Ee)||je.includes(Ee)}),ue=(A==null?void 0:A.reduce((ge,fe)=>ge+fe.total_points,0))||0,ne=(A==null?void 0:A.length)||0,ee=ne>0?Math.round(ue/ne):0;return T?e.jsx(Ks,{title:"Agent Points",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(on,{className:"h-8 w-64"}),e.jsx("div",{className:"grid grid-cols-3 gap-4",children:[1,2,3].map(ge=>e.jsx(on,{className:"h-24"},ge))}),e.jsx(on,{className:"h-96"})]})}):e.jsx(Ks,{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(_e,{children:e.jsxs(Oe,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(qn,{className:"h-4 w-4"}),e.jsx("span",{className:"text-xs font-medium",children:"Total Agents"})]}),e.jsx("p",{className:"text-2xl font-bold",children:ne}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"with points tracked"})]})}),e.jsx(_e,{children:e.jsxs(Oe,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(pl,{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(_e,{children:e.jsxs(Oe,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(Il,{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:ee}),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(Vr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(be,{placeholder:"Search agents...",value:t,onChange:ge=>n(ge.target.value),className:"pl-10"})]}),e.jsxs($,{onClick:()=>y(!0),children:[e.jsx(sn,{className:"h-4 w-4 mr-2"}),"Award Points to New Agent"]})]}),e.jsxs(_e,{children:[e.jsxs(Bt,{children:[e.jsx(Ut,{children:"Agent Leaderboard"}),e.jsx(vr,{children:"All agents with their points, events, and streaks"})]}),e.jsx(Oe,{children:!ce||ce.length===0?e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(pl,{className:"h-12 w-12 mx-auto mb-4 opacity-50"}),e.jsx("p",{children:"No agents with points yet"})]}):e.jsxs(Va,{children:[e.jsx(Ha,{children:e.jsxs(hn,{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(Ga,{children:ce.map((ge,fe)=>{var je,Ee,Me,De;return e.jsxs(hn,{children:[e.jsx(gt,{className:"font-medium",children:fe<3?e.jsx("div",{className:`w-6 h-6 rounded-full flex items-center justify-center ${fe===0?"bg-yellow-100 text-yellow-700":fe===1?"bg-gray-100 text-gray-600":"bg-amber-100 text-amber-700"}`,children:fe+1}):e.jsx("span",{className:"text-muted-foreground",children:fe+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:((Ee=(je=ge.profile)==null?void 0:je.name)==null?void 0:Ee.charAt(0))||"?"})}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:((Me=ge.profile)==null?void 0:Me.name)||"Unknown"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:(De=ge.profile)==null?void 0:De.email})]})]})}),e.jsx(gt,{className:"text-center",children:e.jsxs($e,{variant:"secondary",className:"font-bold",children:[e.jsx(Qa,{className:"h-3 w-3 mr-1"}),ge.total_points]})}),e.jsx(gt,{className:"text-center",children:e.jsxs($e,{variant:"outline",className:"font-bold text-primary",children:[e.jsx(Co,{className:"h-3 w-3 mr-1"}),ge.spendable_points||0]})}),e.jsx(gt,{className:"text-center",children:e.jsxs("div",{className:"flex items-center justify-center gap-1",children:[e.jsx(ia,{className:"h-3 w-3 text-muted-foreground"}),ge.total_events_attended]})}),e.jsx(gt,{className:"text-center",children:e.jsxs("div",{className:"flex items-center justify-center gap-1",children:[e.jsx(yd,{className:"h-3 w-3 text-orange-500"}),ge.current_streak]})}),e.jsx(gt,{className:"text-right",children:e.jsxs("div",{className:"flex items-center justify-end gap-1",children:[e.jsx($,{variant:"ghost",size:"sm",onClick:()=>Q(ge,!0),title:"Award points",children:e.jsx(sn,{className:"h-4 w-4 text-green-600"})}),e.jsx($,{variant:"ghost",size:"sm",onClick:()=>Q(ge,!1),title:"Deduct points",children:e.jsx(DN,{className:"h-4 w-4 text-red-600"})}),e.jsx($,{variant:"ghost",size:"sm",onClick:()=>J(ge),title:"View history",children:e.jsx(Uj,{className:"h-4 w-4"})})]})})]},ge.user_id)})})]})})]}),e.jsx(Os,{open:i,onOpenChange:l,children:e.jsxs(Rs,{children:[e.jsxs(Us,{children:[e.jsx(zs,{children:p?"Award Points":"Deduct Points"}),e.jsxs(Sr,{children:[p?"Award":"Deduct"," points ",p?"to":"from"," ",((le=r==null?void 0:r.profile)==null?void 0:le.name)||"this agent"]})]}),e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"points",children:"Points Amount"}),e.jsx(be,{id:"points",type:"number",min:"1",placeholder:"Enter points...",value:d,onChange:ge=>u(ge.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"reason",children:"Reason"}),e.jsx(Is,{id:"reason",placeholder:"Enter reason for this adjustment...",value:h,onChange:ge=>m(ge.target.value)})]})]}),e.jsxs(kr,{children:[e.jsx($,{variant:"outline",onClick:()=>l(!1),children:"Cancel"}),e.jsx($,{onClick:V,disabled:W.isPending,className:p?"bg-green-600 hover:bg-green-700":"bg-red-600 hover:bg-red-700",children:W.isPending?"Saving...":p?"Award Points":"Deduct Points"})]})]})}),e.jsx(Os,{open:o,onOpenChange:c,children:e.jsxs(Rs,{className:"max-w-2xl",children:[e.jsxs(Us,{children:[e.jsxs(zs,{children:["Point History: ",(he=r==null?void 0:r.profile)==null?void 0:he.name]}),e.jsx(Sr,{children:"View all point transactions and badges for this agent"})]}),e.jsxs(ua,{defaultValue:"history",className:"w-full",children:[e.jsxs(ha,{className:"grid w-full grid-cols-2",children:[e.jsx(Qt,{value:"history",children:"Point History"}),e.jsx(Qt,{value:"badges",children:"Badges"})]}),e.jsx(Jt,{value:"history",className:"mt-4",children:B?e.jsx("div",{className:"space-y-2",children:[1,2,3].map(ge=>e.jsx(on,{className:"h-12"},ge))}):!D||D.length===0?e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(Uj,{className:"h-8 w-8 mx-auto mb-2 opacity-50"}),e.jsx("p",{children:"No point history yet"})]}):e.jsx("div",{className:"max-h-80 overflow-y-auto space-y-2",children:D.map(ge=>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:ge.reason}),e.jsx("p",{className:"text-xs text-muted-foreground",children:Hs(new Date(ge.created_at),"MMM d, yyyy h:mm a")})]}),e.jsxs($e,{variant:ge.points>=0?"default":"destructive",className:ge.points>=0?"bg-green-100 text-green-800":"",children:[ge.points>=0?"+":"",ge.points]})]},ge.id))})}),e.jsx(Jt,{value:"badges",className:"mt-4",children:!q||q.length===0?e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(pu,{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:q.map(ge=>e.jsxs("div",{className:`p-3 rounded-lg ${ADn[ge.badge_type]||"bg-gray-100"}`,children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(pu,{className:"h-5 w-5"}),e.jsx("span",{className:"font-medium",children:ge.badge_name})]}),ge.badge_description&&e.jsx("p",{className:"text-xs mt-1 opacity-80",children:ge.badge_description}),e.jsxs("p",{className:"text-xs mt-1 opacity-60",children:["Earned ",Hs(new Date(ge.earned_at),"MMM d, yyyy")]})]},ge.id))})})]})]})}),e.jsx(Os,{open:g,onOpenChange:ge=>{y(ge),ge||(C(null),v(""),u(""),m(""))},children:e.jsxs(Rs,{className:"max-w-md",children:[e.jsxs(Us,{children:[e.jsx(zs,{children:"Award Points to New Agent"}),e.jsx(Sr,{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:((ve=N.name)==null?void 0:ve.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($,{variant:"ghost",size:"sm",onClick:()=>C(null),children:"Change"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"new-points",children:"Points Amount"}),e.jsx(be,{id:"new-points",type:"number",min:"1",placeholder:"Enter points...",value:d,onChange:ge=>u(ge.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"new-reason",children:"Reason"}),e.jsx(Is,{id:"new-reason",placeholder:"Enter reason for awarding points...",value:h,onChange:ge=>m(ge.target.value)})]})]}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Search Agent"}),e.jsxs("div",{className:"relative",children:[e.jsx(Vr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(be,{placeholder:"Search by name or email...",value:b,onChange:ge=>v(ge.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(qn,{className:"h-6 w-6 mx-auto mb-2 opacity-50"}),e.jsx("p",{className:"text-sm",children:b?"No matching agents found":"All agents already have points"})]}):I.slice(0,20).map(ge=>{var fe;return e.jsxs("button",{onClick:()=>C(ge),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:((fe=ge.name)==null?void 0:fe.charAt(0))||"?"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"font-medium truncate",children:ge.name||"Unknown"}),e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:ge.email})]})]},ge.id)})})]})}),e.jsxs(kr,{children:[e.jsx($,{variant:"outline",onClick:()=>y(!1),children:"Cancel"}),N&&e.jsxs($,{onClick:K,disabled:W.isPending,className:"bg-green-600 hover:bg-green-700",children:[e.jsx(sn,{className:"h-4 w-4 mr-2"}),"Award Points"]})]})]})})]})})}function TDn(){const{data:s,isLoading:t}=g_s(),[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"),x=j.useMemo(()=>(s==null?void 0:s.map(N=>N.user_id))||[],[s]),g=j.useMemo(()=>(s==null?void 0:s.map(N=>N.id))||[],[s]),{data:y}=ht({queryKey:["card-profiles-lookup",x],queryFn:async()=>{if(x.length===0)return{};const{data:N}=await U.from("profiles").select("id, name, email").in("id",x),C={};return N==null||N.forEach(A=>{C[A.id]={name:A.name||"",email:A.email||""}}),C},enabled:x.length>0}),{data:b}=ht({queryKey:["card-stats-all",g],queryFn:async()=>{if(g.length===0)return{};const N={};g.forEach(T=>{N[T]={views:0,leads:0}});const{data:C}=await U.from("agent_card_interactions").select("card_id").in("card_id",g).eq("interaction_type","card_view");C==null||C.forEach(T=>{N[T.card_id]&&N[T.card_id].views++});const{data:A}=await U.from("agent_card_leads").select("card_id").in("card_id",g);return A==null||A.forEach(T=>{N[T.card_id]&&N[T.card_id].leads++}),N},enabled:g.length>0}),v=j.useMemo(()=>{if(!s)return[];let N=[...s];if(c==="live"?N=N.filter(C=>C.is_published):c==="draft"&&(N=N.filter(C=>!C.is_published)),l.trim()){const C=l.toLowerCase();N=N.filter(A=>{var P,M;const T=y==null?void 0:y[A.user_id];return A.slug.toLowerCase().includes(C)||((P=T==null?void 0:T.name)==null?void 0:P.toLowerCase().includes(C))||((M=T==null?void 0:T.email)==null?void 0:M.toLowerCase().includes(C))})}return u==="newest"?N.sort((C,A)=>new Date(A.created_at).getTime()-new Date(C.created_at).getTime()):u==="oldest"?N.sort((C,A)=>new Date(C.created_at).getTime()-new Date(A.created_at).getTime()):u==="name"?N.sort((C,A)=>{var T,P;return(((T=y==null?void 0:y[C.user_id])==null?void 0:T.name)||"").localeCompare(((P=y==null?void 0:y[A.user_id])==null?void 0:P.name)||"")}):u==="slug"?N.sort((C,A)=>C.slug.localeCompare(A.slug)):u==="views_desc"?N.sort((C,A)=>{var T,P;return(((T=b==null?void 0:b[A.id])==null?void 0:T.views)||0)-(((P=b==null?void 0:b[C.id])==null?void 0:P.views)||0)}):u==="views_asc"?N.sort((C,A)=>{var T,P;return(((T=b==null?void 0:b[C.id])==null?void 0:T.views)||0)-(((P=b==null?void 0:b[A.id])==null?void 0:P.views)||0)}):u==="leads_desc"?N.sort((C,A)=>{var T,P;return(((T=b==null?void 0:b[A.id])==null?void 0:T.leads)||0)-(((P=b==null?void 0:b[C.id])==null?void 0:P.leads)||0)}):u==="leads_asc"&&N.sort((C,A)=>{var T,P;return(((T=b==null?void 0:b[C.id])==null?void 0:T.leads)||0)-(((P=b==null?void 0:b[A.id])==null?void 0:P.leads)||0)}),N},[s,c,l,u,y]);return e.jsxs(Ks,{title:"Digital Agent Cards",children:[e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold",children:"Digital Agent Cards"}),e.jsx("p",{className:"text-muted-foreground",children:"Create and manage agent digital business cards"})]}),e.jsxs($,{onClick:()=>i(!0),children:[e.jsx(sn,{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(Vr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(be,{placeholder:"Search by name, email, or slug...",value:l,onChange:N=>o(N.target.value),className:"pl-9"})]}),e.jsxs(vs,{value:c,onValueChange:d,children:[e.jsx(gs,{className:"w-full sm:w-36",children:e.jsx(bs,{placeholder:"Status"})}),e.jsxs(ys,{children:[e.jsx(Ye,{value:"all",children:"All Status"}),e.jsx(Ye,{value:"live",children:"Live"}),e.jsx(Ye,{value:"draft",children:"Draft"})]})]}),e.jsxs(vs,{value:u,onValueChange:h,children:[e.jsx(gs,{className:"w-full sm:w-44",children:e.jsx(bs,{placeholder:"Sort by"})}),e.jsxs(ys,{children:[e.jsx(Ye,{value:"newest",children:"Newest First"}),e.jsx(Ye,{value:"oldest",children:"Oldest First"}),e.jsx(Ye,{value:"name",children:"Name A–Z"}),e.jsx(Ye,{value:"slug",children:"Slug A–Z"}),e.jsx(Ye,{value:"views_desc",children:"Most Views"}),e.jsx(Ye,{value:"views_asc",children:"Fewest Views"}),e.jsx(Ye,{value:"leads_desc",children:"Most Leads"}),e.jsx(Ye,{value:"leads_asc",children:"Fewest Leads"})]})]}),e.jsxs("div",{className:"flex border rounded-md",children:[e.jsx($,{variant:m==="table"?"default":"ghost",size:"sm",onClick:()=>p("table"),className:"rounded-r-none",children:e.jsx($z,{className:"h-4 w-4"})}),e.jsx($,{variant:m==="grid"?"default":"ghost",size:"sm",onClick:()=>p("grid"),className:"rounded-l-none",children:e.jsx(_0,{className:"h-4 w-4"})})]})]}),!t&&s&&s.length>0&&e.jsxs("p",{className:"text-sm text-muted-foreground",children:["Showing ",v.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(on,{className:"h-48"},N))}):v.length>0?m==="table"?e.jsx(MDn,{cards:v,cardProfiles:y,cardStats:b,onEdit:r,sortBy:u,setSortBy:h}):e.jsx("div",{className:"grid gap-4 md:grid-cols-2 lg:grid-cols-3",children:v.map(N=>e.jsx(LDn,{card:N,onEdit:()=>r(N),stats:b==null?void 0:b[N.id]},N.id))}):s&&s.length>0?e.jsx(_e,{children:e.jsxs(Oe,{className:"flex flex-col items-center justify-center py-12",children:[e.jsx(Vr,{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(_e,{children:e.jsxs(Oe,{className:"flex flex-col items-center justify-center py-12",children:[e.jsx(qn,{className:"h-12 w-12 text-muted-foreground mb-4"}),e.jsx("h3",{className:"text-lg font-semibold mb-1",children:"No cards yet"}),e.jsx("p",{className:"text-muted-foreground text-sm mb-4",children:"Create your first digital agent card"}),e.jsxs($,{onClick:()=>i(!0),children:[e.jsx(sn,{className:"h-4 w-4 mr-2"}),"Create Card"]})]})})]}),e.jsx(PDn,{open:a,onOpenChange:i}),n&&e.jsx(IDn,{card:n,open:!!n,onOpenChange:N=>!N&&r(null)})]})}function MDn({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(ax,{className:"h-3 w-3"}):a===`${c}_asc`?e.jsx(sp,{className:"h-3 w-3"}):e.jsx(Tx,{className:"h-3 w-3 opacity-40"});return e.jsx(_e,{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(sp,{className:"h-3 w-3"})]})}),e.jsx("th",{className:"text-left p-3 font-medium text-muted-foreground hidden md:table-cell",children:"Slug"}),e.jsx("th",{className:"text-center p-3 font-medium text-muted-foreground",children:"Status"}),e.jsx("th",{className:"text-right p-3 font-medium",children:e.jsxs("button",{onClick:()=>l("views"),className:"flex items-center gap-1 ml-auto hover:text-foreground text-muted-foreground",children:["Views ",e.jsx(o,{field:"views"})]})}),e.jsx("th",{className:"text-right p-3 font-medium",children:e.jsxs("button",{onClick:()=>l("leads"),className:"flex items-center gap-1 ml-auto hover:text-foreground text-muted-foreground",children:["Leads ",e.jsx(o,{field:"leads"})]})}),e.jsx("th",{className:"text-right p-3 font-medium text-muted-foreground",children:"Actions"})]})}),e.jsx("tbody",{children:s.map(c=>{const d=t==null?void 0:t[c.user_id],u=n==null?void 0:n[c.id],h=`https://cards.relevelup.com/${c.slug}`;return e.jsxs("tr",{className:"border-b last:border-0 hover:bg-muted/30 transition-colors",children:[e.jsx("td",{className:"p-3",children:e.jsxs("div",{children:[e.jsx("span",{className:"font-medium",children:(d==null?void 0:d.name)||"Unknown"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:(d==null?void 0:d.email)||""})]})}),e.jsx("td",{className:"p-3 hidden md:table-cell",children:e.jsxs("span",{className:"text-xs text-muted-foreground font-mono",children:["/",c.slug]})}),e.jsx("td",{className:"p-3 text-center",children:e.jsx($e,{variant:c.is_published?"default":"secondary",className:"text-xs",children:c.is_published?"Live":"Draft"})}),e.jsx("td",{className:"p-3 text-right tabular-nums font-medium",children:(u==null?void 0:u.views)??0}),e.jsx("td",{className:"p-3 text-right tabular-nums font-medium",children:(u==null?void 0:u.leads)??0}),e.jsx("td",{className:"p-3",children:e.jsxs("div",{className:"flex items-center justify-end gap-1",children:[e.jsx($,{variant:"ghost",size:"sm",onClick:()=>r(c),className:"h-8 w-8 p-0",children:e.jsx(Ya,{className:"h-3.5 w-3.5"})}),e.jsx($,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:()=>{navigator.clipboard.writeText(h),ae.success("Link copied!")},children:e.jsx(Ca,{className:"h-3.5 w-3.5"})}),e.jsx($,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",asChild:!0,children:e.jsx("a",{href:h,target:"_blank",rel:"noopener noreferrer",children:e.jsx(Tr,{className:"h-3.5 w-3.5"})})})]})})]},c.id)})})]})})})}function LDn({card:s,onEdit:t,stats:n}){const[r,a]=j.useState(null);j.useEffect(()=>{(async()=>{const{data:c}=await U.from("profiles").select("name").eq("id",s.user_id).single();let d=null;try{const{data:u}=await U.storage.from("avatars").list(`${s.user_id}`);if(u&&u.length>0){const{data:h}=U.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),ae.success("Link copied!")};return e.jsx(_e,{children:e.jsxs(Oe,{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(ki,{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($e,{variant:s.is_published?"default":"secondary",children:s.is_published?"Live":"Draft"})]}),e.jsxs("div",{className:"flex items-center gap-3 mb-3 text-xs text-muted-foreground",children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(ga,{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(qn,{className:"h-3.5 w-3.5"}),(n==null?void 0:n.leads)??0," leads"]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs($,{variant:"outline",size:"sm",onClick:t,className:"flex-1",children:[e.jsx(Ya,{className:"h-3 w-3 mr-1"}),"Edit"]}),e.jsx($,{variant:"outline",size:"sm",onClick:l,children:e.jsx(Ca,{className:"h-3 w-3"})}),e.jsx($,{variant:"outline",size:"sm",asChild:!0,children:e.jsx("a",{href:i,target:"_blank",rel:"noopener noreferrer",children:e.jsx(Tr,{className:"h-3 w-3"})})})]})]})})}function PDn({open:s,onOpenChange:t}){const[n,r]=j.useState(""),[a,i]=j.useState(""),[l,o]=j.useState(""),[c,d]=j.useState(!1),u=TAt(),h=l.trim(),{data:m}=ht({queryKey:["profiles-search-for-cards",h],queryFn:async()=>{let v=U.from("profiles").select("id, name, email").order("name").limit(50);h.length>=2&&(v=v.or(`name.ilike.%${h}%,email.ilike.%${h}%`));const{data:N}=await v;return N||[]},enabled:s}),[p,x]=j.useState(null),g=(m==null?void 0:m.find(v=>v.id===n))||p,y=()=>{if(!n||!a.trim()){ae.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("")}})},b=v=>{var C;r(v),d(!1);const N=m==null?void 0:m.find(A=>A.id===v);N&&(x(N),i(((C=N.name)==null?void 0:C.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/(^-|-$)/g,""))||""))};return e.jsx(Os,{open:s,onOpenChange:t,children:e.jsxs(Rs,{children:[e.jsxs(Us,{children:[e.jsx(zs,{children:"Create Agent Card"}),e.jsx(Sr,{children:"Select an agent and set their card URL slug."})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(se,{children:"Agent"}),e.jsxs(Sc,{open:c,onOpenChange:d,children:[e.jsx(Cc,{asChild:!0,children:e.jsxs($,{variant:"outline",role:"combobox","aria-expanded":c,className:"w-full justify-between font-normal",children:[g?`${g.name} (${g.email})`:"Search for an agent...",e.jsx(sw,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(xc,{className:"w-[--radix-popover-trigger-width] p-0",align:"start",children:e.jsxs(pw,{shouldFilter:!1,children:[e.jsx(fw,{placeholder:"Search by name or email...",value:l,onValueChange:o}),e.jsxs(xw,{children:[e.jsx(gw,{children:"No agents found."}),e.jsx($b,{children:(m||[]).map(v=>e.jsxs(iv,{value:v.id,onSelect:b,children:[e.jsx(oa,{className:Tt("mr-2 h-4 w-4",n===v.id?"opacity-100":"opacity-0")}),v.name," (",v.email,")"]},v.id))})]})]})})]})]}),e.jsxs("div",{children:[e.jsx(se,{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(be,{value:a,onChange:v=>i(v.target.value),placeholder:"john-doe"})]})]}),e.jsx($,{onClick:y,disabled:u.isPending,className:"w-full",children:u.isPending?"Creating...":"Create Card"})]})]})})}function IDn({card:s,open:t,onOpenChange:n}){const r=MAt(),{data:a}=LAt(s.id),i=ts(),[l,o]=j.useState(null),[c,d]=j.useState(!1),[u,h]=j.useState(!1),[m,p]=j.useState(""),[x,g]=j.useState(s.slug),[y,b]=j.useState(!1),[v,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:D}=await U.storage.from("avatars").list(`${s.user_id}`);if(D&&D.length>0){const{data:B}=U.storage.from("avatars").getPublicUrl(`${s.user_id}/${D[0].name}`);o(`${B.publicUrl}?t=${Date.now()}`)}}catch{}})()},[s.user_id,t]);const C=I=>{var q;const D=(q=I.target.files)==null?void 0:q[0];if(!D)return;if(!D.type.startsWith("image/")){ae.error("Please select an image file");return}if(D.size>5*1024*1024){ae.error("Image must be under 5MB");return}const B=new FileReader;B.onloadend=()=>{p(B.result),h(!0)},B.readAsDataURL(D),I.target.value=""},A=async I=>{d(!0);try{const{data:D}=await U.storage.from("avatars").list(`${s.user_id}`);D&&D.length>0&&await U.storage.from("avatars").remove(D.map(K=>`${s.user_id}/${K.name}`));const B=`${s.user_id}/avatar.jpg`,{error:q}=await U.storage.from("avatars").upload(B,I,{upsert:!0,contentType:"image/jpeg"});if(q)throw q;const{data:W}=U.storage.from("avatars").getPublicUrl(B),V=`${W.publicUrl}?t=${Date.now()}`;o(V),await U.from("profiles").update({avatar_url:V}).eq("id",s.user_id),i.invalidateQueries({queryKey:["agent-card-public"]}),ae.success("Photo updated!")}catch(D){ae.error(D.message||"Upload failed")}finally{d(!1)}},T=async()=>{const I=x.trim().toLowerCase().replace(/[^a-z0-9-]/g,"-").replace(/-+/g,"-").replace(/(^-|-$)/g,"");if(!I){ae.error("Please enter a valid URL");return}if(I===s.slug){ae.info("No changes to save");return}b(!0);try{const{data:D}=await U.from("agent_cards").select("id").eq("slug",I).neq("id",s.id).maybeSingle();if(D){ae.error("This URL is already taken. Try another one.");return}const{error:B}=await U.from("agent_cards").update({slug:I}).eq("id",s.id);if(B)throw B;g(I),i.invalidateQueries({queryKey:["agent-cards-admin"]}),ae.success("Card address updated!")}catch{ae.error("Failed to update card address")}finally{b(!1)}},P=async(I,D)=>{var q;const B=(q=I.target.files)==null?void 0:q[0];if(B){if(!B.type.startsWith("image/")){ae.error("Please select an image file");return}try{const W=B.name.split(".").pop()||"png",V=D==="brokerage_logo_url"?"brokerage-logo":"team-logo",K=`${s.user_id}/${V}.${W}`,{error:Q}=await U.storage.from("card-logos").upload(K,B,{upsert:!0});if(Q)throw Q;const{data:J}=U.storage.from("card-logos").getPublicUrl(K),ce=J.publicUrl+"?t="+Date.now();N(D==="brokerage_logo_url"?ue=>({...ue,[D]:ce,brokerage_display_name:""}):ue=>({...ue,[D]:ce,team_name:""})),ae.success("Logo uploaded!")}catch{ae.error("Failed to upload logo")}finally{I.target.value=""}}},M=()=>{r.mutate({id:s.id,...v,title:v.title||null,positioning_statement:v.positioning_statement||null,bio:v.bio||null,review_snippet:v.review_snippet||null,review_source_url:v.review_source_url||null,booking_url:v.booking_url||null,custom_cta_label:v.custom_cta_label||null,custom_cta_url:v.custom_cta_url||null,brokerage_display_name:v.brokerage_display_name||null,brokerage_logo_url:v.brokerage_logo_url||null,brokerage_logo_size:v.brokerage_logo_size,team_name:v.team_name||null,team_logo_url:v.team_logo_url||null,team_logo_size:v.team_logo_size},{onSuccess:()=>n(!1)})};return e.jsxs(e.Fragment,{children:[e.jsx(Os,{open:t,onOpenChange:n,children:e.jsxs(Rs,{className:"max-w-2xl max-h-[85vh] overflow-y-auto",children:[e.jsxs(Us,{children:[e.jsx(zs,{children:"Edit Agent Card"}),e.jsxs(Sr,{children:["/card/",s.slug]})]}),e.jsxs(ua,{defaultValue:"content",children:[e.jsxs(ha,{className:"w-full",children:[e.jsx(Qt,{value:"content",className:"flex-1",children:"Content"}),e.jsx(Qt,{value:"sections",className:"flex-1",children:"Sections"}),e.jsx(Qt,{value:"blocks",className:"flex-1",children:"Blocks"}),e.jsx(Qt,{value:"analytics",className:"flex-1",children:"Analytics"})]}),e.jsxs(Jt,{value:"content",className:"space-y-4 mt-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(se,{children:"Published"}),e.jsx(Tn,{checked:v.is_published,onCheckedChange:I=>N(D=>({...D,is_published:I}))})]}),e.jsxs("div",{children:[e.jsx(se,{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(ki,{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:C,disabled:c}),e.jsx($,{variant:"outline",size:"sm",asChild:!0,disabled:c,children:e.jsx("span",{children:c?e.jsxs(e.Fragment,{children:[e.jsx(Ht,{className:"h-3 w-3 mr-1 animate-spin"}),"Uploading..."]}):e.jsxs(e.Fragment,{children:[e.jsx(si,{className:"h-3 w-3 mr-1"}),"Change Photo"]})})})]})]})]}),e.jsxs("div",{children:[e.jsx(se,{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(be,{value:x,onChange:I=>g(I.target.value.toLowerCase().replace(/[^a-z0-9-]/g,"-")),placeholder:"agent-name",className:"rounded-l-none"})]}),e.jsx($,{variant:"outline",size:"sm",onClick:T,disabled:y||x===s.slug,className:"shrink-0",children:y?"Saving...":"Update"})]})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Theme"}),e.jsxs(vs,{value:v.theme,onValueChange:I=>N(D=>({...D,theme:I})),children:[e.jsx(gs,{children:e.jsx(bs,{})}),e.jsxs(ys,{children:[e.jsx(Ye,{value:"standard",children:"✨ Standard (Modern Clean)"}),e.jsx(Ye,{value:"luxury",children:"🌙 Luxury (Dark & Gold)"}),e.jsx(Ye,{value:"bold",children:"🔥 Bold (Vibrant & Punchy)"}),e.jsx(Ye,{value:"classic",children:"📋 Classic (Professional)"})]})]})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Title / Tagline"}),e.jsx(be,{value:v.title,onChange:I=>N(D=>({...D,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(se,{children:"Positioning Statement"}),e.jsx(be,{value:v.positioning_statement,onChange:I=>N(D=>({...D,positioning_statement:I.target.value})),placeholder:"Your home journey, handled with care."})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Bio"}),e.jsx(Is,{value:v.bio,onChange:I=>N(D=>({...D,bio:I.target.value})),placeholder:"Short about me...",rows:3})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Review Snippet"}),e.jsx(be,{value:v.review_snippet,onChange:I=>N(D=>({...D,review_snippet:I.target.value})),placeholder:"Best agent we've ever worked with..."})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Review Source URL"}),e.jsx(be,{value:v.review_source_url,onChange:I=>N(D=>({...D,review_source_url:I.target.value})),placeholder:"https://g.page/your-business/review"})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Booking URL (optional — if empty, shows lead form)"}),e.jsx(be,{value:v.booking_url,onChange:I=>N(D=>({...D,booking_url:I.target.value})),placeholder:"https://calendly.com/your-link"})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Custom CTA Label (optional)"}),e.jsx(be,{value:v.custom_cta_label,onChange:I=>N(D=>({...D,custom_cta_label:I.target.value})),placeholder:"Book a Call"})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Custom CTA URL (optional)"}),e.jsx(be,{value:v.custom_cta_url,onChange:I=>N(D=>({...D,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(se,{className:"text-xs font-semibold uppercase tracking-wider text-muted-foreground",children:"Brokerage Branding"}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(be,{value:v.brokerage_display_name,onChange:I=>N(D=>({...D,brokerage_display_name:I.target.value,brokerage_logo_url:""})),placeholder:"Brokerage name (or upload logo below)",disabled:!!v.brokerage_logo_url}),e.jsxs("div",{className:"flex items-center gap-3",children:[v.brokerage_logo_url&&e.jsxs("div",{className:"relative group",children:[e.jsx("img",{src:v.brokerage_logo_url,alt:"Brokerage logo",style:{height:`${v.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(si,{className:"h-3.5 w-3.5"}),v.brokerage_logo_url?"Change Logo":"Upload Logo"]}),e.jsx("input",{type:"file",accept:"image/*",className:"hidden",onChange:I=>P(I,"brokerage_logo_url")})]})]}),v.brokerage_logo_url&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(se,{className:"text-xs font-medium text-muted-foreground",children:"Logo Size"}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:[v.brokerage_logo_size||56,"px"]})]}),e.jsx(rx,{value:[v.brokerage_logo_size||56],onValueChange:([I])=>N(D=>({...D,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(se,{className:"text-xs font-semibold uppercase tracking-wider text-muted-foreground",children:"Team Branding"}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(be,{value:v.team_name,onChange:I=>N(D=>({...D,team_name:I.target.value,team_logo_url:""})),placeholder:"Team name (or upload logo below)",disabled:!!v.team_logo_url}),e.jsxs("div",{className:"flex items-center gap-3",children:[v.team_logo_url&&e.jsxs("div",{className:"relative group",children:[e.jsx("img",{src:v.team_logo_url,alt:"Team logo",style:{height:`${v.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(si,{className:"h-3.5 w-3.5"}),v.team_logo_url?"Change Logo":"Upload Logo"]}),e.jsx("input",{type:"file",accept:"image/*",className:"hidden",onChange:I=>P(I,"team_logo_url")})]})]}),v.team_logo_url&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(se,{className:"text-xs font-medium text-muted-foreground",children:"Logo Size"}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:[v.team_logo_size||56,"px"]})]}),e.jsx(rx,{value:[v.team_logo_size||56],onValueChange:([I])=>N(D=>({...D,team_logo_size:I})),min:24,max:120,step:4})]})]})]})]}),e.jsx(Jt,{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:D,hint:B})=>e.jsxs("div",{className:"flex items-center justify-between py-2",children:[e.jsxs("div",{children:[e.jsx(se,{children:D}),B&&e.jsxs("p",{className:"text-xs text-muted-foreground mt-0.5",children:[B," ",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(Tn,{checked:v[I],onCheckedChange:q=>N(W=>({...W,[I]:q}))})]},I))}),e.jsx(Jt,{value:"blocks",className:"mt-4",children:e.jsx(NVt,{cardId:s.id})}),e.jsx(Jt,{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(_e,{children:e.jsxs(Oe,{className:"p-4 text-center",children:[e.jsx("div",{className:"text-2xl font-bold",children:a.views}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Views"})]})}),e.jsx(_e,{children:e.jsxs(Oe,{className:"p-4 text-center",children:[e.jsx("div",{className:"text-2xl font-bold",children:a.clicks}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Clicks"})]})}),e.jsx(_e,{children:e.jsxs(Oe,{className:"p-4 text-center",children:[e.jsx("div",{className:"text-2xl font-bold",children:a.leads.length}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Leads"})]})})]}),a.leads.length>0&&e.jsxs("div",{children:[e.jsx("h3",{className:"font-semibold mb-2",children:"Recent Leads"}),e.jsx("div",{className:"space-y-2",children:a.leads.slice(0,5).map(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($e,{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($,{onClick:M,disabled:r.isPending,className:"w-full mt-4",children:r.isPending?"Saving...":"Save Changes"})]})}),e.jsx(lWe,{open:u,onClose:()=>h(!1),imageSrc:m,onCropComplete:A,aspectRatio:1})]})}const _B={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"},pXe={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 fXe(s=!0){return ht({queryKey:["marketplace-categories",s],queryFn:async()=>{let t=U.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 DDn(){const s=ts();return yt({mutationFn:async t=>{const{data:n,error:r}=await U.from("marketplace_categories").insert([t]).select().single();if(r)throw r;return n},onSuccess:()=>{s.invalidateQueries({queryKey:["marketplace-categories"]}),ae.success("Category created successfully")},onError:t=>{ae.error("Failed to create category: "+t.message)}})}function RDn(){const s=ts();return yt({mutationFn:async({id:t,...n})=>{const{data:r,error:a}=await U.from("marketplace_categories").update(n).eq("id",t).select().single();if(a)throw a;return r},onSuccess:()=>{s.invalidateQueries({queryKey:["marketplace-categories"]}),ae.success("Category updated successfully")},onError:t=>{ae.error("Failed to update category: "+t.message)}})}function ODn(){const s=ts();return yt({mutationFn:async t=>{const{error:n}=await U.from("marketplace_categories").delete().eq("id",t);if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["marketplace-categories"]}),ae.success("Category deleted successfully")},onError:t=>{ae.error("Failed to delete category: "+t.message)}})}function EVt(s,t=!0){return ht({queryKey:["marketplace-products",s,t],queryFn:async()=>{let n=U.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 FDn(s){return ht({queryKey:["marketplace-product",s],queryFn:async()=>{const{data:t,error:n}=await U.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 zDn(){const s=ts();return yt({mutationFn:async t=>{const{data:n,error:r}=await U.from("marketplace_products").insert([t]).select().single();if(r)throw r;return n},onSuccess:()=>{s.invalidateQueries({queryKey:["marketplace-products"]}),ae.success("Product created successfully")},onError:t=>{ae.error("Failed to create product: "+t.message)}})}function BDn(){const s=ts();return yt({mutationFn:async({id:t,...n})=>{const{data:r,error:a}=await U.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]}),ae.success("Product updated successfully")},onError:t=>{ae.error("Failed to update product: "+t.message)}})}function $Dn(){const s=ts();return yt({mutationFn:async t=>{const{error:n}=await U.from("marketplace_products").delete().eq("id",t);if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["marketplace-products"]}),ae.success("Product deleted successfully")},onError:t=>{ae.error("Failed to delete product: "+t.message)}})}function UDn(){const s=ts();return yt({mutationFn:async t=>{const{data:n,error:r}=await U.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 qDn(){const s=ts();return yt({mutationFn:async({id:t,productId:n})=>{const{error:r}=await U.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]}),ae.success("Image deleted successfully")},onError:t=>{ae.error("Failed to delete image: "+t.message)}})}function VDn(){const s=ts();return yt({mutationFn:async({imageId:t,productId:n})=>{const{error:r}=await U.from("marketplace_product_images").update({is_primary:!1}).eq("product_id",n);if(r)throw r;const{error:a}=await U.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]}),ae.success("Primary image updated")},onError:t=>{ae.error("Failed to set primary image: "+t.message)}})}function HDn(){const s=ts();return yt({mutationFn:async t=>{const{data:n,error:r}=await U.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]}),ae.success("Variant added successfully")}})}function GDn(){const s=ts();return yt({mutationFn:async({id:t,productId:n})=>{const{error:r}=await U.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]}),ae.success("Variant deleted successfully")}})}function WDn(){const s=ts();return yt({mutationFn:async({productId:t,videoUrl:n})=>{await U.from("marketplace_product_videos").delete().eq("product_id",t);const{data:r,error:a}=await U.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]}),ae.success("Video updated successfully")}})}function KDn(s){const{isAdmin:t}=_s();return ht({queryKey:["marketplace-orders",s,t],queryFn:async()=>{let n=U.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 U.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 YDn(){const{user:s}=_s();return ht({queryKey:["my-marketplace-orders",s==null?void 0:s.id],queryFn:async()=>{const{data:t,error:n}=await U.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 ZDn(s){return ht({queryKey:["marketplace-order",s],queryFn:async()=>{const{data:t,error:n}=await U.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 XDn(){const s=ts(),{user:t}=_s();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 U.from("marketplace_orders").update(c).eq("id",n);if(d)throw d;const{error:u}=await U.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 U.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"]}),ae.success("Order status updated")},onError:n=>{ae.error("Failed to update order: "+n.message)}})}function QDn(){const s=ts();return yt({mutationFn:async({itemId:t,proofUrl:n,proofNotes:r,orderId:a})=>{const{error:i}=await U.from("marketplace_order_items").update({proof_url:n,proof_notes:r,proof_status:"pending"}).eq("id",t);if(i)throw i;await U.from("marketplace_orders").update({status:"awaiting_proof_approval"}).eq("id",a);try{await U.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"]}),ae.success("Proof uploaded & customer notified")}})}function JDn(){const s=ts();return yt({mutationFn:async({itemId:t,orderId:n})=>{const{error:r}=await U.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"]}),ae.success("Proof approved")}})}function eRn(){const s=ts();return yt({mutationFn:async({itemId:t,orderId:n,reason:r})=>{const{error:a}=await U.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"]}),ae.success("Proof rejected - please upload a new proof")}})}function tRn(){const{data:s,isLoading:t}=fXe(!1),n=DDn(),r=RDn(),a=ODn(),[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=g=>{c(g),u({name:g.name,description:g.description||"",image_url:g.image_url||"",sort_order:g.sort_order,is_active:g.is_active}),l(!0)},p=async g=>{g.preventDefault(),o?await r.mutateAsync({id:o.id,...d}):await n.mutateAsync(d),l(!1),h()},x=async g=>{await Yi("Are you sure you want to delete this category?")&&await a.mutateAsync(g)};return t?e.jsxs(_e,{children:[e.jsx(Bt,{children:e.jsx(on,{className:"h-8 w-48"})}),e.jsx(Oe,{children:e.jsx("div",{className:"space-y-4",children:[1,2,3].map(g=>e.jsx(on,{className:"h-12 w-full"},g))})})]}):e.jsxs(_e,{children:[e.jsxs(Bt,{className:"flex flex-row items-center justify-between",children:[e.jsx(Ut,{children:"Categories"}),e.jsxs(Os,{open:i,onOpenChange:g=>{l(g),g||h()},children:[e.jsx(Ko,{asChild:!0,children:e.jsxs($,{children:[e.jsx(sn,{className:"h-4 w-4 mr-2"}),"Add Category"]})}),e.jsxs(Rs,{children:[e.jsx(Us,{children:e.jsx(zs,{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(se,{htmlFor:"name",children:"Name"}),e.jsx(be,{id:"name",value:d.name,onChange:g=>u({...d,name:g.target.value}),required:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"description",children:"Description"}),e.jsx(Is,{id:"description",value:d.description,onChange:g=>u({...d,description:g.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"image_url",children:"Image URL"}),e.jsx(be,{id:"image_url",value:d.image_url,onChange:g=>u({...d,image_url:g.target.value}),placeholder:"https://..."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"sort_order",children:"Sort Order"}),e.jsx(be,{id:"sort_order",type:"number",value:d.sort_order,onChange:g=>u({...d,sort_order:parseInt(g.target.value)||0})})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Tn,{id:"is_active",checked:d.is_active,onCheckedChange:g=>u({...d,is_active:g})}),e.jsx(se,{htmlFor:"is_active",children:"Active"})]}),e.jsx($,{type:"submit",className:"w-full",disabled:n.isPending||r.isPending,children:o?"Update Category":"Create Category"})]})]})]})]}),e.jsx(Oe,{children:s&&s.length>0?e.jsxs(Va,{children:[e.jsx(Ha,{children:e.jsxs(hn,{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(Ga,{children:s.map(g=>e.jsxs(hn,{children:[e.jsx(gt,{className:"font-medium",children:g.name}),e.jsx(gt,{className:"max-w-xs truncate",children:g.description}),e.jsx(gt,{children:g.sort_order}),e.jsx(gt,{children:e.jsx("span",{className:`px-2 py-1 rounded-full text-xs ${g.is_active?"bg-green-100 text-green-800":"bg-gray-100 text-gray-800"}`,children:g.is_active?"Active":"Inactive"})}),e.jsx(gt,{className:"text-right",children:e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx($,{variant:"ghost",size:"icon",onClick:()=>m(g),children:e.jsx(Ya,{className:"h-4 w-4"})}),e.jsx($,{variant:"ghost",size:"icon",onClick:()=>x(g.id),disabled:a.isPending,children:e.jsx(Pn,{className:"h-4 w-4 text-destructive"})})]})})]},g.id))})]}):e.jsx("div",{className:"text-center py-8 text-muted-foreground",children:"No categories yet. Create your first category to get started."})})]})}function sRn(){var ee,le;const{data:s,isLoading:t}=EVt(void 0,!1),{data:n}=fXe(!1),r=zDn(),a=BDn(),i=$Dn(),l=UDn(),o=qDn(),c=VDn(),d=HDn(),u=GDn(),h=WDn(),[m,p]=j.useState(!1),[x,g]=j.useState(!1),[y,b]=j.useState(!1),[v,N]=j.useState(null),[C,A]=j.useState(null),[T,P]=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}),[D,B]=j.useState({name:"",price_adjustment:0}),[q,W]=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=he=>{N(he),I({name:he.name,description:he.description||"",base_price:Number(he.base_price),shipping_fee:Number(he.shipping_fee),category_id:he.category_id||"",allow_artwork_upload:he.allow_artwork_upload,requires_proof_approval:he.requires_proof_approval,is_active:he.is_active,sort_order:he.sort_order}),p(!0)},Q=async he=>{he.preventDefault();const ve={...M,category_id:M.category_id||null};v?await a.mutateAsync({id:v.id,...ve}):await r.mutateAsync(ve),p(!1),V()},J=async he=>{await Yi("Are you sure you want to delete this product?")&&await i.mutateAsync(he)},ce=async he=>{if(!C||!he.target.files||he.target.files.length===0)return;P(!0);const ve=he.target.files[0],ge=ve.name.split(".").pop(),fe=`products/${C.id}/${Date.now()}.${ge}`;try{const{error:je}=await U.storage.from("marketplace").upload(fe,ve);if(je)throw je;const{data:{publicUrl:Ee}}=U.storage.from("marketplace").getPublicUrl(fe);await l.mutateAsync({product_id:C.id,image_url:Ee,is_primary:!C.images||C.images.length===0}),ae.success("Image uploaded successfully")}catch(je){ae.error("Failed to upload image: "+je.message)}finally{P(!1)}},ue=async he=>{he.preventDefault(),C&&(await d.mutateAsync({product_id:C.id,name:D.name,price_adjustment:D.price_adjustment}),B({name:"",price_adjustment:0}))},ne=async()=>{!C||!q||(await h.mutateAsync({productId:C.id,videoUrl:q}),W(""))};return t?e.jsxs(_e,{children:[e.jsx(Bt,{children:e.jsx(on,{className:"h-8 w-48"})}),e.jsx(Oe,{children:e.jsx("div",{className:"grid gap-4 md:grid-cols-2 lg:grid-cols-3",children:[1,2,3].map(he=>e.jsx(on,{className:"h-64 w-full"},he))})})]}):e.jsxs(e.Fragment,{children:[e.jsxs(_e,{children:[e.jsxs(Bt,{className:"flex flex-row items-center justify-between",children:[e.jsx(Ut,{children:"Products"}),e.jsxs(Os,{open:m,onOpenChange:he=>{p(he),he||V()},children:[e.jsx(Ko,{asChild:!0,children:e.jsxs($,{children:[e.jsx(sn,{className:"h-4 w-4 mr-2"}),"Add Product"]})}),e.jsxs(Rs,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsx(Us,{children:e.jsx(zs,{children:v?"Edit Product":"Add Product"})}),e.jsxs("form",{onSubmit:Q,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(se,{htmlFor:"name",children:"Product Name"}),e.jsx(be,{id:"name",value:M.name,onChange:he=>I({...M,name:he.target.value}),required:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"category",children:"Category"}),e.jsxs(vs,{value:M.category_id,onValueChange:he=>I({...M,category_id:he}),children:[e.jsx(gs,{children:e.jsx(bs,{placeholder:"Select category"})}),e.jsx(ys,{children:n==null?void 0:n.map(he=>e.jsx(Ye,{value:he.id,children:he.name},he.id))})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"description",children:"Description"}),e.jsx(Is,{id:"description",value:M.description,onChange:he=>I({...M,description:he.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(se,{htmlFor:"base_price",children:"Base Price ($)"}),e.jsx(be,{id:"base_price",type:"number",step:"0.01",min:"0",value:M.base_price,onChange:he=>I({...M,base_price:parseFloat(he.target.value)||0}),required:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"shipping_fee",children:"Shipping Fee ($)"}),e.jsx(be,{id:"shipping_fee",type:"number",step:"0.01",min:"0",value:M.shipping_fee,onChange:he=>I({...M,shipping_fee:parseFloat(he.target.value)||0})})]})]}),e.jsx("div",{className:"grid grid-cols-2 gap-4",children:e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"sort_order",children:"Sort Order"}),e.jsx(be,{id:"sort_order",type:"number",value:M.sort_order,onChange:he=>I({...M,sort_order:parseInt(he.target.value)||0})})]})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Tn,{id:"allow_artwork_upload",checked:M.allow_artwork_upload,onCheckedChange:he=>I({...M,allow_artwork_upload:he})}),e.jsx(se,{htmlFor:"allow_artwork_upload",children:"Allow customer to upload artwork"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Tn,{id:"requires_proof_approval",checked:M.requires_proof_approval,onCheckedChange:he=>I({...M,requires_proof_approval:he})}),e.jsx(se,{htmlFor:"requires_proof_approval",children:"Requires proof approval"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Tn,{id:"is_active",checked:M.is_active,onCheckedChange:he=>I({...M,is_active:he})}),e.jsx(se,{htmlFor:"is_active",children:"Active"})]})]}),e.jsx($,{type:"submit",className:"w-full",disabled:r.isPending||a.isPending,children:v?"Update Product":"Create Product"})]})]})]})]}),e.jsx(Oe,{children:s&&s.length>0?e.jsx("div",{className:"grid gap-4 md:grid-cols-2 lg:grid-cols-3",children:s.map(he=>{var ve,ge;return e.jsxs(_e,{className:"overflow-hidden",children:[e.jsxs("div",{className:"aspect-video bg-muted relative",children:[he.images&&he.images.length>0?e.jsx("img",{src:((ve=he.images.find(fe=>fe.is_primary))==null?void 0:ve.image_url)||he.images[0].image_url,alt:he.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"}),!he.is_active&&e.jsx($e,{variant:"secondary",className:"absolute top-2 right-2",children:"Inactive"})]}),e.jsxs(Oe,{className:"p-4",children:[e.jsx("h3",{className:"font-semibold mb-1",children:he.name}),e.jsx("p",{className:"text-sm text-muted-foreground mb-2",children:((ge=he.category)==null?void 0:ge.name)||"No category"}),e.jsxs("div",{className:"flex items-center justify-between mb-3",children:[e.jsxs("span",{className:"font-bold",children:["$",Number(he.base_price).toFixed(2)]}),Number(he.shipping_fee)>0&&e.jsxs("span",{className:"text-sm text-muted-foreground",children:["+$",Number(he.shipping_fee).toFixed(2)," shipping"]})]}),e.jsxs("div",{className:"flex flex-wrap gap-1 mb-3",children:[he.allow_artwork_upload&&e.jsx($e,{variant:"outline",className:"text-xs",children:"Artwork Upload"}),he.requires_proof_approval&&e.jsx($e,{variant:"outline",className:"text-xs",children:"Proof Required"}),he.variants&&he.variants.length>0&&e.jsxs($e,{variant:"outline",className:"text-xs",children:[he.variants.length," Variants"]})]}),e.jsxs("div",{className:"flex gap-2 flex-wrap",children:[e.jsxs($,{variant:"outline",size:"sm",onClick:()=>K(he),children:[e.jsx(Ya,{className:"h-3 w-3 mr-1"}),"Edit"]}),e.jsxs($,{variant:"outline",size:"sm",onClick:()=>{A(he),g(!0)},children:[e.jsx(x1,{className:"h-3 w-3 mr-1"}),"Images"]}),e.jsxs($,{variant:"outline",size:"sm",onClick:()=>{A(he),b(!0)},children:[e.jsx(Up,{className:"h-3 w-3 mr-1"}),"Variants"]}),e.jsx($,{variant:"ghost",size:"sm",onClick:()=>J(he.id),children:e.jsx(Pn,{className:"h-3 w-3 text-destructive"})})]})]})]},he.id)})}):e.jsx("div",{className:"text-center py-8 text-muted-foreground",children:"No products yet. Create your first product to get started."})})]}),e.jsx(Os,{open:x,onOpenChange:g,children:e.jsxs(Rs,{className:"max-w-2xl",children:[e.jsx(Us,{children:e.jsxs(zs,{children:["Manage Images - ",C==null?void 0:C.name]})}),e.jsxs("div",{className:"space-y-4",children:[e.jsx("div",{className:"grid grid-cols-3 gap-4",children:(ee=C==null?void 0:C.images)==null?void 0:ee.map(he=>e.jsxs("div",{className:"relative group",children:[e.jsx("img",{src:he.image_url,alt:"",className:"w-full aspect-square object-cover rounded-lg"}),he.is_primary&&e.jsx($e,{className:"absolute top-2 left-2",variant:"default",children:"Primary"}),e.jsxs("div",{className:"absolute top-2 right-2 flex gap-1 opacity-0 group-hover:opacity-100 transition-opacity",children:[!he.is_primary&&e.jsx($,{variant:"secondary",size:"icon",onClick:async()=>{var ve;await c.mutateAsync({imageId:he.id,productId:C.id}),A({...C,images:(ve=C.images)==null?void 0:ve.map(ge=>({...ge,is_primary:ge.id===he.id}))})},disabled:c.isPending,title:"Set as primary",children:e.jsx(Qa,{className:"h-4 w-4"})}),e.jsx($,{variant:"destructive",size:"icon",onClick:async()=>{var ge;await o.mutateAsync({id:he.id,productId:C.id});const ve=s==null?void 0:s.find(fe=>fe.id===C.id);ve&&A({...ve,images:(ge=ve.images)==null?void 0:ge.filter(fe=>fe.id!==he.id)})},disabled:o.isPending,children:e.jsx(Pn,{className:"h-4 w-4"})})]})]},he.id))}),e.jsxs("div",{className:"border-2 border-dashed rounded-lg p-6 text-center",children:[e.jsx("input",{type:"file",accept:"image/*",onChange:ce,className:"hidden",id:"image-upload",disabled:T}),e.jsxs("label",{htmlFor:"image-upload",className:"cursor-pointer",children:[e.jsx(x1,{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(se,{children:"Product Video (optional)"}),e.jsxs("div",{className:"flex gap-2 mt-2",children:[e.jsx(be,{placeholder:"Enter video URL (YouTube, Vimeo, etc.)",value:q,onChange:he=>W(he.target.value)}),e.jsxs($,{onClick:ne,disabled:!q,children:[e.jsx(Xr,{className:"h-4 w-4 mr-2"}),"Set Video"]})]}),(C==null?void 0:C.video)&&e.jsxs("p",{className:"text-sm text-muted-foreground mt-2",children:["Current video: ",C.video.video_url]})]})]})]})}),e.jsx(Os,{open:y,onOpenChange:b,children:e.jsxs(Rs,{children:[e.jsx(Us,{children:e.jsxs(zs,{children:["Manage Variants - ",C==null?void 0:C.name]})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("form",{onSubmit:ue,className:"flex gap-2",children:[e.jsx(be,{placeholder:"Variant name (e.g., 500 count)",value:D.name,onChange:he=>B({...D,name:he.target.value}),required:!0}),e.jsx(be,{type:"number",step:"0.01",placeholder:"Price adj.",value:D.price_adjustment,onChange:he=>B({...D,price_adjustment:parseFloat(he.target.value)||0}),className:"w-32"}),e.jsx($,{type:"submit",children:"Add"})]}),e.jsxs("div",{className:"space-y-2",children:[(le=C==null?void 0:C.variants)==null?void 0:le.map(he=>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:he.name}),e.jsxs("span",{className:"text-sm text-muted-foreground ml-2",children:[Number(he.price_adjustment)>=0?"+":"","$",Number(he.price_adjustment).toFixed(2)]})]}),e.jsx($,{variant:"ghost",size:"icon",onClick:()=>u.mutateAsync({id:he.id,productId:C.id}),children:e.jsx(Pn,{className:"h-4 w-4 text-destructive"})})]},he.id)),(!(C!=null&&C.variants)||C.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 nRn=["pending_payment","order_submitted","awaiting_proof_approval","proof_approved","processing","in_production","shipped","completed","cancelled","refunded"];function rRn(){var g,y,b;const{data:s,isLoading:t}=KDn(),n=XDn(),r=QDn(),[a,i]=j.useState(null),[l,o]=j.useState(!1),[c,d]=j.useState({status:"",notes:"",trackingNumber:"",trackingUrl:""}),[u,h]=j.useState(!1),m=v=>{i(v),d({status:v.status,notes:"",trackingNumber:v.tracking_number||"",trackingUrl:v.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))},x=async(v,N)=>{if(!a||!v.target.files||v.target.files.length===0)return;h(!0);const C=v.target.files[0],A=C.name.split(".").pop(),T=`proofs/${a.id}/${N}/${Date.now()}.${A}`;try{const{error:P}=await U.storage.from("marketplace").upload(T,C);if(P)throw P;const{data:{publicUrl:M}}=U.storage.from("marketplace").getPublicUrl(T);await r.mutateAsync({itemId:N,proofUrl:M,orderId:a.id}),ae.success("Proof uploaded successfully")}catch(P){ae.error("Failed to upload proof: "+P.message)}finally{h(!1)}};return t?e.jsxs(_e,{children:[e.jsx(Bt,{children:e.jsx(on,{className:"h-8 w-48"})}),e.jsx(Oe,{children:e.jsx("div",{className:"space-y-4",children:[1,2,3].map(v=>e.jsx(on,{className:"h-16 w-full"},v))})})]}):e.jsxs(e.Fragment,{children:[e.jsxs(_e,{children:[e.jsx(Bt,{children:e.jsx(Ut,{children:"Orders"})}),e.jsx(Oe,{children:s&&s.length>0?e.jsxs(Va,{children:[e.jsx(Ha,{children:e.jsxs(hn,{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(Ga,{children:s.map(v=>{var N,C;return e.jsxs(hn,{children:[e.jsx(gt,{className:"font-mono",children:v.order_number}),e.jsx(gt,{children:e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:((N=v.user)==null?void 0:N.name)||"Unknown"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:(C=v.user)==null?void 0:C.email})]})}),e.jsx(gt,{children:Hs(new Date(v.created_at),"MMM d, yyyy")}),e.jsxs(gt,{className:"font-bold",children:["$",Number(v.total).toFixed(2)]}),e.jsx(gt,{children:e.jsx($e,{className:pXe[v.status],children:_B[v.status]})}),e.jsx(gt,{className:"text-right",children:e.jsxs($,{variant:"ghost",size:"sm",onClick:()=>m(v),children:[e.jsx(ga,{className:"h-4 w-4 mr-1"}),"View"]})})]},v.id)})})]}):e.jsx("div",{className:"text-center py-8 text-muted-foreground",children:"No orders yet."})})]}),e.jsx(Os,{open:l,onOpenChange:o,children:e.jsxs(Rs,{className:"max-w-3xl max-h-[90vh] overflow-y-auto",children:[e.jsx(Us,{children:e.jsxs(zs,{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:(g=a.user)==null?void 0:g.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:(b=a.items)==null?void 0:b.map(v=>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:v.product_name}),v.variant_name&&e.jsx("p",{className:"text-sm text-muted-foreground",children:v.variant_name})]}),e.jsxs("p",{className:"font-bold",children:["$",Number(v.unit_price).toFixed(2)," x ",v.quantity]})]}),v.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:v.artwork_url,target:"_blank",rel:"noopener noreferrer",className:"text-primary hover:underline text-sm",children:"View Artwork"})]}),e.jsx("div",{className:"mt-3 pt-3 border-t",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium",children:"Proof Status: "}),e.jsx($e,{variant:v.proof_status==="approved"?"default":"secondary",children:v.proof_status||"No proof yet"})]}),v.proof_url?e.jsx("a",{href:v.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=>x(N,v.id),className:"hidden",id:`proof-${v.id}`,disabled:u}),e.jsx("label",{htmlFor:`proof-${v.id}`,children:e.jsx($,{variant:"outline",size:"sm",asChild:!0,children:e.jsxs("span",{children:[e.jsx(si,{className:"h-4 w-4 mr-1"}),u?"Uploading...":"Upload Proof"]})})})]})]})})]},v.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(se,{children:"Status"}),e.jsxs(vs,{value:c.status,onValueChange:v=>d({...c,status:v}),children:[e.jsx(gs,{children:e.jsx(bs,{})}),e.jsx(ys,{children:nRn.map(v=>e.jsx(Ye,{value:v,children:_B[v]},v))})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Tracking Number"}),e.jsx(be,{value:c.trackingNumber,onChange:v=>d({...c,trackingNumber:v.target.value}),placeholder:"Enter tracking number"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Tracking URL"}),e.jsx(be,{value:c.trackingUrl,onChange:v=>d({...c,trackingUrl:v.target.value}),placeholder:"https://..."})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Notes (optional)"}),e.jsx(Is,{value:c.notes,onChange:v=>d({...c,notes:v.target.value}),placeholder:"Add a note about this status change..."})]}),e.jsxs($,{onClick:p,disabled:n.isPending,className:"w-full",children:[e.jsx(Tu,{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(v=>e.jsxs("div",{className:"flex justify-between text-sm p-2 bg-muted rounded",children:[e.jsxs("div",{children:[e.jsx($e,{variant:"outline",children:_B[v.status]}),v.notes&&e.jsx("p",{className:"text-muted-foreground mt-1",children:v.notes})]}),e.jsx("span",{className:"text-muted-foreground",children:Hs(new Date(v.created_at),"MMM d, h:mm a")})]},v.id))})]})]})]})})]})}function aRn(){const[s,t]=j.useState("products"),n=Vn();return e.jsx(Ks,{title:"Marketplace Management",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold",children:"Marketplace Management"}),e.jsx("p",{className:"text-muted-foreground",children:"Manage products, categories, and orders"})]}),e.jsxs($,{variant:"outline",onClick:()=>n("/marketplace"),children:[e.jsx(Tr,{className:"h-4 w-4 mr-2"}),"View Store"]})]}),e.jsxs(ua,{value:s,onValueChange:t,children:[e.jsxs(ha,{className:"grid w-full grid-cols-3",children:[e.jsxs(Qt,{value:"products",className:"flex items-center gap-2",children:[e.jsx(Tu,{className:"h-4 w-4"}),"Products"]}),e.jsxs(Qt,{value:"categories",className:"flex items-center gap-2",children:[e.jsx(cv,{className:"h-4 w-4"}),"Categories"]}),e.jsxs(Qt,{value:"orders",className:"flex items-center gap-2",children:[e.jsx(ON,{className:"h-4 w-4"}),"Orders"]})]}),e.jsx(Jt,{value:"products",children:e.jsx(sRn,{})}),e.jsx(Jt,{value:"categories",children:e.jsx(tRn,{})}),e.jsx(Jt,{value:"orders",children:e.jsx(rRn,{})})]})]})})}function TVt(){return ht({queryKey:["reward-categories"],queryFn:async()=>{const{data:s,error:t}=await U.from("reward_store_categories").select("*").order("sort_order",{ascending:!0});if(t)throw t;return s}})}function iRn(s){return ht({queryKey:["reward-items",s],queryFn:async()=>{let t=U.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 oRn(s){return ht({queryKey:["active-reward-items",s],queryFn:async()=>{let t=U.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 lRn(s){return ht({queryKey:["user-purchases",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await U.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 cRn(){return ht({queryKey:["all-reward-purchases"],queryFn:async()=>{const{data:s,error:t}=await U.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 U.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 dRn(s){return ht({queryKey:["spendable-points",s],queryFn:async()=>{if(!s)return 0;const{data:t,error:n}=await U.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 uRn(){const s=ts();return yt({mutationFn:async t=>{const{data:n,error:r}=await U.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 hRn(){const s=ts();return yt({mutationFn:async t=>{const{data:n,error:r}=await U.from("reward_store_categories").insert([t]).select().single();if(r)throw r;return n},onSuccess:()=>{s.invalidateQueries({queryKey:["reward-categories"]})}})}function mRn(){const s=ts();return yt({mutationFn:async({id:t,...n})=>{const{data:r,error:a}=await U.from("reward_store_categories").update(n).eq("id",t).select().single();if(a)throw a;return r},onSuccess:()=>{s.invalidateQueries({queryKey:["reward-categories"]})}})}function pRn(){const s=ts();return yt({mutationFn:async t=>{const{error:n}=await U.from("reward_store_categories").delete().eq("id",t);if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["reward-categories"]})}})}function fRn(){const s=ts();return yt({mutationFn:async t=>{const{data:n,error:r}=await U.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 xRn(){const s=ts();return yt({mutationFn:async({id:t,...n})=>{const{data:r,error:a}=await U.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 gRn(){const s=ts();return yt({mutationFn:async t=>{const{error:n}=await U.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 yRn(s){const t=s.match(/\/storage\/v1\/object\/public\/([^/]+)\/(.+)$/);return t?{bucket:t[1],path:t[2]}:null}async function jDe(s,t){const n=yRn(s);if(n)try{const{data:r,error:a}=await U.storage.from(n.bucket).download(n.path);if(a){console.error("Error downloading file:",a),ae.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),ae.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),ae.error("Failed to download file")}}function MVt(){return ht({queryKey:["point-reward-settings"],queryFn:async()=>{const{data:s,error:t}=await U.from("point_reward_settings").select("*").order("action_name");if(t)throw t;return s}})}function vRn(){const s=ts();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 U.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 bRn(){const{user:s}=_s(),[t,n]=j.useState("items"),[r,a]=j.useState(!1),[i,l]=j.useState(null),[o,c]=j.useState(""),[d,u]=j.useState(""),[h,m]=j.useState(""),[p,x]=j.useState(null),[g,y]=j.useState(!1),[b,v]=j.useState(null),[N,C]=j.useState(""),[A,T]=j.useState(""),[P,M]=j.useState(null),[I,D]=j.useState(""),[B,q]=j.useState("file"),[W,V]=j.useState(""),[K,Q]=j.useState(""),[J,ce]=j.useState(""),[ue,ne]=j.useState(!0),[ee,le]=j.useState(null),[he,ve]=j.useState(!1),[ge,fe]=j.useState(!1),je=j.useRef(null),Ee=j.useRef(null),{data:Me,isLoading:De}=TVt(),{data:ze,isLoading:ke}=iRn(),{data:Xe,isLoading:Se}=cRn(),{data:Re,isLoading:Ae}=MVt(),Be=hRn(),qe=mRn(),Ke=pRn(),Ze=fRn(),Ue=xRn(),et=gRn(),Qe=vRn(),[Ge,nt]=j.useState({}),ft=_t=>{_t?(l(_t),c(_t.name),u(_t.description||""),m(_t.icon||"")):(l(null),c(""),u(""),m("")),a(!0)},lt=async()=>{if(!o.trim()){ae.error("Please enter a category name");return}try{i?(await qe.mutateAsync({id:i.id,name:o,description:d||null,icon:h||null}),ae.success("Category updated successfully")):(await Be.mutateAsync({name:o,description:d||null,icon:h||null,sort_order:((Me==null?void 0:Me.length)||0)+1}),ae.success("Category created successfully")),a(!1)}catch(_t){console.error("Error saving category:",_t),ae.error("Failed to save category")}},Mt=async()=>{if(p)try{await Ke.mutateAsync(p),ae.success("Category deleted successfully"),x(null)}catch(_t){console.error("Error deleting category:",_t),ae.error("Failed to delete category")}},Ft=_t=>{var Xs;_t?(v(_t),C(_t.name),T(_t.description||""),M(_t.category_id),D(_t.points_cost.toString()),q(_t.item_type),V(_t.file_url||""),Q(_t.preview_image_url||""),ce(((Xs=_t.max_quantity)==null?void 0:Xs.toString())||""),ne(_t.is_active)):(v(null),C(""),T(""),M(null),D(""),q("file"),V(""),Q(""),ce(""),ne(!0)),y(!0)},Ts=async(_t,Xs)=>{Xs==="file"?ve(!0):fe(!0);try{const rn=_t.name.split(".").pop(),Ps=`${Date.now()}-${Math.random().toString(36).substring(7)}.${rn}`,_n=`${Xs==="file"?"items":"previews"}/${Ps}`,{error:Zs}=await U.storage.from("reward-store").upload(_n,_t);if(Zs)throw Zs;const{data:{publicUrl:gr}}=U.storage.from("reward-store").getPublicUrl(_n);Xs==="file"?V(gr):Q(gr),ae.success("File uploaded successfully")}catch(rn){console.error("Error uploading file:",rn),ae.error("Failed to upload file")}finally{Xs==="file"?ve(!1):fe(!1)}},js=async()=>{if(!N.trim()){ae.error("Please enter an item name");return}if(!I||parseInt(I)<0){ae.error("Please enter a valid points cost");return}try{const _t={name:N,description:A||null,category_id:P,points_cost:parseInt(I),item_type:B,file_url:W||null,preview_image_url:K||null,max_quantity:J?parseInt(J):null,current_quantity:J?parseInt(J):null,is_active:ue,created_by:s==null?void 0:s.id};b?(await Ue.mutateAsync({id:b.id,..._t,current_quantity:b.max_quantity!==(J?parseInt(J):null)?J?parseInt(J):null:b.current_quantity}),ae.success("Item updated successfully")):(await Ze.mutateAsync(_t),ae.success("Item created successfully")),y(!1)}catch(_t){console.error("Error saving item:",_t),ae.error("Failed to save item")}},zt=async()=>{if(ee)try{await et.mutateAsync(ee),ae.success("Item deleted successfully"),le(null)}catch(_t){console.error("Error deleting item:",_t),ae.error("Failed to delete item")}},Nt=async(_t,Xs)=>{const rn=Ge[_t];if(rn===void 0||rn===Xs.toString())return;const Ps=parseInt(rn);if(isNaN(Ps)||Ps<0){ae.error("Please enter a valid positive number");return}try{await Qe.mutateAsync({id:_t,points:Ps}),ae.success("Points updated successfully"),nt(_n=>{const Zs={..._n};return delete Zs[_t],Zs})}catch(_n){console.error("Error updating points:",_n),ae.error("Failed to update points")}};return De||ke||Se||Ae?e.jsx(Ks,{title:"Reward Store",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(on,{className:"h-8 w-64"}),e.jsx(on,{className:"h-96"})]})}):e.jsxs(Ks,{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(_e,{children:e.jsxs(Oe,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(Tu,{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:(ze==null?void 0:ze.length)||0}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[(ze==null?void 0:ze.filter(_t=>_t.is_active).length)||0," active"]})]})}),e.jsx(_e,{children:e.jsxs(Oe,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(cv,{className:"h-4 w-4"}),e.jsx("span",{className:"text-xs font-medium",children:"Categories"})]}),e.jsx("p",{className:"text-2xl font-bold",children:(Me==null?void 0:Me.length)||0})]})}),e.jsx(_e,{children:e.jsxs(Oe,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(Qa,{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:[ze&&ze.length>0?Math.round(ze.reduce((_t,Xs)=>_t+Xs.points_cost,0)/ze.length):0," pts"]})]})})]}),e.jsxs(ua,{value:t,onValueChange:n,children:[e.jsxs(ha,{children:[e.jsx(Qt,{value:"items",children:"Items"}),e.jsx(Qt,{value:"categories",children:"Categories"}),e.jsx(Qt,{value:"purchases",children:"Purchases"}),e.jsx(Qt,{value:"point-settings",children:"Point Settings"})]}),e.jsx(Jt,{value:"items",className:"mt-4",children:e.jsxs(_e,{children:[e.jsxs(Bt,{className:"flex flex-row items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(Ut,{children:"Store Items"}),e.jsx(vr,{children:"Manage rewards that agents can purchase"})]}),e.jsxs($,{onClick:()=>Ft(),children:[e.jsx(sn,{className:"h-4 w-4 mr-2"}),"Add Item"]})]}),e.jsx(Oe,{children:!ze||ze.length===0?e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(Co,{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(Va,{children:[e.jsx(Ha,{children:e.jsxs(hn,{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(Ga,{children:ze.map(_t=>e.jsxs(hn,{children:[e.jsx(gt,{children:e.jsxs("div",{className:"flex items-center gap-3",children:[_t.preview_image_url?e.jsx("img",{src:_t.preview_image_url,alt:_t.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(Co,{className:"h-5 w-5 text-muted-foreground"})}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:_t.name}),e.jsx("p",{className:"text-xs text-muted-foreground line-clamp-1",children:_t.description||"No description"})]})]})}),e.jsx(gt,{children:_t.category?e.jsx($e,{variant:"outline",children:_t.category.name}):e.jsx("span",{className:"text-muted-foreground",children:"—"})}),e.jsx(gt,{className:"text-center",children:e.jsxs($e,{variant:"secondary",className:"font-bold",children:[e.jsx(Qa,{className:"h-3 w-3 mr-1"}),_t.points_cost]})}),e.jsx(gt,{className:"text-center",children:e.jsxs("div",{className:"flex items-center justify-center gap-1",children:[_t.item_type==="file"?e.jsx(Wr,{className:"h-4 w-4 text-muted-foreground"}):e.jsx(kc,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"text-xs capitalize",children:_t.item_type})]})}),e.jsx(gt,{className:"text-center",children:_t.max_quantity!==null?e.jsxs("span",{className:_t.current_quantity===0?"text-red-500":"",children:[_t.current_quantity,"/",_t.max_quantity]}):e.jsx("span",{className:"text-muted-foreground",children:"Unlimited"})}),e.jsx(gt,{className:"text-center",children:e.jsx($e,{variant:_t.is_active?"default":"secondary",children:_t.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($,{variant:"ghost",size:"sm",onClick:()=>Ft(_t),children:e.jsx(Ya,{className:"h-4 w-4"})}),e.jsx($,{variant:"ghost",size:"sm",onClick:()=>le(_t.id),children:e.jsx(Pn,{className:"h-4 w-4 text-destructive"})})]})})]},_t.id))})]})})]})}),e.jsx(Jt,{value:"categories",className:"mt-4",children:e.jsxs(_e,{children:[e.jsxs(Bt,{className:"flex flex-row items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(Ut,{children:"Categories"}),e.jsx(vr,{children:"Organize your store items into categories"})]}),e.jsxs($,{onClick:()=>ft(),children:[e.jsx(sn,{className:"h-4 w-4 mr-2"}),"Add Category"]})]}),e.jsx(Oe,{children:!Me||Me.length===0?e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(cv,{className:"h-12 w-12 mx-auto mb-4 opacity-50"}),e.jsx("p",{children:"No categories yet. Add your first category!"})]}):e.jsxs(Va,{children:[e.jsx(Ha,{children:e.jsxs(hn,{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(Ga,{children:Me.map(_t=>e.jsxs(hn,{children:[e.jsxs(gt,{className:"font-medium",children:[_t.icon&&e.jsx("span",{className:"mr-2",children:_t.icon}),_t.name]}),e.jsx(gt,{className:"text-muted-foreground",children:_t.description||"—"}),e.jsx(gt,{className:"text-center",children:(ze==null?void 0:ze.filter(Xs=>Xs.category_id===_t.id).length)||0}),e.jsx(gt,{className:"text-right",children:e.jsxs("div",{className:"flex items-center justify-end gap-1",children:[e.jsx($,{variant:"ghost",size:"sm",onClick:()=>ft(_t),children:e.jsx(Ya,{className:"h-4 w-4"})}),e.jsx($,{variant:"ghost",size:"sm",onClick:()=>x(_t.id),children:e.jsx(Pn,{className:"h-4 w-4 text-destructive"})})]})})]},_t.id))})]})})]})}),e.jsx(Jt,{value:"purchases",className:"mt-4",children:e.jsxs(_e,{children:[e.jsxs(Bt,{children:[e.jsxs(Ut,{className:"flex items-center gap-2",children:[e.jsx(ON,{className:"h-5 w-5"}),"Purchase History"]}),e.jsx(vr,{children:"View all reward redemptions by agents"})]}),e.jsx(Oe,{children:!Xe||Xe.length===0?e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(ON,{className:"h-12 w-12 mx-auto mb-4 opacity-50"}),e.jsx("p",{children:"No purchases yet."})]}):e.jsxs(Va,{children:[e.jsx(Ha,{children:e.jsxs(hn,{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(Ga,{children:Xe.map(_t=>{var Xs,rn,Ps,_n;return e.jsxs(hn,{children:[e.jsx(gt,{className:"text-muted-foreground",children:Hs(new Date(_t.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(Lo,{className:"h-4 w-4 text-muted-foreground"})}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:((Xs=_t.user)==null?void 0:Xs.name)||"Unknown"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:((rn=_t.user)==null?void 0:rn.email)||"—"})]})]})}),e.jsx(gt,{children:e.jsxs("div",{className:"flex items-center gap-2",children:[(Ps=_t.item)!=null&&Ps.preview_image_url?e.jsx("img",{src:_t.item.preview_image_url,alt:_t.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(Co,{className:"h-4 w-4 text-muted-foreground"})}),e.jsx("span",{children:((_n=_t.item)==null?void 0:_n.name)||"Deleted item"})]})}),e.jsx(gt,{className:"text-center",children:e.jsxs($e,{variant:"secondary",className:"font-bold",children:[e.jsx(Qa,{className:"h-3 w-3 mr-1"}),_t.points_spent]})})]},_t.id)})})]})})]})})]})]}),e.jsx(Os,{open:r,onOpenChange:a,children:e.jsxs(Rs,{children:[e.jsxs(Us,{children:[e.jsx(zs,{children:i?"Edit Category":"Add Category"}),e.jsx(Sr,{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(se,{htmlFor:"categoryName",children:"Name"}),e.jsx(be,{id:"categoryName",value:o,onChange:_t=>c(_t.target.value),placeholder:"e.g., Templates, Resources"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"categoryDescription",children:"Description"}),e.jsx(Is,{id:"categoryDescription",value:d,onChange:_t=>u(_t.target.value),placeholder:"Optional description..."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"categoryIcon",children:"Icon (emoji)"}),e.jsx(be,{id:"categoryIcon",value:h,onChange:_t=>m(_t.target.value),placeholder:"e.g., 📄, 🎁"})]})]}),e.jsxs(kr,{children:[e.jsx($,{variant:"outline",onClick:()=>a(!1),children:"Cancel"}),e.jsx($,{onClick:lt,disabled:Be.isPending||qe.isPending,children:Be.isPending||qe.isPending?"Saving...":"Save"})]})]})}),e.jsx(Os,{open:g,onOpenChange:y,children:e.jsxs(Rs,{className:"max-w-lg max-h-[90vh] overflow-y-auto",children:[e.jsxs(Us,{children:[e.jsx(zs,{children:b?"Edit Item":"Add Item"}),e.jsx(Sr,{children:b?"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(se,{htmlFor:"itemName",children:"Name *"}),e.jsx(be,{id:"itemName",value:N,onChange:_t=>C(_t.target.value),placeholder:"e.g., Premium Template Pack"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"itemDescription",children:"Description"}),e.jsx(Is,{id:"itemDescription",value:A,onChange:_t=>T(_t.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(se,{htmlFor:"itemCategory",children:"Category"}),e.jsxs(vs,{value:P||"none",onValueChange:_t=>M(_t==="none"?null:_t),children:[e.jsx(gs,{children:e.jsx(bs,{placeholder:"Select category"})}),e.jsxs(ys,{children:[e.jsx(Ye,{value:"none",children:"No category"}),Me==null?void 0:Me.map(_t=>e.jsxs(Ye,{value:_t.id,children:[_t.icon&&`${_t.icon} `,_t.name]},_t.id))]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"itemPointsCost",children:"Points Cost *"}),e.jsx(be,{id:"itemPointsCost",type:"number",min:"0",value:I,onChange:_t=>D(_t.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(se,{htmlFor:"itemType",children:"Type"}),e.jsxs(vs,{value:B,onValueChange:q,children:[e.jsx(gs,{children:e.jsx(bs,{})}),e.jsxs(ys,{children:[e.jsx(Ye,{value:"file",children:"File Download"}),e.jsx(Ye,{value:"link",children:"External Link"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"itemMaxQuantity",children:"Max Quantity"}),e.jsx(be,{id:"itemMaxQuantity",type:"number",min:"1",value:J,onChange:_t=>ce(_t.target.value),placeholder:"Leave empty for unlimited"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"File / Link URL"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(be,{value:W,onChange:_t=>V(_t.target.value),placeholder:B==="file"?"Upload a file or paste URL":"Paste external link"}),B==="file"&&e.jsxs(e.Fragment,{children:[e.jsx($,{type:"button",variant:"outline",size:"icon",onClick:()=>{var _t;return(_t=je.current)==null?void 0:_t.click()},disabled:he,children:e.jsx(si,{className:"h-4 w-4"})}),e.jsx("input",{ref:je,type:"file",className:"hidden",onChange:_t=>{var rn;const Xs=(rn=_t.target.files)==null?void 0:rn[0];Xs&&Ts(Xs,"file")}})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Preview Image"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(be,{value:K,onChange:_t=>Q(_t.target.value),placeholder:"Upload an image or paste URL"}),e.jsx($,{type:"button",variant:"outline",size:"icon",onClick:()=>{var _t;return(_t=Ee.current)==null?void 0:_t.click()},disabled:ge,children:e.jsx(Jl,{className:"h-4 w-4"})}),e.jsx("input",{ref:Ee,type:"file",accept:"image/*",className:"hidden",onChange:_t=>{var rn;const Xs=(rn=_t.target.files)==null?void 0:rn[0];Xs&&Ts(Xs,"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(Tn,{id:"itemIsActive",checked:ue,onCheckedChange:ne}),e.jsx(se,{htmlFor:"itemIsActive",children:"Active (visible to agents)"})]})]}),e.jsxs(kr,{children:[e.jsx($,{variant:"outline",onClick:()=>y(!1),children:"Cancel"}),e.jsx($,{onClick:js,disabled:Ze.isPending||Ue.isPending,children:Ze.isPending||Ue.isPending?"Saving...":"Save"})]})]})}),e.jsx(Ll,{open:!!p,onOpenChange:()=>x(null),children:e.jsxs(yl,{children:[e.jsxs(vl,{children:[e.jsx(_l,{children:"Delete Category"}),e.jsx(wl,{children:"Are you sure you want to delete this category? Items in this category will become uncategorized."})]}),e.jsxs(bl,{children:[e.jsx(jl,{children:"Cancel"}),e.jsx(fl,{onClick:Mt,className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Delete"})]})]})}),e.jsx(Ll,{open:!!ee,onOpenChange:()=>le(null),children:e.jsxs(yl,{children:[e.jsxs(vl,{children:[e.jsx(_l,{children:"Delete Item"}),e.jsx(wl,{children:"Are you sure you want to delete this item? This action cannot be undone."})]}),e.jsxs(bl,{children:[e.jsx(jl,{children:"Cancel"}),e.jsx(fl,{onClick:zt,className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Delete"})]})]})}),t==="point-settings"&&e.jsxs(_e,{className:"mt-4",children:[e.jsx(Bt,{children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(pc,{className:"h-5 w-5"}),e.jsxs("div",{children:[e.jsx(Ut,{children:"Point Reward Settings"}),e.jsx(vr,{children:"Configure how many points agents earn for various actions. Adjust these values to run double-points promotions."})]})]})}),e.jsx(Oe,{children:!Re||Re.length===0?e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(pc,{className:"h-12 w-12 mx-auto mb-4 opacity-50"}),e.jsx("p",{children:"No point settings configured."})]}):e.jsxs(Va,{children:[e.jsx(Ha,{children:e.jsxs(hn,{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(Ga,{children:Re.map(_t=>e.jsxs(hn,{children:[e.jsx(gt,{children:e.jsx("p",{className:"font-medium",children:_t.action_name})}),e.jsx(gt,{children:e.jsx("p",{className:"text-sm text-muted-foreground",children:_t.description})}),e.jsx(gt,{className:"text-center",children:e.jsx(be,{type:"number",min:"0",className:"w-20 mx-auto text-center",value:Ge[_t.id]??_t.points.toString(),onChange:Xs=>nt(rn=>({...rn,[_t.id]:Xs.target.value}))})}),e.jsx(gt,{className:"text-right",children:e.jsx($,{size:"sm",variant:"outline",disabled:Ge[_t.id]===void 0||Ge[_t.id]===_t.points.toString()||Qe.isPending,onClick:()=>Nt(_t.id,_t.points),children:e.jsx(Jo,{className:"h-4 w-4"})})})]},_t.id))})]})})]})]})}const Fvt=()=>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"})]}),zvt=[{value:"template",label:"Templates"},{value:"brand",label:"Brand Assets"},{value:"listing",label:"Listing Assets"},{value:"social",label:"Social Media"},{value:"general",label:"General"}];function _Rn(){const s=ts(),[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}=ht({queryKey:["canva-integration"],queryFn:async()=>{const{data:v,error:N}=await U.from("canva_integration").select("*").eq("is_active",!0).maybeSingle();if(N)throw N;return v}}),{data:h}=ht({queryKey:["brokerages-list"],queryFn:async()=>{const{data:v,error:N}=await U.from("brokerages").select("id, name").order("name");if(N)throw N;return v}}),{data:m}=ht({queryKey:["canva-brokerage-folders"],queryFn:async()=>{const{data:v,error:N}=await U.from("canva_brokerage_folders").select("*, brokerages(name)").order("sort_order");if(N)throw N;return v}}),p=async()=>{var v;n(!0);try{const{data:N}=await U.auth.getSession(),C=(v=N==null?void 0:N.session)==null?void 0:v.access_token;if(!C)throw new Error("Not authenticated");const P=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/canva-oauth",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${C}`,apikey:"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6InJlbHplamlzd25vdGlramd2amh6Iiwicm9sZSI6ImFub24iLCJpYXQiOjE3NjE5NTAzNDQsImV4cCI6MjA3NzUyNjM0NH0.dzIkIr_oFSbFE3oWS0ktIr83iKHHkZxt40Gc7SpC_mM"},body:JSON.stringify({action:"get_auth_url"})}),M=await P.json();if(!P.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){ae.error("Popup was blocked. Please allow popups for this site and try again."),n(!1);return}const D=q=>{var W,V;q.origin===window.location.origin&&(((W=q.data)==null?void 0:W.type)==="canva-oauth-success"?(window.removeEventListener("message",D),ae.success("Canva connected successfully!"),s.invalidateQueries({queryKey:["canva-integration"]}),n(!1)):((V=q.data)==null?void 0:V.type)==="canva-oauth-error"&&(window.removeEventListener("message",D),ae.error("Canva connection failed: "+(q.data.error||"Unknown error")),n(!1)))};window.addEventListener("message",D);const B=setInterval(()=>{I.closed&&(clearInterval(B),window.removeEventListener("message",D),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 C=(N==null?void 0:N.message)||"";C.includes("CANVA_CLIENT_ID")?ae.error("Canva app credentials not configured yet."):ae.error(C||"Failed to start Canva connection"),n(!1)}},x=yt({mutationFn:async v=>{var I;const{data:N}=await U.auth.getSession(),C=(I=N==null?void 0:N.session)==null?void 0:I.access_token;if(!C)throw new Error("Not authenticated");const P=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/canva-oauth",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${C}`,apikey:"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6InJlbHplamlzd25vdGlramd2amh6Iiwicm9sZSI6ImFub24iLCJpYXQiOjE3NjE5NTAzNDQsImV4cCI6MjA3NzUyNjM0NH0.dzIkIr_oFSbFE3oWS0ktIr83iKHHkZxt40Gc7SpC_mM"},body:JSON.stringify({action:"disconnect",integrationId:v})}),M=await P.json();if(!P.ok||M!=null&&M.error)throw new Error((M==null?void 0:M.error)||"Failed to disconnect")},onSuccess:()=>{s.invalidateQueries({queryKey:["canva-integration"]}),ae.success("Canva disconnected")},onError:v=>{ae.error(v.message||"Failed to disconnect Canva")}}),g=yt({mutationFn:async v=>{const{error:N}=await U.from("canva_brokerage_folders").insert({brokerage_id:v.brokerage_id,folder_id:v.folder_id.trim(),folder_name:v.folder_name.trim(),folder_type:v.folder_type,description:v.description.trim()||null,sort_order:(m==null?void 0:m.length)||0});if(N)throw N},onSuccess:()=>{s.invalidateQueries({queryKey:["canva-brokerage-folders"]}),ae.success("Folder added"),l(!1),c({brokerage_id:"",folder_id:"",folder_name:"",folder_type:"template",description:""})},onError:()=>ae.error("Failed to add folder")}),y=yt({mutationFn:async v=>{const{error:N}=await U.from("canva_brokerage_folders").delete().eq("id",v);if(N)throw N},onSuccess:()=>{s.invalidateQueries({queryKey:["canva-brokerage-folders"]}),ae.success("Folder removed")},onError:()=>ae.error("Failed to remove folder")}),b=!!d;return e.jsxs(e.Fragment,{children:[e.jsxs(_e,{children:[e.jsx(Bt,{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(Fvt,{})}),e.jsxs("div",{children:[e.jsxs(Ut,{className:"text-lg flex items-center gap-2",children:["Canva Connect",b&&e.jsx($e,{variant:"default",className:"text-xs",children:"Connected"}),e.jsx($e,{variant:"outline",className:"text-xs",children:"Admin Only"})]}),e.jsx(vr,{children:"Auto-share brokerage asset folders with agents when they connect their Canva accounts."})]})]})})}),e.jsx(Oe,{children:e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-start gap-2 text-sm text-muted-foreground",children:[e.jsx(Ro,{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(Ro,{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(Ro,{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"})]}),b?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(Ll,{children:[e.jsx(_f,{asChild:!0,children:e.jsx($,{variant:"ghost",size:"icon",className:"text-destructive hover:text-destructive",children:e.jsx(Pn,{className:"h-4 w-4"})})}),e.jsxs(yl,{children:[e.jsxs(vl,{children:[e.jsx(_l,{children:"Disconnect Canva?"}),e.jsx(wl,{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(bl,{children:[e.jsx(jl,{children:"Cancel"}),e.jsx(fl,{onClick:()=>x.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(cv,{className:"h-4 w-4 text-primary"}),"Brokerage Folder Mappings",m&&m.length>0&&e.jsx($e,{variant:"secondary",className:"text-xs",children:m.length})]}),r?e.jsx(jg,{className:"h-4 w-4"}):e.jsx(_o,{className:"h-4 w-4"})]}),r&&e.jsxs("div",{className:"border-t p-3 space-y-2",children:[m&&m.length>0?m.map(v=>{var N,C;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:v.folder_name}),e.jsx($e,{variant:"outline",className:"text-xs shrink-0",children:((N=zvt.find(A=>A.value===v.folder_type))==null?void 0:N.label)||v.folder_type})]}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[(C=v.brokerages)==null?void 0:C.name," · ID: ",e.jsx("span",{className:"font-mono",children:v.folder_id})]})]}),e.jsx($,{variant:"ghost",size:"icon",className:"h-7 w-7 text-muted-foreground hover:text-destructive shrink-0 ml-2",onClick:()=>y.mutate(v.id),children:e.jsx(pr,{className:"h-3.5 w-3.5"})})]},v.id)}):e.jsx("p",{className:"text-sm text-muted-foreground text-center py-2",children:"No folders mapped yet"}),e.jsxs($,{variant:"outline",size:"sm",className:"w-full gap-1.5 mt-1",onClick:()=>l(!0),children:[e.jsx(sn,{className:"h-3.5 w-3.5"}),"Add Folder Mapping"]})]})]})]}):e.jsxs($,{className:"mt-4",onClick:p,disabled:t||u,children:[t?e.jsx(Wi,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx("div",{className:"mr-2",children:e.jsx(Fvt,{})}),"Connect Canva",e.jsx(ni,{className:"h-4 w-4 ml-2"})]})]})})]}),e.jsx(Os,{open:i,onOpenChange:l,children:e.jsxs(Rs,{children:[e.jsx(Us,{children:e.jsx(zs,{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(se,{children:"Brokerage"}),e.jsxs(vs,{value:o.brokerage_id,onValueChange:v=>c(N=>({...N,brokerage_id:v})),children:[e.jsx(gs,{children:e.jsx(bs,{placeholder:"Select a brokerage…"})}),e.jsx(ys,{children:h==null?void 0:h.map(v=>e.jsx(Ye,{value:v.id,children:v.name},v.id))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:"Canva Folder ID"}),e.jsx(be,{placeholder:"e.g. FABCdef123456",value:o.folder_id,onChange:v=>c(N=>({...N,folder_id:v.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(se,{children:"Folder Display Name"}),e.jsx(be,{placeholder:"e.g. Brand Templates 2024",value:o.folder_name,onChange:v=>c(N=>({...N,folder_name:v.target.value}))})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:"Folder Type"}),e.jsxs(vs,{value:o.folder_type,onValueChange:v=>c(N=>({...N,folder_type:v})),children:[e.jsx(gs,{children:e.jsx(bs,{})}),e.jsx(ys,{children:zvt.map(v=>e.jsx(Ye,{value:v.value,children:v.label},v.value))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs(se,{children:["Description ",e.jsx("span",{className:"text-muted-foreground",children:"(optional)"})]}),e.jsx(be,{placeholder:"What's in this folder?",value:o.description,onChange:v=>c(N=>({...N,description:v.target.value}))})]})]}),e.jsxs(kr,{children:[e.jsx($,{variant:"outline",onClick:()=>l(!1),children:"Cancel"}),e.jsxs($,{onClick:()=>g.mutate(o),disabled:!o.brokerage_id||!o.folder_id||!o.folder_name||g.isPending,children:[g.isPending?e.jsx(Wi,{className:"h-4 w-4 mr-2 animate-spin"}):null,"Add Folder"]})]})]})})]})}function wRn(){const s=Vn();return e.jsx(Ks,{children:e.jsxs("div",{className:"space-y-6 p-4 md:p-8",children:[e.jsx(hh,{title:"Integrations",description:"Manage platform-level service connections"}),e.jsxs(_e,{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(vd,{className:"h-6 w-6 text-primary"})}),e.jsxs("div",{children:[e.jsx("h3",{className:"font-semibold",children:"User Social Connections"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"See which agents have connected Facebook, Instagram, LinkedIn, and Google."})]})]}),e.jsxs($,{onClick:()=>s("/admin/social-connections"),children:["View ",e.jsx(ni,{className:"h-4 w-4 ml-1"})]})]}),e.jsx(_Rn,{}),e.jsx(kVt,{})]})})}const Bvt=s=>{const t="h-4 w-4";return s==="facebook"?e.jsx(jf,{className:t}):s==="instagram"?e.jsx(Qh,{className:t}):s==="linkedin"?e.jsx(kg,{className:t}):s==="google"?e.jsx(nn,{className:t}):null},jRn=s=>s?new Intl.DateTimeFormat("en-US",{timeZone:"America/New_York",year:"numeric",month:"short",day:"numeric"}).format(new Date(s)):"—";function NRn(){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 U.rpc("admin_get_social_connections");if(p){ae.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 x=m.get(p.user_id)||{name:p.user_name,email:p.user_email,platforms:new Set,count:0};x.platforms.add(p.platform),x.count+=1,m.set(p.user_id,x)}),Array.from(m.entries()).map(([p,x])=>({user_id:p,...x}))},[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(_e,{className:"p-4",children:[e.jsxs("div",{className:"text-sm text-muted-foreground capitalize flex items-center gap-2",children:[Bvt(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(be,{placeholder:"Search by user, email, page, or handle…",value:a,onChange:m=>i(m.target.value),className:"md:max-w-md"}),e.jsxs(vs,{value:l,onValueChange:o,children:[e.jsx(gs,{className:"md:w-48",children:e.jsx(bs,{placeholder:"All platforms"})}),e.jsxs(ys,{children:[e.jsx(Ye,{value:"all",children:"All platforms"}),e.jsx(Ye,{value:"facebook",children:"Facebook"}),e.jsx(Ye,{value:"instagram",children:"Instagram"}),e.jsx(Ye,{value:"linkedin",children:"LinkedIn"}),e.jsx(Ye,{value:"google",children:"Google"})]})]})]}),e.jsx(_e,{children:n?e.jsx("div",{className:"flex items-center justify-center p-12",children:e.jsx(Ht,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):e.jsxs(Va,{children:[e.jsx(Ha,{children:e.jsxs(hn,{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(Ga,{children:c.length===0?e.jsx(hn,{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(hn,{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:[Bvt(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($e,{variant:"destructive",className:"gap-1",children:[e.jsx(xo,{className:"h-3 w-3"})," Expired"]}):e.jsx($e,{children:"Active"}):e.jsx($e,{variant:"secondary",children:"Inactive"})}),e.jsx(gt,{className:"text-sm text-muted-foreground",children:jRn(m.created_at)})]},m.id)})})]})})]})})}const kRn={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 BG(s,t=18,n=10){return s.length<=t+n+3?s:`${s.slice(0,t)}…${s.slice(-n)}`}function SRn(){var B,q,W,V,K;const s=ts(),[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,x]=j.useState(null),[g,y]=j.useState(null),{data:b,isLoading:v}=ht({queryKey:["push-notification-settings"],queryFn:async()=>{const{data:Q,error:J}=await U.from("push_notification_settings").select("*").order("setting_key");if(J)throw J;return Q}}),{data:N,isLoading:C}=ht({queryKey:["push-subscription-stats"],queryFn:async()=>{const{count:Q,error:J}=await U.from("push_subscriptions").select("*",{count:"exact",head:!0});if(J)throw J;return{totalSubscriptions:Q||0}}}),A=yt({mutationFn:async({settingKey:Q,isEnabled:J})=>{const{error:ce}=await U.from("push_notification_settings").update({is_enabled:J}).eq("setting_key",Q);if(ce)throw ce},onSuccess:()=>{s.invalidateQueries({queryKey:["push-notification-settings"]}),ae.success("Notification setting updated")},onError:Q=>{ae.error("Failed to update setting: "+Q.message)}}),T=j.useMemo(()=>{var Q,J;return h.isSupported?`perm=${h.permission??"unknown"} · controller=${h.controllerPresent?"yes":"no"} · sw=${((Q=h.serviceWorker)==null?void 0:Q.activeState)??"unknown"} · sub=${(J=h.subscription)!=null&&J.endpoint?"yes":"no"}`:"Push not supported in this browser."},[h]);j.useEffect(()=>{let Q=!0;const J=async()=>{var ee,le,he,ve,ge,fe,je;const ue="serviceWorker"in navigator&&"PushManager"in window,ne={isSupported:ue,permission:typeof Notification<"u"?Notification.permission:void 0,controllerPresent:!!((ee=navigator.serviceWorker)!=null&&ee.controller)};if(!ue){Q&&m(ne);return}try{const{data:Ee,error:Me}=await U.functions.invoke("get-vapid-public-key",{body:{}});if(Me)throw Me;ne.vapidPublicKey=Ee==null?void 0:Ee.vapidPublicKey;const ze=(await navigator.serviceWorker.getRegistrations()).find(ke=>{var Se,Re,Ae;return(((Se=ke.active)==null?void 0:Se.scriptURL)||((Re=ke.waiting)==null?void 0:Re.scriptURL)||((Ae=ke.installing)==null?void 0:Ae.scriptURL)||"").includes("/sw.js")});if(ze){ne.pushWorkerScriptUrl=((le=ze.active)==null?void 0:le.scriptURL)||((he=ze.waiting)==null?void 0:he.scriptURL)||((ve=ze.installing)==null?void 0:ve.scriptURL),ne.serviceWorker={scope:ze.scope,activeState:(ge=ze.active)==null?void 0:ge.state};const ke=await ze.pushManager.getSubscription();if(ke){const Xe=ke.toJSON();ne.subscription={endpoint:Xe.endpoint,p256dh:(fe=Xe.keys)==null?void 0:fe.p256dh,auth:(je=Xe.keys)==null?void 0:je.auth}}}}catch(Ee){ne.error=(Ee==null?void 0:Ee.message)||String(Ee)}Q&&m(ne)};J();const ce=window.setInterval(J,4e3);return()=>{Q=!1,window.clearInterval(ce)}},[]);const P=async()=>{if(typeof Notification>"u"){ae.error("Notifications API not available in this browser.");return}try{if(Notification.permission!=="granted"&&await Notification.requestPermission()!=="granted"){ae.error("Notification permission not granted.");return}new Notification("Local notification test",{body:"If you see this, OS/browser notifications can display."}),ae.success("Triggered a local notification (not push).")}catch(Q){ae.error(`Local notification failed: ${(Q==null?void 0:Q.message)||String(Q)}`)}},M=async()=>{c(!0),x(null);try{const{data:Q,error:J}=await U.functions.invoke("send-push-notification",{body:{title:t,body:r,url:i}});if(J)throw J;x({sent:Q==null?void 0:Q.sent,failed:Q==null?void 0:Q.failed,expiredCleaned:Q==null?void 0:Q.expiredCleaned,vapidPublicKey:Q==null?void 0:Q.vapidPublicKey}),(Q==null?void 0:Q.sent)>0?ae.success(`Test notification sent to ${Q.sent} subscriber(s)`):(Q==null?void 0:Q.failed)>0?ae.warning(`Notification failed for ${Q.failed} subscriber(s). ${Q.expired||0} expired subscriptions cleaned up.`):ae.info("No active subscriptions to send to")}catch(Q){console.error("Error sending test notification:",Q),x({error:(Q==null?void 0:Q.message)||String(Q)}),ae.error("Failed to send test notification: "+(Q.message||"Unknown error"))}finally{c(!1)}},I=async()=>{u(!0),y(null);try{const{data:Q,error:J}=await U.functions.invoke("generate-vapid-keys",{body:{}});if(J)throw J;const ce=Q==null?void 0:Q.publicKey,ue=Q==null?void 0:Q.privateKey;if(!ce||!ue)throw new Error("generate-vapid-keys did not return keys");y({publicKey:ce,privateKey:ue}),ae.success("Generated new VAPID keys. Update backend secrets, then clear + re-subscribe.")}catch(Q){console.error("Error generating VAPID keys:",Q),ae.error("Failed to generate VAPID keys: "+((Q==null?void 0:Q.message)||"Unknown error"))}finally{u(!1)}},D=yt({mutationFn:async()=>{const{error:Q}=await U.from("push_subscriptions").delete().neq("id","00000000-0000-0000-0000-000000000000");if(Q)throw Q},onSuccess:()=>{ae.success("All subscriptions cleared. Users will need to re-enable notifications."),s.invalidateQueries({queryKey:["push-subscription-stats"]})},onError:Q=>{ae.error("Failed to clear subscriptions: "+Q.message)}});return e.jsx(Ks,{title:"Notification Settings",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(hh,{title:"Notification Settings",description:"Manage push notifications and test the notification system"}),e.jsxs(_e,{children:[e.jsxs(Bt,{children:[e.jsxs(Ut,{className:"flex items-center gap-2",children:[e.jsx(qn,{className:"h-5 w-5"}),"Push Notification Subscribers"]}),e.jsx(vr,{children:"Current active push notification subscriptions"})]}),e.jsx(Oe,{children:e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx("div",{className:"text-4xl font-bold",children:C?"...":(N==null?void 0:N.totalSubscriptions)||0}),e.jsx("div",{className:"text-sm text-muted-foreground",children:"active subscriptions"})]})})]}),e.jsxs(_e,{children:[e.jsxs(Bt,{children:[e.jsxs(Ut,{className:"flex items-center gap-2",children:[e.jsx(pc,{className:"h-5 w-5"}),"Notification Types"]}),e.jsx(vr,{children:"Control which types of push notifications are sent to users"})]}),e.jsx(Oe,{children:v?e.jsx("div",{className:"text-sm text-muted-foreground",children:"Loading settings..."}):e.jsx("div",{className:"space-y-4",children:b==null?void 0:b.map(Q=>{const J=kRn[Q.setting_key]||{label:Q.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:J.icon}),e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:J.label}),e.jsx("div",{className:"text-sm text-muted-foreground",children:Q.description})]})]}),e.jsx(Tn,{checked:Q.is_enabled,onCheckedChange:ce=>A.mutate({settingKey:Q.setting_key,isEnabled:ce}),disabled:A.isPending})]},Q.id)})})})]}),e.jsxs(_e,{children:[e.jsxs(Bt,{children:[e.jsxs(Ut,{className:"flex items-center gap-2",children:[e.jsx(Dx,{className:"h-5 w-5"}),"Send Test Notification"]}),e.jsx(vr,{children:"Send a test push notification to all subscribed users"})]}),e.jsxs(Oe,{className:"space-y-4",children:[e.jsxs("div",{className:"rounded-md border bg-muted/30 p-3 text-sm",children:[e.jsx("div",{className:"font-medium",children:"Client push debug"}),e.jsx("div",{className:"mt-1 text-muted-foreground",children: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?BG(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: ",(B=h.serviceWorker)!=null&&B.scope?BG(h.serviceWorker.scope,24,8):"none"]}),e.jsxs("div",{children:["active: ",((q=h.serviceWorker)==null?void 0:q.activeState)??"none"]})]})]}),e.jsxs("div",{className:"space-y-1 sm:col-span-2",children:[e.jsx("div",{className:"text-xs font-medium text-muted-foreground",children:"Current browser subscription"}),e.jsxs("div",{className:"rounded-md border bg-background p-2 font-mono text-xs",children:[e.jsxs("div",{children:["endpoint: ",(W=h.subscription)!=null&&W.endpoint?BG(h.subscription.endpoint,40,12):"none"]}),e.jsxs("div",{children:["p256dh: ",(V=h.subscription)!=null&&V.p256dh?BG(h.subscription.p256dh,22,10):"none"]}),e.jsxs("div",{children:["auth: ",(K=h.subscription)!=null&&K.auth?BG(h.subscription.auth,22,10):"none"]})]})]})]}),e.jsxs("div",{className:"mt-3 flex flex-wrap gap-2",children:[e.jsx($,{variant:"outline",onClick:P,children:"Local notification test"}),e.jsx($,{variant:"outline",onClick:()=>window.location.reload(),children:"Reload page"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"test-title",children:"Notification Title"}),e.jsx(be,{id:"test-title",value:t,onChange:Q=>n(Q.target.value),placeholder:"Enter notification title"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"test-body",children:"Notification Body"}),e.jsx(Is,{id:"test-body",value:r,onChange:Q=>a(Q.target.value),placeholder:"Enter notification message",rows:3})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"test-url",children:"Click URL (optional)"}),e.jsx(be,{id:"test-url",value:i,onChange:Q=>l(Q.target.value),placeholder:"/community or full URL"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Where users will be taken when they click the notification"})]}),e.jsxs($,{onClick:M,disabled:o||!t||!r,className:"w-full sm:w-auto",children:[e.jsx(Br,{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(_e,{children:[e.jsxs(Bt,{children:[e.jsxs(Ut,{className:"flex items-center gap-2 text-destructive",children:[e.jsx(Pn,{className:"h-5 w-5"}),"Subscription Maintenance"]}),e.jsx(vr,{children:"Clear all push subscriptions if VAPID keys were changed or subscriptions are invalid"})]}),e.jsxs(Oe,{className:"space-y-4",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"If you've recently updated the VAPID keys, existing subscriptions will no longer work. Use this to clear all subscriptions so users can re-subscribe with the new keys."}),e.jsxs($,{variant:"destructive",onClick:()=>D.mutate(),disabled:D.isPending,children:[e.jsx(Pn,{className:"h-4 w-4 mr-2"}),D.isPending?"Clearing...":"Clear All Subscriptions"]}),e.jsxs("div",{className:"rounded-md border bg-muted/30 p-3 text-sm",children:[e.jsx("div",{className:"font-medium",children:"VAPID key rotation helper"}),e.jsx("div",{className:"mt-1 text-muted-foreground",children:"If you suspect the backend public/private keys don’t match, generate a fresh pair, update backend secrets, then clear subscriptions and have users re-enable push."}),e.jsx("div",{className:"mt-3 flex flex-wrap gap-2",children:e.jsx($,{variant:"outline",onClick:I,disabled:d,children:d?"Generating…":"Generate VAPID keys"})}),g&&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:g.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:g.privateKey})]})]})]})]})]})]})})}function CRn(){const{toast:s}=gi(),[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}=Iee("presentation_count","desc"),h=u(t,{name:x=>{var g;return((g=x.name)==null?void 0:g.toLowerCase())||""},presentations:x=>x.presentation_count,views:x=>x.total_views,leads:x=>x.total_leads,cta_clicks:x=>x.total_cta_clicks,conversion:x=>x.total_views>0?x.total_leads/x.total_views*100:0});j.useEffect(()=>{m()},[]);const m=async()=>{try{l(!0);const{data:x,error:g}=await U.rpc("get_admin_presentation_stats");if(g)throw g;if(!x||x.length===0){l(!1);return}const y=x.map(A=>A.owner_user_id),{data:b,error:v}=await U.from("profiles").select("id, name, email, avatar_url").in("id",y);if(v)throw v;const N=new Map((b==null?void 0:b.map(A=>[A.id,A]))||[]),C=x.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(C),n(C),a({totalPresentations:C.reduce((A,T)=>A+T.presentation_count,0),totalViews:C.reduce((A,T)=>A+T.total_views,0),totalLeads:C.reduce((A,T)=>A+T.total_leads,0),totalCtaClicks:C.reduce((A,T)=>A+T.total_cta_clicks,0),agentsUsing:C.length})}catch(x){console.error("Error loading presentation stats:",x),s({title:"Error",description:"Failed to load presentation analytics",variant:"destructive"})}finally{l(!1)}},p=[{label:"Agents Using",value:r.agentsUsing,icon:qn,color:"text-blue-600"},{label:"Total Presentations",value:r.totalPresentations,icon:by,color:"text-violet-600"},{label:"Total Views",value:r.totalViews,icon:ga,color:"text-emerald-600"},{label:"Total Leads",value:r.totalLeads,icon:il,color:"text-amber-600"},{label:"CTA Clicks",value:r.totalCtaClicks,icon:uu,color:"text-rose-600"}];return e.jsx(Ks,{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(x=>e.jsxs(_e,{children:[e.jsxs(Bt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Ut,{className:"text-sm font-medium",children:x.label}),e.jsx(x.icon,{className:`h-4 w-4 ${x.color}`})]}),e.jsx(Oe,{children:i?e.jsx(on,{className:"h-8 w-16"}):e.jsx("div",{className:"text-2xl font-bold",children:x.value.toLocaleString()})})]},x.label))}),e.jsxs(_e,{children:[e.jsx(Bt,{children:e.jsxs(Ut,{className:"flex items-center gap-2",children:[e.jsx(Il,{className:"h-5 w-5"}),"Agent Breakdown"]})}),e.jsx(Oe,{children:i?e.jsx("div",{className:"space-y-3",children:[...Array(5)].map((x,g)=>e.jsx(on,{className:"h-12 w-full"},g))}):t.length===0?e.jsx("p",{className:"text-muted-foreground text-center py-8",children:"No presentations created yet."}):e.jsxs(Va,{children:[e.jsx(Ha,{children:e.jsxs(hn,{children:[e.jsx(Ku,{sortKey:"name",currentSortKey:o,currentDirection:c,onSort:d,children:"Agent"}),e.jsx(Ku,{sortKey:"presentations",currentSortKey:o,currentDirection:c,onSort:d,className:"text-center",children:"Presentations"}),e.jsx(Ku,{sortKey:"views",currentSortKey:o,currentDirection:c,onSort:d,className:"text-center",children:"Views"}),e.jsx(Ku,{sortKey:"leads",currentSortKey:o,currentDirection:c,onSort:d,className:"text-center",children:"Leads"}),e.jsx(Ku,{sortKey:"cta_clicks",currentSortKey:o,currentDirection:c,onSort:d,className:"text-center",children:"CTA Clicks"}),e.jsx(Ku,{sortKey:"conversion",currentSortKey:o,currentDirection:c,onSort:d,className:"text-center",children:"Conversion"})]})}),e.jsx(Ga,{children:h.map(x=>{var y,b;const g=x.total_views>0?(x.total_leads/x.total_views*100).toFixed(1):"0.0";return e.jsxs(hn,{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:x.avatar_url?e.jsx("img",{src:x.avatar_url,alt:"",className:"h-full w-full object-cover"}):e.jsx("span",{className:"text-xs font-medium text-muted-foreground",children:((b=(y=x.name)==null?void 0:y.charAt(0))==null?void 0:b.toUpperCase())||"?"})}),e.jsxs("div",{children:[e.jsx("div",{className:"font-medium text-sm",children:x.name}),e.jsx("div",{className:"text-xs text-muted-foreground",children:x.email})]})]})}),e.jsx(gt,{className:"text-center font-medium",children:x.presentation_count}),e.jsx(gt,{className:"text-center",children:x.total_views.toLocaleString()}),e.jsx(gt,{className:"text-center",children:x.total_leads>0?e.jsx($e,{variant:"secondary",children:x.total_leads}):e.jsx("span",{className:"text-muted-foreground",children:"0"})}),e.jsx(gt,{className:"text-center",children:x.total_cta_clicks}),e.jsx(gt,{className:"text-center",children:e.jsxs("span",{className:Number(g)>0?"text-emerald-600 font-medium":"text-muted-foreground",children:[g,"%"]})})]},x.owner_user_id)})})]})})]})]})})}const NDe=s=>s?new Intl.DateTimeFormat("en-US",{timeZone:"America/New_York",month:"short",day:"numeric",year:"numeric"}).format(new Date(s)):"—",ARn=s=>s==null?"—":`$${Number(s).toLocaleString("en-US",{maximumFractionDigits:0})}`;function ERn(){const{toast:s}=gi(),[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=[],b=1e3;for(let C=0;;C+=b){const{data:A,error:T}=await U.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(C,C+b-1);if(T)throw T;if(y.push(...A??[]),!A||A.lengthC.owner_user_id))),N={};for(let C=0;C{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 g=Date.now(),y=g-7*24*60*60*1e3,b=g-30*24*60*60*1e3;return{total:r.length,generated:r.filter(v=>!!v.last_generated_at).length,agents:new Set(r.map(v=>v.owner_user_id)).size,thisWeek:r.filter(v=>new Date(v.created_at).getTime()>=y).length,thisMonth:r.filter(v=>new Date(v.created_at).getTime()>=b).length}},[r]),u=j.useMemo(()=>{const g=new Map;return r.forEach(y=>{const b=i[y.owner_user_id],v=g.get(y.owner_user_id)??{user_id:y.owner_user_id,name:(b==null?void 0:b.name)??"Unknown",email:(b==null?void 0:b.email)??"",total:0,generated:0,last_activity:y.updated_at};v.total+=1,y.last_generated_at&&(v.generated+=1),new Date(y.updated_at)>new Date(v.last_activity)&&(v.last_activity=y.updated_at),g.set(y.owner_user_id,v)}),Array.from(g.values()).sort((y,b)=>b.total-y.total)},[r,i]),h=o.trim().toLowerCase(),m=h?u.filter(g=>g.name.toLowerCase().includes(h)||g.email.toLowerCase().includes(h)):u,p=h?r.filter(g=>{const y=i[g.owner_user_id];return(g.title??"").toLowerCase().includes(h)||(g.property_address_line1??"").toLowerCase().includes(h)||(g.city??"").toLowerCase().includes(h)||((y==null?void 0:y.name)??"").toLowerCase().includes(h)||((y==null?void 0:y.email)??"").toLowerCase().includes(h)}):r,x=[{label:"Total presentations",value:d.total,icon:Wr,sub:"All time"},{label:"Agents using it",value:d.agents,icon:qn,sub:"Created at least one"},{label:"PDFs generated",value:d.generated,icon:dn,sub:"Rendered at least once"},{label:"Created last 30 days",value:d.thisMonth,icon:Xu,sub:`${d.thisWeek} in last 7 days`}];return e.jsx(Ks,{title:"Listing Presentation Studio",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(hh,{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(g=>e.jsx(on,{className:"h-28 w-full"},g))}):e.jsx("div",{className:"grid gap-4 md:grid-cols-2 lg:grid-cols-4",children:x.map(g=>e.jsxs(_e,{children:[e.jsxs(Bt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Ut,{className:"text-sm font-medium",children:g.label}),e.jsx(g.icon,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Oe,{children:[e.jsx("div",{className:"text-2xl font-bold",children:g.value}),e.jsx("p",{className:"text-xs text-muted-foreground",children:g.sub})]})]},g.label))}),e.jsxs("div",{className:"relative max-w-md",children:[e.jsx(Vr,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),e.jsx(be,{className:"pl-9",placeholder:"Search agents, addresses, titles...",value:o,onChange:g=>c(g.target.value)})]}),e.jsxs(ua,{defaultValue:"agents",className:"space-y-4",children:[e.jsxs(ha,{children:[e.jsxs(Qt,{value:"agents",children:["By agent (",m.length,")"]}),e.jsxs(Qt,{value:"all",children:["All presentations (",p.length,")"]})]}),e.jsx(Jt,{value:"agents",children:e.jsx(_e,{children:e.jsx(Oe,{className:"p-0",children:e.jsxs(Va,{children:[e.jsx(Ha,{children:e.jsxs(hn,{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(Ga,{children:[m.map(g=>e.jsxs(hn,{children:[e.jsxs(gt,{children:[e.jsx("div",{className:"font-medium",children:g.name}),e.jsx("div",{className:"text-xs text-muted-foreground",children:g.email})]}),e.jsx(gt,{className:"text-right font-semibold",children:g.total}),e.jsx(gt,{className:"text-right",children:g.generated}),e.jsx(gt,{children:NDe(g.last_activity)})]},g.user_id)),!t&&m.length===0&&e.jsx(hn,{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(Jt,{value:"all",children:e.jsx(_e,{children:e.jsx(Oe,{className:"p-0",children:e.jsxs(Va,{children:[e.jsx(Ha,{children:e.jsxs(hn,{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(Ga,{children:[p.slice(0,300).map(g=>{var y,b;return e.jsxs(hn,{children:[e.jsx(gt,{className:"font-medium",children:g.title||"Untitled"}),e.jsxs(gt,{children:[e.jsx("div",{children:((y=i[g.owner_user_id])==null?void 0:y.name)??"Unknown"}),e.jsx("div",{className:"text-xs text-muted-foreground",children:((b=i[g.owner_user_id])==null?void 0:b.email)??""})]}),e.jsx(gt,{className:"text-sm",children:[g.property_address_line1,g.city,g.state].filter(Boolean).join(", ")||"—"}),e.jsx(gt,{children:ARn(g.list_price)}),e.jsx(gt,{children:e.jsx($e,{variant:g.last_generated_at?"default":"secondary",children:g.last_generated_at?"Generated":g.status||"Draft"})}),e.jsx(gt,{children:NDe(g.created_at)}),e.jsx(gt,{children:NDe(g.last_generated_at)})]},g.id)}),!t&&p.length===0&&e.jsx(hn,{children:e.jsx(gt,{colSpan:7,className:"py-10 text-center text-muted-foreground",children:"No presentations found."})})]})]})})})})]})]})})}const aZ="listing_revival";function TRn(){const{user:s,loading:t,isAdmin:n}=_s(),{data:r}=ht({queryKey:["feature-entitlement",aZ,s==null?void 0:s.id],enabled:!!s&&!n,staleTime:5*60*1e3,queryFn:async()=>{const{data:a,error:i}=await U.from("feature_entitlements").select("enabled, expires_at, tier").eq("user_id",s.id).eq("feature_key",aZ).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 MRn=s=>s?new Intl.DateTimeFormat("en-US",{timeZone:"America/New_York",month:"short",day:"numeric",year:"numeric"}).format(new Date(s)):"—";function LRn(){var u,h;const{user:s}=_s(),t=ts(),[n,r]=j.useState(""),a=ht({queryKey:["lr-admin-stats"],queryFn:async()=>{const{data:m,error:p}=await U.rpc("get_admin_listing_revival_stats");if(p)throw p;return m??[]}}),i=ht({queryKey:["lr-admin-members",n],queryFn:async()=>{let m=U.from("profiles").select("id, name, email").order("name").limit(200);if(n.trim()){const v=`%${n.trim()}%`;m=m.or(`email.ilike.${v},name.ilike.${v}`)}const{data:p,error:x}=await m;if(x)throw x;const g=(p??[]).map(v=>v.id),{data:y}=await U.from("feature_entitlements").select("user_id, enabled, tier").eq("feature_key",aZ).in("user_id",g.length?g:["00000000-0000-0000-0000-000000000000"]),b=new Map((y??[]).map(v=>[v.user_id,v]));return(p??[]).map(v=>{var N;return{user_id:v.id,name:v.name,email:v.email,enabled:!!((N=b.get(v.id))!=null&&N.enabled)}})}}),l=yt({mutationFn:async({userId:m,enabled:p})=>{const{error:x}=await U.from("feature_entitlements").upsert({user_id:m,feature_key:aZ,enabled:p,tier:"member",enabled_by:s.id,enabled_at:new Date().toISOString()},{onConflict:"user_id,feature_key"});if(x)throw x;await U.from("feature_entitlement_audit").insert({feature_key:aZ,target_user_id:m,action:p?"grant":"revoke",performed_by:s.id})},onSuccess:(m,p)=>{t.invalidateQueries({queryKey:["lr-admin-members"]}),ae.success(p.enabled?"Access granted":"Access revoked")},onError:m=>ae.error(m.message)}),o=ht({queryKey:["lr-admin-stat-profiles",(a.data??[]).length],enabled:!!((u=a.data)!=null&&u.length),queryFn:async()=>{const m=(a.data??[]).map(x=>x.owner_user_id),{data:p}=await U.from("profiles").select("id, name, email").in("id",m);return new Map((p??[]).map(x=>[x.id,x]))}}),c=j.useMemo(()=>{const m=a.data??[];return{agents:m.length,campaigns:m.reduce((p,x)=>p+Number(x.campaign_count),0),leads:m.reduce((p,x)=>p+Number(x.lead_count),0),hot:m.reduce((p,x)=>p+Number(x.hot_lead_count),0)}},[a.data]),d=[{label:"Agents using it",value:c.agents,icon:qn},{label:"Campaigns built",value:c.campaigns,icon:dn},{label:"Seller leads",value:c.leads,icon:w0},{label:"Hot leads",value:c.hot,icon:yd}];return e.jsxs(Ks,{title:"Listing Revival Admin",children:[e.jsx(hh,{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(_e,{children:e.jsxs(Oe,{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(ua,{defaultValue:"usage",className:"mt-6",children:[e.jsxs(ha,{children:[e.jsx(Qt,{value:"usage",children:"Agent usage"}),e.jsx(Qt,{value:"access",children:"Access"})]}),e.jsx(Jt,{value:"usage",className:"mt-4",children:e.jsxs(_e,{children:[e.jsx(Bt,{children:e.jsx(Ut,{className:"text-base",children:"Usage by agent"})}),e.jsx(Oe,{children:a.isLoading?e.jsx("div",{className:"space-y-2",children:[0,1,2].map(m=>e.jsx(on,{className:"h-10 w-full"},m))}):(h=a.data)!=null&&h.length?e.jsxs(Va,{children:[e.jsx(Ha,{children:e.jsxs(hn,{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(Ga,{children:[...a.data].sort((m,p)=>Number(p.campaign_count)-Number(m.campaign_count)).map(m=>{var x;const p=(x=o.data)==null?void 0:x.get(m.owner_user_id);return e.jsxs(hn,{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($e,{className:"bg-red-500/15 text-red-600 hover:bg-red-500/15",children:m.hot_lead_count}):e.jsx("span",{className:"text-muted-foreground",children:"0"})}),e.jsx(gt,{className:"text-right tabular-nums",children:m.event_count}),e.jsx(gt,{className:"text-right text-sm text-muted-foreground",children:MRn(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(Jt,{value:"access",className:"mt-4",children:e.jsxs(_e,{children:[e.jsx(Bt,{children:e.jsx(Ut,{className:"text-base",children:"Who can use Listing Revival"})}),e.jsxs(Oe,{className:"space-y-4",children:[e.jsxs("div",{className:"relative max-w-sm",children:[e.jsx(Vr,{className:"h-4 w-4 absolute left-3 top-1/2 -translate-y-1/2 text-muted-foreground"}),e.jsx(be,{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(on,{className:"h-10 w-full"},m))}):e.jsxs(Va,{children:[e.jsx(Ha,{children:e.jsxs(hn,{children:[e.jsx(Lt,{children:"Agent"}),e.jsx(Lt,{children:"Email"}),e.jsx(Lt,{className:"text-right",children:"Access"})]})}),e.jsx(Ga,{children:(i.data??[]).map(m=>e.jsxs(hn,{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(Tn,{checked:m.enabled,onCheckedChange:p=>l.mutate({userId:m.user_id,enabled:p})})})]},m.user_id))})]})]})]})})]})]})}function PRn(){const{toast:s}=gi(),[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 U.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 U.from("profiles").select("id, name, email, avatar_url").in("id",h);if(p)throw p;const x=new Map((m==null?void 0:m.map(y=>[y.id,y]))||[]),g=d.map(y=>{const b=x.get(y.agent_id);return{agent_id:y.agent_id,name:(b==null?void 0:b.name)||"Unknown",email:(b==null?void 0:b.email)||"",avatar_url:(b==null?void 0:b.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)}});g.sort((y,b)=>b.total_visitors-y.total_visitors),n(g),a({totalOpenHouses:g.reduce((y,b)=>y+b.open_house_count,0),totalVisitors:g.reduce((y,b)=>y+b.total_visitors,0),totalLeads:g.reduce((y,b)=>y+b.total_leads,0),activeOpenHouses:g.reduce((y,b)=>y+b.active_count,0),agentsUsing:g.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:qn,color:"text-blue-600"},{label:"Total Open Houses",value:r.totalOpenHouses,icon:sa,color:"text-violet-600"},{label:"Active Now",value:r.activeOpenHouses,icon:Ro,color:"text-emerald-600"},{label:"Total Visitors",value:r.totalVisitors,icon:ga,color:"text-amber-600"},{label:"Leads Created",value:r.totalLeads,icon:il,color:"text-rose-600"}];return e.jsx(Ks,{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(_e,{children:[e.jsxs(Bt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Ut,{className:"text-sm font-medium",children:d.label}),e.jsx(d.icon,{className:`h-4 w-4 ${d.color}`})]}),e.jsx(Oe,{children:i?e.jsx(on,{className:"h-8 w-16"}):e.jsx("div",{className:"text-2xl font-bold",children:d.value.toLocaleString()})})]},d.label))}),e.jsxs(_e,{children:[e.jsx(Bt,{children:e.jsxs(Ut,{className:"flex items-center gap-2",children:[e.jsx(Il,{className:"h-5 w-5"}),"Agent Breakdown"]})}),e.jsx(Oe,{children:i?e.jsx("div",{className:"space-y-3",children:[...Array(5)].map((d,u)=>e.jsx(on,{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(Va,{children:[e.jsx(Ha,{children:e.jsxs(hn,{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(Ga,{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(hn,{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($e,{variant:"secondary",className:"bg-emerald-100 text-emerald-700",children:d.active_count}):e.jsx("span",{className:"text-muted-foreground",children:"0"})}),e.jsx(gt,{className:"text-center",children:d.total_visitors.toLocaleString()}),e.jsx(gt,{className:"text-center",children:d.total_leads>0?e.jsx($e,{variant:"secondary",children:d.total_leads}):e.jsx("span",{className:"text-muted-foreground",children:"0"})}),e.jsx(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 IRn(){const[s]=oc(),t=Vn(),[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"),ae.error("Failed to connect: "+(u||d));return}if(!c){r("error"),l("No authorization code received"),ae.error("Failed to connect: No authorization code");return}try{const{data:m,error:p}=await U.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 x=p.message||"Failed to connect accounts";try{const g=p.context;if(g&&typeof g.json=="function"){const y=await g.json();y!=null&&y.error&&(x=y.error)}}catch{}throw new Error(x)}if(m!=null&&m.success)r("success"),l(m.message||"Accounts connected successfully!"),ae.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"),ae.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(_e,{className:"w-full max-w-md",children:[e.jsxs(Bt,{className:"text-center",children:[e.jsxs("div",{className:"mx-auto mb-4",children:[n==="loading"&&e.jsx(Ht,{className:"h-12 w-12 animate-spin text-primary"}),n==="success"&&e.jsx(Ro,{className:"h-12 w-12 text-green-500"}),n==="error"&&e.jsx($d,{className:"h-12 w-12 text-destructive"})]}),e.jsxs(Ut,{children:[n==="loading"&&"Connecting...",n==="success"&&"Connected!",n==="error"&&"Connection Failed"]}),e.jsx(vr,{children:i})]}),e.jsx(Oe,{className:"flex justify-center",children:e.jsx($,{onClick:()=>t("/admin/integrations"),children:n==="success"?"View Integrations":"Back to Integrations"})})]})})}function DRn(){const s=ts(),[t,n]=j.useState(""),[r,a]=j.useState(""),[i,l]=j.useState([]),o=j.useRef(null),{data:c,isLoading:d}=ht({queryKey:["prospect-emails"],queryFn:async()=>{const{data:v,error:N}=await U.from("prospect_emails").select("*").order("sent_at",{ascending:!1});if(N)throw N;return v}}),u=(c==null?void 0:c.filter(v=>v.status==="live_lead"))||[],h={total:(c==null?void 0:c.length)||0,sent:(c==null?void 0:c.filter(v=>v.status==="sent").length)||0,converted:(c==null?void 0:c.filter(v=>v.status==="converted").length)||0,liveLeads:u.length,conversionRate:c!=null&&c.length?Math.round(c.filter(v=>v.status==="converted").length/c.length*100):0},m=yt({mutationFn:async v=>{const{data:N,error:C}=await U.functions.invoke("send-prospect-email",{body:{emails:v}});if(C)throw C;return N},onSuccess:v=>{s.invalidateQueries({queryKey:["prospect-emails"]}),ae.success(`${v.sent} email${v.sent>1?"s":""} sent successfully!`),n(""),a(""),l([])},onError:v=>{ae.error("Failed to send: "+v.message)}}),p=yt({mutationFn:async()=>{var A,T;const{data:{user:v}}=await U.auth.getUser();if(!(v!=null&&v.email))throw new Error("Could not get your email");const{data:N,error:C}=await U.functions.invoke("send-prospect-email",{body:{emails:[{email:v.email,first_name:(T=(A=v.user_metadata)==null?void 0:A.name)==null?void 0:T.split(" ")[0]}],test_mode:!0}});if(C)throw C;return N},onSuccess:()=>{ae.success("Test email sent to your inbox!")},onError:v=>{ae.error("Failed to send test: "+v.message)}}),x=yt({mutationFn:async()=>{const{data:v,error:N}=await U.functions.invoke("send-prospect-email",{body:{mode:"live_leads"}});if(N)throw N;return v},onSuccess:v=>{s.invalidateQueries({queryKey:["prospect-emails"]}),ae.success(`${v.sent} live lead invite${v.sent===1?"":"s"} sent!`)},onError:v=>{ae.error("Failed to send live lead invites: "+v.message)}}),g=()=>{if(!t.trim()){ae.error("Please enter an email address");return}if(c==null?void 0:c.find(N=>N.email.toLowerCase()===t.trim().toLowerCase())){ae.error("This email has already been prospected");return}m.mutate([{email:t.trim(),first_name:r.trim()||void 0}])},y=v=>{var A;const N=(A=v.target.files)==null?void 0:A[0];if(!N)return;const C=new FileReader;C.onload=T=>{var B,q;const M=((B=T.target)==null?void 0:B.result).split(` `).filter(W=>W.trim()),I=[],D=(q=M[0])!=null&&q.toLowerCase().includes("email")?1:0;for(let W=D;WJ.trim().replace(/"/g,"")),K=V[0],Q=V[1];K&&K.includes("@")&&I.push({email:K,first_name:Q||void 0})}l(I),ae.success(`${I.length} entries loaded from CSV`)},C.readAsText(N),o.current&&(o.current.value="")},b=()=>{if(i.length===0){ae.error("No entries to send");return}const v=new Set((c==null?void 0:c.map(C=>C.email.toLowerCase()))||[]),N=i.filter(C=>!v.has(C.email.toLowerCase()));if(N.length===0){ae.error("All emails have already been prospected");return}N.length0&&e.jsxs(_e,{className:"border-red-200/50 bg-red-500/[0.02]",children:[e.jsxs(Bt,{children:[e.jsxs(Ut,{className:"flex items-center gap-2",children:[e.jsx(Cg,{className:"h-5 w-5 text-red-600"}),"Live Event Leads",e.jsx($e,{variant:"secondary",className:"ml-2",children:h.liveLeads})]}),e.jsx(vr,{children:"These agents registered on a LevelUp Live page but haven't received a free trial invite yet."})]}),e.jsx(Oe,{children:e.jsxs($,{onClick:()=>x.mutate(),disabled:x.isPending,className:"gap-2",children:[x.isPending?e.jsx(Ht,{className:"h-4 w-4 animate-spin"}):e.jsx(Br,{className:"h-4 w-4"}),"Send free trial invite to all live leads"]})})]}),e.jsxs(_e,{children:[e.jsxs(Bt,{children:[e.jsxs(Ut,{className:"flex items-center gap-2",children:[e.jsx(Mu,{className:"h-5 w-5"}),"Send Prospect Email"]}),e.jsxs(vr,{className:"flex items-center justify-between",children:[e.jsx("span",{children:"Send a beautiful free trial invitation email to potential members"}),e.jsxs($,{variant:"outline",size:"sm",onClick:()=>p.mutate(),disabled:p.isPending,className:"gap-2 ml-4 shrink-0",children:[p.isPending?e.jsx(Ht,{className:"h-3 w-3 animate-spin"}):e.jsx(nn,{className:"h-3 w-3"}),"Send Test to Me"]})]})]}),e.jsx(Oe,{children:e.jsxs(ua,{defaultValue:"single",children:[e.jsxs(ha,{className:"mb-4",children:[e.jsxs(Qt,{value:"single",children:[e.jsx(Br,{className:"h-4 w-4 mr-2"}),"Single Send"]}),e.jsxs(Qt,{value:"bulk",children:[e.jsx(si,{className:"h-4 w-4 mr-2"}),"Bulk CSV"]})]}),e.jsx(Jt,{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(se,{htmlFor:"prospect-email",className:"sr-only",children:"Email"}),e.jsx(be,{id:"prospect-email",type:"email",placeholder:"agent@example.com",value:t,onChange:v=>n(v.target.value),onKeyDown:v=>v.key==="Enter"&&g()})]}),e.jsxs("div",{className:"w-full sm:w-48",children:[e.jsx(se,{htmlFor:"prospect-name",className:"sr-only",children:"First Name"}),e.jsx(be,{id:"prospect-name",placeholder:"First name (optional)",value:r,onChange:v=>a(v.target.value),onKeyDown:v=>v.key==="Enter"&&g()})]}),e.jsxs($,{onClick:g,disabled:m.isPending,className:"gap-2",children:[m.isPending?e.jsx(Ht,{className:"h-4 w-4 animate-spin"}):e.jsx(Br,{className:"h-4 w-4"}),"Send Invite"]})]})}),e.jsx(Jt,{value:"bulk",children:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("input",{ref:o,type:"file",accept:".csv",onChange:y,className:"hidden"}),e.jsxs($,{variant:"outline",onClick:()=>{var v;return(v=o.current)==null?void 0:v.click()},className:"gap-2",children:[e.jsx(Wr,{className:"h-4 w-4"}),"Upload CSV"]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Format: email, first_name (one per line)"})]}),i.length>0&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs($e,{variant:"secondary",className:"gap-1",children:[e.jsx(qn,{className:"h-3 w-3"}),i.length," entries ready"]}),e.jsxs($,{variant:"ghost",size:"sm",onClick:()=>l([]),children:[e.jsx(pr,{className:"h-4 w-4"}),"Clear"]})]}),e.jsxs("div",{className:"max-h-40 overflow-y-auto border rounded-lg p-3 bg-muted/30 text-sm font-mono space-y-1",children:[i.slice(0,20).map((v,N)=>e.jsxs("div",{className:"text-muted-foreground",children:[v.email,v.first_name?` — ${v.first_name}`:""]},N)),i.length>20&&e.jsxs("div",{className:"text-muted-foreground/60",children:["...and ",i.length-20," more"]})]}),e.jsxs($,{onClick:b,disabled:m.isPending,className:"gap-2",children:[m.isPending?e.jsx(Ht,{className:"h-4 w-4 animate-spin"}):e.jsx(Br,{className:"h-4 w-4"}),"Send ",i.length," Invites"]})]})]})})]})})]}),e.jsxs(_e,{children:[e.jsxs(Bt,{children:[e.jsxs(Ut,{className:"flex items-center gap-2",children:[e.jsx(nn,{className:"h-5 w-5"}),"Prospect Log"]}),e.jsx(vr,{children:"Track all sent invitations and their conversion status"})]}),e.jsx(Oe,{children:d?e.jsx("div",{className:"space-y-3",children:[...Array(5)].map((v,N)=>e.jsx(on,{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:"Converted"})]})}),e.jsx("tbody",{children:c.map(v=>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:v.email}),e.jsx("td",{className:"py-3 px-4 text-sm text-muted-foreground",children:v.first_name||"—"}),e.jsx("td",{className:"py-3 px-4 text-sm text-muted-foreground",children:Hs(new Date(v.sent_at),"MMM d, yyyy")}),e.jsx("td",{className:"py-3 px-4",children:v.status==="converted"?e.jsxs($e,{className:"bg-green-500/10 text-green-700 hover:bg-green-500/20 border-0",children:[e.jsx(Fr,{className:"h-3 w-3 mr-1"}),"Converted"]}):v.status==="live_lead"?e.jsxs($e,{className:"bg-red-500/10 text-red-700 hover:bg-red-500/20 border-0 gap-1",children:[e.jsx(Cg,{className:"h-3 w-3"}),"Live lead"]}):e.jsxs($e,{variant:"secondary",className:"gap-1",children:[e.jsx(Hr,{className:"h-3 w-3"}),"Sent"]})}),e.jsx("td",{className:"py-3 px-4 text-sm text-muted-foreground",children:v.converted_at?Hs(new Date(v.converted_at),"MMM d, yyyy"):"—"})]},v.id))})]})}):e.jsxs("div",{className:"text-center py-12",children:[e.jsx(Mu,{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 yte(s){const t=ts(),{toast:n}=gi(),r=ht({queryKey:["recruit-stages",s],queryFn:async()=>{if(!s)return[];const{data:c,error:d}=await U.from("recruit_pipeline_stages").select("*").eq("brokerage_id",s).order("sort_order");if(d)throw d;return c},enabled:!!s}),a=ht({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 U.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 U.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 U.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 U.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 U.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 RRn(s){const t=ts(),{toast:n}=gi(),r=ht({queryKey:["recruit-activities",s],queryFn:async()=>{if(!s)return[];const{data:i,error:l}=await U.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 U.auth.getUser();if(!l)throw new Error("Not authenticated");const{data:o,error:c}=await U.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 $vt=(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 LVt({open:s,onOpenChange:t,stages:n,defaultStageId:r,onSubmit:a,isSubmitting:i}){const[l,o]=j.useState($vt(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($vt(r,n)),t(!1)};return e.jsx(Os,{open:s,onOpenChange:t,children:e.jsxs(Rs,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsx(Us,{children:e.jsx(zs,{children:"Add Recruit Prospect"})}),e.jsxs("form",{onSubmit:d,className:"space-y-4",children:[e.jsxs(ua,{defaultValue:"basic",className:"w-full",children:[e.jsxs(ha,{className:"grid w-full grid-cols-4",children:[e.jsx(Qt,{value:"basic",children:"Basic Info"}),e.jsx(Qt,{value:"production",children:"Production"}),e.jsx(Qt,{value:"social",children:"Social & Web"}),e.jsx(Qt,{value:"personal",children:"Personal"})]}),e.jsxs(Jt,{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(se,{children:"First Name *"}),e.jsx(be,{required:!0,value:l.first_name,onChange:c("first_name")})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Last Name"}),e.jsx(be,{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(se,{children:"Email"}),e.jsx(be,{type:"email",value:l.email,onChange:c("email")})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Phone"}),e.jsx(be,{value:l.phone,onChange:c("phone")})]})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Current Brokerage"}),e.jsx(be,{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(se,{children:"License #"}),e.jsx(be,{value:l.license_number,onChange:c("license_number")})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Experience (years)"}),e.jsx(be,{type:"number",min:"0",value:l.experience_years,onChange:c("experience_years")})]})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Address"}),e.jsx(be,{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(se,{children:"City"}),e.jsx(be,{value:l.city,onChange:c("city")})]}),e.jsxs("div",{children:[e.jsx(se,{children:"State"}),e.jsx(be,{value:l.state,onChange:c("state")})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Zip"}),e.jsx(be,{value:l.zip_code,onChange:c("zip_code")})]})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Pipeline Stage"}),e.jsxs(vs,{value:l.stage_id,onValueChange:u=>o(h=>({...h,stage_id:u})),children:[e.jsx(gs,{children:e.jsx(bs,{})}),e.jsx(ys,{children:n.map(u=>e.jsx(Ye,{value:u.id,children:u.name},u.id))})]})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Referred By"}),e.jsx(be,{placeholder:"Who referred this prospect?",value:l.referred_by,onChange:c("referred_by")})]})]}),e.jsxs(Jt,{value:"production",className:"space-y-4 mt-4",children:[e.jsxs("div",{children:[e.jsx(se,{children:"Annual Production Volume"}),e.jsx(be,{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(se,{children:"Last Year Volume"}),e.jsx(be,{placeholder:"e.g. $8.2M",value:l.last_year_volume,onChange:c("last_year_volume")})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Last Year Transactions"}),e.jsx(be,{type:"number",min:"0",placeholder:"e.g. 24",value:l.last_year_transactions,onChange:c("last_year_transactions")})]})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Avg Sale Price"}),e.jsx(be,{placeholder:"e.g. $350K",value:l.avg_sale_price,onChange:c("avg_sale_price")})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Specialties / Niche"}),e.jsx(be,{placeholder:"e.g. Luxury, First-time buyers, Investment",value:l.specialties,onChange:c("specialties")})]})]}),e.jsxs(Jt,{value:"social",className:"space-y-4 mt-4",children:[e.jsxs("div",{children:[e.jsx(se,{children:"LinkedIn URL"}),e.jsx(be,{type:"url",placeholder:"https://linkedin.com/in/...",value:l.linkedin_url,onChange:c("linkedin_url")})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Website URL"}),e.jsx(be,{type:"url",placeholder:"https://...",value:l.website_url,onChange:c("website_url")})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Instagram Handle"}),e.jsx(be,{placeholder:"@handle",value:l.instagram_handle,onChange:c("instagram_handle")})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Facebook URL"}),e.jsx(be,{type:"url",placeholder:"https://facebook.com/...",value:l.facebook_url,onChange:c("facebook_url")})]})]}),e.jsxs(Jt,{value:"personal",className:"space-y-4 mt-4",children:[e.jsxs("div",{children:[e.jsx(se,{children:"Birthday"}),e.jsx(be,{type:"date",value:l.birthday,onChange:c("birthday")})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Spouse / Partner Name"}),e.jsx(be,{value:l.spouse_name,onChange:c("spouse_name")})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Interests / Hobbies"}),e.jsx(be,{placeholder:"Golf, travel, community events...",value:l.interests,onChange:c("interests")})]})]})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Notes"}),e.jsx(Is,{value:l.notes,onChange:c("notes"),rows:3})]}),e.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[e.jsx($,{type:"button",variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsx($,{type:"submit",disabled:i,children:"Add Prospect"})]})]})]})})}function MTe(){const{user:s}=_s();return ht({queryKey:["recruit-email-senders",s==null?void 0:s.id],enabled:!!s,staleTime:6e4,queryFn:async()=>{const[t,n]=await Promise.all([U.from("user_verified_senders").select("email, display_name, status").eq("user_id",s.id).eq("status","verified").limit(1).maybeSingle(),U.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 xXe({value:s,onChange:t}){const{data:n,isLoading:r}=MTe();return e.jsxs("div",{children:[e.jsx(se,{className:"text-xs",children:"Send from"}),e.jsxs(vs,{value:s,onValueChange:a=>t(a),disabled:r,children:[e.jsx(gs,{className:"mt-1",children:e.jsx(bs,{})}),e.jsxs(ys,{children:[e.jsx(Ye,{value:"default",children:e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(Ai,{className:"h-3.5 w-3.5"})," Brokerage default sender"]})}),e.jsx(Ye,{value:"mass_email",disabled:!(n!=null&&n.massEmail),children:e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(bT,{className:"h-3.5 w-3.5"}),"Mass Email",n!=null&&n.massEmail?` (${n.massEmail.email})`:" — not configured"]})}),e.jsx(Ye,{value:"gmail",disabled:!(n!=null&&n.gmail),children:e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(nn,{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 PVt({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,x]=j.useState("default"),[g,y]=j.useState(!1),b=ts(),{data:v}=MTe();j.useEffect(()=>{s&&(u(`${c}, I made you a quick video 🎥`),m(o||""),x(v!=null&&v.massEmail?"mass_email":v!=null&&v.gmail?"gmail":"default"))},[s,c,o,v==null?void 0:v.massEmail,v==null?void 0:v.gmail]);const N=async()=>{var C,A;if(!i){ae.error("This prospect has no email address on file.");return}y(!0);try{const{data:T,error:P}=await U.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(P)throw P;if(((T==null?void 0:T.sent)??0)>0)ae.success(`Email sent to ${i}`),b.invalidateQueries({queryKey:["recruit-videos"]}),b.invalidateQueries({queryKey:["recruit-videos-prospect"]}),t(!1);else{const I=((A=(C=T==null?void 0:T.results)==null?void 0:C[0])==null?void 0:A.error)||"Failed to send";ae.error(I)}}catch(T){ae.error((T==null?void 0:T.message)||"Failed to send email")}finally{y(!1)}};return e.jsx(Os,{open:s,onOpenChange:t,children:e.jsxs(Rs,{className:"max-w-lg",children:[e.jsx(Us,{children:e.jsxs(zs,{className:"flex items-center gap-2",children:[e.jsx(nn,{className:"h-5 w-5"})," Email video to ",a]})}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx(se,{className:"text-xs",children:"To"}),e.jsx(be,{value:i||"— no email on file —",disabled:!0,className:"mt-1"})]}),e.jsx(xXe,{value:p,onChange:x}),e.jsxs("div",{children:[e.jsx(se,{className:"text-xs",children:"Subject"}),e.jsx(be,{value:d,onChange:C=>u(C.target.value),className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-xs",children:"Personal message (optional)"}),e.jsx(Is,{value:h,onChange:C=>m(C.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(kr,{children:[e.jsx($,{variant:"ghost",onClick:()=>t(!1),disabled:g,children:"Cancel"}),e.jsxs($,{onClick:N,disabled:g||!i,children:[g?e.jsx(Ht,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(Br,{className:"h-4 w-4 mr-2"}),"Send Email"]})]})]})})}function WS(s){return s?s.share_token?`https://video.relevelup.com/thumb/${s.share_token}`:s.thumbnail_url||s.preview_url||null:null}const xUe=[{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 ORn(s){return ht({queryKey:["recruit-videos",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await U.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 FRn(s){return ht({queryKey:["recruit-videos-prospect",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await U.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 IVt(){const s=ts(),{toast:t}=gi();return yt({mutationFn:async n=>{const{data:{user:r}}=await U.auth.getUser();if(!r)throw new Error("Not authenticated");const{data:a,error:i}=await U.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 DVt(){const s=ts();return yt({mutationFn:async({id:t,sent_via:n})=>{const{error:r}=await U.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 RVt(s){return ht({queryKey:["recruit-video-scripts",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await U.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 zRn(){const s=ts(),{toast:t}=gi();return yt({mutationFn:async n=>{const{data:{user:r}}=await U.auth.getUser();if(!r)throw new Error("Not authenticated");const{data:a,error:i}=await U.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 BRn(){const s=ts();return yt({mutationFn:async t=>{const{error:n}=await U.from("recruit_video_scripts").delete().eq("id",t);if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["recruit-video-scripts"]})}})}function $Rn({prospectId:s,prospectName:t,prospectEmail:n,brokerageId:r}){var K;const{data:a=[],isLoading:i}=FRn(s),{data:l=[]}=RVt(r),o=IVt(),c=F5();DVt();const[d,u]=j.useState("idle"),[h,m]=j.useState(0),[p,x]=j.useState(0),[g,y]=j.useState(""),[b,v]=j.useState(""),[N,C]=j.useState(!1),[A,T]=j.useState(null),[P,M]=j.useState(null),[I,D]=j.useState(null),B=((K=l.find(Q=>Q.id===g))==null?void 0:K.script_text)||"",q=()=>{u("idle"),m(0),x(0),y(""),v("")},W=j.useCallback(async(Q,J)=>{u("uploading");try{const ce=`Recruiting: ${t}`,{videoId:ue,libraryId:ne}=await Z6(ce),{uploadUrl:ee,apiKey:le}=await X6(ue),he=new XMLHttpRequest;he.upload.onprogress=ze=>{ze.lengthComputable&&m(ze.loaded/ze.total*100)},await new Promise((ze,ke)=>{he.onload=()=>he.status>=200&&he.status<300?ze():ke(new Error("Upload failed")),he.onerror=()=>ke(new Error("Upload failed")),he.open("PUT",ee),he.setRequestHeader("AccessKey",le),he.send(Q)}),u("processing");let ve=0;const ge=Date.now(),fe=9e4,je=`https://iframe.mediadelivery.net/embed/${ne}/${ue}`;for(;ve<4&&(await new Promise(ke=>setTimeout(ke,3e3)),!(Date.now()-ge>fe));){const ze=await o2(ue);if(ve=ze.status,x(ze.encodeProgress||0),ve===5||ve===6)throw new Error("Video processing failed")}const Ee=await o2(ue),Me=(Ee.storageSize||Q.size)/(1024*1024),De=await c.mutateAsync({bunny_video_id:ue,playback_url:Ee.directPlayUrl||je,thumbnail_url:Ee.thumbnailUrl,preview_url:Ee.previewUrl||null,duration_seconds:Ee.length||J,file_size_mb:Me,title:ce,status:ve>=4?"ready":"processing",touch_type:"recruiting"});await o.mutateAsync({prospect_id:s,video_id:De.id,brokerage_id:r,message:b||void 0}),u("done"),ae.success("Video recorded and linked to prospect!"),setTimeout(()=>{C(!1),q()},1500)}catch(ce){ae.error(ce.message||"Failed to upload video"),u("record")}},[s,t,r,b,c,o]),V=Q=>{Q&&(navigator.clipboard.writeText(`${window.location.origin}/recruit-video/${Q}`),ae.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(Xr,{className:"h-4 w-4"})," Video Outreach"]}),e.jsxs(Os,{open:N,onOpenChange:Q=>{!Q&&(d==="uploading"||d==="processing")||(C(Q),Q||q())},children:[e.jsx(Ko,{asChild:!0,children:e.jsxs($,{size:"sm",variant:"outline",onClick:()=>u("script"),children:[e.jsx(sn,{className:"h-3.5 w-3.5 mr-1"})," Record Video"]})}),e.jsxs(Rs,{className:"max-w-2xl",children:[e.jsx(Us,{children:e.jsxs(zs,{children:["Record Video for ",t]})}),d==="script"&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(se,{className:"text-xs",children:"Choose a Script (optional)"}),e.jsxs(vs,{value:g,onValueChange:y,children:[e.jsx(gs,{className:"mt-1",children:e.jsx(bs,{placeholder:"No script — speak freely"})}),e.jsxs(ys,{children:[e.jsx(Ye,{value:"none",children:"No script"}),l.map(Q=>{var J;return e.jsx(Ye,{value:Q.id,children:e.jsxs("span",{className:"flex items-center gap-2",children:[Q.title,e.jsx($e,{variant:"outline",className:"text-[9px] ml-1",children:(J=xUe.find(ce=>ce.value===Q.category))==null?void 0:J.label})]})},Q.id)})]})]}),B&&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:B})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-xs",children:"Personal Message (shown on landing page)"}),e.jsx(Is,{value:b,onChange:Q=>v(Q.target.value),placeholder:`Hi ${t.split(" ")[0]}, I'd love to chat about what we're building here...`,rows:3,className:"mt-1"})]}),e.jsxs($,{onClick:()=>u("record"),className:"w-full",children:[e.jsx(Xr,{className:"h-4 w-4 mr-2"})," Start Recording"]})]}),d==="record"&&e.jsx(J6,{maxDurationSeconds:600,onRecordingComplete:W,teleprompterContent:B||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(Ki,{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(Ki,{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(Td,{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(Q=>{var J;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:WS(Q.video)?e.jsx("img",{src:WS(Q.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(Xr,{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:((J=Q.video)==null?void 0:J.title)||"Untitled"}),e.jsxs("div",{className:"flex items-center gap-2 mt-0.5",children:[Q.view_count>0?e.jsxs($e,{variant:"secondary",className:"text-[9px] h-4",children:[e.jsx(ga,{className:"h-2.5 w-2.5 mr-0.5"}),Q.view_count]}):Q.sent_at?e.jsxs($e,{variant:"outline",className:"text-[9px] h-4",children:[e.jsx(Br,{className:"h-2.5 w-2.5 mr-0.5"}),"Sent"]}):e.jsxs($e,{variant:"outline",className:"text-[9px] h-4",children:[e.jsx(Hr,{className:"h-2.5 w-2.5 mr-0.5"}),"Draft"]}),e.jsx("span",{className:"text-[10px] text-muted-foreground",children:Hs(new Date(Q.created_at),"MMM d")})]})]}),e.jsxs("div",{className:"flex gap-1",children:[e.jsx($,{variant:"ghost",size:"icon",className:"h-7 w-7",onClick:()=>V(Q.share_token),title:"Copy link",children:e.jsx(Ca,{className:"h-3 w-3"})}),e.jsxs($,{variant:Q.sent_at?"ghost":"default",size:"sm",className:"h-7 gap-1",disabled:!n,onClick:()=>{var ce;T(Q.id),M(((ce=Q.video)==null?void 0:ce.title)||null),D(Q.message||null)},title:n?"Email video to prospect":"No email on file",children:[e.jsx(nn,{className:"h-3 w-3"}),e.jsx("span",{className:"text-[10px]",children:Q.sent_at?"Resend":"Email"})]})]})]},Q.id)})}),A&&e.jsx(PVt,{open:!!A,onOpenChange:Q=>{Q||T(null)},recruitVideoId:A,brokerageId:r,prospectName:t,prospectEmail:n,videoTitle:P,defaultMessage:I})]})}function URn({brokerageId:s,onSelect:t}){const{data:n=[],isLoading:r}=ht({queryKey:["recruit-email-templates",s??"global-only"],queryFn:async()=>{let i=U.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(Hd,{children:[e.jsx(Gd,{asChild:!0,children:e.jsxs($,{variant:"outline",size:"sm",className:"gap-2",type:"button",children:[e.jsx(Wr,{className:"h-4 w-4"}),"Use Template",e.jsx(_o,{className:"h-3.5 w-3.5 opacity-60"})]})}),e.jsx(Md,{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(Ht,{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(S0,{}),e.jsx(iO,{className:"text-[11px] uppercase tracking-wide text-muted-foreground",children:i}),l.map(c=>e.jsxs(Na,{onClick:()=>t(c),className:"flex flex-col items-start gap-0.5 py-2",children:[e.jsxs("div",{className:"flex w-full items-center justify-between gap-2",children:[e.jsx("span",{className:"text-sm font-medium truncate",children:c.title}),c.brokerage_id===null&&e.jsx($e,{variant:"secondary",className:"text-[9px] shrink-0",children:"Built-in"})]}),e.jsx("span",{className:"text-xs text-muted-foreground line-clamp-1",children:c.subject})]},c.id))]},i))})]})}function qRn({open:s,onOpenChange:t,prospectId:n,brokerageId:r,prospectName:a,prospectEmail:i}){const{user:l}=_s(),o=(a||"").split(" ")[0]||"there",[c,d]=j.useState(""),[u,h]=j.useState(""),[m,p]=j.useState("default"),[x,g]=j.useState(!1),[y,b]=j.useState(null),[v,N]=j.useState(!1),C=ts(),{data:A}=MTe();j.useEffect(()=>{if(s){d(`Hi ${o}`),h("");const B=A!=null&&A.massEmail?"mass_email":A!=null&&A.gmail?"gmail":"default";p(B),b(null),N(!1)}},[s,o,A==null?void 0:A.massEmail,A==null?void 0:A.gmail]);const{data:T=[],isLoading:P}=ht({queryKey:["prospect-email-video-library",l==null?void 0:l.id],queryFn:async()=>{const{data:B,error:q}=await U.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(q)throw q;return B??[]},enabled:s&&!!(l!=null&&l.id)}),M=T.find(B=>B.id===y)||null,I=async()=>{var B,q;if(!i){ae.error("This prospect has no email address on file.");return}if(!c.trim()||!u.trim()){ae.error("Subject and message are required.");return}g(!0);try{if(y){const{data:W}=await U.from("recruit_videos").select("id").eq("prospect_id",n).eq("video_id",y).maybeSingle();let V=W==null?void 0:W.id;if(!V){const{data:ce,error:ue}=await U.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=ce.id}const{data:K,error:Q}=await U.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(Q)throw Q;if(((K==null?void 0:K.sent)??0)>0)ae.success(`Email sent to ${i}`),C.invalidateQueries({queryKey:["recruit-videos"]}),C.invalidateQueries({queryKey:["recruit-videos-prospect",n]}),C.invalidateQueries({queryKey:["recruit-activities",n]}),C.invalidateQueries({queryKey:["recruit-sent-emails"]}),t(!1);else{const ce=((q=(B=K==null?void 0:K.results)==null?void 0:B[0])==null?void 0:q.error)||"Failed to send";ae.error(ce)}}else{const{data:W,error:V}=await U.functions.invoke("send-recruit-prospect-email",{body:{prospect_id:n,brokerage_id:r,subject:c.trim(),message:u.trim(),send_via:m}});if(V)throw V;W!=null&&W.success?(ae.success(`Email sent to ${i}`),C.invalidateQueries({queryKey:["recruit-activities",n]}),C.invalidateQueries({queryKey:["recruit-sent-emails"]}),t(!1)):ae.error((W==null?void 0:W.error)||"Failed to send")}}catch(W){ae.error((W==null?void 0:W.message)||"Failed to send email")}finally{g(!1)}},D=B=>{const q=W=>W.replace(/\[First Name\]/gi,o);d(q(B.subject)),h(q(B.body)),ae.success(`Loaded "${B.title}"`)};return e.jsx(Os,{open:s,onOpenChange:t,children:e.jsxs(Rs,{className:"max-w-lg max-h-[90vh] overflow-y-auto",children:[e.jsx(Us,{children:e.jsxs(zs,{className:"flex items-center gap-2",children:[e.jsx(nn,{className:"h-5 w-5"})," Email ",a]})}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx(se,{className:"text-xs",children:"To"}),e.jsx(be,{value:i||"— no email on file —",disabled:!0,className:"mt-1"})]}),e.jsx(xXe,{value:m,onChange:p}),e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx(se,{className:"text-xs",children:"Subject"}),e.jsx(URn,{brokerageId:r,onSelect:D})]}),e.jsx(be,{value:c,onChange:B=>d(B.target.value)}),e.jsxs("div",{children:[e.jsx(se,{className:"text-xs",children:"Message"}),e.jsx(Is,{value:u,onChange:B=>h(B.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(se,{className:"text-xs flex items-center gap-1.5",children:[e.jsx(Xr,{className:"h-3.5 w-3.5"})," Include a video"]}),M?e.jsxs($,{type:"button",variant:"ghost",size:"sm",className:"h-7 text-xs",onClick:()=>{b(null),N(!1)},children:[e.jsx(pr,{className:"h-3 w-3 mr-1"})," Remove"]}):e.jsx($,{type:"button",variant:"outline",size:"sm",className:"h-7 text-xs",onClick:()=>N(B=>!B),children:v?"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:WS(M)?e.jsx("img",{src:WS(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(Xr,{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&&v&&e.jsx("div",{className:"max-h-56 overflow-y-auto space-y-1 -mx-1 px-1",children:P?e.jsx("div",{className:"flex items-center justify-center py-4",children:e.jsx(Ht,{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(B=>e.jsxs("button",{type:"button",onClick:()=>{b(B.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:WS(B)?e.jsx("img",{src:WS(B),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(Xr,{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:B.title||"Untitled video"}),B.duration_seconds&&e.jsxs("p",{className:"text-[10px] text-muted-foreground",children:[Math.floor(B.duration_seconds/60),":",String(Math.floor(B.duration_seconds%60)).padStart(2,"0")]})]})]},B.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(kr,{children:[e.jsx($,{variant:"ghost",onClick:()=>t(!1),disabled:x,children:"Cancel"}),e.jsxs($,{onClick:I,disabled:x||!i,children:[x?e.jsx(Ht,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(Br,{className:"h-4 w-4 mr-2"}),"Send Email"]})]})]})})}function VRn(s){return ht({queryKey:["recruit-campaign-sends",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await U.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 Uvt=[{value:"call",label:"Phone Call",icon:ya},{value:"email",label:"Email",icon:nn},{value:"text",label:"Text Message",icon:Ji},{value:"meeting",label:"Meeting",icon:ia},{value:"note",label:"Note",icon:Wr},{value:"campaign_email",label:"Campaign Email",icon:Br}];function v_({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 yae({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(Tr,{className:"h-3 w-3 opacity-50"})]}):null}function xm({label:s,value:t,onChange:n,type:r="text",placeholder:a}){return e.jsxs("div",{children:[e.jsx(se,{className:"text-xs",children:s}),e.jsx(be,{type:r,value:t,onChange:i=>n(i.target.value),placeholder:a,className:"mt-1 h-8 text-sm"})]})}function OVt({prospect:s,stages:t,brokerageId:n,open:r,onOpenChange:a,onUpdate:i,onDelete:l}){const{activities:o,addActivity:c}=RRn((s==null?void 0:s.id)||null),{data:d=[]}=VRn((s==null?void 0:s.id)||null),[u,h]=j.useState({type:"note",title:"",description:""}),[m,p]=j.useState(!1),[x,g]=j.useState(!1),[y,b]=j.useState({}),[v,N]=j.useState(!1);if(!s)return null;const C=()=>{var V,K;b({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||""}),g(!0)},A=()=>{const V={id:s.id};for(const[K,Q]of Object.entries(y))K==="experience_years"||K==="last_year_transactions"?V[K]=Q?parseInt(Q):null:V[K]=Q||null;i(V),g(!1)},T=()=>g(!1),P=V=>K=>b(Q=>({...Q,[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),D=s.address||s.city||s.state,B=s.last_year_volume||s.last_year_transactions||s.avg_sale_price||s.specialties||s.annual_production,q=s.linkedin_url||s.website_url||s.instagram_handle||s.facebook_url,W=s.birthday||s.spouse_name||s.interests||s.referred_by;return e.jsxs(Ub,{open:r,onOpenChange:V=>{V||g(!1),a(V)},children:[e.jsx(T1,{className:"w-full sm:max-w-lg p-0",children:e.jsx(Oi,{className:"h-full",children:e.jsxs("div",{className:"p-6 space-y-5",children:[e.jsx(kw,{children:e.jsxs("div",{className:"flex items-start justify-between",children:[e.jsxs("div",{children:[e.jsxs(Sw,{className:"text-xl",children:[s.first_name," ",s.last_name]}),I&&e.jsx($e,{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:[x?e.jsxs(e.Fragment,{children:[e.jsx($,{variant:"ghost",size:"icon",onClick:T,children:e.jsx(pr,{className:"h-4 w-4"})}),e.jsx($,{variant:"default",size:"icon",onClick:A,children:e.jsx(Jo,{className:"h-4 w-4"})})]}):e.jsx($,{variant:"ghost",size:"icon",onClick:C,title:"Edit prospect",children:e.jsx(Ya,{className:"h-4 w-4"})}),e.jsxs(Ll,{children:[e.jsx(_f,{asChild:!0,children:e.jsx($,{variant:"ghost",size:"icon",className:"text-destructive hover:text-destructive",children:e.jsx(Pn,{className:"h-4 w-4"})})}),e.jsxs(yl,{children:[e.jsxs(vl,{children:[e.jsx(_l,{children:"Delete prospect?"}),e.jsx(wl,{children:"This will permanently remove this prospect and all their activity history."})]}),e.jsxs(bl,{children:[e.jsx(jl,{children:"Cancel"}),e.jsx(fl,{onClick:()=>{l(s.id),a(!1)},children:"Delete"})]})]})]})]})]})}),!x&&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(nn,{className:"h-3.5 w-3.5 flex-shrink-0"}),e.jsx("span",{className:"truncate",children:s.email})]}),e.jsxs($,{size:"sm",variant:"outline",className:"h-7 gap-1.5 flex-shrink-0",onClick:()=>N(!0),children:[e.jsx(nn,{className:"h-3 w-3"})," Email"]})]}),s.phone&&e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground",children:[e.jsx(ya,{className:"h-3.5 w-3.5"})," ",s.phone]}),D&&e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground",children:[e.jsx(ai,{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(se,{className:"text-xs text-muted-foreground",children:"Move to Stage"}),e.jsxs(vs,{value:s.stage_id||"",onValueChange:V=>i({id:s.id,stage_id:V}),children:[e.jsx(gs,{className:"mt-1",children:e.jsx(bs,{})}),e.jsx(ys,{children:t.map(V=>e.jsx(Ye,{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(ua,{defaultValue:"details",className:"w-full",children:[e.jsxs(ha,{className:"grid w-full grid-cols-4 h-8 text-xs",children:[e.jsx(Qt,{value:"details",className:"text-xs",children:"Details"}),e.jsx(Qt,{value:"production",className:"text-xs",children:"Production"}),e.jsx(Qt,{value:"social",className:"text-xs",children:"Social"}),e.jsx(Qt,{value:"personal",className:"text-xs",children:"Personal"})]}),x?e.jsxs(e.Fragment,{children:[e.jsxs(Jt,{value:"details",className:"mt-3 space-y-3",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsx(xm,{label:"First Name",value:y.first_name,onChange:P("first_name")}),e.jsx(xm,{label:"Last Name",value:y.last_name,onChange:P("last_name")})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsx(xm,{label:"Email",value:y.email,onChange:P("email"),type:"email"}),e.jsx(xm,{label:"Phone",value:y.phone,onChange:P("phone")})]}),e.jsx(xm,{label:"Current Brokerage",value:y.current_brokerage,onChange:P("current_brokerage")}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsx(xm,{label:"License #",value:y.license_number,onChange:P("license_number")}),e.jsx(xm,{label:"Experience (years)",value:y.experience_years,onChange:P("experience_years"),type:"number"})]}),e.jsx(xm,{label:"Address",value:y.address,onChange:P("address"),placeholder:"Street address"}),e.jsxs("div",{className:"grid grid-cols-3 gap-3",children:[e.jsx(xm,{label:"City",value:y.city,onChange:P("city")}),e.jsx(xm,{label:"State",value:y.state,onChange:P("state")}),e.jsx(xm,{label:"Zip",value:y.zip_code,onChange:P("zip_code")})]}),e.jsx(xm,{label:"Source",value:y.source,onChange:P("source")}),e.jsx(xm,{label:"Referred By",value:y.referred_by,onChange:P("referred_by")}),e.jsxs("div",{children:[e.jsx(se,{className:"text-xs",children:"Notes"}),e.jsx(Is,{value:y.notes,onChange:V=>b(K=>({...K,notes:V.target.value})),rows:3,className:"mt-1 text-sm"})]})]}),e.jsxs(Jt,{value:"production",className:"mt-3 space-y-3",children:[e.jsx(xm,{label:"Annual Production",value:y.annual_production,onChange:P("annual_production"),placeholder:"e.g. $5M"}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsx(xm,{label:"Last Year Volume",value:y.last_year_volume,onChange:P("last_year_volume"),placeholder:"e.g. $8.2M"}),e.jsx(xm,{label:"Last Year Transactions",value:y.last_year_transactions,onChange:P("last_year_transactions"),type:"number",placeholder:"e.g. 24"})]}),e.jsx(xm,{label:"Avg Sale Price",value:y.avg_sale_price,onChange:P("avg_sale_price"),placeholder:"e.g. $350K"}),e.jsx(xm,{label:"Specialties / Niche",value:y.specialties,onChange:P("specialties"),placeholder:"e.g. Luxury, Investment"})]}),e.jsxs(Jt,{value:"social",className:"mt-3 space-y-3",children:[e.jsx(xm,{label:"LinkedIn URL",value:y.linkedin_url,onChange:P("linkedin_url"),type:"url",placeholder:"https://linkedin.com/in/..."}),e.jsx(xm,{label:"Website URL",value:y.website_url,onChange:P("website_url"),type:"url",placeholder:"https://..."}),e.jsx(xm,{label:"Instagram Handle",value:y.instagram_handle,onChange:P("instagram_handle"),placeholder:"@handle"}),e.jsx(xm,{label:"Facebook URL",value:y.facebook_url,onChange:P("facebook_url"),type:"url",placeholder:"https://facebook.com/..."})]}),e.jsxs(Jt,{value:"personal",className:"mt-3 space-y-3",children:[e.jsx(xm,{label:"Birthday",value:y.birthday,onChange:P("birthday"),type:"date"}),e.jsx(xm,{label:"Spouse / Partner",value:y.spouse_name,onChange:P("spouse_name")}),e.jsx(xm,{label:"Interests / Hobbies",value:y.interests,onChange:P("interests"),placeholder:"Golf, travel, community events..."})]})]}):e.jsxs(e.Fragment,{children:[e.jsxs(Jt,{value:"details",className:"mt-3",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsx(v_,{label:"Current Brokerage",value:s.current_brokerage}),e.jsx(v_,{label:"License #",value:s.license_number}),e.jsx(v_,{label:"Experience",value:s.experience_years!=null?`${s.experience_years} years`:null}),e.jsx(v_,{label:"Referred By",value:s.referred_by}),e.jsx(v_,{label:"Source",value:s.source})]}),s.notes&&e.jsxs("div",{className:"mt-3",children:[e.jsx(se,{className:"text-xs text-muted-foreground",children:"Notes"}),e.jsx("p",{className:"text-sm mt-1 whitespace-pre-wrap",children:s.notes})]})]}),e.jsx(Jt,{value:"production",className:"mt-3",children:B?e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsx(v_,{label:"Annual Production",value:s.annual_production}),e.jsx(v_,{label:"Last Year Volume",value:s.last_year_volume}),e.jsx(v_,{label:"Last Year Transactions",value:s.last_year_transactions}),e.jsx(v_,{label:"Avg Sale Price",value:s.avg_sale_price}),e.jsx(v_,{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(Jt,{value:"social",className:"mt-3",children:q?e.jsxs("div",{className:"space-y-2",children:[e.jsx(yae,{label:"LinkedIn",url:s.linkedin_url,icon:kg}),e.jsx(yae,{label:"Website",url:s.website_url,icon:Gl}),s.instagram_handle&&e.jsx(yae,{label:s.instagram_handle,url:`https://instagram.com/${s.instagram_handle.replace("@","")}`,icon:Qh}),e.jsx(yae,{label:"Facebook",url:s.facebook_url,icon:jf})]}):e.jsx("p",{className:"text-sm text-muted-foreground text-center py-4",children:"No social profiles added yet"})}),e.jsx(Jt,{value:"personal",className:"mt-3",children:W?e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsx(v_,{label:"Birthday",value:s.birthday?Hs(new Date(s.birthday+"T00:00:00"),"MMMM d, yyyy"):null,icon:Co}),e.jsx(v_,{label:"Spouse / Partner",value:s.spouse_name,icon:fo}),e.jsx("div",{className:"col-span-2",children:e.jsx(v_,{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($Rn,{prospectId:s.id,prospectName:`${s.first_name} ${s.last_name||""}`,prospectEmail:s.email,brokerageId:n}),e.jsx(Hl,{}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-3",children:[e.jsx("h3",{className:"font-semibold text-sm",children:"Activity Log"}),e.jsxs($,{size:"sm",variant:"outline",onClick:()=>p(!m),children:[e.jsx(sn,{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(vs,{value:u.type,onValueChange:V=>h(K=>({...K,type:V})),children:[e.jsx(gs,{children:e.jsx(bs,{})}),e.jsx(ys,{children:Uvt.map(V=>e.jsx(Ye,{value:V.value,children:V.label},V.value))})]}),e.jsx(be,{placeholder:"Subject / Title",value:u.title,onChange:V=>h(K=>({...K,title:V.target.value}))}),e.jsx(Is,{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($,{size:"sm",variant:"ghost",onClick:()=>p(!1),children:"Cancel"}),e.jsx($,{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,Q)=>new Date(Q.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 J=K.data,ce=Uvt.find(ne=>ne.value===J.activity_type),ue=(ce==null?void 0:ce.icon)||Wr;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:J.title}),J.description&&e.jsx("p",{className:"text-muted-foreground text-xs mt-0.5",children:J.description}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:Hs(new Date(J.created_at),"MMM d, yyyy h:mm a")})]})]},`activity-${J.id}`)}const Q=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(Br,{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 #",Q.email_number]}),e.jsx("p",{className:"text-muted-foreground text-xs mt-0.5",children:Q.subject}),e.jsxs("div",{className:"flex flex-wrap items-center gap-1.5 mt-1.5",children:[Q.status==="failed"?e.jsx($e,{variant:"destructive",className:"text-[10px] px-1.5 py-0 h-4",children:"Failed"}):e.jsxs($e,{variant:"outline",className:"text-[10px] px-1.5 py-0 h-4 border-green-500 text-green-600",children:[e.jsx(Br,{className:"h-2.5 w-2.5 mr-0.5"})," Sent"]}),Q.opened_at?e.jsxs($e,{variant:"outline",className:"text-[10px] px-1.5 py-0 h-4 border-blue-500 text-blue-600",children:[e.jsx(ga,{className:"h-2.5 w-2.5 mr-0.5"})," Opened ",Hs(new Date(Q.opened_at),"MMM d, h:mm a")]}):Q.status!=="failed"?e.jsx($e,{variant:"outline",className:"text-[10px] px-1.5 py-0 h-4 text-muted-foreground",children:"Not opened"}):null,Q.clicked_at&&e.jsxs($e,{variant:"outline",className:"text-[10px] px-1.5 py-0 h-4 border-purple-500 text-purple-600",children:[e.jsx(pg,{className:"h-2.5 w-2.5 mr-0.5"})," Clicked ",Hs(new Date(Q.clicked_at),"MMM d, h:mm a")]})]}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:Hs(new Date(Q.sent_at||Q.created_at),"MMM d, yyyy h:mm a")})]})]},`send-${Q.id}`)})})()})]})]})})}),e.jsx(qRn,{open:v,onOpenChange:N,prospectId:s.id,brokerageId:s.brokerage_id,prospectName:`${s.first_name} ${s.last_name??""}`.trim(),prospectEmail:s.email})]})}const HRn=["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 FVt({open:s,onOpenChange:t,brokerageId:n,stages:r}){var D;const{toast:a}=gi(),i=ts(),l=j.useRef(null),[o,c]=j.useState([]),[d,u]=j.useState([]),[h,m]=j.useState({}),[p,x]=j.useState(((D=r[0])==null?void 0:D.id)||""),[g,y]=j.useState(!1),[b,v]=j.useState("upload"),[N,C]=j.useState(0),A=()=>{c([]),u([]),m({}),v("upload"),C(0)},T=B=>{var V;const q=(V=B.target.files)==null?void 0:V[0];if(!q)return;const W=new FileReader;W.onload=K=>{var le;const J=((le=K.target)==null?void 0:le.result).split(/\r?\n/).filter(he=>he.trim());if(J.length<2){a({title:"Invalid CSV",description:"File must have a header row and at least one data row",variant:"destructive"});return}const ce=P(J[0]);u(ce);const ue={},ne=new Set;ce.forEach((he,ve)=>{const ge=he.toLowerCase().replace(/[^a-z0-9]/g,"");let fe=null;/^firstname$/.test(ge)||ge==="first"?fe="first_name":/^lastname$/.test(ge)||ge==="last"?fe="last_name":/^email$/.test(ge)||ge==="emailaddress"?fe="email":/^mobile$|^phone$|^cellphone$|^mobilephone$/.test(ge)?fe="phone":/officename|currentbrokerage|brokerage|company/.test(ge)?fe="current_brokerage":/membernumber|licensenumber|license/.test(ge)?fe="license_number":/experienceyears|yearsexperience/.test(ge)?fe="experience_years":/^totalvolume$|annualproduction/.test(ge)?fe="annual_production":/^address$/.test(ge)?fe="address":/^city$/.test(ge)?fe="city":/^state$/.test(ge)?fe="state":/^postalcode$|^zip$|^zipcode$/.test(ge)?fe="zip_code":/listsidevolume|lastyearvolume/.test(ge)?fe="last_year_volume":/^totalcount$|lastyeartransactions/.test(ge)?fe="last_year_transactions":/avgsaleprice|averageprice/.test(ge)?fe="avg_sale_price":/linkedin/.test(ge)?fe="linkedin_url":/website/.test(ge)?fe="website_url":/specialt/.test(ge)?fe="specialties":/referr/.test(ge)?fe="referred_by":/^notes$|^note$/.test(ge)&&(fe="notes"),fe&&!ne.has(fe)&&(ue[String(ve)]=fe,ne.add(fe))}),m(ue);const ee=J.slice(1).map(he=>{const ve=P(he),ge={};return ce.forEach((fe,je)=>{ge[String(je)]=ve[je]||""}),ge});c(ee),v("map")},W.readAsText(q)},P=B=>{const q=[];let W="",V=!1;for(const K of B)K==='"'?V=!V:K===","&&!V?(q.push(W.trim()),W=""):W+=K;return q.push(W.trim()),q},M=async()=>{y(!0);try{const{data:{user:B}}=await U.auth.getUser();if(!B)throw new Error("Not authenticated");const q=o.map(V=>{const K={brokerage_id:n,created_by:B.id,stage_id:p,source:"csv_import",first_name:"Unknown"},Q=K;return Object.entries(h).forEach(([J,ce])=>{var ne;const ue=(ne=V[J])==null?void 0:ne.trim();ue&&(ce==="experience_years"||ce==="last_year_transactions"?Q[ce]=parseInt(ue.replace(/[^0-9.-]/g,""))||null:ce==="annual_production"||ce==="last_year_volume"||ce==="avg_sale_price"?Q[ce]=ue.replace(/[^0-9.$,.-]/g,""):Q[ce]=ue)}),K});let W=0;for(let V=0;V{const B=`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`,q=new Blob([B],{type:"text/csv"}),W=URL.createObjectURL(q),V=document.createElement("a");V.href=W,V.download="recruit-prospects-template.csv",V.click(),URL.revokeObjectURL(W)};return e.jsx(Os,{open:s,onOpenChange:B=>{B||A(),t(B)},children:e.jsxs(Rs,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsx(Us,{children:e.jsx(zs,{children:"Import Prospects from CSV"})}),b==="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(PN,{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($,{onClick:()=>{var B;return(B=l.current)==null?void 0:B.click()},children:[e.jsx(si,{className:"h-4 w-4 mr-2"})," Choose File"]})]}),e.jsx($,{variant:"link",className:"text-xs",onClick:I,children:"Download CSV template"})]}),b==="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(vs,{value:p,onValueChange:x,children:[e.jsx(gs,{className:"w-[180px]",children:e.jsx(bs,{})}),e.jsx(ys,{children:r.map(B=>e.jsx(Ye,{value:B.id,children:B.name},B.id))})]})]})]}),e.jsx("div",{className:"border rounded-lg overflow-hidden",children:e.jsxs(Va,{children:[e.jsx(Ha,{children:e.jsxs(hn,{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(Ga,{children:d.map((B,q)=>{var W;return e.jsxs(hn,{children:[e.jsx(gt,{className:"font-medium text-xs",children:B}),e.jsx(gt,{children:e.jsxs(vs,{value:h[String(q)]||"skip",onValueChange:V=>m(K=>({...K,[String(q)]:V==="skip"?"":V})),children:[e.jsx(gs,{className:"h-8 text-xs",children:e.jsx(bs,{})}),e.jsxs(ys,{children:[e.jsx(Ye,{value:"skip",children:"— Skip —"}),HRn.map(V=>e.jsx(Ye,{value:V,children:V.replace(/_/g," ")},V))]})]})}),e.jsx(gt,{className:"text-xs text-muted-foreground truncate max-w-[200px]",children:((W=o[0])==null?void 0:W[String(q)])||"—"})]},q)})})]})}),!Object.values(h).includes("first_name")&&e.jsxs("div",{className:"flex items-center gap-2 text-amber-600 text-sm",children:[e.jsx(xo,{className:"h-4 w-4"}),' Map at least "first name" to proceed']}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx($,{variant:"outline",onClick:()=>{A()},children:"Back"}),e.jsx($,{onClick:M,disabled:g||!Object.values(h).includes("first_name"),children:g?"Importing...":`Import ${o.length} Prospects`})]})]}),b==="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(oa,{className:"h-6 w-6 text-green-600"})}),e.jsxs("p",{className:"font-semibold",children:[N," prospects imported successfully!"]}),e.jsx($,{onClick:()=>{A(),t(!1)},children:"Close"})]})]})})}function zVt({brokerageId:s}){const{stages:t,prospects:n,isLoading:r,addProspect:a,updateProspect:i,deleteProspect:l}=yte(s),[o,c]=j.useState(!1),[d,u]=j.useState(),[h,m]=j.useState(null),[p,x]=j.useState(!1),[g,y]=j.useState(!1),[b,v]=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(D=>D.stage_id===I),C=(I,D)=>{v(D),I.dataTransfer.effectAllowed="move"},A=I=>{I.preventDefault(),I.dataTransfer.dropEffect="move"},T=(I,D)=>{I.preventDefault(),b&&(i.mutate({id:b,stage_id:D}),v(null))},P=I=>{u(I),c(!0)},M=I=>{m(I),x(!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($,{variant:"outline",onClick:()=>y(!0),children:[e.jsx(si,{className:"h-4 w-4 mr-2"})," Import CSV"]}),e.jsxs($,{onClick:()=>{u(void 0),c(!0)},children:[e.jsx(sn,{className:"h-4 w-4 mr-2"})," Add Prospect"]})]})]}),e.jsxs(Oi,{className:"w-full",children:[e.jsx("div",{className:"flex gap-4 pb-4",style:{minWidth:t.length*300},children:t.map(I=>{const D=N(I.id);return e.jsxs("div",{className:"w-[280px] flex-shrink-0 flex flex-col",onDragOver:A,onDrop:B=>T(B,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($e,{variant:"secondary",className:"text-xs h-5 px-1.5",children:D.length})]}),e.jsx($,{variant:"ghost",size:"icon",className:"h-6 w-6",onClick:()=>P(I.id),children:e.jsx(sn,{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:D.map(B=>e.jsx(_e,{className:"p-3 cursor-pointer hover:shadow-md transition-shadow border-l-4 group",style:{borderLeftColor:I.color},draggable:!0,onDragStart:q=>C(q,B.id),onClick:()=>M(B),children:e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx($p,{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(Lo,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsxs("span",{className:"font-medium text-sm truncate",children:[B.first_name," ",B.last_name]})]}),B.current_brokerage&&e.jsxs("div",{className:"flex items-center gap-1.5 text-xs text-muted-foreground",children:[e.jsx(Ai,{className:"h-3 w-3"}),e.jsx("span",{className:"truncate",children:B.current_brokerage})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[B.email&&e.jsx(nn,{className:"h-3 w-3 text-muted-foreground"}),B.phone&&e.jsx(ya,{className:"h-3 w-3 text-muted-foreground"}),B.experience_years!=null&&e.jsxs($e,{variant:"secondary",className:"text-[10px] h-4 px-1",children:[B.experience_years,"yr"]})]})]})]})},B.id))})]},I.id)})}),e.jsx(Nq,{orientation:"horizontal"})]}),e.jsx(LVt,{open:o,onOpenChange:c,stages:t,defaultStageId:d,onSubmit:I=>a.mutate(I),isSubmitting:a.isPending}),e.jsx(OVt,{prospect:h,stages:t,brokerageId:s,open:p,onOpenChange:x,onUpdate:I=>{i.mutate(I),m(D=>D?{...D,...I}:null)},onDelete:I=>l.mutate(I)}),e.jsx(FVt,{open:g,onOpenChange:y,brokerageId:s,stages:t})]})}function F4e({brokerageId:s}){const{stages:t,prospects:n,isLoading:r,addProspect:a,updateProspect:i,deleteProspect:l}=yte(s),{user:o}=_s(),c=ts(),[d,u]=j.useState(!1),[h,m]=j.useState(null),[p,x]=j.useState(!1),[g,y]=j.useState(!1),[b,v]=j.useState(""),[N,C]=j.useState("all"),[A,T]=j.useState("all"),[P,M]=j.useState("all"),[I,D]=j.useState(null),[B,q]=j.useState("asc"),[W,V]=j.useState(new Set),[K,Q]=j.useState(!1),[J,ce]=j.useState(""),ue=j.useMemo(()=>{const ke=new Set;return n.forEach(Xe=>{Xe.current_brokerage&&ke.add(Xe.current_brokerage)}),Array.from(ke).sort()},[n]),{data:ne=[]}=ht({queryKey:["recruit-campaigns-list",s],queryFn:async()=>{const{data:ke,error:Xe}=await U.from("recruit_campaigns").select("id, name, warmth_level").or(`brokerage_id.is.null,brokerage_id.eq.${s}`).order("name");if(Xe)throw Xe;return ke}}),{data:ee=[]}=ht({queryKey:["recruit-campaign-assignments-lookup",s],queryFn:async()=>{let Xe=[],Se=0;for(;;){const{data:Re,error:Ae}=await U.from("recruit_campaign_assignments").select("prospect_id, campaign_id, status").eq("brokerage_id",s).range(Se,Se+1e3-1);if(Ae)throw Ae;if(Xe=Xe.concat(Re??[]),!Re||Re.length<1e3)break;Se+=1e3}return Xe}}),le=j.useMemo(()=>{const ke=new Map;return ee.forEach(Xe=>{ke.has(Xe.prospect_id)||ke.set(Xe.prospect_id,new Set),ke.get(Xe.prospect_id).add(Xe.campaign_id)}),ke},[ee]),he=ke=>{I===ke?q(Xe=>Xe==="asc"?"desc":"asc"):(D(ke),q("asc"))},ve=({column:ke})=>I!==ke?e.jsx(Tx,{className:"h-3.5 w-3.5 ml-1 text-muted-foreground/50"}):B==="asc"?e.jsx(sp,{className:"h-3.5 w-3.5 ml-1 text-primary"}):e.jsx(ax,{className:"h-3.5 w-3.5 ml-1 text-primary"}),ge=ke=>t.find(Xe=>Xe.id===ke),fe=j.useMemo(()=>{let ke=n.filter(Xe=>{var qe,Ke,Ze;const Se=!b||`${Xe.first_name} ${Xe.last_name}`.toLowerCase().includes(b.toLowerCase())||((qe=Xe.email)==null?void 0:qe.toLowerCase().includes(b.toLowerCase()))||((Ke=Xe.current_brokerage)==null?void 0:Ke.toLowerCase().includes(b.toLowerCase())),Re=N==="all"||Xe.stage_id===N,Ae=A==="all"||Xe.current_brokerage===A;let Be=!0;return P==="in_campaign"?Be=le.has(Xe.id):P==="not_in_campaign"?Be=!le.has(Xe.id):P!=="all"&&(Be=((Ze=le.get(Xe.id))==null?void 0:Ze.has(P))??!1),Se&&Re&&Ae&&Be});return I&&(ke=[...ke].sort((Xe,Se)=>{var qe,Ke;let Re=null,Ae=null;switch(I){case"name":Re=`${Xe.first_name} ${Xe.last_name||""}`.toLowerCase(),Ae=`${Se.first_name} ${Se.last_name||""}`.toLowerCase();break;case"stage":Re=((qe=ge(Xe.stage_id))==null?void 0:qe.sort_order)??999,Ae=((Ke=ge(Se.stage_id))==null?void 0:Ke.sort_order)??999;break;case"brokerage":Re=(Xe.current_brokerage||"").toLowerCase(),Ae=(Se.current_brokerage||"").toLowerCase();break;case"experience":Re=Xe.experience_years??-1,Ae=Se.experience_years??-1;break;case"production":Re=(Xe.annual_production||"").toLowerCase(),Ae=(Se.annual_production||"").toLowerCase();break;case"source":Re=(Xe.source||"").toLowerCase(),Ae=(Se.source||"").toLowerCase();break;default:return 0}if(Re===Ae)return 0;if(Re==null)return 1;if(Ae==null)return-1;const Be=Re0&&fe.every(ke=>W.has(ke.id)),Ee=fe.some(ke=>W.has(ke.id)),Me=()=>{V(je?new Set:new Set(fe.map(ke=>ke.id)))},De=ke=>{V(Xe=>{const Se=new Set(Xe);return Se.has(ke)?Se.delete(ke):Se.add(ke),Se})},ze=yt({mutationFn:async()=>{if(!J||!(o!=null&&o.id))throw new Error("Select a campaign");const ke=new Set(ee.filter(Re=>Re.campaign_id===J).map(Re=>Re.prospect_id)),Xe=Array.from(W).filter(Re=>!ke.has(Re)).map(Re=>({prospect_id:Re,campaign_id:J,brokerage_id:s,assigned_by:o.id,status:"active",current_email_number:0}));if(Xe.length===0)throw new Error("All selected prospects are already in this campaign");const{error:Se}=await U.from("recruit_campaign_assignments").insert(Xe);if(Se)throw Se;return Xe.length},onSuccess:ke=>{ae.success(`${ke} prospect(s) added to campaign`),Q(!1),V(new Set),ce(""),c.invalidateQueries({queryKey:["recruit-campaign-assignments-lookup"]})},onError:ke=>ae.error(ke.message)});return r?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})}):e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between gap-4 flex-wrap",children:[e.jsxs("div",{className:"relative flex-1 max-w-sm min-w-[200px]",children:[e.jsx(Vr,{className:"absolute left-2.5 top-2.5 h-4 w-4 text-muted-foreground"}),e.jsx(be,{placeholder:"Search prospects...",value:b,onChange:ke=>v(ke.target.value),className:"pl-8"})]}),e.jsxs("div",{className:"flex gap-2",children:[W.size>0&&e.jsxs($,{variant:"secondary",onClick:()=>Q(!0),className:"gap-1.5",children:[e.jsx(Br,{className:"h-4 w-4"})," Add ",W.size," to Campaign"]}),e.jsxs($,{variant:"outline",onClick:()=>y(!0),children:[e.jsx(si,{className:"h-4 w-4 mr-2"})," Import CSV"]}),e.jsxs($,{onClick:()=>u(!0),children:[e.jsx(sn,{className:"h-4 w-4 mr-2"})," Add Prospect"]})]})]}),e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx($j,{className:"h-4 w-4 text-muted-foreground"}),e.jsxs(vs,{value:N,onValueChange:C,children:[e.jsx(gs,{className:"w-[160px] h-8 text-xs",children:e.jsx(bs,{placeholder:"All stages"})}),e.jsxs(ys,{children:[e.jsx(Ye,{value:"all",children:"All stages"}),t.map(ke=>e.jsx(Ye,{value:ke.id,children:ke.name},ke.id))]})]}),e.jsxs(vs,{value:A,onValueChange:T,children:[e.jsxs(gs,{className:"w-[200px] h-8 text-xs",children:[e.jsx(Ai,{className:"h-3.5 w-3.5 mr-1.5"}),e.jsx(bs,{placeholder:"All brokerages"})]}),e.jsxs(ys,{children:[e.jsx(Ye,{value:"all",children:"All brokerages"}),ue.map(ke=>e.jsx(Ye,{value:ke,children:ke},ke))]})]}),e.jsxs(vs,{value:P,onValueChange:M,children:[e.jsxs(gs,{className:"w-[200px] h-8 text-xs",children:[e.jsx(nn,{className:"h-3.5 w-3.5 mr-1.5"}),e.jsx(bs,{placeholder:"Campaign status"})]}),e.jsxs(ys,{children:[e.jsx(Ye,{value:"all",children:"All contacts"}),e.jsx(Ye,{value:"in_campaign",children:"In any campaign"}),e.jsx(Ye,{value:"not_in_campaign",children:"Not in any campaign"}),ne.map(ke=>e.jsxs(Ye,{value:ke.id,children:["In: ",ke.name]},ke.id))]})]}),(N!=="all"||A!=="all"||P!=="all")&&e.jsx($,{variant:"ghost",size:"sm",className:"h-8 text-xs text-muted-foreground",onClick:()=>{C("all"),T("all"),M("all")},children:"Clear filters"})]}),e.jsx("div",{className:"rounded-md border",children:e.jsxs(Va,{children:[e.jsx(Ha,{children:e.jsxs(hn,{children:[e.jsx(Lt,{className:"w-[40px]",children:e.jsx(ui,{checked:je,onCheckedChange:Me,"aria-label":"Select all",...Ee&&!je?{"data-state":"indeterminate"}:{}})}),e.jsx(Lt,{className:"cursor-pointer select-none",onClick:()=>he("name"),children:e.jsxs("span",{className:"inline-flex items-center",children:["Name ",e.jsx(ve,{column:"name"})]})}),e.jsx(Lt,{className:"cursor-pointer select-none",onClick:()=>he("stage"),children:e.jsxs("span",{className:"inline-flex items-center",children:["Stage ",e.jsx(ve,{column:"stage"})]})}),e.jsx(Lt,{className:"hidden md:table-cell cursor-pointer select-none",onClick:()=>he("brokerage"),children:e.jsxs("span",{className:"inline-flex items-center",children:["Brokerage ",e.jsx(ve,{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:()=>he("experience"),children:e.jsxs("span",{className:"inline-flex items-center",children:["Experience ",e.jsx(ve,{column:"experience"})]})}),e.jsx(Lt,{className:"hidden lg:table-cell cursor-pointer select-none",onClick:()=>he("production"),children:e.jsxs("span",{className:"inline-flex items-center",children:["Production ",e.jsx(ve,{column:"production"})]})}),e.jsx(Lt,{className:"hidden lg:table-cell",children:"Campaigns"}),e.jsx(Lt,{className:"w-[50px]"})]})}),e.jsx(Ga,{children:fe.length===0?e.jsx(hn,{children:e.jsx(gt,{colSpan:9,className:"text-center text-muted-foreground py-8",children:"No prospects found"})}):fe.map(ke=>{const Xe=ge(ke.stage_id),Se=le.get(ke.id),Re=(Se==null?void 0:Se.size)??0;return e.jsxs(hn,{className:"cursor-pointer",onClick:()=>{m(ke),x(!0)},children:[e.jsx(gt,{onClick:Ae=>Ae.stopPropagation(),children:e.jsx(ui,{checked:W.has(ke.id),onCheckedChange:()=>De(ke.id),"aria-label":`Select ${ke.first_name}`})}),e.jsxs(gt,{className:"font-medium",children:[ke.first_name," ",ke.last_name]}),e.jsx(gt,{children:Xe?e.jsxs($e,{variant:"outline",className:"text-xs gap-1 whitespace-nowrap",style:{borderColor:Xe.color,color:Xe.color,backgroundColor:`${Xe.color}10`},children:[e.jsx("span",{className:"h-1.5 w-1.5 rounded-full inline-block",style:{backgroundColor:Xe.color}}),Xe.name]}):e.jsx("span",{className:"text-muted-foreground text-xs",children:"—"})}),e.jsx(gt,{className:"hidden md:table-cell",children:ke.current_brokerage?e.jsxs("div",{className:"flex items-center gap-1.5 text-sm",children:[e.jsx(Ai,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"truncate max-w-[150px]",children:ke.current_brokerage})]}):e.jsx("span",{className:"text-muted-foreground",children:"—"})}),e.jsx(gt,{className:"hidden md:table-cell",children:e.jsxs("div",{className:"flex items-center gap-2",children:[ke.email&&e.jsx(nn,{className:"h-3.5 w-3.5 text-muted-foreground"}),ke.phone&&e.jsx(ya,{className:"h-3.5 w-3.5 text-muted-foreground"}),!ke.email&&!ke.phone&&e.jsx("span",{className:"text-muted-foreground",children:"—"})]})}),e.jsx(gt,{className:"hidden lg:table-cell",children:ke.experience_years!=null?`${ke.experience_years} yr`:"—"}),e.jsx(gt,{className:"hidden lg:table-cell",children:ke.annual_production||"—"}),e.jsx(gt,{className:"hidden lg:table-cell",children:Re>0?e.jsxs($e,{variant:"secondary",className:"text-xs",children:[Re," campaign",Re>1?"s":""]}):e.jsx("span",{className:"text-muted-foreground text-xs",children:"None"})}),e.jsx(gt,{children:e.jsx($,{variant:"ghost",size:"icon",className:"h-7 w-7 text-muted-foreground hover:text-destructive",onClick:Ae=>{Ae.stopPropagation(),l.mutate(ke.id)},children:e.jsx(Pn,{className:"h-3.5 w-3.5"})})})]},ke.id)})})]})}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[W.size>0&&e.jsxs("span",{className:"font-medium text-foreground",children:[W.size," selected · "]}),fe.length," of ",n.length," prospects"]}),e.jsx(Os,{open:K,onOpenChange:Q,children:e.jsxs(Rs,{className:"sm:max-w-md",children:[e.jsx(Us,{children:e.jsx(zs,{children:"Add to Campaign"})}),e.jsxs("div",{className:"space-y-4 py-2",children:[e.jsxs("p",{className:"text-sm text-muted-foreground",children:["Add ",e.jsx("span",{className:"font-medium text-foreground",children:W.size})," selected prospect(s) to a recruiting campaign drip."]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Campaign"}),e.jsxs(vs,{value:J,onValueChange:ce,children:[e.jsx(gs,{children:e.jsx(bs,{placeholder:"Select a campaign..."})}),e.jsx(ys,{children:ne.map(ke=>e.jsxs(Ye,{value:ke.id,children:[ke.name," ",e.jsxs("span",{className:"text-muted-foreground ml-1",children:["(",ke.warmth_level,")"]})]},ke.id))})]})]})]}),e.jsxs(kr,{children:[e.jsx($,{variant:"outline",onClick:()=>Q(!1),children:"Cancel"}),e.jsx($,{onClick:()=>ze.mutate(),disabled:!J||ze.isPending,children:ze.isPending?"Adding...":"Add to Campaign"})]})]})}),e.jsx(LVt,{open:d,onOpenChange:u,stages:t,onSubmit:ke=>a.mutate(ke),isSubmitting:a.isPending}),e.jsx(OVt,{prospect:h,stages:t,brokerageId:s,open:p,onOpenChange:x,onUpdate:ke=>{i.mutate(ke),m(Xe=>Xe?{...Xe,...ke}:null)},onDelete:ke=>l.mutate(ke)}),e.jsx(FVt,{open:g,onOpenChange:y,brokerageId:s,stages:t})]})}function BVt({brokerageId:s}){const{stages:t,prospects:n,isLoading:r}=yte(s),a=j.useMemo(()=>{if(!t.length||!n.length)return null;const i=n.length,l=t.find(b=>b.name==="Signed"),o=t.find(b=>b.name==="Onboarded"),c=n.filter(b=>b.stage_id===(l==null?void 0:l.id)||b.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((b,v)=>b+r2(u,new Date(v.created_at)),0)/i):0,m=t.map(b=>({...b,count:n.filter(v=>v.stage_id===b.id).length})),p={};n.forEach(b=>{const v=b.source||"unknown";p[v]=(p[v]||0)+1});const x=Object.entries(p).sort((b,v)=>v[1]-b[1]),g=new Date;g.setDate(g.getDate()-30);const y=n.filter(b=>new Date(b.created_at)>=g).length;return{total:i,signed:c,conversionRate:d,avgDays:h,byStage:m,bySrc:x,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(_e,{children:e.jsx(Oe,{className:"pt-6",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"h-10 w-10 rounded-lg bg-blue-500/10 flex items-center justify-center",children:e.jsx(qn,{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(_e,{children:e.jsx(Oe,{className:"pt-6",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"h-10 w-10 rounded-lg bg-green-500/10 flex items-center justify-center",children:e.jsx(Il,{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(_e,{children:e.jsx(Oe,{className:"pt-6",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"h-10 w-10 rounded-lg bg-amber-500/10 flex items-center justify-center",children:e.jsx(Hr,{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(_e,{children:e.jsx(Oe,{className:"pt-6",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"h-10 w-10 rounded-lg bg-violet-500/10 flex items-center justify-center",children:e.jsx(Mu,{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(_e,{children:[e.jsx(Bt,{children:e.jsx(Ut,{className:"text-base",children:"Pipeline Breakdown"})}),e.jsx(Oe,{className:"space-y-3",children:a.byStage.map(i=>{const l=a.total>0?i.count/a.total*100:0;return e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"flex items-center justify-between text-sm",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"h-2.5 w-2.5 rounded-full",style:{backgroundColor:i.color}}),e.jsx("span",{children:i.name})]}),e.jsx("span",{className:"font-medium",children:i.count})]}),e.jsx("div",{className:"h-2 bg-muted rounded-full overflow-hidden",children:e.jsx("div",{className:"h-full rounded-full transition-all",style:{width:`${l}%`,backgroundColor:i.color}})})]},i.id)})})]}),e.jsxs(_e,{children:[e.jsx(Bt,{children:e.jsx(Ut,{className:"text-base",children:"Lead Sources"})}),e.jsxs(Oe,{className:"space-y-3",children:[a.bySrc.map(([i,l])=>e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx($e,{variant:"secondary",className:"capitalize",children:i.replace(/_/g," ")}),e.jsx("span",{className:"text-sm font-medium",children:l})]},i)),a.bySrc.length===0&&e.jsx("p",{className:"text-sm text-muted-foreground",children:"No source data"})]})]})]})]}):e.jsx("p",{className:"text-sm text-muted-foreground text-center py-8",children:"No prospect data yet. Add prospects to see metrics."})}const GRn=["Outreach","Follow-up","Interview","Offer","Referral","Other"];function $Vt({brokerageId:s}){const{toast:t}=gi(),{user:n}=_s(),r=ts(),[a,i]=j.useState(null),[l,o]=j.useState(null),[c,d]=j.useState(!1),[u,h]=j.useState(null),{data:m=[],isLoading:p}=ht({queryKey:["recruit-email-templates-manage",s],queryFn:async()=>{const{data:C,error:A}=await U.from("recruit_email_templates").select("*").or(`brokerage_id.is.null,brokerage_id.eq.${s}`).order("sort_order");if(A)throw A;return C}}),x=yt({mutationFn:async C=>{if(C.id){const{error:A}=await U.from("recruit_email_templates").update({category:C.category,title:C.title,subject:C.subject,body:C.body}).eq("id",C.id);if(A)throw A}else{const{error:A}=await U.from("recruit_email_templates").insert({brokerage_id:s,category:C.category||"Outreach",title:C.title,subject:C.subject,body:C.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:C=>t({title:"Save failed",description:C.message,variant:"destructive"})}),g=yt({mutationFn:async C=>{const{error:A}=await U.from("recruit_email_templates").delete().eq("id",C);if(A)throw A},onSuccess:()=>{r.invalidateQueries({queryKey:["recruit-email-templates-manage",s]}),r.invalidateQueries({queryKey:["recruit-email-templates"]}),t({title:"Template deleted"})},onError:C=>t({title:"Delete failed",description:C.message,variant:"destructive"})}),y=(C,A)=>{navigator.clipboard.writeText(C),i(A),t({title:"Copied to clipboard!"}),setTimeout(()=>i(null),2e3)},b=()=>{h({category:"Outreach",title:"",subject:"",body:""}),d(!0)},v=C=>{h(C),d(!0)},N=Array.from(new Set(m.map(C=>C.category)));return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3 flex-wrap",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Pre-built and custom recruiting templates. Built-in templates are global; your custom ones are private to this brokerage."}),e.jsxs($,{onClick:b,size:"sm",className:"gap-1.5",children:[e.jsx(sn,{className:"h-4 w-4"})," New Template"]})]}),p?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx(Ht,{className:"h-5 w-5 animate-spin text-muted-foreground"})}):N.map(C=>e.jsxs("div",{className:"space-y-3",children:[e.jsxs("h3",{className:"font-semibold text-sm flex items-center gap-2",children:[e.jsx(nn,{className:"h-4 w-4"})," ",C]}),m.filter(A=>A.category===C).map(A=>{const T=A.brokerage_id!==null;return e.jsxs(_e,{className:`transition-all ${l===A.id?"ring-2 ring-primary/20":"hover:shadow-sm"}`,children:[e.jsx(Bt,{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(Ut,{className:"text-sm flex items-center gap-2",children:[e.jsx("span",{className:"truncate",children:A.title}),!T&&e.jsx($e,{variant:"secondary",className:"text-[10px] shrink-0",children:"Built-in"}),T&&e.jsx($e,{className:"text-[10px] shrink-0",children:"Custom"})]}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-0.5 truncate",children:["Subject: ",A.subject]})]}),e.jsx($e,{variant:"outline",className:"text-[10px] shrink-0",children:A.category})]})}),l===A.id&&e.jsxs(Oe,{className:"pt-0 space-y-3",children:[e.jsxs("div",{className:"bg-muted/50 rounded-lg p-4",children:[e.jsx("p",{className:"text-xs font-medium text-muted-foreground mb-1",children:"Subject Line:"}),e.jsx("p",{className:"text-sm mb-3",children:A.subject}),e.jsx("p",{className:"text-xs font-medium text-muted-foreground mb-1",children:"Body:"}),e.jsx("pre",{className:"text-sm whitespace-pre-wrap font-sans",children:A.body})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs($,{size:"sm",variant:"outline",onClick:()=>y(A.subject,A.id+"-s"),children:[a===A.id+"-s"?e.jsx(oa,{className:"h-3.5 w-3.5 mr-1"}):e.jsx(Ca,{className:"h-3.5 w-3.5 mr-1"}),"Copy Subject"]}),e.jsxs($,{size:"sm",variant:"outline",onClick:()=>y(A.body,A.id+"-b"),children:[a===A.id+"-b"?e.jsx(oa,{className:"h-3.5 w-3.5 mr-1"}):e.jsx(Ca,{className:"h-3.5 w-3.5 mr-1"}),"Copy Body"]}),T&&e.jsxs(e.Fragment,{children:[e.jsxs($,{size:"sm",variant:"outline",onClick:()=>v(A),children:[e.jsx(Ya,{className:"h-3.5 w-3.5 mr-1"})," Edit"]}),e.jsxs($,{size:"sm",variant:"outline",className:"text-destructive hover:text-destructive",onClick:async()=>{await Yi("Delete this template?")&&g.mutate(A.id)},children:[e.jsx(Pn,{className:"h-3.5 w-3.5 mr-1"})," Delete"]})]})]})]})]},A.id)})]},C)),e.jsx(Os,{open:c,onOpenChange:d,children:e.jsxs(Rs,{className:"max-w-2xl",children:[e.jsx(Us,{children:e.jsx(zs,{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(se,{className:"text-xs",children:"Title"}),e.jsx(be,{value:(u==null?void 0:u.title)||"",onChange:C=>h(A=>({...A,title:C.target.value})),className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-xs",children:"Category"}),e.jsx("select",{value:(u==null?void 0:u.category)||"Outreach",onChange:C=>h(A=>({...A,category:C.target.value})),className:"mt-1 flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm",children:GRn.map(C=>e.jsx("option",{value:C,children:C},C))})]})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-xs",children:"Subject"}),e.jsx(be,{value:(u==null?void 0:u.subject)||"",onChange:C=>h(A=>({...A,subject:C.target.value})),className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-xs",children:"Body"}),e.jsx(Is,{value:(u==null?void 0:u.body)||"",onChange:C=>h(A=>({...A,body:C.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(kr,{children:[e.jsx($,{variant:"ghost",onClick:()=>d(!1),children:"Cancel"}),e.jsxs($,{onClick:()=>x.mutate(u||{}),disabled:x.isPending||!(u!=null&&u.title)||!(u!=null&&u.subject)||!(u!=null&&u.body),children:[x.isPending&&e.jsx(Ht,{className:"h-4 w-4 mr-2 animate-spin"}),"Save Template"]})]})]})})]})}const qvt={call:ya,email:nn,text:Ji,meeting:ia,note:Wr};function UVt({brokerageId:s}){const{data:t,isLoading:n}=ht({queryKey:["recruit-activity-report",s],queryFn:async()=>{const{data:r,error:a}=await U.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 U.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 U.from("profiles").select("id, name, email").in("id",c),u=Object.fromEntries((d||[]).map(p=>[p.id,p])),h=fY(new Date,30);return{recruiters:c.map(p=>{var v,N;const x=(l||[]).filter(C=>C.created_by===p),g=x.filter(C=>new Date(C.created_at)>=h),y={};g.forEach(C=>{y[C.activity_type]=(y[C.activity_type]||0)+1});const b=r.filter(C=>C.created_by===p).length;return{id:p,name:((v=u[p])==null?void 0:v.name)||"Unknown",email:((N=u[p])==null?void 0:N.email)||"",totalActivities:x.length,recentActivities:g.length,byType:y,prospectsCreated:b}}).sort((p,x)=>x.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(_e,{children:[e.jsx(Bt,{children:e.jsx(Ut,{className:"text-base",children:"Recruiter Leaderboard (Last 30 Days)"})}),e.jsx(Oe,{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(Lo,{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=qvt[i]||Wr;return e.jsxs($e,{variant:"outline",className:"text-[10px] gap-1",children:[e.jsx(o,{className:"h-2.5 w-2.5"})," ",l," ",i,l!==1?"s":""]},i)})})]}),e.jsxs("div",{className:"text-right",children:[e.jsx("p",{className:"text-lg font-bold",children:r.recentActivities}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:"activities"})]}),e.jsxs("div",{className:"text-right",children:[e.jsx("p",{className:"text-lg font-bold",children:r.prospectsCreated}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:"prospects"})]})]},r.id))})]}),e.jsxs(_e,{children:[e.jsx(Bt,{children:e.jsx(Ut,{className:"text-base",children:"Recent Activity"})}),e.jsx(Oe,{className:"space-y-3",children:t.recentActivities.map(r=>{const a=qvt[r.activity_type]||Wr;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:Hs(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 qVt({brokerageId:s}){const{toast:t}=gi(),n=ts(),[r,a]=j.useState(!1),[i,l]=j.useState({first_name:"",last_name:"",email:"",phone:"",current_brokerage:"",notes:""}),{data:o=[],isLoading:c}=ht({queryKey:["recruit-referrals",s],queryFn:async()=>{const{data:y,error:b}=await U.from("recruit_referrals").select("*").eq("brokerage_id",s).order("created_at",{ascending:!1});if(b)throw b;return y}}),d=[...new Set(o.map(y=>y.referred_by))],{data:u=[]}=ht({queryKey:["referral-profiles",d],queryFn:async()=>{if(!d.length)return[];const{data:y}=await U.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:b}}=await U.auth.getUser();if(!b)throw new Error("Not authenticated");const{error:v}=await U.from("recruit_referrals").insert({brokerage_id:s,referred_by:b.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(v)throw v},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:b,incentive_status:v})=>{const N={updated_at:new Date().toISOString()};b&&(N.status=b),v&&(N.incentive_status=v);const{error:C}=await U.from("recruit_referrals").update(N).eq("id",y);if(C)throw C},onSuccess:()=>n.invalidateQueries({queryKey:["recruit-referrals",s]})}),x=y=>y==="approved"||y==="signed"?e.jsx(oa,{className:"h-3 w-3"}):y==="rejected"?e.jsx($d,{className:"h-3 w-3"}):e.jsx(Hr,{className:"h-3 w-3"}),g=y=>y==="approved"||y==="signed"||y==="paid"?"bg-green-500/10 text-green-600 border-green-200":y==="rejected"?"bg-red-500/10 text-red-600 border-red-200":"bg-amber-500/10 text-amber-600 border-amber-200";return c?e.jsx("div",{className:"flex justify-center py-8",children:e.jsx("div",{className:"h-6 w-6 animate-spin rounded-full border-4 border-primary border-t-transparent"})}):e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("p",{className:"text-sm text-muted-foreground",children:[o.length," referral",o.length!==1?"s":""]}),e.jsxs($,{onClick:()=>a(!0),children:[e.jsx(sn,{className:"h-4 w-4 mr-2"})," Submit Referral"]})]}),o.length===0?e.jsxs(_e,{className:"py-12 text-center",children:[e.jsx(il,{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 b;return e.jsx(_e,{className:"p-4",children:e.jsxs("div",{className:"flex items-start justify-between gap-4",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsxs("span",{className:"font-medium",children:[y.referee_first_name," ",y.referee_last_name]}),e.jsxs($e,{variant:"outline",className:g(y.status),children:[x(y.status)," ",y.status]}),y.incentive_status&&e.jsxs($e,{variant:"outline",className:g(y.incentive_status),children:[e.jsx(Co,{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: ",((b=h[y.referred_by])==null?void 0:b.name)||"Unknown"," • ",Hs(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(vs,{value:y.status,onValueChange:v=>p.mutate({id:y.id,status:v}),children:[e.jsx(gs,{className:"h-7 text-xs w-[110px]",children:e.jsx(bs,{})}),e.jsxs(ys,{children:[e.jsx(Ye,{value:"pending",children:"Pending"}),e.jsx(Ye,{value:"contacted",children:"Contacted"}),e.jsx(Ye,{value:"approved",children:"Approved"}),e.jsx(Ye,{value:"signed",children:"Signed"}),e.jsx(Ye,{value:"rejected",children:"Rejected"})]})]}),e.jsxs(vs,{value:y.incentive_status||"pending",onValueChange:v=>p.mutate({id:y.id,incentive_status:v}),children:[e.jsx(gs,{className:"h-7 text-xs w-[100px]",children:e.jsx(bs,{})}),e.jsxs(ys,{children:[e.jsx(Ye,{value:"pending",children:"Unpaid"}),e.jsx(Ye,{value:"paid",children:"Paid"}),e.jsx(Ye,{value:"n/a",children:"N/A"})]})]})]})]})},y.id)})}),e.jsx(Os,{open:r,onOpenChange:a,children:e.jsxs(Rs,{children:[e.jsx(Us,{children:e.jsx(zs,{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(se,{children:"First Name *"}),e.jsx(be,{required:!0,value:i.first_name,onChange:y=>l(b=>({...b,first_name:y.target.value}))})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Last Name"}),e.jsx(be,{value:i.last_name,onChange:y=>l(b=>({...b,last_name:y.target.value}))})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(se,{children:"Email"}),e.jsx(be,{type:"email",value:i.email,onChange:y=>l(b=>({...b,email:y.target.value}))})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Phone"}),e.jsx(be,{value:i.phone,onChange:y=>l(b=>({...b,phone:y.target.value}))})]})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Current Brokerage"}),e.jsx(be,{value:i.current_brokerage,onChange:y=>l(b=>({...b,current_brokerage:y.target.value}))})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Notes"}),e.jsx(Is,{value:i.notes,onChange:y=>l(b=>({...b,notes:y.target.value})),rows:2})]}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx($,{type:"button",variant:"outline",onClick:()=>a(!1),children:"Cancel"}),e.jsx($,{type:"submit",disabled:m.isPending,children:"Submit"})]})]})]})})]})}function VVt({brokerageId:s}){const{toast:t}=gi(),n=ts(),[r,a]=j.useState(!1),{data:i}=ht({queryKey:["brokerage-recruit-form",s],queryFn:async()=>{const{data:m,error:p}=await U.from("brokerages").select("id, name, recruit_form_slug, recruit_form_enabled").eq("id",s).single();if(p)throw p;return m}}),{data:l=[]}=ht({queryKey:["recruit-interest-submissions",s],queryFn:async()=>{const{data:m,error:p}=await U.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 U.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:x}=await U.from("recruit_interest_submissions").update({status:p}).eq("id",m);if(x)throw x},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(_e,{children:[e.jsx(Bt,{children:e.jsx(Ut,{className:"text-base",children:"Public Interest Form"})}),e.jsxs(Oe,{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(se,{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(Tn,{checked:(i==null?void 0:i.recruit_form_enabled)||!1,onCheckedChange:m=>o.mutate(m)})]}),(i==null?void 0:i.recruit_form_enabled)&&e.jsxs("div",{className:"flex items-center gap-2 p-3 bg-muted/50 rounded-lg",children:[e.jsx("code",{className:"text-xs flex-1 truncate",children:d}),e.jsx($,{size:"sm",variant:"outline",onClick:u,children:r?e.jsx(oa,{className:"h-3.5 w-3.5"}):e.jsx(Ca,{className:"h-3.5 w-3.5"})}),e.jsx($,{size:"sm",variant:"outline",asChild:!0,children:e.jsx("a",{href:d,target:"_blank",rel:"noopener noreferrer",children:e.jsx(Tr,{className:"h-3.5 w-3.5"})})})]})]})]}),e.jsxs(_e,{children:[e.jsx(Bt,{children:e.jsxs(Ut,{className:"text-base",children:["Interest Submissions (",l.length,")"]})}),e.jsx(Oe,{children:l.length===0?e.jsxs("div",{className:"text-center py-8",children:[e.jsx(il,{className:"h-8 w-8 mx-auto text-muted-foreground mb-2"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"No submissions yet"})]}):e.jsx("div",{className:"space-y-3",children:l.map(m=>e.jsxs("div",{className:"flex items-start justify-between gap-4 p-3 border rounded-lg",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsxs("span",{className:"font-medium text-sm",children:[m.first_name," ",m.last_name]}),e.jsx($e,{variant:"outline",className:h(m.status),children:m.status})]}),e.jsxs("div",{className:"flex flex-wrap gap-3 text-xs text-muted-foreground",children:[m.email&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(nn,{className:"h-3 w-3"}),m.email]}),m.phone&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(ya,{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:Hs(new Date(m.created_at),"MMM d, yyyy h:mm a")})]}),e.jsxs(vs,{value:m.status,onValueChange:p=>c.mutate({id:m.id,status:p}),children:[e.jsx(gs,{className:"h-7 text-xs w-[110px]",children:e.jsx(bs,{})}),e.jsxs(ys,{children:[e.jsx(Ye,{value:"new",children:"New"}),e.jsx(Ye,{value:"contacted",children:"Contacted"}),e.jsx(Ye,{value:"converted",children:"Converted"}),e.jsx(Ye,{value:"dismissed",children:"Dismissed"})]})]})]},m.id))})})]})]})}function HVt({brokerageId:s}){const{toast:t}=gi(),n=ts(),[r,a]=j.useState(!1),[i,l]=j.useState({prospect_id:"",title:"",description:"",due_date:Hs(Bd(new Date,1),"yyyy-MM-dd'T'HH:mm")}),[o,c]=j.useState("pending"),{data:d=[]}=ht({queryKey:["recruit-prospects-list",s],queryFn:async()=>{const{data:A,error:T}=await U.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}=ht({queryKey:["recruit-follow-ups",s],queryFn:async()=>{const A=d.map(M=>M.id);if(!A.length)return[];const{data:T,error:P}=await U.from("recruit_follow_ups").select("*").in("prospect_id",A).order("due_date");if(P)throw P;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 U.auth.getUser();if(!T)throw new Error("Not authenticated");const{error:P}=await U.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(P)throw P},onSuccess:()=>{n.invalidateQueries({queryKey:["recruit-follow-ups",s]}),t({title:"Follow-up scheduled"}),l({prospect_id:"",title:"",description:"",due_date:Hs(Bd(new Date,1),"yyyy-MM-dd'T'HH:mm")}),a(!1)},onError:A=>t({title:"Error",description:A.message,variant:"destructive"})}),x=yt({mutationFn:async({id:A,completed:T})=>{const{error:P}=await U.from("recruit_follow_ups").update({completed_at:T?new Date().toISOString():null}).eq("id",A);if(P)throw P},onSuccess:()=>n.invalidateQueries({queryKey:["recruit-follow-ups",s]})}),g=u.filter(A=>o==="pending"?!A.completed_at:o==="completed"?!!A.completed_at:!0),y=g.filter(A=>!A.completed_at&&d5(new Date(A.due_date))&&!x0(new Date(A.due_date))),b=g.filter(A=>!A.completed_at&&x0(new Date(A.due_date))),v=g.filter(A=>!A.completed_at&&!d5(new Date(A.due_date))&&!x0(new Date(A.due_date))),N=g.filter(A=>!!A.completed_at),C=A=>{const T=m[A.prospect_id],P=!A.completed_at&&d5(new Date(A.due_date))&&!x0(new Date(A.due_date));return e.jsxs("div",{className:"flex items-start gap-3 p-3 border rounded-lg",children:[e.jsx(ui,{checked:!!A.completed_at,onCheckedChange:M=>x.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($e,{variant:"secondary",className:"text-[10px]",children:[T.first_name," ",T.last_name]}),e.jsxs("span",{className:`flex items-center gap-1 ${P?"text-destructive font-medium":""}`,children:[P?e.jsx(xo,{className:"h-3 w-3"}):e.jsx(ia,{className:"h-3 w-3"}),Hs(new Date(A.due_date),"MMM d, h:mm a")]}),A.is_automated&&e.jsx($e,{variant:"outline",className:"text-[10px]",children:"Auto"})]})]})]},A.id)};return h?e.jsx("div",{className:"flex justify-center py-8",children:e.jsx("div",{className:"h-6 w-6 animate-spin rounded-full border-4 border-primary border-t-transparent"})}):e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("div",{className:"flex gap-2",children:["pending","completed","all"].map(A=>e.jsxs($,{size:"sm",variant:o===A?"default":"outline",onClick:()=>c(A),className:"capitalize text-xs",children:[A," ",A==="pending"&&y.length+b.length+v.length>0&&`(${y.length+b.length+v.length})`]},A))}),e.jsxs($,{size:"sm",onClick:()=>a(!0),children:[e.jsx(sn,{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(xo,{className:"h-3.5 w-3.5"})," Overdue (",y.length,")"]}),y.map(C)]}),o!=="completed"&&b.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(Hr,{className:"h-3.5 w-3.5"})," Today (",b.length,")"]}),b.map(C)]}),o!=="completed"&&v.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(ia,{className:"h-3.5 w-3.5"})," Upcoming (",v.length,")"]}),v.map(C)]}),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(oa,{className:"h-3.5 w-3.5"})," Completed (",N.length,")"]}),N.map(C)]}),g.length===0&&e.jsxs("p",{className:"text-sm text-muted-foreground text-center py-8",children:["No follow-ups ",o!=="all"?`(${o})`:""]}),e.jsx(Os,{open:r,onOpenChange:a,children:e.jsxs(Rs,{children:[e.jsx(Us,{children:e.jsx(zs,{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(se,{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(se,{children:"Task *"}),e.jsx(be,{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(se,{children:"Details"}),e.jsx(Is,{value:i.description,onChange:A=>l(T=>({...T,description:A.target.value})),rows:2})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Due Date *"}),e.jsx(be,{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($,{type:"button",variant:"outline",onClick:()=>a(!1),children:"Cancel"}),e.jsx($,{type:"submit",disabled:p.isPending,children:"Schedule"})]})]})]})})]})}const WRn=[{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 GVt({brokerageId:s}){const{toast:t}=gi(),n=ts(),[r,a]=j.useState(null),{data:i,isLoading:l}=ht({queryKey:["recruit-landing-settings",s],queryFn:async()=>{const{data:y,error:b}=await U.from("recruit_landing_page_settings").select("*").eq("brokerage_id",s).maybeSingle();if(b)throw b;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:WRn,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:b}=await U.from("recruit_landing_page_settings").update(y).eq("id",o.id);if(b)throw b}else{const{error:b}=await U.from("recruit_landing_page_settings").insert(y);if(b)throw b}},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,b)=>{const v=y.name.split(".").pop(),N=`${s}/${b}-${Date.now()}.${v}`,{error:C}=await U.storage.from("recruit-landing").upload(N,y);if(C)throw C;const{data:{publicUrl:A}}=U.storage.from("recruit-landing").getPublicUrl(N);return A},h=async(y,b)=>{var N;const v=(N=y.target.files)==null?void 0:N[0];if(v){a(b);try{const C=await u(v,b);c(A=>({...A,[b]:C})),t({title:"Image uploaded!"})}catch(C){t({title:"Upload failed",description:C.message,variant:"destructive"})}finally{a(null)}}},m=async y=>{var v;const b=(v=y.target.files)==null?void 0:v[0];if(b){a("gallery");try{const N=await u(b,"gallery");c(C=>({...C,gallery_images:[...C.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,b)=>{var N;const v=(N=y.target.files)==null?void 0:N[0];if(v){a(`testimonial-${b}`);try{const C=await u(v,`testimonial-${b}`);c(A=>{const T=[...A.testimonials];return T[b]={...T[b],photo_url:C},{...A,testimonials:T}})}catch(C){t({title:"Upload failed",description:C.message,variant:"destructive"})}finally{a(null)}}},{data:x}=ht({queryKey:["brokerage-slug-for-landing",s],queryFn:async()=>{const{data:y,error:b}=await U.from("brokerages").select("recruit_form_slug, recruit_form_enabled").eq("id",s).single();if(b)throw b;return y}}),g=`https://bestbrokerage.relevelup.com/join-brokerage/${(x==null?void 0:x.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:[(x==null?void 0:x.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:g}),e.jsx($,{size:"sm",variant:"outline",asChild:!0,children:e.jsxs("a",{href:g,target:"_blank",rel:"noopener noreferrer",children:[e.jsx(Tr,{className:"h-3.5 w-3.5 mr-1"})," Preview"]})})]}),e.jsxs(_e,{children:[e.jsx(Bt,{children:e.jsx(Ut,{className:"text-base",children:"Branding"})}),e.jsx(Oe,{className:"space-y-4",children:e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx(se,{children:"Logo"}),e.jsxs("div",{className:"flex items-center gap-3 mt-1",children:[o.logo_url&&e.jsx("img",{src:o.logo_url,alt:"Logo",className:"h-10 w-auto rounded"}),e.jsxs("label",{className:"cursor-pointer",children:[e.jsx($,{variant:"outline",size:"sm",asChild:!0,disabled:r==="logo_url",children:e.jsxs("span",{children:[e.jsx(si,{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(se,{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(b=>({...b,primary_color:y.target.value})),className:"h-9 w-12 rounded border cursor-pointer"}),e.jsx(be,{value:o.primary_color,onChange:y=>c(b=>({...b,primary_color:y.target.value})),className:"font-mono text-xs"})]})]}),e.jsxs("div",{children:[e.jsx(se,{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(b=>({...b,accent_color:y.target.value})),className:"h-9 w-12 rounded border cursor-pointer"}),e.jsx(be,{value:o.accent_color,onChange:y=>c(b=>({...b,accent_color:y.target.value})),className:"font-mono text-xs"})]})]})]})]})})]}),e.jsxs(_e,{children:[e.jsx(Bt,{children:e.jsx(Ut,{className:"text-base",children:"Hero Section"})}),e.jsxs(Oe,{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(se,{children:"Headline"}),e.jsx(be,{value:o.hero_headline,onChange:y=>c(b=>({...b,hero_headline:y.target.value})),placeholder:"Join Our Team"})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Subtext"}),e.jsx(Is,{value:o.hero_subtext,onChange:y=>c(b=>({...b,hero_subtext:y.target.value})),rows:2,placeholder:"Take your career to the next level..."})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Background Image"}),e.jsxs("div",{className:"flex items-center gap-3 mt-1",children:[o.hero_image_url&&e.jsx("img",{src:o.hero_image_url,alt:"Hero",className:"h-16 w-28 object-cover rounded"}),e.jsxs("label",{className:"cursor-pointer",children:[e.jsx($,{variant:"outline",size:"sm",asChild:!0,disabled:r==="hero_image_url",children:e.jsxs("span",{children:[e.jsx(si,{className:"h-3.5 w-3.5 mr-1"}),r==="hero_image_url"?"Uploading...":"Upload Image"]})}),e.jsx("input",{type:"file",accept:"image/*",className:"hidden",onChange:y=>h(y,"hero_image_url")})]}),o.hero_image_url&&e.jsx($,{variant:"ghost",size:"sm",onClick:()=>c(y=>({...y,hero_image_url:null})),children:e.jsx(Pn,{className:"h-3.5 w-3.5"})})]})]})]})]}),e.jsxs(_e,{children:[e.jsxs(Bt,{className:"flex flex-row items-center justify-between",children:[e.jsx(Ut,{className:"text-base",children:"Benefits / Why Join Us"}),e.jsxs($,{size:"sm",variant:"outline",onClick:()=>c(y=>({...y,benefits:[...y.benefits,{title:"",description:"",icon:"✨"}]})),children:[e.jsx(sn,{className:"h-3.5 w-3.5 mr-1"})," Add"]})]}),e.jsxs(Oe,{className:"space-y-3",children:[o.benefits.map((y,b)=>e.jsxs("div",{className:"flex items-start gap-3 p-3 border rounded-lg",children:[e.jsx($p,{className:"h-4 w-4 mt-2 text-muted-foreground"}),e.jsx(be,{value:y.icon,onChange:v=>{const N=[...o.benefits];N[b]={...y,icon:v.target.value},c(C=>({...C,benefits:N}))},className:"w-14 text-center"}),e.jsxs("div",{className:"flex-1 space-y-2",children:[e.jsx(be,{value:y.title,onChange:v=>{const N=[...o.benefits];N[b]={...y,title:v.target.value},c(C=>({...C,benefits:N}))},placeholder:"Benefit title"}),e.jsx(be,{value:y.description,onChange:v=>{const N=[...o.benefits];N[b]={...y,description:v.target.value},c(C=>({...C,benefits:N}))},placeholder:"Short description"})]}),e.jsx($,{variant:"ghost",size:"sm",onClick:()=>c(v=>({...v,benefits:v.benefits.filter((N,C)=>C!==b)})),children:e.jsx(Pn,{className:"h-3.5 w-3.5 text-destructive"})})]},b)),o.benefits.length===0&&e.jsx("p",{className:"text-sm text-muted-foreground text-center py-4",children:"No benefits added yet"})]})]}),e.jsxs(_e,{children:[e.jsxs(Bt,{className:"flex flex-row items-center justify-between",children:[e.jsx(Ut,{className:"text-base",children:"Testimonials"}),e.jsxs($,{size:"sm",variant:"outline",onClick:()=>c(y=>({...y,testimonials:[...y.testimonials,{name:"",role:"",quote:""}]})),children:[e.jsx(sn,{className:"h-3.5 w-3.5 mr-1"})," Add"]})]}),e.jsxs(Oe,{className:"space-y-3",children:[o.testimonials.map((y,b)=>{var v;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:((v=y.name)==null?void 0:v[0])||"?"}),e.jsxs("label",{className:"cursor-pointer",children:[e.jsx("span",{className:"text-[10px] text-primary hover:underline",children:r===`testimonial-${b}`?"...":"Photo"}),e.jsx("input",{type:"file",accept:"image/*",className:"hidden",onChange:N=>p(N,b)})]})]}),e.jsxs("div",{className:"flex-1 space-y-2",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsx(be,{value:y.name,onChange:N=>{const C=[...o.testimonials];C[b]={...y,name:N.target.value},c(A=>({...A,testimonials:C}))},placeholder:"Name"}),e.jsx(be,{value:y.role,onChange:N=>{const C=[...o.testimonials];C[b]={...y,role:N.target.value},c(A=>({...A,testimonials:C}))},placeholder:"Role / Title"})]}),e.jsx(Is,{value:y.quote,onChange:N=>{const C=[...o.testimonials];C[b]={...y,quote:N.target.value},c(A=>({...A,testimonials:C}))},placeholder:"What they say about working here...",rows:2})]}),e.jsx($,{variant:"ghost",size:"sm",onClick:()=>c(N=>({...N,testimonials:N.testimonials.filter((C,A)=>A!==b)})),children:e.jsx(Pn,{className:"h-3.5 w-3.5 text-destructive"})})]},b)}),o.testimonials.length===0&&e.jsx("p",{className:"text-sm text-muted-foreground text-center py-4",children:"No testimonials added yet"})]})]}),e.jsxs(_e,{children:[e.jsxs(Bt,{className:"flex flex-row items-center justify-between",children:[e.jsx(Ut,{className:"text-base",children:"Team & Culture Gallery"}),e.jsxs("label",{className:"cursor-pointer",children:[e.jsx($,{size:"sm",variant:"outline",asChild:!0,disabled:r==="gallery",children:e.jsxs("span",{children:[e.jsx(Jl,{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(Oe,{children:o.gallery_images.length>0?e.jsx("div",{className:"grid grid-cols-3 md:grid-cols-4 gap-2",children:o.gallery_images.map((y,b)=>e.jsxs("div",{className:"relative group",children:[e.jsx("img",{src:y,alt:`Gallery ${b+1}`,className:"h-24 w-full object-cover rounded-lg"}),e.jsx($,{variant:"destructive",size:"sm",className:"absolute top-1 right-1 h-6 w-6 p-0 opacity-0 group-hover:opacity-100 transition-opacity",onClick:()=>c(v=>({...v,gallery_images:v.gallery_images.filter((N,C)=>C!==b)})),children:e.jsx(Pn,{className:"h-3 w-3"})})]},b))}):e.jsx("p",{className:"text-sm text-muted-foreground text-center py-4",children:"No gallery images added yet"})})]}),e.jsxs(_e,{children:[e.jsx(Bt,{children:e.jsxs(Ut,{className:"text-base flex items-center gap-2",children:[e.jsx(dn,{className:"h-4 w-4 text-primary"})," Form Style & Trust"]})}),e.jsxs(Oe,{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(se,{children:"Application Form Style"}),e.jsxs(vs,{value:o.form_style,onValueChange:y=>c(b=>({...b,form_style:y})),children:[e.jsx(gs,{className:"mt-1.5",children:e.jsx(bs,{})}),e.jsxs(ys,{children:[e.jsx(Ye,{value:"classic",children:"Classic — single-page form (all fields visible)"}),e.jsx(Ye,{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(Ad,{className:"h-4 w-4 mt-0.5 text-primary"}),e.jsxs("div",{children:[e.jsx(se,{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(Tn,{checked:o.confidential_messaging,onCheckedChange:y=>c(b=>({...b,confidential_messaging:y}))})]})]})]}),e.jsxs(_e,{children:[e.jsxs(Bt,{className:"flex flex-row items-center justify-between",children:[e.jsxs(Ut,{className:"text-base flex items-center gap-2",children:[e.jsx(s5,{className:"h-4 w-4 text-primary"})," Split & Income Calculator"]}),e.jsx(Tn,{checked:o.calculator_enabled,onCheckedChange:y=>c(b=>({...b,calculator_enabled:y}))})]}),o.calculator_enabled&&e.jsxs(Oe,{className:"space-y-4",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Highest-converting recruiting tool. Agents enter their GCI and instantly see what they'd earn at your brokerage."}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(se,{className:"text-xs",children:"Calculator Headline"}),e.jsx(be,{value:o.calculator_config.headline||"",onChange:y=>c(b=>({...b,calculator_config:{...b.calculator_config,headline:y.target.value}})),placeholder:"See What You Could Earn With Us"})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-xs",children:"Subtext"}),e.jsx(be,{value:o.calculator_config.subtext||"",onChange:y=>c(b=>({...b,calculator_config:{...b.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(se,{className:"text-xs",children:"Pre-Cap Split % (agent keeps)"}),e.jsx(be,{type:"number",value:o.calculator_config.commission_split_pct??80,onChange:y=>c(b=>({...b,calculator_config:{...b.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(se,{className:"text-xs",children:"Cap Amount ($)"}),e.jsx(be,{type:"number",value:o.calculator_config.cap_amount??16e3,onChange:y=>c(b=>({...b,calculator_config:{...b.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(se,{className:"text-xs",children:"Post-Cap Split % (agent keeps)"}),e.jsx(be,{type:"number",value:o.calculator_config.post_cap_split_pct??100,onChange:y=>c(b=>({...b,calculator_config:{...b.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(se,{className:"text-xs",children:"Monthly Fee ($)"}),e.jsx(be,{type:"number",value:o.calculator_config.monthly_fee??99,onChange:y=>c(b=>({...b,calculator_config:{...b.calculator_config,monthly_fee:parseFloat(y.target.value)||0}}))})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-xs",children:"Per-Transaction Fee ($)"}),e.jsx(be,{type:"number",value:o.calculator_config.transaction_fee??0,onChange:y=>c(b=>({...b,calculator_config:{...b.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(se,{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(Tn,{checked:o.calculator_config.show_email_capture!==!1,onCheckedChange:y=>c(b=>({...b,calculator_config:{...b.calculator_config,show_email_capture:y}}))})]})]})]}),e.jsxs(_e,{children:[e.jsxs(Bt,{className:"flex flex-row items-center justify-between",children:[e.jsxs(Ut,{className:"text-base flex items-center gap-2",children:[e.jsx(Bj,{className:"h-4 w-4 text-primary"})," Lead Magnet (Gated PDF)"]}),e.jsx(Tn,{checked:o.lead_magnet_enabled,onCheckedChange:y=>c(b=>({...b,lead_magnet_enabled:y}))})]}),o.lead_magnet_enabled&&e.jsxs(Oe,{className:"space-y-4",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Captures emails from agents not ready to talk. Offer a comp plan PDF, recruiting deck, or guide."}),e.jsxs("div",{children:[e.jsx(se,{className:"text-xs",children:"Title"}),e.jsx(be,{value:o.lead_magnet_config.title||"",onChange:y=>c(b=>({...b,lead_magnet_config:{...b.lead_magnet_config,title:y.target.value}})),placeholder:"Get the Full Comp Plan PDF"})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-xs",children:"Description"}),e.jsx(Is,{rows:2,value:o.lead_magnet_config.description||"",onChange:y=>c(b=>({...b,lead_magnet_config:{...b.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(se,{className:"text-xs",children:"Button Text"}),e.jsx(be,{value:o.lead_magnet_config.button_text||"",onChange:y=>c(b=>({...b,lead_magnet_config:{...b.lead_magnet_config,button_text:y.target.value}})),placeholder:"Email Me the PDF"})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-xs",children:"PDF / File URL"}),e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[e.jsx(be,{value:o.lead_magnet_config.pdf_url||"",onChange:y=>c(b=>({...b,lead_magnet_config:{...b.lead_magnet_config,pdf_url:y.target.value||null}})),placeholder:"https://...",className:"flex-1"}),e.jsxs("label",{className:"cursor-pointer",children:[e.jsx($,{variant:"outline",size:"sm",asChild:!0,disabled:r==="lead_magnet_pdf",children:e.jsxs("span",{children:[e.jsx(si,{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 v;const b=(v=y.target.files)==null?void 0:v[0];if(b){a("lead_magnet_pdf");try{const N=await u(b,"lead-magnet");c(C=>({...C,lead_magnet_config:{...C.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(KRn,{brokerageId:s}),e.jsx("div",{className:"flex justify-end",children:e.jsxs($,{onClick:()=>d.mutate(),disabled:d.isPending,size:"lg",children:[e.jsx(Jo,{className:"h-4 w-4 mr-2"}),d.isPending?"Saving...":"Save Landing Page"]})})]})}function KRn({brokerageId:s}){const{data:t=[]}=ht({queryKey:["lead-magnet-downloads",s],queryFn:async()=>{const{data:n,error:r}=await U.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(_e,{children:[e.jsx(Bt,{children:e.jsxs(Ut,{className:"text-base flex items-center gap-2",children:[e.jsx(di,{className:"h-4 w-4 text-primary"})," Lead Magnet Downloads (",t.length,")"]})}),e.jsx(Oe,{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:[Hs(new Date(n.created_at),"MMM d, yyyy h:mm a")," · via ",n.source]})]})},n.id))})})]})}function WVt({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,x]=j.useState("all"),[g,y]=j.useState(""),[b,v]=j.useState(null),[N,C]=j.useState(""),[A,T]=j.useState(0),[P,M]=j.useState(0),[I,D]=j.useState(""),[B,q]=j.useState(""),{data:W}=MTe(),[V,K]=j.useState("default");j.useEffect(()=>{K(W!=null&&W.massEmail?"mass_email":W!=null&&W.gmail?"gmail":"default")},[W==null?void 0:W.massEmail,W==null?void 0:W.gmail]);const[Q,J]=j.useState(null),{prospects:ce,stages:ue}=yte(s),ne=IVt(),ee=F5(),{data:le=[]}=ht({queryKey:["brokerage-recruit-video-pool",s],queryFn:async()=>{const{data:ke,error:Xe}=await U.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(Xe)throw Xe;return ke??[]},enabled:o&&d==="pick-video"}),he=j.useCallback(()=>{u("pick-recipients"),m(new Set(n?[n]:[])),x("all"),y(""),v(null),C(""),T(0),M(0),D(""),q(""),K("default"),J(null)},[n]),ve=ke=>{!ke&&(d==="uploading"||d==="processing"||d==="sending")||(c(ke),ke||setTimeout(he,200))},ge=j.useMemo(()=>ce.filter(ke=>{if(!ke.email||p!=="all"&&ke.stage_id!==p)return!1;if(g){const Xe=g.toLowerCase();if(!`${ke.first_name} ${ke.last_name??""}`.toLowerCase().includes(Xe)&&!ke.email.toLowerCase().includes(Xe))return!1}return!0}),[ce,p,g]),fe=ke=>{m(Xe=>{const Se=new Set(Xe);return Se.has(ke)?Se.delete(ke):Se.add(ke),Se})},je=()=>{h.size===ge.length?m(new Set):m(new Set(ge.map(ke=>ke.id)))},Ee=j.useCallback(async(ke,Xe)=>{u("uploading");try{const Se=`Recruiting blast (${h.size} recipients)`,{videoId:Re,libraryId:Ae}=await Z6(Se),{uploadUrl:Be,apiKey:qe}=await X6(Re),Ke=new XMLHttpRequest;Ke.upload.onprogress=lt=>{lt.lengthComputable&&T(lt.loaded/lt.total*100)},await new Promise((lt,Mt)=>{Ke.onload=()=>Ke.status>=200&&Ke.status<300?lt():Mt(new Error("Upload failed")),Ke.onerror=()=>Mt(new Error("Upload failed")),Ke.open("PUT",Be),Ke.setRequestHeader("AccessKey",qe),Ke.send(ke)}),u("processing");const Ze=`https://iframe.mediadelivery.net/embed/${Ae}/${Re}`;let Ue=0;const et=Date.now(),Qe=9e4;for(;Ue<4&&(await new Promise(Mt=>setTimeout(Mt,3e3)),!(Date.now()-et>Qe));){const lt=await o2(Re);if(Ue=lt.status,M(lt.encodeProgress||0),Ue===5||Ue===6)throw new Error("Video processing failed")}const Ge=await o2(Re),nt=(Ge.storageSize||ke.size)/(1024*1024),ft=await ee.mutateAsync({bunny_video_id:Re,playback_url:Ge.directPlayUrl||Ze,thumbnail_url:Ge.thumbnailUrl,preview_url:Ge.previewUrl||null,duration_seconds:Ge.length||Xe,file_size_mb:nt,title:Se,status:Ue>=4?"ready":"processing",touch_type:"recruiting"});v(ft.id),C(Se),u("compose")}catch(Se){ae.error((Se==null?void 0:Se.message)||"Failed to upload video"),u("pick-video")}},[h.size,ee]),Me=j.useCallback(async()=>{if(!(!b||h.size===0)){u("sending");try{const ke=[];for(const Re of h){const Ae=await ne.mutateAsync({prospect_id:Re,video_id:b,brokerage_id:s,message:B||void 0});ke.push(Ae.id)}const{data:Xe,error:Se}=await U.functions.invoke("send-recruit-video-email",{body:{recruit_video_ids:ke,brokerage_id:s,subject_override:I||void 0,message_override:B||void 0,send_via:V}});if(Se)throw new Error(Se.message);J({sent:(Xe==null?void 0:Xe.sent)??0,total:(Xe==null?void 0:Xe.total)??ke.length}),u("done"),ae.success(`Sent ${(Xe==null?void 0:Xe.sent)??0} of ${(Xe==null?void 0:Xe.total)??ke.length} videos`)}catch(ke){ae.error((ke==null?void 0:ke.message)||"Failed to send"),u("compose")}}},[b,h,s,B,I,V,ne]),De=h.size,ze=ce.filter(ke=>!ke.email).length;return e.jsxs(Os,{open:o,onOpenChange:ve,children:[t&&e.jsx(Ko,{asChild:!0,children:t}),e.jsxs(Rs,{className:"max-w-3xl max-h-[90vh] overflow-hidden flex flex-col",children:[e.jsx(Us,{children:e.jsxs(zs,{className:"flex items-center gap-2",children:[e.jsx(Xr,{className:"h-5 w-5 text-primary"}),"Send Recruiting Video",De>0&&e.jsxs($e,{variant:"secondary",className:"ml-2",children:[e.jsx(qn,{className:"h-3 w-3 mr-1"}),De," ",De===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(Vr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(be,{placeholder:"Search prospects...",value:g,onChange:ke=>y(ke.target.value),className:"pl-9"})]}),e.jsxs(vs,{value:p,onValueChange:x,children:[e.jsx(gs,{className:"w-48",children:e.jsx(bs,{})}),e.jsxs(ys,{children:[e.jsx(Ye,{value:"all",children:"All stages"}),ue.map(ke=>e.jsx(Ye,{value:ke.id,children:ke.name},ke.id))]})]})]}),e.jsxs("div",{className:"flex items-center justify-between text-xs text-muted-foreground",children:[e.jsxs("button",{onClick:je,className:"hover:underline",children:[h.size===ge.length&&ge.length>0?"Deselect all":"Select all"," ","(",ge.length,")"]}),ze>0&&e.jsxs("span",{children:[ze," prospect(s) hidden — no email on file"]})]}),e.jsx(Oi,{className:"flex-1 border rounded-md",children:ge.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:ge.map(ke=>{const Xe=h.has(ke.id),Se=ue.find(Re=>Re.id===ke.stage_id);return e.jsxs("label",{className:"flex items-center gap-3 p-3 hover:bg-muted/30 cursor-pointer",children:[e.jsx(ui,{checked:Xe,onCheckedChange:()=>fe(ke.id)}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("p",{className:"font-medium text-sm truncate",children:[ke.first_name," ",ke.last_name]}),Se&&e.jsx($e,{variant:"outline",className:"text-[10px]",style:{borderColor:Se.color,color:Se.color},children:Se.name})]}),e.jsxs("p",{className:"text-xs text-muted-foreground truncate",children:[ke.email," ",ke.current_brokerage&&`· ${ke.current_brokerage}`]})]})]},ke.id)})})}),e.jsxs(kr,{children:[e.jsx($,{variant:"outline",onClick:()=>ve(!1),children:"Cancel"}),e.jsx($,{disabled:De===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(ua,{defaultValue:"record",className:"flex-1 flex flex-col overflow-hidden",children:[e.jsxs(ha,{className:"self-start",children:[e.jsxs(Qt,{value:"record",children:[e.jsx(sn,{className:"h-3.5 w-3.5 mr-1"}),"Record New"]}),e.jsxs(Qt,{value:"library",children:[e.jsx(g1,{className:"h-3.5 w-3.5 mr-1"}),"Use Existing"]})]}),e.jsx(Jt,{value:"record",className:"flex-1 overflow-auto",children:e.jsxs("div",{className:"text-center py-8 space-y-4",children:[e.jsx(lh,{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 ",De," ",De===1?"recipient":"recipients"," — each gets their own tracked link."]})]}),e.jsxs($,{onClick:()=>u("record"),children:[e.jsx(Xr,{className:"h-4 w-4 mr-2"}),"Start Recording"]})]})}),e.jsx(Jt,{value:"library",className:"flex-1 overflow-auto",children:le.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:le.map(ke=>e.jsxs("button",{onClick:()=>{v(ke.id),C(ke.title||"Untitled"),u("compose")},className:"text-left group rounded-md border overflow-hidden hover:border-primary transition-colors",children:[e.jsx("div",{className:"aspect-video bg-muted relative",children:WS(ke)?e.jsx("img",{src:WS(ke),alt:"",className:"w-full h-full object-cover",referrerPolicy:"no-referrer"}):e.jsx("div",{className:"w-full h-full flex items-center justify-center",children:e.jsx(Xr,{className:"h-8 w-8 text-muted-foreground"})})}),e.jsx("div",{className:"p-2",children:e.jsx("p",{className:"text-xs font-medium truncate",children:ke.title||"Untitled"})})]},ke.id))})})]}),e.jsx(kr,{children:e.jsx($,{variant:"outline",onClick:()=>u("pick-recipients"),children:"Back"})})]}),d==="record"&&e.jsxs("div",{className:"flex-1 overflow-auto",children:[e.jsx(J6,{maxDurationSeconds:600,onRecordingComplete:Ee}),e.jsx("div",{className:"mt-2 flex justify-start",children:e.jsx($,{variant:"ghost",size:"sm",onClick:()=>u("pick-video"),children:"← Back"})})]}),(d==="uploading"||d==="processing")&&e.jsxs("div",{className:"py-12 space-y-4 text-center",children:[e.jsx(Ht,{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(Ki,{value:d==="uploading"?A:P,className:"mx-auto max-w-sm"}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[Math.round(d==="uploading"?A:P),"%"]})]}),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(Fr,{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:De})," recipient",De===1?"":"s"]})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-xs",children:"Subject (optional override)"}),e.jsx(be,{value:I,onChange:ke=>D(ke.target.value),placeholder:"[First Name], I made you a quick video 🎥",className:"mt-1"}),e.jsx("p",{className:"text-[11px] text-muted-foreground mt-1",children:"Leave blank to use the default personalized subject."})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-xs",children:"Personal message shown in the email & on the landing page"}),e.jsx(Is,{value:B,onChange:ke=>q(ke.target.value),placeholder:"Hey there — wanted to share a quick thought on what we're building here...",rows:5,className:"mt-1"})]}),e.jsx(xXe,{value:V,onChange:K}),e.jsxs(kr,{children:[e.jsx($,{variant:"outline",onClick:()=>u("pick-video"),children:"Back"}),e.jsxs($,{onClick:Me,disabled:!b||De===0,children:[e.jsx(Br,{className:"h-4 w-4 mr-2"})," Send to ",De," ",De===1?"prospect":"prospects"]})]})]}),d==="sending"&&e.jsxs("div",{className:"py-12 text-center space-y-3",children:[e.jsx(Ht,{className:"h-8 w-8 animate-spin mx-auto text-primary"}),e.jsxs("p",{className:"font-medium",children:["Sending to ",De," recipient",De===1?"":"s","…"]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Each prospect gets their own tracked share link."})]}),d==="done"&&Q&&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 ${Q.sent===Q.total?"bg-primary/10":"bg-muted"}`,children:Q.sent===Q.total?e.jsx(Fr,{className:"h-8 w-8 text-primary"}):e.jsx(xo,{className:"h-8 w-8 text-muted-foreground"})}),e.jsxs("div",{children:[e.jsxs("p",{className:"font-semibold text-lg",children:[Q.sent," of ",Q.total," sent"]}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:"View engagement under the Video Outreach tab."})]}),e.jsx($,{onClick:()=>ve(!1),children:"Done"})]})]})]})}function YRn(s){if(!s)return"—";const t=Math.floor(s/60),n=s%60;return t>0?`${t}m ${n}s`:`${n}s`}function ZRn({video:s}){return s.cta_clicked_at?e.jsx($e,{className:"bg-emerald-500/10 text-emerald-600 border-emerald-200",children:"CTA Clicked"}):s.view_count>0?e.jsxs($e,{className:"bg-blue-500/10 text-blue-600 border-blue-200",children:[e.jsx(ga,{className:"h-3 w-3 mr-1"}),s.view_count," views"]}):s.sent_at?e.jsxs($e,{variant:"secondary",children:[e.jsx(Br,{className:"h-3 w-3 mr-1"}),"Sent"]}):e.jsxs($e,{variant:"outline",children:[e.jsx(Hr,{className:"h-3 w-3 mr-1"}),"Draft"]})}function KVt({brokerageId:s}){var N,C,A,T;const{data:t=[],isLoading:n}=ORn(s),{data:r=[]}=RVt(s),a=zRn(),i=BRn(),l=DVt(),[o,c]=j.useState(""),[d,u]=j.useState(!1),[h,m]=j.useState({title:"",script_text:"",category:"general"}),[p,x]=j.useState(null),g=t.filter(P=>{var I,D,B,q;return o?`${((I=P.prospect)==null?void 0:I.first_name)||""} ${((D=P.prospect)==null?void 0:D.last_name)||""}`.toLowerCase().includes(o.toLowerCase())||((q=(B=P.video)==null?void 0:B.title)==null?void 0:q.toLowerCase().includes(o.toLowerCase())):!0}),y={total:t.length,sent:t.filter(P=>P.sent_at).length,viewed:t.filter(P=>P.view_count>0).length,ctaClicked:t.filter(P=>P.cta_clicked_at).length},b=j.useCallback(P=>{if(!P)return;const M=`${window.location.origin}/recruit-video/${P}`;navigator.clipboard.writeText(M),ae.success("Share link copied")},[]);j.useCallback((P,M)=>{l.mutate({id:P,sent_via:M})},[l]);const v=()=>{!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:Xr,color:"text-primary"},{label:"Sent",value:y.sent,icon:Br,color:"text-blue-500"},{label:"Viewed",value:y.viewed,icon:ga,color:"text-amber-500"},{label:"CTA Clicked",value:y.ctaClicked,icon:Fr,color:"text-emerald-500"}].map(P=>e.jsx(_e,{children:e.jsxs(Oe,{className:"p-4 flex items-center gap-3",children:[e.jsx("div",{className:`h-10 w-10 rounded-lg bg-muted flex items-center justify-center ${P.color}`,children:e.jsx(P.icon,{className:"h-5 w-5"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-bold",children:P.value}),e.jsx("p",{className:"text-xs text-muted-foreground",children:P.label})]})]})},P.label))}),e.jsxs(ua,{defaultValue:"videos",className:"space-y-4",children:[e.jsxs(ha,{children:[e.jsxs(Qt,{value:"videos",children:[e.jsx(Xr,{className:"h-4 w-4 mr-1.5"}),"All Videos"]}),e.jsxs(Qt,{value:"scripts",children:[e.jsx(Wr,{className:"h-4 w-4 mr-1.5"}),"Script Library"]}),e.jsxs(Qt,{value:"analytics",children:[e.jsx(ml,{className:"h-4 w-4 mr-1.5"}),"Engagement"]})]}),e.jsx(Jt,{value:"videos",children:e.jsxs(_e,{children:[e.jsx(Bt,{className:"pb-3",children:e.jsxs("div",{className:"flex items-center justify-between gap-2 flex-wrap",children:[e.jsx(Ut,{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(Vr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(be,{placeholder:"Search by name or title...",value:o,onChange:P=>c(P.target.value),className:"pl-9"})]}),e.jsx(WVt,{brokerageId:s,trigger:e.jsxs($,{size:"sm",className:"gap-1.5",children:[e.jsx(nn,{className:"h-4 w-4"})," Send Video Email"]})})]})]})}),e.jsx(Oe,{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"})}):g.length===0?e.jsxs("div",{className:"text-center py-12 text-muted-foreground",children:[e.jsx(Xr,{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:g.map(P=>{var M,I,D,B,q,W,V;return e.jsxs("div",{className:"flex items-center gap-4 p-3 rounded-lg border bg-card hover:bg-muted/30 transition-colors",children:[e.jsxs("div",{className:"relative h-16 w-28 rounded-md overflow-hidden bg-muted flex-shrink-0",children:[WS(P.video)?e.jsx("img",{src:WS(P.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(Xr,{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:YRn(((M=P.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=P.prospect)==null?void 0:I.first_name," ",(D=P.prospect)==null?void 0:D.last_name]}),e.jsx(ZRn,{video:P})]}),e.jsx("p",{className:"text-sm text-muted-foreground truncate",children:((B=P.video)==null?void 0:B.title)||"Untitled video"}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-0.5",children:[Hs(new Date(P.created_at),"MMM d, yyyy"),((q=P.prospect)==null?void 0:q.current_brokerage)&&` · ${P.prospect.current_brokerage}`]})]}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx($,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:()=>b(P.share_token),title:"Copy share link",children:e.jsx(Ca,{className:"h-4 w-4"})}),e.jsxs($,{variant:P.sent_at?"ghost":"default",size:"sm",className:"h-8 gap-1.5",onClick:()=>x(P),disabled:!((W=P.prospect)!=null&&W.email),title:(V=P.prospect)!=null&&V.email?"Email this video to the prospect":"Prospect has no email",children:[e.jsx(nn,{className:"h-4 w-4"}),P.sent_at?"Resend":"Email"]}),P.share_token&&e.jsx($,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:()=>window.open(`/recruit-video/${P.share_token}`,"_blank"),title:"Preview landing page",children:e.jsx(Tr,{className:"h-4 w-4"})})]})]},P.id)})})})]})}),e.jsx(Jt,{value:"scripts",children:e.jsxs(_e,{children:[e.jsx(Bt,{className:"pb-3",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(Ut,{className:"text-lg",children:"Recruiting Scripts"}),e.jsxs(Os,{open:d,onOpenChange:u,children:[e.jsx(Ko,{asChild:!0,children:e.jsxs($,{size:"sm",children:[e.jsx(sn,{className:"h-4 w-4 mr-1.5"}),"New Script"]})}),e.jsxs(Rs,{children:[e.jsx(Us,{children:e.jsx(zs,{children:"Create Recruiting Script"})}),e.jsxs("div",{className:"space-y-4 mt-2",children:[e.jsxs("div",{children:[e.jsx(se,{children:"Title"}),e.jsx(be,{value:h.title,onChange:P=>m(M=>({...M,title:P.target.value})),placeholder:"e.g., Why Switch to Our Brokerage"})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Category"}),e.jsxs(vs,{value:h.category,onValueChange:P=>m(M=>({...M,category:P})),children:[e.jsx(gs,{children:e.jsx(bs,{})}),e.jsx(ys,{children:xUe.map(P=>e.jsx(Ye,{value:P.value,children:P.label},P.value))})]})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Script"}),e.jsx(Is,{value:h.script_text,onChange:P=>m(M=>({...M,script_text:P.target.value})),placeholder:"Hi [Name], I noticed you've been doing great work at [Brokerage]...",rows:8})]}),e.jsx($,{onClick:v,disabled:!h.title.trim()||!h.script_text.trim(),className:"w-full",children:"Save Script"})]})]})]})]})}),e.jsx(Oe,{children:r.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 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(P=>{var I;const M=((I=xUe.find(D=>D.value===P.category))==null?void 0:I.label)||P.category;return e.jsx(_e,{className:"relative group",children:e.jsxs(Oe,{className:"p-4",children:[e.jsxs("div",{className:"flex items-start justify-between",children:[e.jsxs("div",{children:[e.jsx($e,{variant:"outline",className:"text-[10px] mb-2",children:M}),e.jsx("h4",{className:"font-medium text-sm",children:P.title})]}),e.jsx($,{variant:"ghost",size:"icon",className:"h-7 w-7 opacity-0 group-hover:opacity-100 transition-opacity text-destructive",onClick:()=>i.mutate(P.id),children:e.jsx(Pn,{className:"h-3.5 w-3.5"})})]}),e.jsx("p",{className:"text-xs text-muted-foreground mt-2 line-clamp-3",children:P.script_text}),P.is_global&&e.jsx($e,{variant:"secondary",className:"mt-2 text-[10px]",children:"Template"})]})},P.id)})})})]})}),e.jsx(Jt,{value:"analytics",children:e.jsxs(_e,{children:[e.jsx(Bt,{children:e.jsx(Ut,{className:"text-lg",children:"Engagement Funnel"})}),e.jsxs(Oe,{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(P=>e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs("div",{className:"flex justify-between text-sm",children:[e.jsx("span",{children:P.label}),e.jsxs("span",{className:"font-medium",children:[P.count," (",P.pct,"%)"]})]}),e.jsx("div",{className:"h-3 bg-muted rounded-full overflow-hidden",children:e.jsx("div",{className:`h-full ${P.color} rounded-full transition-all`,style:{width:`${P.pct}%`}})})]},P.label))}),t.filter(P=>P.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(P=>P.view_count>0).sort((P,M)=>M.view_count-P.view_count).slice(0,5).map(P=>{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=P.prospect)==null?void 0:M.first_name," ",(I=P.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(ga,{className:"h-3.5 w-3.5"})," ",P.view_count]}),P.cta_clicked_at&&e.jsx(Fr,{className:"h-4 w-4 text-emerald-500"})]})]},P.id)})})]})]})]})})]}),p&&e.jsx(PVt,{open:!!p,onOpenChange:P=>{P||x(null)},recruitVideoId:p.id,brokerageId:s,prospectName:`${((N=p.prospect)==null?void 0:N.first_name)||""} ${((C=p.prospect)==null?void 0:C.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 YVt({brokerageId:s}){const{toast:t}=gi(),n=ts(),{stages:r,prospects:a}=yte(s),[i,l]=j.useState(!1),[o,c]=j.useState({title:"",target_count:"10",target_stage_id:"",period_start:Hs(new Date,"yyyy-MM-dd"),period_end:Hs(new Date(new Date().getFullYear(),new Date().getMonth()+3,0),"yyyy-MM-dd")}),{data:d=[],isLoading:u}=ht({queryKey:["recruit-goals",s],queryFn:async()=>{const{data:x,error:g}=await U.from("recruit_goals").select("*").eq("brokerage_id",s).order("period_end",{ascending:!1});if(g)throw g;return x}}),h=yt({mutationFn:async x=>{const{data:{user:g}}=await U.auth.getUser();if(!g)throw new Error("Not authenticated");const{error:y}=await U.from("recruit_goals").insert({brokerage_id:s,title:x.title,target_count:parseInt(x.target_count),target_stage_id:x.target_stage_id||null,period_start:x.period_start,period_end:x.period_end,created_by:g.id});if(y)throw y},onSuccess:()=>{n.invalidateQueries({queryKey:["recruit-goals",s]}),t({title:"Goal created"}),l(!1)},onError:x=>t({title:"Error",description:x.message,variant:"destructive"})}),m=yt({mutationFn:async x=>{const{error:g}=await U.from("recruit_goals").delete().eq("id",x);if(g)throw g},onSuccess:()=>{n.invalidateQueries({queryKey:["recruit-goals",s]}),t({title:"Goal removed"})}}),p=x=>{const g=r.find(b=>b.id===x.target_stage_id);return{count:a.filter(b=>xN(new Date(b.created_at),{start:new Date(x.period_start),end:new Date(x.period_end)})?x.target_stage_id?b.stage_id===x.target_stage_id:!0:!1).length,stage:g}};return u?e.jsx("div",{className:"flex justify-center py-8",children:e.jsx("div",{className:"h-6 w-6 animate-spin rounded-full border-4 border-primary border-t-transparent"})}):e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("p",{className:"text-sm text-muted-foreground",children:[d.length," goal",d.length!==1?"s":""]}),e.jsxs($,{size:"sm",onClick:()=>l(!0),children:[e.jsx(sn,{className:"h-4 w-4 mr-1"})," New Goal"]})]}),d.length===0?e.jsxs(_e,{className:"py-12 text-center",children:[e.jsx(Mu,{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(x=>{const{count:g,stage:y}=p(x),b=Math.min(100,g/x.target_count*100),v=xN(new Date,{start:new Date(x.period_start),end:new Date(x.period_end)});return e.jsxs(_e,{className:v?"":"opacity-60",children:[e.jsx(Bt,{className:"pb-2",children:e.jsxs("div",{className:"flex items-start justify-between",children:[e.jsxs("div",{children:[e.jsx(Ut,{className:"text-sm",children:x.title}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-0.5",children:[Hs(new Date(x.period_start),"MMM d")," – ",Hs(new Date(x.period_end),"MMM d, yyyy")]})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[v?e.jsx($e,{className:"text-[10px]",children:"Active"}):e.jsx($e,{variant:"secondary",className:"text-[10px]",children:"Ended"}),e.jsx($,{variant:"ghost",size:"icon",className:"h-6 w-6 text-muted-foreground",onClick:()=>m.mutate(x.id),children:e.jsx(Pn,{className:"h-3.5 w-3.5"})})]})]})}),e.jsxs(Oe,{className:"space-y-2",children:[y&&e.jsxs($e,{variant:"outline",className:"text-[10px]",style:{borderColor:y.color,color:y.color},children:["Stage: ",y.name]}),e.jsxs("div",{className:"flex items-center justify-between text-sm",children:[e.jsx("span",{className:"font-bold text-lg",children:g}),e.jsxs("span",{className:"text-muted-foreground",children:["/ ",x.target_count]})]}),e.jsx(Ki,{value:b,className:"h-2"}),e.jsxs("p",{className:"text-xs text-muted-foreground text-right",children:[b.toFixed(0),"% complete"]})]})]},x.id)})}),e.jsx(Os,{open:i,onOpenChange:l,children:e.jsxs(Rs,{children:[e.jsx(Us,{children:e.jsx(zs,{children:"Create Recruiting Goal"})}),e.jsxs("form",{onSubmit:x=>{x.preventDefault(),h.mutate(o)},className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx(se,{children:"Goal Title *"}),e.jsx(be,{required:!0,value:o.title,onChange:x=>c(g=>({...g,title:x.target.value})),placeholder:"e.g. Q2 Recruiting Target"})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Target Count *"}),e.jsx(be,{type:"number",min:"1",required:!0,value:o.target_count,onChange:x=>c(g=>({...g,target_count:x.target.value}))})]}),e.jsxs("div",{children:[e.jsx(se,{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:x=>c(g=>({...g,target_stage_id:x.target.value})),children:[e.jsx("option",{value:"",children:"All stages (total prospects)"}),r.map(x=>e.jsx("option",{value:x.id,children:x.name},x.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(se,{children:"Start Date"}),e.jsx(be,{type:"date",required:!0,value:o.period_start,onChange:x=>c(g=>({...g,period_start:x.target.value}))})]}),e.jsxs("div",{children:[e.jsx(se,{children:"End Date"}),e.jsx(be,{type:"date",required:!0,value:o.period_end,onChange:x=>c(g=>({...g,period_end:x.target.value}))})]})]}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx($,{type:"button",variant:"outline",onClick:()=>l(!1),children:"Cancel"}),e.jsx($,{type:"submit",disabled:h.isPending,children:"Create Goal"})]})]})]})})]})}const XRn={first_name:"Sarah",brokerage_name:"ABC Realty",city:"Austin",sender_name:"Jeremy"};function ZVt({email:s,mergeValues:t=XRn,selectedSubjectIndex:n,onClose:r}){var c;const a=d=>d.replace(/\{\{first_name\}\}/g,t.first_name).replace(/\{\{brokerage_name\}\}/g,t.brokerage_name).replace(/\{\{city\}\}/g,t.city).replace(/\{\{sender_name\}\}/g,t.sender_name).replace(/\{\{landing_page_link\}\}/g,"https://bestbrokerage.relevelup.com/join-brokerage/your-slug"),i=((c=s.subject_line_options)==null?void 0:c.length)>0?s.subject_line_options:[s.subject_line],l=n??0,o=i[l]||s.subject_line;return e.jsx(Os,{open:!0,onOpenChange:()=>r(),children:e.jsxs(Rs,{className:"max-w-2xl max-h-[85vh] overflow-y-auto p-0",children:[e.jsxs(Us,{className:"px-6 pt-6 pb-4 border-b",children:[e.jsxs(zs,{className:"text-base",children:["Email #",s.email_number," — ",s.title]}),e.jsxs("div",{className:"flex items-center gap-3 mt-2",children:[e.jsxs($e,{variant:"outline",className:"text-xs gap-1",children:[e.jsx(Hr,{className:"h-3 w-3"}),s.email_number===1?"Sent immediately":`Day ${s.delay_days}`]}),i.length>1&&e.jsxs($e,{variant:"secondary",className:"text-xs",children:[i.length," subject variants"]})]})]}),e.jsxs("div",{className:"space-y-0",children:[i.length>1&&e.jsxs("div",{className:"px-6 py-3 border-b bg-muted/20",children:[e.jsx("p",{className:"text-[10px] font-medium text-muted-foreground uppercase tracking-wider mb-2",children:"Subject Line Options"}),e.jsx("div",{className:"flex flex-col gap-1.5",children:i.map((d,u)=>e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:`text-[10px] font-bold uppercase px-1.5 py-0.5 rounded ${u===l?"bg-primary/10 text-primary":"bg-muted text-muted-foreground"}`,children:u===l?"Selected":u===0?"Primary":`Alt ${u}`}),e.jsx("span",{className:"text-sm",children:a(d)})]},u))})]}),e.jsxs("div",{className:"border-b",children:[e.jsxs("div",{className:"px-6 py-2 flex items-center gap-2 text-xs text-muted-foreground",children:[e.jsx("span",{className:"font-medium w-14",children:"From:"}),e.jsxs("span",{children:[t.sender_name," "]})]}),e.jsxs("div",{className:"px-6 py-2 flex items-center gap-2 text-xs text-muted-foreground border-t",children:[e.jsx("span",{className:"font-medium w-14",children:"To:"}),e.jsxs("span",{children:[t.first_name," "]})]}),e.jsxs("div",{className:"px-6 py-2 flex items-center gap-2 text-xs border-t",children:[e.jsx("span",{className:"font-medium w-14 text-muted-foreground",children:"Subject:"}),e.jsx("span",{className:"font-medium",children:a(o)})]})]}),e.jsx("div",{className:"bg-white px-8 py-6",children:e.jsx("div",{className:"prose prose-sm max-w-none [&_p]:my-3 [&_p+p]:mt-4 [&_br]:block [&_br]:mt-2",style:{fontSize:"15px",lineHeight:"1.75",color:"#1a1a1a"},dangerouslySetInnerHTML:{__html:a(s.body_html)}})})]})]})})}function gXe({brokerageId:s}){const t=ts(),{user:n}=_s(),[r,a]=j.useState(""),[i,l]=j.useState(!1),[o,c]=j.useState({brokerage_id:s,sender_name:"LevelUp",sender_email:"recruiting@relevelup.com",reply_to_email:"",merge_fields:{city:"",broker_name:""}}),{data:d}=ht({queryKey:["brokerage-recruit-settings",s],queryFn:async()=>{const{data:x,error:g}=await U.from("brokerage_recruit_settings").select("*").eq("brokerage_id",s).maybeSingle();if(g)throw g;return x}}),{data:u}=ht({queryKey:["brokerage-detail",s],queryFn:async()=>{const{data:x,error:g}=await U.from("brokerages").select("name, city, state").eq("id",s).single();if(g)throw g;return x}});j.useEffect(()=>{d?c({...d,merge_fields:d.merge_fields||{city:"",broker_name:""}}):u&&c(x=>({...x,merge_fields:{...x.merge_fields,brokerage_name:u.name,city:u.city||""}}))},[d,u]),j.useEffect(()=>{n!=null&&n.id&&U.from("profiles").select("recruit_cta_url").eq("id",n.id).single().then(({data:x})=>a((x==null?void 0:x.recruit_cta_url)||""))},[n==null?void 0:n.id]);const h=async()=>{if(!(n!=null&&n.id))return;l(!0);const{error:x}=await U.from("profiles").update({recruit_cta_url:r.trim()||null}).eq("id",n.id);l(!1),x?ae.error(x.message):ae.success("Scheduling link saved!")},m=yt({mutationFn:async()=>{const x={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:g}=await U.from("brokerage_recruit_settings").update(x).eq("id",d.id);if(g)throw g}else{const{error:g}=await U.from("brokerage_recruit_settings").insert(x);if(g)throw g}},onSuccess:()=>{t.invalidateQueries({queryKey:["brokerage-recruit-settings",s]}),ae.success("Recruiting email settings saved!")},onError:x=>ae.error(x.message)}),p=(x,g)=>{c(y=>({...y,merge_fields:{...y.merge_fields,[x]:g}}))};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(ia,{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(be,{value:r,onChange:x=>a(x.target.value),placeholder:"https://calendly.com/your-name/intro"}),e.jsxs($,{onClick:h,disabled:i,size:"sm",children:[e.jsx(Jo,{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(se,{className:"text-xs",children:"Sender Display Name"}),e.jsx(be,{value:o.sender_name,onChange:x=>c({...o,sender_name:x.target.value}),placeholder:"e.g. Jeremy at LevelUp"})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(se,{className:"text-xs",children:"Sender Email Address"}),e.jsx(be,{value:o.sender_email,onChange:x=>c({...o,sender_email:x.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(se,{className:"text-xs",children:"Reply-To Email (optional)"}),e.jsx(be,{value:o.reply_to_email,onChange:x=>c({...o,reply_to_email:x.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(j0,{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(SVt,{brokerageId:s,onVerifiedSelect:x=>{c(g=>({...g,sender_email:x})),ae.success(`Sender set to ${x}`)}})]}),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(se,{className:"text-xs",children:"{{brokerage_name}}"}),e.jsx(be,{value:o.merge_fields.brokerage_name||"",onChange:x=>p("brokerage_name",x.target.value),placeholder:(u==null?void 0:u.name)||"Brokerage Name"})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(se,{className:"text-xs",children:"{{city}}"}),e.jsx(be,{value:o.merge_fields.city||"",onChange:x=>p("city",x.target.value),placeholder:"e.g. Austin"})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(se,{className:"text-xs",children:"{{sender_name}}"}),e.jsx(be,{value:o.merge_fields.sender_name||"",onChange:x=>p("sender_name",x.target.value),placeholder:"e.g. Jeremy"})]})]})]}),e.jsxs($,{onClick:()=>m.mutate(),disabled:m.isPending,className:"w-full",children:[e.jsx(Jo,{className:"h-4 w-4 mr-1"})," Save Settings"]})]})}const QRn=GN.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",ap(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()}}}),Vvt=[{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 X0({onClick:s,active:t,disabled:n,icon:r,tooltip:a}){return e.jsxs(Mx,{children:[e.jsx(Lx,{asChild:!0,children:e.jsx($,{type:"button",variant:"ghost",size:"sm",onClick:s,disabled:n,className:`h-8 w-8 p-0 ${t?"bg-accent text-accent-foreground":"text-muted-foreground hover:text-foreground"}`,children:e.jsx(r,{className:"h-4 w-4"})})}),e.jsx(tx,{side:"bottom",className:"text-xs",children:a})]})}function JRn({content:s,onChange:t}){const n=GGe({extensions:[KGe.configure({heading:{levels:[1,2,3]}}),QRn,rWe.configure({openOnClick:!1,HTMLAttributes:{class:"text-primary underline cursor-pointer"}}),aWe.configure({types:["heading","paragraph"]}),iWe,RFt],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(JN,{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(X0,{onClick:()=>n.chain().focus().toggleBold().run(),active:n.isActive("bold"),icon:pT,tooltip:"Bold"}),e.jsx(X0,{onClick:()=>n.chain().focus().toggleItalic().run(),active:n.isActive("italic"),icon:_T,tooltip:"Italic"}),e.jsx(X0,{onClick:()=>n.chain().focus().toggleUnderline().run(),active:n.isActive("underline"),icon:Vz,tooltip:"Underline"}),e.jsx(X0,{onClick:()=>n.chain().focus().toggleStrike().run(),active:n.isActive("strike"),icon:YK,tooltip:"Strikethrough"}),e.jsx(Hl,{orientation:"vertical",className:"mx-1 h-6"}),e.jsx(X0,{onClick:()=>n.chain().focus().toggleHeading({level:1}).run(),active:n.isActive("heading",{level:1}),icon:_z,tooltip:"Heading 1"}),e.jsx(X0,{onClick:()=>n.chain().focus().toggleHeading({level:2}).run(),active:n.isActive("heading",{level:2}),icon:wz,tooltip:"Heading 2"}),e.jsx(X0,{onClick:()=>n.chain().focus().toggleHeading({level:3}).run(),active:n.isActive("heading",{level:3}),icon:EK,tooltip:"Heading 3"}),e.jsx(Hl,{orientation:"vertical",className:"mx-1 h-6"}),e.jsx(X0,{onClick:()=>n.chain().focus().toggleBulletList().run(),active:n.isActive("bulletList"),icon:Sg,tooltip:"Bullet List"}),e.jsx(X0,{onClick:()=>n.chain().focus().toggleOrderedList().run(),active:n.isActive("orderedList"),icon:qj,tooltip:"Numbered List"}),e.jsx(X0,{onClick:()=>n.chain().focus().toggleBlockquote().run(),active:n.isActive("blockquote"),icon:RN,tooltip:"Blockquote"}),e.jsx(X0,{onClick:()=>n.chain().focus().setHorizontalRule().run(),icon:DN,tooltip:"Divider"}),e.jsx(Hl,{orientation:"vertical",className:"mx-1 h-6"}),e.jsx(X0,{onClick:()=>n.chain().focus().setTextAlign("left").run(),active:n.isActive({textAlign:"left"}),icon:iR,tooltip:"Align Left"}),e.jsx(X0,{onClick:()=>n.chain().focus().setTextAlign("center").run(),active:n.isActive({textAlign:"center"}),icon:aR,tooltip:"Align Center"}),e.jsx(X0,{onClick:()=>n.chain().focus().setTextAlign("right").run(),active:n.isActive({textAlign:"right"}),icon:oR,tooltip:"Align Right"}),e.jsx(Hl,{orientation:"vertical",className:"mx-1 h-6"}),e.jsx(X0,{onClick:r,active:n.isActive("link"),icon:kc,tooltip:"Insert Link"}),e.jsx(Hl,{orientation:"vertical",className:"mx-1 h-6"}),e.jsx(X0,{onClick:()=>n.chain().focus().undo().run(),disabled:!n.can().undo(),icon:PT,tooltip:"Undo"}),e.jsx(X0,{onClick:()=>n.chain().focus().redo().run(),disabled:!n.can().redo(),icon:ET,tooltip:"Redo"}),e.jsx("div",{className:"flex-1"}),e.jsx($,{type:"button",variant:"outline",size:"sm",className:"h-8 gap-1.5 text-xs font-medium",onClick:()=>{n&&n.chain().focus().insertContent('

Learn More About Us

').run()},children:"🔘 CTA Button"}),e.jsxs(Hd,{children:[e.jsx(Gd,{asChild:!0,children:e.jsxs($,{type:"button",variant:"outline",size:"sm",className:"h-8 gap-1.5 text-xs font-medium",children:[e.jsx(Gz,{className:"h-3.5 w-3.5"}),"Merge Tags"]})}),e.jsx(Md,{align:"end",className:"w-56",children:Vvt.map(i=>e.jsxs(Na,{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(VGe,{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:"}),Vvt.map(i=>e.jsx($e,{variant:"secondary",className:"cursor-pointer hover:bg-secondary/80 font-mono text-[10px] px-2 py-0.5",onClick:()=>a(i.key),children:`{{${i.key}}}`},i.key))]})})]})}):null}function eOn({open:s,onClose:t,campaignName:n,stat:r}){return e.jsx(Os,{open:s,onOpenChange:a=>!a&&t(),children:e.jsxs(Rs,{className:"max-w-3xl max-h-[85vh] overflow-y-auto",children:[e.jsxs(Us,{children:[e.jsxs(zs,{className:"flex items-center gap-2",children:[e.jsx(Il,{className:"h-5 w-5 text-primary"}),n," — Engagement Stats"]}),e.jsx(Sr,{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(Br,{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(vae,{icon:nn,color:"text-blue-500",label:"Total Sent",value:r.sent.toLocaleString()}),e.jsx(vae,{icon:ga,color:"text-amber-500",label:"Opens",value:`${r.opened.toLocaleString()}`,sub:`${r.openRate.toFixed(1)}% open rate`}),e.jsx(vae,{icon:uu,color:"text-green-500",label:"Clicks",value:`${r.clicked.toLocaleString()}`,sub:`${r.clickRate.toFixed(1)}% click rate`}),e.jsx(vae,{icon:mc,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(Hr,{className:"h-3 w-3"})," Last sent: ",Hs(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(_e,{className:"overflow-hidden",children:e.jsxs(Oe,{className:"py-3",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("div",{className:"h-8 w-8 rounded-full bg-primary/10 text-primary font-bold text-xs flex items-center justify-center shrink-0",children:["#",a.email_number]}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"font-medium text-sm truncate",children:a.title}),e.jsxs("div",{className:"flex flex-wrap gap-1.5 mt-1",children:[e.jsxs($e,{variant:"outline",className:"text-[10px] gap-1",children:[e.jsx(nn,{className:"h-2.5 w-2.5"})," ",a.sent_count.toLocaleString()," sent"]}),e.jsxs($e,{variant:"outline",className:"text-[10px] gap-1 border-amber-500/30 text-amber-600",children:[e.jsx(ga,{className:"h-2.5 w-2.5"})," ",a.opened_count.toLocaleString()," (",i.toFixed(1),"%)"]}),e.jsxs($e,{variant:"outline",className:"text-[10px] gap-1 border-green-500/30 text-green-600",children:[e.jsx(uu,{className:"h-2.5 w-2.5"})," ",a.clicked_count.toLocaleString()," (",l.toFixed(1),"%)"]}),a.failed_count>0&&e.jsxs($e,{variant:"outline",className:"text-[10px] gap-1 border-destructive/30 text-destructive",children:[e.jsx(mc,{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 vae({icon:s,color:t,label:n,value:r,sub:a}){return e.jsx(_e,{children:e.jsx(Oe,{className:"pt-4 pb-3",children:e.jsxs("div",{className:"flex items-center gap-2.5",children:[e.jsx(s,{className:`h-6 w-6 ${t}`}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-xl font-bold leading-none",children: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 XVt(s){return ht({queryKey:["recruit-campaign-stats",s],enabled:!!s,staleTime:6e4,queryFn:async()=>{const{data:t,error:n}=await U.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 Hvt={cold:{icon:Z_,color:"text-blue-500",bg:"bg-blue-50 dark:bg-blue-950/30",label:"Cold — Curiosity"},warm:{icon:Kj,color:"text-amber-500",bg:"bg-amber-50 dark:bg-amber-950/30",label:"Warm — Growth"},hot:{icon:yd,color:"text-red-500",bg:"bg-red-50 dark:bg-red-950/30",label:"Hot — Private Invite"}};function QVt({brokerageId:s}){var je,Ee,Me,De;const{user:t}=_s(),n=ts(),[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,x]=j.useState("editor"),[g,y]=j.useState(null),[b,v]=j.useState(null),{data:N={}}=XVt(s),[C,A]=j.useState({name:"",description:"",theme:"",goal:"",primary_cta:"Learn more",warmth_level:"warm",sender_name:"",sender_email:"",reply_to_email:""}),{data:T}=ht({queryKey:["brokerage-detail",s],queryFn:async()=>{const{data:ze,error:ke}=await U.from("brokerages").select("name, city, state").eq("id",s).single();if(ke)throw ke;return ze}}),{data:P}=ht({queryKey:["brokerage-recruit-settings",s],queryFn:async()=>{const{data:ze,error:ke}=await U.from("brokerage_recruit_settings").select("*").eq("brokerage_id",s).maybeSingle();if(ke)throw ke;return ze}}),M={first_name:"Sarah",brokerage_name:((je=P==null?void 0:P.merge_fields)==null?void 0:je.brokerage_name)||(T==null?void 0:T.name)||"Your Brokerage",city:((Ee=P==null?void 0:P.merge_fields)==null?void 0:Ee.city)||(T==null?void 0:T.city)||"Your City",sender_name:((Me=P==null?void 0:P.merge_fields)==null?void 0:Me.sender_name)||(P==null?void 0:P.sender_name)||"Your Name"},I=ze=>ze.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:D=[],isLoading:B}=ht({queryKey:["recruit-campaigns",s],queryFn:async()=>{const{data:ze,error:ke}=await U.from("recruit_campaigns").select("*").or(`brokerage_id.is.null,brokerage_id.eq.${s}`).order("sort_order");if(ke)throw ke;return ze}}),{data:q={}}=ht({queryKey:["recruit-campaign-emails",s],enabled:D.length>0,queryFn:async()=>{const ze=D.map(Re=>Re.id),{data:ke,error:Xe}=await U.from("recruit_campaign_emails").select("*").in("campaign_id",ze).order("email_number");if(Xe)throw Xe;const Se={};return ke.forEach(Re=>{Se[Re.campaign_id]||(Se[Re.campaign_id]=[]),Se[Re.campaign_id].push(Re)}),Se}}),W=Object.values(q).flat().map(ze=>ze.id),{data:V=[]}=ht({queryKey:["recruit-subject-overrides",s],enabled:W.length>0,queryFn:async()=>{const{data:ze,error:ke}=await U.from("recruit_brokerage_subject_overrides").select("*").eq("brokerage_id",s);if(ke)throw ke;return ze}}),K={};V.forEach(ze=>{K[ze.campaign_email_id]=ze.selected_subject_index});const Q=yt({mutationFn:async({campaignEmailId:ze,selectedIndex:ke})=>{const{error:Xe}=await U.from("recruit_brokerage_subject_overrides").upsert({brokerage_id:s,campaign_email_id:ze,selected_subject_index:ke,updated_at:new Date().toISOString()},{onConflict:"brokerage_id,campaign_email_id"});if(Xe)throw Xe},onSuccess:()=>{n.invalidateQueries({queryKey:["recruit-subject-overrides",s]}),ae.success("Subject line updated for your brokerage")},onError:ze=>ae.error(ze.message)}),J=yt({mutationFn:async ze=>{const{error:ke}=await U.from("recruit_campaign_emails").update({title:ze.title,subject_line:ze.subject_line,subject_line_options:ze.subject_line_options,body_html:ze.body_html,body_text:ze.body_text,delay_days:ze.delay_days,updated_at:new Date().toISOString()}).eq("id",ze.id);if(ke)throw ke},onSuccess:()=>{n.invalidateQueries({queryKey:["recruit-campaign-emails"]}),ae.success("Email template saved!"),l(null)},onError:ze=>ae.error(ze.message)}),ce=yt({mutationFn:async()=>{const ze=C.name.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/(^-|-$)/g,""),{data:ke,error:Xe}=await U.from("recruit_campaigns").insert({name:C.name,slug:ze,description:C.description||null,theme:C.theme||null,goal:C.goal||null,primary_cta:C.primary_cta||"Learn more",warmth_level:C.warmth_level,brokerage_id:s,created_by:t==null?void 0:t.id,sender_name:C.sender_name||null,sender_email:C.sender_email||null,reply_to_email:C.reply_to_email||null,is_active:!0,sort_order:D.length+1}).select().single();if(Xe)throw Xe;const Se=[{email_number:1,title:"Introduction",subject_line:"Hey {{first_name}}, quick question",delay_days:0},{email_number:2,title:"Follow Up",subject_line:"Following up, {{first_name}}",delay_days:7},{email_number:3,title:"Value Add",subject_line:"{{first_name}}, thought you'd want to see this",delay_days:14},{email_number:4,title:"Final Touch",subject_line:"Last note, {{first_name}}",delay_days:21}],{error:Re}=await U.from("recruit_campaign_emails").insert(Se.map(Ae=>({campaign_id:ke.id,...Ae,body_html:"

Hi {{first_name}},

Write your message here...

Best,
{{sender_name}}

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

Hi {{first_name}},

Write your message here...

Best,
{{sender_name}}

",body_text:"",delay_days:Se+7,is_active:!0});if(Ae)throw Ae},onSuccess:()=>{n.invalidateQueries({queryKey:["recruit-campaign-emails"]}),ae.success("Email added to campaign!")},onError:ze=>ae.error(ze.message)}),ee=yt({mutationFn:async ze=>{const{error:ke}=await U.from("recruit_campaigns").delete().eq("id",ze);if(ke)throw ke},onSuccess:()=>{n.invalidateQueries({queryKey:["recruit-campaigns"]}),n.invalidateQueries({queryKey:["recruit-campaign-emails"]}),ae.success("Campaign deleted")},onError:ze=>ae.error(ze.message)}),le=yt({mutationFn:async ze=>{const{error:ke}=await U.from("recruit_campaign_emails").delete().eq("id",ze);if(ke)throw ke},onSuccess:()=>{n.invalidateQueries({queryKey:["recruit-campaign-emails"]}),ae.success("Email removed from campaign")},onError:ze=>ae.error(ze.message)}),he=yt({mutationFn:async({emailId:ze,delay_days:ke})=>{const{error:Xe}=await U.from("recruit_campaign_emails").update({delay_days:ke,updated_at:new Date().toISOString()}).eq("id",ze);if(Xe)throw Xe},onSuccess:()=>{n.invalidateQueries({queryKey:["recruit-campaign-emails"]}),ae.success("Send delay updated")},onError:ze=>ae.error(ze.message)});if(B)return e.jsx("div",{className:"flex justify-center py-12",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})});const ve=D.filter(ze=>!ze.brokerage_id),ge=D.filter(ze=>ze.brokerage_id===s);return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-xl font-bold",children:"Recruiting Campaigns"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"System campaigns + custom campaigns · Each can have its own email settings"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs($,{variant:"outline",size:"sm",onClick:()=>u(!0),className:"gap-1.5",children:[e.jsx(pc,{className:"h-4 w-4"})," Default Settings"]}),e.jsxs($,{size:"sm",onClick:()=>m(!0),className:"gap-1.5",children:[e.jsx(sn,{className:"h-4 w-4"})," New Campaign"]})]})]}),e.jsx(_e,{className:"border-primary/20 bg-primary/5",children:e.jsx(Oe,{className:"py-3",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(dn,{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(pc,{className:"inline h-3.5 w-3.5"})," icon on any campaign to customize."]})]})]})})}),ge.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(LK,{className:"h-4 w-4"})," Your Custom Campaigns"]}),e.jsx("div",{className:"space-y-3",children:ge.map(ze=>fe(ze,!0))})]}),ve.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("h3",{className:"text-sm font-semibold text-muted-foreground uppercase tracking-wider flex items-center gap-2",children:[e.jsx(dn,{className:"h-4 w-4"})," System Campaigns"]}),e.jsx("div",{className:"space-y-3",children:ve.map(ze=>fe(ze,!1))})]}),D.length===0&&e.jsx(_e,{children:e.jsxs(Oe,{className:"py-12 text-center text-muted-foreground",children:[e.jsx(nn,{className:"h-12 w-12 mx-auto mb-4 opacity-50"}),e.jsx("p",{children:"No campaigns yet. Create your first campaign to start automated outreach."}),e.jsxs($,{className:"mt-4",onClick:()=>m(!0),children:[e.jsx(sn,{className:"h-4 w-4 mr-1"})," Create Campaign"]})]})}),e.jsx(eOn,{open:!!b,onClose:()=>v(null),campaignName:(b==null?void 0:b.name)||"",stat:b&&N[b.id]||null}),o&&e.jsx(ZVt,{email:o,mergeValues:M,selectedSubjectIndex:K[o.id],onClose:()=>c(null)}),e.jsx(Os,{open:!!i,onOpenChange:ze=>!ze&&l(null),children:e.jsxs(Rs,{className:"max-w-4xl max-h-[90vh] overflow-y-auto p-0",children:[e.jsxs(Us,{className:"px-6 pt-6 pb-4 border-b",children:[e.jsxs(zs,{className:"flex items-center gap-2",children:[e.jsx(vT,{className:"h-5 w-5 text-primary"}),"Edit Email #",i==null?void 0:i.email_number]}),e.jsx(Sr,{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(se,{className:"text-xs font-medium text-muted-foreground uppercase tracking-wider",children:"Email Title"}),e.jsx(be,{value:i.title,onChange:ze=>l({...i,title:ze.target.value}),className:"h-9"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{className:"text-xs font-medium text-muted-foreground uppercase tracking-wider",children:"Delay (days after previous)"}),e.jsx(be,{type:"number",min:0,max:90,value:i.delay_days,onChange:ze=>l({...i,delay_days:parseInt(ze.target.value)||7}),className:"h-9"})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{className:"text-xs font-medium text-muted-foreground uppercase tracking-wider",children:"Subject Line"}),e.jsx(be,{value:i.subject_line,onChange:ze=>l({...i,subject_line:ze.target.value}),placeholder:"e.g. Hey {{first_name}}, quick question...",className:"h-9"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs(se,{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(Is,{value:((De=i.subject_line_options)==null?void 0:De.join(` `))||"",onChange:ze=>l({...i,subject_line_options:ze.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(se,{className:"text-xs font-medium text-muted-foreground uppercase tracking-wider",children:"Email Body"}),e.jsx(ua,{value:p,onValueChange:ze=>x(ze),children:e.jsxs(ha,{className:"h-7",children:[e.jsx(Qt,{value:"editor",className:"text-xs px-3 h-6",children:"Editor"}),e.jsx(Qt,{value:"preview",className:"text-xs px-3 h-6",children:"Preview"})]})})]}),p==="editor"?e.jsx(JRn,{content:i.body_html,onChange:ze=>l({...i,body_html:ze})}):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($,{variant:"outline",size:"sm",onClick:()=>l(null),children:"Cancel"}),e.jsxs($,{size:"sm",onClick:()=>J.mutate(i),disabled:J.isPending,className:"gap-1.5",children:[e.jsx(Jo,{className:"h-3.5 w-3.5"})," Save Changes"]})]})]})]})]})}),e.jsx(Os,{open:h,onOpenChange:m,children:e.jsxs(Rs,{className:"max-w-lg",children:[e.jsxs(Us,{children:[e.jsxs(zs,{className:"flex items-center gap-2",children:[e.jsx(sn,{className:"h-5 w-5 text-primary"})," Create Custom Campaign"]}),e.jsx(Sr,{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(se,{className:"text-xs font-medium",children:"Campaign Name *"}),e.jsx(be,{value:C.name,onChange:ze=>A({...C,name:ze.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(se,{className:"text-xs font-medium",children:"Warmth Level"}),e.jsxs(vs,{value:C.warmth_level,onValueChange:ze=>A({...C,warmth_level:ze}),children:[e.jsx(gs,{children:e.jsx(bs,{})}),e.jsxs(ys,{children:[e.jsx(Ye,{value:"cold",children:"❄️ Cold — Curiosity"}),e.jsx(Ye,{value:"warm",children:"☀️ Warm — Growth"}),e.jsx(Ye,{value:"hot",children:"🔥 Hot — Private Invite"})]})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{className:"text-xs font-medium",children:"Primary CTA"}),e.jsx(be,{value:C.primary_cta,onChange:ze=>A({...C,primary_cta:ze.target.value}),placeholder:"Learn more"})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{className:"text-xs font-medium",children:"Description"}),e.jsx(Is,{value:C.description,onChange:ze=>A({...C,description:ze.target.value}),placeholder:"What is this campaign about?",rows:2})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{className:"text-xs font-medium",children:"Goal"}),e.jsx(be,{value:C.goal,onChange:ze=>A({...C,goal:ze.target.value}),placeholder:"e.g. Convert warm leads to meetings"})]}),e.jsxs(uv,{children:[e.jsx(hv,{asChild:!0,children:e.jsxs($,{variant:"ghost",size:"sm",className:"w-full justify-between text-xs font-medium text-muted-foreground hover:text-foreground",children:[e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(nn,{className:"h-3.5 w-3.5"})," Email Settings Override"]}),e.jsx(_o,{className:"h-3.5 w-3.5"})]})}),e.jsxs(mv,{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(se,{className:"text-xs",children:"Sender Name"}),e.jsx(be,{value:C.sender_name,onChange:ze=>A({...C,sender_name:ze.target.value}),placeholder:"e.g. Jeremy at LevelUp"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{className:"text-xs",children:"Sender Email"}),e.jsx(be,{value:C.sender_email,onChange:ze=>A({...C,sender_email:ze.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(se,{className:"text-xs",children:"Reply-To Email"}),e.jsx(be,{value:C.reply_to_email,onChange:ze=>A({...C,reply_to_email:ze.target.value}),placeholder:"e.g. jeremy@mybrokerage.com"})]})]})]}),e.jsxs($,{className:"w-full",disabled:!C.name.trim()||ce.isPending,onClick:()=>ce.mutate(),children:[e.jsx(sn,{className:"h-4 w-4 mr-1"})," Create Campaign"]})]})]})}),e.jsx(Os,{open:!!g,onOpenChange:ze=>!ze&&y(null),children:e.jsxs(Rs,{className:"max-w-lg",children:[e.jsxs(Us,{children:[e.jsxs(zs,{className:"flex items-center gap-2",children:[e.jsx(pc,{className:"h-5 w-5 text-primary"})," Campaign Email Settings"]}),e.jsx(Sr,{children:"Override the default sender for this campaign. Leave blank to use brokerage defaults."})]}),g&&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(se,{className:"text-xs font-medium",children:"Campaign Name"}),e.jsx(be,{value:g.name,onChange:ze=>y({...g,name:ze.target.value})})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{className:"text-xs font-medium",children:"Warmth Level"}),e.jsxs(vs,{value:g.warmth_level,onValueChange:ze=>y({...g,warmth_level:ze}),children:[e.jsx(gs,{children:e.jsx(bs,{})}),e.jsxs(ys,{children:[e.jsx(Ye,{value:"cold",children:"❄️ Cold"}),e.jsx(Ye,{value:"warm",children:"☀️ Warm"}),e.jsx(Ye,{value:"hot",children:"🔥 Hot"})]})]})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{className:"text-xs font-medium",children:"Goal"}),e.jsx(be,{value:g.goal||"",onChange:ze=>y({...g,goal:ze.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(nn,{className:"h-4 w-4 text-primary"})," Email Sender Override"]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{className:"text-xs",children:"Sender Name"}),e.jsx(be,{value:g.sender_name||"",onChange:ze=>y({...g,sender_name:ze.target.value}),placeholder:"Uses brokerage default"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{className:"text-xs",children:"Sender Email"}),e.jsx(be,{value:g.sender_email||"",onChange:ze=>y({...g,sender_email:ze.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(se,{className:"text-xs",children:"Reply-To Email"}),e.jsx(be,{value:g.reply_to_email||"",onChange:ze=>y({...g,reply_to_email:ze.target.value}),placeholder:"Uses brokerage default"})]})]}),e.jsxs($,{className:"w-full",onClick:()=>ue.mutate(g),disabled:ue.isPending,children:[e.jsx(Jo,{className:"h-4 w-4 mr-1"})," Save Campaign Settings"]})]})]})}),e.jsx(Os,{open:d,onOpenChange:u,children:e.jsxs(Rs,{className:"max-w-lg",children:[e.jsxs(Us,{children:[e.jsx(zs,{children:"Default Recruiting Email Settings"}),e.jsx(Sr,{children:"These defaults apply to campaigns without their own overrides."})]}),e.jsx(gXe,{brokerageId:s})]})})]});function fe(ze,ke){const Xe=Hvt[ze.warmth_level]||Hvt.cold,Se=Xe.icon,Re=q[ze.id]||[],Ae=r===ze.id,Be=!!(ze.sender_name||ze.sender_email||ze.reply_to_email),qe=N[ze.id];return e.jsxs(_e,{className:"overflow-hidden transition-shadow hover:shadow-md",children:[e.jsx(Bt,{className:"cursor-pointer hover:bg-muted/40 transition-colors py-4",onClick:()=>a(Ae?null:ze.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 ${Xe.bg} flex items-center justify-center`,children:e.jsx(Se,{className:`h-5 w-5 ${Xe.color}`})}),e.jsxs("div",{children:[e.jsxs(Ut,{className:"text-base flex items-center gap-2",children:[ze.name,e.jsx($e,{variant:ze.is_active?"default":"secondary",className:"text-[10px] px-1.5",children:ze.is_active?"Active":"Draft"}),ke&&e.jsx($e,{variant:"outline",className:"text-[10px] px-1.5",children:"Custom"}),Be&&e.jsxs($e,{variant:"outline",className:"text-[10px] px-1.5 border-primary/30 text-primary",children:[e.jsx(nn,{className:"h-2.5 w-2.5 mr-0.5"})," Custom Sender"]})]}),e.jsx(vr,{className:"text-xs mt-0.5",children:ze.theme||ze.description})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx($,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:Ke=>{Ke.stopPropagation(),y({...ze})},children:e.jsx(pc,{className:"h-4 w-4 text-muted-foreground"})}),ke&&e.jsx($,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0 text-destructive hover:text-destructive hover:bg-destructive/10",onClick:async Ke=>{Ke.stopPropagation(),await Yi("Delete this campaign and all its emails? This cannot be undone.")&&ee.mutate(ze.id)},children:e.jsx(Pn,{className:"h-4 w-4"})}),qe&&qe.sent>0&&e.jsxs("div",{className:"hidden md:flex items-center gap-1.5",children:[e.jsxs($e,{variant:"outline",className:"text-[10px] gap-1 font-medium",title:"Total emails sent",children:[e.jsx(nn,{className:"h-2.5 w-2.5"})," ",qe.sent.toLocaleString()]}),e.jsxs($e,{variant:"outline",className:"text-[10px] gap-1 border-amber-500/30 text-amber-600 font-medium",title:`${qe.openRate.toFixed(1)}% open rate`,children:[e.jsx(ga,{className:"h-2.5 w-2.5"})," ",qe.opened.toLocaleString()," (",qe.openRate.toFixed(0),"%)"]}),e.jsxs($e,{variant:"outline",className:"text-[10px] gap-1 border-green-500/30 text-green-600 font-medium",title:`${qe.clickRate.toFixed(1)}% click rate`,children:[e.jsx(uu,{className:"h-2.5 w-2.5"})," ",qe.clicked.toLocaleString()," (",qe.clickRate.toFixed(1),"%)"]})]}),e.jsxs($,{variant:"outline",size:"sm",className:"h-7 px-2 gap-1 text-xs",onClick:Ke=>{Ke.stopPropagation(),v(ze)},title:"View detailed engagement stats",children:[e.jsx(ml,{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(nn,{className:"h-3.5 w-3.5"}),e.jsxs("span",{children:[Re.length," emails"]})]}),e.jsx("div",{className:"h-7 w-7 rounded-md flex items-center justify-center",children:Ae?e.jsx(jg,{className:"h-4 w-4 text-muted-foreground"}):e.jsx(_o,{className:"h-4 w-4 text-muted-foreground"})})]})]})}),Ae&&e.jsxs(Oe,{className:"pt-0 pb-4 space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-4 p-3 rounded-lg bg-muted/40 text-sm",children:[e.jsxs("div",{children:[e.jsx("span",{className:"text-xs font-medium text-muted-foreground uppercase tracking-wider",children:"Goal"}),e.jsx("p",{className:"mt-0.5",children:ze.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:ze.primary_cta||"—"})]})]}),Be&&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(nn,{className:"h-3 w-3"})," Campaign Sender Override"]}),e.jsxs("div",{className:"grid grid-cols-3 gap-2 text-xs text-muted-foreground",children:[ze.sender_name&&e.jsxs("p",{children:[e.jsx("span",{className:"font-medium",children:"Name:"})," ",ze.sender_name]}),ze.sender_email&&e.jsxs("p",{children:[e.jsx("span",{className:"font-medium",children:"Email:"})," ",ze.sender_email]}),ze.reply_to_email&&e.jsxs("p",{children:[e.jsx("span",{className:"font-medium",children:"Reply-To:"})," ",ze.reply_to_email]})]})]}),e.jsx("div",{className:"relative",children:Re.map((Ke,Ze)=>{var Ue,et;return e.jsxs("div",{className:"relative flex gap-4 pb-4 last:pb-0",children:[ZeQe.stopPropagation(),onBlur:Qe=>{const Ge=parseInt(Qe.target.value)||0;Ge!==Ke.delay_days&&he.mutate({emailId:Ke.id,delay_days:Ge})},onKeyDown:Qe=>{Qe.key==="Enter"&&Qe.target.blur()}}),"days"]})]}):e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Hr,{className:"h-3 w-3"}),Ke.email_number===1?"Sent immediately":`Day ${Ke.delay_days}`]}),e.jsx("span",{className:"text-border",children:"•"}),e.jsxs("span",{className:"truncate",children:["Subject: ",I(((Ue=Ke.subject_line_options)==null?void 0:Ue.length)>0&&Ke.subject_line_options[K[Ke.id]??0]||Ke.subject_line)]})]}),((et=Ke.subject_line_options)==null?void 0:et.length)>1&&e.jsx("div",{className:"mt-2",children:e.jsxs(vs,{value:String(K[Ke.id]??0),onValueChange:Qe=>Q.mutate({campaignEmailId:Ke.id,selectedIndex:parseInt(Qe)}),children:[e.jsx(gs,{className:"h-7 text-xs w-full max-w-sm",children:e.jsx(bs,{placeholder:"Choose subject line"})}),e.jsx(ys,{children:Ke.subject_line_options.map((Qe,Ge)=>e.jsxs(Ye,{value:String(Ge),className:"text-xs",children:[e.jsxs("span",{className:"font-medium mr-1.5",children:[Ge===0?"Primary":`Alt ${Ge}`,":"]}),I(Qe)]},Ge))})]})})]}),e.jsxs("div",{className:"flex items-center gap-1 opacity-0 group-hover:opacity-100 transition-opacity shrink-0",children:[e.jsx($,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:()=>c(Ke),children:e.jsx(ga,{className:"h-4 w-4"})}),e.jsx($,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:()=>{l({...Ke}),x("editor")},children:e.jsx(Ya,{className:"h-4 w-4"})}),ke&&Re.length>1&&e.jsx($,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0 text-destructive hover:text-destructive hover:bg-destructive/10",onClick:async()=>{await Yi("Delete this email from the sequence?")&&le.mutate(Ke.id)},children:e.jsx(Pn,{className:"h-4 w-4"})})]})]})})]},Ke.id)})}),ke&&e.jsxs($,{variant:"outline",size:"sm",className:"w-full gap-1.5",onClick:()=>ne.mutate(ze.id),disabled:ne.isPending,children:[e.jsx(sn,{className:"h-3.5 w-3.5"})," Add Email to Sequence"]})]})]},ze.id)}}const Gvt={active:{icon:Td,color:"bg-green-500/10 text-green-600",label:"Active"},paused:{icon:vy,color:"bg-amber-500/10 text-amber-600",label:"Paused"},completed:{icon:Ro,color:"bg-blue-500/10 text-blue-600",label:"Completed"},cancelled:{icon:$d,color:"bg-red-500/10 text-red-600",label:"Cancelled"}},Wvt={sent:{icon:nn,color:"text-blue-500"},opened:{icon:ga,color:"text-amber-500"},clicked:{icon:uu,color:"text-green-500"},failed:{icon:mc,color:"text-destructive"}};function JVt({brokerageId:s}){var De,ze,ke,Xe,Se;const{user:t}=_s(),n=ts(),[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,x]=j.useState(""),[g,y]=j.useState("all"),[b,v]=j.useState("all"),[N,C]=j.useState(!1),{data:A}=Kee(),{data:T={}}=ht({queryKey:["recruit-campaign-emails-for-preview",s],queryFn:async()=>{const{data:Re,error:Ae}=await U.from("recruit_campaign_emails").select("*").order("email_number");if(Ae)throw Ae;const Be={};return(Re??[]).forEach(qe=>{Be[qe.campaign_id]||(Be[qe.campaign_id]=[]),Be[qe.campaign_id].push(qe)}),Be}}),{data:P}=ht({queryKey:["brokerage-detail",s],queryFn:async()=>{const{data:Re,error:Ae}=await U.from("brokerages").select("name, city, state").eq("id",s).single();if(Ae)throw Ae;return Re}}),{data:M}=ht({queryKey:["brokerage-recruit-settings",s],queryFn:async()=>{const{data:Re,error:Ae}=await U.from("brokerage_recruit_settings").select("*").eq("brokerage_id",s).maybeSingle();if(Ae)throw Ae;return Re}}),{data:I=[]}=ht({queryKey:["recruit-subject-overrides",s],queryFn:async()=>{const{data:Re,error:Ae}=await U.from("recruit_brokerage_subject_overrides").select("*").eq("brokerage_id",s);if(Ae)throw Ae;return Re}}),D={};I.forEach(Re=>{D[Re.campaign_email_id]=Re.selected_subject_index});const B={first_name:((De=h==null?void 0:h.prospect)==null?void 0:De.first_name)||"Sarah",brokerage_name:((ze=M==null?void 0:M.merge_fields)==null?void 0:ze.brokerage_name)||(P==null?void 0:P.name)||"Your Brokerage",city:((ke=M==null?void 0:M.merge_fields)==null?void 0:ke.city)||(P==null?void 0:P.city)||"Your City",sender_name:((Xe=M==null?void 0:M.merge_fields)==null?void 0:Xe.sender_name)||(M==null?void 0:M.sender_name)||"Your Name"},q=Re=>{const Ae=T[Re.campaign_id]||[],Be=Re.current_email_number+1;return Ae.find(qe=>qe.email_number===Be)||null},{data:W=[],isLoading:V}=ht({queryKey:["recruit-campaign-assignments",s],queryFn:async()=>{let Ae=[],Be=0;for(;;){const{data:qe,error:Ke}=await U.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(Be,Be+1e3-1);if(Ke)throw Ke;if(Ae=Ae.concat(qe??[]),!qe||qe.length<1e3)break;Be+=1e3}return Ae}}),{data:K=[]}=ht({queryKey:["recruit-campaign-sends",s],queryFn:async()=>{const{data:Re,error:Ae}=await U.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(Ae)throw Ae;return Re}}),{data:Q=[]}=ht({queryKey:["recruit-campaigns"],queryFn:async()=>{const{data:Re,error:Ae}=await U.from("recruit_campaigns").select("id, name, warmth_level").eq("is_active",!0).order("sort_order");if(Ae)throw Ae;return Re}}),{data:J=[]}=ht({queryKey:["recruit-prospects-for-assign",s],queryFn:async()=>{let Ae=[],Be=0;for(;;){const{data:qe,error:Ke}=await U.from("recruit_prospects").select("id, first_name, last_name, email").eq("brokerage_id",s).order("first_name").range(Be,Be+1e3-1);if(Ke)throw Ke;if(Ae=Ae.concat(qe??[]),!qe||qe.length<1e3)break;Be+=1e3}return Ae}}),ce=new Set(W.map(Re=>`${Re.prospect_id}-${Re.campaign_id}`)),ue=yt({mutationFn:async()=>{if(!i||o.size===0)throw new Error("Select a campaign and at least one prospect");const Re=new Date,Ae=Array.from(o).filter(qe=>!ce.has(`${qe}-${i}`)).map(qe=>({prospect_id:qe,campaign_id:i,brokerage_id:s,assigned_by:t.id,status:"active",current_email_number:0,next_send_at:Re.toISOString(),started_at:Re.toISOString()}));if(Ae.length===0)throw new Error("All selected prospects are already assigned to this campaign");const{error:Be}=await U.from("recruit_campaign_assignments").insert(Ae);if(Be)throw Be},onSuccess:()=>{n.invalidateQueries({queryKey:["recruit-campaign-assignments",s]}),ae.success(`Campaign assigned to ${o.size} prospect(s)!`),a(!1),l(""),c(new Set)},onError:Re=>ae.error(Re.message)}),ne=yt({mutationFn:async({id:Re,newStatus:Ae})=>{const{error:Be}=await U.from("recruit_campaign_assignments").update({status:Ae,updated_at:new Date().toISOString()}).eq("id",Re);if(Be)throw Be},onSuccess:()=>{n.invalidateQueries({queryKey:["recruit-campaign-assignments",s]}),ae.success("Assignment updated")}}),ee=yt({mutationFn:async()=>{const{data:Re,error:Ae}=await U.functions.invoke("ses-recruit-drip",{body:{action:"process_drips"}});if(Ae)throw Ae;return Re},onSuccess:Re=>{n.invalidateQueries({queryKey:["recruit-campaign-assignments",s]}),n.invalidateQueries({queryKey:["recruit-campaign-sends",s]}),ae.success(`Wave sent! ${Re.sent} emails delivered, ${Re.skipped} skipped, ${Re.failed} failed`)},onError:Re=>ae.error(`Send failed: ${Re.message}`)}),le=W.filter(Re=>Re.status==="active").length;W.filter(Re=>Re.status==="completed").length;const he=W.filter(Re=>Re.status==="active"&&Re.next_send_at&&new Date(Re.next_send_at)<=new Date).length,{data:ve={}}=XVt(s),ge=W.reduce((Re,Ae)=>Re+Math.max(0,Ae.current_email_number||0),0),fe=Object.values(ve).reduce((Re,Ae)=>Re+Ae.opened,0),je=Object.values(ve).reduce((Re,Ae)=>Re+Ae.clicked,0);Object.values(ve).reduce((Re,Ae)=>Re+Ae.failed,0);const Ee=ge>0?Math.round(fe/ge*100):0,Me=ge>0?je/ge*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:[he>0&&e.jsxs($,{variant:"outline",onClick:()=>{ee.mutate()},disabled:ee.isPending,className:"border-amber-500/50 text-amber-600 hover:bg-amber-500/10",children:[e.jsx(ox,{className:"h-4 w-4 mr-1"}),ee.isPending?"Sending...":`Send Next Wave (${he})`]}),e.jsxs($,{onClick:()=>a(!0),children:[e.jsx(Br,{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(_e,{children:e.jsxs(Oe,{className:"pt-3 pb-2 flex items-center gap-3",children:[e.jsx(qn,{className:"h-7 w-7 text-primary"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xl font-bold",children:W.length}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Assigned"})]})]})}),e.jsx(_e,{children:e.jsxs(Oe,{className:"pt-3 pb-2 flex items-center gap-3",children:[e.jsx(Td,{className:"h-7 w-7 text-green-500"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xl font-bold",children:le}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Active"})]})]})}),e.jsx(_e,{children:e.jsxs(Oe,{className:"pt-3 pb-2 flex items-center gap-3",children:[e.jsx(nn,{className:"h-7 w-7 text-blue-500"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xl font-bold",children:ge.toLocaleString()}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Emails Sent"})]})]})}),e.jsx(_e,{children:e.jsxs(Oe,{className:"pt-3 pb-2 flex items-center gap-3",children:[e.jsx(ga,{className:"h-7 w-7 text-amber-500"}),e.jsxs("div",{children:[e.jsxs("p",{className:"text-xl font-bold",children:[Ee,"%"]}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Open Rate (",fe.toLocaleString(),")"]})]})]})}),e.jsx(_e,{children:e.jsxs(Oe,{className:"pt-3 pb-2 flex items-center gap-3",children:[e.jsx(uu,{className:"h-7 w-7 text-green-500"}),e.jsxs("div",{children:[e.jsxs("p",{className:"text-xl font-bold",children:[Me.toFixed(1),"%"]}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Click Rate (",je.toLocaleString(),")"]})]})]})})]}),e.jsxs(ua,{value:d,onValueChange:u,children:[e.jsxs(ha,{children:[e.jsxs(Qt,{value:"assignments",children:["Active Drips (",le,")"]}),e.jsxs(Qt,{value:"history",children:["Send History (",ge.toLocaleString(),")"]})]}),e.jsx(Jt,{value:"assignments",className:"mt-4",children:V?e.jsx("div",{className:"flex justify-center py-8",children:e.jsx("div",{className:"h-6 w-6 animate-spin rounded-full border-2 border-primary border-t-transparent"})}):W.length===0?e.jsx(_e,{children:e.jsxs(Oe,{className:"py-12 text-center text-muted-foreground",children:[e.jsx(Br,{className:"h-12 w-12 mx-auto mb-4 opacity-50"}),e.jsx("p",{className:"font-medium",children:"No campaigns assigned yet"}),e.jsx("p",{className:"text-sm",children:"Assign a recruiting campaign to your prospects to start automated outreach"})]})}):e.jsx("div",{className:"space-y-2",children:W.map(Re=>{var Ue,et,Qe,Ge;const Ae=Gvt[Re.status]||Gvt.active,Be=Ae.icon,Ke=(T[Re.campaign_id]||[]).length||4,Ze=q(Re);return e.jsxs("div",{className:"flex items-center justify-between p-3 rounded-lg border hover:bg-muted/30 transition-colors",children:[e.jsxs("div",{className:"flex items-center gap-3 min-w-0",children:[e.jsxs($e,{className:`text-xs ${Ae.color} border-0`,children:[e.jsx(Be,{className:"h-3 w-3 mr-1"}),Ae.label]}),e.jsxs("div",{className:"min-w-0",children:[e.jsxs("p",{className:"font-medium text-sm",children:[(Ue=Re.prospect)==null?void 0:Ue.first_name," ",(et=Re.prospect)==null?void 0:et.last_name,e.jsx("span",{className:"text-muted-foreground font-normal ml-2",children:(Qe=Re.prospect)==null?void 0:Qe.email})]}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[(Ge=Re.campaign)==null?void 0:Ge.name," · Email ",Re.current_email_number,"/",Ke,Re.next_send_at&&Re.status==="active"&&e.jsxs(e.Fragment,{children:[" ","· ",e.jsx(Hr,{className:"h-3 w-3 inline"})," Next: ",Hs(new Date(Re.next_send_at),"MMM d, h:mm a"),new Date(Re.next_send_at)<=new Date&&e.jsx($e,{variant:"outline",className:"ml-1 text-[10px] px-1 py-0 border-amber-500 text-amber-600",children:"DUE"})]})]})]})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[Ze&&e.jsx($,{variant:"ghost",size:"sm",title:"Preview next email",onClick:()=>m(Re),children:e.jsx(ga,{className:"h-3.5 w-3.5"})}),Re.status==="active"&&e.jsx($,{variant:"ghost",size:"sm",onClick:()=>ne.mutate({id:Re.id,newStatus:"paused"}),children:e.jsx(vy,{className:"h-3.5 w-3.5"})}),Re.status==="paused"&&e.jsx($,{variant:"ghost",size:"sm",onClick:()=>ne.mutate({id:Re.id,newStatus:"active"}),children:e.jsx(Td,{className:"h-3.5 w-3.5"})}),(Re.status==="active"||Re.status==="paused")&&e.jsx($,{variant:"ghost",size:"sm",className:"text-destructive",onClick:()=>ne.mutate({id:Re.id,newStatus:"cancelled"}),children:e.jsx($d,{className:"h-3.5 w-3.5"})})]})]},Re.id)})})}),e.jsxs(Jt,{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(vs,{value:g,onValueChange:y,children:[e.jsx(gs,{className:"w-[220px] h-8 text-xs",children:e.jsx(bs,{placeholder:"All campaigns"})}),e.jsxs(ys,{children:[e.jsx(Ye,{value:"all",children:"All campaigns"}),Q.map(Re=>e.jsx(Ye,{value:Re.id,children:Re.name},Re.id))]})]}),e.jsxs(vs,{value:b,onValueChange:v,children:[e.jsx(gs,{className:"w-[160px] h-8 text-xs",children:e.jsx(bs,{placeholder:"All statuses"})}),e.jsxs(ys,{children:[e.jsx(Ye,{value:"all",children:"All statuses"}),e.jsx(Ye,{value:"sent",children:"Sent (no engagement)"}),e.jsx(Ye,{value:"opened",children:"Opened"}),e.jsx(Ye,{value:"clicked",children:"Clicked"})]})]}),(g!=="all"||b!=="all")&&e.jsx($,{variant:"ghost",size:"sm",className:"h-8 text-xs",onClick:()=>{y("all"),v("all")},children:"Clear"})]}),(()=>{var Ae;const Re=K.filter(Be=>{var qe;return!(g!=="all"&&((qe=Be.campaign_email)==null?void 0:qe.campaign_id)!==g||b==="opened"&&!Be.opened_at||b==="clicked"&&!Be.clicked_at||b==="sent"&&(Be.opened_at||Be.clicked_at))});return Re.length===0?e.jsx(_e,{children:e.jsxs(Oe,{className:"py-12 text-center text-muted-foreground",children:[e.jsx(nn,{className:"h-12 w-12 mx-auto mb-4 opacity-50"}),e.jsx("p",{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 ",Re.length," of ",K.length," recent sends",g!=="all"&&` · ${(Ae=Q.find(Be=>Be.id===g))==null?void 0:Ae.name}`]}),e.jsx("div",{className:"space-y-1",children:Re.map(Be=>{var Ue,et,Qe;const qe=Wvt[Be.status]||Wvt.sent,Ke=qe.icon,Ze=(Ue=Q.find(Ge=>{var nt;return Ge.id===((nt=Be.campaign_email)==null?void 0:nt.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(Ke,{className:`h-4 w-4 flex-shrink-0 ${qe.color}`}),e.jsxs("div",{className:"min-w-0",children:[e.jsxs("p",{className:"font-medium text-sm truncate",children:[(et=Be.prospect)==null?void 0:et.first_name," ",(Qe=Be.prospect)==null?void 0:Qe.last_name,e.jsxs("span",{className:"text-muted-foreground font-normal ml-2",children:["Email #",Be.email_number]}),Ze&&e.jsx($e,{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:Be.subject})]})]}),e.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground flex-shrink-0",children:[Be.opened_at&&e.jsxs("span",{className:"flex items-center gap-1 text-amber-500",children:[e.jsx(ga,{className:"h-3 w-3"})," ",Hs(new Date(Be.opened_at),"MMM d")]}),Be.clicked_at&&e.jsxs("span",{className:"flex items-center gap-1 text-green-500",children:[e.jsx(uu,{className:"h-3 w-3"})," ",Hs(new Date(Be.clicked_at),"MMM d")]}),e.jsx("span",{children:Hs(new Date(Be.sent_at),"MMM d, h:mm a")})]})]},Be.id)})})]})})()]})]}),e.jsx(Os,{open:r,onOpenChange:Re=>{a(Re),Re||(x(""),c(new Set),l(""))},children:e.jsxs(Rs,{className:"max-w-lg max-h-[85vh] flex flex-col p-0",children:[e.jsxs(Us,{className:"px-6 pt-6 pb-4",children:[e.jsx(zs,{children:"Assign Campaign to Prospects"}),e.jsx(Sr,{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(se,{className:"text-sm font-medium",children:"1. Select Campaign"}),e.jsxs(vs,{value:i,onValueChange:l,children:[e.jsx(gs,{children:e.jsx(bs,{placeholder:"Choose a campaign..."})}),e.jsx(ys,{children:Q.map(Re=>e.jsx(Ye,{value:Re.id,children:Re.name},Re.id))})]})]}),i&&(()=>{const Re=p.toLowerCase(),Ae=J.filter(Ke=>`${Ke.first_name} ${Ke.last_name}`.toLowerCase().includes(Re)||Ke.email.toLowerCase().includes(Re)),Be=Ae.filter(Ke=>!ce.has(`${Ke.id}-${i}`)),qe=Be.length>0&&Be.every(Ke=>o.has(Ke.id));return e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(se,{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(Vr,{className:"absolute left-2.5 top-2.5 h-4 w-4 text-muted-foreground"}),e.jsx(be,{placeholder:"Search by name or email...",value:p,onChange:Ke=>x(Ke.target.value),className:"pl-9 h-9"})]}),e.jsxs($,{variant:"outline",size:"sm",className:"h-9 whitespace-nowrap",onClick:()=>{if(qe){const Ke=new Set(o);Be.forEach(Ze=>Ke.delete(Ze.id)),c(Ke)}else{const Ke=new Set(o);Be.forEach(Ze=>Ke.add(Ze.id)),c(Ke)}},children:[e.jsx(cR,{className:"h-3.5 w-3.5 mr-1"}),qe?"Deselect All":`Select All (${Be.length})`]})]}),e.jsx("div",{className:"border rounded-lg max-h-60 overflow-y-auto divide-y",children:Ae.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"}):Ae.map(Ke=>{const Ze=ce.has(`${Ke.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(ui,{checked:o.has(Ke.id),disabled:Ze,onCheckedChange:Ue=>{const et=new Set(o);Ue?et.add(Ke.id):et.delete(Ke.id),c(et)}}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("p",{className:"text-sm font-medium truncate",children:[Ke.first_name," ",Ke.last_name]}),e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:Ke.email})]}),Ze&&e.jsx($e,{variant:"outline",className:"text-[10px] shrink-0",children:"Already assigned"})]},Ke.id)})}),Ae.length>0&&e.jsxs("p",{className:"text-[11px] text-muted-foreground",children:["Showing ",Ae.length," of ",J.length," prospects",Be.length0&&e.jsx(_e,{className:"bg-primary/5 border-primary/20",children:e.jsxs(Oe,{className:"pt-3 pb-2 text-sm space-y-1",children:[e.jsxs("p",{className:"font-medium text-primary",children:["✅ Ready to assign ",o.size," prospect",o.size>1?"s":""]}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["• Campaign: ",e.jsx("strong",{children:(Se=Q.find(Re=>Re.id===i))==null?void 0:Se.name})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"• First email sends immediately · follow-ups every 7 days"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"• You can pause or cancel any assignment at any time"})]})})]}),e.jsxs(kr,{className:"px-6 py-4 border-t",children:[e.jsx($,{variant:"outline",onClick:()=>a(!1),children:"Cancel"}),e.jsxs($,{onClick:()=>{ue.mutate()},disabled:ue.isPending||!i||o.size===0,children:[e.jsx(Br,{className:"h-4 w-4 mr-1"}),ue.isPending?"Assigning...":`Assign & Start (${o.size})`]})]})]})}),h&&(()=>{const Re=q(h);return Re?e.jsx(ZVt,{email:Re,mergeValues:B,selectedSubjectIndex:D[Re.id],onClose:()=>m(null)}):null})(),e.jsx(OEe,{open:N,onOpenChange:C,hasPending:A==null?void 0:A.hasPendingSes,pendingEmails:A==null?void 0:A.pendingEmails})]})}function eHt({brokerageId:s}){const t=ts(),[n,r]=j.useState([]),[a,i]=j.useState([]),[l,o]=j.useState(!1),c=j.useRef(!1),{data:d,isLoading:u}=ht({queryKey:["recruit-stages-editor",s],queryFn:async()=>{const{data:y,error:b}=await U.from("recruit_pipeline_stages").select("*").eq("brokerage_id",s).order("sort_order");if(b)throw b;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 v of a){const{error:N}=await U.from("recruit_pipeline_stages").delete().eq("id",v);if(N)throw N}const y=n.filter(v=>v.id&&!v.isNew),b=n.filter(v=>!v.id||v.isNew);for(const v of y){const{error:N}=await U.from("recruit_pipeline_stages").update({name:v.name,color:v.color,sort_order:v.sort_order}).eq("id",v.id);if(N)throw N}if(b.length>0){const{error:v}=await U.from("recruit_pipeline_stages").insert(b.map(N=>({brokerage_id:s,name:N.name,color:N.color,sort_order:N.sort_order})));if(v)throw v}},onSuccess:()=>{i([]),t.invalidateQueries({queryKey:["recruit-stages-editor",s]}),t.invalidateQueries({queryKey:["recruit-stages",s]}),ae.success("Pipeline stages saved!"),o(!1)},onError:y=>ae.error(y.message)}),m=(y,b,v)=>{r(N=>N.map((C,A)=>A===y?{...C,[b]:v}:C)),o(!0)},p=()=>{const y=n.length>0?Math.max(...n.map(b=>b.sort_order)):0;r(b=>[...b,{name:"",color:"#6366f1",sort_order:y+1,isNew:!0}]),o(!0)},x=y=>{const b=n[y];b.id&&!b.isNew&&i(v=>[...v,b.id]),r(v=>v.filter((N,C)=>C!==y)),o(!0)},g=(y,b)=>{const v=y+b;if(v<0||v>=n.length)return;const N=[...n];[N[y],N[v]]=[N[v],N[y]],N.forEach((C,A)=>C.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,b)=>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:()=>g(b,-1),disabled:b===0,className:"text-muted-foreground hover:text-foreground disabled:opacity-30 text-xs",children:"▲"}),e.jsx("button",{type:"button",onClick:()=>g(b,1),disabled:b===n.length-1,className:"text-muted-foreground hover:text-foreground disabled:opacity-30 text-xs",children:"▼"})]}),e.jsx($p,{className:"h-4 w-4 text-muted-foreground/50 shrink-0"}),e.jsx("input",{type:"color",value:y.color,onChange:v=>m(b,"color",v.target.value),className:"h-8 w-8 rounded cursor-pointer border-0 p-0 shrink-0"}),e.jsx(be,{value:y.name,onChange:v=>m(b,"name",v.target.value),placeholder:"Stage name…",className:"flex-1"}),e.jsx("span",{className:"text-xs text-muted-foreground w-6 text-center shrink-0",children:b+1}),e.jsx($,{variant:"ghost",size:"icon",onClick:()=>x(b),className:"text-destructive hover:text-destructive shrink-0 h-8 w-8",children:e.jsx(Pn,{className:"h-4 w-4"})})]},y.id||`new-${b}`))}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs($,{variant:"outline",size:"sm",onClick:p,className:"gap-1",children:[e.jsx(sn,{className:"h-4 w-4"})," Add Stage"]}),l&&e.jsxs($,{size:"sm",onClick:()=>h.mutate(),disabled:h.isPending,className:"gap-1",children:[e.jsx(Jo,{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 tOn({brokerageId:s}){const{data:t=[],isLoading:n}=ht({queryKey:["recruit-unsubscribed",s],queryFn:async()=>{const{data:r,error:a}=await U.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(NR,{className:"h-5 w-5 text-muted-foreground"}),"Unsubscribed Prospects"]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Prospects who opted out of recruiting emails. They will not receive further outreach."})]}),e.jsxs($e,{variant:"secondary",className:"text-base px-3 py-1",children:[t.length," total"]})]}),t.length===0?e.jsx(_e,{children:e.jsxs(Oe,{className:"py-12 text-center text-muted-foreground",children:[e.jsx(NR,{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(_e,{className:"hover:shadow-sm transition-shadow",children:[e.jsx(Bt,{className:"pb-3",children:e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{children:[e.jsxs(Ut,{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(nn,{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(ia,{className:"h-3 w-3"}),r.unsubscribed_at&&Hs(new Date(r.unsubscribed_at),"MMM d, yyyy")]})]})}),r.unsubscribe_reason&&e.jsx(Oe,{className:"pt-0",children:e.jsxs("div",{className:"text-sm bg-muted/40 rounded-md px-3 py-2 italic text-muted-foreground",children:['"',r.unsubscribe_reason,'"']})})]},r.id))})]})}function sOn(){var o;const[s,t]=j.useState(""),[n,r]=j.useState("board"),{data:a=[],isLoading:i}=ht({queryKey:["all-brokerages"],queryFn:async()=>{const{data:c,error:d}=await U.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(Ks,{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(Ks,{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(vs,{value:l,onValueChange:t,children:[e.jsxs(gs,{className:"w-[280px]",children:[e.jsx(Ai,{className:"mr-2 h-4 w-4"}),e.jsx(bs,{placeholder:"Select brokerage"})]}),e.jsx(ys,{children:a.map(c=>e.jsx(Ye,{value:c.id,children:c.name},c.id))})]})]}):e.jsx("div",{}),l&&e.jsx(WVt,{brokerageId:l,trigger:e.jsxs($,{size:"sm",className:"gap-1.5",children:[e.jsx(Xr,{className:"h-4 w-4"})," Record & Send Video"]})})]}),l?e.jsxs(ua,{defaultValue:"pipeline",className:"space-y-4",children:[e.jsxs(ha,{className:"flex-wrap h-auto gap-1",children:[e.jsx(Qt,{value:"pipeline",children:"Pipeline"}),e.jsxs(Qt,{value:"contacts",children:[e.jsx(qn,{className:"h-3.5 w-3.5 mr-1"}),"Contacts"]}),e.jsxs(Qt,{value:"video-outreach",children:[e.jsx(Xr,{className:"h-3.5 w-3.5 mr-1"}),"Video Outreach"]}),e.jsx(Qt,{value:"follow-ups",children:"Follow-ups"}),e.jsx(Qt,{value:"referrals",children:"Referrals"}),e.jsx(Qt,{value:"interest",children:"Interest Form"}),e.jsx(Qt,{value:"landing-page",children:"Landing Page"}),e.jsx(Qt,{value:"goals",children:"Goals"}),e.jsx(Qt,{value:"metrics",children:"Metrics"}),e.jsx(Qt,{value:"templates",children:"Email Templates"}),e.jsxs(Qt,{value:"campaigns",children:[e.jsx(nn,{className:"h-3.5 w-3.5 mr-1"}),"Campaigns"]}),e.jsxs(Qt,{value:"drip-assignments",children:[e.jsx(Br,{className:"h-3.5 w-3.5 mr-1"}),"Drip Assignments"]}),e.jsx(Qt,{value:"activity",children:"Recruiter Activity"}),e.jsxs(Qt,{value:"email-settings",children:[e.jsx(pc,{className:"h-3.5 w-3.5 mr-1"}),"Email Settings"]}),e.jsxs(Qt,{value:"pipeline-stages",children:[e.jsx(TT,{className:"h-3.5 w-3.5 mr-1"}),"Pipeline Stages"]}),e.jsxs(Qt,{value:"unsubscribed",children:[e.jsx(NR,{className:"h-3.5 w-3.5 mr-1"}),"Unsubscribed"]})]}),e.jsxs(Jt,{value:"pipeline",children:[e.jsx("div",{className:"flex justify-end mb-3",children:e.jsxs("div",{className:"flex items-center rounded-md border bg-muted p-0.5",children:[e.jsxs($,{variant:n==="board"?"default":"ghost",size:"sm",className:"h-7 px-2.5 gap-1.5",onClick:()=>r("board"),children:[e.jsx(_0,{className:"h-3.5 w-3.5"})," Board"]}),e.jsxs($,{variant:n==="table"?"default":"ghost",size:"sm",className:"h-7 px-2.5 gap-1.5",onClick:()=>r("table"),children:[e.jsx(Uz,{className:"h-3.5 w-3.5"})," Table"]})]})}),n==="board"?e.jsx(zVt,{brokerageId:l}):e.jsx(F4e,{brokerageId:l})]}),e.jsx(Jt,{value:"contacts",children:e.jsx(F4e,{brokerageId:l})}),e.jsx(Jt,{value:"video-outreach",children:e.jsx(KVt,{brokerageId:l})}),e.jsx(Jt,{value:"follow-ups",children:e.jsx(HVt,{brokerageId:l})}),e.jsx(Jt,{value:"referrals",children:e.jsx(qVt,{brokerageId:l})}),e.jsx(Jt,{value:"interest",children:e.jsx(VVt,{brokerageId:l})}),e.jsx(Jt,{value:"landing-page",children:e.jsx(GVt,{brokerageId:l})}),e.jsx(Jt,{value:"goals",children:e.jsx(YVt,{brokerageId:l})}),e.jsx(Jt,{value:"metrics",children:e.jsx(BVt,{brokerageId:l})}),e.jsx(Jt,{value:"templates",children:e.jsx($Vt,{brokerageId:l})}),e.jsx(Jt,{value:"campaigns",children:e.jsx(QVt,{brokerageId:l})}),e.jsx(Jt,{value:"drip-assignments",children:e.jsx(JVt,{brokerageId:l})}),e.jsx(Jt,{value:"activity",children:e.jsx(UVt,{brokerageId:l})}),e.jsx(Jt,{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(gXe,{brokerageId:l})]})}),e.jsx(Jt,{value:"pipeline-stages",children:e.jsx("div",{className:"max-w-2xl",children:e.jsx(eHt,{brokerageId:l})})}),e.jsx(Jt,{value:"unsubscribed",children:e.jsx(tOn,{brokerageId:l})})]}):e.jsxs("div",{className:"text-center py-12 text-muted-foreground",children:[e.jsx(Ai,{className:"h-12 w-12 mx-auto mb-4 opacity-50"}),e.jsx("p",{children:"No brokerages found. Create a brokerage first."})]})]})})}function nOn({brokerageId:s}){const[t,n]=j.useState(""),[r,a]=j.useState("all"),{data:i,isLoading:l}=ht({queryKey:["recruit-sent-emails",s],queryFn:async()=>{var y;const{data:d,error:u}=await U.from("recruit_prospects").select("id, first_name, last_name, email").eq("brokerage_id",s);if(u)throw u;const h=new Map((d||[]).map(b=>[b.id,b]));if(Array.from(h.keys()).length===0)return[];const{data:p}=await U.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:x}=await U.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}),g=[];for(const b of p||[]){const v=h.get(b.prospect_id);v&&g.push({id:`v-${b.id}`,kind:"video",prospect_id:b.prospect_id,prospect_name:`${v.first_name||""} ${v.last_name||""}`.trim()||"—",prospect_email:v.email,subject:(y=b.video)!=null&&y.title?`Video: ${b.video.title}`:"Recruiting Video",status:b.cta_clicked_at?"clicked":b.first_viewed_at?"viewed":"sent",sent_at:b.sent_at,opened_at:b.first_viewed_at,clicked_at:b.cta_clicked_at,view_count:b.view_count,share_token:b.share_token})}for(const b of x||[]){if(!b.sent_at)continue;const v=h.get(b.prospect_id);v&&g.push({id:`c-${b.id}`,kind:"campaign",prospect_id:b.prospect_id,prospect_name:`${v.first_name||""} ${v.last_name||""}`.trim()||"—",prospect_email:v.email,subject:b.subject||`Email #${b.email_number}`,status:b.status||"sent",sent_at:b.sent_at,opened_at:b.opened_at,clicked_at:b.clicked_at,error:b.error_message})}return g.sort((b,v)=>new Date(v.sent_at).getTime()-new Date(b.sent_at).getTime()),g}}),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:Br,color:"text-primary"},{label:"Video Emails",value:o.videos,icon:Xr,color:"text-blue-500"},{label:"Campaign Emails",value:o.campaigns,icon:nn,color:"text-violet-500"},{label:"Opened / Viewed",value:o.opened,icon:ga,color:"text-amber-500"},{label:"Clicked",value:o.clicked,icon:uu,color:"text-emerald-500"}].map(d=>e.jsx(_e,{children:e.jsxs(Oe,{className:"p-3 flex items-center gap-2.5",children:[e.jsx("div",{className:`h-9 w-9 rounded-lg bg-muted flex items-center justify-center ${d.color}`,children:e.jsx(d.icon,{className:"h-4 w-4"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xl font-bold leading-tight",children:d.value}),e.jsx("p",{className:"text-[11px] text-muted-foreground",children:d.label})]})]})},d.label))}),e.jsxs(_e,{children:[e.jsx(Bt,{className:"pb-3",children:e.jsxs("div",{className:"flex items-center justify-between gap-2 flex-wrap",children:[e.jsx(Ut,{className:"text-lg",children:"Sent Emails"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ua,{value:r,onValueChange:d=>a(d),children:e.jsxs(ha,{className:"h-8",children:[e.jsx(Qt,{value:"all",className:"text-xs h-7",children:"All"}),e.jsx(Qt,{value:"video",className:"text-xs h-7",children:"Video"}),e.jsx(Qt,{value:"campaign",className:"text-xs h-7",children:"Campaign"})]})}),e.jsxs("div",{className:"relative w-56",children:[e.jsx(Vr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(be,{placeholder:"Search recruit, subject...",value:t,onChange:d=>n(d.target.value),className:"pl-9 h-9"})]})]})]})}),e.jsx(Oe,{children:l?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})}):c.length===0?e.jsxs("div",{className:"text-center py-12 text-muted-foreground",children:[e.jsx(nn,{className:"h-12 w-12 mx-auto mb-4 opacity-50"}),e.jsx("p",{className:"font-medium",children:"No emails sent yet"}),e.jsx("p",{className:"text-sm mt-1",children:"Emails sent from Video Outreach or Drip Campaigns will appear here."})]}):e.jsx("div",{className:"rounded-lg border overflow-hidden",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{className:"bg-muted/40 text-xs text-muted-foreground",children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left font-medium px-3 py-2",children:"Type"}),e.jsx("th",{className:"text-left font-medium px-3 py-2",children:"Recruit"}),e.jsx("th",{className:"text-left font-medium px-3 py-2",children:"Subject"}),e.jsx("th",{className:"text-left font-medium px-3 py-2",children:"Status"}),e.jsx("th",{className:"text-left font-medium px-3 py-2",children:"Sent"}),e.jsx("th",{className:"text-right font-medium px-3 py-2",children:"Engagement"})]})}),e.jsx("tbody",{children:c.map(d=>e.jsxs("tr",{className:"border-t hover:bg-muted/30 transition-colors",children:[e.jsx("td",{className:"px-3 py-2",children:d.kind==="video"?e.jsxs($e,{variant:"outline",className:"gap-1",children:[e.jsx(Xr,{className:"h-3 w-3"}),"Video"]}):e.jsxs($e,{variant:"outline",className:"gap-1",children:[e.jsx(nn,{className:"h-3 w-3"}),"Campaign"]})}),e.jsxs("td",{className:"px-3 py-2",children:[e.jsx("div",{className:"font-medium",children:d.prospect_name}),d.prospect_email&&e.jsx("div",{className:"text-xs text-muted-foreground",children:d.prospect_email})]}),e.jsx("td",{className:"px-3 py-2 max-w-xs truncate",children:d.subject}),e.jsxs("td",{className:"px-3 py-2",children:[d.status==="failed"||d.status==="bounced"?e.jsxs($e,{variant:"destructive",className:"gap-1",children:[e.jsx(xo,{className:"h-3 w-3"}),d.status]}):d.clicked_at?e.jsxs($e,{className:"bg-emerald-500/15 text-emerald-700 border-emerald-200 gap-1",children:[e.jsx(uu,{className:"h-3 w-3"}),"Clicked"]}):d.opened_at?e.jsxs($e,{className:"bg-blue-500/15 text-blue-700 border-blue-200 gap-1",children:[e.jsx(ga,{className:"h-3 w-3"}),"Opened"]}):e.jsxs($e,{variant:"secondary",className:"gap-1",children:[e.jsx(Br,{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:[Hs(new Date(d.sent_at),"MMM d, yyyy"),e.jsx("div",{className:"text-[10px]",children:Hs(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(ga,{className:"h-3 w-3"}),d.view_count]}),d.kind==="video"&&d.share_token&&e.jsx($,{variant:"ghost",size:"icon",className:"h-7 w-7",onClick:()=>window.open(`/recruit-video/${d.share_token}`,"_blank"),title:"Open landing page",children:e.jsx(Tr,{className:"h-3.5 w-3.5"})})]})})]},d.id))})]})})})]})]})}function rOn(){var l;const{managedBrokerages:s,selectedBrokerageId:t,setSelectedBrokerageId:n}=_s(),[r,a]=j.useState("board"),i=t||((l=s[0])==null?void 0:l.id)||"";return s.length===0?e.jsx(Ks,{title:"Recruiting",description:"Agent Recruiting Pipeline",children:e.jsxs("div",{className:"text-center py-12 text-muted-foreground",children:[e.jsx(Ai,{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(Ks,{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(vs,{value:i,onValueChange:n,children:[e.jsxs(gs,{className:"w-[280px]",children:[e.jsx(Ai,{className:"mr-2 h-4 w-4"}),e.jsx(bs,{placeholder:"Select brokerage"})]}),e.jsx(ys,{children:s.map(o=>e.jsx(Ye,{value:o.id,children:o.name},o.id))})]})]}),i?e.jsxs(ua,{defaultValue:"pipeline",className:"space-y-4",children:[e.jsxs(ha,{className:"flex-wrap h-auto gap-1",children:[e.jsx(Qt,{value:"pipeline",children:"Pipeline"}),e.jsxs(Qt,{value:"contacts",children:[e.jsx(qn,{className:"h-3.5 w-3.5 mr-1"}),"Contacts"]}),e.jsxs(Qt,{value:"video-outreach",children:[e.jsx(Xr,{className:"h-3.5 w-3.5 mr-1"}),"Video Outreach"]}),e.jsx(Qt,{value:"follow-ups",children:"Follow-ups"}),e.jsx(Qt,{value:"referrals",children:"Referrals"}),e.jsx(Qt,{value:"interest",children:"Interest Form"}),e.jsx(Qt,{value:"landing-page",children:"Landing Page"}),e.jsx(Qt,{value:"goals",children:"Goals"}),e.jsx(Qt,{value:"metrics",children:"Metrics"}),e.jsx(Qt,{value:"templates",children:"Email Templates"}),e.jsxs(Qt,{value:"campaigns",children:[e.jsx(nn,{className:"h-3.5 w-3.5 mr-1"}),"Campaigns"]}),e.jsxs(Qt,{value:"drip-assignments",children:[e.jsx(Br,{className:"h-3.5 w-3.5 mr-1"}),"Drip Assignments"]}),e.jsxs(Qt,{value:"sent-emails",children:[e.jsx(bT,{className:"h-3.5 w-3.5 mr-1"}),"Sent Emails"]}),e.jsx(Qt,{value:"activity",children:"Recruiter Activity"}),e.jsxs(Qt,{value:"email-settings",children:[e.jsx(pc,{className:"h-3.5 w-3.5 mr-1"}),"Email Settings"]}),e.jsxs(Qt,{value:"pipeline-stages",children:[e.jsx(TT,{className:"h-3.5 w-3.5 mr-1"}),"Pipeline Stages"]})]}),e.jsxs(Jt,{value:"pipeline",children:[e.jsx("div",{className:"flex justify-end mb-3",children:e.jsxs("div",{className:"flex items-center rounded-md border bg-muted p-0.5",children:[e.jsxs($,{variant:r==="board"?"default":"ghost",size:"sm",className:"h-7 px-2.5 gap-1.5",onClick:()=>a("board"),children:[e.jsx(_0,{className:"h-3.5 w-3.5"})," Board"]}),e.jsxs($,{variant:r==="table"?"default":"ghost",size:"sm",className:"h-7 px-2.5 gap-1.5",onClick:()=>a("table"),children:[e.jsx(Uz,{className:"h-3.5 w-3.5"})," Table"]})]})}),r==="board"?e.jsx(zVt,{brokerageId:i}):e.jsx(F4e,{brokerageId:i})]}),e.jsx(Jt,{value:"contacts",children:e.jsx(F4e,{brokerageId:i})}),e.jsx(Jt,{value:"video-outreach",children:e.jsx(KVt,{brokerageId:i})}),e.jsx(Jt,{value:"follow-ups",children:e.jsx(HVt,{brokerageId:i})}),e.jsx(Jt,{value:"referrals",children:e.jsx(qVt,{brokerageId:i})}),e.jsx(Jt,{value:"interest",children:e.jsx(VVt,{brokerageId:i})}),e.jsx(Jt,{value:"landing-page",children:e.jsx(GVt,{brokerageId:i})}),e.jsx(Jt,{value:"goals",children:e.jsx(YVt,{brokerageId:i})}),e.jsx(Jt,{value:"metrics",children:e.jsx(BVt,{brokerageId:i})}),e.jsx(Jt,{value:"templates",children:e.jsx($Vt,{brokerageId:i})}),e.jsx(Jt,{value:"campaigns",children:e.jsx(QVt,{brokerageId:i})}),e.jsx(Jt,{value:"drip-assignments",children:e.jsx(JVt,{brokerageId:i})}),e.jsx(Jt,{value:"sent-emails",children:e.jsx(nOn,{brokerageId:i})}),e.jsx(Jt,{value:"activity",children:e.jsx(UVt,{brokerageId:i})}),e.jsx(Jt,{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(gXe,{brokerageId:i})]})}),e.jsx(Jt,{value:"pipeline-stages",children:e.jsx("div",{className:"max-w-2xl",children:e.jsx(eHt,{brokerageId:i})})})]}):e.jsxs("div",{className:"text-center py-12 text-muted-foreground",children:[e.jsx(Ai,{className:"h-12 w-12 mx-auto mb-4 opacity-50"}),e.jsx("p",{children:"No brokerages found."})]})]})})}function aOn(){const[s,t]=j.useState(""),{data:n,isLoading:r}=ht({queryKey:["admin-brokerage-content-activity"],queryFn:async()=>{const{data:o}=await U.from("brokerages").select("id, name");if(!o)return[];const{data:c}=await U.from("brokerage_content").select("id, brokerage_id, content_type, created_at"),{data:d}=await U.from("brokerage_content_categories").select("id, brokerage_id"),u=c||[],h=d||[],m=o.map(p=>{const x=u.filter(b=>b.brokerage_id===p.id),g=h.filter(b=>b.brokerage_id===p.id),y=x.length>0?x.reduce((b,v)=>v.created_at>b?v.created_at:b,x[0].created_at):null;return{brokerage_id:p.id,brokerage_name:p.name,total_items:x.length,videos:x.filter(b=>b.content_type==="video").length,pdfs:x.filter(b=>b.content_type==="pdf").length,links:x.filter(b=>b.content_type==="link"||b.content_type==="canva_link").length,events:x.filter(b=>b.content_type==="event").length,graphics:x.filter(b=>b.content_type==="graphic").length,latest_item_date:y,categories:g.length}});return m.sort((p,x)=>x.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(Ks,{title:"Brokerage Content Activity",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(hh,{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(_e,{children:[e.jsx(Bt,{className:"pb-2",children:e.jsx(Ut,{className:"text-sm font-medium text-muted-foreground",children:"Active Brokerages"})}),e.jsxs(Oe,{children:[e.jsx("p",{className:"text-2xl font-bold",children:l}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"with content uploaded"})]})]}),e.jsxs(_e,{children:[e.jsx(Bt,{className:"pb-2",children:e.jsx(Ut,{className:"text-sm font-medium text-muted-foreground",children:"Total Content Items"})}),e.jsxs(Oe,{children:[e.jsx("p",{className:"text-2xl font-bold",children:i}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"across all brokerages"})]})]}),e.jsxs(_e,{children:[e.jsx(Bt,{className:"pb-2",children:e.jsx(Ut,{className:"text-sm font-medium text-muted-foreground",children:"Total Brokerages"})}),e.jsxs(Oe,{children:[e.jsx("p",{className:"text-2xl font-bold",children:a.length}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"registered"})]})]})]}),e.jsxs("div",{className:"relative max-w-sm",children:[e.jsx(Vr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(be,{placeholder:"Search brokerages...",value:s,onChange:o=>t(o.target.value),className:"pl-9"})]}),e.jsx(_e,{children:e.jsx(Oe,{className:"p-0",children:e.jsxs(Va,{children:[e.jsx(Ha,{children:e.jsxs(hn,{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(Xr,{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(Wr,{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(Dc,{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(Nl,{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(Jl,{className:"h-3 w-3"})," Graphics"]})}),e.jsx(Lt,{className:"text-center",children:"Categories"}),e.jsx(Lt,{children:"Last Upload"})]})}),e.jsx(Ga,{children:r?e.jsx(hn,{children:e.jsx(gt,{colSpan:9,className:"text-center py-8 text-muted-foreground",children:"Loading..."})}):a.length===0?e.jsx(hn,{children:e.jsx(gt,{colSpan:9,className:"text-center py-8 text-muted-foreground",children:"No brokerages found"})}):a.map(o=>e.jsxs(hn,{className:o.total_items===0?"opacity-50":"",children:[e.jsx(gt,{children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ai,{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($e,{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:Hs(new Date(o.latest_item_date),"MMM d, yyyy")}):e.jsx("span",{className:"text-muted-foreground",children:"–"})})]},o.brokerage_id))})]})})})]})})}const iOn=[{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:"📉"}],Kvt=[{value:"instagram-square",label:"Instagram Post",dimensions:"1080×1080",icon:e.jsx(Qh,{className:"h-4 w-4"})},{value:"instagram-story",label:"Instagram Story",dimensions:"1080×1920",icon:e.jsx(Qh,{className:"h-4 w-4"})},{value:"facebook-post",label:"Facebook Post",dimensions:"1200×630",icon:e.jsx(jf,{className:"h-4 w-4"})}],oOn=[{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:"📰"}],Yvt=s=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(s),Zvt={"luxury-dark":RWe,"modern-clean":OWe,"bold-colorful":FWe,editorial:zWe};function lOn(){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"),[x,g]=j.useState(["instagram-square"]),[y,b]=j.useState("luxury-dark"),[v,N]=j.useState(!1),[C,A]=j.useState(""),[T,P]=j.useState(""),[M,I]=j.useState(""),[D,B]=j.useState(!1),[q,W]=j.useState(!1),[V,K]=j.useState([]),[Q,J]=j.useState("search"),ce=j.useRef({});j.useEffect(()=>{(async()=>{const{data:{user:Ee}}=await U.auth.getUser();if(!Ee)return;const{data:Me}=await U.from("profiles").select("name, avatar_url, brokerages(name)").eq("id",Ee.id).single();if(Me){A(Me.name||""),I(Me.avatar_url||"");const De=Me.brokerages;P((De==null?void 0:De.name)||"")}})()},[]);const ue=async()=>{var je;if(s.trim()){i(!0),o([]);try{const{data:Ee,error:Me}=await U.functions.invoke("repliers-mls-search",{body:{searchType:n,query:s.trim()}});if(Me)throw Me;if(Ee.error)throw new Error(Ee.error);o(Ee.listings||[]),((je=Ee.listings)==null?void 0:je.length)===0&&ae.info("No listings found. Try a different search.")}catch(Ee){ae.error(Ee.message||"Search failed")}finally{i(!1)}}},ne=je=>{var Ee;d(je),h(0),J("customize"),je.soldDate||(Ee=je.status)!=null&&Ee.toLowerCase().includes("sold")?p("just-sold"):p("just-listed")},ee=je=>{g(Ee=>Ee.includes(je)?Ee.filter(Me=>Me!==je):[...Ee,je])},le=j.useCallback(async()=>{if(!(!c||x.length===0)){B(!0),K([]),J("generate");try{await new Promise(Ee=>setTimeout(Ee,500));const je=[];for(const Ee of x){const Me=`${y}-${Ee}`,De=ce.current[Me];if(!De)continue;const ze=QE[Ee],ke=await hU(De,{width:ze.width,height:ze.height,pixelRatio:1,cacheBust:!0,style:{transform:"none",transformOrigin:"top left"}});je.push({format:Ee,imageUrl:ke})}K(je),ae.success(`Generated ${je.length} social post${je.length>1?"s":""}!`)}catch(je){ae.error(je.message||"Generation failed")}finally{B(!1)}}},[c,x,y,u,v,C,T,M,m]),he=async()=>{if(!(!c||x.length===0)){B(!0),K([]),J("generate");try{const je={...c,photos:c.photos.length>0?[c.photos[u]]:[]},Ee=[];for(const Me of x){const{data:De,error:ze}=await U.functions.invoke("generate-listing-social-post",{body:{listing:je,postType:m,format:Me,branding:v?{enabled:!0,agentName:C,brokerage:T}:{enabled:!1}}});if(ze)throw ze;if(De.error)throw new Error(De.error);Ee.push({format:Me,imageUrl:De.imageUrl})}K(Ee),ae.success(`Generated ${Ee.length} AI post${Ee.length>1?"s":""}!`)}catch(je){ae.error(je.message||"AI generation failed")}finally{B(!1)}}},ve=()=>q?he():le(),ge=(je,Ee)=>{var De;const Me=document.createElement("a");Me.href=je,Me.download=`${((De=c==null?void 0:c.address)==null?void 0:De.replace(/\s+/g,"-"))||"listing"}-${m}-${Ee}.png`,document.body.appendChild(Me),Me.click(),document.body.removeChild(Me)},fe=c?{listing:c,postType:m,format:"instagram-square",branding:v?{enabled:!0,agentName:C,brokerage:T,agentPhotoUrl:M||void 0}:{enabled:!1},selectedPhotoIndex:u}:null;return e.jsx(Ks,{children:e.jsxs("div",{className:"space-y-6 p-4 md:p-8",children:[e.jsx(hh,{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:()=>J("search"),className:`flex items-center gap-1.5 px-3 py-1.5 rounded-full transition-colors ${Q==="search"?"bg-primary text-primary-foreground":"bg-muted text-muted-foreground hover:text-foreground"}`,children:[e.jsx(Vr,{className:"h-3.5 w-3.5"})," 1. Find Listing"]}),e.jsx(Ja,{className:"h-4 w-4 text-muted-foreground"}),e.jsxs("button",{onClick:()=>c&&J("customize"),disabled:!c,className:`flex items-center gap-1.5 px-3 py-1.5 rounded-full transition-colors ${Q==="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(dn,{className:"h-3.5 w-3.5"})," 2. Customize"]}),e.jsx(Ja,{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 ${Q==="generate"?"bg-primary text-primary-foreground":"bg-muted text-muted-foreground/50"}`,children:[e.jsx(Jl,{className:"h-3.5 w-3.5"})," 3. Generate"]})]}),Q==="search"&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs(_e,{children:[e.jsxs(Bt,{children:[e.jsxs(Ut,{className:"flex items-center gap-2",children:[e.jsx(Vr,{className:"h-5 w-5 text-primary"})," Search MLS Listings ",e.jsx(N6t,{})]}),e.jsx(vr,{children:"Find a listing by MLS number or property address using Repliers.io"})]}),e.jsxs(Oe,{className:"space-y-4",children:[e.jsx(ua,{value:n,onValueChange:je=>r(je),children:e.jsxs(ha,{children:[e.jsxs(Qt,{value:"address",children:[e.jsx(ai,{className:"h-4 w-4 mr-1.5"})," Address"]}),e.jsxs(Qt,{value:"mls",children:[e.jsx(Up,{className:"h-4 w-4 mr-1.5"})," MLS #"]})]})}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(be,{value:s,onChange:je=>t(je.target.value),placeholder:n==="mls"?"Enter MLS number...":"Enter property address...",className:"flex-1",onKeyDown:je=>je.key==="Enter"&&ue()}),e.jsxs($,{onClick:ue,disabled:a||!s.trim(),children:[a?e.jsx(Ht,{className:"h-4 w-4 animate-spin"}):e.jsx(Vr,{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((je,Ee)=>{var Me;return e.jsx(_e,{className:"cursor-pointer hover:border-primary/50 hover:shadow-md transition-all group",onClick:()=>ne(je),children:e.jsx(Oe,{className:"p-0",children:e.jsxs("div",{className:"flex",children:[e.jsx("div",{className:"w-32 h-28 flex-shrink-0 bg-muted rounded-l-lg overflow-hidden",children:(Me=je.photos)!=null&&Me[0]?e.jsx("img",{src:je.photos[0],alt:je.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(sa,{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:Yvt(je.price)}),e.jsx("p",{className:"text-sm text-muted-foreground truncate",children:je.address}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[je.city,", ",je.state," ",je.zip]}),e.jsxs("div",{className:"flex items-center gap-3 mt-1.5 text-xs text-muted-foreground",children:[je.bedrooms>0&&e.jsxs("span",{className:"flex items-center gap-0.5",children:[e.jsx(JS,{className:"h-3 w-3"})," ",je.bedrooms]}),je.bathrooms>0&&e.jsxs("span",{className:"flex items-center gap-0.5",children:[e.jsx(_g,{className:"h-3 w-3"})," ",je.bathrooms]}),je.sqft>0&&e.jsxs("span",{className:"flex items-center gap-0.5",children:[e.jsx(_R,{className:"h-3 w-3"})," ",je.sqft.toLocaleString()]})]}),e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[e.jsx($e,{variant:"outline",className:"text-[10px]",children:je.mlsNumber}),e.jsx($e,{variant:"outline",className:"text-[10px]",children:je.status})]})]})]})})},je.mlsNumber||Ee)})})]})]}),Q==="customize"&&c&&e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-3 gap-6",children:[e.jsxs(_e,{className:"lg:col-span-1",children:[e.jsx(Bt,{className:"pb-3",children:e.jsx(Ut,{className:"text-base",children:"Selected Listing"})}),e.jsxs(Oe,{className:"space-y-3",children:[c.photos.length>0&&e.jsxs("div",{className:"relative",children:[e.jsx("div",{className:"aspect-[4/3] rounded-lg overflow-hidden bg-muted",children:e.jsx("img",{src:c.photos[u],alt:"Listing photo",className:"w-full h-full object-cover"})}),c.photos.length>1&&e.jsxs("div",{className:"flex items-center justify-between mt-2",children:[e.jsx($,{variant:"outline",size:"icon",className:"h-7 w-7",onClick:()=>h(je=>Math.max(0,je-1)),disabled:u===0,children:e.jsx(Ic,{className:"h-4 w-4"})}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:[u+1," of ",c.photos.length]}),e.jsx($,{variant:"outline",size:"icon",className:"h-7 w-7",onClick:()=>h(je=>Math.min(c.photos.length-1,je+1)),disabled:u===c.photos.length-1,children:e.jsx(Ja,{className:"h-4 w-4"})})]})]}),e.jsxs("div",{children:[e.jsx("p",{className:"font-bold text-lg",children:Yvt(c.price)}),e.jsx("p",{className:"text-sm text-muted-foreground",children:c.address}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[c.city,", ",c.state," ",c.zip]})]}),e.jsxs("div",{className:"grid grid-cols-3 gap-2 text-center",children:[c.bedrooms>0&&e.jsxs("div",{className:"bg-muted/50 rounded-lg p-2",children:[e.jsx("p",{className:"text-sm font-semibold",children:c.bedrooms}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:"Beds"})]}),c.bathrooms>0&&e.jsxs("div",{className:"bg-muted/50 rounded-lg p-2",children:[e.jsx("p",{className:"text-sm font-semibold",children:c.bathrooms}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:"Baths"})]}),c.sqft>0&&e.jsxs("div",{className:"bg-muted/50 rounded-lg p-2",children:[e.jsx("p",{className:"text-sm font-semibold",children:c.sqft.toLocaleString()}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:"Sq Ft"})]})]}),e.jsxs($,{variant:"outline",size:"sm",className:"w-full",onClick:()=>{J("search"),d(null)},children:[e.jsx(Ih,{className:"h-3.5 w-3.5 mr-1.5"})," Choose Different Listing"]})]})]}),e.jsxs(_e,{className:"lg:col-span-2",children:[e.jsxs(Bt,{children:[e.jsxs(Ut,{className:"flex items-center gap-2",children:[e.jsx(dn,{className:"h-5 w-5 text-primary"})," Customize Your Post"]}),e.jsx(vr,{children:"Choose template, post type, format, and branding"})]}),e.jsxs(Oe,{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between p-3 rounded-lg border bg-muted/30",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Rc,{className:"h-4 w-4 text-primary"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium",children:q?"AI Custom Generation":"Template-Based (Free)"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:q?"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(Tn,{checked:q,onCheckedChange:W}),q&&e.jsx(wm,{className:"h-4 w-4 text-purple-500"})]})]}),!q&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs(se,{className:"text-sm font-medium flex items-center gap-2",children:[e.jsx(Rc,{className:"h-4 w-4"})," Template Style"]}),e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-2",children:oOn.map(je=>e.jsxs("button",{onClick:()=>b(je.value),className:`flex flex-col items-center gap-1 px-3 py-3 rounded-lg border-2 transition-all text-center ${y===je.value?"border-primary bg-primary/5":"border-border hover:border-primary/30"}`,children:[e.jsx("span",{className:"text-2xl",children:je.preview}),e.jsx("span",{className:"text-sm font-medium",children:je.label}),e.jsx("span",{className:"text-[10px] text-muted-foreground leading-tight",children:je.description})]},je.value))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{className:"text-sm font-medium",children:"Post Type"}),e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-2",children:iOn.map(je=>e.jsxs("button",{onClick:()=>p(je.value),className:`flex items-center gap-2 px-3 py-2.5 rounded-lg border-2 transition-all text-sm font-medium ${m===je.value?"border-primary bg-primary/5":"border-border hover:border-primary/30"}`,children:[e.jsx("span",{className:"text-lg",children:je.icon})," ",je.label]},je.value))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{className:"text-sm font-medium",children:"Output Formats"}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-2",children:Kvt.map(je=>e.jsxs("button",{onClick:()=>ee(je.value),className:`flex items-center gap-2 px-3 py-2.5 rounded-lg border-2 transition-all text-sm ${x.includes(je.value)?"border-primary bg-primary/5":"border-border hover:border-primary/30"}`,children:[je.icon,e.jsxs("div",{className:"text-left",children:[e.jsx("p",{className:"font-medium",children:je.label}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:je.dimensions})]})]},je.value))})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(se,{className:"text-sm font-medium flex items-center gap-2",children:[e.jsx(Lo,{className:"h-4 w-4"})," Agent Branding"]}),e.jsx(Tn,{checked:v,onCheckedChange:N})]}),v&&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(se,{className:"text-xs text-muted-foreground",children:"Agent Name"}),e.jsx(be,{value:C,onChange:je=>A(je.target.value),placeholder:"Jane Smith"})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(se,{className:"text-xs text-muted-foreground",children:"Brokerage (optional)"}),e.jsx(be,{value:T,onChange:je=>P(je.target.value),placeholder:"XYZ Realty"})]})]})]})]}),!q&&fe&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{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*(QE[x[0]||"instagram-square"].height/QE[x[0]||"instagram-square"].width)},children:(()=>{const je=Zvt[y],Ee=x[0]||"instagram-square";return e.jsx(je,{...fe,format:Ee})})()})})]}),e.jsx($,{onClick:ve,disabled:x.length===0||D,size:"lg",className:"w-full gap-2",children:D?e.jsxs(e.Fragment,{children:[e.jsx(Ht,{className:"h-5 w-5 animate-spin"})," Generating ",x.length," post",x.length>1?"s":"","..."]}):e.jsxs(e.Fragment,{children:[q?e.jsx(wm,{className:"h-5 w-5"}):e.jsx(dn,{className:"h-5 w-5"}),"Generate ",x.length," Social Post",x.length>1?"s":"",q&&e.jsx($e,{variant:"outline",className:"ml-2 text-[10px]",children:"Uses Credits"})]})})]})]})]}),Q==="generate"&&e.jsxs("div",{className:"space-y-4",children:[D&&e.jsx(_e,{children:e.jsxs(Oe,{className:"flex flex-col items-center justify-center py-16",children:[e.jsx(Ht,{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:q?"AI is creating your unique designs":"Rendering templates to high-res images"})]})}),V.length>0&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("h3",{className:"text-lg font-semibold",children:"Generated Posts"}),e.jsxs($,{variant:"outline",size:"sm",onClick:()=>J("customize"),children:[e.jsx(Ih,{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((je,Ee)=>{const Me=Kvt.find(De=>De.value===je.format);return e.jsxs(_e,{className:"overflow-hidden",children:[e.jsx("div",{className:"bg-muted/30 p-1",children:e.jsx("img",{src:je.imageUrl,alt:`${je.format} social post`,className:"w-full rounded"})}),e.jsxs(Oe,{className:"p-3 space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[Me==null?void 0:Me.icon,e.jsx("span",{className:"text-sm font-medium",children:Me==null?void 0:Me.label})]}),e.jsx($e,{variant:"outline",className:"text-[10px]",children:Me==null?void 0:Me.dimensions})]}),e.jsxs($,{size:"sm",className:"w-full gap-1.5",onClick:()=>ge(je.imageUrl,je.format),children:[e.jsx(di,{className:"h-3.5 w-3.5"})," Download"]})]})]},Ee)})})]})]}),Q==="generate"&&!q&&c&&fe&&e.jsx("div",{style:{position:"absolute",left:"-9999px",top:0},"aria-hidden":!0,children:x.map(je=>{const Ee=Zvt[y],Me=QE[je];return e.jsx("div",{style:{width:Me.width,height:Me.height},children:e.jsx(Ee,{ref:De=>{ce.current[`${y}-${je}`]=De},...fe,format:je})},`${y}-${je}`)})})]})})}function cOn(){return ht({queryKey:["lms-courses-admin"],queryFn:async()=>{const{data:s,error:t}=await U.from("lms_courses").select("*, modules:lms_modules(count), access:lms_course_access(*)").order("sort_order");if(t)throw t;return s}})}function dOn(s){return ht({queryKey:["lms-course-admin",s],queryFn:async()=>{if(!s)return null;const{data:t,error:n}=await U.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 uOn(){const s=ts();return yt({mutationFn:async t=>{const{data:n,error:r}=await U.from("lms_courses").insert(t).select().single();if(r)throw r;return n},onSuccess:()=>s.invalidateQueries({queryKey:["lms-courses"]})})}function tHt(){const s=ts();return yt({mutationFn:async({id:t,...n})=>{const{data:r,error:a}=await U.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 hOn(){const s=ts();return yt({mutationFn:async t=>{const{error:n}=await U.from("lms_courses").delete().eq("id",t);if(n)throw n},onSuccess:()=>s.invalidateQueries({queryKey:["lms-courses"]})})}function mOn(){const s=ts();return yt({mutationFn:async t=>{const{data:n,error:r}=await U.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 pOn(){const s=ts();return yt({mutationFn:async({id:t,...n})=>{const{data:r,error:a}=await U.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 fOn(){const s=ts();return yt({mutationFn:async t=>{const{error:n}=await U.from("lms_modules").delete().eq("id",t);if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["lms-course"]}),s.invalidateQueries({queryKey:["lms-course-admin"]})}})}function xOn(){const s=ts();return yt({mutationFn:async t=>{const{data:n,error:r}=await U.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 gOn(){const s=ts();return yt({mutationFn:async t=>{const{error:n}=await U.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 yOn(){const s=ts();return yt({mutationFn:async({courseId:t,accessRules:n})=>{const{error:r}=await U.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 U.from("lms_course_access").insert(a);if(i)throw i}},onSuccess:()=>{s.invalidateQueries({queryKey:["lms-courses"]}),s.invalidateQueries({queryKey:["lms-course"]})}})}function vOn(){return ht({queryKey:["lms-courses-agent"],queryFn:async()=>{const{data:s,error:t}=await U.from("lms_courses").select("*, modules:lms_modules(id)").eq("is_published",!0).order("sort_order");if(t)throw t;return s}})}function bOn(s){return ht({queryKey:["lms-course-agent",s],queryFn:async()=>{if(!s)return null;const{data:t,error:n}=await U.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 sHt(s){return ht({queryKey:["lms-progress",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await U.from("lms_progress").select("*").eq("course_id",s);if(n)throw n;return t},enabled:!!s})}function _On(){const s=ts();return yt({mutationFn:async({courseId:t,moduleId:n,userId:r})=>{const{data:a,error:i}=await U.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 wOn(){const{user:s}=_s(),t=Vn(),{data:n,isLoading:r}=cOn(),a=uOn(),i=tHt(),l=hOn(),[o,c]=j.useState(!1),[d,u]=j.useState(""),[h,m]=j.useState(""),[p,x]=j.useState(!0),g=async()=>{if(!(!d.trim()||!s))try{const v=await a.mutateAsync({title:d.trim(),description:h.trim()||void 0,is_sequential:p,created_by:s.id});ae.success("Course created"),c(!1),u(""),m(""),x(!0),t(`/admin/lms/${v.id}`)}catch{ae.error("Failed to create course")}},y=async v=>{try{await i.mutateAsync({id:v.id,is_published:!v.is_published}),ae.success(v.is_published?"Course unpublished":"Course published")}catch{ae.error("Failed to update course")}},b=async v=>{if(await Yi("Delete this course and all its modules? This cannot be undone."))try{await l.mutateAsync(v),ae.success("Course deleted")}catch{ae.error("Failed to delete")}};return e.jsxs(Ks,{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(Ph,{className:"h-7 w-7 text-primary"}),"LevelUp U — Course Manager"]}),e.jsx("p",{className:"text-muted-foreground mt-1",children:"Create and manage training courses for your agents"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs($,{variant:"outline",onClick:()=>t("/admin/lms/stats"),children:[e.jsx(ml,{className:"h-4 w-4 mr-2"}),"Analytics"]}),e.jsxs($,{onClick:()=>c(!0),children:[e.jsx(sn,{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(v=>e.jsx(_e,{className:"animate-pulse",children:e.jsxs(Bt,{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"})]})},v))}):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(v=>{var T,P;const N=((P=(T=v.modules)==null?void 0:T[0])==null?void 0:P.count)??0,C=v.access||[],A=C.length===0?"No access set":C.some(M=>M.access_type==="all")?"All agents":`${C.length} rule(s)`;return e.jsxs(_e,{className:"group hover:shadow-md transition-all hover:border-primary/50 cursor-pointer",onClick:()=>t(`/admin/lms/${v.id}`),children:[e.jsx(Bt,{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(Ut,{className:"text-base truncate",children:v.title}),v.description&&e.jsx(vr,{className:"mt-1 line-clamp-2",children:v.description})]}),e.jsx($e,{variant:v.is_published?"default":"secondary",className:"ml-2 shrink-0",children:v.is_published?"Published":"Draft"})]})}),e.jsxs(Oe,{className:"pt-0",children:[e.jsxs("div",{className:"flex items-center gap-4 text-xs text-muted-foreground",children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(wf,{className:"h-3.5 w-3.5"}),N," module",N!==1?"s":""]}),e.jsxs("span",{className:"flex items-center gap-1",children:[v.is_sequential?e.jsx(qj,{className:"h-3.5 w-3.5"}):e.jsx(kR,{className:"h-3.5 w-3.5"}),v.is_sequential?"Sequential":"Free order"]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(qn,{className:"h-3.5 w-3.5"}),A]})]}),e.jsxs("div",{className:"flex items-center gap-2 mt-3 opacity-0 group-hover:opacity-100 transition-opacity",children:[e.jsxs($,{size:"sm",variant:"ghost",onClick:M=>{M.stopPropagation(),y(v)},children:[v.is_published?e.jsx(b0,{className:"h-3.5 w-3.5 mr-1"}):e.jsx(ga,{className:"h-3.5 w-3.5 mr-1"}),v.is_published?"Unpublish":"Publish"]}),e.jsx($,{size:"sm",variant:"ghost",className:"text-destructive",onClick:M=>{M.stopPropagation(),b(v.id)},children:e.jsx(Pn,{className:"h-3.5 w-3.5"})}),e.jsx("div",{className:"flex-1"}),e.jsx(ni,{className:"h-4 w-4 text-muted-foreground"})]})]})]},v.id)})}):e.jsx(_e,{className:"border-dashed",children:e.jsxs(Oe,{className:"flex flex-col items-center justify-center py-16 text-center",children:[e.jsx(wf,{className:"h-12 w-12 text-muted-foreground/50 mb-4"}),e.jsx("h3",{className:"text-lg font-semibold text-foreground mb-1",children:"No courses yet"}),e.jsx("p",{className:"text-muted-foreground text-sm mb-4",children:"Create your first training course to get started"}),e.jsxs($,{onClick:()=>c(!0),children:[e.jsx(sn,{className:"h-4 w-4 mr-2"}),"Create Course"]})]})})]}),e.jsx(Os,{open:o,onOpenChange:c,children:e.jsxs(Rs,{children:[e.jsxs(Us,{children:[e.jsx(zs,{children:"Create New Course"}),e.jsx(Sr,{children:"Set up a new training course for your agents"})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(se,{children:"Course Title"}),e.jsx(be,{value:d,onChange:v=>u(v.target.value),placeholder:"e.g. LevelUp Onboarding"})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Description"}),e.jsx(Is,{value:h,onChange:v=>m(v.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(Tn,{checked:p,onCheckedChange:x})]})]}),e.jsxs(kr,{children:[e.jsx($,{variant:"outline",onClick:()=>c(!1),children:"Cancel"}),e.jsx($,{onClick:g,disabled:!d.trim()||a.isPending,children:a.isPending?"Creating...":"Create Course"})]})]})})]})}function jOn(){const{courseId:s}=Vi(),t=Vn(),{data:n,isLoading:r}=dOn(s),a=tHt(),i=mOn(),l=pOn(),o=fOn(),c=xOn(),d=gOn(),u=yOn(),{data:h}=ht({queryKey:["all-brokerages"],queryFn:async()=>{const{data:et}=await U.from("brokerages").select("id, name").order("name");return et||[]}}),[m,p]=j.useState(null),[x,g]=j.useState(!1),[y,b]=j.useState({title:"",description:"",video_url:"",text_content:"",duration_minutes:""}),[v,N]=j.useState(null),[C,A]=j.useState({title:"",resource_type:"link",url:""}),[T,P]=j.useState(new Set),[M,I]=j.useState(null),[D,B]=j.useState(0),[q,W]=j.useState(!1),V=j.useRef(null),K=j.useRef(null),[Q,J]=j.useState(!1),[ce,ue]=j.useState(""),[ne,ee]=j.useState(""),[le,he]=j.useState(""),[ve,ge]=j.useState(!1);if(r)return e.jsx(Ks,{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(Ks,{title:"Course Not Found",children:e.jsxs("div",{className:"text-center py-20",children:[e.jsx("p",{className:"text-muted-foreground",children:"Course not found"}),e.jsxs($,{variant:"outline",className:"mt-4",onClick:()=>t("/admin/lms"),children:[e.jsx(ka,{className:"h-4 w-4 mr-2"})," Back to Courses"]})]})});const fe=n.modules||[],je=n.access||[],Ee=je.some(et=>et.access_type==="all"),Me=je.filter(et=>et.access_type==="brokerage").map(et=>et.brokerage_id),De=(h||[]).filter(et=>et.name.toLowerCase().includes(ce.toLowerCase())),ze=et=>{const Qe=new Set(T);Qe.has(et)?Qe.delete(et):Qe.add(et),P(Qe)},ke=async()=>{if(!M)return null;W(!0),B(0);try{const{data:et,error:Qe}=await U.functions.invoke("bunny-upload",{body:{action:"create",title:M.name}});if(Qe)throw new Error(Qe.message);const{videoId:Ge,libraryId:nt}=et,{data:ft,error:lt}=await U.functions.invoke("bunny-upload",{body:{action:"upload-url",videoId:Ge,libraryId:nt}});if(lt)throw new Error(lt.message);const Mt=new XMLHttpRequest;return await new Promise((Ft,Ts)=>{Mt.upload.onprogress=js=>{js.lengthComputable&&B(Math.round(js.loaded/js.total*100))},Mt.onload=()=>Mt.status>=200&&Mt.status<300?Ft():Ts(new Error(`Upload failed: ${Mt.status}`)),Mt.onerror=()=>Ts(new Error("Upload failed")),Mt.open("PUT",ft.uploadUrl),Mt.setRequestHeader("AccessKey",ft.apiKey),Mt.send(M)}),`https://iframe.mediadelivery.net/embed/${nt}/${Ge}`}catch(et){return console.error("Bunny upload error:",et),ae.error("Video upload failed"),null}finally{W(!1),B(0)}},Xe=async()=>{if(y.title.trim())try{let et=y.video_url.trim()||void 0;if(M){const Qe=await ke();if(!Qe)return;et=Qe}await i.mutateAsync({course_id:n.id,title:y.title.trim(),description:y.description.trim()||void 0,video_url:et,text_content:y.text_content.trim()||void 0,duration_minutes:y.duration_minutes?parseInt(y.duration_minutes):void 0,sort_order:fe.length}),ae.success("Module added"),g(!1),b({title:"",description:"",video_url:"",text_content:"",duration_minutes:""}),I(null)}catch{ae.error("Failed to add module")}},Se=async()=>{if(m)try{let et=y.video_url.trim()||null;if(M){const Qe=await ke();if(!Qe)return;et=Qe}await l.mutateAsync({id:m.id,title:y.title.trim(),description:y.description.trim()||null,video_url:et,text_content:y.text_content.trim()||null,duration_minutes:y.duration_minutes?parseInt(y.duration_minutes):null}),ae.success("Module updated"),p(null),I(null)}catch{ae.error("Failed to update")}},Re=async et=>{if(await Yi("Delete this module?"))try{await o.mutateAsync(et),ae.success("Module deleted")}catch{ae.error("Failed to delete")}},Ae=async et=>{if(C.title.trim())try{await c.mutateAsync({module_id:et,title:C.title.trim(),resource_type:C.resource_type,url:C.url.trim()||void 0}),ae.success("Resource added"),N(null),A({title:"",resource_type:"link",url:""})}catch{ae.error("Failed to add resource")}},Be=async()=>{try{await u.mutateAsync({courseId:n.id,accessRules:[{access_type:"all"}]}),ae.success("Access updated: All brokerages / all agents")}catch{ae.error("Failed to update access")}},qe=async et=>{const Qe=je.filter(lt=>lt.access_type==="brokerage").map(lt=>lt.brokerage_id),Ge=Qe.includes(et);let nt;Ge?nt=Qe.filter(lt=>lt!==et):nt=[...Qe,et];const ft=nt.map(lt=>({access_type:"brokerage",brokerage_id:lt}));try{await u.mutateAsync({courseId:n.id,accessRules:ft}),ae.success(Ge?"Brokerage removed":"Brokerage added")}catch{ae.error("Failed to update access")}},Ke=async()=>{try{await u.mutateAsync({courseId:n.id,accessRules:[]}),ae.success("Access cleared")}catch{ae.error("Failed")}},Ze=async(et,Qe)=>{const Ge=Qe==="up"?et-1:et+1;if(!(Ge<0||Ge>=fe.length))try{await Promise.all([l.mutateAsync({id:fe[et].id,sort_order:Ge}),l.mutateAsync({id:fe[Ge].id,sort_order:et})])}catch{ae.error("Failed to reorder")}},Ue=async()=>{try{await a.mutateAsync({id:n.id,title:ne,description:le||null}),ae.success("Course updated"),ge(!1)}catch{ae.error("Failed to update")}};return e.jsxs(Ks,{title:n.title,children:[e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-start justify-between gap-4",children:[e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx($,{variant:"ghost",size:"icon",onClick:()=>t("/admin/lms"),children:e.jsx(ka,{className:"h-5 w-5"})}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("h1",{className:"text-2xl font-bold text-foreground",children:n.title}),e.jsx($e,{variant:n.is_published?"default":"secondary",children:n.is_published?"Published":"Draft"})]}),n.description&&e.jsx("p",{className:"text-muted-foreground mt-1",children:n.description}),e.jsxs("div",{className:"flex items-center gap-3 mt-2 text-xs text-muted-foreground",children:[e.jsxs("span",{className:"flex items-center gap-1",children:[n.is_sequential?e.jsx(qj,{className:"h-3.5 w-3.5"}):e.jsx(kR,{className:"h-3.5 w-3.5"}),n.is_sequential?"Sequential":"Free order"]}),e.jsxs("span",{children:[fe.length," module",fe.length!==1?"s":""]})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs($,{variant:"outline",size:"sm",onClick:()=>{ee(n.title),he(n.description||""),ge(!0)},children:[e.jsx(Ya,{className:"h-3.5 w-3.5 mr-1"})," Edit"]}),e.jsxs($,{variant:n.is_published?"secondary":"default",size:"sm",onClick:()=>a.mutateAsync({id:n.id,is_published:!n.is_published}).then(()=>ae.success(n.is_published?"Unpublished":"Published")),children:[n.is_published?e.jsx(b0,{className:"h-3.5 w-3.5 mr-1"}):e.jsx(ga,{className:"h-3.5 w-3.5 mr-1"}),n.is_published?"Unpublish":"Publish"]})]})]}),e.jsxs(ua,{defaultValue:"modules",className:"w-full",children:[e.jsxs(ha,{children:[e.jsx(Qt,{value:"modules",children:"Modules"}),e.jsx(Qt,{value:"access",children:"Access & Permissions"}),e.jsx(Qt,{value:"settings",children:"Settings"})]}),e.jsxs(Jt,{value:"modules",className:"mt-6 space-y-4",children:[fe.map((et,Qe)=>e.jsxs(_e,{className:"overflow-hidden",children:[e.jsxs("div",{className:"flex items-center gap-3 p-4 cursor-pointer hover:bg-muted/50 transition-colors",onClick:()=>ze(et.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:Ge=>{Ge.stopPropagation(),Ze(Qe,"up")},disabled:Qe===0,className:"hover:text-foreground disabled:opacity-30",children:e.jsx(jg,{className:"h-3.5 w-3.5"})}),e.jsx("button",{onClick:Ge=>{Ge.stopPropagation(),Ze(Qe,"down")},disabled:Qe===fe.length-1,className:"hover:text-foreground disabled:opacity-30",children:e.jsx(_o,{className:"h-3.5 w-3.5"})})]})}),e.jsx($e,{variant:"outline",className:"shrink-0 font-mono text-xs",children:Qe+1}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"font-medium text-sm truncate",children:et.title}),e.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground mt-0.5",children:[et.video_url&&e.jsxs("span",{className:"flex items-center gap-0.5",children:[e.jsx(Xr,{className:"h-3 w-3"})," Video"]}),et.text_content&&e.jsxs("span",{className:"flex items-center gap-0.5",children:[e.jsx(Wr,{className:"h-3 w-3"})," Text"]}),et.duration_minutes&&e.jsxs("span",{children:[et.duration_minutes," min"]}),et.resources&&et.resources.length>0&&e.jsxs("span",{className:"flex items-center gap-0.5",children:[e.jsx(Dc,{className:"h-3 w-3"})," ",et.resources.length," resource(s)"]})]})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx($,{size:"sm",variant:"ghost",onClick:Ge=>{var nt;Ge.stopPropagation(),p(et),b({title:et.title,description:et.description||"",video_url:et.video_url||"",text_content:et.text_content||"",duration_minutes:((nt=et.duration_minutes)==null?void 0:nt.toString())||""})},children:e.jsx(Ya,{className:"h-3.5 w-3.5"})}),e.jsx($,{size:"sm",variant:"ghost",className:"text-destructive",onClick:Ge=>{Ge.stopPropagation(),Re(et.id)},children:e.jsx(Pn,{className:"h-3.5 w-3.5"})})]})]}),T.has(et.id)&&e.jsxs("div",{className:"border-t bg-muted/30 p-4 space-y-3",children:[et.description&&e.jsx("p",{className:"text-sm text-muted-foreground",children:et.description}),et.video_url&&e.jsxs("div",{className:"text-xs",children:[e.jsx("span",{className:"text-muted-foreground",children:"Video: "}),e.jsx("a",{href:et.video_url,target:"_blank",rel:"noreferrer",className:"text-primary hover:underline break-all",children:et.video_url})]}),et.text_content&&e.jsx("div",{className:"text-sm bg-background rounded-md p-3 border max-h-40 overflow-auto whitespace-pre-wrap",children:et.text_content}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx("p",{className:"text-xs font-medium text-muted-foreground uppercase tracking-wide",children:"Resources"}),e.jsxs($,{size:"sm",variant:"outline",className:"h-7 text-xs",onClick:()=>{N(et.id),A({title:"",resource_type:"link",url:""})},children:[e.jsx(sn,{className:"h-3 w-3 mr-1"})," Add Resource"]})]}),et.resources&&et.resources.length>0?e.jsx("div",{className:"space-y-1",children:et.resources.map(Ge=>e.jsxs("div",{className:"flex items-center gap-2 text-sm bg-background rounded p-2 border",children:[e.jsx($e,{variant:"outline",className:"text-[10px]",children:Ge.resource_type}),e.jsx("span",{className:"flex-1 truncate",children:Ge.title}),Ge.url&&e.jsx("a",{href:Ge.url,target:"_blank",rel:"noreferrer",className:"text-primary hover:underline text-xs",children:"Open"}),e.jsx($,{size:"sm",variant:"ghost",className:"h-6 w-6 p-0 text-destructive",onClick:()=>d.mutateAsync(Ge.id),children:e.jsx(pr,{className:"h-3 w-3"})})]},Ge.id))}):e.jsx("p",{className:"text-xs text-muted-foreground",children:"No resources yet"})]})]})]},et.id)),e.jsxs($,{variant:"outline",className:"w-full border-dashed",onClick:()=>{g(!0),b({title:"",description:"",video_url:"",text_content:"",duration_minutes:""})},children:[e.jsx(sn,{className:"h-4 w-4 mr-2"})," Add Module"]})]}),e.jsx(Jt,{value:"access",className:"mt-6 space-y-4",children:e.jsxs(_e,{children:[e.jsx(Bt,{children:e.jsx(Ut,{className:"text-base",children:"Who can access this course?"})}),e.jsxs(Oe,{className:"space-y-5",children:[e.jsxs("div",{className:Tt("flex items-center gap-3 p-4 rounded-xl border-2 cursor-pointer transition-all",Ee?"border-primary bg-primary/5":"border-muted hover:border-muted-foreground/30"),onClick:Be,children:[e.jsx("div",{className:Tt("h-10 w-10 rounded-full flex items-center justify-center shrink-0",Ee?"bg-primary/15 text-primary":"bg-muted text-muted-foreground"),children:e.jsx(Gl,{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(Tn,{checked:Ee,onCheckedChange:Be})]}),!Ee&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-semibold",children:"Select Brokerages"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:Me.length===0?"No brokerages selected — agents won't see this course":`${Me.length} brokerage${Me.length!==1?"s":""} selected`})]}),Me.length>0&&e.jsx($,{size:"sm",variant:"ghost",className:"text-xs text-muted-foreground",onClick:Ke,children:"Clear all"})]}),e.jsx(be,{placeholder:"Search brokerages...",value:ce,onChange:et=>ue(et.target.value),className:"h-9"}),e.jsx("div",{className:"border rounded-lg divide-y max-h-[360px] overflow-auto",children:De.length===0?e.jsx("div",{className:"p-4 text-center text-sm text-muted-foreground",children:"No brokerages found"}):De.map(et=>{const Qe=Me.includes(et.id);return e.jsxs("div",{className:Tt("flex items-center gap-3 px-3 py-2.5 cursor-pointer transition-colors",Qe?"bg-primary/5":"hover:bg-muted/50"),onClick:()=>qe(et.id),children:[e.jsx("div",{className:Tt("h-5 w-5 rounded border-2 flex items-center justify-center shrink-0 transition-colors",Qe?"bg-primary border-primary":"border-muted-foreground/30"),children:Qe&&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(Ai,{className:"h-4 w-4 text-muted-foreground shrink-0"}),e.jsx("span",{className:"text-sm flex-1 truncate",children:et.name}),Qe&&e.jsx($e,{variant:"secondary",className:"text-[10px] shrink-0",children:"Active"})]},et.id)})})]})]})]})}),e.jsxs(Jt,{value:"settings",className:"mt-6 space-y-4",children:[e.jsxs(_e,{children:[e.jsx(Bt,{children:e.jsx(Ut,{className:"text-base",children:"Course Thumbnail"})}),e.jsx(Oe,{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(()=>ae.success("Thumbnail removed")),className:"absolute -top-2 -right-2 bg-destructive text-destructive-foreground rounded-full p-1 opacity-0 group-hover:opacity-100 transition-opacity",children:e.jsx(pr,{className:"h-3 w-3"})})]}):e.jsxs("div",{className:"w-48 h-28 rounded-lg border-2 border-dashed border-muted-foreground/25 flex flex-col items-center justify-center text-muted-foreground",children:[e.jsx(x1,{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 et=>{var Ge;const Qe=(Ge=et.target.files)==null?void 0:Ge[0];if(!(!Qe||!n)){J(!0);try{const nt=Qe.name.split(".").pop(),ft=`${n.id}/thumbnail.${nt}`,{error:lt}=await U.storage.from("lms-thumbnails").upload(ft,Qe,{upsert:!0});if(lt)throw lt;const{data:Mt}=U.storage.from("lms-thumbnails").getPublicUrl(ft),Ft=`${Mt.publicUrl}?t=${Date.now()}`;await a.mutateAsync({id:n.id,thumbnail_url:Ft}),ae.success("Thumbnail uploaded")}catch{ae.error("Failed to upload thumbnail")}finally{J(!1),K.current&&(K.current.value="")}}}}),e.jsxs($,{variant:"outline",size:"sm",disabled:Q,onClick:()=>{var et;return(et=K.current)==null?void 0:et.click()},children:[Q?e.jsx(Ht,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(si,{className:"h-4 w-4 mr-2"}),Q?"Uploading...":"Upload Thumbnail"]})]})]})})]}),e.jsxs(_e,{children:[e.jsx(Bt,{children:e.jsx(Ut,{className:"text-base",children:"Course Settings"})}),e.jsxs(Oe,{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between rounded-lg border p-4",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium",children:"Sequential Learning"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Agents must complete modules in order before advancing"})]}),e.jsx(Tn,{checked:n.is_sequential,onCheckedChange:et=>a.mutateAsync({id:n.id,is_sequential:et}).then(()=>ae.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(Tn,{checked:n.is_published,onCheckedChange:et=>a.mutateAsync({id:n.id,is_published:et}).then(()=>ae.success("Updated"))})]})]})]})]})]})]}),e.jsx(Os,{open:x||!!m,onOpenChange:et=>{et||(g(!1),p(null))},children:e.jsxs(Rs,{className:"max-w-lg",children:[e.jsxs(Us,{children:[e.jsx(zs,{children:m?"Edit Module":"Add Module"}),e.jsx(Sr,{children:"Configure the module content"})]}),e.jsxs("div",{className:"space-y-4 max-h-[60vh] overflow-auto",children:[e.jsxs("div",{children:[e.jsx(se,{children:"Title"}),e.jsx(be,{value:y.title,onChange:et=>b(Qe=>({...Qe,title:et.target.value})),placeholder:"Module title"})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Description"}),e.jsx(Is,{value:y.description,onChange:et=>b(Qe=>({...Qe,description:et.target.value})),placeholder:"Brief description",rows:2})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Video"}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:Tt("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 et;return(et=V.current)==null?void 0:et.click()},children:[e.jsx("input",{ref:V,type:"file",accept:"video/*",className:"hidden",onChange:et=>{var Ge;const Qe=(Ge=et.target.files)==null?void 0:Ge[0];Qe&&(I(Qe),b(nt=>({...nt,video_url:""})))}}),M?e.jsxs("div",{className:"flex items-center justify-center gap-2 text-sm",children:[e.jsx(Xr,{className:"h-4 w-4 text-primary"}),e.jsx("span",{className:"font-medium text-primary",children:M.name}),e.jsx($,{type:"button",size:"sm",variant:"ghost",className:"h-6 w-6 p-0",onClick:et=>{et.stopPropagation(),I(null)},children:e.jsx(pr,{className:"h-3 w-3"})})]}):e.jsxs("div",{className:"flex flex-col items-center gap-1 text-muted-foreground",children:[e.jsx(si,{className:"h-5 w-5"}),e.jsx("span",{className:"text-xs",children:"Click to upload a video file"})]})]}),q&&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(Ht,{className:"h-3.5 w-3.5 animate-spin"}),e.jsxs("span",{children:["Uploading to Bunny.net... ",D,"%"]})]}),e.jsx(Ki,{value:D,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(be,{value:y.video_url,onChange:et=>b(Qe=>({...Qe,video_url:et.target.value})),placeholder:"YouTube, Vimeo, or Bunny.net URL"})]})]})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Text Content"}),e.jsx(Is,{value:y.text_content,onChange:et=>b(Qe=>({...Qe,text_content:et.target.value})),placeholder:"Additional text content, instructions, notes...",rows:4})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Duration (minutes)"}),e.jsx(be,{type:"number",value:y.duration_minutes,onChange:et=>b(Qe=>({...Qe,duration_minutes:et.target.value})),placeholder:"e.g. 15"})]})]}),e.jsxs(kr,{children:[e.jsx($,{variant:"outline",onClick:()=>{g(!1),p(null),I(null)},children:"Cancel"}),e.jsxs($,{onClick:m?Se:Xe,disabled:!y.title.trim()||q,children:[q?e.jsx(Ht,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(Jo,{className:"h-4 w-4 mr-2"}),q?"Uploading...":m?"Save Changes":"Add Module"]})]})]})}),e.jsx(Os,{open:!!v,onOpenChange:et=>{et||N(null)},children:e.jsxs(Rs,{children:[e.jsxs(Us,{children:[e.jsx(zs,{children:"Add Resource"}),e.jsx(Sr,{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(se,{children:"Title"}),e.jsx(be,{value:C.title,onChange:et=>A(Qe=>({...Qe,title:et.target.value})),placeholder:"Resource title"})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Type"}),e.jsxs(vs,{value:C.resource_type,onValueChange:et=>A(Qe=>({...Qe,resource_type:et})),children:[e.jsx(gs,{children:e.jsx(bs,{})}),e.jsxs(ys,{children:[e.jsx(Ye,{value:"link",children:"Link"}),e.jsx(Ye,{value:"pdf",children:"PDF"}),e.jsx(Ye,{value:"template",children:"Template"}),e.jsx(Ye,{value:"worksheet",children:"Worksheet"})]})]})]}),e.jsxs("div",{children:[e.jsx(se,{children:"URL"}),e.jsx(be,{value:C.url,onChange:et=>A(Qe=>({...Qe,url:et.target.value})),placeholder:"https://..."})]})]}),e.jsxs(kr,{children:[e.jsx($,{variant:"outline",onClick:()=>N(null),children:"Cancel"}),e.jsx($,{onClick:()=>v&&Ae(v),disabled:!C.title.trim(),children:"Add Resource"})]})]})}),e.jsx(Os,{open:ve,onOpenChange:ge,children:e.jsxs(Rs,{children:[e.jsxs(Us,{children:[e.jsx(zs,{children:"Edit Course"}),e.jsx(Sr,{children:"Update the course title and description"})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(se,{children:"Title"}),e.jsx(be,{value:ne,onChange:et=>ee(et.target.value)})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Description"}),e.jsx(Is,{value:le,onChange:et=>he(et.target.value),rows:3})]})]}),e.jsxs(kr,{children:[e.jsx($,{variant:"outline",onClick:()=>ge(!1),children:"Cancel"}),e.jsx($,{onClick:Ue,disabled:!ne.trim(),children:"Save"})]})]})})]})}function NOn(){return ht({queryKey:["lms-stats-overview"],queryFn:async()=>{const{data:s,error:t}=await U.rpc("get_lms_stats");if(t)throw t;return s}})}function kOn(){return ht({queryKey:["lms-stats-courses"],queryFn:async()=>{const{data:s,error:t}=await U.rpc("get_lms_course_stats");if(t)throw t;return s||[]}})}function SOn(s){return ht({queryKey:["lms-stats-agents",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await U.rpc("get_lms_agent_progress",{p_course_id:s});if(n)throw n;return t||[]},enabled:!!s})}function COn(){const s=Vn(),{data:t,isLoading:n}=NOn(),{data:r,isLoading:a}=kOn(),[i,l]=j.useState(null),{data:o,isLoading:c}=SOn(i),[d,u]=j.useState(""),h=r==null?void 0:r.find(x=>x.course_id===i),m=o==null?void 0:o.filter(x=>{var g,y;return!d||((g=x.agent_name)==null?void 0:g.toLowerCase().includes(d.toLowerCase()))||((y=x.email)==null?void 0:y.toLowerCase().includes(d.toLowerCase()))}),p=[{label:"Total Courses",value:(t==null?void 0:t.total_courses)??0,icon:wf,color:"text-primary"},{label:"Published",value:(t==null?void 0:t.published_courses)??0,icon:Fr,color:"text-emerald-500"},{label:"Enrolled Agents",value:(t==null?void 0:t.total_enrollments)??0,icon:qn,color:"text-blue-500"},{label:"Modules Completed",value:(t==null?void 0:t.total_completions)??0,icon:pl,color:"text-amber-500"},{label:"Active (30d)",value:(t==null?void 0:t.active_learners)??0,icon:Il,color:"text-violet-500"},{label:"Total Modules",value:(t==null?void 0:t.total_modules)??0,icon:ml,color:"text-rose-500"}];return e.jsx(Ks,{title:"LevelUp U - Stats",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx($,{variant:"ghost",size:"icon",onClick:()=>s("/admin/lms"),children:e.jsx(ka,{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(Ph,{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(x=>e.jsx(_e,{className:Tt("transition-all",n&&"animate-pulse"),children:e.jsxs(Oe,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx(x.icon,{className:Tt("h-4 w-4",x.color)}),e.jsx("span",{className:"text-xs font-medium text-muted-foreground",children:x.label})]}),e.jsx("p",{className:"text-2xl font-bold text-foreground",children:n?"—":x.value})]})},x.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(ml,{className:"h-5 w-5 text-primary"}),"Course Breakdown"]}),a?e.jsx("div",{className:"space-y-3",children:[1,2,3].map(x=>e.jsx(_e,{className:"animate-pulse",children:e.jsx(Oe,{className:"p-4",children:e.jsx("div",{className:"h-16 bg-muted rounded"})})},x))}):r!=null&&r.length?e.jsx("div",{className:"space-y-2",children:r.map(x=>{const g=i===x.course_id;return e.jsx(_e,{className:Tt("cursor-pointer transition-all hover:shadow-md",g?"border-primary ring-1 ring-primary/30 shadow-md":"hover:border-primary/40"),onClick:()=>l(g?null:x.course_id),children:e.jsxs(Oe,{className:"p-4",children:[e.jsxs("div",{className:"flex items-start justify-between mb-3",children:[e.jsx("div",{className:"flex-1 min-w-0",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("p",{className:"font-semibold text-sm text-foreground truncate",children:x.course_title}),e.jsx($e,{variant:x.is_published?"default":"secondary",className:"shrink-0 text-[10px] px-1.5 py-0",children:x.is_published?"Live":"Draft"})]})}),e.jsx(Ja,{className:Tt("h-4 w-4 text-muted-foreground transition-transform shrink-0 ml-2",g&&"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:x.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:x.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:x.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:[x.avg_completion_pct,"%"]})]}),e.jsx(Ki,{value:x.avg_completion_pct,className:"h-2"})]})]})},x.course_id)})}):e.jsx(_e,{className:"border-dashed",children:e.jsx(Oe,{className:"py-10 text-center",children:e.jsx("p",{className:"text-muted-foreground text-sm",children:"No courses created yet"})})})]}),e.jsxs("div",{className:"xl:col-span-3 space-y-3",children:[e.jsxs("h2",{className:"text-lg font-semibold text-foreground flex items-center gap-2",children:[e.jsx(Yj,{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(Vr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(be,{value:d,onChange:x=>u(x.target.value),placeholder:"Search agents...",className:"pl-9"})]}),c?e.jsx("div",{className:"space-y-2",children:[1,2,3,4].map(x=>e.jsx(_e,{className:"animate-pulse",children:e.jsx(Oe,{className:"p-4",children:e.jsx("div",{className:"h-12 bg-muted rounded"})})},x))}):m!=null&&m.length?e.jsx("div",{className:"space-y-2 max-h-[600px] overflow-y-auto pr-1",children:m.map((x,g)=>{const y=x.completion_pct>=100;return e.jsx(_e,{className:Tt("transition-all",y&&"border-emerald-200 bg-emerald-50/30 dark:border-emerald-900/40 dark:bg-emerald-950/10"),children:e.jsx(Oe,{className:"p-4",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:Tt("flex items-center justify-center w-7 h-7 rounded-full text-xs font-bold shrink-0",g===0?"bg-amber-100 text-amber-700 dark:bg-amber-900/30 dark:text-amber-400":g===1?"bg-slate-100 text-slate-600 dark:bg-slate-800 dark:text-slate-400":g===2?"bg-orange-100 text-orange-700 dark:bg-orange-900/30 dark:text-orange-400":"bg-muted text-muted-foreground"),children:g+1}),e.jsxs(Ea,{className:"h-9 w-9 shrink-0",children:[e.jsx(ki,{src:x.avatar_url||void 0}),e.jsx(Ta,{className:"text-xs bg-primary/10 text-primary",children:(x.agent_name||x.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:x.agent_name||x.email}),y&&e.jsxs($e,{variant:"default",className:"text-[10px] px-1.5 py-0 bg-emerald-500 hover:bg-emerald-600 shrink-0",children:[e.jsx(Fr,{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:[x.modules_completed,"/",x.total_modules," modules"]}),x.last_activity&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Hr,{className:"h-3 w-3"}),Hs(new Date(x.last_activity),"MMM d, yyyy")]})]})]}),e.jsxs("div",{className:"text-right shrink-0 w-20",children:[e.jsxs("p",{className:Tt("text-sm font-bold",y?"text-emerald-600 dark:text-emerald-400":"text-foreground"),children:[x.completion_pct,"%"]}),e.jsx(Ki,{value:x.completion_pct,className:"h-1.5 mt-1"})]})]})})},x.user_id)})}):e.jsx(_e,{className:"border-dashed",children:e.jsx(Oe,{className:"py-10 text-center",children:e.jsx("p",{className:"text-muted-foreground text-sm",children:d?"No agents match your search":"No agents have started this course yet"})})})]}):e.jsx(_e,{className:"border-dashed",children:e.jsxs(Oe,{className:"py-16 text-center",children:[e.jsx(qn,{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 AOn(){const{user:s}=_s(),t=Vn(),{data:n,isLoading:r}=vOn();return e.jsx(Ks,{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(Ph,{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(_e,{className:"animate-pulse",children:e.jsxs(Oe,{className:"p-6",children:[e.jsx("div",{className:"h-5 bg-muted rounded w-2/3"}),e.jsx("div",{className:"h-3 bg-muted rounded w-1/2 mt-3"})]})},a))}):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(EOn,{course:a,userId:s==null?void 0:s.id,onClick:()=>t(`/levelup-u/${a.id}`)},a.id))}):e.jsx(_e,{className:"border-dashed",children:e.jsxs(Oe,{className:"flex flex-col items-center justify-center py-16 text-center",children:[e.jsx(wf,{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 EOn({course:s,userId:t,onClick:n}){var o;const r=((o=s.modules)==null?void 0:o.length)??0,{data:a}=sHt(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(_e,{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(Ph,{className:"h-10 w-10 text-primary/40"})}),e.jsxs(Oe,{className:"p-4 space-y-3",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"font-semibold text-foreground group-hover:text-primary transition-colors line-clamp-1",children:s.title}),s.description&&e.jsx("p",{className:"text-sm text-muted-foreground mt-1 line-clamp-2",children:s.description})]}),e.jsxs("div",{className:"flex items-center gap-3 text-xs text-muted-foreground",children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(wf,{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(qj,{className:"h-3.5 w-3.5"}):e.jsx(kR,{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(Ki,{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(Ja,{className:"h-3.5 w-3.5"})]})})]})]})}function TOn(){const{courseId:s}=Vi(),t=Vn(),{user:n}=_s(),{data:r,isLoading:a}=bOn(s),{data:i}=sHt(s),l=_On(),[o,c]=j.useState(null),d=(r==null?void 0:r.modules)||[],u=new Set((i==null?void 0:i.filter(v=>v.completed).map(v=>v.module_id))||[]),h=u.size,m=d.length>0?Math.round(h/d.length*100):0;j.useEffect(()=>{if(d.length>0&&!o){const v=d.find(N=>!u.has(N.id));c((v==null?void 0:v.id)||d[0].id)}},[d,o,u]);const p=d.find(v=>v.id===o),x=d.findIndex(v=>v.id===o),g=(v,N)=>{if(!(r!=null&&r.is_sequential)||N===0)return!1;for(let C=0;C{if(!(!p||!n||!s))try{await l.mutateAsync({courseId:s,moduleId:p.id,userId:n.id}),ae.success("Module completed! 🎉"),x{const N=v.match(/(?:youtube\.com\/(?:watch\?v=|embed\/)|youtu\.be\/)([a-zA-Z0-9_-]{11})/);if(N)return`https://www.youtube.com/embed/${N[1]}`;const C=v.match(/vimeo\.com\/(\d+)/);if(C)return`https://player.vimeo.com/video/${C[1]}`;const A=v.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`:v};return a?e.jsx(Ks,{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(Ks,{title:r.title,children:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx($,{variant:"ghost",size:"icon",onClick:()=>t("/levelup-u"),children:e.jsx(ka,{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(Ki,{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(_e,{className:"lg:sticky lg:top-4",children:e.jsxs(Oe,{className:"p-0",children:[e.jsx("div",{className:"p-3 border-b",children:e.jsx("p",{className:"text-xs font-medium text-muted-foreground uppercase tracking-wide",children:"Modules"})}),e.jsx(Oi,{className:"max-h-[calc(100vh-280px)]",children:e.jsx("div",{className:"p-1",children:d.map((v,N)=>{const C=g(v,N),A=u.has(v.id),T=v.id===o;return e.jsxs("button",{disabled:C,onClick:()=>!C&&c(v.id),className:Tt("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",C&&"opacity-50 cursor-not-allowed"),children:[e.jsx("div",{className:"shrink-0",children:C?e.jsx(Ad,{className:"h-4 w-4 text-muted-foreground"}):A?e.jsx(Fr,{className:"h-4 w-4 text-green-500"}):e.jsx(Bp,{className:"h-4 w-4 text-muted-foreground"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("p",{className:Tt("font-medium truncate",T&&"text-primary"),children:[N+1,". ",v.title]}),v.duration_minutes&&e.jsxs("span",{className:"text-[11px] text-muted-foreground flex items-center gap-0.5 mt-0.5",children:[e.jsx(Hr,{className:"h-3 w-3"})," ",v.duration_minutes," min"]})]})]},v.id)})})})]})}),e.jsx("div",{className:"space-y-4",children:p?e.jsxs(e.Fragment,{children:[p.video_url&&e.jsx(_e,{className:"overflow-hidden",children:e.jsx("div",{className:"aspect-video bg-black",children:e.jsx("iframe",{src:b(p.video_url),className:"w-full h-full",allow:"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture",allowFullScreen:!0})})}),e.jsx(_e,{children:e.jsxs(Oe,{className:"p-6 space-y-4",children:[e.jsxs("div",{className:"flex items-start justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-lg font-semibold",children:p.title}),p.description&&e.jsx("p",{className:"text-muted-foreground mt-1",children:p.description})]}),u.has(p.id)?e.jsxs($e,{className:"bg-green-500/15 text-green-600 border-green-500/30 shrink-0",children:[e.jsx(Fr,{className:"h-3.5 w-3.5 mr-1"})," Completed"]}):e.jsxs($,{size:"sm",onClick:y,disabled:l.isPending,children:[e.jsx(Fr,{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(v=>e.jsxs("a",{href:v.url||v.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:[v.resource_type==="pdf"?e.jsx(Wr,{className:"h-4 w-4 text-red-500 shrink-0"}):v.resource_type==="template"?e.jsx(Ph,{className:"h-4 w-4 text-purple-500 shrink-0"}):e.jsx(Dc,{className:"h-4 w-4 text-blue-500 shrink-0"}),e.jsx("span",{className:"flex-1 truncate",children:v.title}),e.jsx(Tr,{className:"h-3.5 w-3.5 text-muted-foreground shrink-0"})]},v.id))})]}),e.jsxs("div",{className:"flex items-center justify-between border-t pt-4",children:[e.jsxs($,{variant:"outline",size:"sm",disabled:x===0,onClick:()=>x>0&&c(d[x-1].id),children:[e.jsx(ka,{className:"h-3.5 w-3.5 mr-1"})," Previous"]}),xc(d[x+1].id),children:["Next ",e.jsx(Ja,{className:"h-3.5 w-3.5 ml-1"})]}):m===100&&e.jsx($e,{className:"bg-green-500/15 text-green-600 border-green-500/30 text-sm px-3 py-1.5",children:"🎉 Course Complete!"})]})]})})]}):e.jsx(_e,{children:e.jsx(Oe,{className:"flex items-center justify-center py-16 text-muted-foreground",children:"Select a module to begin"})})})]})]})}):e.jsx(Ks,{title:"Not Found",children:e.jsxs("div",{className:"text-center py-20",children:[e.jsx("p",{className:"text-muted-foreground",children:"Course not found"}),e.jsxs($,{variant:"outline",className:"mt-4",onClick:()=>t("/levelup-u"),children:[e.jsx(ka,{className:"h-4 w-4 mr-2"})," Back"]})]})})}function MOn({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(jr.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(jr.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(jr.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(jr.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(jr.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(ni,{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(jr.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 _w({children:s,className:t="",delay:n=0,direction:r="up"}){const a=j.useRef(null),i=BSs(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(jr.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 LOn({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(_w,{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(_w,{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 POn({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(_w,{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(qn,{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(_w,{delay:l*.08,children:e.jsxs("button",{onClick:()=>a(l),className:"relative w-full aspect-[4/3] overflow-hidden rounded-xl group cursor-pointer",children:[e.jsx("img",{src:i,alt:`Team ${l+1}`,className:"w-full h-full object-cover transition-transform duration-700 group-hover:scale-110"}),e.jsx("div",{className:"absolute inset-0 bg-black/0 group-hover:bg-black/20 transition-all duration-500"})]})},l))})]})}),r!==null&&e.jsxs("div",{className:"fixed inset-0 z-50 bg-black/90 flex items-center justify-center p-4 cursor-pointer",onClick:()=>a(null),children:[e.jsx("button",{onClick:()=>a(null),className:"absolute top-6 right-6 text-white/80 hover:text-white transition-colors",children:e.jsx(pr,{className:"h-8 w-8"})}),e.jsx("img",{src:s[r],alt:"Gallery",className:"max-w-full max-h-[85vh] object-contain rounded-lg",onClick:i=>i.stopPropagation()})]})]})}function IOn({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(_w,{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(_w,{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(RN,{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 DOn({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(_w,{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(_w,{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(se,{className:"text-gray-700 text-sm font-medium",children:"First Name *"}),e.jsx(be,{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(se,{className:"text-gray-700 text-sm font-medium",children:"Last Name"}),e.jsx(be,{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(se,{className:"text-gray-700 text-sm font-medium",children:"Email *"}),e.jsx(be,{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(se,{className:"text-gray-700 text-sm font-medium",children:"Phone"}),e.jsx(be,{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(se,{className:"text-gray-700 text-sm font-medium",children:"Current Brokerage"}),e.jsx(be,{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(se,{className:"text-gray-700 text-sm font-medium",children:"License #"}),e.jsx(be,{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(se,{className:"text-gray-700 text-sm font-medium",children:"Years Experience"}),e.jsx(be,{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(se,{className:"text-gray-700 text-sm font-medium",children:"Annual Production"}),e.jsx(be,{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(se,{className:"text-gray-700 text-sm font-medium",children:"Why are you interested?"}),e.jsx(Is,{value:s.why_interested,onChange:l=>t(o=>({...o,why_interested:l.target.value})),rows:3,className:"rounded-lg border-gray-200 focus:border-gray-400 transition-colors resize-none",placeholder:"Tell us about your goals and what you're looking for..."})]}),e.jsx($,{type:"submit",className:"w-full h-13 text-base font-semibold rounded-xl group transition-all duration-300 hover:shadow-lg",style:{background:`linear-gradient(135deg, ${a}, ${i})`},disabled:r,children:r?e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"h-4 w-4 animate-spin rounded-full border-2 border-white border-t-transparent"}),"Submitting..."]}):e.jsxs("span",{className:"flex items-center gap-2",children:["Send My Info",e.jsx(ni,{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(kf,{className:"h-3.5 w-3.5"}),e.jsx("span",{children:"Your information is confidential and will not be shared."})]})]})})]})]})}function ROn({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=x=>{u(x),t(g=>({...g,why_interested:x})),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(_w,{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(Ad,{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(_w,{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(x=>e.jsx("div",{className:"h-1 flex-1 rounded-full transition-colors duration-500",style:{backgroundColor:x<=o?a:"#e5e7eb"}},x)),e.jsxs("span",{className:"text-xs text-gray-400 ml-2",children:[o,"/",h]})]}),e.jsxs(Lq,{mode:"wait",children:[o===1&&e.jsxs(jr.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(x=>e.jsxs("button",{type:"button",onClick:()=>p(x.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:x.icon}),e.jsx("span",{className:"font-medium text-gray-700 group-hover:text-gray-900 flex-1",children:x.label}),e.jsx(ni,{className:"h-4 w-4 text-gray-300 group-hover:text-gray-500 group-hover:translate-x-1 transition-all"})]},x.val))]},"step1"),o===2&&e.jsxs(jr.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(se,{className:"text-gray-700 text-sm font-medium",children:"First Name *"}),e.jsx(be,{required:!0,value:s.first_name,onChange:x=>t(g=>({...g,first_name:x.target.value})),className:"h-11",placeholder:"John"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{className:"text-gray-700 text-sm font-medium",children:"Last Name"}),e.jsx(be,{value:s.last_name,onChange:x=>t(g=>({...g,last_name:x.target.value})),className:"h-11",placeholder:"Smith"})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{className:"text-gray-700 text-sm font-medium",children:"Email *"}),e.jsx(be,{type:"email",required:!0,value:s.email,onChange:x=>t(g=>({...g,email:x.target.value})),className:"h-11",placeholder:"john@email.com"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{className:"text-gray-700 text-sm font-medium",children:"Phone (preferred)"}),e.jsx(be,{value:s.phone,onChange:x=>t(g=>({...g,phone:x.target.value})),className:"h-11",placeholder:"(555) 123-4567"})]}),e.jsxs("div",{className:"flex gap-2 pt-2",children:[e.jsxs($,{type:"button",variant:"ghost",onClick:()=>c(1),className:"h-11",children:[e.jsx(ka,{className:"h-4 w-4 mr-1"})," Back"]}),e.jsxs($,{type:"button",disabled:!m,onClick:()=>c(3),className:"flex-1 h-11 text-white font-semibold",style:{background:`linear-gradient(135deg, ${a}, ${i})`},children:["Continue ",e.jsx(ni,{className:"h-4 w-4 ml-1"})]})]})]},"step2"),o===3&&e.jsxs(jr.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(se,{className:"text-gray-700 text-sm font-medium",children:"Current Brokerage"}),e.jsx(be,{value:s.current_brokerage,onChange:x=>t(g=>({...g,current_brokerage:x.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(se,{className:"text-gray-700 text-sm font-medium",children:"Years Experience"}),e.jsx(be,{type:"number",min:"0",value:s.experience_years,onChange:x=>t(g=>({...g,experience_years:x.target.value})),className:"h-11"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{className:"text-gray-700 text-sm font-medium",children:"Annual Production"}),e.jsx(be,{value:s.annual_production,onChange:x=>t(g=>({...g,annual_production:x.target.value})),className:"h-11",placeholder:"e.g. $5M"})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{className:"text-gray-700 text-sm font-medium",children:"Anything else?"}),e.jsx(Is,{value:s.why_interested,onChange:x=>t(g=>({...g,why_interested:x.target.value})),rows:2,className:"resize-none",placeholder:"Optional message..."})]}),e.jsxs("div",{className:"flex gap-2 pt-2",children:[e.jsxs($,{type:"button",variant:"ghost",onClick:()=>c(2),className:"h-11",children:[e.jsx(ka,{className:"h-4 w-4 mr-1"})," Back"]}),e.jsx($,{type:"button",onClick:n,disabled:r,className:"flex-1 h-12 text-white font-semibold rounded-xl",style:{background:`linear-gradient(135deg, ${a}, ${i})`},children:r?e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"h-4 w-4 animate-spin rounded-full border-2 border-white border-t-transparent"}),"Sending..."]}):e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(oa,{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(kf,{className:"h-3 w-3"})," Confidential"]}),e.jsxs("div",{className:"flex items-center gap-1 justify-center",children:[e.jsx(Ji,{className:"h-3 w-3"})," Text first"]}),e.jsxs("div",{className:"flex items-center gap-1 justify-center",children:[e.jsx(ya,{className:"h-3 w-3"})," No spam"]})]})]})})]})]})}function OOn({config:s,primaryColor:t,accentColor:n,brokerageId:r,brokerageName:a}){const{toast:i}=gi(),[l,o]=j.useState("250000"),[c,d]=j.useState("12"),[u,h]=j.useState("70"),[m,p]=j.useState("150"),[x,g]=j.useState(""),[y,b]=j.useState(!1),[v,N]=j.useState(!1),C=s.commission_split_pct??80,A=s.cap_amount??16e3,T=s.post_cap_split_pct??100,P=s.monthly_fee??99,M=s.transaction_fee??0,I=j.useMemo(()=>{const q=parseFloat(l)||0,W=Math.max(0,parseInt(c,10)||0),V=parseFloat(u)||0,K=parseFloat(m)||0,Q=q*(V/100)-K*12-M*W,J=1-C/100,ce=J>0?A/J:q,ue=Math.min(q,ce),ne=Math.max(0,q-ce),ee=ue*J+ne*(1-T/100),le=q-ee-P*12-M*W,he=le-Q;return{currentNet:Q,newNet:le,diff:he}},[l,c,u,m,C,A,T,P,M]),D=q=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(q),B=async q=>{if(q.preventDefault(),!!x){N(!0);try{const{error:W}=await U.from("recruit_lead_magnet_downloads").insert({brokerage_id:r,email:x,source:"calculator"});if(W)throw W;const{error:V}=await U.functions.invoke("send-calculator-breakdown",{body:{brokerage_id:r,brokerage_name:a,email:x,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:C,cap_amount:A,post_cap_split_pct:T,monthly_fee:P,transaction_fee:M},result:I,primary_color:t,accent_color:n}});V&&console.error("Breakdown email failed:",V),b(!0),i({title:"Sent!",description:"Check your email for the full breakdown."})}catch(W){i({title:"Error",description:W.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(_w,{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(Ad,{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(_w,{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(s5,{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(se,{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(be,{type:"number",value:l,onChange:q=>o(q.target.value),className:"pl-7 h-11 text-base",placeholder:"250,000"})]})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-gray-600 text-sm",children:"Transactions per Year"}),e.jsx(be,{type:"number",min:"0",value:c,onChange:q=>d(q.target.value),className:"mt-1.5 h-11 text-base",placeholder:"12"})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-gray-600 text-sm",children:"Your Current Commission Split (%)"}),e.jsx(be,{type:"number",value:u,onChange:q=>h(q.target.value),className:"mt-1.5 h-11 text-base",placeholder:"70"})]}),e.jsxs("div",{children:[e.jsx(se,{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(be,{type:"number",value:m,onChange:q=>p(q.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(Il,{className:"h-5 w-5"}),e.jsxs("h3",{className:"font-semibold",children:["Your Earnings at ",a]})]}),e.jsxs("div",{className:"space-y-4 mb-6",children:[e.jsxs("div",{className:"flex items-baseline justify-between border-b border-white/20 pb-3",children:[e.jsx("span",{className:"text-white/70 text-sm",children:"Current take-home"}),e.jsx("span",{className:"text-xl font-semibold",children:D(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:D(I.newNet)})]})]}),e.jsxs(jr.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?"+":"",D(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:B,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(be,{type:"email",required:!0,value:x,onChange:q=>g(q.target.value),placeholder:"you@email.com",className:"bg-white/95 border-0 text-gray-900 h-10 text-sm"}),e.jsx($,{type:"submit",disabled:v,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(oa,{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 FOn({config:s,primaryColor:t,accentColor:n,brokerageId:r}){const{toast:a}=gi(),[i,l]=j.useState(""),[o,c]=j.useState(""),[d,u]=j.useState(!1),[h,m]=j.useState(!1),p=async x=>{x.preventDefault(),m(!0);try{const{error:g}=await U.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(g)throw g;u(!0),s.pdf_url&&window.open(s.pdf_url,"_blank","noopener,noreferrer")}catch(g){a({title:"Error",description:g.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(_w,{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(Bj,{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(Ad,{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(oa,{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(be,{value:o,onChange:x=>c(x.target.value),placeholder:"First name (optional)",className:"h-11"}),e.jsx(be,{type:"email",required:!0,value:i,onChange:x=>l(x.target.value),placeholder:"your@email.com",className:"h-11"})]}),e.jsxs($,{type:"submit",disabled:h,className:"w-full sm:w-auto h-12 px-6 text-white font-semibold",style:{background:`linear-gradient(135deg, ${t}, ${n})`},children:[e.jsx(Bj,{className:"h-4 w-4 mr-2"}),h?"Sending...":s.button_text||"Email Me the PDF"]})]})]})]})})})})})}function zOn(){const{slug:s}=Vi(),{toast:t}=gi(),[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(W=>document.querySelectorAll(W).forEach(V=>V.style.display="none"))};I();const D=[setTimeout(I,500),setTimeout(I,1500),setTimeout(I,3e3)],B=new MutationObserver(I);return B.observe(document.body,{childList:!0,subtree:!0}),()=>{document.body.classList.remove("recruit-landing-page"),D.forEach(clearTimeout),B.disconnect()}},[]);const{data:l,isLoading:o,error:c}=ht({queryKey:["recruit-form-brokerage",s],queryFn:async()=>{const{data:I,error:D}=await U.from("brokerages").select("id, name, recruit_form_enabled").eq("recruit_form_slug",s).single();if(D)throw D;return I},enabled:!!s}),{data:d}=ht({queryKey:["recruit-landing-public",l==null?void 0:l.id],queryFn:async()=>{const{data:I,error:D}=await U.from("recruit_landing_page_settings").select("*").eq("brokerage_id",l.id).single();if(D&&D.code!=="PGRST116")throw D;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:D}=await U.from("recruit_interest_submissions").insert(I);if(D)throw D;U.functions.invoke("recruit-lead-notify",{body:{lead:I,brokerage_id:l.id}}).catch(B=>console.error("Lead notification error:",B))},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(Ai,{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",x=(h==null?void 0:h.benefits)||[],g=(h==null?void 0:h.testimonials)||[],y=(h==null?void 0:h.gallery_images)||[],b=(h==null?void 0:h.hero_headline)||`Join ${l.name}`,v=(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,C=(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)||{},P=(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(jr.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(oa,{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(ni,{className:"h-3.5 w-3.5"})]})]})}),e.jsx(MOn,{headline:b,subtext:v,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(LOn,{benefits:x,accentColor:p,primaryColor:m}),e.jsx(POn,{images:y,primaryColor:m,accentColor:p}),e.jsx(IOn,{testimonials:g,primaryColor:m,accentColor:p}),N&&e.jsx(OOn,{config:C,primaryColor:m,accentColor:p,brokerageId:l.id,brokerageName:l.name}),A&&e.jsx(FOn,{config:T,primaryColor:m,accentColor:p,brokerageId:l.id}),P==="multi_step"?e.jsx(ROn,{form:a,setForm:i,onSubmit:()=>u.mutate(),isPending:u.isPending,primaryColor:m,accentColor:p,showConfidentialBadges:M}):e.jsx(DOn,{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 BOn(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 $On(){var m,p,x,g;const{shareToken:s}=Vi(),t=j.useRef(!1),{data:n,isLoading:r,error:a}=ht({queryKey:["public-recruit-video",s],queryFn:async()=>{var A;if(!s)throw new Error("No token");const{data:y,error:b}=await U.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(b)throw b;const{data:v}=await U.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 U.from("brokerages").select("name").eq("id",y.brokerage_id).single(),{data:C}=await U.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:v,brokerage:N,settings:C}},enabled:!!s});if(j.useEffect(()=>{var y;!((y=n==null?void 0:n.rv)!=null&&y.id)||t.current||(t.current=!0,U.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=(x=i.video)!=null&&x.playback_url?BOn(i.video.playback_url):null;return e.jsxs(e.Fragment,{children:[e.jsx(Ul,{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:((g=l==null?void 0:l.name)==null?void 0:g.charAt(0))||"?"}),e.jsxs("div",{className:"flex-1",children:[e.jsx("p",{className:"font-semibold",children:l==null?void 0:l.name}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[(l==null?void 0:l.title)||"Recruiter"," · ",o==null?void 0:o.name]})]})]}),(l==null?void 0:l.recruit_cta_url)&&e.jsx("div",{className:"text-center",children:e.jsx($,{size:"lg",asChild:!0,className:"text-white shadow-lg hover:shadow-xl transition-shadow px-8",style:{backgroundColor:d},onClick:()=>{U.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(ia,{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 UOn="relzejiswnotikjgvjhz",Xvt=`https://${UOn}.supabase.co/functions/v1/recruit-unsubscribe`;function qOn(){const[s]=oc(),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(b=>document.querySelectorAll(b).forEach(v=>v.style.display="none"))};p();const x=[setTimeout(p,500),setTimeout(p,1500),setTimeout(p,3e3)],g=new MutationObserver(p);return g.observe(document.body,{childList:!0,subtree:!0}),()=>{document.body.classList.remove("recruit-unsubscribe-page"),x.forEach(clearTimeout),g.disconnect()}},[]),j.useEffect(()=>{if(!t){h({error:"Missing unsubscribe token in link."}),r(!1);return}fetch(`${Xvt}?token=${encodeURIComponent(t)}`).then(async p=>{const x=await p.json();if(!p.ok)throw new Error(x.error||"Lookup failed");h(x),x.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(Xvt,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({token:t,reason:c.trim()||null})}),x=await p.json();if(!p.ok)throw new Error(x.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(Ht,{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(xo,{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(Fr,{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(j0,{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(j0,{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(se,{htmlFor:"reason",className:"text-xs text-slate-500",children:"Optional — what's the main reason? (helps us improve)"}),e.jsx(Is,{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($,{onClick:m,disabled:a,className:"w-full h-11",variant:"default",children:a?e.jsxs(e.Fragment,{children:[e.jsx(Ht,{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 VOn="relzejiswnotikjgvjhz",Qvt=`https://${VOn}.supabase.co/functions/v1/event-invite-unsubscribe`;function HOn(){const[s]=oc(),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(`${Qvt}?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(Qvt,{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(Ht,{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(xo,{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(Fr,{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(j0,{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(vK,{className:"h-7 w-7 text-slate-500"})}),e.jsxs("h1",{className:"text-xl font-semibold text-slate-800",children:["Unsubscribe from event invites",c.first_name?`, ${c.first_name}`:"","?"]}),e.jsxs("p",{className:"text-sm text-slate-500",children:["You'll stop receiving event invite emails from LevelUp. Your ",e.jsx("span",{className:"font-medium text-slate-700",children:"Monday weekly digest"})," will keep coming."]}),c.email&&e.jsx("p",{className:"text-xs text-slate-400",children:c.email})]}),e.jsx($,{onClick:u,disabled:a,className:"w-full h-11",variant:"default",children:a?e.jsxs(e.Fragment,{children:[e.jsx(Ht,{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 GOn(){const s=Vn(),t=ts(),{isAdmin:n}=_s(),[r,a]=j.useState(!1),[i,l]=j.useState(null),[o,c]=j.useState(null),{data:d,isLoading:u}=ht({queryKey:["my-social-accounts"],queryFn:async()=>{const{data:{user:C},error:A}=await U.auth.getUser();if(A)throw A;if(!C)return[];const{data:T,error:P}=await U.from("social_accounts").select("*").eq("user_id",C.id).order("created_at",{ascending:!1});if(P)throw P;return T}}),h=yt({mutationFn:async C=>{const{data:{user:A},error:T}=await U.auth.getUser();if(T)throw T;if(!A)throw new Error("Not authenticated");const{error:P}=await U.from("social_accounts").delete().eq("id",C).eq("user_id",A.id);if(P)throw P},onSuccess:()=>{t.invalidateQueries({queryKey:["my-social-accounts"]}),t.invalidateQueries({queryKey:["social-accounts-for-post"]}),ae.success("Account disconnected successfully")},onError:()=>{ae.error("Failed to disconnect account")}}),m=async()=>{a(!0);try{const{data:C,error:A}=await U.functions.invoke("linkedin-oauth",{body:{action:"get_auth_url",callbackPath:"/social-connections/linkedin-callback"}});if(A)throw A;if(C!=null&&C.authUrl)window.location.href=C.authUrl;else throw new Error("Failed to get LinkedIn authorization URL")}catch(C){console.error("LinkedIn OAuth error:",C),ae.error("Failed to start LinkedIn connection. Please try again."),a(!1)}},p=async()=>{a(!0);try{const{data:C,error:A}=await U.functions.invoke("google-business-oauth",{body:{action:"get_auth_url"}});if(A)throw A;if(C!=null&&C.authUrl)window.location.href=C.authUrl;else throw new Error("Failed to get Google authorization URL")}catch(C){console.error("Google OAuth error:",C),ae.error("Failed to start Google connection. Please try again."),a(!1)}},x=(d==null?void 0:d.filter(C=>C.platform==="facebook"))||[],g=(d==null?void 0:d.filter(C=>C.platform==="instagram"))||[],y=(d==null?void 0:d.filter(C=>C.platform==="linkedin"))||[],b=(d==null?void 0:d.filter(C=>C.platform==="google_business"))||[],v=((d==null?void 0:d.length)||0)>0,N=async(C,A)=>{l(C),c(null);try{const{data:T,error:P}=await U.functions.invoke("meta-api-test",{body:{testType:"all",accountId:C}});if(P)throw P;c(T.results||[]),ae.success(T.summary||"API tests completed")}catch(T){console.error("Meta API test error:",T),ae.error("Failed to run API tests")}finally{l(null)}};return e.jsx(Ks,{title:"Social Connections",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"relative overflow-hidden rounded-2xl bg-gradient-to-br from-pink-500 via-purple-500 to-blue-500 p-6 md:p-8 text-white",children:[e.jsx("div",{className:"absolute inset-0 bg-[url('data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iNjAiIGhlaWdodD0iNjAiIHZpZXdCb3g9IjAgMCA2MCA2MCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj48ZyBmaWxsPSJub25lIiBmaWxsLXJ1bGU9ImV2ZW5vZGQiPjxnIGZpbGw9IiNmZmYiIGZpbGwtb3BhY2l0eT0iMC4xIj48cGF0aCBkPSJNMzYgMzRjMC0yIDItNCAyLTRzMiAyIDIgNC0yIDQtMiA0LTItMi0yLTR6Ii8+PC9nPjwvZz48L3N2Zz4=')] opacity-30"}),e.jsxs("div",{className:"relative",children:[e.jsx("div",{className:"flex items-center gap-2 mb-3",children:e.jsxs($e,{variant:"secondary",className:"bg-white/20 text-white border-0 backdrop-blur-sm",children:[e.jsx(dn,{className:"h-3 w-3 mr-1"}),"Post directly from Social Swag"]})}),e.jsx("h1",{className:"text-2xl md:text-3xl font-bold mb-2",children:"Connect Your Social Accounts"}),e.jsx("p",{className:"text-white/90 max-w-xl",children:"Link your Facebook Pages and Instagram Business accounts to post content directly from Social Swag with one click."})]})]}),e.jsxs($,{variant:"ghost",onClick:()=>s("/social-studio"),className:"gap-2",children:[e.jsx(ka,{className:"h-4 w-4"}),"Back to Social Studio"]}),v&&e.jsx(_e,{className:"border-green-200 bg-green-50 dark:bg-green-950/20 dark:border-green-900",children:e.jsxs(Oe,{className:"flex items-center gap-4 p-4",children:[e.jsx("div",{className:"rounded-full bg-green-500 p-2",children:e.jsx(Ro,{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(_e,{children:[e.jsx(Bt,{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(jf,{className:"h-6 w-6 text-blue-600"})}),e.jsxs("div",{children:[e.jsxs(Ut,{className:"text-lg flex items-center gap-2",children:["Facebook",e.jsx($e,{variant:"outline",className:"text-amber-600 border-amber-200 bg-amber-50",children:"Coming Soon"})]}),e.jsx(vr,{children:"Facebook integration is coming soon — stay tuned!"})]})]})}),e.jsxs(Oe,{className:"space-y-4",children:[u?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx(Wi,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):x.length>0?e.jsx("div",{className:"space-y-3",children:x.map(C=>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(ki,{src:C.profile_picture_url||""}),e.jsx(Ta,{children:e.jsx(jf,{className:"h-5 w-5"})})]}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:C.page_name||C.platform_username||"Facebook Page"}),e.jsx($e,{variant:C.is_active?"default":"secondary",className:"text-xs",children:C.is_active?"Connected":"Inactive"})]})]}),e.jsxs(Ll,{children:[e.jsx(_f,{asChild:!0,children:e.jsx($,{variant:"ghost",size:"icon",className:"text-destructive hover:text-destructive",children:e.jsx(Pn,{className:"h-4 w-4"})})}),e.jsxs(yl,{children:[e.jsxs(vl,{children:[e.jsx(_l,{children:"Disconnect Facebook?"}),e.jsx(wl,{children:"This will remove the connection. You'll need to reconnect to post content."})]}),e.jsxs(bl,{children:[e.jsx(jl,{children:"Cancel"}),e.jsx(fl,{onClick:()=>h.mutate(C.id),className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Disconnect"})]})]})]})]},C.id))}):e.jsx("p",{className:"text-sm text-muted-foreground py-4 text-center",children:"No Facebook pages connected yet"}),e.jsxs($,{disabled:!0,className:"w-full gap-2",variant:"outline",children:[e.jsx(Hr,{className:"h-4 w-4"}),"Coming Soon"]})]})]}),e.jsxs(_e,{children:[e.jsx(Bt,{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(Qh,{className:"h-6 w-6 text-pink-600"})}),e.jsxs("div",{children:[e.jsxs(Ut,{className:"text-lg flex items-center gap-2",children:["Instagram",e.jsx($e,{variant:"outline",className:"text-amber-600 border-amber-200 bg-amber-50",children:"Coming Soon"})]}),e.jsx(vr,{children:"Instagram integration is coming soon — stay tuned!"})]})]})}),e.jsxs(Oe,{className:"space-y-4",children:[u?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx(Wi,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):g.length>0?e.jsx("div",{className:"space-y-3",children:g.map(C=>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(ki,{src:C.profile_picture_url||""}),e.jsx(Ta,{children:e.jsx(Qh,{className:"h-5 w-5"})})]}),e.jsxs("div",{children:[e.jsxs("p",{className:"font-medium",children:["@",C.platform_username||"Instagram Account"]}),e.jsx($e,{variant:C.is_active?"default":"secondary",className:"text-xs",children:C.is_active?"Connected":"Inactive"})]})]}),e.jsxs(Ll,{children:[e.jsx(_f,{asChild:!0,children:e.jsx($,{variant:"ghost",size:"icon",className:"text-destructive hover:text-destructive",children:e.jsx(Pn,{className:"h-4 w-4"})})}),e.jsxs(yl,{children:[e.jsxs(vl,{children:[e.jsx(_l,{children:"Disconnect Instagram?"}),e.jsx(wl,{children:"This will remove the connection. You'll need to reconnect to post content."})]}),e.jsxs(bl,{children:[e.jsx(jl,{children:"Cancel"}),e.jsx(fl,{onClick:()=>h.mutate(C.id),className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Disconnect"})]})]})]})]},C.id))}):e.jsx("p",{className:"text-sm text-muted-foreground py-4 text-center",children:"No Instagram accounts connected yet"}),e.jsxs($,{disabled:!0,className:"w-full gap-2",variant:"outline",children:[e.jsx(Hr,{className:"h-4 w-4"}),"Coming Soon"]}),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(_e,{children:[e.jsx(Bt,{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(kg,{className:"h-6 w-6 text-blue-700"})}),e.jsxs("div",{children:[e.jsx(Ut,{className:"text-lg",children:"LinkedIn"}),e.jsx(vr,{children:"Connect your LinkedIn profile"})]})]})}),e.jsxs(Oe,{className:"space-y-4",children:[u?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx(Wi,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):y.length>0?e.jsx("div",{className:"space-y-3",children:y.map(C=>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(ki,{src:C.profile_picture_url||""}),e.jsx(Ta,{children:e.jsx(kg,{className:"h-5 w-5"})})]}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:C.platform_username||"LinkedIn Account"}),e.jsx($e,{variant:C.is_active?"default":"secondary",className:"text-xs",children:C.is_active?"Connected":"Inactive"})]})]}),e.jsxs(Ll,{children:[e.jsx(_f,{asChild:!0,children:e.jsx($,{variant:"ghost",size:"icon",className:"text-destructive hover:text-destructive",children:e.jsx(Pn,{className:"h-4 w-4"})})}),e.jsxs(yl,{children:[e.jsxs(vl,{children:[e.jsx(_l,{children:"Disconnect LinkedIn?"}),e.jsx(wl,{children:"This will remove the connection. You'll need to reconnect to post content."})]}),e.jsxs(bl,{children:[e.jsx(jl,{children:"Cancel"}),e.jsx(fl,{onClick:()=>h.mutate(C.id),className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Disconnect"})]})]})]})]},C.id))}):e.jsx("p",{className:"text-sm text-muted-foreground py-4 text-center",children:"No LinkedIn account connected yet"}),e.jsxs($,{onClick:m,disabled:r,className:"w-full gap-2",variant:y.length>0?"outline":"default",children:[r?e.jsx(Wi,{className:"h-4 w-4 animate-spin"}):e.jsx(sn,{className:"h-4 w-4"}),y.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(_e,{className:`relative overflow-hidden ${n?"":"opacity-75"}`,children:[!n&&e.jsx("div",{className:"absolute top-3 right-3 z-10",children:e.jsx($e,{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($e,{variant:"secondary",className:"bg-green-100 text-green-800 dark:bg-green-900/30 dark:text-green-400",children:"Admin Testing"})}),e.jsx(Bt,{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(ai,{className:"h-6 w-6 text-red-600"})}),e.jsxs("div",{children:[e.jsx(Ut,{className:"text-lg",children:"Google Business"}),e.jsx(vr,{children:"Connect your Google Business Profile"})]})]})}),e.jsxs(Oe,{className:"space-y-4",children:[u?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx(Wi,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):b.length>0?e.jsx("div",{className:"space-y-3",children:b.map(C=>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(ki,{src:C.profile_picture_url||""}),e.jsx(Ta,{children:e.jsx(ai,{className:"h-5 w-5"})})]}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:C.page_name||C.platform_username||"Google Business"}),e.jsx($e,{variant:C.is_active?"default":"secondary",className:"text-xs",children:C.is_active?"Connected":"Inactive"})]})]}),e.jsxs(Ll,{children:[e.jsx(_f,{asChild:!0,children:e.jsx($,{variant:"ghost",size:"icon",className:"text-destructive hover:text-destructive",children:e.jsx(Pn,{className:"h-4 w-4"})})}),e.jsxs(yl,{children:[e.jsxs(vl,{children:[e.jsx(_l,{children:"Disconnect Google Business?"}),e.jsx(wl,{children:"This will remove the connection. You'll need to reconnect to post content."})]}),e.jsxs(bl,{children:[e.jsx(jl,{children:"Cancel"}),e.jsx(fl,{onClick:()=>h.mutate(C.id),className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Disconnect"})]})]})]})]},C.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($,{onClick:n?p:void 0,disabled:!n||r,className:"w-full gap-2",variant:b.length>0?"outline":"default",children:[r?e.jsx(Wi,{className:"h-4 w-4 animate-spin"}):e.jsx(sn,{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||g.length>0)&&e.jsxs(_e,{className:"border-amber-200 bg-amber-50 dark:bg-amber-950/20 dark:border-amber-900",children:[e.jsx(Bt,{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(yT,{className:"h-6 w-6 text-amber-600"})}),e.jsxs("div",{children:[e.jsx(Ut,{className:"text-lg",children:"Meta API Testing (Admin Only)"}),e.jsx(vr,{children:"Run API tests to trigger all required permissions for Meta App Review"})]})]})}),e.jsxs(Oe,{className:"space-y-4",children:[e.jsxs("p",{className:"text-sm text-muted-foreground",children:['Click "Run Tests" on an account to trigger API calls for: ',e.jsx("strong",{children:"public_profile"}),", ",e.jsx("strong",{children:"pages_show_list"}),", ",e.jsx("strong",{children:"pages_read_engagement"}),", ",e.jsx("strong",{children:"instagram_basic"}),", ",e.jsx("strong",{children:"pages_manage_posts"}),", and ",e.jsx("strong",{children:"instagram_content_publish"}),"."]}),e.jsxs("div",{className:"space-y-3",children:[x.map(C=>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(jf,{className:"h-5 w-5 text-blue-600"}),e.jsx("span",{className:"font-medium",children:C.page_name||"Facebook Page"})]}),e.jsx($,{size:"sm",variant:"outline",onClick:()=>N(C.id),disabled:i===C.id,children:i===C.id?e.jsxs(e.Fragment,{children:[e.jsx(Ht,{className:"h-4 w-4 mr-2 animate-spin"}),"Testing..."]}):e.jsxs(e.Fragment,{children:[e.jsx(yT,{className:"h-4 w-4 mr-2"}),"Run Tests"]})})]},`test-fb-${C.id}`)),g.map(C=>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(Qh,{className:"h-5 w-5 text-pink-600"}),e.jsxs("span",{className:"font-medium",children:["@",C.platform_username||"Instagram"]})]}),e.jsx($,{size:"sm",variant:"outline",onClick:()=>N(C.id),disabled:i===C.id,children:i===C.id?e.jsxs(e.Fragment,{children:[e.jsx(Ht,{className:"h-4 w-4 mr-2 animate-spin"}),"Testing..."]}):e.jsxs(e.Fragment,{children:[e.jsx(yT,{className:"h-4 w-4 mr-2"}),"Run Tests"]})})]},`test-ig-${C.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((C,A)=>e.jsxs("div",{className:"flex items-start gap-2 text-sm",children:[C.status==="success"?e.jsx(Fr,{className:"h-4 w-4 text-green-600 mt-0.5 shrink-0"}):C.status==="pending"?e.jsx(Ht,{className:"h-4 w-4 text-amber-600 mt-0.5 shrink-0"}):e.jsx($d,{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:C.test}),e.jsx("span",{className:"ml-2 text-muted-foreground",children:C.details})]})]},A))})]}),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(_e,{children:[e.jsx(Bt,{children:e.jsx(Ut,{className:"text-lg",children:"How it works"})}),e.jsx(Oe,{children:e.jsxs("div",{className:"grid gap-4 md:grid-cols-3",children:[e.jsxs("div",{className:"flex gap-3",children:[e.jsx("div",{className:"flex h-8 w-8 shrink-0 items-center justify-center rounded-full bg-primary text-primary-foreground text-sm font-medium",children:"1"}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:"Connect your accounts"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Link your Facebook, Instagram, or LinkedIn account"})]})]}),e.jsxs("div",{className:"flex gap-3",children:[e.jsx("div",{className:"flex h-8 w-8 shrink-0 items-center justify-center rounded-full bg-primary text-primary-foreground text-sm font-medium",children:"2"}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:"Browse Social Swag"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Find the perfect image and caption for your post"})]})]}),e.jsxs("div",{className:"flex gap-3",children:[e.jsx("div",{className:"flex h-8 w-8 shrink-0 items-center justify-center rounded-full bg-primary text-primary-foreground text-sm font-medium",children:"3"}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:"Post with one click"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:'Click "Create Post" to share directly to your accounts'})]})]})]})})]})]})})}function WOn(){const[s]=oc(),t=Vn(),[n,r]=j.useState("loading"),a=j.useRef(!1),[i,l]=j.useState("Processing your connection..."),o=(()=>{const c=sessionStorage.getItem("social-connect-return-to");return c&&c.startsWith("/")&&!c.startsWith("/admin")?c:"/social-connections"})();return j.useEffect(()=>{if(a.current)return;a.current=!0,(async()=>{var p;const d=s.get("code"),u=s.get("error"),h=s.get("error_description"),m=s.get("state");if(u){r("error"),l(h||"Authorization was denied"),ae.error("Connection failed: "+(h||u));return}if(!d){r("error"),l("No authorization code received"),ae.error("No authorization code received");return}try{const{data:x,error:g}=await U.functions.invoke("meta-oauth",{body:{action:"exchange_code",code:d,state:m,callbackPath:"/social-connections/callback"}});if(g)throw g;if(x!=null&&x.success)r("success"),l(`Successfully connected ${((p=x.accounts)==null?void 0:p.length)||0} account(s)!`),ae.success("Social accounts connected successfully!");else throw new Error((x==null?void 0:x.error)||"Unknown error")}catch(x){console.error("OAuth callback error:",x),r("error"),l(x instanceof Error?x.message:"Failed to connect accounts"),ae.error("Failed to connect: "+(x instanceof Error?x.message:"Unknown error"))}})()},[s]),e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-background p-4",children:e.jsxs(_e,{className:"w-full max-w-md",children:[e.jsxs(Bt,{className:"text-center",children:[n==="loading"&&e.jsx(Ht,{className:"h-12 w-12 animate-spin mx-auto text-primary"}),n==="success"&&e.jsx(Ro,{className:"h-12 w-12 mx-auto text-green-500"}),n==="error"&&e.jsx($d,{className:"h-12 w-12 mx-auto text-destructive"}),e.jsxs(Ut,{className:"mt-4",children:[n==="loading"&&"Connecting...",n==="success"&&"Connected!",n==="error"&&"Connection Failed"]}),e.jsx(vr,{children:i})]}),e.jsx(Oe,{className:"flex justify-center",children:n!=="loading"&&e.jsx($,{onClick:()=>t(o),children:n==="success"?"View Connected Accounts":"Try Again"})})]})})}function KOn(){const[s]=oc(),t=Vn(),[n,r]=j.useState("loading"),[a,i]=j.useState("Connecting your Google Business Profile...");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"),ae.error("Connection failed: "+(d||c));return}if(!o){r("error"),i("No authorization code received"),ae.error("No authorization code received");return}try{const{data:h,error:m}=await U.functions.invoke("google-business-oauth",{body:{action:"exchange_code",code:o,state:u}});if(m)throw m;if(h!=null&&h.success)r("success"),i(h.message||"Successfully connected Google Business Profile!"),ae.success("Google Business Profile connected!");else throw new Error((h==null?void 0:h.error)||"Unknown error")}catch(h){console.error("Google OAuth callback error:",h),r("error"),i(h instanceof Error?h.message:"Failed to connect Google Business Profile"),ae.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(_e,{className:"w-full max-w-md",children:[e.jsxs(Bt,{className:"text-center",children:[n==="loading"&&e.jsx(Ht,{className:"h-12 w-12 animate-spin mx-auto text-primary"}),n==="success"&&e.jsx(Ro,{className:"h-12 w-12 mx-auto text-green-500"}),n==="error"&&e.jsx($d,{className:"h-12 w-12 mx-auto text-destructive"}),e.jsxs(Ut,{className:"mt-4",children:[n==="loading"&&"Connecting...",n==="success"&&"Connected!",n==="error"&&"Connection Failed"]}),e.jsx(vr,{children:a})]}),e.jsx(Oe,{className:"flex justify-center",children:n!=="loading"&&e.jsx($,{onClick:()=>t("/social-connections"),children:n==="success"?"View Connected Accounts":"Try Again"})})]})})}function YOn(){const[s]=oc(),t=Vn(),[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"),ae.error(u||"Failed to connect LinkedIn");return}if(!o){r("error"),i("No authorization code received"),ae.error("No authorization code received");return}try{const{data:m,error:p}=await U.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`),ae.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"),ae.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(_e,{className:"w-full max-w-md",children:[e.jsxs(Bt,{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(Ht,{className:"h-8 w-8 animate-spin text-blue-600"}),n==="success"&&e.jsx(Ro,{className:"h-8 w-8 text-green-600"}),n==="error"&&e.jsx($d,{className:"h-8 w-8 text-red-600"})]}),e.jsxs(Ut,{className:"flex items-center justify-center gap-2",children:[e.jsx(kg,{className:"h-5 w-5 text-blue-600"}),n==="loading"&&"Connecting...",n==="success"&&"Connected!",n==="error"&&"Connection Failed"]}),e.jsx(vr,{children:a})]}),e.jsx(Oe,{className:"flex justify-center",children:e.jsx($,{onClick:()=>t("/mission-control/integrations"),disabled:n==="loading",children:n==="success"?"View Integrations":"Back to Integrations"})})]})})}function ZOn(){const s=Vn(),[t,n]=j.useState(null),{data:r,isLoading:a}=EVt(t||void 0,!0),{data:i,isLoading:l}=fXe(!0),{cartItems:o}=DCe(),c=o.reduce((u,h)=>u+h.quantity,0),d=u=>{s(`/marketplace/${u.id}`)};return a||l?e.jsx(Ks,{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(on,{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(on,{className:"h-72 w-full"},u))})]})}):e.jsx(Ks,{title:"Marketplace",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-5xl font-bold text-foreground",children:"Marketplace"}),e.jsx("p",{className:"text-muted-foreground mt-1",children:"Shop exclusive products for LevelUp members"})]}),e.jsxs($,{variant:"outline",onClick:()=>s("/marketplace/cart"),className:"relative",children:[e.jsx(ON,{className:"h-4 w-4 mr-2"}),"Cart",c>0&&e.jsx($e,{className:"absolute -top-2 -right-2 h-5 w-5 flex items-center justify-center p-0 text-xs",children:c})]})]}),i&&i.length>0&&e.jsxs("div",{className:"flex gap-2 overflow-x-auto pb-2",children:[e.jsx($,{variant:t===null?"default":"outline",size:"sm",onClick:()=>n(null),children:"All"}),i.map(u=>e.jsx($,{variant:t===u.id?"default":"outline",size:"sm",onClick:()=>n(u.id),children:u.name},u.id))]}),r&&r.length>0?e.jsx("div",{className:"grid gap-4 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4",children:r.map(u=>{var h;return e.jsxs(_e,{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(Tu,{className:"h-12 w-12 text-muted-foreground"})}),u.category&&e.jsx($e,{className:"absolute top-2 left-2",variant:"secondary",children:u.category.name})]}),e.jsxs(Oe,{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(Tu,{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 nHt=j.forwardRef(({...s},t)=>e.jsx("nav",{ref:t,"aria-label":"breadcrumb",...s}));nHt.displayName="Breadcrumb";const rHt=j.forwardRef(({className:s,...t},n)=>e.jsx("ol",{ref:n,className:Tt("flex flex-wrap items-center gap-1.5 break-words text-sm text-muted-foreground sm:gap-2.5",s),...t}));rHt.displayName="BreadcrumbList";const MNe=j.forwardRef(({className:s,...t},n)=>e.jsx("li",{ref:n,className:Tt("inline-flex items-center gap-1.5",s),...t}));MNe.displayName="BreadcrumbItem";const gUe=j.forwardRef(({asChild:s,className:t,...n},r)=>{const a=s?Jqe:"a";return e.jsx(a,{ref:r,className:Tt("transition-colors hover:text-foreground",t),...n})});gUe.displayName="BreadcrumbLink";const aHt=j.forwardRef(({className:s,...t},n)=>e.jsx("span",{ref:n,role:"link","aria-disabled":"true","aria-current":"page",className:Tt("font-normal text-foreground",s),...t}));aHt.displayName="BreadcrumbPage";const yUe=({children:s,className:t,...n})=>e.jsx("li",{role:"presentation","aria-hidden":"true",className:Tt("[&>svg]:size-3.5",t),...n,children:s??e.jsx(Ja,{})});yUe.displayName="BreadcrumbSeparator";function XOn(){var W,V;const{productId:s}=Vi(),t=Vn(),{data:n,isLoading:r}=FDn(s||""),{addToCart:a,cartItems:i}=DCe(),[l,o]=j.useState(null),[c,d]=j.useState(1),[u,h]=j.useState(0),[m,p]=j.useState(null),[x,g]=j.useState(!1),[y,b]=j.useState(!1),v=(W=n==null?void 0:n.variants)==null?void 0:W.find(K=>K.id===l),N=((V=n==null?void 0:n.variants)==null?void 0:V.filter(K=>K.is_active))||[],C=Number((n==null?void 0:n.base_price)||0),A=v?Number(v.price_adjustment):0,T=C+A,P=Number((n==null?void 0:n.shipping_fee)||0),M=i.reduce((K,Q)=>K+Q.quantity,0),I=async K=>{if(!K.target.files||K.target.files.length===0)return;g(!0);const Q=K.target.files[0],J=Q.name.split(".").pop(),ce=`artwork/${Date.now()}-${Math.random().toString(36).substring(7)}.${J}`;try{const{error:ue}=await U.storage.from("marketplace").upload(ce,Q);if(ue)throw ue;const{data:{publicUrl:ne}}=U.storage.from("marketplace").getPublicUrl(ce);p(ne),ae.success("Artwork uploaded successfully")}catch(ue){ae.error("Failed to upload artwork: "+ue.message)}finally{g(!1)}},D=()=>{if(n){if(N.length>0&&!l){ae.error("Please select an option");return}a(n,v||void 0,c,m||void 0),b(!0),ae.success("Added to cart!"),setTimeout(()=>b(!1),2e3)}},B=()=>{n!=null&&n.images&&h(K=>(K+1)%n.images.length)},q=()=>{n!=null&&n.images&&h(K=>(K-1+n.images.length)%n.images.length)};return r?e.jsx(Ks,{title:"Product",children:e.jsxs("div",{className:"grid gap-8 lg:grid-cols-2",children:[e.jsx(on,{className:"aspect-square w-full"}),e.jsxs("div",{className:"space-y-4",children:[e.jsx(on,{className:"h-8 w-3/4"}),e.jsx(on,{className:"h-6 w-1/4"}),e.jsx(on,{className:"h-24 w-full"}),e.jsx(on,{className:"h-12 w-full"})]})]})}):n?e.jsxs(Ks,{title:n.name,children:[e.jsx(nHt,{className:"mb-6",children:e.jsxs(rHt,{children:[e.jsx(MNe,{children:e.jsx(gUe,{asChild:!0,children:e.jsx(Wn,{to:"/marketplace",children:"Marketplace"})})}),n.category&&e.jsxs(e.Fragment,{children:[e.jsx(yUe,{}),e.jsx(MNe,{children:e.jsx(gUe,{asChild:!0,children:e.jsx(Wn,{to:`/marketplace?category=${n.category.id}`,children:n.category.name})})})]}),e.jsx(yUe,{}),e.jsx(MNe,{children:e.jsx(aHt,{children:n.name})})]})}),e.jsxs("div",{className:"grid gap-8 lg:grid-cols-2",children:[e.jsxs("div",{className:"space-y-4",children:[e.jsx("div",{className:"relative aspect-square bg-muted rounded-lg overflow-hidden flex items-center justify-center",children:n.images&&n.images.length>0?e.jsxs(e.Fragment,{children:[e.jsx("img",{src:n.images[u].image_url,alt:n.name,className:"max-w-full max-h-full object-contain"}),n.images.length>1&&e.jsxs(e.Fragment,{children:[e.jsx($,{variant:"ghost",size:"icon",className:"absolute left-2 top-1/2 -translate-y-1/2 bg-background/80 hover:bg-background",onClick:q,children:e.jsx(Ic,{className:"h-6 w-6"})}),e.jsx($,{variant:"ghost",size:"icon",className:"absolute right-2 top-1/2 -translate-y-1/2 bg-background/80 hover:bg-background",onClick:B,children:e.jsx(Ja,{className:"h-6 w-6"})})]})]}):e.jsx("div",{className:"flex items-center justify-center h-full",children:e.jsx(Tu,{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,Q)=>e.jsx("button",{onClick:()=>h(Q),className:`w-16 h-16 flex-shrink-0 rounded-md overflow-hidden border-2 ${Q===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(_e,{children:e.jsxs(Oe,{className:"p-4",children:[e.jsx("h4",{className:"font-medium mb-2",children:"Product Video"}),e.jsx("div",{className:"aspect-video",children:e.jsx("iframe",{src:n.video.video_url,className:"w-full h-full rounded-lg",allowFullScreen:!0})})]})})]}),e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{children:[n.category&&e.jsx($e,{variant:"secondary",className:"mb-2",children:n.category.name}),e.jsx("h1",{className:"text-3xl font-bold mb-2",children:n.name}),e.jsxs("div",{className:"flex items-baseline gap-2",children:[e.jsxs("span",{className:"text-3xl font-bold",children:["$",T.toFixed(2)]}),P>0&&e.jsxs("span",{className:"text-muted-foreground",children:["+ $",P.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(se,{children:"Select Option"}),e.jsx("div",{className:"flex flex-wrap gap-2",children:N.map(K=>e.jsxs($,{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(se,{children:"Upload Your Artwork (Optional)"}),m?e.jsxs("div",{className:"relative inline-block",children:[e.jsx("img",{src:m,alt:"Your artwork",className:"h-24 w-auto rounded-lg border"}),e.jsx($,{variant:"ghost",size:"sm",className:"absolute -top-2 -right-2",onClick:()=>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:x}),e.jsxs("label",{htmlFor:"artwork-upload",className:"flex flex-col items-center cursor-pointer",children:[e.jsx(si,{className:"h-8 w-8 text-muted-foreground mb-2"}),e.jsx("span",{className:"text-sm text-muted-foreground",children:x?"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(se,{children:"Quantity"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx($,{variant:"outline",size:"icon",onClick:()=>d(K=>Math.max(1,K-1)),children:"-"}),e.jsx(be,{type:"number",value:c,onChange:K=>d(Math.max(1,parseInt(K.target.value)||1)),className:"w-20 text-center",min:"1"}),e.jsx($,{variant:"outline",size:"icon",onClick:()=>d(K=>K+1),children:"+"})]})]}),e.jsxs("div",{className:"flex gap-4",children:[e.jsx($,{size:"lg",className:"flex-1",onClick:D,disabled:y,children:y?e.jsxs(e.Fragment,{children:[e.jsx(oa,{className:"h-5 w-5 mr-2"}),"Added!"]}):e.jsxs(e.Fragment,{children:[e.jsx(ON,{className:"h-5 w-5 mr-2"}),"Add to Cart"]})}),e.jsxs($,{variant:"outline",size:"lg",onClick:()=>t("/marketplace/cart"),className:"relative",children:[e.jsx(ON,{className:"h-5 w-5"}),M>0&&e.jsx($e,{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(Ks,{title:"Product Not Found",children:e.jsxs("div",{className:"text-center py-12",children:[e.jsx(Tu,{className:"h-12 w-12 mx-auto text-muted-foreground mb-4"}),e.jsx("p",{className:"text-muted-foreground mb-4",children:"Product not found"}),e.jsx($,{onClick:()=>t("/marketplace"),children:"Back to Marketplace"})]})})}function QOn(){const s=Vn(),{cartItems:t,removeFromCart:n,updateQuantity:r,getItemPrice:a,getSubtotal:i,getShippingTotal:l,getTotal:o,clearCart:c}=DCe(),[d,u]=j.useState(!1),[h,m]=j.useState(""),p=async()=>{if(t.length===0){ae.error("Your cart is empty");return}u(!0);try{const{data:x,error:g}=await U.functions.invoke("marketplace-checkout",{body:{items:t.map(y=>{var b;return{product_id:y.product.id,variant_id:((b=y.variant)==null?void 0:b.id)||null,quantity:y.quantity,artwork_url:y.artworkUrl||null}}),notes:h.trim()||null}});if(g)throw g;if(x!=null&&x.url)c(),window.open(x.url,"_blank");else throw new Error("No checkout URL received")}catch(x){ae.error("Checkout failed: "+x.message)}finally{u(!1)}};return t.length===0?e.jsx(Ks,{title:"Shopping Cart",children:e.jsxs("div",{className:"text-center py-12",children:[e.jsx(l5,{className:"h-16 w-16 mx-auto text-muted-foreground mb-4"}),e.jsx("h2",{className:"text-xl font-semibold mb-2",children:"Your cart is empty"}),e.jsx("p",{className:"text-muted-foreground mb-6",children:"Add some products to get started!"}),e.jsx($,{onClick:()=>s("/marketplace"),children:"Browse Marketplace"})]})}):e.jsx(Ks,{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(x=>{var g,y;return e.jsx(_e,{children:e.jsx(Oe,{className:"p-4",children:e.jsxs("div",{className:"flex gap-4",children:[e.jsx("div",{className:"w-24 h-24 flex-shrink-0 bg-muted rounded-lg overflow-hidden",children:x.product.images&&x.product.images.length>0?e.jsx("img",{src:((g=x.product.images.find(b=>b.is_primary))==null?void 0:g.image_url)||x.product.images[0].image_url,alt:x.product.name,className:"w-full h-full object-cover"}):e.jsx("div",{className:"flex items-center justify-center h-full",children:e.jsx(l5,{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:x.product.name}),x.variant&&e.jsx("p",{className:"text-sm text-muted-foreground",children:x.variant.name}),e.jsxs("p",{className:"font-medium mt-1",children:["$",a(x).toFixed(2),Number(x.product.shipping_fee)>0&&e.jsxs("span",{className:"text-sm text-muted-foreground ml-2",children:["+ $",Number(x.product.shipping_fee).toFixed(2)," shipping"]})]}),x.artworkUrl&&e.jsx("div",{className:"mt-2",children:e.jsx("span",{className:"text-xs text-muted-foreground",children:"Artwork uploaded ✓"})})]}),e.jsxs("div",{className:"flex flex-col items-end gap-2",children:[e.jsx($,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:()=>{var b;return n(x.product.id,(b=x.variant)==null?void 0:b.id)},children:e.jsx(Pn,{className:"h-4 w-4 text-destructive"})}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx($,{variant:"outline",size:"icon",className:"h-8 w-8",onClick:()=>{var b;return r(x.product.id,(b=x.variant)==null?void 0:b.id,x.quantity-1)},disabled:x.quantity<=1,children:e.jsx(DN,{className:"h-3 w-3"})}),e.jsx(be,{type:"number",value:x.quantity,onChange:b=>{var v;return r(x.product.id,(v=x.variant)==null?void 0:v.id,parseInt(b.target.value)||1)},className:"w-14 h-8 text-center text-sm",min:"1"}),e.jsx($,{variant:"outline",size:"icon",className:"h-8 w-8",onClick:()=>{var b;return r(x.product.id,(b=x.variant)==null?void 0:b.id,x.quantity+1)},children:e.jsx(sn,{className:"h-3 w-3"})})]})]})]})})},`${x.product.id}-${((y=x.variant)==null?void 0:y.id)||"base"}`)}),e.jsx($,{variant:"ghost",className:"text-destructive",onClick:c,children:"Clear Cart"})]}),e.jsx("div",{children:e.jsxs(_e,{className:"sticky top-4",children:[e.jsx(Bt,{children:e.jsx(Ut,{children:"Order Summary"})}),e.jsxs(Oe,{className:"space-y-4",children:[e.jsxs("div",{className:"flex justify-between text-sm",children:[e.jsxs("span",{children:["Subtotal (",t.reduce((x,g)=>x+g.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(Hl,{}),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(Hl,{}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"orderNotes",children:"Order Notes (Optional)"}),e.jsx(Is,{id:"orderNotes",placeholder:"Add any special instructions, design notes, or comments for your order...",value:h,onChange:x=>m(x.target.value),rows:3,className:"resize-none"})]}),e.jsx($,{className:"w-full",size:"lg",onClick:p,disabled:d,children:d?e.jsxs(e.Fragment,{children:[e.jsx(Ht,{className:"h-5 w-5 mr-2 animate-spin"}),"Processing..."]}):e.jsxs(e.Fragment,{children:["Checkout",e.jsx(ni,{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 JOn(){const s=Vn(),{data:t,isLoading:n}=YDn();return n?e.jsx(Ks,{title:"My Orders",children:e.jsx("div",{className:"space-y-4",children:[1,2,3].map(r=>e.jsx(on,{className:"h-32 w-full"},r))})}):!t||t.length===0?e.jsx(Ks,{title:"My Orders",children:e.jsxs("div",{className:"text-center py-12",children:[e.jsx(Tu,{className:"h-16 w-16 mx-auto text-muted-foreground mb-4"}),e.jsx("h2",{className:"text-xl font-semibold mb-2",children:"No orders yet"}),e.jsx("p",{className:"text-muted-foreground mb-6",children:"Start shopping to see your orders here!"}),e.jsx($,{onClick:()=>s("/marketplace"),children:"Browse Marketplace"})]})}):e.jsx(Ks,{title:"My Orders",children:e.jsx("div",{className:"space-y-4",children:t.map(r=>{var a,i,l;return e.jsx(_e,{className:"cursor-pointer hover:shadow-md transition-shadow",onClick:()=>s(`/marketplace/orders/${r.id}`),children:e.jsxs(Oe,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center justify-between mb-3",children:[e.jsxs("div",{children:[e.jsx("span",{className:"font-semibold",children:r.order_number}),e.jsx("span",{className:"text-muted-foreground text-sm ml-2",children:Hs(new Date(r.created_at),"MMM d, yyyy")})]}),e.jsx($e,{className:pXe[r.status],children:_B[r.status]})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsxs("div",{className:"flex -space-x-2",children:[(a=r.items)==null?void 0:a.slice(0,3).map((o,c)=>e.jsxs("div",{className:"w-10 h-10 bg-muted rounded border-2 border-background flex items-center justify-center text-xs font-medium",style:{zIndex:3-c},children:[o.quantity,"×"]},o.id)),r.items&&r.items.length>3&&e.jsxs("div",{className:"w-10 h-10 bg-muted rounded border-2 border-background flex items-center justify-center text-xs font-medium",children:["+",r.items.length-3]})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm",children:((i=r.items)==null?void 0:i.length)===1?r.items[0].product_name:`${(l=r.items)==null?void 0:l.length} items`}),e.jsxs("p",{className:"font-semibold",children:["$",Number(r.total).toFixed(2)]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[r.tracking_url&&e.jsxs($,{variant:"outline",size:"sm",onClick:o=>{o.stopPropagation(),window.open(r.tracking_url,"_blank")},children:[e.jsx(Tr,{className:"h-4 w-4 mr-1"}),"Track"]}),e.jsx(Ja,{className:"h-5 w-5 text-muted-foreground"})]})]})]})},r.id)})})})}const Jvt=["order_submitted","awaiting_proof_approval","proof_approved","processing","in_production","shipped","completed"];function eFn({currentStatus:s,statusHistory:t}){const n=Jvt.indexOf(s);return e.jsx("div",{className:"space-y-3",children:Jvt.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(Fr,{className:"h-4 w-4"}):o?e.jsx(Hr,{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:_B[r]}),i&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:[Hs(new Date(i.created_at),"MMM d, yyyy h:mm a"),i.notes&&` — ${i.notes}`]})]})]},r)})})}function tFn(){var b;const{orderId:s}=Vi(),t=Vn(),{data:n,isLoading:r,refetch:a}=ZDn(s||""),i=JDn(),l=eRn(),[o,c]=j.useState(!1),[d,u]=j.useState(null),[h,m]=j.useState(""),[p,x]=j.useState(null),g=async v=>{x(v);try{await i.mutateAsync({orderId:s,itemId:v}),ae.success("Proof approved!"),a()}catch{ae.error("Failed to approve proof")}finally{x(null)}},y=async()=>{if(d){x(d);try{await l.mutateAsync({orderId:s,itemId:d,reason:h}),ae.success("Revision requested"),c(!1),m(""),u(null),a()}catch{ae.error("Failed to request revision")}finally{x(null)}}};return r?e.jsx(Ks,{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(on,{className:"h-64 w-full"}),e.jsx(on,{className:"h-48 w-full"})]}),e.jsx(on,{className:"h-96 w-full"})]})}):n?e.jsxs(Ks,{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(_e,{children:[e.jsxs(Bt,{className:"flex flex-row items-center justify-between",children:[e.jsx(Ut,{children:"Order Status"}),e.jsx($e,{className:pXe[n.status],children:_B[n.status]})]}),e.jsx(Oe,{children:e.jsx(eFn,{currentStatus:n.status,statusHistory:n.status_history})})]}),e.jsxs(_e,{children:[e.jsx(Bt,{children:e.jsx(Ut,{children:"Items"})}),e.jsx(Oe,{className:"space-y-4",children:(b=n.items)==null?void 0:b.map(v=>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:v.product_name}),v.variant_name&&e.jsx("p",{className:"text-sm text-muted-foreground",children:v.variant_name}),e.jsxs("p",{className:"text-sm",children:["Qty: ",v.quantity," × $",Number(v.unit_price).toFixed(2)]})]}),e.jsxs("p",{className:"font-semibold",children:["$",(Number(v.unit_price)*v.quantity).toFixed(2)]})]}),v.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:v.artwork_url,target:"_blank",rel:"noopener noreferrer",className:"inline-flex items-center gap-2 text-primary hover:underline",children:[e.jsx(gT,{className:"h-4 w-4"}),"View Artwork",e.jsx(Tr,{className:"h-3 w-3"})]})]}),v.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:v.proof_url,target:"_blank",rel:"noopener noreferrer",className:"inline-flex items-center gap-2 text-primary hover:underline mb-3",children:[e.jsx(gT,{className:"h-4 w-4"}),"View Proof",e.jsx(Tr,{className:"h-3 w-3"})]}),v.proof_status==="pending"&&e.jsxs("div",{className:"flex gap-2 mt-3",children:[e.jsxs($,{size:"sm",onClick:()=>g(v.id),disabled:p===v.id,children:[p===v.id?e.jsx(Ht,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(Ox,{className:"h-4 w-4 mr-1"}),"Approve"]}),e.jsxs($,{size:"sm",variant:"outline",onClick:()=>{u(v.id),c(!0)},disabled:p===v.id,children:[e.jsx(QK,{className:"h-4 w-4 mr-1"}),"Request Changes"]})]}),v.proof_status==="approved"&&e.jsxs($e,{className:"bg-green-100 text-green-800",children:[e.jsx(Fr,{className:"h-3 w-3 mr-1"}),"Proof Approved"]}),v.proof_status==="rejected"&&v.proof_notes&&e.jsxs("div",{className:"mt-2",children:[e.jsx($e,{variant:"destructive",className:"mb-2",children:"Revision Requested"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:v.proof_notes})]})]})]},v.id))})]}),n.shipping_name&&e.jsxs(_e,{children:[e.jsx(Bt,{children:e.jsxs(Ut,{className:"flex items-center gap-2",children:[e.jsx(JK,{className:"h-5 w-5"}),"Shipping"]})}),e.jsxs(Oe,{children:[e.jsx("p",{className:"font-medium",children:n.shipping_name}),e.jsxs("p",{className:"text-muted-foreground",children:[n.shipping_address,e.jsx("br",{}),n.shipping_city,", ",n.shipping_state," ",n.shipping_zip]}),n.tracking_number&&e.jsxs("div",{className:"mt-4 p-3 bg-muted rounded-lg",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Tracking Number:"}),e.jsx("p",{className:"font-mono font-medium",children:n.tracking_number}),n.tracking_url&&e.jsxs($,{variant:"link",className:"p-0 h-auto mt-1",onClick:()=>window.open(n.tracking_url,"_blank"),children:["Track Package",e.jsx(Tr,{className:"h-3 w-3 ml-1"})]})]})]})]})]}),e.jsx("div",{children:e.jsxs(_e,{className:"sticky top-4",children:[e.jsx(Bt,{children:e.jsx(Ut,{children:"Order Summary"})}),e.jsxs(Oe,{className:"space-y-4",children:[e.jsxs("div",{className:"text-sm text-muted-foreground",children:["Placed on ",Hs(new Date(n.created_at),"MMMM d, yyyy")]}),e.jsx(Hl,{}),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(Hl,{}),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(Hl,{}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium mb-1",children:"Order Notes"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:n.notes})]})]})]})]})})]}),e.jsx(Os,{open:o,onOpenChange:c,children:e.jsxs(Rs,{children:[e.jsxs(Us,{children:[e.jsx(zs,{children:"Request Changes"}),e.jsx(Sr,{children:"Please describe what changes you'd like made to the proof."})]}),e.jsx(Is,{placeholder:"Describe the changes needed...",value:h,onChange:v=>m(v.target.value),rows:4}),e.jsxs(kr,{children:[e.jsx($,{variant:"outline",onClick:()=>c(!1),children:"Cancel"}),e.jsxs($,{onClick:y,disabled:!h.trim()||p!==null,children:[p?e.jsx(Ht,{className:"h-4 w-4 mr-2 animate-spin"}):null,"Submit Request"]})]})]})})]}):e.jsx(Ks,{title:"Order Not Found",children:e.jsxs("div",{className:"text-center py-12",children:[e.jsx(Tu,{className:"h-16 w-16 mx-auto text-muted-foreground mb-4"}),e.jsx("p",{className:"text-muted-foreground mb-4",children:"Order not found"}),e.jsx($,{onClick:()=>t("/marketplace/orders"),children:"View All Orders"})]})})}function sFn(){const s=Vn(),[t]=oc();return t.get("session_id"),j.useEffect(()=>{localStorage.removeItem("marketplace-cart")},[]),e.jsx(Ks,{title:"Order Confirmed",children:e.jsx("div",{className:"max-w-lg mx-auto text-center py-8",children:e.jsx(_e,{children:e.jsxs(Oe,{className:"pt-8 pb-6",children:[e.jsx("div",{className:"w-16 h-16 bg-green-100 rounded-full flex items-center justify-center mx-auto mb-6",children:e.jsx(Fr,{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(Tu,{className:"h-4 w-4"}),"What happens next?"]}),e.jsxs("ul",{className:"text-sm text-muted-foreground space-y-2",children:[e.jsx("li",{children:"• We'll review your order and prepare it for production"}),e.jsx("li",{children:"• If your order requires a proof, you'll receive it for approval"}),e.jsx("li",{children:"• Once approved, we'll begin production and ship when ready"}),e.jsx("li",{children:"• You'll receive tracking info when your order ships"})]})]}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-3",children:[e.jsxs($,{className:"flex-1",onClick:()=>s("/marketplace/orders"),children:["View My Orders",e.jsx(ni,{className:"h-4 w-4 ml-2"})]}),e.jsx($,{variant:"outline",className:"flex-1",onClick:()=>s("/marketplace"),children:"Continue Shopping"})]})]})})})})}function nFn(){const{user:s}=_s(),[t,n]=j.useState("store"),[r,a]=j.useState(null),[i,l]=j.useState(null),[o,c]=j.useState(!1),[d,u]=j.useState(5),[h,m]=j.useState(""),[p,x]=j.useState(!1),[g,y]=j.useState(!1),[b,v]=j.useState(""),[N,C]=j.useState(null),[A,T]=j.useState(!1),{hasSubmittedReview:P,submitReview:M,markPostedToGoogle:I}=KCt(),{data:D}=MVt(),{data:B,isLoading:q}=TVt(),{data:W,isLoading:V}=oRn(r),{data:K,isLoading:Q}=lRn(s==null?void 0:s.id),{data:J=0}=dRn(s==null?void 0:s.id),ce=uRn(),ue=new Set((K==null?void 0:K.map(fe=>fe.item_id))||[]),ne=async()=>{if(i)try{const fe=await ce.mutateAsync(i.id);i.item_type==="reelflow_credits"?ae.success(`🎬 ${i.max_quantity} ReelFlow credits added to your balance!`):ae.success(`Successfully purchased "${i.name}"!`),l(null)}catch(fe){ae.error(fe.message||"Failed to purchase item")}},ee=async()=>{if(!h.trim()){ae.error("Please write a review");return}x(!0);const fe=await M(d,h);x(!1),fe.success?(ae.success("Thank you for your review! You earned 25 points!"),v(h),y(!0),m(""),u(5)):ae.error(fe.error||"Failed to submit review")},le=()=>{navigator.clipboard.writeText(b),ae.success("Review copied to clipboard!")},he=()=>{I(),window.open("https://g.page/r/CT8bqTBTm7nJEBM/review","_blank")},ve=()=>{y(!1),c(!1),v("")};return q||V||Q?e.jsx(Ks,{title:"Reward Store",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(on,{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(fe=>e.jsx(on,{className:"h-64"},fe))})]})}):e.jsxs(Ks,{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(_e,{className:"bg-gradient-to-r from-primary/10 to-primary/5 border-primary/20",children:e.jsx(Oe,{className:"pt-6",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx("div",{className:"h-12 w-12 rounded-full bg-primary/20 flex items-center justify-center",children:e.jsx(Qa,{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:J.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(pl,{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(yd,{className:"h-4 w-4 text-orange-500"}),e.jsx("span",{children:"Streak bonuses add extra points!"})]})]})]})})}),e.jsx(uv,{open:A,onOpenChange:T,children:e.jsxs(_e,{className:"border-primary/20",children:[e.jsx(hv,{asChild:!0,children:e.jsx(Bt,{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(pl,{className:"h-5 w-5 text-primary"})}),e.jsxs("div",{children:[e.jsx(Ut,{className:"text-base",children:"How to Earn Points"}),e.jsx(vr,{children:"See all the ways you can earn spendable points"})]})]}),A?e.jsx(jg,{className:"h-5 w-5 text-muted-foreground"}):e.jsx(_o,{className:"h-5 w-5 text-muted-foreground"})]})})}),e.jsx(mv,{children:e.jsx(Oe,{className:"pt-0",children:e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-3",children:[D==null?void 0:D.filter(fe=>fe.is_active).map(fe=>{const je=Ee=>{switch(Ee){case"event_attendance":return e.jsx(ia,{className:"h-5 w-5"});case"leave_review":return e.jsx(Qa,{className:"h-5 w-5"});case"add_listing":return e.jsx(sa,{className:"h-5 w-5"});case"first_contact":return e.jsx(qn,{className:"h-5 w-5"});case"first_video":return e.jsx(Xr,{className:"h-5 w-5"});case"first_community_post":return e.jsx(Ji,{className:"h-5 w-5"});default:return e.jsx(Co,{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:je(fe.action_key)}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"font-medium text-sm",children:fe.action_name}),fe.description&&e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:fe.description})]}),e.jsxs($e,{variant:"secondary",className:"font-bold shrink-0",children:["+",fe.points]})]},fe.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(yd,{className:"h-5 w-5"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"font-medium text-sm",children:"Streak Bonuses"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Attend consecutive weeks for bonus points!"})]}),e.jsx($e,{variant:"outline",className:"font-bold shrink-0 border-orange-500/50 text-orange-600",children:"+Bonus"})]})]})})})]})}),!P&&e.jsx(_e,{className:"bg-gradient-to-r from-yellow-500/10 to-orange-500/10 border-yellow-500/20",children:e.jsx(Oe,{className:"pt-6",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx("div",{className:"h-12 w-12 rounded-full bg-yellow-500/20 flex items-center justify-center",children:e.jsx(Ji,{className:"h-6 w-6 text-yellow-600"})}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:"Earn 25 Free Points!"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Leave a quick review and earn 25 spendable points"})]})]}),e.jsxs($,{onClick:()=>c(!0),className:"bg-yellow-600 hover:bg-yellow-700",children:[e.jsx(Qa,{className:"h-4 w-4 mr-2"}),"Leave Review"]})]})})}),e.jsxs(ua,{value:t,onValueChange:n,children:[e.jsxs(ha,{children:[e.jsxs(Qt,{value:"store",className:"flex items-center gap-2",children:[e.jsx(l5,{className:"h-4 w-4"}),"Store"]}),e.jsxs(Qt,{value:"my-rewards",className:"flex items-center gap-2",children:[e.jsx(Tu,{className:"h-4 w-4"}),"My Rewards",K&&K.length>0&&e.jsx($e,{variant:"secondary",className:"ml-1",children:K.length})]})]}),e.jsxs(Jt,{value:"store",className:"mt-6",children:[B&&B.length>0&&e.jsxs("div",{className:"flex flex-wrap gap-2 mb-6",children:[e.jsx($,{variant:r===null?"default":"outline",size:"sm",onClick:()=>a(null),children:"All"}),B.map(fe=>e.jsxs($,{variant:r===fe.id?"default":"outline",size:"sm",onClick:()=>a(fe.id),children:[fe.icon&&`${fe.icon} `,fe.name]},fe.id))]}),!W||W.length===0?e.jsx(_e,{children:e.jsx(Oe,{className:"py-12",children:e.jsxs("div",{className:"text-center text-muted-foreground",children:[e.jsx(Co,{className:"h-12 w-12 mx-auto mb-4 opacity-50"}),e.jsx("p",{className:"font-medium",children:"No items available"}),e.jsx("p",{className:"text-sm",children:"Check back later for new rewards!"})]})})}):e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:W.map(fe=>{const je=fe.item_type==="reelflow_credits",Ee=!je&&ue.has(fe.id),Me=!je&&fe.max_quantity!==null&&fe.current_quantity===0,De=J>=fe.points_cost;return e.jsxs(_e,{className:`overflow-hidden transition-all cursor-pointer hover:shadow-lg ${Ee?"ring-2 ring-green-500/50 bg-green-500/5":""}`,onClick:()=>C(fe),children:[fe.preview_image_url?e.jsxs("div",{className:"aspect-video relative overflow-hidden bg-muted",children:[e.jsx("img",{src:fe.preview_image_url,alt:fe.name,className:"w-full h-full object-cover"}),Ee&&e.jsx("div",{className:"absolute top-2 right-2",children:e.jsxs($e,{className:"bg-green-500 text-white",children:[e.jsx(Fr,{className:"h-3 w-3 mr-1"}),"Owned"]})}),Me&&!Ee&&e.jsx("div",{className:"absolute inset-0 bg-black/50 flex items-center justify-center",children:e.jsx($e,{variant:"destructive",children:"Sold Out"})})]}):e.jsxs("div",{className:"aspect-video bg-muted flex items-center justify-center relative",children:[e.jsx(Co,{className:"h-12 w-12 text-muted-foreground/50"}),Ee&&e.jsx("div",{className:"absolute top-2 right-2",children:e.jsxs($e,{className:"bg-green-500 text-white",children:[e.jsx(Fr,{className:"h-3 w-3 mr-1"}),"Owned"]})})]}),e.jsxs(Bt,{className:"pb-2",children:[e.jsxs("div",{className:"flex items-start justify-between",children:[e.jsx(Ut,{className:"text-lg",children:fe.name}),e.jsxs($e,{variant:"secondary",className:"font-bold shrink-0",children:[e.jsx(Qa,{className:"h-3 w-3 mr-1"}),fe.points_cost]})]}),fe.category&&e.jsxs($e,{variant:"outline",className:"w-fit",children:[fe.category.icon&&`${fe.category.icon} `,fe.category.name]})]}),e.jsxs(Oe,{children:[e.jsx(vr,{className:"mb-4 line-clamp-2",children:fe.description||"No description available"}),fe.max_quantity!==null&&!Ee&&!je&&e.jsxs("p",{className:"text-xs text-muted-foreground mb-3",children:[fe.current_quantity," of ",fe.max_quantity," remaining"]}),je&&e.jsxs("p",{className:"text-xs text-violet-600 font-medium mb-3",children:["🎬 Grants ",fe.max_quantity," ReelFlow credits per purchase"]}),Ee?e.jsx($,{className:"w-full",onClick:ze=>{ze.stopPropagation(),fe.file_url&&jDe(fe.file_url,fe.name)},disabled:!fe.file_url,children:fe.item_type==="file"?e.jsxs(e.Fragment,{children:[e.jsx(di,{className:"h-4 w-4 mr-2"}),"Download"]}):e.jsxs(e.Fragment,{children:[e.jsx(Tr,{className:"h-4 w-4 mr-2"}),"Access"]})}):e.jsx($,{className:"w-full",onClick:ze=>{ze.stopPropagation(),l(fe)},disabled:Me||!De,children:Me?"Sold Out":De?e.jsxs(e.Fragment,{children:[e.jsx(l5,{className:"h-4 w-4 mr-2"}),"Purchase"]}):`Need ${fe.points_cost-J} more pts`})]})]},fe.id)})})]}),e.jsx(Jt,{value:"my-rewards",className:"mt-6",children:!K||K.length===0?e.jsx(_e,{children:e.jsx(Oe,{className:"py-12",children:e.jsxs("div",{className:"text-center text-muted-foreground",children:[e.jsx(Tu,{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(fe=>{var je,Ee,Me,De,ze,ke,Xe;return e.jsxs(_e,{className:"overflow-hidden",children:[(je=fe.item)!=null&&je.preview_image_url?e.jsx("div",{className:"aspect-video relative overflow-hidden bg-muted",children:e.jsx("img",{src:fe.item.preview_image_url,alt:((Ee=fe.item)==null?void 0:Ee.name)||"Reward",className:"w-full h-full object-cover"})}):e.jsx("div",{className:"aspect-video bg-muted flex items-center justify-center",children:e.jsx(Co,{className:"h-12 w-12 text-muted-foreground/50"})}),e.jsxs(Bt,{className:"pb-2",children:[e.jsx(Ut,{className:"text-lg",children:((Me=fe.item)==null?void 0:Me.name)||"Unknown Item"}),e.jsxs(vr,{className:"text-xs",children:["Purchased for ",fe.points_spent," points • ",new Date(fe.purchased_at).toLocaleDateString()]})]}),e.jsx(Oe,{children:((De=fe.item)==null?void 0:De.item_type)==="reelflow_credits"?e.jsxs($,{className:"w-full",variant:"outline",disabled:!0,children:[e.jsx(Fr,{className:"h-4 w-4 mr-2 text-green-500"}),(ze=fe.item)==null?void 0:ze.max_quantity," Credits Applied"]}):e.jsx($,{className:"w-full",onClick:()=>{var Se,Re;(Se=fe.item)!=null&&Se.file_url&&jDe(fe.item.file_url,(Re=fe.item)==null?void 0:Re.name)},disabled:!((ke=fe.item)!=null&&ke.file_url),children:((Xe=fe.item)==null?void 0:Xe.item_type)==="file"?e.jsxs(e.Fragment,{children:[e.jsx(di,{className:"h-4 w-4 mr-2"}),"Download"]}):e.jsxs(e.Fragment,{children:[e.jsx(Tr,{className:"h-4 w-4 mr-2"}),"Access"]})})})]},fe.id)})})})]})]}),e.jsx(Ll,{open:!!i,onOpenChange:()=>l(null),children:e.jsxs(yl,{children:[e.jsxs(vl,{children:[e.jsx(_l,{children:"Confirm Purchase"}),e.jsxs(wl,{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:[J," points"]}),". After this purchase, you'll have"," ",e.jsxs("strong",{children:[J-((i==null?void 0:i.points_cost)||0)," points"]})," remaining."]})]}),e.jsxs(bl,{children:[e.jsx(jl,{children:"Cancel"}),e.jsx(fl,{onClick:ne,disabled:ce.isPending,children:ce.isPending?"Purchasing...":"Confirm Purchase"})]})]})}),e.jsx(Os,{open:o,onOpenChange:fe=>{!fe&&g?ve():c(fe)},children:e.jsx(Rs,{children:g?e.jsxs(e.Fragment,{children:[e.jsxs(Us,{children:[e.jsxs(zs,{className:"flex items-center gap-2",children:[e.jsx(Fr,{className:"h-5 w-5 text-green-500"}),"Thank You for Your Review!"]}),e.jsx(Sr,{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:['"',b,'"']})]}),e.jsxs($,{variant:"outline",className:"w-full",onClick:le,children:[e.jsx(Ca,{className:"h-4 w-4 mr-2"}),"Copy Review to Clipboard"]})]}),e.jsxs(kr,{className:"flex-col sm:flex-row gap-2",children:[e.jsx($,{variant:"outline",onClick:ve,children:"Maybe Later"}),e.jsxs($,{onClick:he,className:"bg-blue-600 hover:bg-blue-700",children:[e.jsx(Tr,{className:"h-4 w-4 mr-2"}),"Leave Google Review"]})]})]}):e.jsxs(e.Fragment,{children:[e.jsxs(Us,{children:[e.jsx(zs,{children:"Leave a Review"}),e.jsx(Sr,{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(fe=>e.jsx("button",{type:"button",onClick:()=>u(fe),className:"focus:outline-none",children:e.jsx(Qa,{className:`h-8 w-8 transition-colors ${d>=fe?"fill-yellow-400 text-yellow-400":"text-muted-foreground hover:text-yellow-400"}`})},fe))})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium mb-2 block",children:"Your Review"}),e.jsx(Is,{placeholder:"What do you love about LevelUp? How has it helped your business?",value:h,onChange:fe=>m(fe.target.value),rows:4})]})]}),e.jsxs(kr,{children:[e.jsx($,{variant:"outline",onClick:()=>c(!1),children:"Cancel"}),e.jsx($,{onClick:ee,disabled:p,className:"bg-yellow-600 hover:bg-yellow-700",children:p?"Submitting...":"Submit & Earn 25 Points"})]})]})})}),e.jsx(Os,{open:!!N,onOpenChange:()=>C(null),children:e.jsxs(Rs,{className:"max-w-lg",children:[e.jsxs(Us,{children:[e.jsxs(zs,{className:"flex items-center gap-2",children:[N==null?void 0:N.name,e.jsxs($e,{variant:"secondary",className:"font-bold",children:[e.jsx(Qa,{className:"h-3 w-3 mr-1"}),N==null?void 0:N.points_cost]})]}),(N==null?void 0:N.category)&&e.jsxs($e,{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(kr,{children:N&&N.item_type!=="reelflow_credits"&&ue.has(N.id)?e.jsx($,{className:"w-full",onClick:()=>{N.file_url&&jDe(N.file_url,N.name)},disabled:!N.file_url,children:N.item_type==="file"?e.jsxs(e.Fragment,{children:[e.jsx(di,{className:"h-4 w-4 mr-2"}),"Download"]}):e.jsxs(e.Fragment,{children:[e.jsx(Tr,{className:"h-4 w-4 mr-2"}),"Access"]})}):N&&e.jsx($,{className:"w-full",onClick:()=>{C(null),l(N)},disabled:N.item_type!=="reelflow_credits"&&N.max_quantity!==null&&N.current_quantity===0||J{s&&Q()},[s==null?void 0:s.id]);const Q=async()=>{if(!s)return;o(!0),b(!1),g(!0);const{data:ze}=await U.from("point_reward_settings").select("action_key, points").in("action_key",["referral_signup","referral_paid"]);ze==null||ze.forEach(Re=>{Re.action_key==="referral_signup"&&h(Re.points),Re.action_key==="referral_paid"&&p(Re.points)});const{data:ke}=await U.from("profiles").select("name").eq("id",s.id).maybeSingle();ke!=null&&ke.name&&N(ke.name);let{data:Xe}=await U.from("agent_referral_codes").select("code").eq("user_id",s.id).maybeSingle();if(!Xe){const{data:Re}=await U.rpc("generate_agent_referral_code",{_user_id:s.id}),Ae=Re||`agent${s.id.slice(0,6)}`,{data:Be,error:qe}=await U.from("agent_referral_codes").insert({user_id:s.id,code:Ae}).select("code").maybeSingle();!qe&&Be&&(Xe=Be)}i((Xe==null?void 0:Xe.code)??null);const{data:Se}=await U.from("agent_referrals").select("id, referred_user_id, status, signed_up_at, qualified_at, signup_points_awarded, paid_points_awarded").eq("referrer_user_id",s.id).order("signed_up_at",{ascending:!1});if(Se&&Se.length>0){const Re=Se.map(qe=>qe.referred_user_id),{data:Ae}=await U.from("profiles").select("id, name, email").in("id",Re),Be=new Map((Ae==null?void 0:Ae.map(qe=>[qe.id,qe]))??[]);d(Se.map(qe=>({...qe,referred_profile:Be.get(qe.referred_user_id)??null})))}else d([]);o(!1)},J=j.useMemo(()=>a?`${rFn}/trial?ref=${a}`:"",[a]),ce=c.length,ue=c.filter(ze=>ze.status==="qualified").length,ne=c.filter(ze=>ze.signup_points_awarded).length*u+c.filter(ze=>ze.paid_points_awarded).length*m,ee=async()=>{J&&(await navigator.clipboard.writeText(J),ae.success("Referral link copied!"))},le=()=>{const ze=encodeURIComponent("Join me on LevelUp"),ke=encodeURIComponent(`Hi — I've been using LevelUp to grow my real estate business and thought you'd love it too. Sign up using my link and we'll both get a head start: ${J} Let me know if you have any questions!`);window.location.href=`mailto:?subject=${ze}&body=${ke}`},he=()=>{const ze=encodeURIComponent(`Hey! I think you'd love LevelUp for your business — sign up with my link: ${J}`);window.location.href=`sms:?&body=${ze}`},ve=async()=>{if(navigator.share&&J)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:J})}catch{}else ee()},ge=ze=>/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(ze.trim()),fe=ze=>{const ke=(ze??T).trim().replace(/,$/,"");if(!ke)return;const Xe=ke.split(/[\s,;]+/).filter(Boolean),Se=[...M];let Re=0;for(const Ae of Xe){if(!ge(Ae)){ae.error(`Invalid email: ${Ae}`);continue}Se.includes(Ae)||(Se.push(Ae),Re++)}I(Se),Re>0&&P("")},je=ze=>I(M.filter(ke=>ke!==ze)),Ee=()=>{W(`${v?v.split(" ")[0]+" invited you to":"Join me on"} LevelUp`),B("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)},Me=ze=>{const ke=ze.replace(/&/g,"&").replace(//g,">").replace(/\n/g,"
"),Xe=v||"A fellow agent",Se="https://relzejiswnotikjgvjhz.supabase.co/storage/v1/object/public/email-assets/levelup-logo-email.png",Re=J;return`
LevelUp
You're Invited

${Xe} thinks you'd love LevelUp 🎉

${ke}

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

Or copy & paste this link:
${Re}

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

`.trim()},De=async()=>{if(M.length===0&&(T.trim()&&fe(),M.length===0)){ae.error("Add at least one recipient");return}if(!q.trim()){ae.error("Subject is required");return}K(!0);const ze=Me(D);let ke=0,Xe=0;for(const Se of M)try{const{data:Re,error:Ae}=await U.functions.invoke("gmail-send",{body:{to:Se,subject:q,body:ze,source:"referral_invite"}});if(Ae||Re!=null&&Re.error)throw new Error((Ae==null?void 0:Ae.message)||(Re==null?void 0:Re.error));ke++}catch(Re){console.error("Gmail send failed for",Se,Re),Xe++}K(!1),ke>0?(ae.success(`Invite sent to ${ke} ${ke===1?"person":"people"}`+(Xe>0?` (${Xe} failed)`:"")),I([]),P(""),A(!1)):ae.error("Failed to send invites")};return!y&&!x?e.jsx(Ks,{title:"Refer & Earn",children:e.jsxs("div",{className:"container max-w-3xl mx-auto p-4 md:p-8",children:[e.jsx(Ul,{children:e.jsx("title",{children:"Refer & Earn | LevelUp"})}),e.jsxs(_e,{className:"border-2 border-dashed",children:[e.jsxs(Bt,{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(Ad,{className:"h-6 w-6 text-muted-foreground"})}),e.jsx(Ut,{children:"Refer & Earn is for active members"}),e.jsx(vr,{children:"Activate your subscription to unlock your personal referral link and start earning points."})]}),e.jsx(Oe,{className:"flex justify-center",children:e.jsx($,{onClick:()=>t("/subscription"),children:"View Subscription"})})]})]})}):e.jsxs(Ks,{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(Ul,{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(Co,{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(_e,{children:e.jsxs(Oe,{className:"p-4 flex items-center gap-3",children:[e.jsx(qn,{className:"h-5 w-5 text-muted-foreground"}),e.jsxs("div",{children:[e.jsx("div",{className:"text-2xl font-bold",children:ce}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Friends signed up"})]})]})}),e.jsx(_e,{children:e.jsxs(Oe,{className:"p-4 flex items-center gap-3",children:[e.jsx(Fr,{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(_e,{children:e.jsxs(Oe,{className:"p-4 flex items-center gap-3",children:[e.jsx(pl,{className:"h-5 w-5 text-amber-500"}),e.jsxs("div",{children:[e.jsx("div",{className:"text-2xl font-bold",children:ne.toLocaleString()}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Points earned"})]})]})})]}),e.jsxs(_e,{children:[e.jsxs(Bt,{children:[e.jsxs(Ut,{className:"flex items-center gap-2",children:[e.jsx(dn,{className:"h-5 w-5 text-primary"}),"Your referral link"]}),e.jsx(vr,{children:"Anyone who signs up through this link is credited to you."})]}),e.jsxs(Oe,{className:"space-y-4",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row gap-2",children:[e.jsx(be,{readOnly:!0,value:l?"Loading…":J,className:"font-mono text-sm",onFocus:ze=>ze.currentTarget.select()}),e.jsxs($,{onClick:ee,disabled:!J,children:[e.jsx(Ca,{className:"h-4 w-4 mr-2"}),"Copy link"]})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[n&&e.jsxs($,{size:"sm",onClick:Ee,disabled:!J,className:"bg-primary hover:bg-primary/90",children:[e.jsx(Br,{className:"h-4 w-4 mr-2"})," Send via Gmail"]}),e.jsxs($,{variant:"outline",size:"sm",onClick:le,disabled:!J,children:[e.jsx(nn,{className:"h-4 w-4 mr-2"})," Email"]}),e.jsxs($,{variant:"outline",size:"sm",onClick:he,disabled:!J,children:[e.jsx(Ji,{className:"h-4 w-4 mr-2"})," Text"]}),e.jsxs($,{variant:"outline",size:"sm",onClick:ve,disabled:!J,children:[e.jsx(vd,{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(_e,{children:[e.jsxs(Bt,{children:[e.jsx(Ut,{children:"Your Referrals"}),e.jsx(vr,{children:"Track who joined and when they upgrade."})]}),e.jsx(Oe,{children:l?e.jsx("p",{className:"text-sm text-muted-foreground py-6 text-center",children:"Loading…"}):c.length===0?e.jsxs("div",{className:"text-center py-10 space-y-2",children:[e.jsx(qn,{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(ze=>{var Se,Re;const ke=((Se=ze.referred_profile)==null?void 0:Se.name)||((Re=ze.referred_profile)==null?void 0:Re.email)||"New agent",Xe=new Intl.DateTimeFormat("en-US",{timeZone:"America/New_York",month:"short",day:"numeric",year:"numeric"}).format(new Date(ze.signed_up_at));return e.jsxs("div",{className:"py-3 flex items-center justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"font-medium truncate",children:ke}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:["Joined ",Xe]})]}),ze.status==="qualified"?e.jsxs($e,{className:"bg-emerald-100 text-emerald-700 border-emerald-200 hover:bg-emerald-100",children:[e.jsx(Fr,{className:"h-3 w-3 mr-1"})," Paid · +",u+m," pts"]}):e.jsxs($e,{variant:"secondary",children:[e.jsx(Hr,{className:"h-3 w-3 mr-1"})," Signed up · +",u," pts"]})]},ze.id)})})})]}),e.jsx(_e,{className:"bg-muted/30",children:e.jsxs(Oe,{className:"p-6",children:[e.jsxs("h3",{className:"font-semibold mb-3 flex items-center gap-2",children:[e.jsx(dn,{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(Hl,{className:"opacity-0"})]}),e.jsx(Os,{open:C,onOpenChange:A,children:e.jsxs(Rs,{className:"sm:max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsxs(Us,{children:[e.jsxs(zs,{className:"flex items-center gap-2",children:[e.jsx(Br,{className:"h-5 w-5 text-primary"})," Send referral invites via Gmail"]}),e.jsxs(Sr,{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(se,{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(ze=>e.jsxs($e,{variant:"secondary",className:"gap-1 pr-1",children:[ze,e.jsx("button",{type:"button",onClick:()=>je(ze),className:"hover:bg-muted-foreground/20 rounded-full p-0.5","aria-label":`Remove ${ze}`,children:e.jsx(pr,{className:"h-3 w-3"})})]},ze)),e.jsx("input",{type:"email",value:T,onChange:ze=>P(ze.target.value),onKeyDown:ze=>{ze.key==="Enter"||ze.key===","||ze.key===" "?(ze.preventDefault(),fe()):ze.key==="Backspace"&&!T&&M.length>0&&I(M.slice(0,-1))},onBlur:()=>T.trim()&&fe(),onPaste:ze=>{const ke=ze.clipboardData.getData("text");/[\s,;]/.test(ke)&&(ze.preventDefault(),fe(ke))},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(se,{htmlFor:"email-subject",children:"Subject"}),e.jsx(be,{id:"email-subject",value:q,onChange:ze=>W(ze.target.value),placeholder:"Subject line"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"personal-note",children:"Your personal note"}),e.jsx(Is,{id:"personal-note",value:D,onChange:ze=>B(ze.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(se,{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: ",q||"(no subject)"]})]}),e.jsx("iframe",{title:"Email preview",srcDoc:Me(D),className:"w-full h-[420px] bg-white"})]})]})]}),e.jsxs(kr,{children:[e.jsx($,{variant:"outline",onClick:()=>A(!1),disabled:V,children:"Cancel"}),e.jsxs($,{onClick:De,disabled:V,children:[e.jsx(Br,{className:"h-4 w-4 mr-2"}),V?"Sending…":`Send${M.length>0?` to ${M.length}`:""}`]})]})]})})]})}const iHt=()=>{const{user:s}=_s(),t=ts(),n=ht({queryKey:["smart-presentations",s==null?void 0:s.id],queryFn:async()=>{const{data:d,error:u}=await U.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=ht({queryKey:["smart-presentation-templates",s==null?void 0:s.id],queryFn:async()=>{const{data:d,error:u}=await U.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 U.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 U.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 U.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"]}),ae.success("Presentation published!")}}),o=yt({mutationFn:async d=>{const{error:u}=await U.from("smart_presentations").update({status:"archived"}).eq("id",d);if(u)throw u},onSuccess:()=>{t.invalidateQueries({queryKey:["smart-presentations"]}),ae.success("Presentation archived")}}),c=yt({mutationFn:async d=>{const{error:u}=await U.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"]}),ae.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}},iFn=()=>{const s=Vn(),{presentations:t,isLoading:n,archivePresentation:r,saveAsTemplate:a}=iHt(),i=o=>o.status==="draft"?e.jsx($e,{variant:"outline",className:"text-xs",children:"Draft"}):o.view_count>1?e.jsx($e,{className:"text-xs bg-emerald-100 text-emerald-700 border-emerald-200",children:"Revisited"}):o.view_count===1?e.jsx($e,{className:"text-xs bg-blue-100 text-blue-700 border-blue-200",children:"Opened"}):e.jsx($e,{variant:"secondary",className:"text-xs",children:"Not Opened"}),l=o=>{const c=`https://presentations.relevelup.com/${o}`;navigator.clipboard.writeText(c),ae.success("Link copied!")};return e.jsx(Ks,{title:"Smart Presentations",children:e.jsxs("div",{className:"max-w-5xl mx-auto space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsx("h1",{className:"text-2xl font-serif font-bold text-foreground",children:"Smart Presentations"})}),e.jsx("p",{className:"text-muted-foreground mt-1",children:"Create personalized, video-first presentations for your clients"})]}),e.jsxs($,{onClick:()=>s("/mission-control/presentations/new"),className:"gap-2",children:[e.jsx(sn,{className:"h-4 w-4"}),"Create Presentation"]})]}),n?e.jsx("div",{className:"space-y-3",children:[1,2,3].map(o=>e.jsx(on,{className:"h-20 w-full rounded-lg"},o))}):t.length===0?e.jsx(_e,{children:e.jsxs(Oe,{className:"flex flex-col items-center justify-center py-16 text-center",children:[e.jsx("div",{className:"w-16 h-16 rounded-full bg-primary/10 flex items-center justify-center mb-4",children:e.jsx(by,{className:"h-8 w-8 text-primary"})}),e.jsx("h3",{className:"text-lg font-semibold mb-2",children:"No presentations yet"}),e.jsx("p",{className:"text-muted-foreground mb-6 max-w-md",children:"Create your first Smart Presentation to impress clients with personalized, video-first content."}),e.jsxs($,{onClick:()=>s("/mission-control/presentations/new"),className:"gap-2",children:[e.jsx(sn,{className:"h-4 w-4"}),"Create Your First Presentation"]})]})}):e.jsx("div",{className:"space-y-3",children:t.map(o=>e.jsx(_e,{className:"hover:shadow-sm transition-shadow",children:e.jsx(Oe,{className:"p-4",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:"w-10 h-10 rounded-lg bg-primary/10 flex items-center justify-center shrink-0",children:e.jsx(Wr,{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 ",Hs(new Date(o.created_at),"MMM d, yyyy")]}),o.view_count>0&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(ga,{className:"h-3 w-3"})," ",o.view_count," view",o.view_count!==1?"s":""]}),o.cta_clicked_count>0&&e.jsx("span",{className:"text-emerald-600 font-medium",children:"CTA clicked"})]})]}),e.jsxs("div",{className:"flex items-center gap-2 flex-wrap sm:flex-nowrap sm:shrink-0",children:[o.status==="published"&&o.share_token&&e.jsxs($,{variant:"outline",size:"sm",onClick:()=>l(o.share_token),children:[e.jsx(Ca,{className:"h-3.5 w-3.5 mr-1"}),"Copy Link"]}),o.status==="published"&&e.jsx($,{variant:"outline",size:"sm",onClick:()=>s(`/mission-control/presentations/${o.id}?edit=true`),children:"Edit"}),e.jsx($,{variant:"outline",size:"sm",onClick:()=>s(`/mission-control/presentations/${o.id}`),children:o.status==="draft"?"Edit":"View"}),e.jsxs(Hd,{children:[e.jsx(Gd,{asChild:!0,children:e.jsx($,{variant:"ghost",size:"icon",className:"h-8 w-8",children:e.jsx(cy,{className:"h-4 w-4"})})}),e.jsxs(Md,{align:"end",children:[o.status==="published"&&o.share_token&&e.jsxs(Na,{onClick:()=>window.open(`https://presentations.relevelup.com/${o.share_token}`,"_blank"),children:[e.jsx(Tr,{className:"h-4 w-4 mr-2"}),"Preview Link"]}),e.jsxs(Na,{onClick:()=>a.mutate(o),children:[e.jsx(Wr,{className:"h-4 w-4 mr-2"}),"Save as Template"]}),e.jsxs(Na,{onClick:()=>r.mutate(o.id),className:"text-destructive",children:[e.jsx(Am,{className:"h-4 w-4 mr-2"}),"Archive"]})]})]})]})]})})]})})},o.id))})]})})},e1t={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."}]},oFn=[{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 lFn(s){const t=e1t[s];if(t)return t;const n=s.toLowerCase();for(const[r,a]of Object.entries(e1t))if(n.includes(r.toLowerCase())||r.toLowerCase().includes(n))return a;return oFn}function cFn({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}=I7t(),m=F5(),[p,x]=j.useState(""),[g,y]=j.useState(!1),[b,v]=j.useState(!0),[N,C]=j.useState(!1),[A,T]=j.useState(null),P=lFn(s),M=()=>{l("script"),c(0),u(0),x(""),y(!1),v(!0),C(!1),T(null)},I=V=>{!V&&(i==="uploading"||i==="processing")||(a(V),V||M())},D=V=>{T(V),x(P[V].text),y(!1)},B=()=>{l("record"),v(p.trim().length>0)},q=()=>{x(""),v(!1),l("record")},W=j.useCallback(async(V,K)=>{l("uploading");try{const Q=s||"Presentation Video",{videoId:J,uploadUrl:ce,libraryId:ue}=await Z6(Q),{apiKey:ne}=await X6(J),ee=new XMLHttpRequest;ee.upload.onprogress=fe=>{fe.lengthComputable&&c(fe.loaded/fe.total*100)},await new Promise((fe,je)=>{ee.onload=()=>ee.status>=200&&ee.status<300?fe():je(new Error("Upload failed")),ee.onerror=()=>je(new Error("Upload failed")),ee.open("PUT",ce),ee.setRequestHeader("AccessKey",ne),ee.send(V)}),l("processing");let le=0;const he=Date.now(),ve=9e4;let ge=null;for(;le<4;){if(await new Promise(je=>setTimeout(je,3e3)),Date.now()-he>ve){const je=V.size/1048576,Ee=`https://iframe.mediadelivery.net/embed/${ue}/${J}?responsive=true`;await m.mutateAsync({bunny_video_id:J,playback_url:Ee,file_size_mb:je,title:Q,contact_id:t||void 0,status:"processing",touch_type:"presentation"}),n(Ee),ae.success("Video saved — still encoding. It will be ready shortly."),l("done"),setTimeout(()=>a(!1),1500);return}const fe=await o2(J);if(le=fe.status,u(fe.encodeProgress||0),le===4)ge={playbackUrl:fe.directPlayUrl,thumbnailUrl:fe.thumbnailUrl,previewUrl:fe.previewUrl||null,duration:fe.length||K,fileSizeMb:(fe.storageSize||V.size)/(1024*1024)};else if(le===5||le===6)throw new Error("Video processing failed")}if(!ge)throw new Error("No video data");await m.mutateAsync({bunny_video_id:J,contact_id:t||void 0,playback_url:ge.playbackUrl,thumbnail_url:ge.thumbnailUrl,preview_url:ge.previewUrl,duration_seconds:ge.duration,file_size_mb:ge.fileSizeMb,title:Q,status:"ready",touch_type:"presentation"}),n(ge.playbackUrl),ae.success("Video recorded, saved to library & attached!"),l("done"),setTimeout(()=>a(!1),1500)}catch(Q){console.error("Recording upload error:",Q),ae.error("Failed to process video. Please try again."),l("record")}},[s,t,n,m]);return e.jsxs(Os,{open:r,onOpenChange:I,children:[e.jsx(Ko,{asChild:!0,children:e.jsxs($,{variant:"outline",size:"sm",className:"gap-1.5 shrink-0",title:"Record a video",children:[e.jsx(Xr,{className:"h-3.5 w-3.5"}),"Record"]})}),e.jsxs(Rs,{className:"max-w-2xl max-h-[90vh] overflow-y-auto !top-[5%] !translate-y-0 sm:!top-[5%] sm:!translate-y-0",children:[e.jsx(Us,{children:e.jsxs(zs,{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:P.map((V,K)=>e.jsxs("button",{onClick:()=>D(K),className:Tt("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(Wr,{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"}),!g&&e.jsxs($,{variant:"ghost",size:"sm",onClick:()=>y(!0),className:"h-7 text-xs gap-1",children:[e.jsx(Ya,{className:"h-3 w-3"}),"Edit"]})]}),g?e.jsx(Is,{value:p,onChange:V=>x(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(Is,{value:p,onChange:V=>{x(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($,{variant:"ghost",size:"sm",onClick:q,className:"text-muted-foreground",children:"Skip — no teleprompter"}),e.jsx($,{onClick:B,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(mc,{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($,{variant:"ghost",size:"sm",onClick:()=>v(!b),className:"h-7 text-xs gap-1",children:[b?e.jsx(b0,{className:"h-3 w-3"}):e.jsx(ga,{className:"h-3 w-3"}),b?"Hide Script":"Show Script"]})]}),e.jsx(J6,{maxDurationSeconds:600,onRecordingComplete:W,onRecordingStateChange:C,onError:V=>ae.error(V),teleprompterContent:p.trim()?e.jsx(lXe,{text:p,isVisible:b,onToggleVisibility:()=>v(!b),isRecording:N,startCountdown:!1}):void 0}),e.jsx($,{variant:"ghost",size:"sm",onClick:()=>l("script"),className:"text-xs text-muted-foreground",children:"← Back to script"})]}):i==="uploading"?e.jsxs("div",{className:"flex flex-col items-center gap-4 py-12",children:[e.jsx(Ht,{className:"h-10 w-10 animate-spin text-primary"}),e.jsxs("div",{className:"w-full max-w-xs space-y-2",children:[e.jsx(Ki,{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(Ht,{className:"h-10 w-10 animate-spin text-primary"}),e.jsxs("div",{className:"w-full max-w-xs space-y-2",children:[e.jsx(Ki,{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(Ro,{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 dFn({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=F5(),{data:p}=WEe(),x=(p==null?void 0:p.total_storage_mb)||0,y=((p==null?void 0:p.max_storage_mb)||1024)-x,b=()=>{l(null),c("idle"),u(0)},v=P=>{!P&&o!=="idle"&&o!=="done"||(a(P),P||b())},N=P=>{var D;const M=(D=P.target.files)==null?void 0:D[0];if(!M)return;if(!M.type.startsWith("video/")){ae.error("Please select a video file");return}const I=M.size/(1024*1024);if(I>500){ae.error("Video file must be less than 500MB");return}if(I>y){ae.error(`Not enough storage. You have ${y.toFixed(1)} MB remaining.`);return}l(M)},C=j.useCallback(async()=>{if(i){c("creating"),u(0);try{const P=s||i.name,{data:M,error:I}=await U.functions.invoke("bunny-upload",{body:{action:"create",title:P,isAgentVideo:!0}});if(I)throw new Error(I.message);const{videoId:D,libraryId:B}=M;c("uploading");const{data:q,error:W}=await U.functions.invoke("bunny-upload",{body:{action:"upload-url",videoId:D,isAgentVideo:!0}});if(W)throw new Error(W.message);await new Promise((Q,J)=>{const ce=new XMLHttpRequest;ce.upload.addEventListener("progress",ue=>{ue.lengthComputable&&u(Math.round(ue.loaded/ue.total*100))}),ce.addEventListener("load",()=>ce.status>=200&&ce.status<300?Q():J(new Error(`Upload failed (${ce.status})`))),ce.addEventListener("error",()=>J(new Error("Upload failed"))),ce.open("PUT",q.uploadUrl),ce.setRequestHeader("AccessKey",q.apiKey),ce.send(i)}),c("processing");const V=i.size/(1024*1024),K=`https://iframe.mediadelivery.net/embed/${B}/${D}`;await m.mutateAsync({bunny_video_id:D,playback_url:K,file_size_mb:V,title:P,contact_id:t||void 0,status:"processing",touch_type:"presentation"}),n(K),c("done"),ae.success("Video uploaded & attached to section!"),setTimeout(()=>a(!1),1200)}catch(P){console.error("Upload error:",P),ae.error(P instanceof Error?P.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(Os,{open:r,onOpenChange:v,children:[e.jsx(Ko,{asChild:!0,children:e.jsxs($,{variant:"outline",size:"sm",className:"gap-1.5 shrink-0",title:"Upload a video file",children:[e.jsx(si,{className:"h-3.5 w-3.5"}),"Upload"]})}),e.jsxs(Rs,{className:"sm:max-w-md",children:[e.jsx(Us,{children:e.jsxs(zs,{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(Xr,{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($,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:()=>l(null),children:e.jsx(pr,{className:"h-4 w-4"})})]}):e.jsxs("div",{className:"border-2 border-dashed border-muted-foreground/25 rounded-lg p-8 text-center cursor-pointer hover:border-primary/50 transition-colors",onClick:()=>{var P;return(P=h.current)==null?void 0:P.click()},children:[e.jsx(si,{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(Ht,{className:"h-4 w-4 animate-spin"}),e.jsx("span",{children:A()})]}),e.jsx(Ki,{value:o==="uploading"?d:o==="processing"?100:10})]})]}),e.jsxs(kr,{children:[e.jsx($,{variant:"outline",onClick:()=>v(!1),disabled:T,children:"Cancel"}),e.jsx($,{onClick:C,disabled:!i||T,children:T?e.jsxs(e.Fragment,{children:[e.jsx(Ht,{className:"h-4 w-4 mr-2 animate-spin"}),"Uploading..."]}):e.jsxs(e.Fragment,{children:[e.jsx(si,{className:"h-4 w-4 mr-2"}),"Upload & Attach"]})})]})]})]})}const t1t=[{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"}],s1t=()=>{const s=Vn(),{id:t}=Vi(),{user:n}=_s(),{templates:r,templatesLoading:a,createPresentation:i,updatePresentation:l,publishPresentation:o}=iHt(),{isGmailConnected:c,gmailEmail:d}=ux(),[u,h]=j.useState(!1),[m,p]=j.useState("client"),[x,g]=j.useState(!1),[y,b]=j.useState(""),[v,N]=j.useState([]),[C,A]=j.useState(!1),[T,P]=j.useState(null),[M,I]=j.useState(!1),[D,B]=j.useState(""),[q,W]=j.useState(""),[V,K]=j.useState(""),[Q,J]=j.useState("buyer"),[ce,ue]=j.useState(""),[ne,ee]=j.useState(null),[le,he]=j.useState(""),[ve,ge]=j.useState([]),[fe,je]=j.useState("schedule_call"),[Ee,Me]=j.useState("Schedule a Call"),[De,ze]=j.useState(""),[ke,Xe]=j.useState(""),[Se,Re]=j.useState(null),[Ae,Be]=j.useState(t||null),[qe,Ke]=j.useState(null),[Ze,Ue]=j.useState(!1),et=async(_t,Xs)=>{if(!n)return;const rn=5*1024*1024;if(_t.size>rn){ae.error("Image must be under 5MB");return}if(!_t.type.startsWith("image/")){ae.error("Please upload an image file");return}Re(Xs);try{const Ps=_t.name.split(".").pop()||"jpg",_n=`${n.id}/${Date.now()}.${Ps}`,{error:Zs}=await U.storage.from("listing-photos").upload(_n,_t);if(Zs)throw Zs;const{data:{publicUrl:gr}}=U.storage.from("listing-photos").getPublicUrl(_n);Mt(Xs,{image_url:gr}),ae.success("Image uploaded")}catch{ae.error("Failed to upload image")}finally{Re(null)}};j.useEffect(()=>{t&&Qe(t)},[t]);const Qe=async _t=>{const{data:Xs,error:rn}=await U.from("smart_presentations").select("*").eq("id",_t).single();if(rn||!Xs)return;const Ps=Xs;if(g(!0),he(Ps.title),B(Ps.client_name||""),ue(Ps.property_address||""),ge(Ps.sections||[]),je(Ps.cta_type||"schedule_call"),Me(Ps.cta_label||"Schedule a Call"),ze(Ps.cta_url||""),Xe(Ps.heading||""),Ke(Ps.share_token),Ue(Ps.status==="published"),Be(Ps.id),p("builder"),Ps.contact_id){const{data:_n}=await U.from("innercircle_contacts").select("id, first_name, last_name, email, phone").eq("id",Ps.contact_id).maybeSingle();_n&&(P(_n),W(_n.email||""),K(_n.phone||""))}};j.useEffect(()=>{if(!n||y.length<1){N([]);return}const _t=setTimeout(async()=>{A(!0);const{data:Xs}=await U.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(Xs||[]),A(!1)},300);return()=>clearTimeout(_t)},[y,n]);const Ge=_t=>{P(_t),B(`${_t.first_name} ${_t.last_name||""}`.trim()),W(_t.email||""),K(_t.phone||""),I(!1)},nt=async()=>{if(!D.trim()){ae.error("Client name is required");return}const _t=D.trim().split(" "),Xs=_t[0],rn=_t.slice(1).join(" ")||null,{data:Ps,error:_n}=await U.from("innercircle_contacts").insert({owner_user_id:n.id,first_name:Xs,last_name:rn,email:q||null,phone:V||null,lead_source:"Smart Presentation"}).select().single();if(_n){ae.error("Failed to create client");return}P(Ps),ae.success("Client created & saved to Agent OS"),p("template")},ft=_t=>{ee(_t);const Xs=(_t.sections||[]).map(rn=>({...rn,is_visible:!0,video_url:"",text:""}));if(ge(Xs),he(_t.name+(D?` for ${D}`:"")),_t.cta_config){const rn=_t.cta_config;je(rn.type||"schedule_call"),Me(rn.label||"Schedule a Call")}p("builder")},lt=()=>{ge([{title:"Welcome",description:"A personal welcome",type:"video",icon:"👋",is_visible:!0}]),he(D?`Presentation for ${D}`:"New Presentation"),p("builder")},Mt=(_t,Xs)=>{ge(rn=>rn.map((Ps,_n)=>_n===_t?{...Ps,...Xs}:Ps))},Ft=_t=>{Mt(_t,{is_visible:!ve[_t].is_visible})},Ts=()=>{ge(_t=>[..._t,{title:"New Section",description:"",type:"video",icon:"📝",is_visible:!0}])},js=_t=>{ge(Xs=>Xs.filter((rn,Ps)=>Ps!==_t))},zt=async()=>{if(!le.trim()){ae.error("Title is required");return}try{if(Ae){const _t=await l.mutateAsync({id:Ae,title:le,sections:ve,client_name:D,property_address:ce||null,cta_type:fe,cta_label:Ee,cta_url:De||null,heading:ke||null});ae.success("Saved")}else{const _t=await i.mutateAsync({title:le,contact_id:(T==null?void 0:T.id)||void 0,client_name:D,property_address:ce||void 0,template_id:(ne==null?void 0:ne.id)||void 0,sections:ve,cta_type:fe,cta_label:Ee,cta_url:De||void 0,heading:ke||void 0});Be(_t.id),Ke(_t.share_token),ae.success("Presentation created!")}}catch(_t){console.error("Failed to save presentation:",_t);const Xs=(_t==null?void 0:_t.message)||(_t==null?void 0:_t.toString())||"Unknown error";ae.error(`Failed to save: ${Xs}`)}},Nt=async()=>{try{await zt();const _t=Ae;if(_t){const Xs=await o.mutateAsync(_t);Ke(Xs.share_token),Ue(!0),p("share")}}catch(_t){console.error("Failed to publish presentation:",_t),ae.error(`Failed to publish: ${(_t==null?void 0:_t.message)||"Unknown error"}`)}},Ds=qe?`https://presentations.relevelup.com/${qe}`:"";return e.jsx(Ks,{title:"Smart Presentations",children:e.jsxs("div",{className:"max-w-4xl mx-auto space-y-6",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx($,{variant:"ghost",size:"icon",onClick:()=>s("/mission-control/presentations"),children:e.jsx(ka,{className:"h-4 w-4"})}),e.jsxs("div",{children:[e.jsx("h1",{className:"text-xl font-serif font-bold text-foreground",children:x?"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"]})]})]}),!x&&e.jsx("div",{className:"flex items-center gap-2",children:["client","template","builder","share"].map((_t,Xs)=>e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:Tt("w-8 h-8 rounded-full flex items-center justify-center text-sm font-medium transition-colors",m===_t?"bg-primary text-primary-foreground":Xs<["client","template","builder","share"].indexOf(m)?"bg-emerald-100 text-emerald-700":"bg-muted text-muted-foreground"),children:Xs<["client","template","builder","share"].indexOf(m)?e.jsx(oa,{className:"h-4 w-4"}):Xs+1}),e.jsx("span",{className:"text-sm font-medium capitalize hidden sm:inline",children:_t}),Xs<3&&e.jsx("div",{className:"w-8 h-px bg-border"})]},_t))}),m==="client"&&e.jsxs("div",{className:"space-y-6",children:[e.jsxs("button",{onClick:()=>{P(null),B(""),W(""),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(Br,{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(ni,{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(_e,{children:[e.jsx(Bt,{className:"pb-3",children:e.jsxs(Ut,{className:"text-base flex items-center gap-2",children:[e.jsx(Vr,{className:"h-4 w-4 text-muted-foreground"}),"Select Existing Client"]})}),e.jsxs(Oe,{className:"space-y-3",children:[e.jsxs("div",{className:"relative",children:[e.jsx(Vr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(be,{placeholder:"Search by name or email...",value:y,onChange:_t=>b(_t.target.value),className:"pl-10"})]}),e.jsxs("div",{className:"space-y-2 max-h-56 overflow-y-auto",children:[C&&e.jsx(on,{className:"h-12 w-full"}),v.map(_t=>e.jsxs("button",{onClick:()=>Ge(_t),className:Tt("w-full text-left p-3 rounded-lg border transition-colors",(T==null?void 0:T.id)===_t.id?"border-primary bg-primary/5":"border-border hover:border-primary/50"),children:[e.jsxs("p",{className:"font-medium text-sm",children:[_t.first_name," ",_t.last_name]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:_t.email||_t.phone||"No contact info"})]},_t.id)),!y&&e.jsx("p",{className:"text-sm text-muted-foreground text-center py-6",children:"Start typing to search your contacts"}),y&&v.length===0&&!C&&e.jsx("p",{className:"text-sm text-muted-foreground text-center py-6",children:"No clients found"})]}),T&&e.jsxs($,{onClick:()=>p("template"),className:"w-full gap-2",children:["Continue with ",T.first_name,e.jsx(ni,{className:"h-4 w-4"})]})]})]}),e.jsxs(_e,{children:[e.jsx(Bt,{className:"pb-3",children:e.jsxs(Ut,{className:"text-base flex items-center gap-2",children:[e.jsx(il,{className:"h-4 w-4 text-muted-foreground"}),"Add New Client"]})}),e.jsxs(Oe,{className:"space-y-3",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"col-span-2",children:[e.jsx(se,{className:"text-xs",children:"Name *"}),e.jsx(be,{value:D,onChange:_t=>{B(_t.target.value),I(!0),P(null)},placeholder:"Sarah & Mike Johnson"})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-xs",children:"Email"}),e.jsx(be,{value:q,onChange:_t=>W(_t.target.value),placeholder:"Optional",type:"email"})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-xs",children:"Phone"}),e.jsx(be,{value:V,onChange:_t=>K(_t.target.value),placeholder:"Optional"})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-xs",children:"Client Type"}),e.jsxs(vs,{value:Q,onValueChange:J,children:[e.jsx(gs,{children:e.jsx(bs,{})}),e.jsxs(ys,{children:[e.jsx(Ye,{value:"buyer",children:"Buyer"}),e.jsx(Ye,{value:"seller",children:"Seller"}),e.jsx(Ye,{value:"recruit",children:"Recruit"}),e.jsx(Ye,{value:"other",children:"Other"})]})]})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-xs",children:"Property Address"}),e.jsx(be,{value:ce,onChange:_t=>ue(_t.target.value),placeholder:"Optional"})]})]}),M&&D&&e.jsxs($,{onClick:nt,className:"w-full gap-2",children:["Create Client & Continue",e.jsx(ni,{className:"h-4 w-4"})]})]})]})]})]}),m==="template"&&e.jsxs("div",{className:"space-y-6",children:[e.jsxs(ua,{defaultValue:"system",children:[e.jsxs(ha,{children:[e.jsx(Qt,{value:"mine",children:"My Core Templates"}),e.jsx(Qt,{value:"system",children:"LevelUp Smart Templates"}),e.jsx(Qt,{value:"blank",children:"+ Start Blank"})]}),e.jsx(Jt,{value:"mine",className:"mt-4",children:a?e.jsx("div",{className:"grid grid-cols-2 gap-4",children:[1,2].map(_t=>e.jsx(on,{className:"h-32"},_t))}):e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:r.filter(_t=>!_t.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(_t=>!_t.is_system).map(_t=>e.jsx(n1t,{template:_t,onSelect:ft},_t.id))})}),e.jsx(Jt,{value:"system",className:"mt-4",children:e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:r.filter(_t=>_t.is_system).map(_t=>e.jsx(n1t,{template:_t,onSelect:ft},_t.id))})}),e.jsx(Jt,{value:"blank",className:"mt-4",children:e.jsx(_e,{children:e.jsxs(Oe,{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx("p",{className:"text-muted-foreground mb-4",children:"Start with a blank canvas and add your own sections."}),e.jsx($,{onClick:lt,children:"Start from Scratch"})]})})})]}),e.jsxs($,{variant:"outline",onClick:()=>p("client"),className:"gap-2",children:[e.jsx(ka,{className:"h-4 w-4"}),"Back"]})]}),m==="builder"&&e.jsxs("div",{className:"space-y-6",children:[e.jsx(_e,{children:e.jsxs(Oe,{className:"pt-6 space-y-4",children:[e.jsxs("div",{children:[e.jsx(se,{children:"Presentation Title"}),e.jsx(be,{value:le,onChange:_t=>he(_t.target.value)})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Page Heading"}),e.jsx(be,{value:ke,onChange:_t=>Xe(_t.target.value),placeholder:D?`Welcome, ${D}!`:"e.g. Welcome! or Your Custom Listing Plan"}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-1",children:['The main heading visitors see. Leave blank for "Welcome, ',"",'!"']})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx(se,{children:"Client Name"}),e.jsx(be,{value:D,onChange:_t=>B(_t.target.value)})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Property Address"}),e.jsx(be,{value:ce,onChange:_t=>ue(_t.target.value),placeholder:"Optional"})]})]})]})}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-3",children:[e.jsx("h2",{className:"text-lg font-semibold",children:"Sections"}),e.jsx($,{variant:"outline",size:"sm",onClick:Ts,children:"+ Add Section"})]}),e.jsx("div",{className:"space-y-3",children:ve.map((_t,Xs)=>e.jsx(_e,{className:Tt(!_t.is_visible&&"opacity-50"),children:e.jsx(Oe,{className:"p-4",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsxs("div",{className:"flex flex-col items-center gap-1 pt-1",children:[e.jsx($p,{className:"h-4 w-4 text-muted-foreground cursor-grab"}),e.jsx("span",{className:"text-lg",children:_t.icon})]}),e.jsxs("div",{className:"flex-1 space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(be,{value:_t.title,onChange:rn=>Mt(Xs,{title:rn.target.value}),className:"font-semibold border-none p-0 h-auto text-base focus-visible:ring-0 bg-transparent"}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx($,{variant:"ghost",size:"icon",onClick:()=>Ft(Xs),children:_t.is_visible?e.jsx(ga,{className:"h-4 w-4"}):e.jsx(b0,{className:"h-4 w-4"})}),e.jsx($,{variant:"ghost",size:"icon",onClick:()=>js(Xs),className:"text-destructive hover:text-destructive",children:e.jsx(Pn,{className:"h-4 w-4"})})]})]}),e.jsx(be,{value:_t.description||"",onChange:rn=>Mt(Xs,{description:rn.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(se,{className:"text-xs",children:"Video URL"}),e.jsx(be,{value:_t.video_url||"",onChange:rn=>Mt(Xs,{video_url:rn.target.value}),placeholder:"Paste a YouTube or video URL...",className:"text-sm"})]}),e.jsx(cFn,{sectionTitle:_t.title,contactId:T==null?void 0:T.id,onVideoReady:rn=>Mt(Xs,{video_url:rn})}),e.jsx(dFn,{sectionTitle:_t.title,contactId:T==null?void 0:T.id,onVideoReady:rn=>Mt(Xs,{video_url:rn})}),e.jsx(hF,{userId:n==null?void 0:n.id,onSelect:rn=>Mt(Xs,{video_url:rn})})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-xs",children:"Image (optional — shown if no video is set)"}),_t.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:_t.image_url,alt:"",className:"w-full max-h-40 object-cover"}),e.jsx($,{variant:"destructive",size:"icon",className:"absolute top-2 right-2 h-7 w-7 opacity-0 group-hover:opacity-100 transition-opacity",onClick:()=>Mt(Xs,{image_url:""}),children:e.jsx(pr,{className:"h-3.5 w-3.5"})})]}):e.jsxs("label",{className:"mt-1 flex items-center gap-2 cursor-pointer rounded-lg border border-dashed border-border hover:border-primary/50 p-3 transition-colors",children:[Se===Xs?e.jsx(Ht,{className:"h-4 w-4 animate-spin text-muted-foreground"}):e.jsx(x1,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"text-sm text-muted-foreground",children:Se===Xs?"Uploading...":"Click to upload an image"}),e.jsx("input",{type:"file",accept:"image/*",className:"hidden",disabled:Se===Xs,onChange:rn=>{var _n;const Ps=(_n=rn.target.files)==null?void 0:_n[0];Ps&&et(Ps,Xs),rn.target.value=""}})]})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-xs",children:"Text (optional)"}),e.jsx(m2,{content:_t.text||"",onChange:rn=>Mt(Xs,{text:rn}),placeholder:"Add supporting text...",minHeight:"80px",compact:!0})]})]})]})})},Xs))})]}),e.jsxs(_e,{children:[e.jsx(Bt,{children:e.jsx(Ut,{className:"text-base",children:"Call to Action"})}),e.jsxs(Oe,{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(se,{children:"CTA Type"}),e.jsxs(vs,{value:fe,onValueChange:_t=>{je(_t);const Xs=t1t.find(rn=>rn.value===_t);Xs&&Me(Xs.label)},children:[e.jsx(gs,{children:e.jsx(bs,{})}),e.jsx(ys,{children:t1t.map(_t=>e.jsx(Ye,{value:_t.value,children:_t.label},_t.value))})]})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Button Label"}),e.jsx(be,{value:Ee,onChange:_t=>Me(_t.target.value)})]}),e.jsxs("div",{children:[e.jsxs(se,{children:["Link URL ",e.jsx("span",{className:"text-muted-foreground",children:"(optional — leave blank to show a lead capture form instead)"})]}),e.jsx(be,{value:De,onChange:_t=>ze(_t.target.value),placeholder:"https://calendly.com/..."}),!De&&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:[!x&&e.jsxs($,{variant:"outline",onClick:()=>p("template"),className:"gap-2",children:[e.jsx(ka,{className:"h-4 w-4"}),"Back"]}),e.jsxs("div",{className:"flex gap-3 ml-auto",children:[e.jsx($,{variant:"outline",onClick:zt,disabled:i.isPending||l.isPending,children:"Save Draft"}),e.jsxs($,{onClick:Nt,disabled:o.isPending,className:"gap-2",children:[e.jsx(Br,{className:"h-4 w-4"}),Ze?"Update & Reshare":"Publish & Share"]})]})]})]}),m==="share"&&qe&&e.jsxs("div",{className:"space-y-6",children:[e.jsx(_e,{children:e.jsxs(Oe,{className:"flex flex-col items-center py-12 text-center",children:[e.jsx("div",{className:"w-16 h-16 rounded-full bg-emerald-100 flex items-center justify-center mb-4",children:e.jsx(oa,{className:"h-8 w-8 text-emerald-600"})}),e.jsx("h2",{className:"text-xl font-semibold mb-2",children:"Your Presentation is Live!"}),e.jsxs("p",{className:"text-muted-foreground mb-6 max-w-md",children:["Share this link with ",D||"your client",". You'll be notified when they view it."]}),e.jsxs("div",{className:"flex items-center gap-2 w-full max-w-lg",children:[e.jsx(be,{value:Ds,readOnly:!0,className:"text-center font-mono text-sm"}),e.jsx($,{onClick:()=>{navigator.clipboard.writeText(Ds),ae.success("Link copied!")},children:e.jsx(Ca,{className:"h-4 w-4"})})]}),e.jsxs("div",{className:"flex gap-3 mt-6",children:[e.jsxs($,{variant:"outline",className:"gap-2",onClick:()=>{const _t=`Hi ${D||""}! I put together something for you — check it out: ${Ds}`;navigator.clipboard.writeText(_t),ae.success("Message copied!")},children:[e.jsx(Ji,{className:"h-4 w-4"}),"Copy Text Message"]}),e.jsxs($,{variant:"outline",className:"gap-2",onClick:()=>{c?h(!0):window.open(`mailto:${q||""}?subject=${encodeURIComponent(le)}&body=${encodeURIComponent(`Hi ${(T==null?void 0:T.first_name)||(D==null?void 0:D.split(" ")[0])||""}, I put together a personalized presentation for you: ${Ds} Looking forward to connecting!`)}`)},children:[e.jsx(nn,{className:"h-4 w-4"}),"Send Email"]})]}),c&&e.jsx(x2,{open:u,onOpenChange:h,contact:T?{id:T.id,first_name:T.first_name,last_name:T.last_name,email:q||T.email||""}:q?{id:"",first_name:(D==null?void 0:D.split(" ")[0])||"",last_name:(D==null?void 0:D.split(" ").slice(1).join(" "))||"",email:q}:void 0,defaultSubject:le,defaultBody:`Hi ${(T==null?void 0:T.first_name)||(D==null?void 0:D.split(" ")[0])||""}, I put together a personalized presentation for you: ${Ds} Looking forward to connecting!`,gmailEmail:d})]})}),e.jsxs("div",{className:"flex justify-between",children:[e.jsxs($,{variant:"outline",onClick:()=>p("builder"),children:[e.jsx(ka,{className:"h-4 w-4 mr-2"}),"Edit Presentation"]}),e.jsx($,{onClick:()=>s("/mission-control/presentations"),children:"Done"})]})]})]})})},n1t=({template:s,onSelect:t})=>e.jsx(_e,{className:"hover:shadow-sm transition-shadow",children:e.jsxs(Oe,{className:"p-5",children:[e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("span",{className:"text-2xl",children:s.icon}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("h3",{className:"font-semibold",children:s.name}),e.jsx("p",{className:"text-sm text-muted-foreground mt-0.5",children:s.description}),e.jsxs("div",{className:"flex items-center gap-2 mt-2",children:[e.jsx($e,{variant:"outline",className:"text-xs capitalize",children:s.template_type}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:[(s.sections||[]).length," sections"]})]})]})]}),e.jsx($,{className:"w-full mt-4",size:"sm",onClick:()=>t(s),children:"Use Template"})]})}),uFn=()=>{var g;const{shareToken:s}=Vi(),[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:b}=await U.from("smart_presentations").select("*").eq("share_token",s).eq("status","published").single();if(b||!y){c(!0),a(!1);return}const{data:v}=await U.from("profiles").select("name, email, phone, avatar_url, title, brokerage_id").eq("id",y.owner_user_id).single();let N;if(v!=null&&v.brokerage_id){const{data:A}=await U.from("brokerages").select("name").eq("id",v.brokerage_id).single();N=(A==null?void 0:A.name)||void 0}let C=null;if(y.contact_id){const{data:A}=await U.from("innercircle_contacts").select("first_name, last_name, email, phone").eq("id",y.contact_id).single();C=A}n({...y,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:N,contact_name:C?[C.first_name,C.last_name].filter(Boolean).join(" "):void 0,contact_email:(C==null?void 0:C.email)||void 0,contact_phone:(C==null?void 0:C.phone)||void 0}),a(!1);try{await U.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 U.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(on,{className:"h-12 w-3/4 mx-auto"}),e.jsx(on,{className:"h-64 w-full"}),e.jsx(on,{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 b=y.match(/(?:youtube\.com\/watch\?v=|youtu\.be\/)([a-zA-Z0-9_-]+)/);if(b)return`https://www.youtube.com/embed/${b[1]}?rel=0`;if(y.includes("iframe.mediadelivery.net/play/")){const C=y.replace("/play/","/embed/"),A=C.includes("?")?"&":"?";return`${C}${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 v=y.match(/loom\.com\/share\/([a-zA-Z0-9]+)/);if(v)return`https://www.loom.com/embed/${v[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},x=!!((g=t.cta_url)!=null&&g.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,b)=>e.jsx("button",{onClick:()=>l(b),className:Tt("w-full text-left p-4 rounded-xl border transition-all",i===b?"border-blue-500 bg-blue-50 shadow-sm":"border-gray-200 bg-white hover:border-blue-200 hover:bg-blue-50/50"),children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsxs("span",{className:"text-blue-600 font-bold text-sm mt-0.5",children:[String(b+1).padStart(2,"0"),"."]}),e.jsxs("div",{children:[e.jsx("span",{className:"mr-2",children: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})]})]})},b))})]}),e.jsxs("div",{className:"mt-12 max-w-md mx-auto bg-white rounded-2xl border border-gray-200 shadow-sm p-6 text-center",children:[t.owner_avatar&&e.jsx("img",{src:t.owner_avatar,alt:t.owner_name||"Agent",className:"h-20 w-20 rounded-full object-cover mx-auto mb-3 border-2 border-gray-100"}),e.jsx("h3",{className:"text-lg font-bold text-gray-900",children:t.owner_name}),t.owner_title&&e.jsx("p",{className:"text-sm text-gray-500",children:t.owner_title}),t.brokerage_name&&e.jsx("p",{className:"text-sm text-gray-500",children:t.brokerage_name}),e.jsxs("div",{className:"mt-3 flex flex-col items-center gap-1 text-sm text-gray-600",children:[t.owner_phone&&e.jsx("a",{href:`tel:${t.owner_phone}`,className:"hover:text-blue-600 transition-colors",children:t.owner_phone}),t.owner_email&&e.jsx("a",{href:`mailto:${t.owner_email}`,className:"hover:text-blue-600 transition-colors",children:t.owner_email})]})]}),t.cta_label&&e.jsxs("div",{className:"text-center mt-8 py-8",children:[e.jsx("h2",{className:"text-2xl font-bold text-gray-900 mb-4",children:"Ready to Get Started?"}),x?e.jsxs($,{size:"lg",onClick:u,className:"text-lg px-8 py-6 rounded-xl bg-blue-600 hover:bg-blue-700 text-white shadow-lg",children:[t.cta_label,e.jsx(Tr,{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(PAt,{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"})]})},kDe="__none__";function hFn({value:s,onChange:t}){const{data:n=[],isLoading:r}=Xee(),a=TYe(),[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),ja({title:"Open House Follow-Up added",description:"The 6-email sequence is now in your library and selected here."})}catch(h){ja({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(se,{className:"text-sm font-medium flex items-center gap-2",children:[e.jsx(MT,{className:"h-4 w-4 text-emerald-600"}),"Auto follow-up campaign"]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Everyone who signs in with an email is automatically enrolled."})]}),s&&e.jsx($e,{variant:"outline",className:"text-[10px] border-emerald-300 bg-emerald-500/10 text-emerald-700",children:"On"})]}),e.jsxs(vs,{value:s??kDe,onValueChange:h=>t(h===kDe?null:h),disabled:r,children:[e.jsx(gs,{children:e.jsx(bs,{placeholder:"No follow-up campaign"})}),e.jsxs(ys,{children:[e.jsx(Ye,{value:kDe,children:"No follow-up campaign"}),o.map(h=>e.jsxs(Ye,{value:h.id,children:[h.icon?`${h.icon} `:"",h.name,h.is_active?"":" (paused)"]},h.id))]})]}),c&&!d&&e.jsxs($,{type:"button",variant:"outline",size:"sm",className:"w-full gap-1.5 text-xs",onClick:u,disabled:i,children:[i?e.jsx(Ht,{className:"h-3.5 w-3.5 animate-spin"}):e.jsx(dn,{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 mFn({openHouseId:s,enableSurvey:t,onToggleSurvey:n}){const{data:r,isLoading:a}=Q_s(s),i=sws(),l=nws(),o=rws(),c=aws(),[d,u]=j.useState(""),[h,m]=j.useState("rating"),p=async b=>{n(b),b&&(!r||r.length===0)&&await c.mutateAsync(s)},x=async()=>{if(!d.trim())return;const b=(r==null?void 0:r.reduce((v,N)=>Math.max(v,N.sort_order),0))??0;await i.mutateAsync({open_house_id:s,question_type:h,question_text:d.trim(),sort_order:b+1}),u("")},g=async b=>{await l.mutateAsync({id:b.id,open_house_id:s,is_active:!b.is_active})},y=async b=>{await o.mutateAsync({id:b.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(se,{className:"text-sm font-medium flex items-center gap-2",children:[e.jsx(v0,{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(Tn,{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(Ht,{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(b=>e.jsxs("div",{className:"flex items-center gap-2 p-2 rounded-lg border border-border bg-muted/20",children:[e.jsx($p,{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:b.question_text}),e.jsx("p",{className:"text-xs text-muted-foreground capitalize",children:b.question_type.replace("_"," ")})]}),e.jsx(Tn,{checked:b.is_active,onCheckedChange:()=>g(b),className:"scale-75"}),e.jsx($,{variant:"ghost",size:"icon",className:"h-7 w-7 shrink-0 text-muted-foreground hover:text-destructive",onClick:()=>y(b),children:e.jsx(Pn,{className:"h-3.5 w-3.5"})})]},b.id))}),e.jsxs("div",{className:"flex items-end gap-2",children:[e.jsxs("div",{className:"flex-1",children:[e.jsx(se,{className:"text-xs text-muted-foreground",children:"Add Question"}),e.jsx(be,{value:d,onChange:b=>u(b.target.value),placeholder:"e.g. How did you hear about this listing?",className:"mt-1 h-9 text-sm",onKeyDown:b=>b.key==="Enter"&&x()})]}),e.jsxs(vs,{value:h,onValueChange:m,children:[e.jsx(gs,{className:"w-28 h-9 text-xs",children:e.jsx(bs,{})}),e.jsxs(ys,{children:[e.jsx(Ye,{value:"rating",children:"Rating"}),e.jsx(Ye,{value:"open_text",children:"Text"})]})]}),e.jsx($,{size:"sm",variant:"outline",onClick:x,disabled:!d.trim()||i.isPending,className:"h-9",children:e.jsx(sn,{className:"h-3.5 w-3.5"})})]})]})})]})}function pFn({openHouseId:s}){const{user:t}=_s(),{data:n=[],isLoading:r}=cws(s),a=uws(),[i,l]=j.useState(""),[o,c]=j.useState(!1),d=async()=>{const u=i.trim();if(u){c(!0);try{await a.mutateAsync({open_house_id:s,name:u,sort_order:n.length}),l("")}finally{c(!1)}}};return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(se,{className:"text-sm font-medium",children:"Rooms"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Add rooms and upload photos or videos. Visitors swipe through them on mobile and tab through them on desktop."})]}),r?e.jsxs("div",{className:"py-6 text-center text-sm text-muted-foreground",children:[e.jsx(Ht,{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((u,h)=>e.jsx(fFn,{room:u,index:h,total:n.length,userId:(t==null?void 0:t.id)||"",openHouseId:s},u.id))}),e.jsxs("div",{className:"flex gap-2 pt-2",children:[e.jsx(be,{value:i,onChange:u=>l(u.target.value),placeholder:"e.g. Kitchen, Primary Bedroom, Backyard…",onKeyDown:u=>{u.key==="Enter"&&(u.preventDefault(),d())}}),e.jsx($,{onClick:d,disabled:!i.trim()||o,size:"sm",children:o?e.jsx(Ht,{className:"h-4 w-4 animate-spin"}):e.jsxs(e.Fragment,{children:[e.jsx(sn,{className:"h-4 w-4 mr-1"})," Add"]})})]})]})}function fFn({room:s,index:t,total:n,userId:r,openHouseId:a}){const i=hws(),l=mws(),o=pws(),c=fws(),d=j.useRef(null),[u,h]=j.useState(!0),[m,p]=j.useState(s.name),[x,g]=j.useState(s.description||""),[y,b]=j.useState(!1),v=j.useMemo(()=>s.media.filter(I=>I.kind==="video"&&I.agent_video_id).map(I=>I.agent_video_id),[s.media]),{data:N={}}=ht({queryKey:["room-video-statuses",s.id,v.join(",")],enabled:v.length>0,queryFn:async()=>{const{data:I,error:D}=await U.from("agent_videos").select("id, status, bunny_video_id, thumbnail_url, preview_url").in("id",v);if(D)throw D;const B=I||[],q=B.filter(V=>V.status==="processing"&&V.bunny_video_id);await Promise.all(q.map(async V=>{try{const{data:K}=await U.functions.invoke("bunny-upload",{body:{action:"status",videoId:V.bunny_video_id,isAgentVideo:!0}});K&&K.status===4&&(await U.from("agent_videos").update({status:"ready",playback_url:K.directPlayUrl,thumbnail_url:K.thumbnailUrl,preview_url:K.previewUrl,duration_seconds:K.length||void 0,updated_at:new Date().toISOString()}).eq("id",V.id),V.status="ready",V.thumbnail_url=K.thumbnailUrl,V.preview_url=K.previewUrl)}catch{}}));const W={};return B.forEach(V=>{W[V.id]={status:V.status,thumbnail_url:V.thumbnail_url,preview_url:V.preview_url}}),W},refetchInterval:I=>{const D=I.state.data;return D?Object.values(D).some(B=>B.status!=="ready"&&B.status!=="failed")?5e3:!1:5e3}}),C=()=>{m.trim()&&m!==s.name&&i.mutate({id:s.id,open_house_id:a,name:m.trim()})},A=()=>{x!==(s.description||"")&&i.mutate({id:s.id,open_house_id:a,description:x.trim()||null})},T=async()=>{await Yi(`Delete "${s.name}" and all its media?`)&&l.mutate({id:s.id,open_house_id:a})},P=I=>{i.mutate({id:s.id,open_house_id:a,sort_order:t+I})},M=async I=>{const D=Array.from(I.target.files||[]);if(!(!D.length||!r)){b(!0);try{for(const B of D){const q=B.type.startsWith("video/"),W=q?500*1024*1024:15*1024*1024;if(B.size>W){ja({title:`${B.name} is too large`,description:q?"Videos must be under 500MB":"Photos must be under 15MB",variant:"destructive"});continue}if(q){try{const ce=`${s.name} – ${B.name.replace(/\.[^/.]+$/,"")}`,{data:ue,error:ne}=await U.functions.invoke("bunny-upload",{body:{action:"create",title:ce,isAgentVideo:!0}});if(ne||!ue)throw new Error((ne==null?void 0:ne.message)||"Could not start upload");const{videoId:ee,libraryId:le}=ue,{data:he,error:ve}=await U.functions.invoke("bunny-upload",{body:{action:"upload-url",videoId:ee,isAgentVideo:!0}});if(ve||!he)throw new Error((ve==null?void 0:ve.message)||"Could not get upload URL");await new Promise((Me,De)=>{const ze=new XMLHttpRequest;ze.addEventListener("load",()=>{ze.status>=200&&ze.status<300?Me():De(new Error(`Upload failed (${ze.status})`))}),ze.addEventListener("error",()=>De(new Error("Upload failed"))),ze.open("PUT",he.uploadUrl),ze.setRequestHeader("AccessKey",he.apiKey),ze.send(B)});const ge=`https://iframe.mediadelivery.net/embed/${le}/${ee}`,fe=B.size/(1024*1024),{data:je,error:Ee}=await U.from("agent_videos").insert({owner_user_id:r,bunny_video_id:ee,playback_url:ge,file_size_mb:fe,title:ce,status:"processing",touch_type:"open_house_tour",category:"open_house",page_template:"default"}).select().single();if(Ee)throw Ee;await o.mutateAsync({open_house_id:a,room_id:s.id,kind:"video",url:ge,sort_order:s.media.length,agent_video_id:je.id}),ja({title:"Video uploaded",description:"Processing in the background — it’ll appear in your Video Library too."})}catch(ce){ja({title:"Video upload failed",description:(ce==null?void 0:ce.message)||"Try again",variant:"destructive"})}continue}const V=B.name.split(".").pop()||"jpg",K=`${r}/${a}/rooms/${s.id}-${Date.now()}-${Math.random().toString(36).slice(2,7)}.${V}`,{error:Q}=await U.storage.from("open-house-tour-media").upload(K,B,{upsert:!1,contentType:B.type});if(Q){ja({title:"Upload failed",description:Q.message,variant:"destructive"});continue}const{data:J}=U.storage.from("open-house-tour-media").getPublicUrl(K);await o.mutateAsync({open_house_id:a,room_id:s.id,kind:"photo",url:J.publicUrl,sort_order:s.media.length})}}finally{b(!1),d.current&&(d.current.value="")}}};return e.jsxs("div",{className:"rounded-lg border border-border bg-card",children:[e.jsxs("div",{className:"flex items-center gap-2 px-3 py-2 border-b border-border",children:[e.jsx($p,{className:"h-4 w-4 text-muted-foreground"}),e.jsxs("button",{onClick:()=>h(I=>!I),className:"flex-1 text-left text-sm font-medium truncate",children:[s.name," ",e.jsxs("span",{className:"text-muted-foreground font-normal text-xs",children:["· ",s.media.length," ",s.media.length===1?"item":"items"]})]}),e.jsx($,{size:"icon",variant:"ghost",className:"h-7 w-7",onClick:()=>P(-1),disabled:t===0,children:e.jsx(jg,{className:"h-4 w-4"})}),e.jsx($,{size:"icon",variant:"ghost",className:"h-7 w-7",onClick:()=>P(1),disabled:t===n-1,children:e.jsx(_o,{className:"h-4 w-4"})}),e.jsx($,{size:"icon",variant:"ghost",className:"h-7 w-7 text-destructive",onClick:T,children:e.jsx(Pn,{className:"h-4 w-4"})})]}),u&&e.jsxs("div",{className:"p-3 space-y-3",children:[e.jsx(be,{value:m,onChange:I=>p(I.target.value),onBlur:C,placeholder:"Room name",className:"h-9"}),e.jsx(Is,{value:x,onChange:I=>g(I.target.value),onBlur:A,placeholder:"Optional description — what makes this room special?",rows:2,className:"text-sm"}),s.media.length>0&&e.jsx("div",{className:"grid grid-cols-3 gap-2",children:s.media.map(I=>{const D=I.agent_video_id?N[I.agent_video_id]:void 0,B=D==null?void 0:D.status,q=I.kind==="video"&&B&&B!=="ready"&&B!=="failed",W=I.kind==="video"&&B==="failed",V=(D==null?void 0:D.thumbnail_url)||(D==null?void 0:D.preview_url);return e.jsxs("div",{className:"relative aspect-square rounded-md overflow-hidden bg-muted group",children:[I.kind==="video"?e.jsxs(e.Fragment,{children:[V?e.jsx("img",{src:V,alt:"",className:"w-full h-full object-cover"}):/iframe\.mediadelivery\.net\/embed\//.test(I.url)?e.jsx("div",{className:"w-full h-full bg-slate-800"}):e.jsx("video",{src:I.url,className:"w-full h-full object-cover"}),!q&&!W&&e.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-black/30 pointer-events-none",children:e.jsx(Xr,{className:"h-6 w-6 text-white"})}),q&&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(Ht,{className:"h-5 w-5 animate-spin"}),e.jsx("span",{className:"text-[10px] font-medium uppercase tracking-wide",children:"Processing"})]}),W&&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:I.url,alt:"",className:"w-full h-full object-cover"}),e.jsx("button",{onClick:()=>c.mutate({id:I.id,open_house_id:a}),className:"absolute top-1 right-1 w-6 h-6 rounded-full bg-black/60 text-white flex items-center justify-center opacity-0 group-hover:opacity-100 transition",children:e.jsx(pr,{className:"h-3.5 w-3.5"})})]},I.id)})}),e.jsx("input",{ref:d,type:"file",accept:"image/*,video/*",multiple:!0,onChange:M,className:"hidden"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx($,{variant:"outline",size:"sm",onClick:()=>{var I;return(I=d.current)==null?void 0:I.click()},disabled:y,className:"flex-1",children:y?e.jsx(Ht,{className:"h-4 w-4 animate-spin"}):e.jsxs(e.Fragment,{children:[e.jsx(si,{className:"h-4 w-4 mr-2"})," Upload"]})}),e.jsx(hF,{userId:r,triggerLabel:"From Video Library",triggerClassName:"gap-1.5 flex-1 justify-center",onSelect:()=>{},onSelectVideo:async I=>{try{await o.mutateAsync({open_house_id:a,room_id:s.id,kind:"video",url:I.playback_url||"",sort_order:s.media.length,agent_video_id:I.id}),ja({title:"Video added to room"})}catch(D){ja({title:"Failed to add video",description:D==null?void 0:D.message,variant:"destructive"})}}})]})]})]})}function xFn({open:s,onOpenChange:t,openHouse:n}){const r=DAt(),{user:a}=_s(),i=j.useRef(null),l=j.useRef(null),o=j.useRef(null),c=n.kind==="virtual",[d,u]=j.useState(n.auto_forward_to_card??!1),[h,m]=j.useState(n.disclosure_pdf_url??""),[p,x]=j.useState(n.enable_survey??!1),[g,y]=j.useState(n.ask_visitor_intent??!0),[b,v]=j.useState(n.ask_visitor_address??!1),[N,C]=j.useState(n.photo_url??""),[A,T]=j.useState(!1),[P,M]=j.useState(!1),[I,D]=j.useState(!1),[B,q]=j.useState(n.hero_video_url??""),[W,V]=j.useState(!1),[K,Q]=j.useState(n.price!=null?String(n.price):""),[J,ce]=j.useState(n.beds!=null?String(n.beds):""),[ue,ne]=j.useState(n.baths!=null?String(n.baths):""),[ee,le]=j.useState(n.sqft!=null?String(n.sqft):""),[he,ve]=j.useState(n.enable_question??!0),[ge,fe]=j.useState(n.enable_showing??!0),[je,Ee]=j.useState(n.enable_disclosures??!0),[Me,De]=j.useState(n.enable_offer??!0),[ze,ke]=j.useState(n.brand_color_override??""),[Xe,Se]=j.useState(n.property_description??""),[Re,Ae]=j.useState(n.drip_campaign_id??null),Be=async Qe=>{var Ft;const Ge=(Ft=Qe.target.files)==null?void 0:Ft[0];if(!Ge||!a)return;if(Ge.size>200*1024*1024){ja({title:"Video must be under 200MB",variant:"destructive"});return}if(!Ge.type.startsWith("video/")){ja({title:"Please upload a video file",variant:"destructive"});return}V(!0);const nt=Ge.name.split(".").pop()||"mp4",ft=`${a.id}/${n.id}/hero-${Date.now()}.${nt}`,{error:lt}=await U.storage.from("open-house-tour-media").upload(ft,Ge,{upsert:!0,contentType:Ge.type});if(lt){ja({title:"Upload failed",description:lt.message,variant:"destructive"}),V(!1);return}const{data:Mt}=U.storage.from("open-house-tour-media").getPublicUrl(ft);q(Mt.publicUrl),V(!1),ja({title:"Video uploaded!"})},qe=async Qe=>{var Ft;const Ge=(Ft=Qe.target.files)==null?void 0:Ft[0];if(!Ge||!a)return;if(Ge.size>10*1024*1024){ja({title:"Image must be under 10MB",variant:"destructive"});return}if(!Ge.type.startsWith("image/")){ja({title:"Please upload an image file",variant:"destructive"});return}M(!0);const nt=Ge.name.split(".").pop()||"jpg",ft=`${a.id}/${n.id}-${Date.now()}.${nt}`,{error:lt}=await U.storage.from("open-house-photos").upload(ft,Ge,{upsert:!0});if(lt){ja({title:"Upload failed",description:lt.message,variant:"destructive"}),M(!1);return}const{data:Mt}=U.storage.from("open-house-photos").getPublicUrl(ft);C(Mt.publicUrl),M(!1),ja({title:"Photo updated!"})},Ke=()=>{C(""),l.current&&(l.current.value="")},Ze=async Qe=>{var Mt;const Ge=(Mt=Qe.target.files)==null?void 0:Mt[0];if(!Ge||!a)return;if(Ge.size>20*1024*1024){ja({title:"File must be under 20MB",variant:"destructive"});return}if(Ge.type!=="application/pdf"){ja({title:"Only PDF files are accepted",variant:"destructive"});return}T(!0);const nt=`${a.id}/disclosures/${n.id}-${Date.now()}.pdf`,{error:ft}=await U.storage.from("open-house-photos").upload(nt,Ge,{upsert:!0});if(ft){ja({title:"Upload failed",description:ft.message,variant:"destructive"}),T(!1);return}const{data:lt}=U.storage.from("open-house-photos").getPublicUrl(nt);m(lt.publicUrl),T(!1),ja({title:"PDF uploaded!"})},Ue=()=>{m(""),i.current&&(i.current.value="")},et=async()=>{D(!0);try{const Qe={id:n.id,auto_forward_to_card:d,disclosure_pdf_url:h||null,enable_survey:p,ask_visitor_intent:g,ask_visitor_address:b,photo_url:N||null,drip_campaign_id:Re};c&&(Qe.hero_video_url=B||null,Qe.price=K.trim()?Number(K):null,Qe.beds=J.trim()?parseInt(J,10):null,Qe.baths=ue.trim()?Number(ue):null,Qe.sqft=ee.trim()?parseInt(ee,10):null,Qe.enable_question=he,Qe.enable_showing=ge,Qe.enable_disclosures=je,Qe.enable_offer=Me,Qe.brand_color_override=ze.trim()||null,Qe.property_description=Xe.trim()||null),await r.mutateAsync(Qe),ja({title:"Settings saved!"}),t(!1)}catch{ja({title:"Failed to save",variant:"destructive"})}finally{D(!1)}};return e.jsx(Os,{open:s,onOpenChange:t,children:e.jsxs(Rs,{className:"sm:max-w-md max-h-[85vh] overflow-y-auto",children:[e.jsxs(Us,{children:[e.jsx(zs,{children:c?"Virtual Open House Settings":"Guest Book Settings"}),e.jsx(Sr,{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(se,{className:"text-sm font-medium flex items-center gap-2",children:[e.jsx(Xr,{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:Be,className:"hidden"}),B?e.jsxs("div",{className:"relative rounded-lg overflow-hidden border border-border bg-black",children:[e.jsx("video",{src:B,controls:!0,className:"w-full max-h-48"}),e.jsxs("div",{className:"absolute top-2 right-2 flex gap-2",children:[e.jsx($,{variant:"secondary",size:"sm",className:"h-8",onClick:()=>{var Qe;return(Qe=o.current)==null?void 0:Qe.click()},disabled:W,children:W?e.jsx(Ht,{className:"h-3.5 w-3.5 animate-spin"}):e.jsxs(e.Fragment,{children:[e.jsx(si,{className:"h-3.5 w-3.5 mr-1"}),"Replace"]})}),e.jsx($,{variant:"secondary",size:"icon",className:"h-8 w-8",onClick:()=>q(""),children:e.jsx(pr,{className:"h-4 w-4"})})]})]}):e.jsx("button",{type:"button",onClick:()=>{var Qe;return(Qe=o.current)==null?void 0:Qe.click()},disabled:W,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:W?e.jsx(Ht,{className:"h-5 w-5 animate-spin"}):e.jsxs(e.Fragment,{children:[e.jsx(Xr,{className:"h-5 w-5"}),e.jsx("span",{className:"text-xs",children:"Upload tour video (max 200MB)"})]})})]}):e.jsx(pFn,{openHouseId:n.id}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{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(se,{className:"text-xs text-muted-foreground",children:"Price (USD)"}),e.jsx(be,{type:"number",value:K,onChange:Qe=>Q(Qe.target.value),placeholder:"650000",className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-xs text-muted-foreground",children:"Sq Ft"}),e.jsx(be,{type:"number",value:ee,onChange:Qe=>le(Qe.target.value),placeholder:"2200",className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-xs text-muted-foreground",children:"Beds"}),e.jsx(be,{type:"number",value:J,onChange:Qe=>ce(Qe.target.value),placeholder:"3",className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-xs text-muted-foreground",children:"Baths"}),e.jsx(be,{type:"number",step:"0.5",value:ue,onChange:Qe=>ne(Qe.target.value),placeholder:"2.5",className:"mt-1"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{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(Is,{value:Xe,onChange:Qe=>Se(Qe.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(se,{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(Tn,{checked:he,onCheckedChange:ve})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-sm",children:"Schedule a private showing"}),e.jsx(Tn,{checked:ge,onCheckedChange:fe})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-sm",children:"Request seller disclosures"}),e.jsx(Tn,{checked:je,onCheckedChange:Ee})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-sm",children:"Make an offer / express interest"}),e.jsx(Tn,{checked:Me,onCheckedChange:De})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{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:ze||"#0f172a",onChange:Qe=>ke(Qe.target.value),className:"h-10 w-14 rounded-md border border-input cursor-pointer bg-transparent"}),e.jsx(be,{value:ze,onChange:Qe=>ke(Qe.target.value),placeholder:"#0f172a",className:"flex-1 font-mono text-sm"}),ze&&e.jsx($,{variant:"ghost",size:"sm",onClick:()=>ke(""),children:"Reset"})]}),e.jsx("div",{className:"flex flex-wrap gap-1.5 pt-1",children:["#0f172a","#406E71","#2a4c64","#7c2d12","#1e3a8a","#581c87","#9f1239","#065f46"].map(Qe=>e.jsx("button",{type:"button",onClick:()=>ke(Qe),className:"w-6 h-6 rounded-full border border-border hover:scale-110 transition-transform",style:{backgroundColor:Qe},"aria-label":Qe},Qe))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{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:qe,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($,{variant:"secondary",size:"sm",className:"h-8",onClick:()=>{var Qe;return(Qe=l.current)==null?void 0:Qe.click()},disabled:P,children:[P?e.jsx(Ht,{className:"h-3.5 w-3.5 animate-spin"}):e.jsx(si,{className:"h-3.5 w-3.5 mr-1"}),P?"":"Replace"]}),e.jsx($,{variant:"secondary",size:"icon",className:"h-8 w-8",onClick:Ke,children:e.jsx(pr,{className:"h-4 w-4"})})]})]}):e.jsx("button",{type:"button",onClick:()=>{var Qe;return(Qe=l.current)==null?void 0:Qe.click()},disabled:P,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:P?e.jsx(Ht,{className:"h-5 w-5 animate-spin"}):e.jsxs(e.Fragment,{children:[e.jsx(Jl,{className:"h-5 w-5"}),e.jsx("span",{className:"text-xs",children:"Upload property photo (max 10MB)"})]})})]}),e.jsx(hFn,{value:Re,onChange:Ae}),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(se,{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(Tn,{checked:d,onCheckedChange:u})]})}),!d&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{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(Wr,{className:"h-5 w-5 text-primary shrink-0"}),e.jsx("span",{className:"text-sm truncate flex-1",children:"Disclosure PDF uploaded"}),e.jsx($,{variant:"ghost",size:"icon",className:"h-7 w-7 shrink-0",onClick:Ue,children:e.jsx(pr,{className:"h-4 w-4"})})]}):e.jsx("button",{type:"button",onClick:()=>{var Qe;return(Qe=i.current)==null?void 0:Qe.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(Ht,{className:"h-5 w-5 animate-spin"}):e.jsxs(e.Fragment,{children:[e.jsx(si,{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(se,{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(Tn,{checked:g,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(se,{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(Tn,{checked:b,onCheckedChange:v})]})}),e.jsx(mFn,{openHouseId:n.id,enableSurvey:p,onToggleSurvey:x}),e.jsx($,{onClick:et,disabled:I,className:"w-full",children:I?"Saving...":"Save Settings"})]})]})})}const oHt={5:"Excellent",4:"Good",3:"Neutral",2:"Bad",1:"Very Bad"};function gFn({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:oHt[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 yFn({openHouseId:s}){const{data:t,isLoading:n}=tws(s),{data:r}=IAt(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(_e,{children:[e.jsx(Bt,{className:"pb-3",children:e.jsxs(Ut,{className:"text-base flex items-center gap-2",children:[e.jsx(v0,{className:"h-4 w-4"}),"Survey Results"]})}),e.jsx(Oe,{children:e.jsx("p",{className:"text-sm text-muted-foreground",children:"No survey responses yet."})})]}):e.jsxs(_e,{children:[e.jsx(Bt,{className:"pb-3",children:e.jsxs(Ut,{className:"text-base flex items-center gap-2",children:[e.jsx(v0,{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(Oe,{children:e.jsxs(ua,{defaultValue:"summary",children:[e.jsxs(ha,{className:"mb-4",children:[e.jsxs(Qt,{value:"summary",className:"text-xs gap-1",children:[e.jsx(ml,{className:"h-3.5 w-3.5"})," Summary"]}),e.jsxs(Qt,{value:"individual",className:"text-xs gap-1",children:[e.jsx(Lo,{className:"h-3.5 w-3.5"})," Per Visitor"]})]}),e.jsxs(Jt,{value:"summary",className:"space-y-6",children:[o.map(h=>e.jsx(gFn,{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 x=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:[x?`${x.first_name} ${x.last_name||""}`.trim():"Visitor",":"]}),e.jsx("p",{className:"mt-0.5",children:p.text_value})]},p.id)})})]},h.id)})]}),e.jsx(Jt,{value:"individual",className:"space-y-4",children:d.map(h=>{const m=a[h],p=l.filter(x=>x.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(x=>{const g=i.find(y=>y.id===x.question_id);return g?e.jsxs("div",{className:"flex items-center justify-between text-sm",children:[e.jsx("span",{className:"text-muted-foreground",children:g.question_text}),e.jsx("span",{className:"font-medium",children:x.rating_value!=null?oHt[x.rating_value]||x.rating_value:x.text_value})]},x.id):null})})]},h)})})]})})]})}const vFn={question:{label:"Question",icon:Ji,color:"text-sky-700 dark:text-sky-300",bg:"bg-sky-100 dark:bg-sky-950"},showing:{label:"Showing",icon:ia,color:"text-orange-700 dark:text-orange-300",bg:"bg-orange-100 dark:bg-orange-950"},disclosure:{label:"Disclosures",icon:Wr,color:"text-indigo-700 dark:text-indigo-300",bg:"bg-indigo-100 dark:bg-indigo-950"},offer:{label:"Hot Lead",icon:qd,color:"text-emerald-700 dark:text-emerald-300",bg:"bg-emerald-100 dark:bg-emerald-950"}},r1t={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 bFn({openHouseId:s}){const{data:t=[],isLoading:n}=xws(s),r=gws(),[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(bT,{className:"h-4 w-4"}),"Virtual Open House Leads",e.jsx($e,{variant:"secondary",className:"ml-1",children:d.all}),d.new>0&&e.jsxs($e,{className:"bg-emerald-600 hover:bg-emerald-600",children:[d.new," new"]})]}),e.jsx("div",{className:"flex items-center gap-1 flex-wrap",children:[["all","All",d.all],["new","New",d.new],["offer","Hot",d.offer],["showing","Showings",d.showing],["question","Questions",d.question],["disclosure","Docs",d.disclosure]].map(([h,m,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=vFn[h.action_type],p=m.icon,x=h.payload||{},g=a===h.id,y=h.status==="contacted",b=h.status==="archived";return e.jsxs("li",{className:`transition-colors ${b?"opacity-60":""} ${h.status==="new"?"bg-emerald-50/40 dark:bg-emerald-950/10":""}`,children:[e.jsxs("button",{onClick:()=>i(g?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:x.visitor_name||"Visitor"}),e.jsx($e,{variant:"outline",className:`text-[10px] ${m.color}`,children:m.label}),h.status==="new"&&e.jsx("span",{className:"text-[10px] font-bold text-emerald-600 uppercase tracking-wide",children:"New"}),y&&e.jsxs("span",{className:"text-[10px] font-bold text-muted-foreground uppercase tracking-wide flex items-center gap-1",children:[e.jsx(Fr,{className:"h-3 w-3"}),"Contacted"]})]}),x.message&&e.jsxs("p",{className:"text-sm text-muted-foreground line-clamp-1 mt-0.5 italic",children:['"',x.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(Hr,{className:"h-3 w-3"}),Hs(new Date(h.created_at),"MMM d, h:mm a")]}),x.email&&e.jsxs("span",{className:"flex items-center gap-1 truncate",children:[e.jsx(nn,{className:"h-3 w-3"}),x.email]}),x.phone&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(ya,{className:"h-3 w-3"}),x.phone]})]})]}),g?e.jsx(_o,{className:"h-4 w-4 mt-1 text-muted-foreground"}):e.jsx(Ja,{className:"h-4 w-4 mt-1 text-muted-foreground"})]}),g&&e.jsxs("div",{className:"px-4 pb-4 pl-16 space-y-3",children:[x.message&&e.jsxs("div",{className:"bg-muted/40 rounded-md p-3 text-sm border-l-2 border-foreground/30",children:['"',x.message,'"']}),Object.keys(r1t).some(v=>x[v]!=null&&x[v]!==""&&!(Array.isArray(x[v])&&x[v].length===0))&&e.jsx("div",{className:"grid grid-cols-2 gap-x-4 gap-y-1.5 text-sm",children:Object.entries(r1t).map(([v,N])=>{const C=x[v];return C==null||C===""||Array.isArray(C)&&C.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(C)?C.join(", "):String(C)})]},v)})}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2 pt-1",children:[x.email&&e.jsx("a",{href:`mailto:${x.email}?subject=${encodeURIComponent("Re: your open house inquiry")}`,children:e.jsxs($,{size:"sm",variant:"default",className:"gap-1.5",children:[e.jsx(nn,{className:"h-3.5 w-3.5"}),"Reply"]})}),x.phone&&e.jsx("a",{href:`tel:${String(x.phone).replace(/[^0-9+]/g,"")}`,children:e.jsxs($,{size:"sm",variant:"outline",className:"gap-1.5",children:[e.jsx(ya,{className:"h-3.5 w-3.5"}),"Call"]})}),!y&&e.jsxs($,{size:"sm",variant:"outline",className:"gap-1.5",onClick:()=>u(h.id,"contacted"),children:[e.jsx(Fr,{className:"h-3.5 w-3.5"}),"Mark contacted"]}),b?e.jsx($,{size:"sm",variant:"ghost",className:"gap-1.5 text-muted-foreground",onClick:()=>u(h.id,"new"),children:"Restore"}):e.jsxs($,{size:"sm",variant:"ghost",className:"gap-1.5 text-muted-foreground",onClick:()=>u(h.id,"archived"),children:[e.jsx(Am,{className:"h-3.5 w-3.5"}),"Archive"]})]})]})]},h.id)})})]})}const a1t=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}`},_Fn=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"})},i1t=25;function wFn({open:s,onOpenChange:t,openHouse:n,variant:r="tour"}){var Ze;const a=r==="rsvp",{isGmailConnected:i,gmailEmail:l}=ux(),{data:o}=Kee(),c=!!(o!=null&&o.hasVerifiedSes),d=Za(),{data:u=[]}=Hb(),[h,m]=j.useState([]),[p,x]=j.useState(!1),[g,y]=j.useState("all"),[b,v]=j.useState([]),[N,C]=j.useState([]),[A,T]=j.useState(""),[P,M]=j.useState([]),[I,D]=j.useState(""),[B,q]=j.useState(""),[W,V]=j.useState(""),[K,Q]=j.useState("platform"),[J,ce]=j.useState(!1),[ue,ne]=j.useState(0),[ee,le]=j.useState(!1),he=a?`https://guestbook.relevelup.com/rsvp/${n.slug}`:`https://guestbook.relevelup.com/${n.slug}`,ve=_Fn(n.event_date),ge=n.start_time?`${a1t(n.start_time)}${n.end_time?` – ${a1t(n.end_time)}`:""}`:"",fe=[ve,ge].filter(Boolean).join(" · ");j.useEffect(()=>{s&&(q(a?`You're invited: Open House at ${n.property_address}`:`Take a virtual tour of ${n.property_address}`),V(a?`I'm hosting an open house at ${n.property_address}${ve?` on ${ve}`:""}${ge?` from ${ge}`:""}. 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.`),C([]),v([]),M([]),T(""),y("all"),ne(0),Q(c?"ses":i?"gmail":"platform"),h.length===0&&je())},[s,n.id,i,c]);const je=async()=>{if(d){x(!0);try{const Ue=[];let Qe=0;for(;;){const{data:Ge,error:nt}=await U.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(Qe,Qe+1e3-1);if(nt)throw nt;const ft=Ge||[];if(Ue.push(...ft),ft.length<1e3)break;Qe+=1e3}m(Ue.map(Ge=>({id:Ge.id,first_name:Ge.first_name,last_name:Ge.last_name,email:Ge.email,tagIds:(Ge.tags||[]).map(nt=>nt.relationship_type_id)})))}catch{ae.error("Failed to load contacts")}finally{x(!1)}}},Ee=Ue=>`${Ue.first_name} ${Ue.last_name||""}`.trim(),Me=j.useMemo(()=>{const Ue=I.trim().toLowerCase();return Ue?h.filter(et=>`${Ee(et)} ${et.email||""}`.toLowerCase().includes(Ue)):h},[h,I]),De=j.useMemo(()=>{const Ue={};return h.forEach(et=>et.tagIds.forEach(Qe=>{Ue[Qe]=(Ue[Qe]||0)+1})),Ue},[h]),ze=j.useMemo(()=>g==="all"?h:g==="tags"?b.length===0?[]:h.filter(Ue=>Ue.tagIds.some(et=>b.includes(et))):h.filter(Ue=>N.includes(Ue.id)),[g,h,b,N]),ke=j.useMemo(()=>{const Ue=new Set,et=[];return[...ze.map(Qe=>({email:Qe.email,name:Ee(Qe)})),...P].forEach(Qe=>{const Ge=Qe.email.toLowerCase();!Qe.email||Ue.has(Ge)||(Ue.add(Ge),et.push(Qe))}),et},[ze,P]),Xe=()=>{const Ue=A.trim();if(Ue){if(!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(Ue)){ae.error("Invalid email");return}M(et=>[...et,{email:Ue,name:Ue.split("@")[0]}]),T("")}},Se=Ue=>Ue.replace(/&/g,"&").replace(//g,">"),Re=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||"",Ae=Ue=>{const et=Ue?`Hi ${Se(Ue)},`:"Hi there,",Qe=[n.city,n.state].filter(Boolean).join(", "),Ge=Se(W).split(/\n\n+/).map(nt=>`

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

`).join("");return`
${Re?``:""} ${a&&fe?``:""}

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

${Se(n.property_address)}

${Qe?`

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

`:""}
 

When

${Se(fe)}

${et}

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

Or copy this link:
${he}

`},Be=j.useMemo(()=>Ae("Alex"),[W,n.id,Re,a,fe]),qe=async()=>{var Ue;if(ke.length===0){ae.error("Add at least one recipient");return}ce(!0),ne(0);try{if(K==="gmail"&&i){let et=0;for(const Qe of ke){const{data:Ge,error:nt}=await U.functions.invoke("gmail-send",{body:{to:Qe.email,subject:B,body:Ae((Ue=Qe.name)==null?void 0:Ue.split(" ")[0])}});!nt&&(Ge!=null&&Ge.success)&&(et+=1),ne(et)}if(et===0)throw new Error("Gmail send failed");ae.success(`Sent to ${et} of ${ke.length} via Gmail`)}else{let et=0;for(let Qe=0;Qe{await navigator.clipboard.writeText(he),le(!0),setTimeout(()=>le(!1),1500)};return e.jsx(Os,{open:s,onOpenChange:t,children:e.jsxs(Rs,{className:"sm:max-w-[900px] w-[calc(100vw-2rem)] max-h-[92vh] overflow-y-auto overflow-x-hidden",children:[e.jsxs(Us,{className:"min-w-0",children:[e.jsxs(zs,{className:"flex items-center gap-2",children:[e.jsx(nn,{className:"h-5 w-5 text-primary"}),a?"Invite to Open House":"Email Virtual Tour"]}),e.jsx(Sr,{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(kc,{className:"h-4 w-4 text-muted-foreground shrink-0"}),e.jsx("code",{className:"flex-1 min-w-0 text-xs truncate",children:he}),e.jsxs($,{variant:"ghost",size:"sm",onClick:Ke,className:"shrink-0 h-7 gap-1",children:[ee?e.jsx(oa,{className:"h-3.5 w-3.5 text-emerald-600"}):e.jsx(Ca,{className:"h-3.5 w-3.5"}),ee?"Copied":"Copy"]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(se,{className:"flex items-center gap-1.5",children:[e.jsx(nn,{className:"h-3.5 w-3.5"}),"Send from"]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[c&&e.jsx($,{type:"button",variant:K==="ses"?"default":"outline",size:"sm",onClick:()=>Q("ses"),className:"gap-1.5",children:"Mass Email (your address)"}),i&&e.jsx($,{type:"button",variant:K==="gmail"?"default":"outline",size:"sm",onClick:()=>Q("gmail"),className:"gap-1.5",children:"Gmail"}),e.jsx($,{type:"button",variant:K==="platform"?"default":"outline",size:"sm",onClick:()=>Q("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(se,{className:"flex items-center gap-1.5",children:[e.jsx(qn,{className:"h-3.5 w-3.5"}),"Who should receive this?"]}),e.jsxs(ua,{value:g,onValueChange:Ue=>y(Ue),children:[e.jsxs(ha,{className:"grid w-full grid-cols-3",children:[e.jsx(Qt,{value:"all",children:"All contacts"}),e.jsx(Qt,{value:"tags",children:"By tag"}),e.jsx(Qt,{value:"select",children:"Pick people"})]}),e.jsx(Jt,{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(Jt,{value:"tags",className:"pt-3",children:e.jsx(Oi,{className:"h-[210px] rounded-lg border p-2",children:e.jsxs("div",{className:"space-y-1",children:[u.map(Ue=>{const et=b.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(ui,{checked:et,onCheckedChange:()=>v(Qe=>et?Qe.filter(Ge=>Ge!==Ue.id):[...Qe,Ue.id])}),e.jsxs("span",{className:"flex items-center gap-1.5 text-sm flex-1 min-w-0 truncate",children:[e.jsx(Up,{className:"h-3 w-3 text-muted-foreground shrink-0"}),Ue.name]}),e.jsx("span",{className:"text-xs text-muted-foreground",children:De[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(Jt,{value:"select",className:"pt-3 space-y-2",children:[e.jsxs("div",{className:"relative",children:[e.jsx(Vr,{className:"absolute left-2.5 top-2.5 h-3.5 w-3.5 text-muted-foreground"}),e.jsx(be,{value:I,onChange:Ue=>D(Ue.target.value),placeholder:"Search contacts...",className:"pl-8 h-9"})]}),e.jsx(Oi,{className:"h-[210px] rounded-lg border p-2",children:e.jsxs("div",{className:"space-y-1",children:[Me.slice(0,300).map(Ue=>{const et=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(ui,{checked:et,onCheckedChange:()=>C(Qe=>et?Qe.filter(Ge=>Ge!==Ue.id):[...Qe,Ue.id])}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("div",{className:"text-sm font-medium truncate",children:Ee(Ue)||"(no name)"}),e.jsx("div",{className:"text-xs text-muted-foreground truncate",children:Ue.email})]})]},Ue.id)}),Me.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(be,{value:A,onChange:Ue=>T(Ue.target.value),placeholder:"Also send to an email...",type:"email",onKeyDown:Ue=>{Ue.key==="Enter"&&(Ue.preventDefault(),Xe())}}),e.jsx($,{type:"button",variant:"outline",size:"sm",onClick:Xe,children:"Add"})]}),P.length>0&&e.jsx("div",{className:"flex flex-wrap gap-1.5",children:P.map(Ue=>e.jsxs($e,{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(et=>et.filter(Qe=>Qe.email!==Ue.email)),className:"hover:bg-muted-foreground/20 rounded p-0.5",children:e.jsx(pr,{className:"h-3 w-3"})})]},Ue.email))})]}),e.jsx(Hl,{}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{htmlFor:"vt-subject",children:"Subject"}),e.jsx(be,{id:"vt-subject",value:B,onChange:Ue=>q(Ue.target.value)})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{htmlFor:"vt-message",children:"Message"}),e.jsx(Is,{id:"vt-message",value:W,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(se,{className:"flex items-center gap-1.5",children:[e.jsx(ga,{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:`${Be}`,className:"w-full h-[420px] lg:h-[560px] border-0 bg-white",sandbox:""})})]})]}),e.jsxs("div",{className:Tt("flex flex-wrap items-center justify-between gap-3 pt-2 border-t"),children:[e.jsxs("p",{className:"text-sm text-muted-foreground",children:[e.jsx("span",{className:"font-semibold text-foreground",children:ke.length.toLocaleString()})," recipient",ke.length===1?"":"s",J&&ue>0&&e.jsxs("span",{children:[" · sent ",ue]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx($,{variant:"outline",onClick:()=>t(!1),disabled:J,children:"Cancel"}),e.jsxs($,{onClick:qe,disabled:J||ke.length===0||!B.trim(),className:"gap-2",children:[J?e.jsx(Ht,{className:"h-4 w-4 animate-spin"}):e.jsx(Br,{className:"h-4 w-4"}),J?"Sending...":`Send${ke.length?` to ${ke.length}`:""}`]})]})]})]})})}function jFn({openHouseId:s}){const{data:t=[],isLoading:n}=Pws(s),r=Dws(s),a=Rws(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(gy,{className:"h-4 w-4 text-primary"}),e.jsx("span",{className:"text-sm font-semibold",children:"RSVPs"}),e.jsx($e,{variant:"secondary",className:"text-[11px]",children:t.length})]}),t.length>0&&e.jsxs("span",{className:"text-xs text-muted-foreground",children:[i," checked in"]})]}),n?e.jsx("div",{className:"px-4 py-6 text-sm text-muted-foreground",children:"Loading RSVPs…"}):t.length===0?e.jsxs("div",{className:"px-4 py-6 text-center",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"No RSVPs yet."}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"Send an invite to your database to start filling the list."})]}):e.jsx("ul",{className:"divide-y divide-border",children:t.map(l=>e.jsxs("li",{className:"flex items-center gap-3 px-4 py-3",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx("span",{className:"text-sm font-medium truncate",children:[l.first_name,l.last_name].filter(Boolean).join(" ")}),l.checked_in_at&&e.jsxs($e,{className:"text-[10px] gap-1",children:[e.jsx(oa,{className:"h-3 w-3"}),"Checked in"]}),l.has_agent&&e.jsxs($e,{variant:"outline",className:"text-[10px] gap-1",children:[e.jsx(Yj,{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(nn,{className:"h-3 w-3"}),l.email]}),l.phone&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(ya,{className:"h-3 w-3"}),l.phone]})]}),l.message&&e.jsxs("p",{className:"text-xs text-muted-foreground mt-1 italic",children:["“",l.message,"”"]})]}),e.jsx($,{variant:l.checked_in_at?"secondary":"outline",size:"sm",className:"h-8 text-xs",onClick:()=>a.mutate({id:l.id,checkedIn:!l.checked_in_at}),children:l.checked_in_at?"Undo":"Check in"}),e.jsx($,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0 text-muted-foreground hover:text-destructive","aria-label":"Delete RSVP",onClick:()=>r.mutate(l.id),children:e.jsx(Pn,{className:"h-4 w-4"})})]},l.id))})]})}function NFn({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(sn,{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(Rx,{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(Vr,{className:"pointer-events-none absolute left-3.5 top-1/2 h-4 w-4 -translate-y-1/2 opacity-70"}),e.jsx(be,{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:Tt("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 o1t={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 kFn({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(qn,{className:"h-6 w-6 text-primary"})}),e.jsx("p",{className:"text-sm font-semibold text-foreground",children:"No sign-ins yet"}),e.jsx("p",{className:"mx-auto mt-1 max-w-sm text-xs text-muted-foreground",children:"Share the link or print the QR flyer so visitors can sign in from their phone."}),n&&e.jsxs($,{variant:"outline",size:"sm",className:"mt-4 gap-1.5",onClick:n,children:[e.jsx(vd,{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(yd,{className:"h-3 w-3"}),r," hot"]})]}),e.jsxs($,{variant:"outline",size:"sm",onClick:t,className:"h-7 gap-1 text-xs",children:[e.jsx(di,{className:"h-3 w-3"}),"Export CSV"]})]}),e.jsx("div",{className:"max-h-[420px] overflow-auto rounded-xl border border-border",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{className:"sticky top-0 z-10 bg-muted/80 backdrop-blur",children:e.jsxs("tr",{className:"text-[11px] uppercase tracking-wide text-muted-foreground",children:[e.jsx("th",{className:"p-2.5 text-left font-semibold",children:"Name"}),e.jsx("th",{className:"hidden p-2.5 text-left font-semibold sm:table-cell",children:"Contact"}),e.jsx("th",{className:"hidden p-2.5 text-left font-semibold md:table-cell",children:"Intent"}),e.jsx("th",{className:"p-2.5 text-left font-semibold",children:"Time"})]})}),e.jsx("tbody",{children:s.map(a=>{var o,c;const i=a.visitor_intent==="buying"&&!a.has_agent,l=o1t[a.visitor_intent||""]||o1t.browsing;return e.jsxs("tr",{className:Tt("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:Tt("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:Tt("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:Hs(new Date(a.created_at),"h:mm a")})]},a.id)})})]})})]})}const LNe="guestbook.relevelup.com";function SFn(){const{data:s,isLoading:t}=Y_s(),n=Z_s(),r=DAt(),a=X_s(),[i,l]=j.useState(!1),[o,c]=j.useState(null),[d,u]=j.useState(""),[h,m]=j.useState("all"),[p,x]=j.useState(!1),{user:g}=_s(),y=Za(),[b,v]=j.useState(null),[N,C]=j.useState(null),[A,T]=j.useState(!1),P=j.useRef(null),[M,I]=j.useState({property_address:"",city:"",state:"",zip:"",event_date:Hs(new Date,"yyyy-MM-dd"),start_time:"10:00",end_time:"14:00",agent_greeting:"Welcome! Please sign in below.",event_type:"property",kind:"physical",tour_mode:"rooms"}),D=ee=>{var he;const le=(he=ee.target.files)==null?void 0:he[0];if(le){if(le.size>5*1024*1024){ja({title:"Photo must be under 5MB",variant:"destructive"});return}v(le),C(URL.createObjectURL(le))}},B=()=>{v(null),C(null),P.current&&(P.current.value="")},q=async()=>{if(!M.property_address){ja({title:M.event_type==="community"?"Event name is required":"Address is required",variant:"destructive"});return}let ee;if(b&&g){T(!0);const he=b.name.split(".").pop(),ve=`${y}/${Date.now()}.${he}`,{error:ge}=await U.storage.from("open-house-photos").upload(ve,b,{upsert:!0});if(ge){ja({title:"Photo upload failed",description:ge.message,variant:"destructive"}),T(!1);return}const{data:fe}=U.storage.from("open-house-photos").getPublicUrl(ve);ee=fe.publicUrl,T(!1)}const le=M.kind==="virtual"?{...M,start_time:void 0,end_time:void 0,photo_url:ee}:{...M,photo_url:ee};await n.mutateAsync(le),l(!1),I({property_address:"",city:"",state:"",zip:"",event_date:Hs(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"}),B()},W=ee=>{navigator.clipboard.writeText(`https://${LNe}/${ee}`),ja({title:"Link copied!"})},V=Hs(new Date,"yyyy-MM-dd"),K=j.useMemo(()=>{const ee=s??[],le=d.trim().toLowerCase(),he=ke=>!le||[ke.property_address,ke.city,ke.state].filter(Boolean).join(" ").toLowerCase().includes(le),ve=ee.filter(he),ge=ve.filter(ke=>ke.kind==="virtual"),fe=ve.filter(ke=>ke.kind!=="virtual"),je=fe.filter(ke=>ke.event_date===V),Ee=fe.filter(ke=>ke.event_date>V).sort((ke,Xe)=>ke.event_date.localeCompare(Xe.event_date)),Me=fe.filter(ke=>ke.event_dateXe.event_date.localeCompare(ke.event_date)),De=ee.reduce((ke,Xe)=>ke+(Xe.visitor_count||0),0),ze=ee.reduce((ke,Xe)=>ke+(Xe.qr_scan_count||0),0);return{today:je,upcoming:Ee,past:Me,virtual:ge,totalSignIns:De,totalScans:ze}},[s,d,V]),Q=K.today.length+K.upcoming.length,J=Q>0?`${Q} upcoming · ${K.totalSignIns.toLocaleString()} total sign-ins`:`${K.totalSignIns.toLocaleString()} total sign-ins collected`,ce=ee=>h==="all"||h===ee,ue=ee=>m(le=>le===ee?"all":ee),ne=ee=>e.jsx(CFn,{openHouse:ee,isExpanded:o===ee.id,onToggle:()=>c(o===ee.id?null:ee.id),onCopyLink:()=>W(ee.slug||""),onToggleActive:()=>r.mutate({id:ee.id,is_active:!ee.is_active}),onDelete:()=>a.mutate(ee.id),isToday:ee.kind!=="virtual"&&ee.event_date===V},ee.id);return e.jsxs(Ks,{title:"Guest Book",children:[e.jsx(Ul,{children:e.jsx("title",{children:"Guest Book | LevelUp"})}),e.jsxs("div",{className:"space-y-6",children:[e.jsx(NFn,{summary:J,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(Os,{open:i,onOpenChange:l,children:[e.jsx(Ko,{asChild:!0,children:e.jsx("span",{className:"sr-only",children:"Open create dialog"})}),e.jsxs(Rs,{className:"sm:max-w-lg max-h-[90vh] flex flex-col",children:[e.jsxs(Us,{children:[e.jsx(zs,{children:"Create Open House"}),e.jsx(Sr,{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(se,{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(ee=>({...ee,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(ee=>({...ee,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(ee=>({...ee,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(ee=>({...ee,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(se,{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(ee=>({...ee,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(ee=>({...ee,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(se,{children:M.event_type==="community"?"Event Name *":"Property Address *"}),e.jsx(be,{value:M.property_address,onChange:ee=>I(le=>({...le,property_address:ee.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(se,{children:"City"}),e.jsx(be,{value:M.city,onChange:ee=>I(le=>({...le,city:ee.target.value})),placeholder:"Austin"})]}),e.jsxs("div",{children:[e.jsx(se,{children:"State"}),e.jsx(be,{value:M.state,onChange:ee=>I(le=>({...le,state:ee.target.value})),placeholder:"TX",maxLength:2})]}),e.jsxs("div",{children:[e.jsx(se,{children:"ZIP"}),e.jsx(be,{value:M.zip,onChange:ee=>I(le=>({...le,zip:ee.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(se,{children:"Date"}),e.jsx(be,{type:"date",value:M.event_date,onChange:ee=>I(le=>({...le,event_date:ee.target.value}))})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Start Time"}),e.jsx(be,{type:"time",value:M.start_time,onChange:ee=>I(le=>({...le,start_time:ee.target.value}))})]}),e.jsxs("div",{children:[e.jsx(se,{children:"End Time"}),e.jsx(be,{type:"time",value:M.end_time,onChange:ee=>I(le=>({...le,end_time:ee.target.value}))})]})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Welcome Message"}),e.jsx(Is,{value:M.agent_greeting,onChange:ee=>I(le=>({...le,agent_greeting:ee.target.value})),placeholder:"Welcome! Please sign in below."})]}),e.jsxs("div",{children:[e.jsx(se,{children:M.event_type==="community"?"Event Photo":"Property Photo"}),e.jsx("input",{ref:P,type:"file",accept:"image/*",onChange:D,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:B,className:"absolute top-2 right-2 bg-black/60 hover:bg-black/80 text-white rounded-full p-1 transition-colors",children:e.jsx(pr,{className:"h-4 w-4"})})]}):e.jsxs("button",{type:"button",onClick:()=>{var ee;return(ee=P.current)==null?void 0:ee.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(x1,{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($,{onClick:q,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(ee=>e.jsx(_e,{className:"animate-pulse",children:e.jsxs(Bt,{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"})]})},ee))}):s!=null&&s.length?e.jsxs("div",{className:"space-y-8",children:[K.today.length>0&&ce("today")&&e.jsxs("section",{className:"space-y-3",children:[e.jsx(SDe,{title:"Happening Today",count:K.today.length,accent:!0}),e.jsx("div",{className:"space-y-4",children:K.today.map(ne)})]}),K.upcoming.length>0&&ce("upcoming")&&e.jsxs("section",{className:"space-y-3",children:[e.jsx(SDe,{title:"Upcoming",count:K.upcoming.length}),e.jsx("div",{className:"space-y-4",children:K.upcoming.map(ne)})]}),K.virtual.length>0&&ce("virtual")&&e.jsxs("section",{className:"space-y-3",children:[e.jsx(SDe,{title:"Virtual Tours",count:K.virtual.length}),e.jsx("div",{className:"space-y-4",children:K.virtual.map(ne)})]}),K.past.length>0&&h==="all"&&e.jsxs("section",{className:"space-y-3",children:[e.jsxs("button",{onClick:()=>x(ee=>!ee),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(Uj,{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(jg,{className:"h-4 w-4 text-muted-foreground"}):e.jsx(_o,{className:"h-4 w-4 text-muted-foreground"})]}),p&&e.jsx("div",{className:"space-y-4",children:K.past.map(ne)})]}),Q===0&&K.virtual.length===0&&K.past.length===0&&e.jsx(_e,{className:"border-dashed",children:e.jsxs(Oe,{className:"py-12 text-center text-sm text-muted-foreground",children:["No open houses match “",d,"”."]})})]}):e.jsx(_e,{className:"border-dashed",children:e.jsxs(Oe,{className:"flex flex-col items-center justify-center py-16 text-center",children:[e.jsx("div",{className:"w-16 h-16 rounded-2xl bg-primary/10 flex items-center justify-center mb-4",children:e.jsx(Rx,{className:"h-8 w-8 text-primary"})}),e.jsx("h3",{className:"text-lg font-semibold mb-1",children:"No Open Houses Yet"}),e.jsx("p",{className:"text-muted-foreground text-sm max-w-sm mb-6",children:"Create your first open house to get a beautiful, mobile-friendly sign-in page with a shareable link and QR code."}),e.jsxs($,{onClick:()=>l(!0),children:[e.jsx(sn,{className:"h-4 w-4 mr-2"}),"Create Your First Open House"]})]})})]})]})}function SDe({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 CFn({openHouse:s,isExpanded:t,onToggle:n,onCopyLink:r,onToggleActive:a,onDelete:i,isToday:l}){const{data:o}=IAt(t?s.id:void 0),{data:c}=ht({queryKey:["agent-profile-flyer",s.agent_id],queryFn:async()=>{const{data:M,error:I}=await U.from("profiles").select("name, avatar_url, phone, title, brokerages:brokerage_id(name)").eq("id",s.agent_id).single();if(I)throw I;const D=M.brokerages;return{...M,brokerage_name:(D==null?void 0:D.name)||null}},enabled:!!s.agent_id}),[d,u]=j.useState(!1),[h,m]=j.useState(!1),[p,x]=j.useState(!1),[g,y]=j.useState(!1),b=j.useRef(null),v=`https://${LNe}/${s.slug}`,N=M=>{if(!M)return"";const[I,D]=M.split(":"),B=parseInt(I),q=B>=12?"PM":"AM";return`${B>12?B-12:B||12}:${D} ${q}`},C=()=>{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,'""'),Hs(new Date(V.created_at),"MM/dd/yyyy h:mm a")]),D=[M,...I].map(V=>V.map(K=>`"${K}"`).join(",")).join(` `),B=new Blob([D],{type:"text/csv"}),q=URL.createObjectURL(B),W=document.createElement("a");W.href=q,W.download=`${s.property_address.replace(/[^a-zA-Z0-9]/g,"-")}-visitors.csv`,W.click(),URL.revokeObjectURL(q)},A=j.useCallback(()=>{if(!b.current)return;const M=b.current.querySelector("svg");if(!M)return;const I=new XMLSerializer().serializeToString(M),D=document.createElement("canvas");D.width=1024,D.height=1024;const B=D.getContext("2d"),q=new Image;q.onload=()=>{B==null||B.drawImage(q,0,0,1024,1024);const W=document.createElement("a");W.download=`${s.property_address.replace(/[^a-zA-Z0-9]/g,"-")}-qr.png`,W.href=D.toDataURL("image/png"),W.click()},q.src="data:image/svg+xml;base64,"+btoa(unescape(encodeURIComponent(I)))},[s.property_address]),T=j.useCallback(()=>{var Re;if(!b.current)return;const M=b.current.querySelector("svg");if(!M)return;const I=new XMLSerializer().serializeToString(M),D="data:image/svg+xml;base64,"+btoa(unescape(encodeURIComponent(I))),B=Hs(new Date(s.event_date+"T00:00:00"),"EEEE, MMMM d, yyyy"),q=s.start_time?`${N(s.start_time)}${s.end_time?" – "+N(s.end_time):""}`:"",W=[s.city,s.state].filter(Boolean).join(", "),V=s.agent_greeting||"Welcome! Please sign in below.",K=!!s.photo_url,Q=!!c,J=K||Q,ce=K&&Q,ue=ce?"0.35in 0.75in 0.3in":"0.55in 0.75in 0.45in",ne=ce?"28px":"34px",ee=ce?"0.2in 0.75in":J?"0.3in 0.75in":"0.4in 0.75in",le=J?"0.15in":"0.3in",he=J?"0.15in":"0.3in",ve=ce?"14px 36px":"22px 44px",ge=ce?"20px":"24px",fe=J?"0.2in":"0.35in",je=ce?"1.8in":"2.4in",Ee=J?"0.15in":"0.3in",Me=ce?"140px":J?"160px":"200px",De=ce?"16px":"24px",ze=ce?"10px 20px":"16px 28px",ke=ce?"44px":"56px",Xe="0.15in",Se=window.open("","_blank");Se&&(Se.document.write(` Open House – ${s.property_address}
${s.event_type==="community"?"Community Event":"Open House"}
${s.property_address}
${W?`
${W}${s.zip?" "+s.zip:""}
`:""}
Date
${B}
${q?`
Time
${q}
`:""}
${V}
${c?`
${c.avatar_url?`${c.name}`:`
${((Re=c.name)==null?void 0:Re.charAt(0))||"A"}
`}
Hosted By
${c.name}
${c.title?`
${c.title}
`:""} ${c.brokerage_name?`
${c.brokerage_name}
`:""} ${c.phone?`
${c.phone}
`:""}
`:""} ${s.photo_url?`Property`:""}
QR Code
Scan to Sign In
Point your phone camera at the QR code
`),Se.document.close(),setTimeout(()=>{Se.focus(),Se.print()},500))},[s,v,c]),P=async()=>{y(!0);try{const{error:M}=await U.functions.invoke("guestbook-email-link",{body:{openHouseId:s.id}});if(M)throw M;ja({title:"Email sent!",description:"Check your inbox for the guest book link."})}catch(M){ja({title:"Failed to send",description:M.message,variant:"destructive"})}finally{y(!1)}};return e.jsxs(_e,{className:Tt("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:Tt("absolute inset-y-0 left-0 w-1",l?"bg-emerald-500":s.kind==="virtual"?"bg-purple-500/70":"bg-primary/40")}),e.jsx(Bt,{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(Ut,{className:"text-base leading-snug break-words",children:s.property_address}),e.jsxs("div",{className:"flex items-center gap-1.5 mt-1.5 flex-wrap",children:[l&&e.jsxs($e,{className:"shrink-0 gap-1 border-none bg-emerald-500/15 text-[11px] text-emerald-700 dark:text-emerald-300",children:[e.jsx(Cg,{className:"h-3 w-3"}),"Today"]}),e.jsx($e,{variant:s.is_active?"default":"secondary",className:"shrink-0 text-[11px]",children:s.is_active?"Active":"Inactive"}),s.kind==="virtual"?e.jsxs($e,{variant:"outline",className:"shrink-0 gap-1 text-[11px] bg-purple-500/10 text-purple-700 dark:text-purple-300 border-purple-500/20",children:[e.jsx(ga,{className:"h-3 w-3"}),"Virtual"]}):e.jsxs($e,{variant:"outline",className:"shrink-0 gap-1 text-[11px] bg-emerald-500/10 text-emerald-700 dark:text-emerald-300 border-emerald-500/20",children:[e.jsx(ai,{className:"h-3 w-3"}),"In-Person"]}),s.agent_name&&e.jsxs($e,{variant:"outline",className:"shrink-0 gap-1 text-[11px] bg-blue-500/10 text-blue-700 dark:text-blue-300 border-blue-500/20",children:[e.jsx(Lo,{className:"h-3 w-3"}),s.agent_name]}),s.event_type==="community"&&e.jsxs($e,{variant:"outline",className:"shrink-0 gap-1 text-[11px]",children:[e.jsx(Ai,{className:"h-3 w-3"}),"Community"]})]})]}),e.jsx($,{variant:"ghost",size:"icon",onClick:n,className:"shrink-0 -mr-2 -mt-1",children:t?e.jsx(jg,{className:"h-4 w-4"}):e.jsx(_o,{className:"h-4 w-4"})})]}),e.jsxs(vr,{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(ai,{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(Hr,{className:"h-3 w-3"}),"Always on"]}):e.jsxs(e.Fragment,{children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(ia,{className:"h-3 w-3"}),Hs(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(Hr,{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(qn,{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(Rx,{className:"h-3.5 w-3.5 text-primary"}),s.qr_scan_count,e.jsx("span",{className:"font-normal text-muted-foreground",children:"scans"})]})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs($,{variant:"outline",size:"sm",onClick:()=>window.location.href=`/mission-control/guest-book/live/${s.id}`,className:"h-8 gap-1.5 text-xs text-emerald-600 border-emerald-500/30 hover:bg-emerald-500/10 dark:text-emerald-400",children:[e.jsx(Cg,{className:"h-3.5 w-3.5"}),"Live"]}),e.jsxs($,{variant:"outline",size:"sm",onClick:r,className:"h-8 gap-1.5 text-xs",children:[e.jsx(Ca,{className:"h-3.5 w-3.5"}),"Copy Link"]}),e.jsxs($,{variant:"outline",size:"sm",onClick:()=>u(!0),className:"h-8 gap-1.5 text-xs",children:[e.jsx(Rx,{className:"h-3.5 w-3.5"}),"QR Code"]}),s.kind==="virtual"?e.jsxs($,{variant:"outline",size:"sm",onClick:()=>x(!0),className:"h-8 gap-1.5 text-xs text-primary border-primary/30 hover:bg-primary/10",children:[e.jsx(vd,{className:"h-3.5 w-3.5"}),"Email Tour"]}):e.jsxs(e.Fragment,{children:[e.jsxs($,{variant:"outline",size:"sm",onClick:()=>x(!0),className:"h-8 gap-1.5 text-xs text-primary border-primary/30 hover:bg-primary/10",children:[e.jsx(nn,{className:"h-3.5 w-3.5"}),"Invite"]}),e.jsxs($,{variant:"outline",size:"sm",onClick:()=>window.open(`${v}?kiosk=1`,"_blank"),className:"h-8 gap-1.5 text-xs",children:[e.jsx(qz,{className:"h-3.5 w-3.5"}),"Tablet Mode"]})]}),e.jsxs($,{variant:"outline",size:"sm",onClick:()=>m(!0),className:"h-8 gap-1.5 text-xs",children:[e.jsx(pc,{className:"h-3.5 w-3.5"}),"Settings"]}),e.jsxs(Hd,{children:[e.jsx(Gd,{asChild:!0,children:e.jsx($,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0","aria-label":"More actions",children:e.jsx(p0,{className:"h-4 w-4"})})}),e.jsxs(Md,{align:"end",className:"w-52",children:[e.jsxs(Na,{onClick:()=>window.open(v,"_blank"),children:[e.jsx(Tr,{className:"mr-2 h-4 w-4"}),"Preview sign-in page"]}),s.kind==="virtual"?e.jsxs(Na,{onClick:()=>window.open(`/guestbook/${s.slug}?preview=1`,"_blank"),children:[e.jsx(ga,{className:"mr-2 h-4 w-4"}),"Preview tour"]}):e.jsxs(Na,{onClick:()=>window.open(`https://${LNe}/rsvp/${s.slug}`,"_blank"),children:[e.jsx(gy,{className:"mr-2 h-4 w-4"}),"Preview RSVP page"]}),e.jsxs(Na,{onClick:a,children:[s.is_active?e.jsx(b0,{className:"mr-2 h-4 w-4"}):e.jsx(ga,{className:"mr-2 h-4 w-4"}),s.is_active?"Deactivate":"Activate"]}),e.jsx(S0,{}),e.jsxs(Na,{onClick:i,className:"text-destructive focus:text-destructive",children:[e.jsx(Pn,{className:"mr-2 h-4 w-4"}),"Delete"]})]})]})]})]})}),t&&e.jsxs(Oe,{className:"pt-0",children:[e.jsx(Hl,{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://",LNe,"/",s.slug]})]}),e.jsx(kFn,{visitors:o??[],onExport:C}),s.kind!=="virtual"&&e.jsx("div",{className:"mt-4",children:e.jsx(jFn,{openHouseId:s.id})}),s.kind==="virtual"&&e.jsx("div",{className:"mt-4",children:e.jsx(bFn,{openHouseId:s.id})}),s.enable_survey&&e.jsx("div",{className:"mt-4",children:e.jsx(yFn,{openHouseId:s.id})})]}),e.jsx(Os,{open:d,onOpenChange:u,children:e.jsxs(Rs,{className:"sm:max-w-sm",children:[e.jsxs(Us,{children:[e.jsx(zs,{children:"QR Code"}),e.jsx(Sr,{className:"truncate",children:s.property_address})]}),e.jsxs("div",{className:"flex flex-col items-center gap-4 py-4",children:[e.jsx("div",{ref:b,className:"bg-white p-4 rounded-xl",children:e.jsx(XN,{value:v,size:240,level:"H"})}),e.jsx("p",{className:"text-xs text-muted-foreground text-center break-all",children:v}),e.jsxs("div",{className:"flex gap-2 w-full",children:[e.jsxs($,{variant:"outline",className:"flex-1",onClick:A,children:[e.jsx(di,{className:"h-4 w-4 mr-2"}),"Download"]}),e.jsxs($,{variant:"outline",className:"flex-1",onClick:T,children:[e.jsx(AT,{className:"h-4 w-4 mr-2"}),"Print Flyer"]})]}),e.jsxs($,{variant:"default",className:"w-full",onClick:P,disabled:g,children:[e.jsx(nn,{className:"h-4 w-4 mr-2"}),g?"Sending...":"Email Link to Me"]})]})]})}),e.jsx(xFn,{open:h,onOpenChange:m,openHouse:s}),e.jsx(wFn,{open:p,onOpenChange:x,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}})]})}function AFn(){const{slug:s}=Vi();return s?e.jsx(HTt,{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 lHt({photoUrl:s,videoUrl:t,onPhotoChange:n,onVideoChange:r,contactId:a}){const{user:i}=_s(),l=F5(),o=j.useRef(null),c=j.useRef(null),[d,u]=j.useState(!1),[h,m]=j.useState(!1),[p,x]=j.useState(0),g=async b=>{if(i){u(!0);try{const v=b.name.split(".").pop()||"jpg",N=`${i.id}/card-${Date.now()}.${v}`,{error:C}=await U.storage.from("listing-photos").upload(N,b);if(C)throw C;const{data:{publicUrl:A}}=U.storage.from("listing-photos").getPublicUrl(N);n(A),ae.success("Photo uploaded")}catch(v){ae.error(v.message||"Failed to upload photo")}finally{u(!1)}}},y=async b=>{if(i){if(b.size>500*1024*1024){ae.error("Video must be under 500MB");return}m(!0),x(0);try{const{videoId:v,libraryId:N}=await Z6(`Card Video - ${Date.now()}`),{uploadUrl:C,apiKey:A}=await X6(v);await new Promise((M,I)=>{const D=new XMLHttpRequest;D.upload.addEventListener("progress",B=>{B.lengthComputable&&x(Math.round(B.loaded/B.total*100))}),D.addEventListener("load",()=>{D.status>=200&&D.status<300?M():I(new Error("Upload failed"))}),D.addEventListener("error",()=>I(new Error("Upload failed"))),D.open("PUT",C),D.setRequestHeader("AccessKey",A),D.send(b)});const T=`https://iframe.mediadelivery.net/embed/${N}/${v}`;r(T);const P=parseFloat((b.size/(1024*1024)).toFixed(2));await l.mutateAsync({bunny_video_id:v,playback_url:`https://iframe.mediadelivery.net/play/${N}/${v}`,file_size_mb:P,title:"Card Video",status:"processing",touch_type:"video",contact_id:a||void 0}),ae.success("Video uploaded & added to your library")}catch(v){ae.error(v.message||"Failed to upload video")}finally{m(!1),x(0)}}};return e.jsxs("div",{className:"space-y-3",children:[e.jsx(se,{children:"Media (optional)"}),e.jsxs(ua,{defaultValue:"photo",className:"w-full",children:[e.jsxs(ha,{className:"grid w-full grid-cols-2",children:[e.jsxs(Qt,{value:"photo",className:"gap-1.5 text-xs",children:[e.jsx(Jl,{className:"h-3.5 w-3.5"}),"Photo"]}),e.jsxs(Qt,{value:"video",className:"gap-1.5 text-xs",children:[e.jsx(Xr,{className:"h-3.5 w-3.5"}),"Video"]})]}),e.jsxs(Jt,{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($,{variant:"destructive",size:"icon",className:"absolute top-2 right-2 h-7 w-7",onClick:()=>n(null),children:e.jsx(pr,{className:"h-3.5 w-3.5"})})]}):e.jsx("button",{onClick:()=>{var b;return(b=o.current)==null?void 0:b.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(Ht,{className:"h-6 w-6 animate-spin"}):e.jsxs(e.Fragment,{children:[e.jsx(y0,{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:b=>{var N;const v=(N=b.target.files)==null?void 0:N[0];v&&g(v),b.target.value=""}})]}),e.jsxs(Jt,{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($,{variant:"destructive",size:"icon",className:"absolute top-2 right-2 h-7 w-7",onClick:()=>r(null),children:e.jsx(pr,{className:"h-3.5 w-3.5"})})]}):e.jsx("button",{onClick:()=>{var b;return(b=c.current)==null?void 0:b.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(Ht,{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(si,{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(cXe,{contactId:a,onVideoReady:b=>r(b)})}),e.jsx("input",{ref:c,type:"file",accept:"video/*",className:"hidden",onChange:b=>{var N;const v=(N=b.target.files)==null?void 0:N[0];v&&y(v),b.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 EFn=[{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 TFn({onSelect:s}){return e.jsx("div",{className:"grid grid-cols-2 gap-2.5",children:EFn.map((t,n)=>e.jsxs(jr.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 EV={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 l1t({initialOpen:s,initialCardType:t,initialContactId:n,initialRecipientName:r,initialAddress:a,initialDate:i,onOpenChange:l}){const{user:o}=_s(),c=ts(),[d,u]=j.useState(!1),[h,m]=j.useState("type"),[p,x]=j.useState(""),[g,y]=j.useState(null),[b,v]=j.useState(!1),[N,C]=j.useState("home_anniversary"),[A,T]=j.useState(""),[P,M]=j.useState(""),[I,D]=j.useState(""),[B,q]=j.useState(""),[W,V]=j.useState("elegant"),[K,Q]=j.useState(null),[J,ce]=j.useState(null),ue=j.useState(!1);!ue[0]&&s&&t&&(ue[1](!0),u(!0),C(t),n&&y(n),r&&T(r),a&&M(a),i&&D(i),m(r?"details":"contact"));const{data:ne}=ht({queryKey:["contacts-for-card",o==null?void 0:o.id,p],queryFn:async()=>{let ze=U.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&&(ze=ze.or(`first_name.ilike.%${p}%,last_name.ilike.%${p}%`));const{data:ke,error:Xe}=await ze;if(Xe)throw Xe;return ke},enabled:!!(o!=null&&o.id)&&d}),{data:ee}=ht({queryKey:["agent-profile-card",o==null?void 0:o.id],queryFn:async()=>{const{data:ze,error:ke}=await U.from("profiles").select("name, email, phone, avatar_url, brokerage:brokerages(name)").eq("id",o.id).single();if(ke)throw ke;return ze},enabled:!!(o!=null&&o.id)}),le=ze=>{y(ze.id),T(`${ze.first_name}${ze.last_name?" "+ze.last_name:""}`),M([ze.address,ze.city,ze.state].filter(Boolean).join(", "));const ke=N==="wedding_anniversary"?ze.wedding_anniversary:N==="home_anniversary"?ze.home_anniversary:"";D(ke||""),m("details")},he=ze=>{C(ze),m("contact")},ve=async()=>{var ze;if(!(!o||!ee)){v(!0);try{const ke={owner_user_id:o.id,contact_id:g,card_type:N,template:W,recipient_name:A,property_address:P||null,home_anniversary_date:I||null,custom_message:B||null,property_photo_url:K||null,video_url:J||null,agent_name:ee.name||"Agent",agent_photo_url:ee.avatar_url,agent_phone:ee.phone,agent_email:ee.email,agent_brokerage:((ze=ee.brokerage)==null?void 0:ze.name)||null},{error:Xe}=await U.from("sendable_cards").insert(ke);if(Xe)throw Xe;ae.success("Card created! Copy the link to share it."),c.invalidateQueries({queryKey:["sendable-cards"]}),ge()}catch(ke){ae.error(ke.message||"Failed to create card")}finally{v(!1)}}},ge=()=>{u(!1),m("type"),C("home_anniversary"),x(""),y(null),T(""),M(""),D(""),q(""),V("elegant"),Q(null),ce(null)},fe={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"},je=EV[N],Ee=N==="home_anniversary"||N==="wedding_anniversary",Me=N==="wedding_anniversary"?"Wedding Anniversary Date":"Home Anniversary Date",De=["home_anniversary","just_listed","just_sold"].includes(N);return e.jsxs(Os,{open:d,onOpenChange:ze=>{ze?u(!0):(ge(),l==null||l(!1))},children:[e.jsx(Ko,{asChild:!0,children:e.jsxs($,{className:"gap-2",children:[e.jsx(sn,{className:"h-4 w-4"}),"Create Card"]})}),e.jsxs(Rs,{className:"sm:max-w-lg max-h-[90vh] overflow-y-auto",children:[e.jsx(Us,{children:e.jsx(zs,{children:h==="type"?"What type of card?":h==="contact"?`${fe[N]} — Choose a Contact`:`${fe[N]} — Customize`})}),h==="type"&&e.jsx(TFn,{onSelect:he}),h==="contact"&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs($,{variant:"ghost",size:"sm",className:"gap-1.5 -ml-2 text-muted-foreground",onClick:()=>m("type"),children:[e.jsx(ka,{className:"h-3.5 w-3.5"})," Back to card types"]}),e.jsxs("div",{className:"relative",children:[e.jsx(Vr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(be,{placeholder:"Search contacts...",value:p,onChange:ze=>x(ze.target.value),className:"pl-9"})]}),e.jsxs("div",{className:"space-y-1 max-h-64 overflow-y-auto",children:[ne==null?void 0:ne.map(ze=>e.jsxs("button",{onClick:()=>le(ze),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(Lo,{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:[ze.first_name," ",ze.last_name]}),ze.address&&e.jsxs("p",{className:"text-xs text-muted-foreground truncate flex items-center gap-1",children:[e.jsx(sa,{className:"h-3 w-3"}),ze.address]})]}),(N==="home_anniversary"&&ze.home_anniversary||N==="wedding_anniversary"&&ze.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"})]},ze.id)),(ne==null?void 0:ne.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($,{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($,{variant:"ghost",size:"sm",className:"gap-1.5 -ml-2 text-muted-foreground",onClick:()=>m("contact"),children:[e.jsx(ka,{className:"h-3.5 w-3.5"})," Back"]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Recipient Name"}),e.jsx(be,{value:A,onChange:ze=>T(ze.target.value),placeholder:"John & Jane Smith"})]}),De&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Property Address"}),e.jsx(be,{value:P,onChange:ze=>M(ze.target.value),placeholder:"123 Main St, Austin, TX"})]}),Ee&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:Me}),e.jsx(be,{type:"date",value:I,onChange:ze=>D(ze.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Personal Message (optional)"}),e.jsx(Is,{value:B,onChange:ze=>q(ze.target.value),placeholder:je.defaultMessage,rows:3})]}),e.jsx(lHt,{photoUrl:K,videoUrl:J,onPhotoChange:Q,onVideoChange:ce,contactId:g}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{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:ze,label:ke,gradient:Xe})=>e.jsxs("button",{onClick:()=>V(ze),className:`p-2 rounded-lg border-2 transition-all text-center ${W===ze?"border-primary bg-primary/5":"border-border hover:border-primary/30"}`,children:[e.jsx("div",{className:`h-10 rounded-md mb-1.5 ${Xe}`}),e.jsx("span",{className:"text-[10px] font-medium",children:ke})]},ze))})]}),e.jsxs("div",{className:"flex gap-2 pt-2",children:[e.jsx($,{variant:"outline",onClick:()=>m("contact"),className:"flex-1",children:"Back"}),e.jsx($,{onClick:ve,disabled:!A||b,className:"flex-1 gap-2",children:b?"Creating...":"Create Card"})]})]})]})]})}const MFn={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 LFn({card:s}){const{user:t}=_s(),{isGmailConnected:n,hasVerifiedSes:r,canSendEmail:a,sendMethod:i}=ux(),l=ts(),[o,c]=j.useState(!1);j.useState(!1);const[d,u]=j.useState("");j.useEffect(()=>{o&&s.contact_id&&!d&&U.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}!`),[x,g]=j.useState(""),y=`https://cardstudio.relevelup.com/c/${s.share_token}`,b=yt({mutationFn:async()=>{if(!d)throw new Error("Recipient email is required");const N=`
${x?`

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


`:""}

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

${s.property_address?`

${s.property_address}

`:""}
`,C=async()=>{const{data:M,error:I}=await U.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 C();const{data:A,error:T}=await U.functions.invoke("gmail-send",{body:{to:d,subject:m,body:N,contactId:s.contact_id||void 0}});let P=A&&A.error?A:null;if(T){P={error:"send_failed",message:T.message};const M=T.context;if(M&&typeof M.json=="function")try{P=await M.clone().json()}catch{}}if(P){if(P.error==="insufficient_scope"||P.error==="no_integration")return await C(),ae.warning("Sent using system email — reconnect Gmail in Integrations to send from your own inbox.",{duration:8e3}),"system";throw new Error(P.message||P.error||"Failed to send")}if(!(A!=null&&A.success))throw new Error("Failed to send");return"gmail"},onSuccess:async N=>{await U.from("sendable_cards").update({sent_at:new Date().toISOString(),sent_via:N==="gmail"?"gmail":"system"}).eq("id",s.id),l.invalidateQueries({queryKey:["sendable-cards"]}),ae.success(`Card sent to ${d}!`),c(!1)},onError:N=>{ae.error(N.message||"Failed to send email")}}),v=i==="mass_email"?"Mass Email":i==="gmail"?"Gmail":"Email";return e.jsxs(Os,{open:o,onOpenChange:c,children:[e.jsx(Ko,{asChild:!0,children:e.jsx($,{variant:"outline",size:"sm",className:"gap-1 text-xs",children:e.jsx(Br,{className:"h-3 w-3"})})}),e.jsxs(Rs,{className:"sm:max-w-md",children:[e.jsx(Us,{children:e.jsxs(zs,{children:["Send Card via ",v]})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"gmail-to",children:"To"}),e.jsx(k7t,{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(se,{children:"Subject"}),e.jsx(be,{value:m,onChange:N=>p(N.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Personal Note (optional)"}),e.jsx(Is,{value:x,onChange:N=>g(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($,{onClick:()=>b.mutate(),disabled:!d||b.isPending,className:"w-full gap-2",children:b.isPending?e.jsxs(e.Fragment,{children:[e.jsx(Ht,{className:"h-4 w-4 animate-spin"})," Sending..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Br,{className:"h-4 w-4"})," Send Card"]})})]})]})]})}function PFn({card:s}){const t=ts(),[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||""),[x,g]=j.useState(s.template),[y,b]=j.useState(s.property_photo_url),[v,N]=j.useState(s.video_url||null),C=T=>{T&&(o(s.recipient_name),d(s.property_address||""),h(s.home_anniversary_date||""),p(s.custom_message||""),g(s.template),b(s.property_photo_url),N(s.video_url||null)),r(T)},A=async()=>{if(!l.trim()){ae.error("Recipient name is required");return}i(!0);try{const{error:T}=await U.from("sendable_cards").update({recipient_name:l.trim(),property_address:c.trim()||null,home_anniversary_date:u||null,custom_message:m.trim()||null,template:x,property_photo_url:y||null,video_url:v||null}).eq("id",s.id);if(T)throw T;t.invalidateQueries({queryKey:["sendable-cards"]}),ae.success("Card updated"),r(!1)}catch(T){ae.error(T.message||"Failed to update card")}finally{i(!1)}};return e.jsxs(Os,{open:n,onOpenChange:C,children:[e.jsx(Ko,{asChild:!0,children:e.jsx($,{variant:"outline",size:"sm",className:"gap-1 text-xs",children:e.jsx(Ya,{className:"h-3 w-3"})})}),e.jsxs(Rs,{className:"sm:max-w-lg max-h-[90vh] overflow-y-auto",children:[e.jsx(Us,{children:e.jsx(zs,{children:"Edit Card"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Recipient Name"}),e.jsx(be,{value:l,onChange:T=>o(T.target.value),placeholder:"John & Jane Smith"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Property Address"}),e.jsx(be,{value:c,onChange:T=>d(T.target.value),placeholder:"123 Main St, Austin, TX"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Home Anniversary Date"}),e.jsx(be,{type:"date",value:u,onChange:T=>h(T.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Personal Message (optional)"}),e.jsx(Is,{value:m,onChange:T=>p(T.target.value),placeholder:"Wishing you many more happy years in your beautiful home!",rows:3})]}),e.jsx(lHt,{photoUrl:y,videoUrl:v,onPhotoChange:b,onVideoChange:N,contactId:s.contact_id}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Template Style"}),e.jsx("div",{className:"grid grid-cols-3 gap-2",children:["elegant","bold","warm"].map(T=>e.jsxs("button",{onClick:()=>g(T),className:`p-3 rounded-lg border-2 transition-all text-center ${x===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($,{onClick:A,disabled:!l.trim()||a,className:"w-full gap-2",children:a?e.jsxs(e.Fragment,{children:[e.jsx(Ht,{className:"h-4 w-4 animate-spin"})," Saving..."]}):"Save Changes"})]})]})]})}function IFn(){const{user:s}=_s(),t=ts(),[n,r]=j.useState(""),[a,i]=oc(),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}=ht({queryKey:["sendable-cards",s==null?void 0:s.id],queryFn:async()=>{const{data:N,error:C}=await U.from("sendable_cards").select("*").eq("owner_user_id",s.id).order("created_at",{ascending:!1});if(C)throw C;return N},enabled:!!(s!=null&&s.id)}),x=yt({mutationFn:async N=>{const{error:C}=await U.from("sendable_cards").delete().eq("id",N);if(C)throw C},onSuccess:()=>{t.invalidateQueries({queryKey:["sendable-cards"]}),ae.success("Card deleted")}}),g=N=>{const C=`https://cardstudio.relevelup.com/c/${N}`;navigator.clipboard.writeText(C),ae.success("Share link copied!")},y=m==null?void 0:m.filter(N=>{var C;return!n||N.recipient_name.toLowerCase().includes(n.toLowerCase())||((C=N.property_address)==null?void 0:C.toLowerCase().includes(n.toLowerCase()))}),b={elegant:"Elegant",bold:"Bold",warm:"Warm"},v={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(Ks,{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(l1t,{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(Vr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(be,{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(_e,{className:"animate-pulse",children:e.jsxs(Oe,{className:"p-4",children:[e.jsx("div",{className:"h-40 bg-muted rounded-lg mb-3"}),e.jsx("div",{className:"h-4 bg-muted rounded w-2/3 mb-2"}),e.jsx("div",{className:"h-3 bg-muted rounded w-1/2"})]})},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(_e,{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:v[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($e,{variant:N.template==="bold"?"outline":"secondary",className:`text-[10px] ${N.template==="bold"?"border-white/30 text-white/80":""}`,children:b[N.template]||N.template})})]}),e.jsxs(Oe,{className:"p-3",children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground",children:[e.jsx(ga,{className:"h-3 w-3"}),N.view_count," views"]}),e.jsx("span",{className:"text-xs text-muted-foreground",children:fc(new Date(N.created_at),{addSuffix:!0})})]}),N.sent_at&&e.jsxs("p",{className:"text-[10px] text-emerald-600 mb-2",children:["Sent ",Hs(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($,{variant:"outline",size:"sm",className:"flex-1 gap-1 text-xs",onClick:()=>g(N.share_token),children:[e.jsx(Ca,{className:"h-3 w-3"}),"Copy Link"]}),e.jsx(PFn,{card:N}),e.jsx(LFn,{card:N}),e.jsx($,{variant:"outline",size:"sm",className:"gap-1 text-xs",onClick:()=>window.open(`https://cardstudio.relevelup.com/c/${N.share_token}`,"_blank"),children:e.jsx(Tr,{className:"h-3 w-3"})}),e.jsx($,{variant:"ghost",size:"sm",className:"text-destructive hover:text-destructive gap-1 text-xs",onClick:()=>x.mutate(N.id),children:e.jsx(Pn,{className:"h-3 w-3"})})]})]})]},N.id))}):e.jsx(_e,{className:"border-dashed",children:e.jsxs(Oe,{className:"flex flex-col items-center justify-center py-16",children:[e.jsx("div",{className:"h-16 w-16 rounded-full bg-primary/10 flex items-center justify-center mb-4",children:e.jsx(nn,{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(l1t,{initialOpen:h,initialCardType:l,initialContactId:o||void 0,initialRecipientName:c||void 0,initialAddress:d||void 0,initialDate:u||void 0,onOpenChange:()=>i({})})]})})]})})}const bae=[{id:"mls",label:"MLS Description",tag:"Standard",icon:sa,accent:"from-sky-500 to-cyan-500",desc:"Polished MLS-ready listing",category:"listing"},{id:"luxury",label:"Luxury MLS",tag:"Premium",icon:Ng,accent:"from-amber-500 to-orange-500",desc:"Evocative, high-end voice",category:"listing"},{id:"short",label:"Short MLS",tag:"Concise",icon:ox,accent:"from-violet-500 to-fuchsia-500",desc:"Punchy 60–90 words",category:"listing"},{id:"openHouse",label:"Open House",tag:"Promo",icon:zj,accent:"from-emerald-500 to-teal-500",desc:"Friendly invite copy",category:"listing",extras:["openHouse"]},{id:"newConstruction",label:"New Construction",tag:"Build",icon:CK,accent:"from-rose-500 to-pink-500",desc:"Builder-focused angle",category:"listing",extras:["newConstruction"]},{id:"investment",label:"Investment",tag:"ROI",icon:Il,accent:"from-indigo-500 to-blue-500",desc:"Cap rate & income hooks",category:"listing",extras:["investment"]},{id:"facebookPost",label:"Facebook Post",tag:"Social",icon:jf,accent:"from-blue-600 to-blue-400",desc:"Engaging FB caption",category:"social"},{id:"instagramPost",label:"Instagram Post",tag:"Social",icon:Qh,accent:"from-pink-500 via-fuchsia-500 to-orange-400",desc:"IG caption + hashtags",category:"social"},{id:"linkedinPost",label:"LinkedIn Post",tag:"Social",icon:kg,accent:"from-sky-700 to-sky-500",desc:"Professional tone",category:"social"},{id:"justListed",label:"Just Listed",tag:"Announce",icon:Eh,accent:"from-emerald-500 to-green-500",desc:"Hit the market announcement",category:"social"},{id:"comingSoon",label:"Coming Soon",tag:"Tease",icon:Hr,accent:"from-amber-500 to-yellow-500",desc:"Build pre-market buzz",category:"social",extras:["comingSoon"]},{id:"priceImprovement",label:"Price Improvement",tag:"Update",icon:FN,accent:"from-orange-500 to-red-500",desc:"New price announcement",category:"social",extras:["priceImprovement"]},{id:"openHousePost",label:"Open House Post",tag:"Event",icon:Nl,accent:"from-teal-500 to-emerald-500",desc:"Social invite to OH",category:"social",extras:["openHouse"]},{id:"underContract",label:"Under Contract",tag:"Status",icon:jK,accent:"from-indigo-500 to-purple-500",desc:"Pending celebration",category:"social",extras:["underContract"]},{id:"justSold",label:"Just Sold",tag:"Celebrate",icon:Nf,accent:"from-fuchsia-500 to-pink-500",desc:"Sold success post",category:"social",extras:["sold"]},{id:"propertyTourScript",label:"Property Tour",tag:"Script",icon:Xr,accent:"from-red-500 to-rose-500",desc:"Full walkthrough script",category:"video",extras:["signoff"]},{id:"reelScript",label:"Reel Script",tag:"Short",icon:lh,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:Vj,accent:"from-violet-500 to-purple-500",desc:"5 scroll-stopping hooks",category:"video",extras:["vibe"]},{id:"luxuryWalkthrough",label:"Luxury Walkthrough",tag:"Premium",icon:Ng,accent:"from-amber-500 to-yellow-500",desc:"Cinematic, refined tone",category:"video",extras:["signoff"]},{id:"droneScript",label:"Drone Script",tag:"Aerial",icon:BK,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:ai,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:nn,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:Cz,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:qn,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:FN,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:$3,accent:"from-fuchsia-500 to-pink-500",desc:"Sold announcement email",category:"email",extras:["sold","signoff"]},{id:"neighborhoodEmail",label:"Neighborhood Email",tag:"Nurture",icon:ai,accent:"from-sky-500 to-indigo-500",desc:"Area update / market touch",category:"email",extras:["neighborhood","signoff"]}];function DFn(){var hi,el,Oo,Ei,Wa,wo,Io,is,zr,Sa,Kn;const{user:s}=_s(),[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,x]=j.useState(""),[g,y]=j.useState(""),[b,v]=j.useState(""),[N,C]=j.useState(""),[A,T]=j.useState(""),[P,M]=j.useState(""),[I,D]=j.useState(null),[B,q]=j.useState(""),[W,V]=j.useState(""),[K,Q]=j.useState(""),[J,ce]=j.useState(""),[ue,ne]=j.useState(""),[ee,le]=j.useState(""),[he,ve]=j.useState(""),[ge,fe]=j.useState(""),[je,Ee]=j.useState(""),[Me,De]=j.useState(""),[ze,ke]=j.useState(""),[Xe,Se]=j.useState(""),[Re,Ae]=j.useState(""),[Be,qe]=j.useState(""),[Ke,Ze]=j.useState(""),[Ue,et]=j.useState(""),[Qe,Ge]=j.useState(""),[nt,ft]=j.useState(""),[lt,Mt]=j.useState(""),[Ft,Ts]=j.useState(""),[js,zt]=j.useState(""),[Nt,Ds]=j.useState(""),[_t,Xs]=j.useState(""),[rn,Ps]=j.useState(""),[_n,Zs]=j.useState(""),[gr,Un]=j.useState("listing"),[In,Ar]=j.useState("mls"),[or,qs]=j.useState({}),[yr,fn]=j.useState({}),[Zn,Xt]=j.useState(!1),[rr,Qn]=j.useState(!1),Sn=wn=>{Un(wn);const Ur=bae.find(ca=>ca.category===wn);Ur&&Ar(Ur.id)},{data:$n}=ht({queryKey:["listing-studio-listings",s==null?void 0:s.id],enabled:!!(s!=null&&s.id)&&Zn,queryFn:async()=>{const{data:wn,error:Ur}=await U.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(Ur)throw Ur;return wn||[]}}),tn=()=>{const wn=o.trim();wn&&(l(Ur=>[...Ur,wn]),c(""))},ln=wn=>l(Ur=>Ur.filter((ca,yo)=>yo!==wn)),Cr=wn=>{var Ur,ca,yo,vo;D(wn.id),n(wn.property_address||""),T(wn.city||""),M(wn.state||""),v(((Ur=wn.price)==null?void 0:Ur.toString())||""),m(((ca=wn.bedrooms)==null?void 0:ca.toString())||""),x(((yo=wn.bathrooms)==null?void 0:yo.toString())||""),y(((vo=wn.square_footage)==null?void 0:vo.toString())||""),C(wn.property_type||""),a(wn.description||""),Xt(!1),ae.success("Listing imported")},ms=async wn=>{if(!(!wn.target.files||!(s!=null&&s.id))){Qn(!0);try{const Ur=[];for(const ca of Array.from(wn.target.files).slice(0,10)){const yo=`${s.id}/${Date.now()}-${ca.name.replace(/[^\w.-]/g,"_")}`,{error:vo}=await U.storage.from("listing-photos").upload(yo,ca,{upsert:!1});if(vo){console.error(vo);continue}const{data:Vo}=U.storage.from("listing-photos").getPublicUrl(yo);Ur.push(Vo.publicUrl)}u(ca=>[...ca,...Ur]),Ur.length&&ae.success(`${Ur.length} photo(s) uploaded`)}catch(Ur){ae.error(Ur.message||"Photo upload failed")}finally{Qn(!1)}}},ot=bae.find(wn=>wn.id===In),pt=async wn=>{var ca,yo,vo;const Ur=bae.find(Vo=>Vo.id===wn);if(!t.trim()&&!r.trim()&&i.length===0){ae.error("Add a property address, MLS remarks, or features first");return}if((ca=Ur.extras)!=null&&ca.includes("openHouse")&&(!B||!W||!K)){ae.error("Add the open house date, start and end time");return}if((yo=Ur.extras)!=null&&yo.includes("priceImprovement")&&(!J||!ue)){ae.error("Add previous and new price");return}if((vo=Ur.extras)!=null&&vo.includes("sold")&&!ee){ae.error("Add the sold price");return}Ar(wn),fn(Vo=>({...Vo,[wn]:!0}));try{const{data:Vo,error:Xc}=await U.functions.invoke("listing-studio-generate",{body:{copyType:wn,propertyAddress:t,mlsRemarks:r,features:i,photoUrls:d,listingId:I,bedrooms:h?Number(h):null,bathrooms:p?Number(p):null,squareFootage:g?Number(g):null,price:b?Number(b):null,propertyType:N||null,city:A||null,state:P||null,openHouseDate:B||null,openHouseStart:W||null,openHouseEnd:K||null,previousPrice:J?Number(J):null,newPrice:ue?Number(ue):null,soldPrice:ee?Number(ee):null,soldDate:he||null,comingSoonDate:ge||null,builderName:je||null,yearBuilt:Me?Number(Me):null,warrantyInfo:ze||null,monthlyRent:Xe?Number(Xe):null,capRate:Re||null,occupancy:Be||null,daysOnMarket:Ke?Number(Ke):null,offerCount:Ue?Number(Ue):null,originalListPrice:Qe?Number(Qe):null,soldDaysOnMarket:nt?Number(nt):null,commissionOffered:lt||null,refreshments:Ft||null,vibe:js||null,neighborhoodHighlights:Nt||null,agentName:_t||null,agentBrokerage:rn||null,agentContact:_n||null}});if(Xc)throw Xc;if(Vo!=null&&Vo.error)throw new Error(Vo.error);qs(uo=>({...uo,[wn]:Vo.content}))}catch(Vo){ae.error(Vo.message||"Generation failed")}finally{fn(Vo=>({...Vo,[wn]:!1}))}},vt=wn=>{navigator.clipboard.writeText(wn),ae.success("Copied to clipboard")},At=ot.icon,Zt=or[In]?or[In].trim().split(/\s+/).length:0,as=wn=>e.jsx("div",{className:"grid grid-cols-2 sm:grid-cols-3 gap-3",children:bae.filter(Ur=>Ur.category===wn).map(Ur=>{const ca=Ur.icon,yo=In===Ur.id,vo=!!or[Ur.id];return e.jsxs("button",{onClick:()=>Ar(Ur.id),className:Tt("relative text-left p-4 rounded-2xl border transition-all overflow-hidden group",yo?"border-primary shadow-lg shadow-primary/10 bg-card":"border-border/60 hover:border-border bg-card/50 hover:bg-card"),children:[yo&&e.jsx("div",{className:Tt("absolute inset-0 opacity-[0.07] bg-gradient-to-br",Ur.accent)}),e.jsxs("div",{className:"relative space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("div",{className:Tt("h-9 w-9 rounded-xl grid place-items-center text-white bg-gradient-to-br shadow-sm",Ur.accent),children:e.jsx(ca,{className:"h-4 w-4"})}),vo&&e.jsx("div",{className:"h-5 w-5 rounded-full bg-emerald-500/15 text-emerald-600 grid place-items-center",children:e.jsx(oa,{className:"h-3 w-3"})})]}),e.jsxs("div",{children:[e.jsx("div",{className:"font-semibold text-sm",children:Ur.label}),e.jsx("div",{className:"text-xs text-muted-foreground line-clamp-1",children:Ur.desc})]})]})]},Ur.id)})}),Ls=(hi=ot.extras)==null?void 0:hi.includes("openHouse"),cs=(el=ot.extras)==null?void 0:el.includes("priceImprovement"),qt=(Oo=ot.extras)==null?void 0:Oo.includes("sold"),Gs=(Ei=ot.extras)==null?void 0:Ei.includes("comingSoon"),Vs=(Wa=ot.extras)==null?void 0:Wa.includes("newConstruction"),Hn=(wo=ot.extras)==null?void 0:wo.includes("investment"),Kr=(Io=ot.extras)==null?void 0:Io.includes("underContract"),ma=(is=ot.extras)==null?void 0:is.includes("brokerOpen"),Or=(zr=ot.extras)==null?void 0:zr.includes("vibe"),ta=(Sa=ot.extras)==null?void 0:Sa.includes("neighborhood"),da=(Kn=ot.extras)==null?void 0:Kn.includes("signoff"),va=Ls||cs||qt||Gs||Vs||Hn||Kr||ma||Or||ta||da;return e.jsx(Ks,{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(dn,{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(Os,{open:Zn,onOpenChange:Xt,children:[e.jsx(Ko,{asChild:!0,children:e.jsxs($,{size:"lg",variant:"secondary",className:"shadow-lg shadow-fuchsia-500/10",children:[e.jsx(Wr,{className:"h-4 w-4 mr-2"}),"Import from Listings"]})}),e.jsxs(Rs,{className:"max-w-2xl max-h-[80vh] overflow-y-auto",children:[e.jsx(Us,{children:e.jsx(zs,{children:"Import from Listing Exchange"})}),e.jsxs("div",{className:"space-y-2 mt-2",children:[!($n!=null&&$n.length)&&e.jsx("p",{className:"text-sm text-muted-foreground py-8 text-center",children:"No listings found yet."}),$n==null?void 0:$n.map(wn=>e.jsxs("button",{onClick:()=>Cr(wn),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:wn.property_address||"Untitled listing"}),e.jsxs("div",{className:"text-sm text-muted-foreground mt-0.5",children:[[wn.city,wn.state].filter(Boolean).join(", "),wn.price?` · $${Number(wn.price).toLocaleString()}`:"",wn.bedrooms?` · ${wn.bedrooms}bd`:"",wn.bathrooms?` · ${wn.bathrooms}ba`:""]})]},wn.id))]})]})]})]})]}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-5 gap-6",children:[e.jsx(_e,{className:"lg:col-span-2 border-border/60 shadow-sm",children:e.jsxs(Oe,{className:"p-6 space-y-5",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"h-8 w-8 rounded-lg bg-primary/10 grid place-items-center",children:e.jsx(sa,{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(se,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Address"}),e.jsx(be,{value:t,onChange:wn=>n(wn.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(se,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"City"}),e.jsx(be,{value:A,onChange:wn=>T(wn.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"State"}),e.jsx(be,{value:P,onChange:wn=>M(wn.target.value)})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Price"}),e.jsx(be,{type:"number",value:b,onChange:wn=>v(wn.target.value),placeholder:"$"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Type"}),e.jsx(be,{value:N,onChange:wn=>C(wn.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(se,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Beds"}),e.jsx(be,{type:"number",value:h,onChange:wn=>m(wn.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Baths"}),e.jsx(be,{type:"number",step:"0.5",value:p,onChange:wn=>x(wn.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Sqft"}),e.jsx(be,{type:"number",value:g,onChange:wn=>y(wn.target.value)})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"MLS Remarks / Notes"}),e.jsx(Is,{value:r,onChange:wn=>a(wn.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(se,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Features"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(be,{value:o,onChange:wn=>c(wn.target.value),onKeyDown:wn=>wn.key==="Enter"&&(wn.preventDefault(),tn()),placeholder:"e.g. Quartz countertops"}),e.jsx($,{type:"button",size:"icon",variant:"secondary",onClick:tn,children:e.jsx(sn,{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((wn,Ur)=>e.jsxs($e,{variant:"secondary",className:"pl-3 pr-1 py-1 gap-1",children:[wn,e.jsx("button",{onClick:()=>ln(Ur),className:"ml-0.5 p-0.5 hover:bg-background/60 rounded-full",children:e.jsx(pr,{className:"h-3 w-3"})})]},Ur))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{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(x1,{className:"h-4 w-4"}),rr?"Uploading…":"Click to upload photos",e.jsx("input",{type:"file",accept:"image/*",multiple:!0,onChange:ms,disabled:rr,className:"hidden"})]}),d.length>0&&e.jsx("div",{className:"grid grid-cols-4 gap-2 mt-2",children:d.map((wn,Ur)=>e.jsxs("div",{className:"relative aspect-square rounded-lg overflow-hidden group",children:[e.jsx("img",{src:wn,alt:"",className:"w-full h-full object-cover"}),e.jsx("button",{onClick:()=>u(ca=>ca.filter((yo,vo)=>vo!==Ur)),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(pr,{className:"h-3 w-3"})})]},Ur))})]}),va&&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(dn,{className:"h-4 w-4 text-primary"}),e.jsxs("div",{className:"text-sm font-semibold",children:["Extra info for ",ot.label]})]}),Ls&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Date"}),e.jsx(be,{type:"date",value:B,onChange:wn=>q(wn.target.value)})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Start"}),e.jsx(be,{type:"time",value:W,onChange:wn=>V(wn.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"End"}),e.jsx(be,{type:"time",value:K,onChange:wn=>Q(wn.target.value)})]})]})]}),cs&&e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Previous Price"}),e.jsx(be,{type:"number",value:J,onChange:wn=>ce(wn.target.value),placeholder:"$"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"New Price"}),e.jsx(be,{type:"number",value:ue,onChange:wn=>ne(wn.target.value),placeholder:"$"})]})]}),qt&&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(se,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Sold Price"}),e.jsx(be,{type:"number",value:ee,onChange:wn=>le(wn.target.value),placeholder:"$"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Sold Date"}),e.jsx(be,{type:"date",value:he,onChange:wn=>ve(wn.target.value)})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Original List Price (optional)"}),e.jsx(be,{type:"number",value:Qe,onChange:wn=>Ge(wn.target.value),placeholder:"$"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Days on Market (optional)"}),e.jsx(be,{type:"number",value:nt,onChange:wn=>ft(wn.target.value)})]})]})]}),Gs&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Expected Live Date (optional)"}),e.jsx(be,{type:"date",value:ge,onChange:wn=>fe(wn.target.value)})]}),Vs&&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(se,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Builder Name"}),e.jsx(be,{value:je,onChange:wn=>Ee(wn.target.value),placeholder:"ABC Homes"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Year Built"}),e.jsx(be,{type:"number",value:Me,onChange:wn=>De(wn.target.value),placeholder:"2026"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Warranty / Energy / Smart-home (optional)"}),e.jsx(be,{value:ze,onChange:wn=>ke(wn.target.value),placeholder:"10-yr structural, ENERGY STAR, smart-home pkg"})]})]}),Hn&&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(se,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Monthly Rent (optional)"}),e.jsx(be,{type:"number",value:Xe,onChange:wn=>Se(wn.target.value),placeholder:"$"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Cap Rate (optional)"}),e.jsx(be,{value:Re,onChange:wn=>Ae(wn.target.value),placeholder:"6.5%"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Occupancy"}),e.jsxs("select",{value:Be,onChange:wn=>qe(wn.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"})]})]})]}),Kr&&e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Days on Market (optional)"}),e.jsx(be,{type:"number",value:Ke,onChange:wn=>Ze(wn.target.value),placeholder:"e.g. 3"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"# of Offers (optional)"}),e.jsx(be,{type:"number",value:Ue,onChange:wn=>et(wn.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(se,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Commission / Co-op Offered (optional)"}),e.jsx(be,{value:lt,onChange:wn=>Mt(wn.target.value),placeholder:"2.5% buyer agent commission"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Refreshments / Perks (optional)"}),e.jsx(be,{value:Ft,onChange:wn=>Ts(wn.target.value),placeholder:"Lunch + raffle for $100 gift card"})]})]}),Or&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Vibe / Tone"}),e.jsxs("select",{value:js,onChange:wn=>zt(wn.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"})]})]}),ta&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Nearby Highlights (optional)"}),e.jsx(Is,{value:Nt,onChange:wn=>Ds(wn.target.value),rows:3,placeholder:"Top schools, parks, coffee shops, restaurants, commute, walkability…"})]}),da&&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(se,{className:"text-xs font-medium text-muted-foreground",children:"Agent Name"}),e.jsx(be,{value:_t,onChange:wn=>Xs(wn.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{className:"text-xs font-medium text-muted-foreground",children:"Brokerage"}),e.jsx(be,{value:rn,onChange:wn=>Ps(wn.target.value)})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{className:"text-xs font-medium text-muted-foreground",children:"Phone / Email"}),e.jsx(be,{value:_n,onChange:wn=>Zs(wn.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:Wr},{key:"social",label:"Social Media",icon:Qh},{key:"video",label:"Video Scripts",icon:Xr},{key:"email",label:"Email Marketing",icon:nn}].map(wn=>{const Ur=wn.icon,ca=gr===wn.key;return e.jsxs("button",{onClick:()=>Sn(wn.key),className:Tt("flex-1 flex items-center justify-center gap-2 px-4 py-2.5 rounded-lg text-sm font-medium transition-all",ca?"bg-card shadow-sm text-foreground border border-border/60":"text-muted-foreground hover:text-foreground hover:bg-background/50"),children:[e.jsx(Ur,{className:"h-4 w-4"}),wn.label]},wn.key)})}),as(gr),e.jsxs(_e,{className:"border-border/60 shadow-sm overflow-hidden",children:[e.jsx("div",{className:Tt("h-1 bg-gradient-to-r",ot.accent)}),e.jsxs(Oe,{className:"p-6 space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between gap-4 flex-wrap",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:Tt("h-10 w-10 rounded-xl grid place-items-center text-white bg-gradient-to-br",ot.accent),children:e.jsx(At,{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($e,{variant:"outline",className:"text-[10px] font-normal",children:ot.tag})]}),e.jsx("div",{className:"text-xs text-muted-foreground",children:or[In]?`${Zt} words`:"Ready to generate"})]})]}),e.jsxs("div",{className:"flex gap-2",children:[or[In]&&e.jsxs($,{variant:"outline",size:"sm",onClick:()=>vt(or[In]),children:[e.jsx(Ca,{className:"h-4 w-4 mr-2"})," Copy"]}),e.jsx($,{onClick:()=>pt(In),disabled:yr[In],className:Tt("shadow-lg shadow-primary/10 bg-gradient-to-r text-white border-0 hover:opacity-90",ot.accent),size:"sm",children:yr[In]?e.jsxs(e.Fragment,{children:[e.jsx(Ht,{className:"h-4 w-4 mr-2 animate-spin"})," Generating"]}):or[In]?e.jsxs(e.Fragment,{children:[e.jsx(Wi,{className:"h-4 w-4 mr-2"})," Regenerate"]}):e.jsxs(e.Fragment,{children:[e.jsx(wm,{className:"h-4 w-4 mr-2"})," Generate"]})})]})]}),or[In]?e.jsx(Is,{value:or[In],onChange:wn=>qs(Ur=>({...Ur,[In]:wn.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:Tt("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(wm,{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 $G({delay:s,x:t,y:n,size:r}){return e.jsx(jr.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 RFn(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=EV[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(jr.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(jr.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($G,{delay:0,x:"15%",y:"20%",size:8}),e.jsx($G,{delay:1,x:"80%",y:"30%",size:6}),e.jsx($G,{delay:2,x:"60%",y:"70%",size:10}),e.jsx($G,{delay:.5,x:"25%",y:"80%",size:7}),e.jsx($G,{delay:1.5,x:"70%",y:"15%",size:5})]}),e.jsxs(jr.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(jr.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(jr.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(jr.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(jr.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(jr.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(jr.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(jr.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(jr.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(jr.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(jr.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(jr.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(jr.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(jr.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(jr.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(jr.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(ya,{className:"h-3.5 w-3.5"})," Call"]}),d&&e.jsxs(jr.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(nn,{className:"h-3.5 w-3.5"})," Email"]})]})]})]})]}),e.jsx(jr.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 CDe({delay:s,x:t,y:n,color:r,size:a}){return e.jsx(jr.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 UG({delay:s,x:t,y:n}){return e.jsx(jr.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 c1t={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 OFn(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=EV[t],x=c1t[t]||c1t.home_anniversary;return e.jsxs("div",{className:`min-h-screen bg-gradient-to-br ${x.bg} flex items-center justify-center p-4 overflow-hidden relative`,children:[e.jsx(CDe,{delay:0,x:"10%",y:"10%",color:x.orbs[0],size:200}),e.jsx(CDe,{delay:1,x:"70%",y:"60%",color:x.orbs[1],size:180}),e.jsx(CDe,{delay:2,x:"50%",y:"20%",color:x.orbs[2],size:150}),e.jsx(UG,{delay:0,x:"20%",y:"25%"}),e.jsx(UG,{delay:.8,x:"75%",y:"15%"}),e.jsx(UG,{delay:1.6,x:"85%",y:"65%"}),e.jsx(UG,{delay:2.4,x:"10%",y:"75%"}),e.jsx(UG,{delay:.4,x:"45%",y:"85%"}),e.jsxs(jr.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(jr.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(jr.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(jr.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(jr.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(jr.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(jr.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(jr.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(jr.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(jr.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(jr.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(sa,{className:"h-3.5 w-3.5"}),r]})]}),h&&e.jsx(jr.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(jr.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(jr.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(jr.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(jr.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(jr.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(ya,{className:"h-3.5 w-3.5"})," Call Me"]}),d&&e.jsxs(jr.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(nn,{className:"h-3.5 w-3.5"})," Email"]})]})]})]})]}),e.jsx(jr.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 FFn({emoji:s,delay:t,x:n,duration:r}){return e.jsx(jr.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 d1t={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 zFn(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=EV[t],x=d1t[t]||d1t.home_anniversary;return e.jsxs("div",{className:`min-h-screen bg-gradient-to-b ${x.bg} flex items-center justify-center p-4 overflow-hidden relative`,children:[p.emojis.map((g,y)=>e.jsx(FFn,{emoji:g,delay:y*1.2,x:`${15+y*14}%`,duration:5+y%3},y)),e.jsx(jr.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(jr.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(jr.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(jr.div,{className:`h-28 bg-gradient-to-r ${x.header} relative overflow-hidden`,children:[e.jsx(jr.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(jr.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(jr.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(jr.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(jr.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(jr.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(jr.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 ${x.accent}`,children:[e.jsx(jr.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(jr.h1,{className:`text-3xl font-bold ${x.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(jr.div,{initial:{opacity:0},animate:{opacity:1},transition:{delay:1.1},children:[e.jsx("p",{className:`text-lg font-semibold ${x.text} mb-1`,children:n}),r&&e.jsxs("p",{className:`text-sm ${x.text} opacity-70 flex items-center justify-center gap-1 mb-5`,children:[e.jsx(ai,{className:"h-3 w-3"}),r]})]}),h&&e.jsx(jr.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(jr.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(jr.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 ${x.text} leading-relaxed italic`,children:['"',i||p.defaultMessage,'"']})}),e.jsxs(jr.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(jr.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 ${x.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 ${x.accent}`,children:l}),u&&e.jsx("p",{className:`text-xs ${x.text} opacity-60`,children:u})]})]}),e.jsxs("div",{className:"flex items-center justify-center gap-2 mt-4",children:[c&&e.jsxs(jr.a,{href:`tel:${c}`,className:`flex items-center gap-1.5 px-5 py-2.5 rounded-full bg-gradient-to-r ${x.header} text-xs font-semibold text-white shadow-md`,whileHover:{scale:1.05},whileTap:{scale:.95},children:[e.jsx(ya,{className:"h-3.5 w-3.5"})," Call"]}),d&&e.jsxs(jr.a,{href:`mailto:${d}`,className:`flex items-center gap-1.5 px-5 py-2.5 rounded-full bg-gradient-to-r ${x.header} text-xs font-semibold text-white shadow-md`,whileHover:{scale:1.05},whileTap:{scale:.95},children:[e.jsx(nn,{className:"h-3.5 w-3.5"})," Email"]})]})]})]})]}),e.jsx(jr.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 _ae({delay:s,x:t,y:n,size:r,color:a}){return e.jsx(jr.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 ADe({delay:s,x:t,y:n,size:r}){return e.jsx(jr.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 u1t={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 BFn(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=EV[t],x=u1t[t]||u1t.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(_ae,{delay:0,x:"5%",y:"10%",size:300,color:x.mesh[0]}),e.jsx(_ae,{delay:2,x:"60%",y:"50%",size:250,color:x.mesh[1]}),e.jsx(_ae,{delay:4,x:"30%",y:"70%",size:200,color:x.mesh[2]}),e.jsx(_ae,{delay:1,x:"80%",y:"15%",size:180,color:x.mesh[0]}),e.jsx(ADe,{delay:0,x:"15%",y:"20%",size:100}),e.jsx(ADe,{delay:3,x:"70%",y:"60%",size:140}),e.jsx(ADe,{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(jr.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(jr.div,{className:`relative rounded-[28px] overflow-hidden backdrop-blur-2xl bg-white/[0.06] border border-white/[0.12] shadow-2xl ${x.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(jr.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(jr.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(jr.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(jr.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(jr.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(jr.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] ${x.accent}`,children:a===1?"Year":"Years"})]}),e.jsx(jr.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(jr.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(jr.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(ai,{className:"h-3 w-3"})," ",r]})]}),e.jsx(jr.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(jr.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(jr.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(jr.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(jr.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(jr.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(jr.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(ya,{className:"h-3.5 w-3.5"})," Call"]}),d&&e.jsxs(jr.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(nn,{className:"h-3.5 w-3.5"})," Email"]})]})]})]})]}),e.jsx(jr.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 EDe({delay:s,x:t,angle:n,color:r}){return e.jsx(jr.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 wae({delay:s,x:t}){return e.jsx(jr.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 h1t={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 $Fn(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=EV[t],x=h1t[t]||h1t.home_anniversary;return e.jsxs("div",{className:`min-h-screen bg-gradient-to-b ${x.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(EDe,{delay:0,x:"20%",angle:15,color:x.stripe}),e.jsx(EDe,{delay:2,x:"75%",angle:-12,color:x.stripe}),e.jsx(EDe,{delay:4,x:"50%",angle:5,color:x.stripe}),e.jsx(wae,{delay:0,x:"30%"}),e.jsx(wae,{delay:1.5,x:"60%"}),e.jsx(wae,{delay:3,x:"45%"}),e.jsx(wae,{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(jr.div,{className:"w-full max-w-md relative z-10",initial:{opacity:0},animate:{opacity:1},transition:{duration:1.2},children:[e.jsx(jr.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(jr.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(jr.div,{className:`h-20 w-20 mx-auto rounded-2xl bg-gradient-to-br ${x.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(jr.div,{className:"mb-6",initial:{opacity:0},animate:{opacity:1},transition:{delay:.7},children:[e.jsx(jr.span,{className:`text-6xl font-black bg-gradient-to-r ${x.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(jr.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(jr.h2,{className:`text-5xl font-black bg-gradient-to-r ${x.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(jr.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(ai,{className:"h-3 w-3"})," ",r]})]}),e.jsxs(jr.div,{className:"flex items-center justify-center gap-3 my-8",initial:{opacity:0},animate:{opacity:1},transition:{delay:1.2},children:[e.jsx(jr.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(jr.span,{className:"text-white/10 text-xs",animate:{rotate:[0,360]},transition:{duration:20,repeat:1/0,ease:"linear"},children:"✦"}),e.jsx(jr.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(jr.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(jr.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(jr.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(jr.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(jr.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 ${x.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(jr.a,{href:`tel:${c}`,className:`flex items-center gap-1.5 px-5 py-2.5 rounded-full bg-gradient-to-r ${x.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(ya,{className:"h-3.5 w-3.5"})," Call"]}),d&&e.jsxs(jr.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(nn,{className:"h-3.5 w-3.5"})," Email"]})]})]})]})}),e.jsx(jr.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 cHt(){const{shareToken:s}=Vi(),{data:t,isLoading:n,error:r}=ht({queryKey:["public-sendable-card",s],queryFn:async()=>{const{data:l,error:o}=await U.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&&U.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()-mu(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(OFn,{...i});case"warm":return e.jsx(zFn,{...i});case"glass":return e.jsx(BFn,{...i});case"cinematic":return e.jsx($Fn,{...i});case"elegant":default:return e.jsx(RFn,{...i})}}function UFn(){const s=Za();return ht({queryKey:["drip-settings",s],queryFn:async()=>{if(!s)return null;const{data:t,error:n}=await U.from("drip_settings").select("*").eq("user_id",s).maybeSingle();if(n)throw n;return t},enabled:!!s})}function qFn(){const s=Za(),t=ts();return yt({mutationFn:async n=>{if(!s)throw new Error("Not authenticated");const{data:r}=await U.from("drip_settings").select("id").eq("user_id",s).maybeSingle();if(r){const{data:a,error:i}=await U.from("drip_settings").update(n).eq("user_id",s).select().single();if(i)throw i;return a}else{const{data:a,error:i}=await U.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 VFn(){const s=Vn(),{isGmailConnected:t,gmailEmail:n}=ux(),{data:r,isLoading:a}=UFn(),i=qFn(),[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 x=>{if(x&&!t){ae.error("Connect your Gmail account first before enabling Smart Drips");return}o(x);try{await i.mutateAsync({is_globally_enabled:x}),ae.success(x?"Smart Drips enabled globally":"Smart Drips paused globally")}catch{o(!x),ae.error("Failed to update settings")}},p=async x=>{d(x);try{await i.mutateAsync({append_signature:x}),ae.success(x?"Signature will be appended to drip emails":"Signature disabled for drip emails")}catch{d(!x),ae.error("Failed to update settings")}};return e.jsxs(Os,{open:u,onOpenChange:h,children:[e.jsx(Ko,{asChild:!0,children:e.jsxs($,{variant:"outline",size:"sm",className:"gap-1.5",children:[e.jsx(pc,{className:"h-3.5 w-3.5"}),"Settings"]})}),e.jsxs(Rs,{className:"sm:max-w-md",children:[e.jsxs(Us,{children:[e.jsxs(zs,{className:"flex items-center gap-2",children:[e.jsx(pc,{className:"h-5 w-5 text-primary"}),"Smart Drip Settings"]}),e.jsx(Sr,{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(nn,{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($e,{variant:"outline",className:"gap-1 text-emerald-600 border-emerald-200 bg-emerald-500/10 text-[10px]",children:[e.jsx(Fr,{className:"h-3 w-3"}),"Active"]}):e.jsxs($,{variant:"outline",size:"sm",className:"text-xs gap-1",onClick:()=>{h(!1),s("/mission-control/integrations")},children:[e.jsx(Tr,{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(Hl,{}),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($K,{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(Tn,{checked:l,onCheckedChange:m,disabled:a||i.isPending})]}),e.jsx(Hl,{}),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(kj,{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(Tn,{checked:c,onCheckedChange:p,disabled:a||i.isPending})]}),c&&e.jsxs($,{variant:"ghost",size:"sm",className:"w-full text-xs text-muted-foreground",onClick:()=>{h(!1),s("/profile")},children:[e.jsx(kj,{className:"h-3 w-3 mr-1"}),"Edit your email signature in Profile settings"]})]})]})]})}function HFn(){const s=Za();return ht({queryKey:["drip-templates",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await U.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 GFn(){const s=Za();return ht({queryKey:["drip-pipeline-stages",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await U.from("deal_pipeline_stages").select("*").eq("owner_user_id",s).order("sort_order",{ascending:!0});if(n)throw n;return t},enabled:!!s})}function WFn(){const s=Za(),t=ts();return yt({mutationFn:async n=>{if(!s)throw new Error("Not authenticated");const{data:r,error:a}=await U.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 KFn(){const s=ts();return yt({mutationFn:async({id:t,...n})=>{const{data:r,error:a}=await U.from("drip_templates").update(n).eq("id",t).select().single();if(a)throw a;return r},onSuccess:()=>{s.invalidateQueries({queryKey:["drip-templates"]})}})}function YFn(){const s=ts();return yt({mutationFn:async t=>{const{error:n}=await U.from("drip_templates").delete().eq("id",t);if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["drip-templates"]})}})}function ZFn(){const s=Za(),t=ts();return yt({mutationFn:async({templateId:n,stageId:r})=>{if(!s)throw new Error("Not authenticated");const{data:a,error:i}=await U.from("drip_templates").select("*").eq("id",n).single();if(i)throw i;const{data:l,error:o}=await U.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 XFn=[{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"}],TDe=1e3;function dHt({open:s,onOpenChange:t,campaignId:n,campaignName:r,birthdayFocused:a,onSuccess:i}){const l=Za(),o=MYe(),[c,d]=j.useState(""),[u,h]=j.useState(!!a),[m,p]=j.useState(new Set),{data:x,isLoading:g}=ht({queryKey:["campaign-contact-picker",l],queryFn:async()=>{const M=[];for(let I=0;;I+=TDe){const{data:D,error:B}=await U.from("innercircle_contacts").select("id, first_name, last_name, email, birthday").eq("owner_user_id",l).order("first_name").range(I,I+TDe-1);if(B)throw B;if(M.push(...D||[]),!D||D.length{const{data:M,error:I}=await U.from("drip_campaign_enrollments").select("contact_id, status").eq("campaign_id",n);if(I)throw I;return new Set((M||[]).filter(D=>D.status==="active"||D.status==="paused").map(D=>D.contact_id))},enabled:s&&!!n}),b=j.useMemo(()=>{const M=c.trim().toLowerCase();return(x||[]).filter(I=>u&&!I.birthday?!1:M?`${I.first_name||""} ${I.last_name||""}`.toLowerCase().includes(M)||(I.email||"").toLowerCase().includes(M):!0)},[x,c,u]),v=b.filter(M=>!(y!=null&&y.has(M.id))).map(M=>M.id),N=v.length>0&&v.every(M=>m.has(M)),C=M=>{p(I=>{const D=new Set(I);return D.has(M)?D.delete(M):D.add(M),D})},A=()=>{p(M=>{if(N){const I=new Set(M);return v.forEach(D=>I.delete(D)),I}return new Set([...M,...v])})},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`),ae.success(I.join(" · ")),p(new Set),t(!1),i==null||i()}catch(M){ae.error(M.message||"Failed to add contacts")}},P=(x||[]).filter(M=>M.birthday).length;return e.jsx(Os,{open:s,onOpenChange:t,children:e.jsxs(Rs,{className:"max-w-lg max-h-[85vh] flex flex-col p-0 overflow-hidden",children:[e.jsxs(Us,{className:"p-5 pb-3 border-b shrink-0 text-left",children:[e.jsxs(zs,{className:"flex items-center gap-2",children:[e.jsx(qn,{className:"h-4 w-4 text-primary"}),"Add contacts — ",r||"Campaign"]}),e.jsxs(Sr,{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(Vr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-muted-foreground"}),e.jsx(be,{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(ui,{checked:u,onCheckedChange:M=>h(!!M)}),e.jsx(np,{className:"h-3.5 w-3.5 text-primary"}),"Only contacts with a birthday on file (",P,")"]}),e.jsx($,{variant:"ghost",size:"sm",className:"text-xs h-7",onClick:A,disabled:v.length===0,children:N?"Clear all":`Select all ${v.length}`})]})]}),e.jsx("div",{className:"flex-1 min-h-0 px-5 py-3",children:e.jsx(Oi,{className:"h-[320px] -mx-1 px-1",children:g?e.jsx("div",{className:"text-center py-10 text-sm text-muted-foreground",children:"Loading contacts..."}):b.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:b.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(ui,{checked:I?!0:m.has(M.id),disabled:I,onCheckedChange:()=>C(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(nn,{className:"h-2.5 w-2.5"}),M.email]}),M.birthday&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(np,{className:"h-2.5 w-2.5"}),M.birthday]})]})]}),I&&e.jsx($e,{variant:"outline",className:"text-[9px]",children:"In campaign"})]},M.id)})})})}),e.jsxs(kr,{className:"p-4 border-t shrink-0 gap-2 sm:gap-2",children:[e.jsx($,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsxs($,{onClick:T,disabled:m.size===0||o.isPending,children:[o.isPending&&e.jsx(Ht,{className:"h-3.5 w-3.5 mr-1.5 animate-spin"}),"Add ",m.size||""," contact",m.size===1?"":"s"]})]})]})})}function QFn({open:s,onOpenChange:t,campaignId:n,campaignName:r}){const{data:a,isLoading:i}=UNn(n||void 0),l=VNn(),o=MYe(),[c,d]=j.useState(!1),u=async(p,x)=>{try{await l.mutateAsync({id:p,status:x}),ae.success(`Enrollment ${x}`)}catch{ae.error("Failed to update")}},h=async p=>{if(n)try{const x=await o.mutateAsync({campaignId:n,contactIds:[p]});x.enrolled>0?ae.success("Contact re-enrolled — first email queued"):x.skipped>0?ae.message("Already active in this campaign"):ae.error("Could not re-enroll")}catch{ae.error("Failed to re-enroll")}},m=p=>{const x={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($e,{variant:"outline",className:`text-[10px] capitalize ${x[p]||""}`,children:p})};return e.jsxs(Os,{open:s,onOpenChange:t,children:[e.jsxs(Rs,{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(zs,{className:"flex items-center gap-2",children:[e.jsx(qn,{className:"h-4 w-4 text-primary"}),"Enrollments — ",r||"Campaign"]}),e.jsx(Sr,{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($,{size:"sm",variant:"outline",onClick:()=>d(!0),children:[e.jsx(il,{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(on,{className:"h-14"},p))}):!a||a.length===0?e.jsxs("div",{className:"text-center py-12",children:[e.jsx(qn,{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($,{size:"sm",onClick:()=>d(!0),children:[e.jsx(il,{className:"h-3.5 w-3.5 mr-1.5"})," Add contacts"]})]}):e.jsx("div",{className:"space-y-2",children:a.map(p=>{var x,g,y,b;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:[(x=p.contact)==null?void 0:x.first_name," ",(g=p.contact)==null?void 0:g.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(nn,{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: ",Hs(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($,{size:"sm",variant:"ghost",onClick:()=>u(p.id,"paused"),title:"Pause",children:e.jsx(vy,{className:"h-3.5 w-3.5"})}),p.status==="paused"&&e.jsx($,{size:"sm",variant:"ghost",onClick:()=>u(p.id,"active"),title:"Resume",children:e.jsx(Td,{className:"h-3.5 w-3.5"})}),(p.status==="active"||p.status==="paused")&&e.jsx($,{size:"sm",variant:"ghost",onClick:()=>u(p.id,"exited"),title:"Exit",children:e.jsx(pr,{className:"h-3.5 w-3.5 text-destructive"})}),(p.status==="exited"||p.status==="completed")&&((b=p.contact)==null?void 0:b.id)&&e.jsxs($,{size:"sm",variant:"outline",className:"h-7 text-[11px] gap-1",onClick:()=>h(p.contact.id),disabled:o.isPending,children:[e.jsx(Ih,{className:"h-3 w-3"}),"Re-enroll"]})]},p.id)})})})})]}),e.jsx(dHt,{open:c,onOpenChange:d,campaignId:n,campaignName:r,birthdayFocused:/birthday/i.test(r||"")})]})}function JFn(){var A,T,P;const{data:s,isLoading:t}=Xee(),{hasLeadSite:n}=Mf(),r=TYe(),a=FNn(),i=L7t(),[l,o]=j.useState(null),[c,d]=j.useState(!1),[u,h]=j.useState(null),[m,p]=j.useState(null),[x,g]=j.useState(null),y=(s||[]).filter(M=>!M.is_starter),b=(s||[]).filter(M=>M.is_starter).filter(M=>!M.requires_lead_site||n),v=async M=>{try{await r.mutateAsync(M),ae.success("Campaign added to your library — customize and activate it!"),o(null)}catch(I){ae.error(I.message||"Failed to copy campaign")}},N=async M=>{try{await i.mutateAsync({id:M.id,is_active:!M.is_active}),ae.success(M.is_active?"Campaign paused":"Campaign activated")}catch{ae.error("Failed to update")}},C=async M=>{if(await Yi("Delete this campaign? Active enrollments will be removed."))try{await a.mutateAsync(M),ae.success("Campaign deleted")}catch{ae.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(on,{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(r5,{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(Mu,{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(Br,{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(qn,{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($,{size:"sm",onClick:()=>{h(null),d(!0)},children:[e.jsx(sn,{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(dn,{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($,{size:"sm",onClick:()=>{h(null),d(!0)},children:[e.jsx(sn,{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(e7n,{campaign:M,onPreview:()=>o(M.id),onToggleActive:()=>N(M),onDelete:()=>C(M.id),onEdit:()=>{h(M.id),d(!0)},onViewEnrollments:()=>p(M.id),onAddContacts:()=>g(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(dn,{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($e,{variant:"outline",className:"text-[10px]",children:[b.length," templates"]})]}),e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4",children:b.map(M=>e.jsx(t7n,{campaign:M,onPreview:()=>o(M.id)},M.id))})]}),e.jsx(dHt,{open:!!x,onOpenChange:M=>!M&&g(null),campaignId:x,campaignName:(A=y.find(M=>M.id===x))==null?void 0:A.name,birthdayFocused:/birthday/i.test(((T=y.find(M=>M.id===x))==null?void 0:T.name)||"")}),e.jsx(s7n,{campaignId:l,open:!!l,onOpenChange:M=>!M&&o(null),onClone:v,isCloning:r.isPending,onEdit:M=>{o(null),h(M),d(!0)}}),e.jsx(R7t,{open:c,onOpenChange:d,campaignId:u}),e.jsx(QFn,{open:!!m,onOpenChange:M=>!M&&p(null),campaignId:m,campaignName:(P=y.find(M=>M.id===m))==null?void 0:P.name})]})}function e7n({campaign:s,onPreview:t,onToggleActive:n,onDelete:r,onEdit:a,onViewEnrollments:i,onAddContacts:l}){const c=qNn(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($e,{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($e,{variant:"outline",className:"text-[9px] mt-2",children:GEe[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(mc,{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($,{size:"sm",className:"w-full h-8 text-xs mt-3",onClick:l,children:[e.jsx(il,{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($,{size:"sm",variant:"outline",className:"h-7 text-xs",onClick:a,children:[e.jsx(Ya,{className:"h-3 w-3 mr-1"})," Edit"]}),e.jsx($,{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 t7n({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($e,{className:"absolute top-2 right-2 bg-white/90 text-foreground hover:bg-white text-[10px]",children:[e.jsx(dn,{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($e,{variant:"outline",className:"text-[9px] mt-2",children:GEe[s.category]})]})]})}function s7n({campaignId:s,open:t,onOpenChange:n,onClone:r,isCloning:a,onEdit:i}){const{data:l}=Xee(),{data:o}=P7t(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(x=>{const g=new Set(x);return g.has(p)?g.delete(p):g.add(p),g})},m=(p,x)=>{if(p.delay_type==="calendar_anchor"){const y=p.anchor_field==="birthday"?"birthday":"home anniversary",b=p.anchor_offset_days||0;return b===0?`On their ${y}`:b<0?`${Math.abs(b)} days before ${y}`:`${b} days after ${y}`}if(x===0&&p.delay_days===0&&p.delay_hours===0)return"Sends immediately";const g=[];return p.delay_days&&g.push(`${p.delay_days}d`),p.delay_hours&&g.push(`${p.delay_hours}h`),x===0?`After ${g.join(" ")}`:`+${g.join(" ")}`};return e.jsx(Os,{open:t,onOpenChange:n,children:e.jsxs(Rs,{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(zs,{className:"text-xl font-bold text-white",children:u.name}),e.jsx(Sr,{className:"text-white/90 mt-1",children:u.description}),e.jsxs("div",{className:"flex gap-2 mt-3",children:[e.jsx($e,{className:"bg-white/20 text-white border-white/20 hover:bg-white/20",children:GEe[u.category]}),e.jsxs($e,{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,x)=>{const g=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:x+1}),xh(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(ia,{className:"h-3 w-3"}):e.jsx(Hr,{className:"h-3 w-3"}),e.jsx("span",{children:m(p,x)}),e.jsx("span",{children:"·"}),e.jsx(nn,{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||"",b=/<\/?[a-z][\s\S]*>/i.test(y),v=b?y.replace(//gi,"").replace(/<[^>]+>/g," ").replace(/ /g," ").replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/\s+/g," ").trim():y;return g?b?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:v})})(),p.body&&p.body.length>160&&e.jsx("span",{className:"text-[10px] text-primary mt-1.5 inline-block",children:g?"Show less":"Show full email"})]})})]},p.id)})]})}),e.jsxs(kr,{className:"border-t p-4 shrink-0",children:[e.jsx($,{variant:"outline",onClick:()=>n(!1),children:"Close"}),!u.is_starter&&i&&e.jsxs($,{variant:"secondary",onClick:()=>i(u.id),children:[e.jsx(Ya,{className:"h-3.5 w-3.5 mr-1.5"})," Edit Campaign"]}),u.is_starter&&e.jsxs($,{onClick:()=>r(u.id),disabled:a,children:[a?e.jsx(Ht,{className:"h-3.5 w-3.5 mr-1.5 animate-spin"}):e.jsx(Ca,{className:"h-3.5 w-3.5 mr-1.5"}),"Copy to my campaigns"]})]})]})})}const PNe=[{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 n7n(){const s=Za();return ht({queryKey:["drip-auto-rules",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await U.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 r7n(){const s=Za(),t=ts();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 U.from("drip_auto_enroll_rules").upsert(r).select().single();if(i)throw i;return a},onSuccess:()=>{t.invalidateQueries({queryKey:["drip-auto-rules"]})}})}function a7n(){const s=ts();return yt({mutationFn:async({id:t,is_active:n})=>{const{error:r}=await U.from("drip_auto_enroll_rules").update({is_active:n}).eq("id",t);if(r)throw r},onSuccess:()=>s.invalidateQueries({queryKey:["drip-auto-rules"]})})}function i7n(){const s=ts();return yt({mutationFn:async t=>{const{error:n}=await U.from("drip_auto_enroll_rules").delete().eq("id",t);if(n)throw n},onSuccess:()=>s.invalidateQueries({queryKey:["drip-auto-rules"]})})}function o7n(s=25){const t=Za();return ht({queryKey:["drip-auto-log",t,s],queryFn:async()=>{if(!t)return[];const{data:n,error:r}=await U.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 l7n(){const s=Za();return ht({queryKey:["life-event-coverage",s],queryFn:async()=>{if(!s)return null;const{data:t,error:n}=await U.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 c7n(){const s=ts();return yt({mutationFn:async t=>{const{data:n,error:r}=await U.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 d7n={birthday:np,home_anniversary:LN,spouse_birthday:Co,wedding_anniversary:fo};function u7n(){var C;const{data:s,isLoading:t}=n7n(),{data:n}=Xee(),{data:r}=l7n(),{data:a}=o7n(10),i=r7n(),l=a7n(),o=i7n(),c=c7n(),d=TYe(),[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"},x=j.useMemo(()=>{if(!(u!=null&&u.trigger_type))return null;const A=p[u.trigger_type];return!A||m.some(P=>String(P.name||"").toLowerCase().includes(A.toLowerCase()))?null:(n||[]).find(P=>P.is_starter&&String(P.name||"").toLowerCase()===A.toLowerCase())??null},[n,m,u==null?void 0:u.trigger_type]),g=async()=>{if(x)try{const A=await d.mutateAsync(x.id);h(T=>({...T,campaign_id:A.id})),ae.success(`“${x.name}” template added to your campaigns`)}catch(A){ae.error((A==null?void 0:A.message)||"Could not copy the template")}},y=A=>(s||[]).find(T=>T.trigger_type===A),b=async()=>{if(!(u!=null&&u.campaign_id)||!(u!=null&&u.trigger_type)){ae.error("Pick a campaign first");return}try{await i.mutateAsync(u),ae.success("Autopilot rule saved"),h(null)}catch(A){ae.error((A==null?void 0:A.message)||"Could not save rule")}},v=async()=>{try{const A=await c.mutateAsync(void 0);ae.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){ae.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(dn,{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($,{variant:"outline",onClick:v,disabled:c.isPending||N===0,className:"gap-2 shrink-0",children:[c.isPending?e.jsx(Ht,{className:"h-4 w-4 animate-spin"}):e.jsx(Wi,{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:PNe.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(Ht,{className:"h-5 w-5 animate-spin text-muted-foreground"})}):e.jsx("div",{className:"grid sm:grid-cols-2 gap-3",children:PNe.map(A=>{var I;const T=y(A.value),P=d7n[A.value]||np,M=r==null?void 0:r.counts[A.value];return e.jsxs("div",{className:Tt("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:Tt("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(P,{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($e,{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(Tn,{checked:T.is_active,onCheckedChange:D=>l.mutate({id:T.id,is_active:D})}):null]}),e.jsxs("div",{className:"flex gap-2 mt-3",children:[e.jsxs($,{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(ox,{className:"h-3.5 w-3.5"}):e.jsx(sn,{className:"h-3.5 w-3.5"}),T?"Edit rule":"Turn on autopilot"]}),T&&e.jsx($,{size:"sm",variant:"ghost",className:"text-muted-foreground hover:text-destructive",onClick:()=>o.mutate(T.id),children:e.jsx(Pn,{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,P;return e.jsxs("div",{className:"flex items-center gap-3 px-4 py-2.5",children:[e.jsx(oa,{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," ",(P=A.contact)==null?void 0:P.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(Os,{open:!!u,onOpenChange:A=>!A&&h(null),children:e.jsxs(Rs,{className:"sm:max-w-md",children:[e.jsxs(Us,{children:[e.jsxs(zs,{children:[(C=PNe.find(A=>A.value===(u==null?void 0:u.trigger_type)))==null?void 0:C.label," autopilot"]}),e.jsx(Sr,{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(se,{children:"Campaign to enroll into"}),e.jsxs(vs,{value:(u==null?void 0:u.campaign_id)??"",onValueChange:A=>h(T=>({...T,campaign_id:A})),children:[e.jsx(gs,{children:e.jsx(bs,{placeholder:"Select one of your campaigns"})}),e.jsx(ys,{children:m.map(A=>e.jsx(Ye,{value:A.id,children:A.name},A.id))})]}),x&&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(dn,{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 “",x.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($,{size:"sm",variant:"outline",className:"mt-2 gap-1.5",disabled:d.isPending,onClick:g,children:[d.isPending?e.jsx(Ht,{className:"h-3.5 w-3.5 animate-spin"}):e.jsx(sn,{className:"h-3.5 w-3.5"}),"Use this template"]})]})]})}),m.length===0&&!x&&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(se,{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(rx,{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(se,{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(Tn,{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(se,{className:"text-sm",children:"Autopilot active"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Runs every morning automatically."})]}),e.jsx(Tn,{checked:(u==null?void 0:u.is_active)??!0,onCheckedChange:A=>h(T=>({...T,is_active:A}))})]})]}),e.jsxs(kr,{children:[e.jsx($,{variant:"ghost",onClick:()=>h(null),children:"Cancel"}),e.jsxs($,{onClick:b,disabled:i.isPending||!(u!=null&&u.campaign_id),children:[i.isPending&&e.jsx(Ht,{className:"h-4 w-4 mr-1.5 animate-spin"}),"Save rule"]})]})]})})]})}function h7n(){const s=Za(),t=Vn(),{isGmailConnected:n,gmailEmail:r,isLoading:a}=ux(),{data:i,isLoading:l}=HFn(),{data:o,isLoading:c}=GFn(),d=WFn(),u=KFn(),h=YFn(),m=ZFn(),[p,x]=j.useState(null),[g,y]=j.useState(null),b=(i==null?void 0:i.filter(I=>!I.is_starter&&I.owner_user_id===s))||[],v=(i==null?void 0:i.filter(I=>I.is_starter))||[],N=I=>b.filter(D=>D.stage_id===I),C=async I=>{try{await u.mutateAsync({id:I.id,is_enabled:!I.is_enabled}),ae.success(I.is_enabled?"Drip disabled":"Drip enabled")}catch{ae.error("Failed to update")}},A=async I=>{try{const D=o==null?void 0:o.find(B=>B.id===I);await d.mutateAsync({stage_id:I,title:`${(D==null?void 0:D.name)||"Stage"} follow-up`,subject:"",body:"",channel:"email",delay_type:"instant",delay_minutes:0}),x(I),ae.success("Drip template created")}catch{ae.error("Failed to create template")}},T=async I=>{try{await h.mutateAsync(I),ae.success("Template deleted")}catch{ae.error("Failed to delete")}},P=async I=>{if(!o||o.length===0){ae.error("No pipeline stages found");return}const D=o[0].id;try{await m.mutateAsync({templateId:I,stageId:D}),ae.success("Template copied to your drips!")}catch{ae.error("Failed to copy template")}},M=l||c;return e.jsx(Ks,{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(ox,{className:"h-5 w-5 text-primary"}),e.jsx("h1",{className:"text-2xl font-bold",children:"Smart Drips"}),e.jsx($e,{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(VFn,{})]}),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(r5,{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(nn,{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(r5,{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($,{variant:"outline",size:"sm",className:"h-7 text-xs",onClick:()=>t("/mission-control/integrations"),children:[e.jsx(nn,{className:"h-3 w-3 mr-1.5"}),"Connect Gmail"]})]})]})),e.jsxs(ua,{defaultValue:"my-drips",children:[e.jsxs(ha,{className:"grid grid-cols-4 w-full max-w-2xl mb-6",children:[e.jsx(Qt,{value:"my-drips",children:"Stage Drips"}),e.jsxs(Qt,{value:"campaigns",children:["Campaigns",e.jsx($e,{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(Qt,{value:"autopilot",children:["Life Events",e.jsx($e,{variant:"outline",className:"ml-1.5 text-[9px] bg-primary/10 text-primary border-primary/20 px-1 py-0",children:"Auto"})]}),e.jsxs(Qt,{value:"starters",children:["Stage Starters",v.length>0&&e.jsx($e,{variant:"secondary",className:"ml-1.5 text-[10px] px-1.5 py-0",children:v.length})]})]}),e.jsx(Jt,{value:"campaigns",children:e.jsx(JFn,{})}),e.jsx(Jt,{value:"autopilot",children:e.jsx(u7n,{})}),e.jsx(Jt,{value:"my-drips",children:M?e.jsx("div",{className:"space-y-3",children:[1,2,3,4].map(I=>e.jsx(on,{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(ox,{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 D=N(I.id),B=p===I.id,q=D.some(W=>W.is_enabled);return e.jsxs("div",{className:"border rounded-xl overflow-hidden",children:[e.jsxs("button",{onClick:()=>x(B?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}),D.length>0&&e.jsxs($e,{variant:"outline",className:`text-[10px] ${q?"bg-emerald-500/10 text-emerald-600 border-emerald-200":"text-muted-foreground"}`,children:[D.length," drip",D.length!==1?"s":"",q&&" · Active"]}),B?e.jsx(_o,{className:"h-4 w-4 text-muted-foreground"}):e.jsx(Ja,{className:"h-4 w-4 text-muted-foreground"})]}),B&&e.jsx("div",{className:"border-t bg-muted/10 p-4 space-y-3",children:D.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($,{variant:"outline",size:"sm",onClick:()=>A(I.id),disabled:d.isPending,children:[e.jsx(sn,{className:"h-3.5 w-3.5 mr-1.5"}),"Create Drip"]})]}):e.jsxs(e.Fragment,{children:[D.map(W=>e.jsx(m1t,{template:W,isEditing:g===W.id,onToggleEdit:()=>y(g===W.id?null:W.id),onToggleEnabled:()=>C(W),onUpdate:V=>u.mutateAsync({id:W.id,...V}),onDelete:()=>T(W.id),userId:s||""},W.id)),e.jsxs($,{variant:"ghost",size:"sm",className:"w-full text-xs text-muted-foreground",onClick:()=>A(I.id),children:[e.jsx(sn,{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 D=N(I.id),B=p===I.id,q=D.some(W=>W.is_enabled);return e.jsxs("div",{className:"border rounded-xl overflow-hidden mb-2",children:[e.jsxs("button",{onClick:()=>x(B?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}),D.length>0&&e.jsxs($e,{variant:"outline",className:`text-[10px] ${q?"bg-emerald-500/10 text-emerald-600 border-emerald-200":"text-muted-foreground"}`,children:[D.length," drip",D.length!==1?"s":"",q&&" · Active"]}),B?e.jsx(_o,{className:"h-4 w-4 text-muted-foreground"}):e.jsx(Ja,{className:"h-4 w-4 text-muted-foreground"})]}),B&&e.jsx("div",{className:"border-t bg-muted/10 p-4 space-y-3",children:D.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($,{variant:"outline",size:"sm",onClick:()=>A(I.id),disabled:d.isPending,children:[e.jsx(sn,{className:"h-3.5 w-3.5 mr-1.5"})," Create Drip"]})]}):e.jsxs(e.Fragment,{children:[D.map(W=>e.jsx(m1t,{template:W,isEditing:g===W.id,onToggleEdit:()=>y(g===W.id?null:W.id),onToggleEnabled:()=>C(W),onUpdate:V=>u.mutateAsync({id:W.id,...V}),onDelete:()=>T(W.id),userId:s||""},W.id)),e.jsxs($,{variant:"ghost",size:"sm",className:"w-full text-xs text-muted-foreground",onClick:()=>A(I.id),children:[e.jsx(sn,{className:"h-3 w-3 mr-1"})," Add another drip"]})]})})]},I.id)})]})]})}),e.jsx(Jt,{value:"starters",children:v.length===0?e.jsxs("div",{className:"text-center py-12 border border-dashed rounded-xl",children:[e.jsx(dn,{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:v.map(I=>e.jsx(m7n,{template:I,onCopy:()=>P(I.id),isCopying:m.isPending},I.id))})})]})]})})}function m1t({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,x]=j.useState(s.video_url||""),[g,y]=j.useState(s.channel),[b,v]=j.useState(s.delay_type),[N,C]=j.useState(s.delay_minutes),[A,T]=j.useState(!1),P=async()=>{T(!0);try{await a({title:o,subject:d,body:h,video_url:p||null,channel:g,delay_type:b,delay_minutes:N}),ae.success("Drip saved"),n()}catch{ae.error("Failed to save")}finally{T(!1)}},M=I=>{m(D=>D+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(Ji,{className:"h-3 w-3 text-muted-foreground"}):e.jsx(nn,{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(Xr,{className:"h-3 w-3 text-primary"})]})]}),e.jsx(Tn,{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(se,{className:"text-xs font-medium",children:"Title (internal)"}),e.jsx(be,{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(se,{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 ${g===I?"bg-primary text-primary-foreground border-primary":"bg-background text-muted-foreground border-input hover:border-primary/50"}`,children:[I==="sms"?e.jsx(Ji,{className:"h-3 w-3"}):e.jsx(nn,{className:"h-3 w-3"}),I==="sms"?"SMS":"Email"]},I))})]}),e.jsxs("div",{className:"flex-1",children:[e.jsx(se,{className:"text-xs font-medium",children:"Timing"}),e.jsxs("div",{className:"flex gap-1 mt-1",children:[e.jsx("button",{onClick:()=>v("instant"),className:`flex-1 px-3 py-1.5 rounded-md text-xs font-medium border transition-colors ${b==="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:()=>v("scheduled"),className:`flex-1 px-3 py-1.5 rounded-md text-xs font-medium border transition-colors ${b==="scheduled"?"bg-primary text-primary-foreground border-primary":"bg-background text-muted-foreground border-input hover:border-primary/50"}`,children:[e.jsx(Hr,{className:"h-3 w-3 mr-1 inline"}),"Delay"]})]})]})]}),b==="scheduled"&&e.jsxs("div",{children:[e.jsx(se,{className:"text-xs font-medium",children:"Delay"}),e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[e.jsx(be,{type:"number",min:1,value:N>=60?Math.round(N/60):N,onChange:I=>{const D=parseInt(I.target.value)||0;C(N>=60?D*60:D)},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"?C(30):I.label==="Hours"?C(60):C(1440)},children:I.label},I.label))})]})]}),g==="email"&&e.jsxs("div",{children:[e.jsx(se,{className:"text-xs font-medium",children:"Subject Line"}),e.jsx(be,{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(se,{className:"text-xs font-medium",children:g==="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..."}),XFn.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:g==="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(se,{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(Xr,{className:"h-3 w-3 inline mr-1 text-primary"}),p.length>50?p.slice(0,50)+"...":p]}),e.jsx($,{variant:"ghost",size:"sm",className:"h-7 text-xs text-destructive",onClick:()=>x(""),children:"Remove"})]}):e.jsxs("div",{className:"mt-1 flex items-center gap-1.5",children:[e.jsx(cXe,{onVideoReady:I=>x(I)}),e.jsx(hF,{userId:l,onSelect:I=>x(I),triggerSize:"sm",triggerClassName:"gap-1.5 flex-1"}),e.jsxs($,{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&&x(I)},children:[e.jsx(kc,{className:"h-3 w-3"})," Paste URL"]})]})]}),e.jsxs("div",{className:"flex items-center justify-between pt-2 border-t",children:[e.jsxs($,{variant:"ghost",size:"sm",className:"text-xs text-destructive hover:text-destructive",onClick:i,children:[e.jsx(Pn,{className:"h-3 w-3 mr-1"})," Delete"]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx($,{variant:"outline",size:"sm",className:"text-xs",onClick:n,children:"Cancel"}),e.jsx($,{size:"sm",className:"text-xs",onClick:P,disabled:A,children:A?"Saving...":"Save Drip"})]})]})]})]})}function m7n({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($e,{variant:"secondary",className:"text-[10px] px-1.5 py-0",children:l}),e.jsxs($e,{variant:"outline",className:"text-[10px] gap-1",children:[s.channel==="sms"?e.jsx(Ji,{className:"h-3 w-3"}):e.jsx(nn,{className:"h-3 w-3"}),s.channel==="sms"?"SMS":"Email"]}),e.jsxs($e,{variant:"outline",className:"text-[10px] gap-1",children:[e.jsx(Hr,{className:"h-3 w-3"}),s.delay_type==="instant"?"Instant":o.replace("Sends ","")]}),r?e.jsx(_o,{className:"h-4 w-4 text-muted-foreground ml-1"}):e.jsx(Ja,{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(Hr,{className:"h-3.5 w-3.5"}),e.jsx("span",{children:o})]}),e.jsxs($,{onClick:c=>{c.stopPropagation(),t()},size:"sm",className:"w-full gap-1.5",disabled:n,children:[e.jsx(Ca,{className:"h-3.5 w-3.5"}),"Use This Template"]})]})]})}const uHt=()=>{const s=Wd();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 p7n(){return j.useEffect(()=>(document.body.classList.add("cardstudio-page"),()=>{document.body.classList.remove("cardstudio-page")}),[]),e.jsxs(RZ,{children:[e.jsx(ds,{path:"/c/:shareToken",element:e.jsx(cHt,{})}),e.jsx(ds,{path:"*",element:e.jsx(uHt,{})})]})}const MDe={Home:"🏠",Search:"🔍",DollarSign:"💰",Coffee:"☕",Calendar:"📅",Users:"👥",Phone:"📞",Video:"🎥"},f7n=["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 x7n(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 LDe(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 hHt({slugOverride:s}){const t=Vi(),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,x]=j.useState({name:"",email:"",phone:"",message:""}),[g,y]=j.useState(!1),[b,v]=j.useState(null),[N,C]=j.useState(()=>{try{return Intl.DateTimeFormat().resolvedOptions().timeZone||"America/New_York"}catch{return"America/New_York"}}),{data:A,isLoading:T}=ht({queryKey:["public-booking-settings",n],queryFn:async()=>{const{data:ne,error:ee}=await U.from("agent_booking_settings").select("*").eq("slug",n).eq("is_active",!0).single();if(ee)throw ee;return ne},enabled:!!n}),{data:P}=ht({queryKey:["public-booking-profile",A==null?void 0:A.user_id],queryFn:async()=>{const{data:ne,error:ee}=await U.from("profiles").select("name, avatar_url, email, phone, title, bio").eq("id",A.user_id).single();if(ee)throw ee;return ne},enabled:!!(A!=null&&A.user_id)}),{data:M=[]}=ht({queryKey:["public-booking-types",A==null?void 0:A.user_id],queryFn:async()=>{const{data:ne,error:ee}=await U.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(ee)throw ee;return ne},enabled:!!(A!=null&&A.user_id)}),I=Hs(h,"yyyy-MM"),{data:D={},isFetching:B}=ht({queryKey:["public-availability-map",n,i==null?void 0:i.id,I],enabled:!!n&&!!i,staleTime:6e4,queryFn:async()=>{const ne=new Date(h.getFullYear(),h.getMonth(),1),ee=ep(new Date),le=Pb(ee,ne)?ee:ne,he=new Date(h.getFullYear(),h.getMonth()+1,0),ve=Math.max(1,Math.round((he.getTime()-le.getTime())/864e5)+1),{data:ge,error:fe}=await U.functions.invoke("agent-booking",{body:{action:"availability",slug:n,booking_type_id:i.id,start:Hs(le,"yyyy-MM-dd"),days:Math.min(ve,90)}});if(fe)throw fe;if(ge!=null&&ge.error)throw new Error(ge.error);return(ge==null?void 0:ge.availability)||{}}}),q=ne=>{const ee=ep(new Date),le=Bd(ee,(A==null?void 0:A.max_advance_days)||30);return aw(ne,ee)||Pb(ne,le)?!1:(D[Hs(ne,"yyyy-MM-dd")]||[]).length>0},W=j.useMemo(()=>o?D[Hs(o,"yyyy-MM-dd")]||[]:[],[o,D]),V=j.useMemo(()=>{const ne=h.getFullYear(),ee=h.getMonth(),le=new Date(ne,ee,1),he=new Date(ne,ee+1,0),ve=le.getDay(),ge=[];for(let fe=0;fe{var ne,ee;if(!(!i||!o||!d||!p.name||!A)){y(!0);try{const le=Hs(o,"yyyy-MM-dd"),{data:he,error:ve}=await U.functions.invoke("agent-booking",{body:{action:"create",slug:n,booking_type_id:i.id,date:le,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(ve){let je=ve.message;try{const Ee=await((ee=(ne=ve.context)==null?void 0:ne.json)==null?void 0:ee.call(ne));Ee!=null&&Ee.error&&(je=Ee.error)}catch{}throw new Error(je)}if(he!=null&&he.error)throw new Error(he.error);const ge=(he==null?void 0:he.end_time)||d,fe=he!=null&&he.manage_token?`${window.location.origin}/booking/manage/${he.manage_token}`:null;v(fe),U.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:le,startTime:d,endTime:ge,durationMinutes:i.duration_minutes,meetingLink:A.meeting_link||null,manageUrl:fe}}).catch(je=>console.error("Booking notify error:",je)),a("confirmed")}catch(le){ae.error("Failed to book: "+le.message)}finally{y(!1)}}},Q=ne=>{const[ee,le]=ne.split(":").map(Number),he=ee>=12?"PM":"AM";return`${ee%12||12}:${le.toString().padStart(2,"0")} ${he}`},J=(A==null?void 0:A.timezone)||"America/New_York",ce=N!==J,ue=(ne,ee)=>{if(!ce)return Q(ee);try{return new Intl.DateTimeFormat("en-US",{timeZone:N,hour:"numeric",minute:"2-digit"}).format(new Date(x7n(ne,ee,J)))}catch{return Q(ee)}};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:[P!=null&&P.avatar_url?e.jsx("img",{src:P.avatar_url,alt:(P==null?void 0:P.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(Lo,{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:(P==null?void 0:P.name)||"Agent"}),(P==null?void 0:P.title)&&e.jsx("p",{className:"text-sm text-slate-500 mt-0.5",children:P.title})]})]})}),e.jsxs("div",{className:"px-6 py-4 flex flex-wrap gap-2",children:[(P==null?void 0:P.phone)&&e.jsxs("a",{href:`tel:${P.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(ya,{className:"h-3.5 w-3.5"}),e.jsx("span",{className:"hidden sm:inline",children:P.phone}),e.jsx("span",{className:"sm:hidden",children:"Call"})]}),(P==null?void 0:P.email)&&e.jsxs("a",{href:`mailto:${P.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(nn,{className:"h-3.5 w-3.5"}),e.jsx("span",{className:"hidden sm:inline",children:P.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(ne=>e.jsx("button",{onClick:()=>{l(ne),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:ne.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:MDe[ne.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:ne.name}),ne.description&&e.jsx("p",{className:"text-xs text-slate-500 mt-0.5 line-clamp-2",children:ne.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(Hr,{className:"h-3 w-3"}),ne.duration_minutes,"m"]})]})})},ne.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(ka,{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:MDe[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(Hr,{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:Hs(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(Ic,{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(Ja,{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(ne=>e.jsx("div",{className:"text-[10px] uppercase tracking-wider text-slate-400 font-semibold py-2",children:ne},ne)),V.map((ne,ee)=>{if(!ne)return e.jsx("div",{},`pad-${ee}`);const le=q(ne),he=o&&hu(ne,o),ve=hu(ne,new Date);return e.jsx("button",{disabled:!le,onClick:()=>{c(ne),u(null)},className:`h-10 w-10 mx-auto rounded-xl text-sm font-medium transition-all duration-150 ${he?"bg-[#406E71] text-white shadow-md shadow-[#406E71]/30 scale-105":le?"hover:bg-[#406E71]/10 text-slate-700 hover:text-[#406E71]":"text-slate-200 cursor-not-allowed"} ${ve&&!he?"ring-1 ring-[#406E71]/40":""}`,children:ne.getDate()},ne.toISOString())})]})]}),o&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Nl,{className:"h-4 w-4 text-[#406E71]"}),e.jsx("h3",{className:"font-semibold text-sm text-slate-800",children:Hs(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:ne=>C(ne.target.value),className:"text-[11px] font-medium text-slate-700 bg-transparent focus:outline-none cursor-pointer",children:Array.from(new Set([N,J,...f7n])).map(ne=>e.jsxs("option",{value:ne,children:[ne.replace(/_/g," ")," (",LDe(ne),")"]},ne))})]}),B&&W.length===0?e.jsxs("div",{className:"text-center py-8 space-y-2",children:[e.jsx(Ht,{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…"})]}):W.length===0?e.jsxs("div",{className:"text-center py-8 space-y-2",children:[e.jsx(Hr,{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:W.map(ne=>{const ee=d===ne;return e.jsx("button",{onClick:()=>u(ne),className:`px-3 py-2.5 rounded-xl text-sm font-medium transition-all duration-150 ${ee?"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(Hs(o,"yyyy-MM-dd"),ne)},ne)})}),d&&e.jsx($,{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(ka,{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:MDe[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(Nl,{className:"h-3.5 w-3.5 text-[#406E71]"}),Hs(o,"EEE, MMM d, yyyy")]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Hr,{className:"h-3.5 w-3.5 text-[#406E71]"}),ue(Hs(o,"yyyy-MM-dd"),d)," (",LDe(N),") · ",i.duration_minutes," min"]})]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{className:"text-xs font-semibold text-slate-700",children:"Full Name *"}),e.jsx(be,{value:p.name,onChange:ne=>x({...p,name:ne.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(se,{className:"text-xs font-semibold text-slate-700",children:"Email"}),e.jsxs("div",{className:"relative",children:[e.jsx(nn,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-slate-400"}),e.jsx(be,{type:"email",value:p.email,onChange:ne=>x({...p,email:ne.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(se,{className:"text-xs font-semibold text-slate-700",children:"Phone"}),e.jsxs("div",{className:"relative",children:[e.jsx(ya,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-slate-400"}),e.jsx(be,{type:"tel",value:p.phone,onChange:ne=>x({...p,phone:ne.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(se,{className:"text-xs font-semibold text-slate-700",children:"Message (optional)"}),e.jsx(Is,{value:p.message,onChange:ne=>x({...p,message:ne.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($,{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||g,children:g?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(Fr,{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 ",(P==null?void 0:P.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&&Hs(o,"EEEE, MMMM d, yyyy")}),e.jsxs("p",{className:"text-slate-500",children:[o&&d?`${ue(Hs(o,"yyyy-MM-dd"),d)} (${LDe(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."}),b&&e.jsx("div",{className:"pt-1",children:e.jsx("a",{href:b,className:"inline-flex items-center gap-1.5 text-xs font-semibold text-[#406E71] underline underline-offset-4",children:"Reschedule or cancel this meeting"})}),((P==null?void 0:P.phone)||(P==null?void 0:P.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:[(P==null?void 0:P.phone)&&e.jsxs("a",{href:`tel:${P.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(ya,{className:"h-3.5 w-3.5"})," Call"]}),(P==null?void 0:P.email)&&e.jsxs("a",{href:`mailto:${P.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(nn,{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(Nl,{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 g7n(){const t=Wd().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(hHt,{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 y7n(){const t=Wd().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(u6t,{slugOverride:t})}function v7n(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 b7n={playfair:"'Playfair Display', Georgia, serif",baskerville:"'Libre Baskerville', Georgia, serif",instrument:"'Instrument Serif', Georgia, serif",sans:"'Inter', system-ui, sans-serif"};function _7n({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=b7n[s.heading_font||"playfair"],u=s.eyebrow||null,h=s.headline_accent||null,m=Array.isArray(s.trust_pills)?s.trust_pills:[],p=t.slice(0,5);return e.jsxs("section",{className:"relative w-full min-h-screen md:min-h-[760px] overflow-hidden",style:{backgroundColor:c},children:[s.hero_image_url?e.jsx("img",{src:s.hero_image_url,alt:"",className:"absolute inset-0 w-full h-full object-cover",loading:"eager"}):e.jsx("div",{className:"absolute inset-0",style:{background:`linear-gradient(135deg, ${c}, #000)`}}),e.jsx("div",{className:"absolute inset-0 bg-gradient-to-r from-black/85 via-black/55 to-black/25"}),e.jsx("div",{className:"absolute inset-0 bg-gradient-to-t from-black/70 via-transparent to-black/20"}),e.jsx("div",{className:"relative z-10 mx-auto w-full max-w-7xl px-6 md:px-10 py-16 md:py-24 min-h-screen md:min-h-[760px] flex items-center",children:e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-5 gap-10 lg:gap-12 w-full items-center",children:[e.jsxs("div",{className:"lg:col-span-3 text-white",children:[s.logo_url&&e.jsx(w7n,{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(ya,{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(nn,{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:[p.map(x=>e.jsxs("div",{children:[e.jsxs(se,{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",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,g)=>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]},g))})]})})]})})]})}function w7n({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(v7n(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 j7n(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 N7n(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 k7n(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 S7n({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=j7n(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(Hr,{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(ai,{className:"h-3.5 w-3.5"})," ",h]})]})]}),!d&&e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs("a",{href:N7n(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(ia,{className:"h-4 w-4"})," Add to Google"]}),e.jsxs("a",{href:k7n(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(ia,{className:"h-4 w-4"})," Apple / Outlook"]})]})]})})})}function C7n(){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 mHt({slugOverride:s}){var B;const{slug:t}=Vi(),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()),x=j.useState(()=>C7n())[0],{data:g,isLoading:y}=ht({queryKey:["public-landing-page",n],queryFn:async()=>{const{data:q,error:W}=await U.from("landing_pages").select("*").eq("slug",n).eq("is_published",!0).single();if(W)throw W;return q},enabled:!!n}),{data:b=[]}=ht({queryKey:["public-landing-page-fields",g==null?void 0:g.id],queryFn:async()=>{const{data:q,error:W}=await U.from("landing_page_fields").select("*").eq("page_id",g.id).order("sort_order");if(W)throw W;return q},enabled:!!(g!=null&&g.id)});j.useEffect(()=>{g!=null&&g.id&&U.from("landing_pages").update({view_count:(g.view_count||0)+1}).eq("id",g.id).then(()=>{})},[g==null?void 0:g.id]),j.useEffect(()=>{if(!(g!=null&&g.id))return;const q=new URLSearchParams(window.location.search);U.functions.invoke("landing-page-track",{body:{page_id:g.id,event_type:"view",session_id:x,utm_source:q.get("utm_source"),utm_medium:q.get("utm_medium"),utm_campaign:q.get("utm_campaign"),referrer:document.referrer||null,device:window.matchMedia("(max-width: 768px)").matches?"mobile":"desktop"}}).catch(()=>{})},[g==null?void 0:g.id,x]);const v=yt({mutationFn:async()=>{const q=b.find(ee=>ee.field_type==="text"&&ee.label.toLowerCase().includes("name")),W=b.find(ee=>ee.field_type==="email"),V=b.find(ee=>ee.field_type==="phone"),K=q?String(i[q.label]||""):null,Q=W?String(i[W.label]||""):null,J=V?String(i[V.label]||""):null,ce=new URLSearchParams(window.location.search),{data:ue,error:ne}=await U.functions.invoke("landing-page-submit",{body:{page_id:g.id,answers:JSON.parse(JSON.stringify(i)),contact_name:K,contact_email:Q,contact_phone:J,session_id:x,honeypot:h,rendered_at:p,utm_source:ce.get("utm_source"),utm_medium:ce.get("utm_medium"),utm_campaign:ce.get("utm_campaign"),referrer:document.referrer||null}});if(ne)throw ne;return ue},onSuccess:q=>{a(!0),q!=null&&q.redirect_url&&setTimeout(()=>{window.location.href=q.redirect_url},1500)}}),N=q=>{q.preventDefault(),!(b.filter(V=>V.is_required&&!i[V.label]).length>0)&&v.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(!g)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 C=g.primary_color||"#406E71",A=g.accent_color||"#2a4c64",T=g,P=g.page_type==="lead_magnet",M=g.page_type==="just_listed"||g.page_type==="just_sold",I=Array.isArray(T.property_photos)?T.property_photos:[],D=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, ${C}, ${A})`},children:e.jsxs("div",{className:"bg-white rounded-2xl shadow-2xl p-8 max-w-md mx-4 text-center",children:[e.jsx(Fr,{className:"h-16 w-16 mx-auto mb-4",style:{color:C}}),e.jsx("h2",{className:"text-2xl font-bold mb-2",children:P?"Your download is ready!":"Submitted!"}),e.jsx("p",{className:"text-gray-600",children:g.success_message}),P&&D&&e.jsxs("a",{href:D,target:"_blank",rel:"noopener noreferrer",className:"inline-flex items-center gap-2 mt-6 px-6 py-3 rounded-lg text-white font-semibold transition-transform hover:scale-105",style:{backgroundColor:C},children:[e.jsx(di,{className:"h-5 w-5"}),"Download ",T.lead_magnet_file_name||"Your File"]}),g.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:g.agent_name}),g.agent_phone&&e.jsxs("a",{href:`tel:${g.agent_phone}`,className:"text-sm flex items-center justify-center gap-1 mt-1",style:{color:C},children:[e.jsx(ya,{className:"h-3 w-3"})," ",g.agent_phone]}),g.agent_email&&e.jsxs("a",{href:`mailto:${g.agent_email}`,className:"text-sm flex items-center justify-center gap-1 mt-1",style:{color:C},children:[e.jsx(nn,{className:"h-3 w-3"})," ",g.agent_email]})]})]})});if(M){const q=W=>{const V=parseFloat(W.replace(/[^0-9.]/g,""));return isNaN(V)?W: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(pr,{className:"h-8 w-8"})}),e.jsx("button",{onClick:W=>{W.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(Ic,{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:W=>W.stopPropagation()}),e.jsx("button",{onClick:W=>{W.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(Ja,{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":C},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(IT,{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((W,V)=>e.jsx("div",{className:"cursor-pointer group relative",onClick:()=>{c(V),u(!0)},children:e.jsx("img",{src:W,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((W,V)=>e.jsxs("div",{className:"cursor-pointer group relative",onClick:()=>{c(V+1),u(!0)},children:[e.jsx("img",{src:W,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(IT,{className:"h-4 w-4"})," View all ",I.length," photos"]})]}),I.length===0&&e.jsx("div",{className:"relative py-16 px-4",style:{background:g.hero_image_url?`linear-gradient(rgba(0,0,0,0.55), rgba(0,0,0,0.55)), url(${g.hero_image_url}) center/cover`:`linear-gradient(135deg, ${C}, ${A})`},children:e.jsxs("div",{className:"max-w-2xl mx-auto text-center text-white",children:[g.logo_url&&e.jsx("img",{src:g.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:g.hero_headline}),g.hero_subtext&&e.jsx("p",{className:"mt-3 text-lg opacity-90",children:g.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:C},children:q(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(ai,{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(tw,{className:"h-5 w-5",style:{color:C}})," ",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(_g,{className:"h-5 w-5",style:{color:C}})," ",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(o5,{className:"h-5 w-5",style:{color:C}})," ",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:C},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!"}),g.agent_name&&e.jsxs("div",{className:"flex items-center gap-3 mb-5 pb-4 border-b",children:[g.agent_photo_url&&e.jsx("img",{src:g.agent_photo_url,alt:g.agent_name,className:"h-12 w-12 rounded-full object-cover"}),e.jsxs("div",{children:[e.jsx("p",{className:"font-semibold text-sm",children:g.agent_name}),e.jsxs("div",{className:"flex flex-col gap-0.5 text-xs text-gray-500",children:[g.agent_phone&&e.jsxs("a",{href:`tel:${g.agent_phone}`,className:"flex items-center gap-1 hover:underline",children:[e.jsx(ya,{className:"h-3 w-3"})," ",g.agent_phone]}),g.agent_email&&e.jsxs("a",{href:`mailto:${g.agent_email}`,className:"flex items-center gap-1 hover:underline",children:[e.jsx(nn,{className:"h-3 w-3"})," ",g.agent_email]})]})]})]}),e.jsxs("form",{onSubmit:N,className:"space-y-3",children:[b.map(W=>e.jsxs("div",{children:[e.jsxs(se,{className:"text-xs font-medium",children:[W.label,W.is_required&&e.jsx("span",{className:"text-red-500 ml-1",children:"*"})]}),PDe(W,i,l)]},W.id)),e.jsx($,{type:"submit",className:"w-full text-white",style:{backgroundColor:C},disabled:v.isPending,children:v.isPending?"Submitting...":"Submit"}),v.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 g.theme_style!=="classic"&&!P?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:q=>m(q.target.value),style:{position:"absolute",left:"-10000px",top:"auto",width:"1px",height:"1px",overflow:"hidden"}}),e.jsx(_7n,{page:g,fields:b,answers:i,setAnswers:l,onSubmit:N,isSubmitting:v.isPending,renderField:PDe}),g.page_type==="event_registration"&&((B=g.settings)==null?void 0:B.event_starts_at)&&e.jsx(S7n,{startsAt:g.settings.event_starts_at,locationName:g.settings.event_location_name,address:g.settings.event_address,title:g.hero_headline||g.title,accent:g.accent_color||g.primary_color||"#406E71"}),v.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:g.hero_image_url?`linear-gradient(rgba(0,0,0,0.55), rgba(0,0,0,0.55)), url(${g.hero_image_url}) center/cover`:`linear-gradient(135deg, ${C}, ${A})`},children:e.jsxs("div",{className:"max-w-2xl mx-auto text-center text-white",children:[g.logo_url&&e.jsx("img",{src:g.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:g.hero_headline}),g.hero_subtext&&e.jsx("p",{className:"mt-3 text-lg opacity-90",children:g.hero_subtext}),P&&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(di,{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:[P&&e.jsx("p",{className:"text-sm text-gray-500 mb-4 text-center",children:"Fill out the form below to get your free download!"}),g.agent_name&&e.jsxs("div",{className:"flex items-center gap-3 mb-6 pb-4 border-b",children:[g.agent_photo_url&&e.jsx("img",{src:g.agent_photo_url,alt:g.agent_name,className:"h-12 w-12 rounded-full object-cover"}),e.jsxs("div",{children:[e.jsx("p",{className:"font-semibold",children:g.agent_name}),e.jsxs("div",{className:"flex items-center gap-3 text-sm text-gray-500",children:[g.agent_phone&&e.jsxs("a",{href:`tel:${g.agent_phone}`,className:"flex items-center gap-1 hover:underline",children:[e.jsx(ya,{className:"h-3 w-3"})," ",g.agent_phone]}),g.agent_email&&e.jsxs("a",{href:`mailto:${g.agent_email}`,className:"flex items-center gap-1 hover:underline",children:[e.jsx(nn,{className:"h-3 w-3"})," ",g.agent_email]})]})]})]}),e.jsxs("form",{onSubmit:N,className:"space-y-4",children:[b.map(q=>e.jsxs("div",{children:[e.jsxs(se,{className:"text-sm font-medium",children:[q.label,q.is_required&&e.jsx("span",{className:"text-red-500 ml-1",children:"*"})]}),PDe(q,i,l)]},q.id)),e.jsx($,{type:"submit",className:"w-full text-white",style:{backgroundColor:C},disabled:v.isPending,children:v.isPending?"Submitting...":P?"Get My Free Download":"Submit"}),v.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 PDe(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(be,{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(Is,{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(vs,{value:String(a),onValueChange:l=>n(o=>({...o,[s.label]:l})),children:[e.jsx(gs,{className:"mt-1",children:e.jsx(bs,{placeholder:"Select..."})}),e.jsx(ys,{children:i.map(l=>e.jsx(Ye,{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(ui,{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(Tn,{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(be,{value:String(a),onChange:l=>n(o=>({...o,[s.label]:l.target.value})),className:"mt-1"})}}function A7n(){const t=Wd().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(mHt,{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 E7n=[{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}],LQn={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"},PQn={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"},p1t={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 IQn(s){return p1t[s]||p1t.basic}function T7n(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}):E7n,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 M7n=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 L7n(s){const t=s.toLowerCase().replace(/:\d+$/,"");return!!(M7n.has(t)||t.endsWith(".lovable.app")||t.endsWith(".lovableproject.com")||t.endsWith(".lovable.dev"))}function P7n(){const s=new URLSearchParams(window.location.search).get("previewSlug");if(s)return s;const n=window.location.hostname.match(/^([^.]+)\.thelocalmove\.com$/i);return n?n[1]:null}function I7n(){const s=P7n(),t=window.location.hostname,n=s?null:z2t(t),r=!s&&!L7n(t)&&t.includes(".")&&!F2t(t),a=s||n||(r?t:null),{data:i,isLoading:l,error:o}=ht({queryKey:["lead-site",a,r],queryFn:async()=>{var b;if(!a)return null;const d=U.from("lead_sites").select("*").eq("is_active",!0);let u;if(s)u=await d.eq("subdomain_slug",s).maybeSingle();else if(n)u=await d.ilike("custom_domain",n).maybeSingle();else if(r)u=await d.ilike("custom_domain",t).maybeSingle();else return null;const{data:h,error:m}=u;if(m)throw m;if(!h)return null;const{data:p}=await U.from("profiles").select("id, name, avatar_url, email, phone, title, bio, areas_served, years_experience, instagram_url, facebook_url, linkedin_url").eq("id",h.agent_id).single();let x=null;if(h.show_team_logo)if(h.team_logo_url)x=h.team_logo_url;else{const{data:v}=await U.from("team_members").select("team_id, teams(avatar_url, name)").eq("user_id",h.agent_id).limit(1).maybeSingle();v&&((b=v.teams)!=null&&b.avatar_url)&&(x=v.teams.avatar_url)}const g={id:h.id,agentId:h.agent_id,subdomainSlug:h.subdomain_slug,customDomain:h.custom_domain||null,mlsProviderId:h.mls_provider_id,siteTitle:h.site_title,siteTagline:h.site_tagline,leadRegistrationMode:h.lead_registration_mode||"disabled",registrationTriggerCount:h.registration_trigger_count??1,themeConfig:h.theme_config||{},themeTier:h.theme_tier||"basic",planTier:h.plan_tier||"paid",brandColor:h.brand_color||void 0,accentColor:h.accent_color||void 0,mlsServiceCities:Array.isArray(h.mls_service_cities)?h.mls_service_cities:[],isActive:h.is_active,brokerageLegalName:h.brokerage_legal_name||null,brokerageLicenseNumber:h.brokerage_license_number||null,agentLicenseNumber:h.agent_license_number||null,licenseState:h.license_state||null,mlsDisclaimerText:h.mls_disclaimer_text||null,mlsLogoUrl:h.mls_logo_url||null,equalHousingEnabled:h.equal_housing_enabled??!0,faviconUrl:h.favicon_url||null,ogImageUrl:h.og_image_url||null,showTeamLogo:h.show_team_logo??!1,teamLogoUrl:x,noMlsMode:h.no_mls_mode===!0,bookingUrl:h.booking_url||null,pageSubtitles:h.page_subtitles||{},agent:p?{id:p.id,full_name:p.name||"",avatar_url:p.avatar_url,email:p.email,phone:p.phone,title:p.title,bio:p.bio,areas_served:p.areas_served||null,years_experience:p.years_experience??null,instagram_url:p.instagram_url||null,facebook_url:p.facebook_url||null,linkedin_url:p.linkedin_url||null}:void 0,testimonials:Array.isArray(h.testimonials)?h.testimonials.filter(v=>v&&typeof v=="object"&&v.text).map(v=>({name:String(v.name||"Client"),text:String(v.text),rating:typeof v.rating=="number"?v.rating:5,location:v.location?String(v.location):void 0})):[],seoMetaTitle:h.seo_meta_title||null,seoMetaDescription:h.seo_meta_description||null},y=T7n(h);return{siteConfig:g,themeConfig:y}},enabled:!!a,staleTime:5*60*1e3,gcTime:30*60*1e3,refetchOnWindowFocus:!1}),c=n||(r?t:null);return{siteConfig:(i==null?void 0:i.siteConfig)??null,themeConfig:(i==null?void 0:i.themeConfig)??null,isLoading:l,error:o,slug:s??(i==null?void 0:i.siteConfig.subdomainSlug)??null,customDomain:c}}async function D7n(s,t){try{await U.functions.invoke("lead-site-notify",{body:{lead:t,lead_site_id:s}})}catch(n){console.warn("Lead notification failed:",n)}}const pHt=j.createContext(null);function LTe(){const s=j.useContext(pHt);if(!s)throw new Error("useLeadSiteAuth must be used within LeadSiteAuthProvider");return s}function R7n({siteConfig:s,children:t}){const[n,r]=j.useState(null),[a,i]=j.useState(null),[l,o]=j.useState(!0);j.useEffect(()=>{const{data:{subscription:h}}=U.auth.onAuthStateChange(async(m,p)=>{const x=(p==null?void 0:p.user)??null;if(r(x),x){const{data:g}=await U.from("lead_site_consumer_profiles").select("id, name, phone").eq("user_id",x.id).eq("lead_site_id",s.id).maybeSingle();g&&i({...g,email:x.email||""})}else i(null);o(!1)});return U.auth.getSession().then(({data:{session:m}})=>{r((m==null?void 0:m.user)??null),m!=null&&m.user?U.from("lead_site_consumer_profiles").select("id, name, phone").eq("user_id",m.user.id).eq("lead_site_id",s.id).maybeSingle().then(({data:p})=>{p&&i({...p,email:m.user.email||""}),o(!1)}):o(!1)}),()=>h.unsubscribe()},[s.id]);const c=j.useCallback(async h=>{const m=h.email.toLowerCase().trim(),p=h.phone.replace(/\D/g,""),{data:x,error:g}=await U.auth.signUp({email:m,password:p,options:{data:{full_name:h.name,consumer_site_id:s.id},emailRedirectTo:window.location.origin}});if(g){if(g.message.includes("already registered")){await d(m,p);return}throw g}if(x.user){const{error:y}=await U.from("lead_site_consumer_profiles").insert({user_id:x.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:b}=await U.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}});b&&console.error("Lead insert error (CRM sync may not trigger):",b),D7n(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:x}=await U.auth.signInWithPassword({email:h.toLowerCase().trim(),password:p});if(x)throw x},[]),u=j.useCallback(async()=>{await U.auth.signOut(),r(null),i(null)},[]);return e.jsx(pHt.Provider,{value:{user:n,profile:a,isLoading:l,signUp:c,signIn:d,signOut:u},children:t})}const O7n=new Set(["7605cc2e-ce21-4f4f-8bb1-4c0f217b1109"]),F7n=new Set(["tomlois"]);function yXe(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||O7n.has(s.id||"")||F7n.has((s.subdomainSlug||"").toLowerCase())||!s.mlsProviderId:!1}function DQn(s){return`Contact ${s.split(" ")[0]||"Me"}`}const TV="#c9a96e",z7n="Schedule a Free Consultation",B7n={sm:"px-5 py-2.5 text-[11px]",md:"px-7 py-3.5 text-xs",lg:"px-9 py-4 text-xs"};function J3({bookingUrl:s,label:t=z7n,className:n="",variant:r="solid",color:a=TV,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 ${B7n[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(gy,{className:"h-4 w-4 flex-shrink-0"}),e.jsx("span",{children:t})]})}function RQn({bookingUrl:s,agentName:t,accentColor:n=TV,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:Hr,title:r.point1Title||"30 Minutes",text:r.point1Text||"A focused conversation about your goals, timeline, and options."},{icon:FK,title:r.point2Title||"A Personal Call",text:r.point2Text||`${t.split(" ")[0]} calls you at the time you choose — no phone tag.`},{icon:Fr,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(jr.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(J3,{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 OQn({bookingUrl:s,accentColor:t=TV,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(J3,{bookingUrl:s,label:"Schedule Now",color:t,size:"sm",className:"flex-shrink-0",source:l})]}):null}function $7n({bookingUrl:s,accentColor:t=TV}){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(gy,{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(pr,{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(J3,{bookingUrl:s,label:"Schedule a Free Consultation",size:"sm",color:t,source:"sticky"})})]})}function U7n({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(gy,{className:"h-8 w-8 mx-auto mb-6",style:{color:TV}}),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(J3,{bookingUrl:s,label:"Open Booking Calendar",size:"lg",source:"schedule_page"})})]})})}function vXe({open:s,mode:t,siteConfig:n,onComplete:r,onSkip:a,theme:i="default",accentColor:l}){var W;const{signUp:o,signIn:c}=LTe(),[d,u]=j.useState(!1),[h,m]=j.useState(""),[p,x]=j.useState(""),[g,y]=j.useState(""),[b,v]=j.useState(!1),[N,C]=j.useState(""),A=t==="required",T=i==="luxury",P=l||(T?"#c9a96e":"#2563eb"),M=((W=n.agent)==null?void 0:W.full_name)||"the agent",I={borderColor:`${P}66`,"--tw-ring-color":`${P}66`},D=async V=>{var Q;if(V.preventDefault(),C(""),!p.trim()||!g.trim()){C("Email and phone number are required.");return}if(!d&&!h.trim()){C("Name is required.");return}if(g.replace(/\D/g,"").length<7){C("Please enter a valid phone number.");return}v(!0);try{d?await c(p,g):await o({name:h,email:p,phone:g}),r()}catch(J){(Q=J==null?void 0:J.message)!=null&&Q.includes("Invalid login")?C("Invalid email or phone number. Please try again."):C((J==null?void 0:J.message)||"Something went wrong. Please try again.")}finally{v(!1)}},B=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",q=T?I:void 0;return e.jsx(Os,{open:s,onOpenChange:A?void 0:V=>{V||a()},children:e.jsxs(Rs,{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(Us,{children:[e.jsx(zs,{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(Sr,{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:D,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:B,style:q}),e.jsx("input",{type:"email",required:!0,placeholder:"Email address",value:p,onChange:V=>x(V.target.value),className:B,style:q}),e.jsxs("div",{children:[e.jsx("input",{type:"tel",required:!0,placeholder:"Phone number",value:g,onChange:V=>y(V.target.value),className:B,style:q}),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:b,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:P}:void 0,children:b?d?"Signing in...":"Creating account...":d?"Sign In":"Create Account"}),e.jsx("button",{type:"button",onClick:()=>{u(!d),C("")},className:"w-full text-center text-sm hover:opacity-80 transition-opacity",style:{color:P},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 bXe({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,C)=>N+(C.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),x={"@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[C,A]=N.split(/,\s*/);return{"@type":"City",name:C,...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}}}))}},g={"@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"}},b=[{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"}],v={"@context":"https://schema.org","@type":"ItemList","@id":`${r}/#nav`,name:"Main Navigation",itemListElement:b.map((N,C)=>({"@type":"SiteNavigationElement",position:C+1,name:N.name,description:N.description,url:`${r}${N.path}`}))};return e.jsxs(Ul,{children:[e.jsx("script",{type:"application/ld+json",children:JSON.stringify(x)}),e.jsx("script",{type:"application/ld+json",children:JSON.stringify(g)}),e.jsx("script",{type:"application/ld+json",children:JSON.stringify(y)}),e.jsx("script",{type:"application/ld+json",children:JSON.stringify(v)})]})}function FQn({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(Ul,{children:e.jsx("script",{type:"application/ld+json",children:JSON.stringify(r)})})}function zQn({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(Ul,{children:e.jsx("script",{type:"application/ld+json",children:JSON.stringify(r)})})}function q7n({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(Ul,{children:e.jsx("script",{type:"application/ld+json",children:JSON.stringify(t)})})}function BQn({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(Ul,{children:e.jsx("script",{type:"application/ld+json",children:JSON.stringify(c)})})}function $Qn({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(Ul,{children:e.jsx("script",{type:"application/ld+json",children:JSON.stringify(c)})})}function _Xe({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(x=>x.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(q7n,{faqs:m})}const f1t="ls_visitor_geo",V7n=1e3*60*60,IDe="lu_lc_attrib_v1",H7n=1e3*60*60*24*90;function G7n(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 W7n(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 K7n(){try{const s=localStorage.getItem(f1t);if(s){const t=JSON.parse(s);if(Date.now()-t.ts{i.current||(i.current=!0,K7n().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=G7n(l),c=W7n(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(IDe,JSON.stringify({contact_id:p,ts:Date.now()}))}catch{}return p}const x=m.get("lc");if(x&&/^[0-9a-f-]{36}$/i.test(x)){const{data:g}=await U.from("listing_email_recipients").select("contact_id").eq("id",x).maybeSingle(),y=g==null?void 0:g.contact_id;if(y){try{localStorage.setItem(IDe,JSON.stringify({contact_id:y,ts:Date.now()}))}catch{}return y}}try{const g=localStorage.getItem(IDe);if(g){const y=JSON.parse(g);if(y!=null&&y.contact_id&&Date.now()-(y.ts||0){U.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 Y7n=3e4;function jXe(s,t){const n=Wd(),r=j.useRef(null),a=j.useRef(null),i=j.useRef(0),l=n.pathname,o=Z7n(l),c=X7n(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 U.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&&U.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,Y7n),()=>{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&&U.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 Z7n(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 X7n(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 Mi=Number.isFinite||function(s){return typeof s=="number"&&isFinite(s)},Q7n=Number.isSafeInteger||function(s){return typeof s=="number"&&Math.abs(s)<=J7n},J7n=Number.MAX_SAFE_INTEGER||9007199254740991;let mo=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}({}),fr=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}({}),Dt=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 $c={MANIFEST:"manifest",LEVEL:"level",AUDIO_TRACK:"audioTrack",SUBTITLE_TRACK:"subtitleTrack"},Gi={MAIN:"main",AUDIO:"audio",SUBTITLE:"subtitle"};class W7{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 e9n{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 W7(t),this.fast_=new W7(n),this.defaultTTFB_=a,this.ttfb_=new W7(t)}update(t,n){const{slow_:r,fast_:a,ttfb_:i}=this;r.halfLife!==t&&(this.slow_=new W7(t,r.getEstimate(),r.getTotalWeight())),a.halfLife!==n&&(this.fast_=new W7(n,a.getEstimate(),a.getTotalWeight())),i.halfLife!==t&&(this.ttfb_=new W7(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 t9n(s,t,n){return(t=n9n(t))in s?Object.defineProperty(s,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):s[t]=n,s}function dh(){return dh=Object.assign?Object.assign.bind():function(s){for(var t=1;t`):WA}function g1t(s,t,n){return t[s]?t[s].bind(t):a9n(s,n)}const bUe=vUe();function i9n(s,t,n){const r=vUe();if(typeof console=="object"&&s===!0||typeof s=="object"){const a=["debug","log","info","warn","error"];a.forEach(i=>{r[i]=g1t(i,s,n)});try{r.log(`Debug logs enabled for "${t}" in hls.js version 1.6.16`)}catch{return vUe()}a.forEach(i=>{bUe[i]=g1t(i,s)})}else dh(bUe,r);return r}const Yu=bUe;function f6(s=!0){return typeof self>"u"?void 0:(s||!self.MediaSource)&&self.ManagedMediaSource||self.MediaSource||self.WebKitMediaSource}function o9n(s){return typeof self<"u"&&s===self.ManagedMediaSource}function fHt(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 uw(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 ly(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(!Mi(t)){this._programDateTime=this.rawProgramDateTime=null;return}this._programDateTime=t}get ref(){return Jf(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 d9n extends gHt{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 yHt(s,t){const n=Object.getPrototypeOf(s);if(n){const r=Object.getOwnPropertyDescriptor(n,t);return r||yHt(n,t)}}function u9n(s,t){const n=yHt(s,t);n&&(n.enumerable=!0,Object.defineProperty(s,t,n))}const v1t=Math.pow(2,32)-1,h9n=[].push,vHt={video:1,audio:2,id3:3,text:4};function lg(s){return String.fromCharCode.apply(null,s)}function bHt(s,t){const n=s[t]<<8|s[t+1];return n<0?65536+n:n}function Tl(s,t){const n=_Ht(s,t);return n<0?4294967296+n:n}function b1t(s,t){let n=Tl(s,t);return n*=Math.pow(2,32),n+=Tl(s,t+4),n}function _Ht(s,t){return s[t]<<24|s[t+1]<<16|s[t+2]<<8|s[t+3]}function m9n(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 Lc(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=Lc(s.subarray(a+8,o),t.slice(1));c.length&&h9n.apply(n,c)}a=o}return n}function p9n(s){const t=[],n=s[0];let r=8;const a=Tl(s,r);r+=4;let i=0,l=0;n===0?(i=Tl(s,r),l=Tl(s,r+4),r+=8):(i=b1t(s,r),l=b1t(s,r+8),r+=16),r+=2;let o=s.length+l;const c=bHt(s,r);r+=2;for(let d=0;d>>31===1)return Yu.warn("SIDX has hierarchical references (not supported)"),null;const x=Tl(s,u);u+=4,t.push({referenceSize:m,subsegmentDuration:x,info:{duration:x/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 wHt(s){const t=[],n=Lc(s,["moov","trak"]);for(let a=0;a{const i=Tl(a,4),l=t[i];l&&(l.default={duration:Tl(a,12),flags:Tl(a,20)})}),t}function f9n(s){const t=s.subarray(8),n=t.subarray(86),r=lg(t.subarray(4,8));let a=r,i;const l=r==="enca"||r==="encv";if(l){const d=Lc(t,[r])[0].subarray(r==="enca"?28:78);Lc(d,["sinf"]).forEach(h=>{const m=Lc(h,["schm"])[0];if(m){const p=lg(m.subarray(4,8));if(p==="cbcs"||p==="cenc"){const x=Lc(h,["frma"])[0];x&&(a=lg(x))}}})}const o=a;switch(a){case"avc1":case"avc2":case"avc3":case"avc4":{const c=Lc(n,["avcC"])[0];c&&c.length>3&&(a+="."+Nae(c[1])+Nae(c[2])+Nae(c[3]),i=jae(o==="avc1"?"dva1":"dvav",n));break}case"mp4a":{const c=Lc(t,[r])[0],d=Lc(c.subarray(28),["esds"])[0];if(d&&d.length>7){let u=4;if(d[u++]!==3)break;u=ODe(d,u),u+=2;const h=d[u++];if(h&128&&(u+=2),h&64&&(u+=d[u++]),d[u++]!==4)break;u=ODe(d,u);const m=d[u++];if(m===64)a+="."+Nae(m);else break;if(u+=12,d[u++]!==5)break;u=ODe(d,u);const p=d[u++];let x=(p&248)>>3;x===31&&(x+=1+((p&7)<<3)+((d[u]&224)>>5)),a+="."+x}break}case"hvc1":case"hev1":{const c=Lc(n,["hvcC"])[0];if(c&&c.length>12){const d=c[1],u=["","A","B","C"][d>>6],h=d&31,m=Tl(c,2),p=(d&32)>>5?"H":"L",x=c[12],g=c.subarray(6,12);a+="."+u+h,a+="."+x9n(m).toString(16).toUpperCase(),a+="."+p+x;let y="";for(let b=g.length;b--;){const v=g[b];(v||y)&&(y="."+v.toString(16).toUpperCase()+y)}a+=y}i=jae(o=="hev1"?"dvhe":"dvh1",n);break}case"dvh1":case"dvhe":case"dvav":case"dva1":case"dav1":{a=jae(a,n)||a;break}case"vp09":{const c=Lc(n,["vpcC"])[0];if(c&&c.length>6){const d=c[4],u=c[5],h=c[6]>>4&15;a+="."+iS(d)+"."+iS(u)+"."+iS(h)}break}case"av01":{const c=Lc(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,x=d===2&&m?p?12:10:m?10:8,g=(c[2]&16)>>4,y=(c[2]&8)>>3,b=(c[2]&4)>>2,v=c[2]&3;a+="."+d+"."+iS(u)+h+"."+iS(x)+"."+g+"."+y+b+v+"."+iS(1)+"."+iS(1)+"."+iS(1)+"."+0,i=jae("dav1",n)}break}}return{codec:a,encrypted:l,supplemental:i}}function jae(s,t){const n=Lc(t,["dvvC"]),r=n.length?n[0]:Lc(t,["dvcC"])[0];if(r){const a=r[2]>>1&127,i=r[2]<<5&32|r[3]>>3&31;return s+"."+iS(a)+"."+iS(i)}}function x9n(s){let t=0;for(let n=0;n<32;n++)t|=(s>>n&1)<<31-n;return t>>>0}function ODe(s,t){const n=t+5;for(;s[t++]&128&&t{const i=r.subarray(8,24);i.some(l=>l!==0)||(Yu.log(`[eme] Patching keyId in 'enc${a?"a":"v"}>sinf>>tenc' box: ${ly(i)} -> ${ly(n)}`),r.set(n,8))})}function y9n(s){const t=[];return jHt(s,n=>t.push(n.subarray(8,24))),t}function jHt(s,t){Lc(s,["moov","trak"]).forEach(r=>{const a=Lc(r,["mdia","minf","stbl","stsd"])[0];if(!a)return;const i=a.subarray(8);let l=Lc(i,["enca"]);const o=l.length>0;o||(l=Lc(i,["encv"])),l.forEach(c=>{const d=o?c.subarray(28):c.subarray(78);Lc(d,["sinf"]).forEach(h=>{const m=NHt(h);m&&t(m,o)})})})}function NHt(s){const t=Lc(s,["schm"])[0];if(t){const n=lg(t.subarray(4,8));if(n==="cbcs"||n==="cenc"){const r=Lc(s,["schi","tenc"])[0];if(r)return r}}}function v9n(s,t,n){const r={},a=Lc(s,["moof","traf"]);for(let i=0;ir[i].duration)){let i=1/0,l=0;const o=Lc(s,["sidx"]);for(let c=0;ch+m.info.duration||0,0);l=Math.max(l,u+d.earliestPresentationTime/d.timescale)}}l&&Mi(l)&&Object.keys(r).forEach(c=>{r[c].duration||(r[c].duration=l*r[c].timescale-r[c].start)})}return r}function b9n(s){const t={valid:null,remainder:null},n=Lc(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 d2(s,t){const n=new Uint8Array(s.length+t.length);return n.set(s),n.set(t,s.length),n}function _1t(s,t){const n=[],r=t.samples,a=t.timescale,i=t.id;let l=!1;return Lc(r,["moof"]).map(c=>{const d=c.byteOffset-8;Lc(c,["traf"]).map(h=>{const m=Lc(h,["tfdt"]).map(p=>{const x=p[0];let g=Tl(p,4);return x===1&&(g*=Math.pow(2,32),g+=Tl(p,8)),g/a})[0];return m!==void 0&&(s=m),Lc(h,["tfhd"]).map(p=>{const x=Tl(p,4),g=Tl(p,0)&16777215,y=(g&1)!==0,b=(g&2)!==0,v=(g&8)!==0;let N=0;const C=(g&16)!==0;let A=0;const T=(g&32)!==0;let P=8;x===i&&(y&&(P+=8),b&&(P+=4),v&&(N=Tl(p,P),P+=4),C&&(A=Tl(p,P),P+=4),T&&(P+=4),t.type==="video"&&(l=PTe(t.codec)),Lc(h,["trun"]).map(M=>{const I=M[0],D=Tl(M,0)&16777215,B=(D&1)!==0;let q=0;const W=(D&4)!==0,V=(D&256)!==0;let K=0;const Q=(D&512)!==0;let J=0;const ce=(D&1024)!==0,ue=(D&2048)!==0;let ne=0;const ee=Tl(M,4);let le=8;B&&(q=Tl(M,le),le+=4),W&&(le+=4);let he=q+d;for(let ve=0;ve>1&63;return n===39||n===40}else return(t&31)===6}function SXe(s,t,n,r){const a=kHt(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){Yu.error(`Malformed SEI payload. ${o} is too small, only ${d} bytes left to parse.`);break}if(l===4){if(a[u++]===181){const m=bHt(a,u);if(u+=2,m===49){const p=Tl(a,u);if(u+=4,p===1195456820){const x=a[u++];if(x===3){const g=a[u++],y=31&g,b=64&g,v=b?2+y*3:0,N=new Uint8Array(v);if(b){N[0]=g;for(let C=1;C16){const h=[];for(let x=0;x<16;x++){const g=a[u++].toString(16);h.push(g.length==1?"0"+g:g),(x===3||x===5||x===7||x===9)&&h.push("-")}const m=o-16,p=new Uint8Array(m);for(let x=0;x>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),j9n([112,115,115,104],new Uint8Array([r,0,0,0]),s,i,a,l,n)}function k9n(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=ly(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),sq={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 CXe(s,t){const n=sq[t];return!!n&&!!n[s.slice(0,4)]}function mQ(s,t,n=!0){return!s.split(",").some(r=>!AXe(r,t,n))}function AXe(s,t,n=!0){var r;const a=f6(n);return(r=a==null?void 0:a.isTypeSupported(pQ(s,t)))!=null?r:!1}function pQ(s,t){return`${t}/mp4;codecs=${s}`}function w1t(s){if(s){const t=s.substring(0,4);return sq.video[t]}return 2}function z4e(s){const t=SHt();return s.split(",").reduce((n,r)=>{const i=t&&PTe(r)?9:sq.video[r];return i?(i*2+n)/(n?3:2):(sq.audio[r]+n)/(n?2:1)},0)}const FDe={};function C9n(s,t=!0){if(FDe[s])return FDe[s];const n={flac:["flac","fLaC","FLAC"],opus:["opus","Opus"],"mp4a.40.34":["mp3"]}[s];for(let a=0;aC9n(n.toLowerCase(),t))}function E9n(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)&&(j1t(s,"audio")||j1t(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 j1t(s,t){return CXe(s,t)&&AXe(s,t)}function T9n(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 M9n(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 N1t(s){const t=f6(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 _Ue(s){return s.replace(/^.+codecs=["']?([^"']+).*$/,"$1")}const L9n={supported:!0,powerEfficient:!0,smooth:!0},P9n={supported:!1,smooth:!1,powerEfficient:!1},CHt={supported:!0,configurations:[],decodingInfoResults:[L9n]};function AHt(s,t){return{supported:!1,configurations:t,decodingInfoResults:[P9n],error:s}}function I9n(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 x=t.groups[p];if(!x)throw new Error(`Audio track group ${p} not found`);Object.keys(x.channels).forEach(g=>{m[g]=(m[g]||0)+x.channels[g]})}return m},{2:0})}catch{return!0}return l!==void 0&&(l.split(",").some(m=>PTe(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&&Mi(u)&&Object.keys(h).some(m=>parseInt(m)>u)}function EHt(s,t,n,r={}){const a=s.videoCodec;if(!a&&!s.audioCodec||!n)return Promise.resolve(CHt);const i=[],l=D9n(s),o=l.length,c=R9n(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=>PTe(h))&&SHt())return Promise.resolve(AHt(new Error(`Overriding Windows Firefox HEVC MediaCapabilities result based on user-agent string: (${u})`),i))}return Promise.all(i.map(u=>{const h=F9n(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 D9n(s){var t;const n=(t=s.videoCodec)==null?void 0:t.split(","),r=THt(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:pQ(M9n(c),"video"),width:a,height:i,bitrate:r,framerate:l};return o!=="sdr"&&(d.transferFunction=o),d}):[]}function R9n(s,t,n){var r;const a=(r=s.audioCodec)==null?void 0:r.split(","),i=THt(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 x={contentType:pQ(p,"audio"),bitrate:n?O9n(p,i):i};m&&(x.channels=""+m),u.push(x)})}return u},l):l},[]):[]}function O9n(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 THt(s){return Math.ceil(Math.max(s.bitrate*.9,s.averageBitrate)/1e3)*1e3||1}function F9n(s){let t="";const{audio:n,video:r}=s;if(r){const a=_Ue(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=_Ue(n.contentType);t+=`${r?"_":""}${a}_c${n.channels}`}return t}const wUe=["NONE","TYPE-0","TYPE-1",null];function z9n(s){return wUe.indexOf(s)>-1}const $4e=["SDR","PQ","HLG"];function B9n(s){return!!s&&$4e.indexOf(s)>-1}var DNe={No:"",Yes:"YES",v2:"v2"};function k1t(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 C1t(this._audioGroups,t)}hasSubtitleGroup(t){return C1t(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 C1t(s,t){return!t||!s?!1:s.indexOf(t)!==-1}function $9n(){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 U9n(s,t){let n=!1,r=[];if(s&&(n=s!=="SDR",r=[s]),t){r=t.allowedVideoRanges||$4e.slice(0);const a=r.join("")!=="SDR"&&!t.videoCodec;n=t.preferHDR!==void 0?t.preferHDR:a&&$9n(),n||(r=["SDR"])}return{preferHDR:n,allowedVideoRanges:r}}const q9n=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}},Lh=(s,t)=>JSON.stringify(s,q9n(t));function V9n(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,x=1/0,g=1/0,y=0,b=[];const{preferHDR:v,allowedVideoRanges:N}=U9n(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),x=Math.min(x,I.minBitrate),N.filter(B=>I.videoRanges[B]>0).length>0&&(h=!0)}m=Mi(m)?m:0,p=Mi(p)?p:0;const C=Math.max(1080,m),A=Math.max(30,p);x=Mi(x)?x:n,n=Math.max(x,n),h||(t=void 0);const T=i.length>1;return{codecSet:i.reduce((M,I)=>{const D=s[I];if(I===M)return M;if(b=h?N.filter(B=>D.videoRanges[B]>0):[],T){if(D.minBitrate>n)return Vk(I,`min bitrate of ${D.minBitrate} > current estimate of ${n}`),M;if(!D.hasDefaultAudio)return Vk(I,"no renditions with default or auto-select sound found"),M;if(o&&I.indexOf(o.substring(0,4))%5!==0)return Vk(I,`audio codec preference "${o}" not found`),M;if(l&&!d){if(!D.channels[l])return Vk(I,`no renditions with ${l} channel sound found (channels options: ${Object.keys(D.channels)})`),M}else if((!o||d)&&u&&D.channels[2]===0)return Vk(I,"no renditions with stereo sound found"),M;if(D.minHeight>C)return Vk(I,`min resolution of ${D.minHeight} > maximum of ${C}`),M;if(D.minFramerate>A)return Vk(I,`min framerate of ${D.minFramerate} > maximum of ${A}`),M;if(!b.some(B=>D.videoRanges[B]>0))return Vk(I,`no variants with VIDEO-RANGE of ${Lh(b)} found`),M;if(c&&I.indexOf(c.substring(0,4))%5!==0)return Vk(I,`video codec preference "${c}" not found`),M;if(D.maxScore=z4e(M)||D.fragmentError>s[M].fragmentError)?M:(g=D.minIndex,y=D.maxScore,I)},void 0),videoRanges:b,preferHDR:v,minFramerate:p,minBitrate:x,minIndex:g}}function Vk(s,t){Yu.log(`[abr] start candidates with "${s}" ignored because ${t}`)}function MHt(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 H9n(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 A1t(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 KS(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 x8(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 K9n(s,t,n,r,a){const i=t[r],o=t.reduce((m,p,x)=>{const g=p.uri;return(m[g]||(m[g]=[])).push(x),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=E1t(t,r,m=>{if(m.videoRange!==c||m.frameRate!==d||m.codecSet.substring(0,4)!==u)return!1;const p=m.audioGroups,x=n.filter(g=>!p||p.indexOf(g.groupId)!==-1);return KS(s,x,a)>-1});return h>-1?h:E1t(t,r,m=>{const p=m.audioGroups,x=n.filter(g=>!p||p.indexOf(g.groupId)!==-1);return KS(s,x,a)>-1})}function E1t(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,x=a.level,g=this._nextAutoLevel;if(u.aborted||u.loaded&&u.loaded===u.total||x<=p){this.clearTimer(),this._nextAutoLevel=-1;return}if(!o)return;const y=g>-1&&g!==x,b=!!n||y;if(!b&&(c.paused||!c.playbackRate||!c.readyState))return;const v=l.mainForwardBufferInfo;if(!b&&v===null)return;const N=this.bwEstimator.getEstimateTTFB(),C=Math.abs(c.playbackRate);if(m<=Math.max(N,1e3*(h/(C*2))))return;const A=v?v.len/C:0,T=u.loading.first?u.loading.first-u.loading.start:-1,P=u.loaded&&T>-1,M=this.getBwEstimate(),I=l.levels,D=I[x],B=Math.max(u.loaded,Math.round(h*(a.bitrate||D.averageBitrate)/8));let q=P?m-T:m;q<1&&P&&(q=Math.min(m,u.loaded*8/M));const W=P?u.loaded*1e3/q:0,V=N/1e3,K=W?(B-u.loaded)/W:B*8/M+V;if(K<=A)return;const Q=W?W*8:M,J=((r=(n==null?void 0:n.details)||this.hls.latestLevelDetails)==null?void 0:r.live)===!0,ce=this.hls.config.abrBandWidthUpFactor;let ue=Number.POSITIVE_INFINITY,ne;for(ne=x-1;ne>p;ne--){const ve=I[ne].maxBitrate,ge=!I[ne].details||J;if(ue=this.getTimeToLoadFrag(V,Q,h*ve,ge),ue=K||ue>h*10)return;P?this.bwEstimator.sample(m-Math.min(N,T),u.loaded):this.bwEstimator.sampleTTFB(m);const ee=I[ne].maxBitrate;this.getBwEstimate()*ce>ee&&this.resetEstimator(ee);const le=this.findBestLevel(ee,p,ne,0,A,1,1);le>-1&&(ne=le),this.warn(`Fragment ${a.sn}${i?" part "+i.index:""} of level ${x} 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: ${Mi(M)?M|0:"Unknown"} bps New BW estimate: ${this.getBwEstimate()|0} bps Switching to level ${ne} @ ${ee|0} bps`),l.nextLoadLevel=l.nextAutoLevel=ne,this.clearTimer();const he=()=>{if(this.clearTimer(),this.fragCurrent===a&&this.hls.loadLevel===ne&&ne>0){const ve=this.getStarvationDelay();if(this.warn(`Aborting inflight request ${ne>0?"and switching down":""} Fragment duration: ${a.duration.toFixed(3)} s Time to underbuffer: ${ve.toFixed(3)} s`),a.abortRequests(),this.fragCurrent=this.partCurrent=null,ne>p){let ge=this.findBestLevel(this.hls.levels[p].bitrate,p,ne,0,ve,1,1);ge===-1&&(ge=p),this.hls.nextLoadLevel=this.hls.nextAutoLevel=ge,this.resetEstimator(this.hls.levels[ge].bitrate)}}};y||K>ue*2?he():this.timer=self.setInterval(he,ue*1e3),l.trigger(Dt.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 e9n(t.abrEwmaSlowVoD,t.abrEwmaFastVoD,t.abrEwmaDefaultEstimate)}registerListeners(){const{hls:t}=this;t.on(Dt.MANIFEST_LOADING,this.onManifestLoading,this),t.on(Dt.FRAG_LOADING,this.onFragLoading,this),t.on(Dt.FRAG_LOADED,this.onFragLoaded,this),t.on(Dt.FRAG_BUFFERED,this.onFragBuffered,this),t.on(Dt.LEVEL_SWITCHING,this.onLevelSwitching,this),t.on(Dt.LEVEL_LOADED,this.onLevelLoaded,this),t.on(Dt.LEVELS_UPDATED,this.onLevelsUpdated,this),t.on(Dt.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),t.on(Dt.ERROR,this.onError,this)}unregisterListeners(){const{hls:t}=this;t&&(t.off(Dt.MANIFEST_LOADING,this.onManifestLoading,this),t.off(Dt.FRAG_LOADING,this.onFragLoading,this),t.off(Dt.FRAG_LOADED,this.onFragLoaded,this),t.off(Dt.FRAG_BUFFERED,this.onFragBuffered,this),t.off(Dt.LEVEL_SWITCHING,this.onLevelSwitching,this),t.off(Dt.LEVEL_LOADED,this.onLevelLoaded,this),t.off(Dt.LEVELS_UPDATED,this.onLevelsUpdated,this),t.off(Dt.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),t.off(Dt.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 fr.BUFFER_ADD_CODEC_ERROR:case fr.BUFFER_APPEND_ERROR:this.lastLoadedFragLevel=-1,this.firstSelection=-1;break;case fr.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;Mi(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===Gi.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(Dt.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!==Gi.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 x=r.levels[l],g=r.loadLevelObj;return g&&(x==null?void 0:x.bitrate)=n;Q--){var K;const J=x[Q],ce=Q>h;if(!J)continue;if(b.useMediaCapabilities&&!J.supportedResult&&!J.supportedPromise){const ge=navigator.mediaCapabilities;typeof(ge==null?void 0:ge.decodingInfo)=="function"&&I9n(J,D,T,P,t,M)?(J.supportedPromise=EHt(J,D,ge,this.supportedCache),J.supportedPromise.then(fe=>{if(!this.hls)return;J.supportedResult=fe;const je=this.hls.levels,Ee=je.indexOf(J);fe.error?this.warn(`MediaCapabilities decodingInfo error: "${fe.error}" for level ${Ee} ${Lh(fe)}`):fe.supported?fe.decodingInfoResults.some(Me=>Me.smooth===!1||Me.powerEfficient===!1)&&this.log(`MediaCapabilities decodingInfo for level ${Ee} not smooth or powerEfficient: ${Lh(fe)}`):(this.warn(`Unsupported MediaCapabilities decodingInfo result for level ${Ee} ${Lh(fe)}`),Ee>-1&&je.length>1&&(this.log(`Removing unsupported level ${Ee}`),this.hls.removeLevel(Ee),this.hls.loadLevel===-1&&(this.hls.nextLoadLevel=0)))}).catch(fe=>{this.warn(`Error handling MediaCapabilities decodingInfo: ${fe}`)})):J.supportedResult=CHt}if((A&&J.codecSet!==A||T&&J.videoRange!==T||ce&&P>J.frameRate||!ce&&P>0&&Pge.smooth===!1))&&(!C||Q!==B)){V.push(Q);continue}const ue=J.details,ne=(p?ue==null?void 0:ue.partTarget:ue==null?void 0:ue.averagetargetduration)||q;let ee;ce?ee=o*t:ee=l*t;const le=q&&a>=q*2&&i===0?J.averageBitrate:J.maxBitrate,he=this.getTimeToLoadFrag(W,ee,le*ne,ue===void 0);if(ee>=le&&(Q===u||J.loadError===0&&J.fragmentError===0)&&(he<=W||!Mi(he)||N&&!this.bitrateTestDelay||he${Q} adjustedbw(${Math.round(ee)})-bitrate=${Math.round(ee-le)} ttfb:${W.toFixed(1)} avgDuration:${ne.toFixed(1)} maxFetchDuration:${d.toFixed(1)} fetchDuration:${he.toFixed(1)} firstSelection:${C} codecSet:${J.codecSet} videoRange:${J.videoRange} hls.loadLevel:${y}`)),C&&(this.firstSelection=Q),Q}}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 LHt={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 Z9n(s,t,n){if(t===null||!Array.isArray(s)||!s.length||!Mi(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)&&T1t(n,r,i)===0||X9n(i,s,Math.min(a,r))))return i;const l=LHt.search(t,T1t.bind(null,n,r));return l&&(l!==s||!i)?l:i}function X9n(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 T1t(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 Q9n(s,t,n){const r=Math.min(t,n.duration+(n.deltaPTS?n.deltaPTS:0))*1e3;return(n.endProgramDateTime||0)-r>s}function PHt(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 LHt.search(r,l=>l.cct?-1:(i=l,l.end<=n?1:l.start>n?-1:0)),i||null}return null}function q4e(s){switch(s.details){case fr.FRAG_LOAD_TIMEOUT:case fr.KEY_LOAD_TIMEOUT:case fr.LEVEL_LOAD_TIMEOUT:case fr.MANIFEST_LOAD_TIMEOUT:return!0}return!1}function IHt(s){return s.details.startsWith("key")}function DHt(s){return IHt(s)&&!!s.frag&&!s.frag.decryptdata}function M1t(s,t){const n=q4e(t);return s.default[`${n?"timeout":"error"}Retry`]}function EXe(s,t){const n=s.backoff==="linear"?1:Math.pow(2,t);return Math.min(n*s.retryDelayMs,s.maxRetryDelayMs)}function L1t(s){return qu(qu({},s),{errorRetry:null,timeoutRetry:null})}function V4e(s,t,n,r){if(!s)return!1;const a=r==null?void 0:r.code,i=t499)}function jUe(s){return s===0&&navigator.onLine===!1}var oy={DoNothing:0,SendEndCallback:1,SendAlternateToPenaltyBox:2,RemoveAlternatePermanently:3,InsertDiscontinuity:4,RetryRequest:5},C_={None:0,MoveAllAlternatesMatchingHost:1,MoveAllAlternatesMatchingHDCP:2,MoveAllAlternatesMatchingKey:4,SwitchToSDR:8};class ezn extends v2{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(Dt.ERROR,this.onError,this),t.on(Dt.MANIFEST_LOADING,this.onManifestLoading,this),t.on(Dt.LEVEL_UPDATED,this.onLevelUpdated,this)}unregisterListeners(){const t=this.hls;t&&(t.off(Dt.ERROR,this.onError,this),t.off(Dt.ERROR,this.onErrorOut,this),t.off(Dt.MANIFEST_LOADING,this.onManifestLoading,this),t.off(Dt.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)===Gi.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 fr.FRAG_LOAD_ERROR:case fr.FRAG_LOAD_TIMEOUT:case fr.KEY_LOAD_ERROR:case fr.KEY_LOAD_TIMEOUT:n.errorAction=this.getFragRetryOrSwitchAction(n);return;case fr.FRAG_PARSING_ERROR:if((r=n.frag)!=null&&r.gap){n.errorAction=wB();return}case fr.FRAG_GAP:case fr.FRAG_DECRYPT_ERROR:{n.errorAction=this.getFragRetryOrSwitchAction(n),n.errorAction.action=oy.SendAlternateToPenaltyBox;return}case fr.LEVEL_EMPTY_ERROR:case fr.LEVEL_PARSING_ERROR:{var l;const c=n.parent===Gi.MAIN?n.level:a.loadLevel;n.details===fr.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 fr.LEVEL_LOAD_ERROR:case fr.LEVEL_LOAD_TIMEOUT:typeof(i==null?void 0:i.level)=="number"&&(n.errorAction=this.getPlaylistRetryOrSwitchAction(n,i.level));return;case fr.AUDIO_TRACK_LOAD_ERROR:case fr.AUDIO_TRACK_LOAD_TIMEOUT:case fr.SUBTITLE_LOAD_ERROR:case fr.SUBTITLE_TRACK_LOAD_TIMEOUT:if(i){const c=a.loadLevelObj;if(c&&(i.type===$c.AUDIO_TRACK&&c.hasAudioGroup(i.groupId)||i.type===$c.SUBTITLE_TRACK&&c.hasSubtitleGroup(i.groupId))){n.errorAction=this.getPlaylistRetryOrSwitchAction(n,a.loadLevel),n.errorAction.action=oy.SendAlternateToPenaltyBox,n.errorAction.flags=C_.MoveAllAlternatesMatchingHost;return}}return;case fr.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:n.errorAction={action:oy.SendAlternateToPenaltyBox,flags:C_.MoveAllAlternatesMatchingHDCP};return;case fr.KEY_SYSTEM_SESSION_UPDATE_FAILED:case fr.KEY_SYSTEM_STATUS_INTERNAL_ERROR:case fr.KEY_SYSTEM_NO_SESSION:n.errorAction={action:oy.SendAlternateToPenaltyBox,flags:C_.MoveAllAlternatesMatchingKey};return;case fr.BUFFER_ADD_CODEC_ERROR:case fr.REMUX_ALLOC_ERROR:case fr.BUFFER_APPEND_ERROR:if(!n.errorAction){var o;n.errorAction=this.getLevelSwitchAction(n,(o=n.level)!=null?o:a.loadLevel)}return;case fr.INTERNAL_EXCEPTION:case fr.BUFFER_APPENDING_ERROR:case fr.BUFFER_FULL_ERROR:case fr.LEVEL_SWITCH_ERROR:case fr.BUFFER_STALLED_ERROR:case fr.BUFFER_SEEK_OVER_HOLE:case fr.BUFFER_NUDGE_ON_STALL:n.errorAction=wB();return}n.type===mo.KEY_SYSTEM_ERROR&&(n.levelRetry=!1,n.errorAction=wB())}getPlaylistRetryOrSwitchAction(t,n){const r=this.hls,a=M1t(r.config.playlistLoadPolicy,t),i=this.playlistError++;if(V4e(a,i,q4e(t),t.response))return{action:oy.RetryRequest,flags:C_.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=M1t(IHt(t)?l:i,t),c=n.levels.reduce((u,h)=>u+h.fragmentError,0);if(a&&(t.details!==fr.FRAG_GAP&&a.fragmentError++,!DHt(t)&&V4e(o,c,q4e(t),t.response)))return{action:oy.RetryRequest,flags:C_.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===fr.BUFFER_APPEND_ERROR&&a.fragmentError++;let u=-1;const{levels:h,loadLevel:m,minAutoLevel:p,maxAutoLevel:x}=r;!r.autoLevelEnabled&&!r.config.preserveManualLevelOnError&&(r.loadLevel=-1);const g=(i=t.frag)==null?void 0:i.type,b=(g===Gi.AUDIO&&d===fr.FRAG_PARSING_ERROR||t.sourceBufferName==="audio"&&(d===fr.BUFFER_ADD_CODEC_ERROR||d===fr.BUFFER_APPEND_ERROR))&&h.some(({audioCodec:T})=>a.audioCodec!==T),N=t.sourceBufferName==="video"&&(d===fr.BUFFER_ADD_CODEC_ERROR||d===fr.BUFFER_APPEND_ERROR)&&h.some(({codecSet:T,audioCodec:P})=>a.codecSet!==T&&a.audioCodec===P),{type:C,groupId:A}=(l=t.context)!=null?l:{};for(let T=h.length;T--;){const P=(T+m)%h.length;if(P!==m&&P>=p&&P<=x&&h[P].loadError===0){var o,c;const M=h[P];if(d===fr.FRAG_GAP&&g===Gi.MAIN&&t.frag){const I=h[P].details;if(I){const D=$O(t.frag,I.fragments,t.frag.start);if(D!=null&&D.gap)continue}}else{if(C===$c.AUDIO_TRACK&&M.hasAudioGroup(A)||C===$c.SUBTITLE_TRACK&&M.hasSubtitleGroup(A))continue;if(g===Gi.AUDIO&&(o=a.audioGroups)!=null&&o.some(I=>M.hasAudioGroup(I))||g===Gi.SUBTITLE&&(c=a.subtitleGroups)!=null&&c.some(I=>M.hasSubtitleGroup(I))||b&&a.audioCodec===M.audioCodec||N&&a.codecSet===M.codecSet||!b&&a.codecSet!==M.codecSet)continue}u=P;break}}if(u>-1&&r.loadLevel!==u)return t.levelRetry=!0,this.playlistError=0,{action:oy.SendAlternateToPenaltyBox,flags:C_.None,nextAutoLevel:u}}return{action:oy.SendAlternateToPenaltyBox,flags:C_.MoveAllAlternatesMatchingHost}}onErrorOut(t,n){var r;switch((r=n.errorAction)==null?void 0:r.action){case oy.DoNothing:break;case oy.SendAlternateToPenaltyBox:this.sendAlternateToPenaltyBox(n),!n.errorAction.resolved&&n.details!==fr.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 C_.None:this.switchLevel(t,i);break;case C_.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=wUe[wUe.indexOf(u)-1],r.resolved=!0,this.warn(`Restricting playback to HDCP-LEVEL of "${n.maxHdcpLevel}" or lower`);break}}case C_.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) ${ly(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=K7(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),kae(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]=P1t(r,a=>a.fragment.sn>=t))}fragBuffered(t,n){const r=K7(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)),x=Math.min(o,a.end(u));x>p&&(i.partial=!0,i.time.push({startPTS:p,endPTS:x}))}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&&kae(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||kae(n))}getState(t){const n=K7(t),r=this.fragments[n];return r?r.buffered?kae(r)?ug.PARTIAL:ug.OK:ug.APPENDING:ug.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=K7(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=K7(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=K7(t);t.clearElementaryStreamInfo();const r=this.activePartLists[t.type];if(r){const a=t.sn;this.activePartLists[t.type]=P1t(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 kae(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 K7(s){return`${s.type}_${s.level}_${s.sn}`}function P1t(s,t){return s.filter(n=>{const r=t(n);return r||n.clearElementaryStreamInfo(),r})}var x6={cbc:0,ctr:1};class szn{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 x6.cbc:return this.subtle.decrypt({name:"AES-CBC",iv:this.aesIV},n,t);case x6.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 nzn(s){const t=s.byteLength,n=t&&new DataView(s.buffer).getUint8(t-1);return n?s.slice(0,t-n):s}class rzn{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 x=0,g=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 b=g^g<<1^g<<2^g<<3^g<<4;b=b>>>8^b&255^99,t[x]=b,n[b]=x;const v=p[x],N=p[v],C=p[N];let A=p[b]*257^b*16843008;a[x]=A<<24|A>>>8,i[x]=A<<16|A>>>16,l[x]=A<<8|A>>>24,o[x]=A,A=C*16843009^N*65537^v*257^x*16843008,d[b]=A<<24|A>>>8,u[b]=A<<16|A>>>16,h[b]=A<<8|A>>>24,m[b]=A,x?(x=v^p[p[p[C^v]]],g^=p[p[g]]):x=g=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!==x6.cbc||n.byteLength!==16)return Yu.warn("SoftwareDecrypt: can only handle AES-128-CBC"),null;this.logOnce("JS AES decrypt"),o&&(t=d2(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 rzn),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 azn(this.subtle,n,a)}return this.fastAesKey.expandKey().then(i=>this.subtle?(this.logOnce("WebCrypto AES decrypt"),new szn(this.subtle,new Uint8Array(r),a).decrypt(t.buffer,i)):Promise.reject(new Error("web crypto not initialized"))).catch(i=>(Yu.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%ozn;return r!==t.length&&(n=t.slice(0,r),this.remainderData=t.slice(r)),n}logOnce(t){this.logEnabled&&(Yu.log(`[decrypter]: ${t}`),this.logEnabled=!1)}}const I1t=Math.pow(2,17);class lzn{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 H4({type:mo.NETWORK_ERROR,details:fr.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(x=>x[0]==="GAP")){c(R1t(t));return}else t.gap=!1;const d=this.loader=i?new i(a):new l(a),u=D1t(t);t.loader=d;const h=L1t(a.fragLoadPolicy.default),m={loadPolicy:h,timeout:h.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:t.sn==="initSegment"?1/0:I1t};t.stats=d.stats;const p={onSuccess:(x,g,y,b)=>{this.resetLoader(t,d);let v=x.data;y.resetIV&&t.decryptdata&&(t.decryptdata.iv=new Uint8Array(v.slice(0,16)),v=v.slice(16)),o({frag:t,part:null,payload:v,networkDetails:b})},onError:(x,g,y,b)=>{this.resetLoader(t,d),c(new H4({type:mo.NETWORK_ERROR,details:fr.FRAG_LOAD_ERROR,fatal:!1,frag:t,response:qu({url:r,data:void 0},x),error:new Error(`HTTP Error ${x.code} ${x.text}`),networkDetails:y,stats:b}))},onAbort:(x,g,y)=>{this.resetLoader(t,d),c(new H4({type:mo.NETWORK_ERROR,details:fr.INTERNAL_ABORTED,fatal:!1,frag:t,error:new Error("Aborted"),networkDetails:y,stats:x}))},onTimeout:(x,g,y)=>{this.resetLoader(t,d),c(new H4({type:mo.NETWORK_ERROR,details:fr.FRAG_LOAD_TIMEOUT,fatal:!1,frag:t,error:new Error(`Timeout after ${m.timeout}ms`),networkDetails:y,stats:x}))}};n&&(p.onProgress=(x,g,y,b)=>n({frag:t,part:null,payload:y,networkDetails:b})),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(R1t(t,n));return}const d=this.loader=i?new i(a):new l(a),u=D1t(t,n);t.loader=d;const h=L1t(a.fragLoadPolicy.default),m={loadPolicy:h,timeout:h.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:I1t};n.stats=d.stats,d.load(u,m,{onSuccess:(p,x,g,y)=>{this.resetLoader(t,d),this.updateStatsFromPart(t,n);const b={frag:t,part:n,payload:p.data,networkDetails:y};r(b),o(b)},onError:(p,x,g,y)=>{this.resetLoader(t,d),c(new H4({type:mo.NETWORK_ERROR,details:fr.FRAG_LOAD_ERROR,fatal:!1,frag:t,part:n,response:qu({url:u.url,data:void 0},p),error:new Error(`HTTP Error ${p.code} ${p.text}`),networkDetails:g,stats:y}))},onAbort:(p,x,g)=>{t.stats.aborted=n.stats.aborted,this.resetLoader(t,d),c(new H4({type:mo.NETWORK_ERROR,details:fr.INTERNAL_ABORTED,fatal:!1,frag:t,part:n,error:new Error("Aborted"),networkDetails:g,stats:p}))},onTimeout:(p,x,g)=>{this.resetLoader(t,d),c(new H4({type:mo.NETWORK_ERROR,details:fr.FRAG_LOAD_TIMEOUT,fatal:!1,frag:t,part:n,error:new Error(`Timeout after ${m.timeout}ms`),networkDetails:g,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 D1t(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(Mi(a)&&Mi(i)){var l;let o=a,c=i;if(s.sn==="initSegment"&&czn((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 R1t(s,t){const n=new Error(`GAP ${s.gap?"tag":"attribute"} found`),r={type:mo.MEDIA_ERROR,details:fr.FRAG_GAP,fatal:!1,frag:s,error:n,networkDetails:null};return t&&(r.part=t),(t||s).stats.aborted=!0,new H4(r)}function czn(s){return s==="AES-128"||s==="AES-256"}class H4 extends Error{constructor(t){super(t.error.message),this.data=void 0,this.data=t}}class RHt extends v2{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 MXe{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=Sae(),this.buffering={audio:Sae(),video:Sae(),audiovideo:Sae()},this.level=t,this.sn=n,this.id=r,this.size=a,this.part=i,this.partial=l}}function Sae(){return{start:0,executeStart:0,executeEnd:0,end:0}}const O1t={length:0,start:()=>0,end:()=>0};class Bl{static isBuffered(t,n){if(t){const r=Bl.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=Bl.getBuffered(t);return Bl.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 z1t(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 dzn(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 uzn=/^(\d+)x(\d+)$/,B1t=/(.+?)=(".*?"|.*?)(?:,|$)/g;class Sp{constructor(t,n){typeof t=="string"&&(t=Sp.parseAttrList(t,n)),dh(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=uzn.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(B1t.lastIndex=0;(r=B1t.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=NUe(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":Yu.warn(`${t}: attribute ${l} is missing quotes`)}a[l]=o}return a}}const hzn="com.apple.hls.interstitial";function mzn(s){return s!=="ID"&&s!=="CLASS"&&s!=="CUE"&&s!=="START-DATE"&&s!=="DURATION"&&s!=="END-DATE"&&s!=="END-ON-NEXT"}function pzn(s){return s==="SCTE35-OUT"||s==="SCTE35-IN"||s==="SCTE35-CMD"}class FHt{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]){Yu.warn(`DATERANGE tag attribute: "${l}" does not match for tags with ID: "${t.ID}"`),this._badValueForSameId=l;break}t=dh(new Sp({}),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"]);Mi(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?(Yu.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(Mi(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===hzn}get isValid(){return!!this.id&&!this._badValueForSameId&&Mi(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 fzn=10;class xzn{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?Mi(this.fragments[this.fragments.length-1].programDateTime):!1}get levelTargetDuration(){return this.averagetargetduration||this.targetduration||fzn}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 H4e(s,t){return s.length===t.length?!s.some((n,r)=>n!==t[r]):!1}function $1t(s,t){return!s&&!t?!0:!s||!t?!1:H4e(s,t)}function jB(s){return s==="AES-128"||s==="AES-256"||s==="AES-256-CTR"}function LXe(s){switch(s){case"AES-128":case"AES-256":return x6.cbc;case"AES-256-CTR":return x6.ctr;default:throw new Error(`invalid full segment method ${s}`)}}function PXe(s){return Uint8Array.from(atob(s),t=>t.charCodeAt(0))}function kUe(s){return Uint8Array.from(unescape(encodeURIComponent(s)),t=>t.charCodeAt(0))}function gzn(s){const t=kUe(s).subarray(0,16),n=new Uint8Array(16);return n.set(t,16-t.length),n}function zHt(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 BHt(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=PXe(l)):n=gzn(l)}}return n}const G4e=typeof self<"u"?self:void 0;var Pp={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.fps",PLAYREADY:"com.microsoft.playready",WIDEVINE:"com.widevine.alpha"},hy={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.streamingkeydelivery",PLAYREADY:"com.microsoft.playready",WIDEVINE:"urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed"};function RNe(s){switch(s){case hy.FAIRPLAY:return Pp.FAIRPLAY;case hy.PLAYREADY:return Pp.PLAYREADY;case hy.WIDEVINE:return Pp.WIDEVINE;case hy.CLEARKEY:return Pp.CLEARKEY}}function zDe(s){switch(s){case Pp.FAIRPLAY:return hy.FAIRPLAY;case Pp.PLAYREADY:return hy.PLAYREADY;case Pp.WIDEVINE:return hy.WIDEVINE;case Pp.CLEARKEY:return hy.CLEARKEY}}function JW(s){const{drmSystems:t,widevineLicenseUrl:n}=s,r=t?[Pp.FAIRPLAY,Pp.WIDEVINE,Pp.PLAYREADY,Pp.CLEARKEY].filter(a=>!!t[a]):[];return!r[Pp.WIDEVINE]&&n&&r.push(Pp.WIDEVINE),r}const $Ht=function(s){return G4e!=null&&(s=G4e.navigator)!=null&&s.requestMediaKeySystemAccess?self.navigator.requestMediaKeySystemAccess.bind(self.navigator):null}();function yzn(s,t,n,r){let a;switch(s){case Pp.FAIRPLAY:a=["cenc","sinf"];break;case Pp.WIDEVINE:case Pp.PLAYREADY:a=["cenc"];break;case Pp.CLEARKEY:a=["cenc","keyids"];break;default:throw new Error(`Unknown key-system: ${s}`)}return vzn(a,t,n,r)}function vzn(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 bzn(s){var t;return!!s&&(s.sessionType==="persistent-license"||!!((t=s.sessionTypes)!=null&&t.some(n=>n==="persistent-license")))}function UHt(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=PXe(o).subarray(0,16);return zHt(c),c}}return null}let Y7={};class KT{static clearKeyUriToKeyIdMap(){Y7={}}static setKeyIdForUri(t,n){Y7[t]=n}static addKeyIdForUri(t){const n=Object.keys(Y7).length%Number.MAX_SAFE_INTEGER,r=new Uint8Array(16);return new DataView(r.buffer,12,4).setUint32(0,n),Y7[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&&!jB(t),l!=null&&l.startsWith("0x")&&(this.keyId=new Uint8Array(xHt(l)))}matches(t){return t.uri===this.uri&&t.method===this.method&&t.encrypted===this.encrypted&&t.keyFormat===this.keyFormat&&H4e(t.keyFormatVersions,this.keyFormatVersions)&&$1t(t.iv,this.iv)&&$1t(t.keyId,this.keyId)}isSupported(){if(this.method){if(jB(this.method)||this.method==="NONE")return!0;if(this.keyFormat==="identity")return this.method==="SAMPLE-AES";switch(this.keyFormat){case hy.FAIRPLAY:case hy.WIDEVINE:case hy.PLAYREADY:case hy.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(jB(this.method)){let i=this.iv;return i||(typeof t!="number"&&(Yu.warn(`missing IV for initialization segment with method="${this.method}" - compliance issue`),t=0),i=wzn(t)),new KT(this.method,this.uri,"identity",this.keyFormatVersions,i)}if(this.keyId){const i=Y7[this.uri];if(i&&!H4e(this.keyId,i)&&KT.setKeyIdForUri(this.uri,this.keyId),this.pssh)return this}const r=BHt(this.uri);if(r)switch(this.keyFormat){case hy.WIDEVINE:if(this.pssh=r,!this.keyId){const i=k9n(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=U1t(n));break;case hy.PLAYREADY:{const i=new Uint8Array([154,4,240,121,152,64,66,134,171,146,230,91,224,136,95,149]);this.pssh=N9n(i,null,r),this.keyId=UHt(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=_zn(n),i||(i=U1t(n),i||(i=Y7[this.uri])),i&&(this.keyId=i,KT.setKeyIdForUri(this.uri,i))}return this}}function _zn(s){const t=s==null?void 0:s[hy.WIDEVINE];return t?t.keyId:null}function U1t(s){const t=s==null?void 0:s[hy.PLAYREADY];if(t){const n=BHt(t.uri);if(n)return UHt(n)}return null}function wzn(s){const t=new Uint8Array(16);for(let n=12;n<16;n++)t[n]=s>>8*(15-n)&255;return t}const q1t=/#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,V1t=/#EXT-X-MEDIA:(.*)/g,jzn=/^#EXT(?:INF|-X-TARGETDURATION):/m,BDe=new RegExp([/#EXTINF:\s*(\d*(?:\.\d+)?)(?:,(.*)\s+)?/.source,/(?!#) *(\S[^\r\n]*)/.source,/#.*/.source].join("|"),"g"),Nzn=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 YS{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(V1t.lastIndex=0;(a=V1t.exec(t))!==null;){const d=new Sp(a[1],r),u=d.TYPE;if(u){const h=o[u],m=i[u]||[];i[u]=m;const p=d.LANGUAGE,x=d["ASSOC-LANGUAGE"],g=d.CHANNELS,y=d.CHARACTERISTICS,b=d["INSTREAM-ID"],v={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?YS.resolve(d.URI,n):""};if(x&&(v.assocLang=x),g&&(v.channels=g),y&&(v.characteristics=y),b&&(v.instreamId=b),h!=null&&h.length){const N=YS.findGroup(h,v.groupId)||h[0];K1t(v,N,"audioCodec"),K1t(v,N,"textCodec")}m.push(v)}}return i}static parseLevelPlaylist(t,n,r,a,i,l){var o;const c={url:n},d=new xzn(n),u=d.fragments,h=[];let m=null,p=0,x=0,g=0,y=0,b=0,v=null,N=new RDe(a,c),C,A,T,P=-1,M=!1,I=null,D;if(BDe.lastIndex=0,d.m3u8=t,d.hasVariableRefs=F1t(t),((o=BDe.exec(t))==null?void 0:o[0])!=="#EXTM3U")return d.playlistParsingError=new Error("Missing format identifier #EXTM3U"),d;for(;(C=BDe.exec(t))!==null;){M&&(M=!1,N=new RDe(a,c),N.playlistOffset=g,N.setStart(g),N.sn=p,N.cc=y,b&&(N.bitrate=b),N.level=r,m&&(N.initSegment=m,m.rawProgramDateTime&&(N.rawProgramDateTime=m.rawProgramDateTime,m.rawProgramDateTime=null),I&&(N.setByteRange(I),I=null)));const V=C[1];if(V){N.duration=parseFloat(V);const K=(" "+C[2]).slice(1);N.title=K||null,N.tagList.push(K?["INF",V,K]:["INF",V])}else if(C[3]){if(Mi(N.duration)){N.playlistOffset=g,N.setStart(g),T&&Z1t(N,T,d),N.sn=p,N.level=r,N.cc=y,u.push(N);const K=(" "+C[3]).slice(1);N.relurl=NUe(d,K),SUe(N,v,h),v=N,g+=N.duration,p++,x=0,M=!0}}else{if(C=C[0].match(Nzn),!C){Yu.warn("No matches on slow regex match for level playlist!");continue}for(A=1;A0&&X1t(d,K,C),p=d.startSN=parseInt(Q);break;case"SKIP":{d.skippedSegments&&T4(d,K,C);const ce=new Sp(Q,d),ue=ce.decimalInteger("SKIPPED-SEGMENTS");if(Mi(ue)){d.skippedSegments+=ue;for(let ee=ue;ee--;)u.push(null);p+=ue}const ne=ce.enumeratedString("RECENTLY-REMOVED-DATERANGES");ne&&(d.recentlyRemovedDateranges=(d.recentlyRemovedDateranges||[]).concat(ne.split(" ")));break}case"TARGETDURATION":d.targetduration!==0&&T4(d,K,C),d.targetduration=Math.max(parseInt(Q),1);break;case"VERSION":d.version!==null&&T4(d,K,C),d.version=parseInt(Q);break;case"INDEPENDENT-SEGMENTS":break;case"ENDLIST":d.live||T4(d,K,C),d.live=!1;break;case"#":(Q||J)&&N.tagList.push(J?[Q,J]:[Q]);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,Q]),b=parseInt(Q)*1e3,Mi(b)?N.bitrate=b:b=0;break;case"DATERANGE":{const ce=new Sp(Q,d),ue=new FHt(ce,d.dateRanges[ce.ID],d.dateRangeTagCount);d.dateRangeTagCount++,ue.isValid||d.skippedSegments?d.dateRanges[ue.id]=ue:Yu.warn(`Ignoring invalid DATERANGE tag: "${Q}"`),N.tagList.push(["EXT-X-DATERANGE",Q]);break}case"DEFINE":{{const ce=new Sp(Q,d);"IMPORT"in ce?dzn(d,ce,l):z1t(d,ce,n)}break}case"DISCONTINUITY-SEQUENCE":d.startCC!==0?T4(d,K,C):u.length>0&&X1t(d,K,C),d.startCC=y=parseInt(Q);break;case"KEY":{const ce=H1t(Q,n,d);if(ce.isSupported()){if(ce.method==="NONE"){T=void 0;break}T||(T={});const ue=T[ce.keyFormat];ue!=null&&ue.matches(ce)||(ue&&(T=dh({},T)),T[ce.keyFormat]=ce)}else Yu.warn(`[Keys] Ignoring unsupported EXT-X-KEY tag: "${Q}"`);break}case"START":d.startTimeOffset=G1t(Q);break;case"MAP":{const ce=new Sp(Q,d);if(N.duration){const ue=new RDe(a,c);Y1t(ue,ce,r,T),m=ue,N.initSegment=m,m.rawProgramDateTime&&!N.rawProgramDateTime&&(N.rawProgramDateTime=m.rawProgramDateTime)}else{const ue=N.byteRangeEndOffset;if(ue){const ne=N.byteRangeStartOffset;I=`${ue-ne}@${ne}`}else I=null;Y1t(N,ce,r,T),m=N,M=!0}m.cc=y;break}case"SERVER-CONTROL":{D&&T4(d,K,C),D=new Sp(Q),d.canBlockReload=D.bool("CAN-BLOCK-RELOAD"),d.canSkipUntil=D.optionalFloat("CAN-SKIP-UNTIL",0),d.canSkipDateRanges=d.canSkipUntil>0&&D.bool("CAN-SKIP-DATERANGES"),d.partHoldBack=D.optionalFloat("PART-HOLD-BACK",0),d.holdBack=D.optionalFloat("HOLD-BACK",0);break}case"PART-INF":{d.partTarget&&T4(d,K,C);const ce=new Sp(Q);d.partTarget=ce.decimalFloatingPoint("PART-TARGET");break}case"PART":{let ce=d.partList;ce||(ce=d.partList=[]);const ue=x>0?ce[ce.length-1]:void 0,ne=x++,ee=new Sp(Q,d),le=new d9n(ee,N,c,ne,ue);ce.push(le),N.duration+=le.duration;break}case"PRELOAD-HINT":{const ce=new Sp(Q,d);d.preloadHint=ce;break}case"RENDITION-REPORT":{const ce=new Sp(Q,d);d.renditionReports=d.renditionReports||[],d.renditionReports.push(ce);break}default:Yu.warn(`line parsed but not handled: ${C}`);break}}}v&&!v.relurl?(u.pop(),g-=v.duration,d.partList&&(d.fragmentHint=v)):d.partList&&(SUe(N,v,h),N.cc=y,d.fragmentHint=N,T&&Z1t(N,T,d)),d.targetduration||(d.playlistParsingError=new Error("Missing Target Duration"));const B=u.length,q=u[0],W=u[B-1];if(g+=d.skippedSegments*d.targetduration,g>0&&B&&W){d.averagetargetduration=g/B;const V=W.sn;d.endSN=V!=="initSegment"?V:0,d.live||(W.endList=!0),P>0&&(Szn(u,P),q&&h.unshift(q))}return d.fragmentHint&&(g+=d.fragmentHint.duration),d.totalduration=g,h.length&&d.dateRangeTagCount&&q&&qHt(h,d),d.endCC=y,d}}function qHt(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 x=u[p].programDateTime;if(t>=x&&tr);["video","audio","text"].forEach(r=>{const a=n.filter(i=>CXe(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 K1t(s,t,n){const r=t[n];r&&(s[n]=r)}function Szn(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 SUe(s,t,n){s.rawProgramDateTime?n.push(s):t!=null&&t.programDateTime&&(s.programDateTime=t.endProgramDateTime)}function Y1t(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 Z1t(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 T4(s,t,n){s.playlistParsingError=new Error(`#EXT-X-${t} must not appear more than once (${n[0]})`)}function X1t(s,t,n){s.playlistParsingError=new Error(`#EXT-X-${t} must appear before the first Media Segment (${n[0]})`)}function $De(s,t){const n=t.startPTS;if(Mi(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 VHt(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(Mi(u)){const b=Math.abs(u-n);s&&b>s.totalduration?l.warn(`media timestamps and playlist times differ by ${b}s for level ${t.level} ${s.url}`):Mi(t.deltaPTS)?t.deltaPTS=Math.max(b,t.deltaPTS):t.deltaPTS=b,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 x;const g=p-s.startSN,y=s.fragments;for(y[g]=t,x=g;x>0;x--)$De(y[x],y[x-1]);for(x=g;x=0;u--){const h=a[u].initSegment;if(h){r=h;break}}s.fragmentHint&&delete s.fragmentHint.endPTS;let i;Tzn(s,t,(u,h,m,p)=>{if((!t.startCC||t.skippedSegments)&&h.cc!==u.cc){const x=u.cc-h.cc;for(let g=m;g{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=Azn(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?VHt(t,i,i.startPTS,i.endPTS,i.startDTS,i.endDTS,n):HHt(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 Azn(s,t,n){const{dateRanges:r,recentlyRemovedDateranges:a}=t,i=dh({},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 FHt(r[c].attr,d);u.isValid?(i[c]=u,d||(u.tagOrder+=o)):n.warn(`Ignoring invalid Playlist Delta Update DATERANGE tag: "${Lh(r[c].attr)}"`)}),i):r}function Ezn(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 Tzn(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&&Mzn(m,p)){t.playlistParsingError=Q1t(`media sequence mismatch ${h.sn}:`,s,t,u,h);return}else if(u.cc!==h.cc){t.playlistParsingError=Q1t(`discontinuity sequence mismatch (${u.cc}!=${h.cc})`,s,t,u,h);return}}}}function Q1t(s,t,n,r,a){return new Error(`${s} ${a.url} Playlist starting @${t.startSN} ${t.m3u8} Playlist starting @${n.startSN} ${n.m3u8}`)}function HHt(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 Mzn(s,t){return s!==t&&t?ebt(s)!==ebt(t):!1}function ebt(s){return s.replace(/\?[^?]*$/,"")}function iZ(s,t){for(let r=0,a=s.length;rs.startCC)}function tbt(s,t){const n=s.start+t;s.startPTS=n,s.setStart(n),s.endPTS=n+s.duration}function ZHt(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=Bl.bufferInfo(d||c,h,l.maxBufferHole),p=!m.len;if(this.log(`Media seeking to ${Mi(h)?h.toFixed(3):h}, state: ${u}, ${p?"out of":"in"} buffer`),this.state===ea.ENDED)this.resetLoadingState();else if(o){const x=l.maxFragLookUpTolerance,g=o.start-x,y=o.start+o.duration+x;if(p||ym.end){const b=h>y;(hx&&(this.lastCurrentTime=h),!this.loadingParts){const g=Math.max(m.end,h),y=this.shouldLoadParts(this.getLevelDetails(),g);y&&(this.log(`LL-Part loading ON after seeking to ${h.toFixed(2)} with buffer @${g.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===ea.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 lzn(t.config),this.keyLoader=r,this.fragmentTracker=n,this.config=t.config,this.decrypter=new TXe(t.config)}registerListeners(){const{hls:t}=this;t.on(Dt.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(Dt.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(Dt.MANIFEST_LOADING,this.onManifestLoading,this),t.on(Dt.MANIFEST_LOADED,this.onManifestLoaded,this),t.on(Dt.ERROR,this.onError,this)}unregisterListeners(){const{hls:t}=this;t.off(Dt.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(Dt.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(Dt.MANIFEST_LOADING,this.onManifestLoading,this),t.off(Dt.MANIFEST_LOADED,this.onManifestLoaded,this),t.off(Dt.ERROR,this.onError,this)}doTick(){this.onTickEnd()}onTickEnd(){}startLoad(t){}stopLoad(){if(this.state===ea.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=ea.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=Bl.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===ea.FRAG_LOADING||!this.fragCurrent&&l===ea.PARSING)&&(this.fragmentTracker.removeFragment(o),this.state=ea.IDLE);return}"payload"in i&&(this.log(`Loaded ${o.type} sn: ${o.sn} of ${this.playlistLabel()} ${o.level}`),this.hls.trigger(Dt.FRAG_LOADED,i)),this._handleFragmentLoadComplete(i)}).catch(i=>{this.state===ea.STOPPED||this.state===ea.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)===ug.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)===ug.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(Dt.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&&jB(o.method)){const c=self.performance.now();return this.decrypter.decrypt(new Uint8Array(l),o.key.buffer,o.iv.buffer,LXe(o.method)).catch(d=>{throw a.trigger(Dt.ERROR,{type:mo.MEDIA_ERROR,details:fr.FRAG_DECRYPT_ERROR,fatal:!1,error:d,reason:d.message,frag:i}),d}).then(d=>{const u=self.performance.now();return a.trigger(Dt.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===ea.STOPPED||this.state===ea.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!==ea.STOPPED&&(this.state=ea.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(Dt.ERROR,{type:mo.KEY_SYSTEM_ERROR,details:fr.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?Izn.toString(Bl.getBuffered(r)):"(detached)"})`),Jf(t)){var a;if(t.type!==Gi.SUBTITLE){const l=t.elementaryStreams;if(!Object.keys(l).some(o=>!!l[o])){this.state=ea.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=ea.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 MXe(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=ea.KEY_LOADING,this.fragCurrent=t,o=this.keyLoader.load(t).then(m=>{if(!this.fragContextChanged(m.frag))return this.hls.trigger(Dt.KEY_LOADED,m),this.state===ea.KEY_LOADING&&(this.state=ea.IDLE),m}),this.hls.trigger(Dt.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(Jf(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&&Jf(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 x=m[p];t=this.fragCurrent=x.fragment,this.log(`Loading ${t.type} sn: ${t.sn} part: ${x.index} (${p}/${m.length-1}) of ${this.fragInfo(t,!1,x)}) cc: ${t.cc} [${l.startSN}-${l.endSN}], target: ${parseFloat(r.toFixed(3))}`),this.nextLoadPosition=x.start+x.duration,this.state=ea.FRAG_LOADING;let g;return o?g=o.then(y=>!y||this.fragContextChanged(y.frag)?null:this.doFragPartsLoad(t,x,n,a)).catch(y=>this.handleFragLoadError(y)):g=this.doFragPartsLoad(t,x,n,a).catch(y=>this.handleFragLoadError(y)),this.hls.trigger(Dt.FRAG_LOADING,{frag:t,part:x,targetBufferTime:r}),this.fragCurrent===null?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING parts")):g}else if(!t.url||this.loadedEndOfParts(m,r))return Promise.resolve(null)}}if(Jf(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))}`),Mi(t.sn)&&!this.bitrateTest&&(this.nextLoadPosition=t.start+t.duration),this.state=ea.FRAG_LOADING;const u=this.config.progressive&&t.type!==Gi.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(Dt.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(Dt.FRAG_LOADED,m);const x=J1t(r.details,t.sn,h.index+1)||KHt(d,t.sn,h.index+1);if(x)u(x);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===fr.INTERNAL_ABORTED?this.handleFragLoadAborted(n.frag,n.part):n.frag&&n.type===mo.KEY_SYSTEM_ERROR?(n.frag.abortRequests(),this.resetStartWhenNotLoaded(),this.resetFragmentLoading(n.frag)):this.hls.trigger(Dt.ERROR,n)}else this.hls.trigger(Dt.ERROR,{type:mo.OTHER_ERROR,details:fr.INTERNAL_EXCEPTION,err:t,error:t,fatal:!0});return null}_handleTransmuxerFlush(t){const n=this.getCurrentContext(t);if(!n||this.state!==ea.PARSING){!this.fragCurrent&&this.state!==ea.STOPPED&&this.state!==ea.ERROR&&(this.state=ea.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===Gi.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?J1t(c,i,l):null,u=d?d.fragment:WHt(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!==ea.PARSING)return;const{data1:l,data2:o}=t;let c=l;if(o&&(c=d2(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(Dt.BUFFER_APPENDING,h),t.dropped&&t.independent&&!r){if(i)return;this.flushBufferGap(n)}}flushBufferGap(t){const n=this.media;if(!n)return;if(!Bl.isBuffered(n,n.currentTime)){this.flushMainBuffer(0,t.start);return}const r=n.currentTime,a=Bl.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(!Mi(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=Bl.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 Bl.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=Gi.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,b=p===m?"config":"next load start"):x!==null?(y=x,b="live edge"):(y=t,b="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(sbt(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(sbt(this.config)&&t.type!==Gi.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=Z9n(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=PHt(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=$O(i,l,t,g)}else m=l[l.length-1];if(m){const x=m.sn-r.startSN,g=this.fragmentTracker.getState(m);if((g===ug.OK||g===ug.PARTIAL&&m.gap)&&(i=m),i&&m.sn===i.sn&&(!h||u[0].fragment.sn>m.sn||!r.live)&&m.level===i.level){const b=l[x+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&&Jf(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!==ea.FRAG_LOADING_WAITING_RETRY)&&(this.state=ea.IDLE)}onFragmentOrKeyLoadError(t,n){var r;if(n.chunkMeta&&!n.frag){const b=this.getCurrentContext(n.chunkMeta);b&&(n.frag=b.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===fr.FRAG_GAP;l&&this.fragmentTracker.fragBuffered(a,!0);const o=n.errorAction;if(!o){this.state=ea.ERROR;return}const{action:c,flags:d,retryCount:u=0,retryConfig:h}=o,m=!!h,p=m&&c===oy.RetryRequest,x=m&&!o.resolved&&d===C_.MoveAllAlternatesMatchingHost,g=(r=this.hls.latestLevelDetails)==null?void 0:r.live;if(!p&&x&&Jf(a)&&!a.endList&&g&&!DHt(n))this.resetFragmentErrors(t),this.treatAsGap(a),o.resolved=!0;else if((p||x)&&u=n||r&&!jUe(0))&&(r&&this.log("Connection restored (online)"),this.resetStartWhenNotLoaded(),this.state=ea.IDLE)}reduceLengthAndFlushBuffer(t){if(this.state===ea.PARSING||this.state===ea.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===Gi.AUDIO&&(this.fragCurrent=null),this.hls.hasEnoughToStart||(this.startFragRequested=!1),this.state!==ea.STOPPED&&(this.state=ea.IDLE)}afterBufferFlushed(t,n,r){if(!t)return;const a=Bl.getBuffered(t);this.fragmentTracker.detectEvictedFragments(n,a,r),this.state===ea.ENDED&&this.resetLoadingState()}resetLoadingState(){this.log("Reset loading state"),this.fragCurrent=null,this.fragPrevious=null,this.state!==ea.STOPPED&&(this.state=ea.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:VHt(i,t,u.startPTS,u.endPTS,u.startDTS,u.endDTS,this);return this.hls.trigger(Dt.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(Dt.ERROR,{type:mo.MEDIA_ERROR,details:fr.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=ea.PARSED,this.log(`Parsed ${t.type} sn: ${t.sn}${n?" part: "+n.index:""} of ${this.fragInfo(t,!1,n)})`),this.hls.trigger(Dt.FRAG_PARSED,{frag:t,part:n})}playlistLabel(){return this.playlistType===Gi.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 sbt(s){return!!s.interstitialsController&&s.enableInterstitialPlayback!==!1}class QHt{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=Dzn(t,n);else return new Uint8Array(0);return this.reset(),r}reset(){this.chunks.length=0,this.dataLength=0}}function Dzn(s,t){const n=new Uint8Array(t);let r=0;for(let a=0;a0)return s.subarray(n,n+r)}function Uzn(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(Dt.ERROR,Dt.ERROR,{type:mo.MEDIA_ERROR,details:fr.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 Yu.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 eGt(s,t){return s[t]===255&&(s[t+1]&246)===240}function tGt(s,t){return s[t+1]&1?7:9}function OXe(s,t){return(s[t+3]&3)<<11|s[t+4]<<3|(s[t+5]&224)>>>5}function qzn(s,t){return t+5=s.length)return!1;const r=OXe(s,t);if(r<=n)return!1;const a=t+r;return a===s.length||K4e(s,a)}return!1}function sGt(s,t,n,r,a){if(!s.samplerate){const i=Uzn(t,n,r,a);if(!i)return;dh(s,i)}}function nGt(s){return 1024*9e4/s}function Gzn(s,t){const n=tGt(s,t);if(t+n<=s.length){const r=OXe(s,t)-n;if(r>0)return{headerLength:n,frameLength:r}}}function rGt(s,t,n,r,a){const i=nGt(s.samplerate),l=r+a*i,o=Gzn(t,n);let c;if(o){const{frameLength:h,headerLength:m}=o,p=m+h,x=Math.max(0,n+p-t.length);x?(c=new Uint8Array(p-m),c.set(t.subarray(n+m,t.length),0)):c=t.subarray(n+m,n+p);const g={unit:c,pts:l};return x||s.samples.push(g),{sample:g,length:p,missing:x}}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 Wzn(s,t){return RXe(s,t)&&ITe(s,t+6)+10<=s.length-t}function Kzn(s){return s instanceof ArrayBuffer?s:s.byteOffset==0&&s.byteLength==s.buffer.byteLength?s.buffer:new Uint8Array(s).buffer}function qDe(s,t=0,n=1/0){return Yzn(s,t,n,Uint8Array)}function Yzn(s,t,n,r){const a=Zzn(s);let i=1;"BYTES_PER_ELEMENT"in r&&(i=r.BYTES_PER_ELEMENT);const l=Xzn(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 Zzn(s){return s instanceof ArrayBuffer?s:s.buffer}function Xzn(s){return s&&s.buffer instanceof ArrayBuffer&&s.byteLength!==void 0&&s.byteOffset!==void 0}function Qzn(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=uw(qDe(s.data,1,r)),i=s.data[2+r],l=s.data.subarray(3+r).indexOf(0);if(l===-1)return;const o=uw(qDe(s.data,3+r,l));let c;return a==="-->"?c=uw(qDe(s.data,4+r+l)):c=Kzn(s.data.subarray(4+r+l)),t.mimeType=a,t.pictureType=i,t.description=o,t.data=c,t}function Jzn(s){if(s.size<2)return;const t=uw(s.data,!0),n=new Uint8Array(s.data.subarray(t.length+1));return{key:s.type,info:t,data:n.buffer}}function eBn(s){if(s.size<2)return;if(s.type==="TXXX"){let n=1;const r=uw(s.data.subarray(n),!0);n+=r.length+1;const a=uw(s.data.subarray(n));return{key:s.type,info:r,data:a}}const t=uw(s.data.subarray(1));return{key:s.type,info:"",data:t}}function tBn(s){if(s.type==="WXXX"){if(s.size<2)return;let n=1;const r=uw(s.data.subarray(n),!0);n+=r.length+1;const a=uw(s.data.subarray(n));return{key:s.type,info:r,data:a}}const t=uw(s.data);return{key:s.type,info:"",data:t}}function sBn(s){return s.type==="PRIV"?Jzn(s):s.type[0]==="W"?tBn(s):s.type==="APIC"?Qzn(s):eBn(s)}function nBn(s){const t=String.fromCharCode(s[0],s[1],s[2],s[3]),n=ITe(s,4),r=10;return{type:t,size:n,data:s.subarray(r,r+n)}}const Cae=10,rBn=10;function aGt(s){let t=0;const n=[];for(;RXe(s,t);){const r=ITe(s,t+6);s[t+5]>>6&1&&(t+=Cae),t+=Cae;const a=t+r;for(;t+rBn0&&o.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:r,type:q_.audioId3,duration:Number.POSITIVE_INFINITY});a{if(Mi(s))return s*90;const r=n?n.baseTime*9e4/n.timescale:0;return t*9e4+r};let Aae=null;const oBn=[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],lBn=[44100,48e3,32e3,22050,24e3,16e3,11025,12e3,8e3],cBn=[[0,72,144,12],[0,0,0,0],[0,72,144,12],[0,144,144,12]],dBn=[0,1,1,4];function oGt(s,t,n,r,a){if(n+24>t.length)return;const i=lGt(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 lGt(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=oBn[c*14+a-1]*1e3,h=lBn[(n===3?0:n===2?1:2)*3+i],m=o===3?1:2,p=cBn[n][r],x=dBn[r],g=p*8*x,y=Math.floor(p*d/h+l)*x;if(Aae===null){const N=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);Aae=N?parseInt(N[1]):0}return!!Aae&&Aae<=87&&r===2&&d>=224e3&&o===0&&(s[t+3]=s[t+3]|128),{sampleRate:h,channelCount:m,frameLength:y,samplesPerFrame:g}}}function BXe(s,t){return s[t]===255&&(s[t+1]&224)===224&&(s[t+1]&6)!==0}function cGt(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,g=[2,1,2,3,3,4,4,5][h]+p,y=t[n+5]>>3,b=t[n+5]&7,v=new Uint8Array([i<<6|y<<1|b>>2,(b&3)<<6|h<<3|p<<2|c>>4,c<<4&224]),N=1536/o*9e4,C=r+a*N,A=t.subarray(n,n+u);return s.config=v,s.channelCount=g,s.samplerate=o,s.samples.push({unit:A,pts:C}),u}class pBn extends zXe{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=gQ(t,0);let r=(n==null?void 0:n.length)||0;if(n&&t[r]===11&&t[r+1]===119&&FXe(n)!==void 0&&uGt(t,r)<=16)return!1;for(let a=t.length;r{const l=w9n(i);if(fBn.test(l.schemeIdUri)){const o=rbt(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:q_.emsg,duration:c})}else if(this.config.enableEmsgKLVMetadata&&l.schemeIdUri.startsWith("urn:misb:KLV:bin:1910.1")){const o=rbt(l,n);r.samples.push({data:l.payload,len:l.payload.byteLength,dts:o,pts:o,type:q_.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 rbt(s,t){return Mi(s.presentationTime)?s.presentationTime/s.timeScale:t+s.presentationTimeDelta/s.timeScale}class gBn{constructor(t,n,r){this.keyData=void 0,this.decrypter=void 0,this.keyData=r,this.decrypter=new TXe(n,{removePKCS7Padding:!1})}decryptBuffer(t){return this.decrypter.decrypt(t,this.keyData.key.buffer,this.keyData.iv.buffer,x6.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 mGt{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 x={data:n.subarray(m,u),type:p};o.push(x)}else{const x=this.getLastNalUnit(t.samples);x&&(l&&c<=4-l&&x.state&&(x.data=x.data.subarray(0,x.data.byteLength-l)),u>0&&(x.data=d2(x.data,n.subarray(0,u)),x.state=0))}c=0&&i>=0){const x={data:n.subarray(m,a),type:p,state:i};o.push(x)}if(o.length===0){const x=this.getLastNalUnit(t.samples);x&&(x.data=d2(x.data,n))}return t.naluState=i,o}}class oZ{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&&Yu.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 yBn extends mGt{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 g=!1;o=!0;const y=d.data;if(c&&y.length>4){const b=this.readSliceType(y);(b===2||b===4||b===7||b===9)&&(g=!0)}if(g){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=g;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,SXe(d.data,1,r.pts,n.samples);break}case 7:{var p,x;o=!0,c=!0;const g=d.data,y=this.readSPS(g);if(!t.sps||t.width!==y.width||t.height!==y.height||((p=t.pixelRatio)==null?void 0:p[0])!==y.pixelRatio[0]||((x=t.pixelRatio)==null?void 0:x[1])!==y.pixelRatio[1]){t.width=y.width,t.height=y.height,t.pixelRatio=y.pixelRatio,t.sps=[g];const b=g.subarray(1,4);let v="avc1.";for(let N=0;N<3;N++){let C=b[N].toString(16);C.length<2&&(C="0"+C),v+=C}t.codec=v}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 oZ(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,SXe(d.data,2,r.pts,n.samples);break;case 32:o=!0,t.vps||(typeof t.params!="object"&&(t.params={}),t.params=dh(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 x in p.params)t.params[x]=p.params[x]}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 x in p)t.params[x]=p[x]}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 oZ(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 oZ(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(),x=n.readUByte(),g=n.readUByte(),y=n.readUByte(),b=n.readUByte(),v=[],N=[];for(let Ae=0;Ae0)for(let Ae=r;Ae<8;Ae++)n.readBits(2);for(let Ae=0;Ae1&&n.readEG();for(let Ue=0;Ue0&&et<16?(le=Qe[et-1],he=Ge[et-1]):et===255&&(le=n.readBits(16),he=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(),je=n.readBoolean(),je&&(n.skipUEG(),n.skipUEG(),n.skipUEG(),n.skipUEG()),n.readBoolean()&&(ge=n.readBits(32),fe=n.readBits(32),n.readBoolean()&&n.readUEG(),n.readBoolean())){const Ge=n.readBoolean(),nt=n.readBoolean();let ft=!1;(Ge||nt)&&(ft=n.readBoolean(),ft&&(n.readUByte(),n.readBits(5),n.readBoolean(),n.readBits(5)),n.readBits(4),n.readBits(4),ft&&n.readBits(4),n.readBits(5),n.readBits(5),n.readBits(5));for(let lt=0;lt<=r;lt++){ve=n.readBoolean();const Mt=ve||n.readBoolean();let Ft=!1;Mt?n.readEG():Ft=n.readBoolean();const Ts=Ft?1:n.readUEG()+1;if(Ge)for(let js=0;js>Ae&1)<<31-Ae)>>>0;let Se=Xe.toString(16);return l===1&&Se==="2"&&(Se="6"),{codecString:`hvc1.${ze}${l}.${Se}.${i?"H":"L"}${b}.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,x,g,y],general_level_idc:b,bit_depth:q+8,bit_depth_luma_minus8:q,bit_depth_chroma_minus8:W,min_spatial_segmentation_idc:ee,chroma_format_idc:C,frame_rate:{fixed:ve,fps:fe/ge}},width:Me,height:De,pixelRatio:[le,he]}}readPPS(t){const n=new oZ(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 Jg=188;class KA{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=KA.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(Jg*5,n-Jg)+1,a=0;for(;a1&&(l===0&&o>2||c+Jg>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:vHt[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=KA.createTrack("video"),this._videoTrack.duration=a,this._audioTrack=KA.createTrack("audio",a),this._id3Track=KA.createTrack("id3"),this._txtTrack=KA.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,x=o.pesData,g=c.pesData,y=null,b=this.pmtParsed,v=this._pmtId,N=t.length;if(this.remainderData&&(t=d2(this.remainderData,t),N=t.length,this.remainderData=null),N>4;let B;if(D>1){if(B=P+5+t[P+4],B===P+Jg)continue}else B=P+4;switch(I){case u:M&&(h&&(i=Z7(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(B,P+Jg)),h.size+=P+Jg-B);break;case m:if(M){if(x&&(i=Z7(x,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}x={data:[],size:0}}x&&(x.data.push(t.subarray(B,P+Jg)),x.size+=P+Jg-B);break;case p:M&&(g&&(i=Z7(g,this.logger))&&this.parseID3PES(c,i),g={data:[],size:0}),g&&(g.data.push(t.subarray(B,P+Jg)),g.size+=P+Jg-B);break;case 0:M&&(B+=t[B]+1),v=this._pmtId=bBn(t,B);break;case v:{M&&(B+=t[B]+1);const q=_Bn(t,B,this.typeSupported,r,this.observer,this.logger);u=q.videoPid,u>0&&(l.pid=u,l.segmentCodec=q.segmentVideoCodec),m=q.audioPid,m>0&&(o.pid=m,o.segmentCodec=q.segmentAudioCodec),p=q.id3Pid,p>0&&(c.pid=p),y!==null&&!b&&(this.logger.warn(`MPEG-TS PMT found at ${P} after unknown PID '${y}'. Backtracking to sync byte @${C} to parse all TS packets.`),y=null,P=C-188),b=this.pmtParsed=!0;break}case 17:case 8191:break;default:y=I;break}}else A++;A>0&&EUe(this.observer,new Error(`Found ${A} TS packet/s that do not start with 0x47`),void 0,this.logger),l.pesData=h,o.pesData=x,c.pesData=g;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=Z7(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=Z7(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=Z7(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 gBn(this.observer,this.config,n);return this.decrypt(a,i)}readyVideoParser(t){this.videoParser===null&&(t==="avc"?this.videoParser=new yBn:t==="hevc"&&(this.videoParser=new vBn))}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=d2(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=dh({},n,{type:this._videoTrack?q_.emsg:q_.audioId3,duration:Number.POSITIVE_INFINITY});t.samples.push(r)}}function AUe(s,t){return((s[t+1]&31)<<8)+s[t+2]}function bBn(s,t){return(s[t+10]&31)<<8|s[t+11]}function _Bn(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 g=s[m+1]+2;m+=g,p-=g}}break;case 194:case 135:return EUe(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 EUe(s,t,n,r){r.warn(`parsing error: ${t.message}`),s.emit(Dt.ERROR,Dt.ERROR,{type:mo.MEDIA_ERROR,details:fr.FRAG_PARSING_ERROR,fatal:!1,levelRetry:n,error:t,reason:t.message})}function VDe(s,t){t.log(`${s} with AES-128-CBC encryption found in unencrypted stream`)}function Z7(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]=d2(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,x=c.length;pg){h-=g;continue}else r=r.subarray(h),g-=h,h=0;m.set(r,n),n+=g}return a&&(a-=i+3),{data:m,pts:l,dts:o,len:a}}return null}class wBn{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 mA=Math.pow(2,32)-1;class mr{static init(){mr.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 mr.types)mr.types.hasOwnProperty(t)&&(mr.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]);mr.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]);mr.STTS=mr.STSC=mr.STCO=i,mr.STSZ=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0]),mr.VMHD=new Uint8Array([0,0,0,1,0,0,0,0,0,0,0,0]),mr.SMHD=new Uint8Array([0,0,0,0,0,0,0,0]),mr.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]);mr.FTYP=mr.box(mr.types.ftyp,l,c,l,o),mr.DINF=mr.box(mr.types.dinf,mr.box(mr.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 mr.box(mr.types.mdia,mr.mdhd(t.timescale||0,t.duration||0),mr.hdlr(t.type),mr.minf(t))}static mfhd(t){return mr.box(mr.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"?mr.box(mr.types.minf,mr.box(mr.types.smhd,mr.SMHD),mr.DINF,mr.stbl(t)):mr.box(mr.types.minf,mr.box(mr.types.vmhd,mr.VMHD),mr.DINF,mr.stbl(t))}static moof(t,n,r){return mr.box(mr.types.moof,mr.mfhd(t),mr.traf(r,n))}static moov(t){let n=t.length;const r=[];for(;n--;)r[n]=mr.trak(t[n]);return mr.box.apply(null,[mr.types.moov,mr.mvhd(t[0].timescale||0,t[0].duration||0)].concat(r).concat(mr.mvex(t)))}static mvex(t){let n=t.length;const r=[];for(;n--;)r[n]=mr.trex(t[n]);return mr.box.apply(null,[mr.types.mvex,...r])}static mvhd(t,n){n*=t;const r=Math.floor(n/(mA+1)),a=Math.floor(n%(mA+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 mr.box(mr.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=mr.box(mr.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 mr.box(mr.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,mr.box(mr.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),mr.box(mr.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 mr.box(mr.types.mp4a,mr.audioStsd(t),mr.box(mr.types.esds,mr.esds(t)))}static mp3(t){return mr.box(mr.types[".mp3"],mr.audioStsd(t))}static ac3(t){return mr.box(mr.types["ac-3"],mr.audioStsd(t),mr.box(mr.types.dac3,t.config))}static stsd(t){const{segmentCodec:n}=t;if(t.type==="audio"){if(n==="aac")return mr.box(mr.types.stsd,mr.STSD,mr.mp4a(t));if(n==="ac3"&&t.config)return mr.box(mr.types.stsd,mr.STSD,mr.ac3(t));if(n==="mp3"&&t.codec==="mp3")return mr.box(mr.types.stsd,mr.STSD,mr.mp3(t))}else if(t.pps&&t.sps){if(n==="avc")return mr.box(mr.types.stsd,mr.STSD,mr.avc1(t));if(n==="hevc"&&t.vps)return mr.box(mr.types.stsd,mr.STSD,mr.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/(mA+1)),o=Math.floor(r%(mA+1));return mr.box(mr.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=mr.sdtp(t),a=t.id,i=Math.floor(n/(mA+1)),l=Math.floor(n%(mA+1));return mr.box(mr.types.traf,mr.box(mr.types.tfhd,new Uint8Array([0,0,0,0,a>>24,a>>16&255,a>>8&255,a&255])),mr.box(mr.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])),mr.trun(t,r.length+16+20+8+16+8+8),r)}static trak(t){return t.duration=t.duration||4294967295,mr.box(mr.types.trak,mr.tkhd(t),mr.mdia(t))}static trex(t){const n=t.id;return mr.box(mr.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 mr.box(mr.types.trun,l)}static initSegment(t){mr.types||mr.init();const n=mr.moov(t);return d2(mr.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 x=0;x>8,r[x][g].length&255]),l),l+=2,o.set(r[x][g],l),l+=r[x][g].length}const d=mr.box(mr.types.hvcC,o),u=t.width,h=t.height,m=t.pixelRatio[0],p=t.pixelRatio[1];return mr.box(mr.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,mr.box(mr.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),mr.box(mr.types.pasp,new Uint8Array([m>>24,m>>16&255,m>>8&255,m&255,p>>24,p>>16&255,p>>8&255,p&255])))}}mr.types=void 0;mr.HDLR_TYPES=void 0;mr.STTS=void 0;mr.STSC=void 0;mr.STCO=void 0;mr.STSZ=void 0;mr.VMHD=void 0;mr.SMHD=void 0;mr.STSD=void 0;mr.FTYP=void 0;mr.DINF=void 0;const pGt=9e4;function $Xe(s,t,n=1,r=!1){const a=s*t*n;return r?Math.round(a):a}function jBn(s,t,n=1,r=!1){return $Xe(s,t,1/n,r)}function qG(s,t=!1){return $Xe(s,1e3,1/pGt,t)}function NBn(s,t=1){return $Xe(s,pGt,1/t)}function abt(s){const{baseTime:t,timescale:n,trackId:r}=s;return`${t/n} (${t}/${n}) trackId: ${r}`}const kBn=10*1e3,SBn=1024,CBn=1152,ABn=1536;let X7=null,HDe=null;function ibt(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 ONe extends v2{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,X7===null){const l=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);X7=l?parseInt(l[1]):0}if(HDe===null){const i=navigator.userAgent.match(/Safari\/(\d+)/i);HDe=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&&abt(n)} > ${t&&abt(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=F_(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,x,g=i,y=i;const b=t.pid>-1,v=n.pid>-1,N=n.samples.length,C=t.samples.length>0,A=o&&N>0||N>1;if((!b||C)&&(!v||A)||this.ISGenerated||o){if(this.ISGenerated){var P,M,I,D;const V=this.videoTrackConfig;(V&&(n.width!==V.width||n.height!==V.height||((P=n.pixelRatio)==null?void 0:P[0])!==((M=V.pixelRatio)==null?void 0:M[0])||((I=n.pixelRatio)==null?void 0:I[1])!==((D=V.pixelRatio)==null?void 0:D[1]))||!V&&A||this.nextAudioTs===null&&C)&&this.resetInitSegment()}this.ISGenerated||(h=this.generateIS(t,n,i,l));const B=this.isVideoContiguous;let q=-1,W;if(A&&(q=EBn(n.samples),!B&&this.config.forceKeyFrameOnDiscontinuity))if(x=!0,q>0){this.warn(`Dropped ${q} out of ${N} video samples due to a missing keyframe`);const V=this.getVideoStartPts(n.samples);n.samples=n.samples.slice(q),n.dropped+=q,y+=(n.samples[0].pts-V)/n.inputTimeScale,W=y}else q===-1&&(this.warn(`No keyframe found out of ${N} video samples`),x=!1);if(this.ISGenerated){if(C&&A){const V=this.getVideoStartPts(n.samples),Q=(F_(t.samples[0].pts,V)-V)/n.inputTimeScale;g+=Math.max(0,Q),y+=Math.max(0,-Q)}if(C){if(t.samplerate||(this.warn("regenerate InitSegment as audio detected"),h=this.generateIS(t,n,i,l)),u=this.remuxAudio(t,g,this.isAudioContiguous,l,v||A||c===Gi.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,B,V)}}else A&&(d=this.remuxVideo(n,y,B,0));d&&(d.firstKeyFrame=q,d.independent=q!==-1,d.firstKeyFramePTS=W)}}return this.ISGenerated&&this._initPTS&&this._initDTS&&(r.samples.length&&(p=fGt(r,i,this._initPTS,this._initDTS)),a.samples.length&&(m=xGt(a,i,this._initPTS))),{audio:u,video:d,initSegment:h,independent:x,text:m,id3:p}}computeInitPts(t,n,r,a){const i=Math.round(r*n);let l=F_(t,i);if(l0?ee-1:ee].dts&&(v=!0)}v&&l.sort(function(ee,le){const he=ee.dts-le.dts,ve=ee.pts-le.pts;return he||ve}),x=l[0].dts,g=l[l.length-1].dts;const C=g-x,A=C?Math.round(C/(c-1)):p||t.inputTimeScale/30;if(r){const ee=x-N,le=ee>A,he=ee<-1;if((le||he)&&(le?this.warn(`${(t.segmentCodec||"").toUpperCase()}: ${qG(ee,!0)} ms (${ee}dts) hole between fragments detected at ${n.toFixed(3)}`):this.warn(`${(t.segmentCodec||"").toUpperCase()}: ${qG(-ee,!0)} ms (${ee}dts) overlapping between fragments detected at ${n.toFixed(3)}`),!he||N>=l[0].pts||X7)){x=N;const ve=l[0].pts-ee;if(le)l[0].dts=x,l[0].pts=ve;else{let ge=!0;for(let fe=0;feve&&ge);fe++){const je=l[fe].pts;if(l[fe].dts-=ee,l[fe].pts-=ee,fe0?le.dts-l[ee-1].dts:A;if(ge=ee>0?le.pts-l[ee-1].pts:A,je.stretchShortVideoTrack&&this.nextAudioTs!==null){const Me=Math.floor(je.maxBufferHole*i),De=(a?y+a*i:this.nextAudioTs+u)-le.pts;De>Me?(p=De-Ee,p<0?p=Ee:q=!0,this.log(`It is approximately ${De/90} ms to the next segment; using duration ${p/90} ms for the last video frame.`)):p=Ee}else p=Ee}const fe=Math.round(le.pts-le.dts);W=Math.min(W,p),K=Math.max(K,p),V=Math.min(V,ge),Q=Math.max(Q,ge),o.push(ibt(le.key,p,ve,fe))}if(o.length){if(X7){if(X7<70){const ee=o[0].flags;ee.dependsOn=2,ee.isNonSync=0}}else if(HDe&&Q-V0&&(a&&Math.abs(N-(b+v))<9e3||Math.abs(F_(g[0].pts,N)-(b+v))<20*u),g.forEach(function(Q){Q.pts=F_(Q.pts,N)}),!r||b<0){const Q=g.length;if(g=g.filter(J=>J.pts>=0),Q!==g.length&&this.warn(`Removed ${g.length-Q} of ${Q} samples (initPTS ${v} / ${l})`),!g.length)return;i===0?b=0:a&&!x?b=Math.max(0,N-v):b=g[0].pts-v}if(t.segmentCodec==="aac"){const Q=this.config.maxAudioFramesDrift;for(let J=0,ce=b+v;J=Q*u&&le0){P+=y;try{T=new Uint8Array(P)}catch(le){this.observer.emit(Dt.ERROR,Dt.ERROR,{type:mo.MUX_ERROR,details:fr.REMUX_ALLOC_ERROR,fatal:!1,error:le,bytes:P,reason:`fail allocating audio mdat ${P}`});return}m||(new DataView(T.buffer).setUint32(0,P),T.set(mr.types.mdat,4))}else return;T.set(ue,y);const ee=ue.byteLength;y+=ee,p.push(ibt(!0,d,ee,0)),A=ne}const I=p.length;if(!I)return;const D=p[p.length-1];b=A-v,this.nextAudioTs=b+c*D.duration;const B=m?new Uint8Array(0):mr.moof(t.sequenceNumber++,C/c,dh({},t,{samples:p}));t.samples=[];const q=(C-v)/l,W=this.nextAudioTs/l,K={data1:B,data2:T,startPTS:q,endPTS:W,startDTS:q,endDTS:W,type:"audio",hasAudio:!0,hasVideo:!1,nb:I};return this.isAudioContiguous=!0,K}}function F_(s,t){let n;if(t===null)return s;for(t4294967296;)s+=n;return s}function EBn(s){for(let t=0;tl.pts-o.pts);const i=s.samples;return s.samples=[],{samples:i}}class TBn extends v2{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=wHt(t);if(n)g9n(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=obt(i,kh.AUDIO,this)),l&&(a=obt(l,kh.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};Mi(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 x=this.initData;if((o=x)!=null&&o.length||(this.generateInitSegment(m),x=this.initData),!((c=x)!=null&&c.length))return this.warn("Failed to generate initSegment."),h;this.emitInitSegment&&(p.tracks=this.initTracks,this.emitInitSegment=!1);const g=v9n(m,x,this),y=x.audio?g[x.audio.id]:null,b=x.video?g[x.video.id]:null,v=Eae(b,1/0),N=Eae(y,1/0),C=Eae(b,0,!0),A=Eae(y,0,!0);let T=i,P=0;const M=y&&(!b||!d&&N0?this.lastEndTime=B:(this.warn("Duration parsed from mp4 should be greater than zero"),this.resetNextTimestamp());const q=!!x.audio,W=!!x.video;let V="";q&&(V+="audio"),W&&(V+="video");const K=(x.audio?x.audio.encrypted:!1)||(x.video?x.video.encrypted:!1),Q={data1:m,startPTS:D,startDTS:D,endPTS:B,endDTS:B,type:V,hasAudio:q,hasVideo:W,nb:1,dropped:0,encrypted:K};h.audio=q&&!W?Q:void 0,h.video=W?Q:void 0;const J=b==null?void 0:b.sampleCount;if(J){const ce=b.keyFrameIndex,ue=ce!==-1;Q.nb=J,Q.dropped=ce===0||this.isVideoContiguous?0:ue?ce:J,Q.independent=ue,Q.firstKeyFrame=ce,ue&&b.keyFrameStart&&(Q.firstKeyFramePTS=(b.keyFrameStart-d.baseTime)/d.timescale),this.isVideoContiguous||(h.independent=ue),this.isVideoContiguous||(this.isVideoContiguous=ue),Q.dropped&&this.warn(`fmp4 does not start with IDR: firstIDR ${ce}/${J} dropped: ${Q.dropped} start: ${Q.firstKeyFramePTS||"NA"}`)}return h.initSegment=p,h.id3=fGt(r,i,d,d),a.samples.length&&(h.text=xGt(a,i,d)),h}}function Eae(s,t,n=!1){return(s==null?void 0:s.start)!==void 0?(s.start+(n?s.duration:0))/s.timescale:t}function MBn(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 obt(s,t,n){const r=s.codec;return r&&r.length>4?r:t===kh.AUDIO?r==="ec-3"||r==="ac-3"||r==="alac"?r:r==="fLaC"||r==="Opus"?B4e(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 G4;try{G4=self.performance.now.bind(self.performance)}catch{G4=Date.now}const FNe=[{demux:xBn,remux:TBn},{demux:KA,remux:ONe},{demux:hBn,remux:ONe},{demux:pBn,remux:ONe}];FNe.splice(2,0,{demux:mBn,remux:ONe});class lbt{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=G4();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:x}=a||o,{audioCodec:g,videoCodec:y,defaultInitPts:b,duration:v,initSegmentData:N}=c,C=LBn(l,n);if(C&&jB(C.method)){const M=this.getDecrypter(),I=LXe(C.method);if(M.isSync()){let D=M.softwareDecrypt(l,C.key.buffer,C.iv.buffer,I);if(r.part>-1){const q=M.flush();D=q&&q.buffer}if(!D)return i.executeEnd=G4(),GDe(r);l=new Uint8Array(D)}else return this.asyncResult=!0,this.decryptionPromise=M.webCryptoDecrypt(l,C.key.buffer,C.iv.buffer,I).then(D=>{const B=this.push(D,null,r);return this.decryptionPromise=null,B}),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(Dt.ERROR,Dt.ERROR,{type:mo.MEDIA_ERROR,details:fr.FRAG_PARSING_ERROR,fatal:!1,error:M,reason:M.message}),i.executeEnd=G4(),GDe(r)}(u||h||x||A)&&this.resetInitSegment(N,g,y,v,n),(u||x||A)&&this.resetInitialTimestamp(b),d||this.resetContiguity();const T=this.transmux(l,C,p,m,r);this.asyncResult=yQ(T);const P=this.currentTransmuxState;return P.contiguous=!0,P.discontinuity=!1,P.trackSwitch=!1,i.executeEnd=G4(),T}flush(t){const n=t.transmuxing;n.executeStart=G4();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=G4();const h=[GDe(t)];return this.asyncResult?Promise.resolve(h):h}const u=c.flush(o);return yQ(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===Gi.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=G4()}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=FNe.length;h0&&(t==null?void 0:t.key)!=null&&t.iv!==null&&t.method!=null&&(n=t),n}const GDe=s=>({remuxResult:{},chunkMeta:s});function yQ(s){return"then"in s&&s.then instanceof Function}class PBn{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 IBn{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 cbt=0;class gGt{constructor(t,n,r,a){this.error=null,this.hls=void 0,this.id=void 0,this.instanceNo=cbt++,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(Dt.ERROR,{type:mo.OTHER_ERROR,details:fr.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===Dt.ERROR&&(d=d,d.parent=this.id,d.part=this.part,this.error=d.error),this.hls.trigger(c,d)};this.observer=new DXe,this.observer.on(Dt.FRAG_DECRYPTED,l),this.observer.on(Dt.ERROR,l);const o=N1t(i.preferManagedMediaSource);if(this.useWorker&&typeof Worker<"u"){const c=this.hls.logger;if(i.workerPath||Fzn()){try{i.workerPath?(c.log(`loading Web Worker ${i.workerPath} for "${n}"`),this.workerContext=Bzn(i.workerPath)):(c.log(`injecting Web Worker for "${n}"`),this.workerContext=zzn());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:Lh(i)})}catch(u){c.warn(`Error setting up "${n}" Web Worker, fallback to inline`,u),this.terminateWorker(),this.error=null,this.transmuxer=new lbt(this.observer,o,i,"",n,t.logger)}return}}this.transmuxer=new lbt(this.observer,o,i,"",n,t.logger)}reset(){if(this.frag=null,this.part=null,this.workerContext){const t=this.instanceNo;this.instanceNo=cbt++;const n=this.hls.config,r=N1t(n.preferManagedMediaSource);this.workerContext.worker.postMessage({instanceNo:this.instanceNo,cmd:"reset",resetNo:t,typeSupported:r,id:this.id,config:Lh(n)})}}terminateWorker(){if(this.workerContext){const{worker:t}=this.workerContext;this.workerContext=null,t.removeEventListener("message",this.onWorkerMessage),t.removeEventListener("error",this.onWorkerError),$zn(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:x}=this,g=l?l.start:i.start,y=i.decryptdata,b=this.frag,v=!(b&&i.cc===b.cc),N=!(b&&d.level===b.level),C=b?d.sn-b.sn:-1,A=this.part?d.part-this.part.index:-1,T=C===0&&d.id>1&&d.id===(b==null?void 0:b.stats.chunkCount),P=!N&&(C===1||C===0&&(A===1||T&&A<=0)),M=self.performance.now();(N||C||i.stats.parsing.start===0)&&(i.stats.parsing.start=M),l&&(A||!P)&&(l.stats.parsing.start=M);const I=!(b&&((h=i.initSegment)==null?void 0:h.url)===((m=b.initSegment)==null?void 0:m.url)),D=new IBn(v,P,c,N,g,I);if(!P||v||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===Gi.MAIN?"level":"track"}: ${d.level} id: ${d.id} discontinuity: ${v} trackSwitch: ${N} contiguous: ${P} accurateTimeOffset: ${c} timeOffset: ${g} initSegmentChange: ${I}`);const B=new PBn(r,a,n,o,u);this.configureTransmuxer(B)}if(this.frag=i,this.part=l,this.workerContext)this.workerContext.worker.postMessage({instanceNo:p,cmd:"demux",data:t,decryptdata:y,chunkMeta:d,state:D},t instanceof ArrayBuffer?[t]:[]);else if(x){const B=x.push(t,y,d,D);yQ(B)?B.then(q=>{this.handleTransmuxComplete(q)}).catch(q=>{this.transmuxerError(q,d,"transmuxer-interface push error")}):this.handleTransmuxComplete(B)}}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);yQ(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(Dt.ERROR,{type:mo.MEDIA_ERROR,details:fr.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 dbt=100;class DBn extends IXe{constructor(t,n,r){super(t,n,r,"audio-stream-controller",Gi.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(Dt.LEVEL_LOADED,this.onLevelLoaded,this),t.on(Dt.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),t.on(Dt.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.on(Dt.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),t.on(Dt.BUFFER_RESET,this.onBufferReset,this),t.on(Dt.BUFFER_CREATED,this.onBufferCreated,this),t.on(Dt.BUFFER_FLUSHING,this.onBufferFlushing,this),t.on(Dt.BUFFER_FLUSHED,this.onBufferFlushed,this),t.on(Dt.INIT_PTS_FOUND,this.onInitPtsFound,this),t.on(Dt.FRAG_LOADING,this.onFragLoading,this),t.on(Dt.FRAG_BUFFERED,this.onFragBuffered,this)}unregisterListeners(){const{hls:t}=this;t&&(super.unregisterListeners(),t.off(Dt.LEVEL_LOADED,this.onLevelLoaded,this),t.off(Dt.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),t.off(Dt.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.off(Dt.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),t.off(Dt.BUFFER_RESET,this.onBufferReset,this),t.off(Dt.BUFFER_CREATED,this.onBufferCreated,this),t.off(Dt.BUFFER_FLUSHING,this.onBufferFlushing,this),t.off(Dt.BUFFER_FLUSHED,this.onBufferFlushed,this),t.off(Dt.INIT_PTS_FOUND,this.onInitPtsFound,this),t.off(Dt.FRAG_LOADING,this.onFragLoading,this),t.off(Dt.FRAG_BUFFERED,this.onFragBuffered,this))}onInitPtsFound(t,{frag:n,id:r,initPTS:a,timescale:i,trackId:l}){if(r===Gi.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===ea.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===ea.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=PHt(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===ea.IDLE&&this.doTickIdle())}startLoad(t,n){if(!this.levels){this.startPosition=t,this.state=ea.STOPPED;return}const r=this.lastCurrentTime;this.stopLoad(),this.setInterval(dbt),r>0&&t===-1?(this.log(`Override startPosition with lastCurrentTime @${r.toFixed(3)}`),t=r,this.state=ea.IDLE):this.state=ea.WAITING_TRACK,this.nextLoadPosition=this.lastCurrentTime=t+this.timelineOffset,this.startPosition=n?-1:t,this.tick()}doTick(){switch(this.state){case ea.IDLE:this.doTickIdle();break;case ea.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=ea.WAITING_INIT_PTS}break}case ea.FRAG_LOADING_WAITING_RETRY:{this.checkRetryDate();break}case ea.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=ea.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=ea.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=ea.WAITING_TRACK,this.startFragRequested=!1;return}const d=this.mediaBuffer?this.mediaBuffer:this.media;this.bufferFlushed&&d&&(this.bufferFlushed=!1,this.afterBufferFlushed(d,kh.AUDIO,Gi.AUDIO));const u=this.getFwdBufferInfo(d,Gi.AUDIO);if(u===null)return;if(!this.switchingTrack&&this._streamEnded(u,c)){n.trigger(Dt.BUFFER_EOS,{type:"audio"}),this.state=ea.ENDED;return}const h=u.len,m=n.maxBufferLength,p=c.fragments,x=p[0].start,g=this.getLoadPosition(),y=this.flushing?g:u.end;if(this.switchingTrack&&a){const N=g;c.PTSKnown&&Nx||u.nextStart)&&(this.log("Alt audio track ahead of main track, seek to start of alt audio track"),a.currentTime=x+.05)}if(h>=m&&!this.switchingTrack&&yv.end){const C=this.fragmentTracker.getFragAtPos(y,Gi.MAIN);C&&C.end>v.end&&(v=C,this.mainFragLoading={frag:C,targetBufferTime:null})}if(b.start>v.end)return}this.loadFragment(b,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 fQ(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!==ea.STOPPED&&(this.setInterval(dbt),this.state=ea.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(Dt.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!==ea.STOPPED&&(this.state=ea.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||(XHt(i,d),i.alignedSliding||W4e(i,d),h=i.fragmentStart)}u.details=i,this.levelLastLoaded=u,this.startFragRequested||this.setStartPosition(d,h),this.hls.trigger(Dt.AUDIO_TRACK_UPDATED,{details:i,id:l,groupId:n.groupId}),this.state===ea.WAITING_TRACK&&!this.waitForCdnTuneIn(i)&&(this.state=ea.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 gGt(this.hls,Gi.AUDIO,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)));const p=this.initPTS[r.cc],x=(n=r.initSegment)==null?void 0:n.data;if(p!==void 0){const y=a?a.index:-1,b=y!==-1,v=new MXe(r.level,r.sn,r.stats.chunkCount,i.byteLength,y,b);m.push(i,x,h,"",r,a,u.totalduration,!1,v,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:g}=this.waitingData=this.waitingData||{frag:r,part:a,cache:new QHt,complete:!1};g.push(new Uint8Array(i)),this.state!==ea.STOPPED&&(this.state=ea.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===Gi.MAIN&&Jf(n.frag)&&(this.mainFragLoading=n,this.state===ea.IDLE&&this.tick())}onFragBuffered(t,n){const{frag:r,part:a}=n;if(r.type!==Gi.AUDIO){!this.audioOnly&&r.type===Gi.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(Jf(r)){this.fragPrevious=r;const i=this.switchingTrack;i&&(this.bufferedTrack=i,this.switchingTrack=null,this.hls.trigger(Dt.AUDIO_TRACK_SWITCHED,qu({},i)))}this.fragBufferedComplete(r,a),this.media&&this.tick()}onError(t,n){var r;if(n.fatal){this.state=ea.ERROR;return}switch(n.details){case fr.FRAG_GAP:case fr.FRAG_PARSING_ERROR:case fr.FRAG_DECRYPT_ERROR:case fr.FRAG_LOAD_ERROR:case fr.FRAG_LOAD_TIMEOUT:case fr.KEY_LOAD_ERROR:case fr.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(Gi.AUDIO,n);break;case fr.AUDIO_TRACK_LOAD_ERROR:case fr.AUDIO_TRACK_LOAD_TIMEOUT:case fr.LEVEL_PARSING_ERROR:!n.levelRetry&&this.state===ea.WAITING_TRACK&&((r=n.context)==null?void 0:r.type)===$c.AUDIO_TRACK&&(this.state=ea.IDLE);break;case fr.BUFFER_ADD_CODEC_ERROR:case fr.BUFFER_APPEND_ERROR:if(n.parent!=="audio")return;this.reduceLengthAndFlushBuffer(n)||this.resetLoadingState();break;case fr.BUFFER_FULL_ERROR:if(n.parent!=="audio")return;this.reduceLengthAndFlushBuffer(n)&&(this.bufferedTrack=null,super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio"));break;case fr.INTERNAL_EXCEPTION:this.recoverWorkerError(n);break}}onBufferFlushing(t,{type:n}){n!==kh.VIDEO&&(this.flushing=!0)}onBufferFlushed(t,{type:n}){if(n!==kh.VIDEO){this.flushing=!1,this.bufferFlushed=!0,this.state===ea.ENDED&&(this.state=ea.IDLE);const r=this.mediaBuffer||this.media;r&&(this.afterBufferFlushed(r,n,Gi.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:x,initSegment:g}=i;if(this.fragContextChanged(c)||!h){this.fragmentTracker.removeFragment(c);return}if(this.state=ea.PARSING,this.switchingTrack&&m&&this.completeAudioSwitch(this.switchingTrack),g!=null&&g.tracks){const y=c.initSegment||c;if(this.unhandledEncryptionError(g,c))return;this._bufferInitSegment(u,g.tracks,y,l),a.trigger(Dt.FRAG_PARSING_INIT_SEGMENT,{frag:y,id:r,tracks:g.tracks})}if(m){const{startPTS:y,endPTS:b,startDTS:v,endDTS:N}=m;d&&(d.elementaryStreams[kh.AUDIO]={startPTS:y,endPTS:b,startDTS:v,endDTS:N}),c.setElementaryStreamInfo(kh.AUDIO,y,b,v,N),this.bufferFragmentData(m,c,d,l)}if(x!=null&&(n=x.samples)!=null&&n.length){const y=dh({id:r,frag:c,details:h},x);a.trigger(Dt.FRAG_PARSING_METADATA,y)}if(p){const y=dh({id:r,frag:c,details:h},p);a.trigger(Dt.FRAG_PARSING_USERDATA,y)}}_bufferInitSegment(t,n,r,a){if(this.state!==ea.PARSING||(n.video&&delete n.video,n.audiovideo&&delete n.audiovideo,!n.audio))return;const i=n.audio;i.id=Gi.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(Dt.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(Dt.BUFFER_APPENDING,c)}this.tickImmediate()}loadFragment(t,n,r){const a=this.fragmentTracker.getState(t);if(this.switchingTrack||a===ug.NOT_LOADED||a===ug.PARTIAL){var i;if(!Jf(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=ea.WAITING_INIT_PTS;const l=this.mainDetails;l&&l.fragmentStart!==n.details.fragmentStart&&W4e(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;ZR({name:n,lang:r,assocLang:a,characteristics:i,audioCodec:l,channels:o},t,x8)||(U4e(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(Dt.AUDIO_TRACK_SWITCHED,qu({},t))}}class UXe extends v2{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&&k1t(r);return new S1t(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){Czn(r,a,this);const v=a.playlistParsingError;if(v){this.warn(v);const N=this.hls;if(!N.config.ignorePlaylistParsingErrors){var d;const{networkDetails:C}=n;N.trigger(Dt.ERROR,{type:mo.NETWORK_ERROR,details:fr.LEVEL_PARSING_ERROR,fatal:!1,url:a.url,error:v,reason:v.message,level:n.level||void 0,parent:(d=a.fragments[0])==null?void 0:d.type,networkDetails:C,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,x=GHt(a,p);if(a.requestScheduled+x0){if(I>a.targetduration*3)this.log(`Playlist last advanced ${M.toFixed(2)}s ago. Omitting segment and part directives.`),y=void 0,b=void 0;else if(r!=null&&r.tuneInGoal&&I-a.partTarget>r.tuneInGoal)this.warn(`CDN Tune-in goal increased from: ${r.tuneInGoal} to: ${D} with playlist age: ${a.age}`),D=0;else{const B=Math.floor(D/a.targetduration);if(y+=B,b!==void 0){const q=Math.round(D%a.targetduration/a.partTarget);b+=q}this.log(`CDN Tune-in age: ${a.ageHeader}s last advanced ${M.toFixed(2)}s goal: ${D} skip sn ${B} to part ${b}`)}a.tuneInGoal=D}if(g=this.getDeliveryDirectives(a,n.deliveryDirectives,y,b),v||!P){a.requestScheduled=l,this.loadingPlaylist(u,g);return}}else(a.canBlockReload||a.canSkipUntil)&&(g=this.getDeliveryDirectives(a,n.deliveryDirectives,y,b));g&&y!==void 0&&a.canBlockReload&&(a.requestScheduled=i.loading.first+Math.max(x-o*2,x/2)),this.scheduleLoading(u,g,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=k1t(t);return n!=null&&n.skip&&t.deltaUpdateFailed&&(r=n.msn,a=n.part,i=DNe.No),new S1t(r,a,i)}checkRetry(t){const n=t.details,r=q4e(t),a=t.errorAction,{action:i,retryCount:l=0,retryConfig:o}=a||{},c=!!a&&!!o&&(i===oy.RetryRequest||!a.resolved&&i===oy.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=EXe(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 yGt(s,t){if(s.length!==t.length)return!1;for(let n=0;ns[a]!==t[a])}function TUe(s,t){return t.label.toLowerCase()===s.name.toLowerCase()&&(!t.language||t.language.toLowerCase()===(s.lang||"").toLowerCase())}class RBn extends UXe{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(Dt.MANIFEST_LOADING,this.onManifestLoading,this),t.on(Dt.MANIFEST_PARSED,this.onManifestParsed,this),t.on(Dt.LEVEL_LOADING,this.onLevelLoading,this),t.on(Dt.LEVEL_SWITCHING,this.onLevelSwitching,this),t.on(Dt.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),t.on(Dt.ERROR,this.onError,this)}unregisterListeners(){const{hls:t}=this;t.off(Dt.MANIFEST_LOADING,this.onManifestLoading,this),t.off(Dt.MANIFEST_PARSED,this.onManifestParsed,this),t.off(Dt.LEVEL_LOADING,this.onLevelLoading,this),t.off(Dt.LEVEL_SWITCHING,this.onLevelSwitching,this),t.off(Dt.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),t.off(Dt.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=KS(c,o,x8);if(m>-1)i=o[m];else{const p=KS(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(Dt.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(Dt.ERROR,{type:mo.MEDIA_ERROR,details:fr.AUDIO_TRACK_LOAD_ERROR,fatal:!0,error:m})}}}onError(t,n){n.fatal||!n.context||n.context.type===$c.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&&ZR(t,a,x8))return a;const i=KS(t,this.tracksInGroup,x8);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=K9n(t,n.levels,r,l,x8);if(o===-1)return null;n.nextLoadLevel=o}if(t.channels||t.audioCodec){const l=KS(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(Dt.AUDIO_TRACK_SWITCHING,qu({},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 ubt=/(avc[1234]|hvc1|hev1|dvh[1e]|vp09|av01)(?:\.[^.,]+)+/,vGt="HlsJsTrackRemovedError";class FBn extends Error{constructor(t){super(t),this.name=vGt}}class zBn extends v2{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(Dt.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=o9n(f6(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(Dt.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on(Dt.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(Dt.MANIFEST_LOADING,this.onManifestLoading,this),t.on(Dt.MANIFEST_PARSED,this.onManifestParsed,this),t.on(Dt.BUFFER_RESET,this.onBufferReset,this),t.on(Dt.BUFFER_APPENDING,this.onBufferAppending,this),t.on(Dt.BUFFER_CODECS,this.onBufferCodecs,this),t.on(Dt.BUFFER_EOS,this.onBufferEos,this),t.on(Dt.BUFFER_FLUSHING,this.onBufferFlushing,this),t.on(Dt.LEVEL_UPDATED,this.onLevelUpdated,this),t.on(Dt.FRAG_PARSED,this.onFragParsed,this),t.on(Dt.FRAG_CHANGED,this.onFragChanged,this),t.on(Dt.ERROR,this.onError,this)}unregisterListeners(){const{hls:t}=this;t.off(Dt.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off(Dt.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(Dt.MANIFEST_LOADING,this.onManifestLoading,this),t.off(Dt.MANIFEST_PARSED,this.onManifestParsed,this),t.off(Dt.BUFFER_RESET,this.onBufferReset,this),t.off(Dt.BUFFER_APPENDING,this.onBufferAppending,this),t.off(Dt.BUFFER_CODECS,this.onBufferCodecs,this),t.off(Dt.BUFFER_EOS,this.onBufferEos,this),t.off(Dt.BUFFER_FLUSHING,this.onBufferFlushing,this),t.off(Dt.LEVEL_UPDATED,this.onLevelUpdated,this),t.off(Dt.FRAG_PARSED,this.onFragParsed,this),t.off(Dt.FRAG_CHANGED,this.onFragChanged,this),t.off(Dt.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?dh(r,a.tracks):this.sourceBuffers.forEach(i=>{const[l]=i;l&&(r[l]=dh({},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=f6(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,hbt(r),BBn(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: ${Lh(r,(c,d)=>c==="initSegment"?void 0:d)}; transfer tracks: ${Lh(a,(c,d)=>c==="initSegment"?void 0:d)}}`),!fHt(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(Dt.MEDIA_DETACHING,{}),this.onMediaAttaching(Dt.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=Bl.getBuffered(h);m.detectEvictedFragments(d,y,p,null,!0)}const x=WDe(d),g=[d,h];this.sourceBuffers[x]=g,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&&hbt(a),a.load()):this.warn("media|source.src was changed by a third party - skip cleanup")),this.media=null),this.hls.trigger(Dt.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[WDe(t)]=[null,null];const n=this.tracks[t];n&&(n.buffer=void 0)}resetQueue(){this.operationQueue&&this.operationQueue.destroy(),this.operationQueue=new OBn(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:x,container:g,metadata:y,supplemental:b}=h;let v=a[c];const N=(d=this.transferData)==null||(d=d.tracks)==null?void 0:d[c],C=N!=null&&N.buffer?N:v,A=(C==null?void 0:C.pendingCodec)||(C==null?void 0:C.codec),T=C==null?void 0:C.levelCodec;v||(v=a[c]={buffer:void 0,listeners:[],codec:p,supplemental:b,container:g,levelCodec:x,metadata:y,id:m});const P=INe(A,T),M=P==null?void 0:P.replace(ubt,"$1");let I=INe(p,x);const D=(u=I)==null?void 0:u.replace(ubt,"$1");I&&P&&M!==D&&(c.slice(0,5)==="audio"&&(I=B4e(I,this.appendSource)),this.log(`switching codec ${A} to ${I}`),I!==(v.pendingCodec||v.codec)&&(v.pendingCodec=I),v.container=g,this.appendChangeType(c,g,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,Gi.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&&Bl.isBuffered(c.buffer,a)||((o=this.fragmentTracker.getAppendedFrag(a,Gi.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,x=self.performance.now();h.start=x;const g=o.stats.buffering,y=c?c.stats.buffering:null;g.start===0&&(g.start=x),y&&y.start===0&&(y.start=x);const b=r.audio;let v=!1;i==="audio"&&(b==null?void 0:b.container)==="audio/mpeg"&&(v=!this.lastMpegAudioChunk||d.id===1||this.lastMpegAudioChunk.sn!==d.sn,this.lastMpegAudioChunk=d);const N=r.video,C=N==null?void 0:N.buffer;if(C&&m!=="initSegment"){const P=c||o,M=this.blockedAudioAppend;if(i==="audio"&&l!=="main"&&!this.blockedAudioAppend&&!(N.ending||N.ended)){const D=P.start+P.duration*.05,B=C.buffered,q=this.currentOp("video");!B.length&&!q?this.blockAudio(P):!q&&!Bl.isBuffered(C,D)&&this.lastVideoAppendEndD||I{var P;h.executeStart=self.performance.now();const M=(P=this.tracks[i])==null?void 0:P.buffer;M&&(v?this.updateTimestampOffset(M,A,.1,i,m,p):u!==void 0&&Mi(u)&&this.updateTimestampOffset(M,u,1e-6,i,m,p)),this.appendExecutor(a,i)},onStart:()=>{},onComplete:()=>{const P=self.performance.now();h.executeEnd=h.end=P,g.first===0&&(g.first=P),y&&y.first===0&&(y.first=P);const M={};this.sourceBuffers.forEach(([I,D])=>{I&&(M[I]=Bl.getBuffered(D))}),this.appendErrors[i]=0,i==="audio"||i==="video"?this.appendErrors.audiovideo=0:(this.appendErrors.audio=0,this.appendErrors.video=0),this.hls.trigger(Dt.BUFFER_APPENDED,{type:i,frag:o,part:c,chunkMeta:d,parent:o.type,timeRanges:M})},onError:P=>{var M;const I={type:mo.MEDIA_ERROR,parent:o.type,details:fr.BUFFER_APPEND_ERROR,sourceBufferName:i,frag:o,part:c,chunkMeta:d,error:P,err:P,fatal:!1},D=(M=this.media)==null?void 0:M.error;if(P.code===DOMException.QUOTA_EXCEEDED_ERR||P.name=="QuotaExceededError"||"quota"in P)I.details=fr.BUFFER_FULL_ERROR;else if(P.code===DOMException.INVALID_STATE_ERR&&this.mediaSourceOpenOrEnded&&!D)I.errorAction=wB(!0);else if(P.name===vGt&&this.sourceBufferCount===0)I.errorAction=wB(!0);else{const B=++this.appendErrors[i];this.warn(`Failed ${B}/${this.hls.config.appendErrorMaxRetry} times to append segment in "${i}" sourceBuffer (${D||"no media error"})`),(B>=this.hls.config.appendErrorMaxRetry||D)&&(I.fatal=!0)}this.hls.trigger(Dt.ERROR,I)}};this.log(`queuing "${i}" append sn: ${m}${c?" p: "+c.index:""} of ${o.type===Gi.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(Dt.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[kh.AUDIOVIDEO]?i.push("audiovideo"):(l[kh.AUDIO]&&i.push("audio"),l[kh.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(Dt.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(Dt.BUFFERED_TO_END,void 0)})):(this.tracksEnded(),this.hls.trigger(Dt.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===fr.BUFFER_APPEND_ERROR&&n.frag){var r;const a=(r=n.errorAction)==null?void 0:r.nextAutoLevel;Mi(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(Mi(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(Mi(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=Bl.getBuffered(i);if(o.length>0&&r>o.start(0)){var l;this.hls.trigger(Dt.BACK_BUFFER_REACHED,{bufferEnd:r});const c=this.tracks[a];if((l=this.details)!=null&&l.live)this.hls.trigger(Dt.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(Dt.BUFFER_FLUSHING,{startOffset:0,endOffset:r,type:a})}}})}flushFrontBuffer(t,n,r){this.sourceBuffers.forEach(([a,i])=>{if(i){const l=Bl.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(Dt.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 Mi(i)?{duration:i}:null;const l=this.media.duration,o=Mi(r.duration)?r.duration:0;return a>o&&a>l||!Mi(l)?{duration:a}:null}updateMediaSource({duration:t,start:n,end:r}){const a=this.mediaSource;!this.media||!a||a.readyState!=="open"||(a.duration!==t&&(Mi(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}) ${Lh(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(Dt.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(Dt.ERROR,{type:mo.MEDIA_ERROR,details:fr.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":""} ${Lh(o)}`);try{const u=r.addSourceBuffer(d),h=WDe(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(Dt.ERROR,{type:mo.MEDIA_ERROR,details:fr.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")&&mQ(r,"video")&&(a=E9n(a,r));const i=INe(a,t.levelCodec);return i?n.slice(0,5)==="audio"?B4e(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(Dt.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(Dt.ERROR,{type:mo.MEDIA_ERROR,details:fr.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=Mi(a.duration)?a.duration:1/0,d=Mi(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 FBn(`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 hbt(s){const t=s.querySelectorAll("source");[].slice.call(t).forEach(n=>{s.removeChild(n)})}function BBn(s,t){const n=self.document.createElement("source");n.type="video/mp4",n.src=t,s.appendChild(n)}function WDe(s){return s==="audio"?1:0}class qXe{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(Dt.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),t.on(Dt.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on(Dt.MANIFEST_PARSED,this.onManifestParsed,this),t.on(Dt.LEVELS_UPDATED,this.onLevelsUpdated,this),t.on(Dt.BUFFER_CODECS,this.onBufferCodecs,this),t.on(Dt.MEDIA_DETACHING,this.onMediaDetaching,this)}unregisterListener(){const{hls:t}=this;t.off(Dt.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),t.off(Dt.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off(Dt.MANIFEST_PARSED,this.onManifestParsed,this),t.off(Dt.LEVELS_UPDATED,this.onLevelsUpdated,this),t.off(Dt.BUFFER_CODECS,this.onBufferCodecs,this),t.off(Dt.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&&Mi(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,qXe.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 $Bn={MANIFEST:"m",AUDIO:"a",VIDEO:"v",MUXED:"av",INIT:"i",CAPTION:"c",TIMED_TEXT:"tt",KEY:"k",OTHER:"o"},sb=$Bn,UBn={HLS:"h"},qBn=UBn;class A5{constructor(t,n){Array.isArray(t)&&(t=t.map(r=>r instanceof A5?r:new A5(r))),this.value=t,this.params=n}}const VBn="Dict";function HBn(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 GBn(s,t,n,r){return new Error(`failed to ${s} "${HBn(t)}" as ${n}`,{cause:r})}function E5(s,t,n){return GBn("serialize",s,t,n)}class bGt{constructor(t){this.description=t}}const mbt="Bare Item",WBn="Boolean";function KBn(s){if(typeof s!="boolean")throw E5(s,WBn);return s?"?1":"?0"}function YBn(s){return btoa(String.fromCharCode(...s))}const ZBn="Byte Sequence";function XBn(s){if(ArrayBuffer.isView(s)===!1)throw E5(s,ZBn);return`:${YBn(s)}:`}const QBn="Integer";function JBn(s){return s<-999999999999999||99999999999999912)throw E5(s,t$n);const n=t.toString();return n.includes(".")?n:`${n}.0`}const n$n="String",r$n=/[\x00-\x1f\x7f]+/;function a$n(s){if(r$n.test(s))throw E5(s,n$n);return`"${s.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`}function i$n(s){return s.description||s.toString().slice(7,-1)}const o$n="Token";function pbt(s){const t=i$n(s);if(/^([a-zA-Z*])([!#$%&'*+\-.^_`|~\w:/]*)$/.test(t)===!1)throw E5(t,o$n);return t}function MUe(s){switch(typeof s){case"number":if(!Mi(s))throw E5(s,mbt);return Number.isInteger(s)?_Gt(s):s$n(s);case"string":return a$n(s);case"symbol":return pbt(s);case"boolean":return KBn(s);case"object":if(s instanceof Date)return e$n(s);if(s instanceof Uint8Array)return XBn(s);if(s instanceof bGt)return pbt(s);default:throw E5(s,mbt)}}const l$n="Key";function LUe(s){if(/^[a-z*][a-z0-9\-_.*]*$/.test(s)===!1)throw E5(s,l$n);return s}function VXe(s){return s==null?"":Object.entries(s).map(([t,n])=>n===!0?`;${LUe(t)}`:`;${LUe(t)}=${MUe(n)}`).join("")}function jGt(s){return s instanceof A5?`${MUe(s.value)}${VXe(s.params)}`:MUe(s)}function c$n(s){return`(${s.value.map(jGt).join(" ")})${VXe(s.params)}`}function d$n(s,t={whitespace:!0}){if(typeof s!="object"||s==null)throw E5(s,VBn);const n=s instanceof Map?s.entries():Object.entries(s),r=t!=null&&t.whitespace?" ":"";return Array.from(n).map(([a,i])=>{i instanceof A5||(i=new A5(i));let l=LUe(a);return i.value===!0?l+=VXe(i.params):(l+="=",Array.isArray(i.value)?l+=c$n(i):l+=jGt(i)),l}).join(`,${r}`)}function NGt(s,t){return d$n(s,t)}const Hk="CMCD-Object",df="CMCD-Request",VM="CMCD-Session",pA="CMCD-Status",u$n={br:Hk,ab:Hk,d:Hk,ot:Hk,tb:Hk,tpb:Hk,lb:Hk,tab:Hk,lab:Hk,url:Hk,pb:df,bl:df,tbl:df,dl:df,ltc:df,mtp:df,nor:df,nrr:df,rc:df,sn:df,sta:df,su:df,ttfb:df,ttfbb:df,ttlb:df,cmsdd:df,cmsds:df,smrt:df,df,cs:df,ts:df,cid:VM,pr:VM,sf:VM,sid:VM,st:VM,v:VM,msd:VM,bs:pA,bsd:pA,cdn:pA,rtp:pA,bg:pA,pt:pA,ec:pA,e:pA},h$n={REQUEST:df};function m$n(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 p$n(s,t){const n={};if(!s)return n;const r=Object.keys(s),a=t?m$n(t):{};return r.reduce((i,l)=>{var o;const c=u$n[l]||a[l]||h$n.REQUEST,d=(o=i[c])!==null&&o!==void 0?o:i[c]={};return d[l]=s[l],i},n)}function f$n(s){return["ot","sf","st","e","sta"].includes(s)}function x$n(s){return typeof s=="number"?Mi(s):s!=null&&s!==""&&s!==!1}const kGt="event";function g$n(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 zNe=s=>Math.round(s),PUe=(s,t)=>Array.isArray(s)?s.map(n=>PUe(n,t)):s instanceof A5&&typeof s.value=="string"?new A5(PUe(s.value,t),s.params):(t.baseUrl&&(s=g$n(s,t.baseUrl)),t.version===1?encodeURIComponent(s):s),Tae=s=>zNe(s/100)*100,y$n=(s,t)=>{let n=s;return t.version>=2&&(s instanceof A5&&typeof s.value=="string"?n=new A5([s]):typeof s=="string"&&(n=[s])),PUe(n,t)},v$n={br:zNe,d:zNe,bl:Tae,dl:Tae,mtp:Tae,nor:y$n,rtp:Tae,tb:zNe},SGt="request",CGt="response",HXe=["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"],b$n=["e"],_$n=/^[a-zA-Z0-9-.]+-[a-zA-Z0-9-.]+$/;function DTe(s){return _$n.test(s)}function w$n(s){return HXe.includes(s)||b$n.includes(s)||DTe(s)}const AGt=["d","dl","nor","ot","rtp","su"];function j$n(s){return HXe.includes(s)||AGt.includes(s)||DTe(s)}const N$n=["cmsdd","cmsds","rc","smrt","ttfb","ttfbb","ttlb","url"];function k$n(s){return HXe.includes(s)||AGt.includes(s)||N$n.includes(s)||DTe(s)}const S$n=["bl","br","bs","cid","d","dl","mtp","nor","nrr","ot","pr","rtp","sf","sid","st","su","tb","v"];function C$n(s){return S$n.includes(s)||DTe(s)}const A$n={[CGt]:k$n,[kGt]:w$n,[SGt]:j$n};function EGt(s,t={}){const n={};if(s==null||typeof s!="object")return n;const r=t.version||s.v||1,a=t.reportingMode||SGt,i=r===1?C$n:A$n[a];let l=Object.keys(s).filter(i);const o=t.filter;typeof o=="function"&&(l=l.filter(o));const c=a===CGt||a===kGt;c&&!l.includes("ts")&&l.push("ts"),r>1&&!l.includes("v")&&l.push("v");const d=dh({},v$n,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"&&!Mi(m)&&(m=Date.now()),x$n(m)&&(f$n(h)&&typeof m=="string"&&(m=new bGt(m)),n[h]=m))}),n}function E$n(s,t={}){const n={};if(!s)return n;const r=EGt(s,t),a=p$n(r,t==null?void 0:t.customHeaderMap);return Object.entries(a).reduce((i,[l,o])=>{const c=NGt(o,{whitespace:!1});return c&&(i[l]=c),i},n)}function T$n(s,t,n){return dh(s,E$n(t,n))}const M$n="CMCD";function L$n(s,t={}){return s?NGt(EGt(s,t),{whitespace:!1}):""}function P$n(s,t={}){if(!s)return"";const n=L$n(s,t);return encodeURIComponent(n)}function I$n(s,t={}){if(!s)return"";const n=P$n(s,t);return`${M$n}=${n}`}const fbt=/CMCD=[^&#]+/;function D$n(s,t,n){const r=I$n(t,n);if(!r)return s;if(fbt.test(s))return s.replace(fbt,r);const a=s.includes("?")?"&":"?";return`${s}${a}${r}`}class R$n{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:sb.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===sb.VIDEO||c===sb.AUDIO||c==sb.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(Dt.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(Dt.MEDIA_DETACHED,this.onMediaDetached,this),t.on(Dt.BUFFER_CREATED,this.onBufferCreated,this)}unregisterListeners(){const t=this.hls;t.off(Dt.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(Dt.MEDIA_DETACHED,this.onMediaDetached,this),t.off(Dt.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:qBn.HLS,sid:this.sid,cid:this.cid,pr:(t=this.media)==null?void 0:t.playbackRate,mtp:this.hls.bandwidthEstimate/1e3}}apply(t,n={}){dh(n,this.createData());const r=n.ot===sb.INIT||n.ot===sb.VIDEO||n.ot===sb.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={}),T$n(t.headers,n,i)):t.url=D$n(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 sb.TIMED_TEXT;if(t.sn==="initSegment")return sb.INIT;if(n==="audio")return sb.AUDIO;if(n==="main")return this.hls.audioTracks.length?sb.VIDEO:sb.MUXED}getTopBandwidth(t){let n=0,r;const a=this.hls;if(t===sb.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===sb.AUDIO?this.audioBuffer:this.videoBuffer;return!r||!n?NaN:Bl.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 O$n=3e5;class F$n extends v2{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(Dt.MANIFEST_LOADING,this.onManifestLoading,this),t.on(Dt.MANIFEST_LOADED,this.onManifestLoaded,this),t.on(Dt.MANIFEST_PARSED,this.onManifestParsed,this),t.on(Dt.ERROR,this.onError,this)}unregisterListeners(){const t=this.hls;t&&(t.off(Dt.MANIFEST_LOADING,this.onManifestLoading,this),t.off(Dt.MANIFEST_LOADED,this.onManifestLoaded,this),t.off(Dt.MANIFEST_PARSED,this.onManifestParsed,this),t.off(Dt.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)===oy.SendAlternateToPenaltyBox&&r.flags===C_.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===fr.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: ${Lh(i)} penalized: ${Lh(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]>O$n&&delete r[i]});for(let i=0;i0){this.log(`Setting Pathway to "${l}"`),this.pathwayId=l,YHt(n),this.hls.trigger(Dt.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 Sp(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 x=TGt(u.uri,h["STABLE-VARIANT-ID"],"PER-VARIANT-URIS",c),g=new fQ({attrs:h,audioCodec:u.audioCodec,bitrate:u.bitrate,height:u.height,name:u.name,url:x,videoCodec:u.videoCodec,width:u.width});if(u.audioGroups)for(let y=1;y{this.log(`Loaded steering manifest: "${a}"`);const x=u.data;if((x==null?void 0:x.VERSION)!==1){this.log(`Steering VERSION ${x.VERSION} not supported!`);return}this.updated=performance.now(),this.timeToLoad=x.TTL;const{"RELOAD-URI":g,"PATHWAY-CLONES":y,"PATHWAY-PRIORITY":b}=x;if(g)try{this.uri=new self.URL(g,a).href}catch{this.enabled=!1,this.log(`Failed to parse Steering Manifest RELOAD-URI: ${g}`);return}this.scheduleRefresh(this.uri||m.url),y&&this.clonePathways(y);const v={steeringManifest:x,url:a.toString()};this.hls.trigger(Dt.STEERING_MANIFEST_LOADED,v),b&&this.updatePathwayPriority(b)},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 x=this.timeToLoad*1e3;if(u.code===429){const g=this.loader;if(typeof(g==null?void 0:g.getResponseHeader)=="function"){const y=g.getResponseHeader("Retry-After");y&&(x=parseFloat(y)*1e3)}this.log(`Steering manifest ${h.url} rate limited`);return}this.scheduleRefresh(this.uri||h.url,x)},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 xbt(s,t,n,r){s&&Object.keys(t).forEach(a=>{const i=s.filter(l=>l.groupId===a).map(l=>{const o=dh({},l);return o.details=void 0,o.attrs=new Sp(o.attrs),o.url=o.attrs.URI=TGt(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 TGt(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 NB extends v2{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=NB.CDMCleanupPromise?[NB.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=JW(this.config));const o=l.map(zDe).filter(c=>!!c);this.keyFormatPromise=this.getKeyFormatPromise(o)}this.keyFormatPromise.then(l=>{const o=RNe(l);if(r!=="sinf"||o!==Pp.FAIRPLAY){this.log(`Ignoring "${n.type}" event with init data type: "${r}" for selected key-system ${o}`);return}let c;try{const p=lg(new Uint8Array(a)),x=PXe(JSON.parse(p).sinf),g=NHt(x);if(!g)throw new Error("'schm' box missing or not cbcs/cenc with schi > tenc");c=new Uint8Array(g.subarray(8,24))}catch(p){this.warn(`${i} Failed to parse sinf: ${p}`);return}const d=ly(c),{keyIdToKeySessionPromise:u,mediaKeySessions:h}=this;let m=u[d];for(let p=0;pthis.generateRequestWithPreferredKeySession(x,r,a,"encrypted-event-key-match")),m.catch(b=>this.handleError(b));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(Dt.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.on(Dt.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.on(Dt.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.on(Dt.MANIFEST_LOADED,this.onManifestLoaded,this),this.hls.on(Dt.DESTROYING,this.onDestroying,this)}unregisterListeners(){this.hls.off(Dt.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.off(Dt.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.off(Dt.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.off(Dt.MANIFEST_LOADED,this.onManifestLoaded,this),this.hls.off(Dt.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===Pp.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 w_?o(h):o(new w_({type:mo.KEY_SYSTEM_ERROR,details:fr.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 $Ht===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=yzn(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: ${Lh(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: ${ly(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=Mae(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 ${ly(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})=>zDe(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=zDe(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=JW(this.config),r=t.map(RNe).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 w_){const c=qu({},o.data);this.getKeyStatus(n)==="internal-error"&&(c.decryptdata=n);const d=new w_(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 w_){n&&(t.data.frag=n);const r=t.data.decryptdata;this.error(`${t.message}${r?` (${ly(r.keyId||[])})`:""}`),this.hls.trigger(Dt.ERROR,t.data)}else this.error(t.message),this.hls.trigger(Dt.ERROR,{type:mo.KEY_SYSTEM_ERROR,details:fr.KEY_SYSTEM_NO_KEYS,error:t,fatal:!0})}getKeySystemForKeyPromise(t){const n=Mae(t),r=this.keyIdToKeySessionPromise[n];if(!r){const a=RNe(t.keyFormat),i=a?[a]:JW(this.config);return this.attemptKeySystemAccess(i)}return r}getKeySystemSelectionPromise(t){if(t.length||(t=JW(this.config)),t.length===0)throw new w_({type:mo.KEY_SYSTEM_ERROR,details:fr.KEY_SYSTEM_NO_CONFIGURED_LICENSE,fatal:!0},`Missing key-system license configuration options ${Lh({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 x=l.call(this.hls,n,r,t);if(!x)throw new Error("Invalid response from configured generateRequest filter");n=x.initDataType,r=x.initData?x.initData:null,t.decryptdata.pssh=r?new Uint8Array(r):null}catch(x){if(this.warn(x.message),this.hls&&this.hls.config.debug)throw x}if(r===null)return this.log(`Skipping key-session request for "${a}" (no initData)`),Promise.resolve(t);const o=Mae(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 DXe,u=t._onmessage=x=>{const g=t.mediaKeysSession;if(!g){d.emit("error",new Error("invalid state"));return}const{messageType:y,message:b}=x;this.log(`"${y}" message event for session "${g.sessionId}" message size: ${b.byteLength}`),y==="license-request"||y==="license-renewal"?this.renewLicense(t,b).catch(v=>{d.eventNames().length?d.emit("error",v):this.handleError(v)}):y==="license-release"?t.keySystem===Pp.FAIRPLAY&&this.updateKeySession(t,kUe("acknowledged")).then(()=>this.removeSession(t)).catch(v=>this.handleError(v)):this.warn(`unhandled media key message type "${y}"`)},h=(x,g)=>{g.keyStatus=x;let y;x.startsWith("usable")?d.emit("resolved"):x==="internal-error"||x==="output-restricted"||x==="output-downscaled"?y=gbt(x,g.decryptdata):x==="expired"?y=new Error(`key expired (keyId: ${o})`):x==="released"?y=new Error("key released"):x==="status-pending"||this.warn(`unhandled key status change "${x}" (keyId: ${o})`),y&&(d.eventNames().length?d.emit("error",y):this.handleError(y))},m=t._onkeystatuseschange=x=>{if(!t.mediaKeysSession){d.emit("error",new Error("invalid state"));return}const y=this.getKeyStatuses(t);if(!Object.keys(y).some(C=>y[C]!=="status-pending"))return;if(y[o]==="expired"){this.log(`Expired key ${Lh(y)} in key-session "${t.mediaKeysSession.sessionId}"`),this.renewKeySession(t);return}let v=y[o];if(v)h(v,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`),v="internal-error",h(v,t)},1e3)),this.log(`No status for keyId ${o} (${Lh(y)}).`)}};m1(t.mediaKeysSession,"message",u),m1(t.mediaKeysSession,"keystatuseschange",m);const p=new Promise((x,g)=>{d.on("error",g),d.on("resolved",x)});return t.mediaKeysSession.generateRequest(n,r).then(()=>{this.log(`Request generated for key-session "${t.mediaKeysSession.sessionId}" keyId: ${o} URI: ${c}`)}).catch(x=>{throw new w_({type:mo.KEY_SYSTEM_ERROR,details:fr.KEY_SYSTEM_NO_SESSION,error:x,decryptdata:t.decryptdata,fatal:!1},`Error generating key-session request: ${x}`)}).then(()=>p).catch(x=>(d.removeAllListeners(),this.removeSession(t).then(()=>{throw x}))).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===Pp.PLAYREADY&&i.length===16){const o=ly(i);n[o]=r,zHt(i)}const l=ly(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,x,g)=>{l(m.data)},onError:(m,p,x,g)=>{o(new w_({type:mo.KEY_SYSTEM_ERROR,details:fr.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:x,response:qu({url:c.url,data:void 0},m)},`"${t}" certificate request failed (${i}). Status: ${m.code} (${m.text})`))},onTimeout:(m,p,x)=>{o(new w_({type:mo.KEY_SYSTEM_ERROR,details:fr.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:x,response:{url:c.url,data:void 0}},`"${t}" certificate request timed out (${i})`))},onAbort:(m,p,x)=>{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 w_({type:mo.KEY_SYSTEM_ERROR,details:fr.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 w_({type:mo.KEY_SYSTEM_ERROR,details:fr.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 kUe(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 w_({type:mo.KEY_SYSTEM_ERROR,details:fr.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==Pp.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,m1(r,"encrypted",this.onMediaEncrypted),m1(r,"waitingforkey",this.onWaitingForKey);const a=this.mediaResolved;a?a():this.mediaKeys=r.mediaKeys}onMediaDetached(){const t=this.media;t&&(kb(t,"encrypted",this.onMediaEncrypted),kb(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,KT.clearKeyUriToKeyIdMap();const i=a.length;NB.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(Dt.ERROR,{type:mo.OTHER_ERROR,details:fr.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(Dt.ERROR,{type:mo.OTHER_ERROR,details:fr.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: ${ly((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(bzn(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(Dt.ERROR,{type:mo.OTHER_ERROR,details:fr.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(Dt.ERROR,{type:mo.OTHER_ERROR,details:fr.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,fatal:!1,error:new Error(`Could not close session: ${d}`)})})}return Promise.resolve()}}NB.CDMCleanupPromise=void 0;function Mae(s){if(!s)throw new Error("Could not read keyId of undefined decryptdata");if(s.keyId===null)throw new Error("keyId is null");return ly(s.keyId)}function z$n(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 w_ 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 gbt(s,t){const n=s==="output-restricted",r=n?fr.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:fr.KEY_SYSTEM_STATUS_INTERNAL_ERROR;return new w_({type:mo.KEY_SYSTEM_ERROR,details:r,fatal:!1,decryptdata:t},n?"HDCP level output restricted":`key status changed to "${s}"`)}class B$n{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(Dt.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.on(Dt.MEDIA_DETACHING,this.onMediaDetaching,this)}unregisterListeners(){this.hls.off(Dt.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.off(Dt.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(Dt.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(Dt.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 MGt(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 LGt(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){Yu.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){Yu.debug(`[texttrack-utils]: Legacy TextTrackCue fallback failed: ${a}`)}}n==="disabled"&&(s.mode=n)}function rz(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 IUe(s,t,n,r){const a=s.mode;if(a==="disabled"&&(s.mode="hidden"),s.cues&&s.cues.length>0){const i=U$n(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 BNe(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=BNe(this.media.textTracks);for(let i=0;i-1&&this.toggleTrackModes()}registerListeners(){const{hls:t}=this;t.on(Dt.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(Dt.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(Dt.MANIFEST_LOADING,this.onManifestLoading,this),t.on(Dt.MANIFEST_PARSED,this.onManifestParsed,this),t.on(Dt.LEVEL_LOADING,this.onLevelLoading,this),t.on(Dt.LEVEL_SWITCHING,this.onLevelSwitching,this),t.on(Dt.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),t.on(Dt.ERROR,this.onError,this)}unregisterListeners(){const{hls:t}=this;t.off(Dt.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(Dt.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(Dt.MANIFEST_LOADING,this.onManifestLoading,this),t.off(Dt.MANIFEST_PARSED,this.onManifestParsed,this),t.off(Dt.LEVEL_LOADING,this.onLevelLoading,this),t.off(Dt.LEVEL_SWITCHING,this.onLevelSwitching,this),t.off(Dt.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),t.off(Dt.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;BNe(r.textTracks).forEach(l=>{rz(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=KS(o,l);if(u>-1)i=l[u];else{const h=KS(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(Dt.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=KS(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(Dt.SUBTITLE_TRACK_LOADING,{url:i,id:r,groupId:a,deliveryDirectives:n||null,track:t})}toggleTrackModes(){const{media:t}=this;if(!t)return;const n=BNe(t.textTracks),r=this.currentTrack;let a;if(r&&(a=n.filter(i=>TUe(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||!Mi(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(Dt.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(Dt.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 V$n(){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 lZ(s){let t=5381,n=s.length;for(;n;)t=t*33^s.charCodeAt(--n);return(t>>>0).toString()}const kB=.025;let Y4e=function(s){return s[s.Point=0]="Point",s[s.Range=1]="Range",s}({});function H$n(s,t,n){return`${s.identifier}-${n+1}-${lZ(t)}`}class G$n{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 KDe(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=KDe(n,t);return n-r<.1}return!1}get resumptionOffset(){const t=this.resumeOffset,n=Mi(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 KDe(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 W$n(this)}}function KDe(s,t){return s-t.start":s.cue.post?"":""}${s.timelineStart.toFixed(2)}-${s.resumeTime.toFixed(2)}]`}function S9(s){const t=s.timelineStart,n=s.duration||0;return`["${s.identifier}" ${t.toFixed(2)}-${(t+n).toFixed(2)}]`}class K$n{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(Dt.PLAYOUT_LIMIT_REACHED,{})};const i=this.hls=new t(n);this.interstitial=r,this.assetItem=a;const l=()=>{this.hasDetails=!0};i.once(Dt.LEVEL_LOADED,l),i.once(Dt.AUDIO_TRACK_LOADED,l),i.once(Dt.SUBTITLE_TRACK_LOADED,l),i.on(Dt.MEDIA_ATTACHING,(o,{media:c})=>{this.removeMediaListeners(),this.mediaAttached=c,this.interstitial.playoutLimit&&(c.addEventListener("timeupdate",this.checkPlayout),this.appendInPlace&&i.on(Dt.BUFFER_APPENDED,()=>{const u=this.bufferedEnd;this.reachedPlayout(u)&&(this._bufferedEosTime=u,i.trigger(Dt.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=PGt(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=Bl.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=Bl.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: ${S9(this.assetItem)} ${(t=this.hls)==null?void 0:t.sessionId} ${this.appendInPlace?"append-in-place":""}`}}const ybt=.033;class Y$n extends v2{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,x=u.cue.post;if(h&&!p)return-1;if(p&&!h||m&&!x)return 1;if(x&&!m)return-1;if(!h&&!p&&!m&&!x){const g=d.startTime,y=u.startTime;if(g!==y)return g-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,x=t[h-1]||null,g=u.appendInPlace,y=p?i:u.startOffset,b=u.duration,v=u.timelineOccupancy===Y4e.Range?b:0,N=u.resumptionOffset,C=(x==null?void 0:x.startTime)===y,A=y+u.cumulativeDuration;let T=g?A+b:y+N;if(m||!p&&y<=0){const M=d;d+=v,u.timelineStart=A;const I=l;l+=b,r.push({event:u,start:A,end:T,playout:{start:I,end:l},integrated:{start:M,end:d}})}else if(y<=i){if(!C){const D=y-c;if(D>ybt){const B=c,q=d;d+=D;const W=l;l+=D;const V={previousEvent:t[h-1]||null,nextEvent:u,start:B,end:B+D,playout:{start:W,end:l},integrated:{start:q,end:d}};r.push(V)}else D>0&&x&&(x.cumulativeDuration+=D,r[r.length-1].end=y)}p&&(T=A),u.timelineStart=A;const M=d;d+=v;const I=l;l+=b,r.push({event:u,start:A,end:T,playout:{start:I,end:l},integrated:{start:M,end:d}})}else return;const P=u.resumeTime;p||P>i?c=i:c=P}),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=$O(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+1kB?(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=$O(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,b=y==null?void 0:y.ASSETS;if(!Array.isArray(b)){const v=this.assignAssetListError(t,fr.ASSET_LIST_PARSING_ERROR,new Error("Invalid interstitial asset list"),x.url,p,g);this.hls.trigger(Dt.ERROR,v);return}t.assetListResponse=y,this.hls.trigger(Dt.ASSET_LIST_LOADED,{event:t,assetListResponse:y,networkDetails:g})},onError:(m,p,x,g)=>{const y=this.assignAssetListError(t,fr.ASSET_LIST_LOAD_ERROR,new Error(`Error loading X-ASSET-LIST: HTTP status ${m.code} ${m.text} (${p.url})`),p.url,g,x);this.hls.trigger(Dt.ERROR,y)},onTimeout:(m,p,x)=>{const g=this.assignAssetListError(t,fr.ASSET_LIST_LOAD_TIMEOUT,new Error(`Timeout loading X-ASSET-LIST (${p.url})`),p.url,m,x);this.hls.trigger(Dt.ERROR,g)}};return o.load(c,u,h),this.hls.trigger(Dt.ASSET_LIST_LOADING,{event:t}),o}assignAssetListError(t,n,r,a,i,l){return t.error=r,{type:mo.NETWORK_ERROR,details:n,fatal:!1,interstitial:t,url:a,error:r,networkDetails:l,stats:i}}}function vbt(s){var t;s==null||(t=s.play())==null||t.catch(()=>{})}function Q7(s,t){return`[${s}] Advancing timeline position to ${t}`}class X$n extends v2{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 x=this.schedule.findItemIndexAtTime(r);if(x===-1&&(x=p+(l?-1:1),this.log(`seeked ${l?"back ":""}to position not covered by schedule ${r} (resolving from ${p} to ${x})`)),!this.isInterstitial(o)&&(c=this.media)!=null&&c.paused&&(this.shouldPlay=!1),!l&&x>p){const g=this.schedule.findJumpRestrictedIndex(p+1,x);if(g>p){this.setSchedulePosition(g);return}}this.setSchedulePosition(x);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(g=>g.identifier),h=!!(o.length||u.length);(h||a)&&this.log(`INTERSTITIALS_UPDATED (${o.length}): ${o} Schedule: ${c.map(g=>H2(g))} 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 x=this.bufferingItem;if(x&&(p=this.updateItem(x,this.bufferedPos),this.itemsMatch(x,p)?this.bufferingItem=p:x.event&&(this.bufferingItem=this.playingItem,this.clearInterstitial(x.event,null))),r.forEach(g=>{g.assetList.forEach(y=>{this.clearAssetPlayer(y.identifier,null)})}),this.playerQueue.forEach(g=>{if(g.interstitial.appendInPlace){const y=g.assetItem.timelineStart,b=g.timelineOffset-y;if(b)try{g.timelineOffset=y}catch(v){Math.abs(b)>kB&&this.warn(`${v} ("${g.assetId}" ${g.timelineOffset}->${y})`)}}}),h||a){if(this.hls.trigger(Dt.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),x&&p!==m&&this.trimInPlace(p,x),this.checkBuffer()}},this.hls=t,this.HlsPlayerClass=n,this.assetListLoader=new Z$n(t),this.schedule=new Y$n(this.onScheduleUpdate,t.logger),this.registerListeners()}registerListeners(){const t=this.hls;t&&(t.on(Dt.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on(Dt.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(Dt.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(Dt.MANIFEST_LOADING,this.onManifestLoading,this),t.on(Dt.LEVEL_UPDATED,this.onLevelUpdated,this),t.on(Dt.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.on(Dt.AUDIO_TRACK_UPDATED,this.onAudioTrackUpdated,this),t.on(Dt.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),t.on(Dt.SUBTITLE_TRACK_UPDATED,this.onSubtitleTrackUpdated,this),t.on(Dt.EVENT_CUE_ENTER,this.onInterstitialCueEnter,this),t.on(Dt.ASSET_LIST_LOADED,this.onAssetListLoaded,this),t.on(Dt.BUFFER_APPENDED,this.onBufferAppended,this),t.on(Dt.BUFFER_FLUSHED,this.onBufferFlushed,this),t.on(Dt.BUFFERED_TO_END,this.onBufferedToEnd,this),t.on(Dt.MEDIA_ENDED,this.onMediaEnded,this),t.on(Dt.ERROR,this.onError,this),t.on(Dt.DESTROYING,this.onDestroying,this))}unregisterListeners(){const t=this.hls;t&&(t.off(Dt.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off(Dt.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(Dt.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(Dt.MANIFEST_LOADING,this.onManifestLoading,this),t.off(Dt.LEVEL_UPDATED,this.onLevelUpdated,this),t.off(Dt.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.off(Dt.AUDIO_TRACK_UPDATED,this.onAudioTrackUpdated,this),t.off(Dt.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),t.off(Dt.SUBTITLE_TRACK_UPDATED,this.onSubtitleTrackUpdated,this),t.off(Dt.EVENT_CUE_ENTER,this.onInterstitialCueEnter,this),t.off(Dt.ASSET_LIST_LOADED,this.onAssetListLoaded,this),t.off(Dt.BUFFER_CODECS,this.onBufferCodecs,this),t.off(Dt.BUFFER_APPENDED,this.onBufferAppended,this),t.off(Dt.BUFFER_FLUSHED,this.onBufferFlushed,this),t.off(Dt.BUFFERED_TO_END,this.onBufferedToEnd,this),t.off(Dt.MEDIA_ENDED,this.onMediaEnded,this),t.off(Dt.ERROR,this.onError,this),t.off(Dt.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){kb(t,"play",this.onPlay),kb(t,"pause",this.onPause),kb(t,"seeking",this.onSeeking),kb(t,"timeupdate",this.onTimeupdate)}onMediaAttaching(t,n){const r=this.media=n.media;m1(r,"seeking",this.onSeeking),m1(r,"timeupdate",this.onTimeupdate),m1(r,"play",this.onPlay),m1(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,x,g)=>{if(h){let y=h[m].start;const b=h.event;if(b){if(m==="playout"||b.timelineOccupancy!==Y4e.Point){const v=r(p);(v==null?void 0:v.interstitial)===b&&(y+=v.assetItem.startOffset+v[g])}}else{const v=x==="bufferedPos"?l():t[x];y+=v-h.start}return y}return 0},i=(h,m)=>{var p;if(h!==0&&m!=="primary"&&(p=t.schedule)!=null&&p.length){var x;const g=t.schedule.findItemIndexAtTime(h),y=(x=t.schedule.items)==null?void 0:x[g];if(y){const b=y[m].start-y.start;return h+b}}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,x;const g=t.effectivePlayingItem;if(g!=null&&(p=g.event)!=null&&p.restrictions.skip||!t.schedule)return;t.log(`seek to ${h} "${m}"`);const y=t.effectivePlayingItem,b=t.schedule.findItemIndexAtTime(h,m),v=(x=t.schedule.items)==null?void 0:x[b],N=t.getBufferingPlayer(),C=N==null?void 0:N.interstitial,A=C==null?void 0:C.appendInPlace,T=y&&t.itemsMatch(y,v);if(y&&(A||T)){const P=r(t.playingAsset),M=(P==null?void 0:P.media)||t.primaryMedia;if(M){const I=m==="primary"?M.currentTime:a(y,m,t.playingAsset,"timelinePos","currentTime"),D=h-I,B=(A?I:M.currentTime)+D;if(B>=0&&(!P||A||B<=P.duration)){M.currentTime=B;return}}}if(v){let P=h;if(m!=="primary"){const I=v[m].start,D=h-I;P=v.start+D}const M=!t.isInterstitial(v);if((!t.isInterstitial(y)||y.event.appendInPlace)&&(M||v.event.appendInPlace)){const I=t.media||(A?N==null?void 0:N.media:null);I&&(I.currentTime=P)}else if(y){const I=t.findItemIndex(y);if(b>I){const B=t.schedule.findJumpRestrictedIndex(I+1,b);if(B>I){t.setSchedulePosition(B);return}}let D=0;if(M)t.timelinePos=P,t.checkBuffer();else{const B=v.event.assetList,q=h-(v[m]||v).start;for(let W=B.length;W--;){const V=B[W];if(V.duration&&q>=V.startOffset&&q{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 x=h.playout.start+h.event.duration;c(x+.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||!Mi(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} ${Lh(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 x=this.getBufferingPlayer();x?(i=x.transferMedia(),u=`${x}`):u="detached MediaSource"}else u="detached media";if(!i){if(d)i=this.detachedData,this.log(`using detachedData: MediaSource ${Lh(i)}`);else if(!this.detachedData||l.media===n){const x=this.playerQueue;x.length>1&&x.forEach(g=>{if(o&&g.interstitial.appendInPlace!==c){const y=g.interstitial;this.clearInterstitial(g.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 x=o&&t.assetId===p.assetIdAtEnd;m.overrides={duration:p.duration,endOfStream:!o||x,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(Q7("checkStart (preroll)",i));const l=t.findEventIndex(n[0].identifier);this.setSchedulePosition(l)}else if(i>=0||!this.primaryLive){this.log(Q7("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(Q7("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=YDe(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=YDe(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&&H2(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 x=u.findAssetIndex(h);if(this.log(`INTERSTITIAL_ASSET_ENDED ${x+1}/${u.assetList.length} ${S9(h)}`),this.endedAsset=h,this.playingAsset=null,this.hls.trigger(Dt.INTERSTITIAL_ASSET_ENDED,{asset:h,assetListIndex:x,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),x);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} ${H2(l)}`),u.hasPlayed=!0,this.hls.trigger(Dt.INTERSTITIAL_ENDED,{event:u,schedule:a.slice(0),scheduleIndex:t}),u.cue.once)){var d;this.updateSchedule();const x=(d=this.schedule)==null?void 0:d.items;if(i&&x){const g=this.findItemIndex(i);this.advanceSchedule(g,x,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 x=YDe(u,r-1);if(u.isAssetPastPlayoutLimit(x)||u.appendInPlace&&this.timelinePos===o.end){this.advanceAfterAssetEnded(u,t,r);return}r=x}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 ${H2(o)} ${u.appendInPlace?"append in place":""}`),this.hls.trigger(Dt.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 x=u.assetList.length;this.warn(`asset ${r+1}/${x} 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&&vbt(m.media)}else o?(this.resumePrimary(o,t,a),this.shouldPlay&&vbt(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 ${H2(t)}`),!((a=this.detachedData)!=null&&a.mediaSource)){let o=this.timelinePos;(o=t.end)&&(o=this.getPrimaryResumption(t,n),this.log(Q7("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 ${H2(t)}`),this.hls.trigger(Dt.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:Bl.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(Q7("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(Dt.BUFFER_CODECS,this.onBufferCodecs,this),this.hls.on(Dt.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=qu(qu({},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=qu(qu({},this.altSelection),{},{audio:r});return}const i=qu(qu({},a),{},{audio:r});this.mediaSelection=i}onSubtitleTrackUpdated(t,n){const r=this.hls.subtitleTracks[n.id],a=this.mediaSelection;if(!a){this.altSelection=qu(qu({},this.altSelection),{},{subtitles:r});return}const i=qu(qu({},a),{},{subtitles:r});this.mediaSelection=i}onAudioTrackSwitching(t,n){const r=A1t(n);this.playerQueue.forEach(({hls:a})=>a&&(a.setAudioOption(n)||a.setAudioOption(r)))}onSubtitleTrackSwitch(t,n){const r=A1t(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=Bl.bufferInfo(this.primaryMedia,r,0);(a.end>r||(a.nextStart||0)>r)&&(this.log(`trim buffered interstitial ${H2(t)} (was ${H2(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=Bl.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 ${H2(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(Dt.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(Dt.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&&C{if(C.live){var A;const M=new Error(`Interstitials MUST be VOD assets ${t}`),I={fatal:!0,type:mo.OTHER_ERROR,details:fr.INTERSTITIAL_ASSET_ITEM_ERROR,error:M},D=((A=this.schedule)==null?void 0:A.findEventIndex(t.identifier))||-1;this.handleAssetItemError(I,t,D,r,M.message);return}const T=C.edge-C.fragmentStart,P=n.duration;(g||P===null||T>P)&&(g=!1,this.log(`Interstitial asset "${h}" duration change ${P} > ${T}`),n.duration=T,this.updateSchedule())};x.on(Dt.LEVEL_UPDATED,(C,{details:A})=>y(A)),x.on(Dt.LEVEL_PTS_UPDATED,(C,{details:A})=>y(A)),x.on(Dt.EVENT_CUE_ENTER,()=>this.onInterstitialCueEnter());const b=(C,A)=>{const T=this.getAssetPlayer(h);if(T&&A.tracks){T.off(Dt.BUFFER_CODECS,b),T.tracks=A.tracks;const P=this.primaryMedia;this.bufferingAsset===T.assetItem&&P&&!T.media&&this.bufferAssetPlayer(T,P)}};x.on(Dt.BUFFER_CODECS,b);const v=()=>{var C;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),P=(C=this.schedule.items)==null?void 0:C[T];this.isInterstitial(P)&&this.advanceAssetBuffering(P,n)};x.on(Dt.BUFFERED_TO_END,v);const N=C=>()=>{if(!this.getAssetPlayer(h)||!this.schedule)return;this.shouldPlay=!0;const T=this.schedule.findEventIndex(t.identifier);this.advanceAfterAssetEnded(t,T,C)};return x.once(Dt.MEDIA_ENDED,N(r)),x.once(Dt.PLAYOUT_LIMIT_REACHED,N(1/0)),x.on(Dt.ERROR,(C,A)=>{if(!this.schedule)return;const T=this.getAssetPlayer(h);if(A.details===fr.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}`)}),x.on(Dt.DESTROYING,()=>{if(!this.getAssetPlayer(h)||!this.schedule)return;const A=new Error(`Asset player destroyed unexpectedly ${h}`),T={fatal:!0,type:mo.OTHER_ERROR,details:fr.INTERSTITIAL_ASSET_ITEM_ERROR,error:A};this.handleAssetItemError(T,t,this.schedule.findEventIndex(t.identifier),r,A.message)}),this.log(`INTERSTITIAL_ASSET_PLAYER_CREATED ${S9(n)}`),this.hls.trigger(Dt.INTERSTITIAL_ASSET_PLAYER_CREATED,{asset:n,assetListIndex:r,event:t,player:x}),x}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&&H2(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} ${S9(o)}`),this.hls.trigger(Dt.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&&!fHt(h,t.tracks)){const m=new Error(`Asset ${S9(l)} SourceBuffer tracks ('${Object.keys(t.tracks)}') are not compatible with primary content tracks ('${Object.keys(h)}')`),p={fatal:!0,type:mo.OTHER_ERROR,details:fr.INTERSTITIAL_ASSET_ITEM_ERROR,error:m},x=i.findAssetIndex(l);this.handleAssetItemError(p,i,o,x,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!g.error))n.error=x;else for(let g=a;g{const b=parseFloat(g.DURATION);this.createAsset(i,y,u,c+u,b,g.URI),u+=b}),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 x;const g=this.schedule.findEventIndex(l),y=(x=this.schedule.items)==null?void 0:x[g];if(y){if(!this.playingItem&&this.timelinePos>y.end&&this.schedule.findItemIndexAtTime(this.timelinePos)!==g){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(g)}else if((p==null?void 0:p.identifier)===l){const g=i.assetList[0];if(g){const y=this.getAssetPlayer(g.identifier);if(p.appendInPlace){const b=this.primaryMedia;y&&b&&this.bufferAssetPlayer(y,b)}else y&&y.loadSource()}}}onError(t,n){if(this.schedule)switch(n.details){case fr.ASSET_LIST_PARSING_ERROR:case fr.ASSET_LIST_LOAD_ERROR:case fr.ASSET_LIST_LOAD_TIMEOUT:{const r=n.interstitial;r&&(this.updateSchedule(!0),this.primaryFallback(r));break}case fr.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 bbt=500;class Q$n extends IXe{constructor(t,n,r){super(t,n,r,"subtitle-stream-controller",Gi.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(Dt.LEVEL_LOADED,this.onLevelLoaded,this),t.on(Dt.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),t.on(Dt.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),t.on(Dt.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),t.on(Dt.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),t.on(Dt.BUFFER_FLUSHING,this.onBufferFlushing,this)}unregisterListeners(){super.unregisterListeners();const{hls:t}=this;t.off(Dt.LEVEL_LOADED,this.onLevelLoaded,this),t.off(Dt.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),t.off(Dt.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),t.off(Dt.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),t.off(Dt.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),t.off(Dt.BUFFER_FLUSHING,this.onBufferFlushing,this)}startLoad(t,n){this.stopLoad(),this.state=ea.IDLE,this.setInterval(bbt),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)||(Jf(r)&&(this.fragPrevious=r),this.state=ea.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 fQ(r));return}this.tracksBuffered=[],this.levels=n.map(r=>{const a=new fQ(r);return this.tracksBuffered[a.id]=[],a}),this.fragmentTracker.removeFragmentsInRange(0,Number.POSITIVE_INFINITY,Gi.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!==ea.STOPPED&&this.setInterval(bbt)}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?(W4e(l,h),d=l.fragmentStart):m&&(d=m.start,CUe(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,CUe(l,d))}h&&!this.startFragRequested&&this.setStartPosition(h,d)}c.details=l,this.levelLastLoaded=c,o===a&&(this.hls.trigger(Dt.SUBTITLE_TRACK_UPDATED,{details:l,id:o,groupId:n.groupId}),this.tick(),l.live&&!this.fragCurrent&&this.media&&this.state===ea.IDLE&&($O(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&&jB(a.method)){const l=performance.now();this.decrypter.decrypt(new Uint8Array(r),a.key.buffer,a.iv.buffer,LXe(a.method)).catch(o=>{throw i.trigger(Dt.ERROR,{type:mo.MEDIA_ERROR,details:fr.FRAG_DECRYPT_ERROR,fatal:!1,error:o,reason:o.message,frag:n}),o}).then(o=>{const c=performance.now();i.trigger(Dt.FRAG_DECRYPTED,{frag:n,payload:o,stats:{tstart:l,tdecrypt:c}})}).catch(o=>{this.warn(`${o.name}: ${o.message}`),this.state=ea.IDLE})}}doTick(){if(!this.media){this.state=ea.IDLE;return}if(this.state===ea.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=Bl.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 x=null;const g=this.fragPrevious;if(op-v?0:v;x=$O(g,h,Math.max(h[0].start,o),N),!x&&g&&g.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 eUn={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},IGt=s=>String.fromCharCode(eUn[s]||s),Y2=15,M4=100,tUn={17:1,18:3,21:5,22:7,23:9,16:11,19:12,20:14},sUn={17:2,18:4,21:6,22:8,23:10,19:13,20:15},nUn={25:1,26:3,29:5,30:7,31:9,24:11,27:12,28:14},rUn={25:2,26:4,29:6,30:8,31:10,27:13,28:15},aUn=["white","green","blue","cyan","red","yellow","magenta","black","transparent"];class iUn{constructor(){this.time=null,this.verboseLevel=0}log(t,n){if(this.verboseLevel>=t){const r=typeof n=="function"?n():n;Yu.log(`${this.time} [${t}] ${r}`)}}}const HM=function(t){const n=[];for(let r=0;rM4&&(this.logger.log(3,"Too large cursor position "+this.pos),this.pos=M4)}moveCursor(t){const n=this.pos+t;if(t>1)for(let r=this.pos+1;r=144&&this.backSpace();const n=IGt(t);if(this.pos>=M4){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 = "+Lh(t));let n=t.row-1;if(this.nrRollUpRows&&n"bkgData = "+Lh(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 _bt{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 ZDe(r),this.nonDisplayedMemory=new ZDe(r),this.lastOutputScreen=new ZDe(r),this.currRollUpRow=this.displayedMemory.rows[Y2-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[Y2-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: "+Lh(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 wbt{constructor(t,n,r){this.channels=void 0,this.currentChannel=0,this.cmdHistory=dUn(),this.logger=void 0;const a=this.logger=new iUn;this.channels=[null,new _bt(t,n,a),new _bt(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"["+HM([n[r],n[r+1]])+"] -> ("+HM([a,i])+")");const c=this.cmdHistory;if(a>=16&&a<=31){if(cUn(a,i,c)){Lae(null,null,c),this.logger.log(3,()=>"Repeated command ("+HM([a,i])+") is dropped");continue}Lae(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 Lae(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 "+HM([a,i])+" orig: "+HM([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 ("+HM([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?tUn[t]:nUn[t]:r=l===1?sUn[t]:rUn[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 '"+IGt(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 = "+HM(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=aUn[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=D,this.hasBeenReset=!0}})),Object.defineProperty(u,"positionAlign",i({},h,{get:function(){return P},set:function(D){const B=a(D);if(!B)throw new SyntaxError("An invalid or illegal string was specified.");P=B,this.hasBeenReset=!0}})),Object.defineProperty(u,"size",i({},h,{get:function(){return M},set:function(D){if(D<0||D>100)throw new Error("Size must be between 0 and 100.");M=D,this.hasBeenReset=!0}})),Object.defineProperty(u,"align",i({},h,{get:function(){return I},set:function(D){const B=a(D);if(!B)throw new SyntaxError("An invalid or illegal string was specified.");I=B,this.hasBeenReset=!0}})),u.displayState=void 0}return l.prototype.getCueAsHTML=function(){return self.WebVTT.convertCueToDOMTree(self,this.text)},l}();class uUn{decode(t,n){if(!t)return"";if(typeof t!="string")throw new Error("Error - expected string data.");return decodeURIComponent(encodeURIComponent(t))}}function RGt(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 hUn{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 OGt(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 DUe=new GXe(0,0,""),Pae=DUe.align==="middle"?"middle":"center";function mUn(s,t,n){const r=s;function a(){const o=RGt(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 hUn;OGt(o,function(m,p){let x;switch(m){case"region":for(let g=n.length-1;g>=0;g--)if(n[g].id===p){d.set(m,n[g].region);break}break;case"vertical":d.alt(m,p,["rl","lr"]);break;case"line":x=p.split(","),d.integer(m,x[0]),d.percent(m,x[0])&&d.set("snapToLines",!1),d.alt(m,x[0],["auto"]),x.length===2&&d.alt("lineAlign",x[1],["start",Pae,"end"]);break;case"position":x=p.split(","),d.percent(m,x[0]),x.length===2&&d.alt("positionAlign",x[1],["start",Pae,"end","line-left","line-right","auto"]);break;case"size":d.percent(m,p);break;case"align":d.alt(m,p,["start",Pae,"end","left","right"]);break}},/:/,/\s/),c.region=d.get("region",null),c.vertical=d.get("vertical","");let u=d.get("line","auto");u==="auto"&&DUe.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",Pae);let h=d.get("position","auto");h==="auto"&&DUe.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 FGt(s){return s.replace(//gi,` `)}class pUn{constructor(){this.state="INITIAL",this.buffer="",this.decoder=new uUn,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=FGt(i);l")===-1){n.cue.id=i;continue}case"CUE":if(!n.cue){n.state="BADCUE";continue}try{mUn(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 fUn=/\r\n|\n\r|\n|\r/g,XDe=function(t,n,r=0){return t.slice(r,r+n.length)===n},xUn=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(!Mi(n)||!Mi(r)||!Mi(a)||!Mi(i))throw Error(`Malformed X-TIMESTAMP-MAP: Local:${t}`);return n+=1e3*r,n+=60*1e3*a,n+=60*60*1e3*i,n};function WXe(s,t,n){return lZ(s.toString())+lZ(t.toString())+lZ(n)}const gUn=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 yUn(s,t,n,r,a,i,l){const o=new pUn,c=uw(new Uint8Array(s)).trim().replace(fUn,` `).split(` `),d=[],u=t?NBn(t.baseTime,t.timescale):0;let h="00:00.000",m=0,p=0,x,g=!0;o.oncue=function(y){const b=n[r];let v=n.ccOffset;const N=(m-u)/9e4;if(b!=null&&b.new&&(p!==void 0?v=n.ccOffset=b.start:gUn(n,r,N)),N){if(!t){x=new Error("Missing initPTS for VTT MPEGTS");return}v=N-n.presentationOffset}const C=y.endTime-y.startTime,A=F_((y.startTime+v-p)*9e4,a*9e4)/9e4;y.startTime=Math.max(A,0),y.endTime=Math.max(A+C,0);const T=y.text.trim();y.text=decodeURIComponent(encodeURIComponent(T)),y.id||(y.id=WXe(y.startTime,y.endTime,T)),y.endTime>0&&d.push(y)},o.onparsingerror=function(y){x=y},o.onflush=function(){if(x){l(x);return}i(d)},c.forEach(y=>{if(g)if(XDe(y,"X-TIMESTAMP-MAP=")){g=!1,y.slice(16).split(",").forEach(b=>{XDe(b,"LOCAL:")?h=b.slice(6):XDe(b,"MPEGTS:")&&(m=parseInt(b.slice(7)))});try{p=xUn(h)/1e3}catch(b){x=b}return}else y===""&&(g=!1);o.parse(y+` `)}),o.flush()}const QDe="stpp.ttml.im1t",zGt=/^(\d{2,}):(\d{2}):(\d{2}):(\d{2})\.?(\d+)?$/,BGt=/^(\d*(?:\.\d*)?)(h|m|s|ms|f|t)$/,vUn={left:"start",center:"center",right:"end",start:"start",end:"end"};function jbt(s,t,n,r){const a=Lc(new Uint8Array(s),["mdat"]);if(a.length===0){r(new Error("Could not parse IMSC1 mdat"));return}const i=a.map(o=>uw(o)),l=jBn(t.baseTime,1,t.timescale);try{i.forEach(o=>n(bUn(o,l)))}catch(o){r(o)}}function bUn(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=Nbt(JDe(a,"styling","style")),d=Nbt(JDe(a,"layout","region")),u=JDe(a,"body","[begin]");return[].map.call(u,h=>{const m=$Gt(h,o);if(!m||!h.hasAttribute("begin"))return null;const p=tRe(h.getAttribute("begin"),l),x=tRe(h.getAttribute("dur"),l);let g=tRe(h.getAttribute("end"),l);if(p===null)throw kbt(h);if(g===null){if(x===null)throw kbt(h);g=p+x}const y=new GXe(p-t,g-t,m);y.id=WXe(y.startTime,y.endTime,y.text);const b=d[h.getAttribute("region")],v=c[h.getAttribute("style")],N=_Un(b,v,c),{textAlign:C}=N;if(C){const A=vUn[C];A&&(y.lineAlign=A),y.align=C}return dh(y,N),y}).filter(h=>h!==null)}function JDe(s,t,n){const r=s.getElementsByTagName(t)[0];return r?[].slice.call(r.querySelectorAll(n)):[]}function Nbt(s){return s.reduce((t,n)=>{const r=n.getAttribute("xml:id");return r&&(t[r]=n),t},{})}function $Gt(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?$Gt(r,t):t?n+r.textContent.trim().replace(/\s+/g," "):n+r.textContent},"")}function _Un(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=eRe(t,r,c)||eRe(s,r,c)||eRe(a,r,c);return d&&(o[c]=d),o},{})}function eRe(s,t,n){return s&&s.hasAttributeNS(t,n)?s.getAttributeNS(t,n):null}function kbt(s){return new Error(`Could not parse ttml timestamp ${s}`)}function tRe(s,t){if(!s)return null;let n=RGt(s);return n===null&&(zGt.test(s)?n=wUn(s,t):BGt.test(s)&&(n=jUn(s,t))),n}function wUn(s,t){const n=zGt.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 jUn(s,t){const n=BGt.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 Iae{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 NUn{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=Cbt(),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(Dt.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on(Dt.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(Dt.MANIFEST_LOADING,this.onManifestLoading,this),t.on(Dt.MANIFEST_LOADED,this.onManifestLoaded,this),t.on(Dt.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),t.on(Dt.FRAG_LOADING,this.onFragLoading,this),t.on(Dt.FRAG_LOADED,this.onFragLoaded,this),t.on(Dt.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),t.on(Dt.FRAG_DECRYPTED,this.onFragDecrypted,this),t.on(Dt.INIT_PTS_FOUND,this.onInitPtsFound,this),t.on(Dt.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),t.on(Dt.BUFFER_FLUSHING,this.onBufferFlushing,this)}destroy(){const{hls:t}=this;t.off(Dt.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off(Dt.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(Dt.MANIFEST_LOADING,this.onManifestLoading,this),t.off(Dt.MANIFEST_LOADED,this.onManifestLoaded,this),t.off(Dt.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),t.off(Dt.FRAG_LOADING,this.onFragLoading,this),t.off(Dt.FRAG_LOADED,this.onFragLoaded,this),t.off(Dt.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),t.off(Dt.FRAG_DECRYPTED,this.onFragDecrypted,this),t.off(Dt.INIT_PTS_FOUND,this.onInitPtsFound,this),t.off(Dt.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),t.off(Dt.BUFFER_FLUSHING,this.onBufferFlushing,this),this.hls=this.config=this.media=null,this.cea608Parser1=this.cea608Parser2=void 0}initCea608Parsers(){const t=new Iae(this,"textTrack1"),n=new Iae(this,"textTrack2"),r=new Iae(this,"textTrack3"),a=new Iae(this,"textTrack4");this.cea608Parser1=new wbt(1,t,n),this.cea608Parser2=new wbt(3,r,a)}addCues(t,n,r,a,i){let l=!1;for(let o=i.length;o--;){const c=i[o],d=kUn(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(Dt.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===Gi.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(Dt.FRAG_LOADED,c):this.hls.trigger(Dt.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{rz(a[i]),delete a[i]}),this.nonNativeCaptionsTracks={}}onManifestLoading(){this.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs=Cbt(),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===QDe);if(this.config.enableWebVTT||a&&this.config.enableIMSC1){if(yGt(this.tracks,r)){this.tracks=r;return}if(this.textTracks=[],this.tracks=r,this.config.renderTextTracksNatively){const l=this.media,o=l?BNe(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(Dt.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===Gi.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===Gi.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===QDe?this._parseIMSC1(r,a):this._parseVTTs(n)}}else this.hls.trigger(Dt.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:r,error:new Error("Empty subtitle payload")})}_parseIMSC1(t,n){const r=this.hls;jbt(n,this.initPTS[t.cc],a=>{this._appendCues(a,t.level),r.trigger(Dt.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:t})},a=>{r.logger.log(`Failed to parse IMSC1: ${a}`),r.trigger(Dt.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?d2(r.initSegment.data,new Uint8Array(a)).buffer:a;yUn(d,this.initPTS[r.cc],this.vttCCs,r.cc,r.start,u=>{this._appendCues(u,r.level),c.trigger(Dt.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(Dt.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:r,error:u})})}_fallbackToIMSC1(t,n){const r=this.tracks[t.level];r.textCodec||jbt(n,this.initPTS[t.cc],()=>{r.textCodec=QDe,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=>LGt(a,i))}else{const a=this.tracks[n];if(!a)return;const i=a.default?"default":"subtitles"+n;r.trigger(Dt.CUES_PARSED,{type:"subtitles",cues:t,track:i})}}onFragDecrypted(t,n){const{frag:r}=n;r.type===Gi.SUBTITLE&&this.onFragLoaded(Dt.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===Gi.MAIN&&this.closedCaptionsForLevel(r)==="NONE"))for(let i=0;iIUe(o[c],n,r))}if(this.config.renderTextTracksNatively&&n===0&&a!==void 0){const{textTracks:o}=this;Object.keys(o).forEach(c=>IUe(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=FGt(d.trim()),x=WXe(t,n,p);s!=null&&(h=s.cues)!=null&&h.getCueById(x)||(l=new u(t,n,p),l.id=x,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=>LGt(s,m))),a}};function AUn(){if(self.fetch&&self.AbortController&&self.ReadableStream&&self.Request)try{return new self.ReadableStream({}),!0}catch{}return!1}const EUn=/(\d+)-(\d+)\/(\d+)/;class Abt{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||PUn,this.controller=new self.AbortController,this.stats=new kXe}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=TUn(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&&Mi(c)?c:d,this.requestTimeout=self.setTimeout(()=>{this.callbacks&&(this.abortInternal(),this.callbacks.onTimeout(a,t,this.response))},n.timeout),(yQ(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:g,statusText:y}=h;throw new IUn(y||"fetch, bad network response",g,h)}a.loading.first=p,a.total=LUn(h.headers)||a.total;const x=(m=this.callbacks)==null?void 0:m.onProgress;return x&&Mi(n.highWaterMark)?this.loadProgressively(h,a,t,n.highWaterMark,x):l?h.arrayBuffer():t.responseType==="json"?h.json():h.text()}).then(h=>{var m,p;const x=this.response;if(!x)throw new Error("loader destroyed");self.clearTimeout(this.requestTimeout),a.loading.end=Math.max(self.performance.now(),a.loading.first);const g=h[o];g&&(a.loaded=a.total=g);const y={url:x.url,data:h,code:x.status},b=(m=this.callbacks)==null?void 0:m.onProgress;b&&!Mi(n.highWaterMark)&&b(a,t,h,x),(p=this.callbacks)==null||p.onSuccess(y,a,t,x)}).catch(h=>{var m;if(self.clearTimeout(this.requestTimeout),a.aborted)return;const p=h&&h.code||0,x=h?h.message:null;(m=this.callbacks)==null||m.onError({code:p,text:x},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 QHt,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 TUn(s,t){const n={method:"GET",mode:"cors",credentials:"same-origin",signal:t,headers:new self.Headers(dh({},s.headers))};return s.rangeEnd&&n.headers.set("Range","bytes="+s.rangeStart+"-"+String(s.rangeEnd-1)),n}function MUn(s){const t=EUn.exec(s);if(t)return parseInt(t[2])-parseInt(t[1])+1}function LUn(s){const t=s.get("Content-Range");if(t){const r=MUn(t);if(Mi(r))return r}const n=s.get("Content-Length");if(n)return parseInt(n)}function PUn(s,t){return new self.Request(s.url,t)}class IUn extends Error{constructor(t,n,r){super(t),this.code=void 0,this.details=void 0,this.code=n,this.details=r}}const DUn=/^age:\s*[\d.]+\s*$/im;class qGt{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 kXe,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&&Mi(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 x=u??n.response;if(x!=null){var l,o;r.loading.end=Math.max(self.performance.now(),r.loading.first);const g=n.responseType==="arraybuffer"?x.byteLength:x.length;r.loaded=r.total=g,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,x,n);const b={url:n.responseURL,data:x,code:d};(o=this.callbacks)==null||o.onSuccess(b,r,t,n);return}}const h=i.loadPolicy.errorRetry,m=r.retry,p={url:t.url,data:void 0,code:d};if(V4e(h,m,!1,p))this.retry(h);else{var c;Yu.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(V4e(t,n,!0))this.retry(t);else{var r;Yu.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=EXe(t,r.retry),r.retry++,Yu.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&&DUn.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 RUn={maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:null,errorRetry:null},OUn=qu(qu({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:qGt,fLoader:void 0,pLoader:void 0,xhrSetup:void 0,licenseXhrSetup:void 0,licenseResponseCallback:void 0,abrController:Y9n,bufferController:zBn,capLevelController:qXe,errorController:ezn,fpsController:B$n,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:$Ht,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:RUn},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},FUn()),{},{subtitleStreamController:Q$n,subtitleTrackController:q$n,timelineController:NUn,audioStreamController:DBn,audioTrackController:RBn,emeController:NB,cmcdController:R$n,contentSteeringController:F$n,interstitialsController:X$n});function FUn(){return{cueHandler:CUn,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 zUn(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=RUe(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}": ${Lh(t[o])}`)}),qu(qu({},r),t)}function RUe(s){return s&&typeof s=="object"?Array.isArray(s)?s.map(RUe):Object.keys(s).reduce((t,n)=>(t[n]=RUe(s[n]),t),{}):s}function BUn(s,t){const n=s.loader;n!==Abt&&n!==qGt?(t.log("[config]: Custom loader detected, cannot enable progressive streaming"),s.progressive=!1):AUn()&&(s.loader=Abt,s.progressive=!0,s.enableSoftwareAES=!0,t.log("[config]: Progressive streaming enabled, using FetchLoader"))}const $Ne=2,$Un=.1,UUn=.05,qUn=100;class VUn extends RHt{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(Dt.MEDIA_ENDED,{stalled:!1})}},this.hls=t,this.fragmentTracker=n,this.registerListeners()}registerListeners(){const{hls:t}=this;t&&(t.on(Dt.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(Dt.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(Dt.BUFFER_APPENDED,this.onBufferAppended,this))}unregisterListeners(){const{hls:t}=this;t&&(t.off(Dt.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(Dt.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(Dt.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(qUn),this.mediaSource=n.mediaSource;const r=this.media=n.media;m1(r,"playing",this.onMediaPlaying),m1(r,"waiting",this.onMediaWaiting),m1(r,"ended",this.onMediaEnded)}onMediaDetaching(t,n){this.clearInterval();const{media:r}=this;r&&(kb(r,"playing",this.onMediaPlaying),kb(r,"waiting",this.onMediaWaiting),kb(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(Dt.MEDIA_ENDED,{stalled:!1}));return}if(!Bl.getBuffered(l).length){this.nudgeRetry=0;return}const h=Bl.bufferInfo(l,t,0),m=h.nextStart||0,p=this.fragmentTracker;if(o&&p&&this.hls){const T=Ebt(this.hls.inFlightFragments,t),P=h.len>$Ne,M=!m||T||m-t>$Ne&&!p.getPartialFragment(t);if(P||M)return;this.moved=!1}const x=(a=this.hls)==null?void 0:a.latestLevelDetails;if(!this.moved&&this.stalled!==null&&p){if(!(h.len>0)&&!m)return;const P=Math.max(m,h.start||0)-t,I=!!(x!=null&&x.live)?x.targetduration*2:$Ne,D=Dae(t,p);if(P>0&&(P<=I||D)){l.paused||this._trySkipBufferHole(D);return}}const g=i.detectStallWithCurrentTimeMs,y=self.performance.now(),b=this.waiting;let v=this.stalled;if(v===null)if(b>0&&y-b=g||b)&&this.hls){var C;if(((C=this.mediaSource)==null?void 0:C.readyState)==="ended"&&!(x!=null&&x.live)&&Math.abs(t-((x==null?void 0:x.edge)||0))<1){if(this.ended)return;this.ended=t||1,this.hls.trigger(Dt.MEDIA_ENDED,{stalled:!0});return}if(this._reportStall(h),!this.media||!this.hls)return}const A=Bl.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(Dt.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=Bl.bufferedInfo(Bl.timeRangesToArray(this.buffered.audio),t,0);if(i.len>1&&n>=i.start){const l=Bl.timeRangesToArray(a),o=Bl.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=Dae(t,this.fragmentTracker);m&&"fragment"in m?m=m.fragment:m||(m=void 0);const p=Bl.bufferInfo(this.media,t,0);this.hls.trigger(Dt.ERROR,{type:mo.MEDIA_ERROR,details:fr.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=Dae(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,Gi.MAIN),l=r.getFragAtPos(a,Gi.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 (${Lh(t)})`);this.warn(l.message),n.trigger(Dt.ERROR,{type:mo.MEDIA_ERROR,details:fr.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=Bl.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 x=!1;if(l===0){const g=r.getAppendedFrag(0,Gi.MAIN);g&&c"u"))return self.VTTCue||self.TextTrackCue}function sRe(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,Lh(a?qu({type:a},r):r))}return i}const Rae=(()=>{const s=OUe();try{s&&new s(0,Number.POSITIVE_INFINITY,"")}catch{return Number.MAX_VALUE}return Number.POSITIVE_INFINITY})();class GUn{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(Dt.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(Dt.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on(Dt.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(Dt.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(Dt.MANIFEST_LOADING,this.onManifestLoading,this),t.on(Dt.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),t.on(Dt.BUFFER_FLUSHING,this.onBufferFlushing,this),t.on(Dt.LEVEL_UPDATED,this.onLevelUpdated,this),t.on(Dt.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this))}_unregisterListeners(){const{hls:t}=this;t&&(t.off(Dt.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off(Dt.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(Dt.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(Dt.MANIFEST_LOADING,this.onManifestLoading,this),t.off(Dt.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),t.off(Dt.BUFFER_FLUSHING,this.onBufferFlushing,this),t.off(Dt.LEVEL_UPDATED,this.onLevelUpdated,this),t.off(Dt.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&&rz(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;nRae&&(h=Rae),h-u<=0&&(h=u+HUn);for(let p=0;pu.type===q_.audioId3&&c:a==="video"?d=u=>u.type===q_.emsg&&o:d=u=>u.type===q_.audioId3&&c||u.type===q_.emsg&&o,IUe(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=OUe();if(r&&a&&!l){const{fragmentStart:g,fragmentEnd:y}=t;let b=this.assetCue;b?(b.startTime=g,b.endTime=y):o&&(b=this.assetCue=sRe(o,g,y,{assetPlayerId:this.hls.config.assetPlayerId},"hlsjs.interstitial.asset"),b&&(b.id=r,this.id3Track||(this.id3Track=this.createTrack(this.media)),this.id3Track.addCue(b),b.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 g=Object.keys(h).filter(y=>!u.includes(y));for(let y=g.length;y--;){var p;const b=g[y],v=(p=h[b])==null?void 0:p.cues;delete h[b],v&&Object.keys(v).forEach(N=>{const C=v[N];if(C){C.removeEventListener("enter",this.onEventCueEnter);try{c.removeCue(C)}catch{}}})}}else h=this.dateRangeCuesAppended={}}const x=t.fragments[t.fragments.length-1];if(!(u.length===0||!Mi(x==null?void 0:x.programDateTime))){this.id3Track||(this.id3Track=this.createTrack(this.media));for(let g=0;g{if(q!==b.id){const W=d[q];if(W.class===b.class&&W.startDate>b.startDate&&(!B||b.startDate.01&&(q.startTime=v,q.endTime=T);else if(o){let W=b.attr[B];pzn(B)&&(W=xHt(W));const K=sRe(o,v,T,{key:B,data:W},q_.dateRange);K&&(K.id=y,this.id3Track.addCue(K),C[B]=K,l&&(B==="X-ASSET-LIST"||B==="X-ASSET-URL")&&K.addEventListener("enter",this.onEventCueEnter))}}h[y]={cues:C,dateRange:b,durationKnown:A}}}}}class WUn{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(Dt.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(Dt.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(Dt.MANIFEST_LOADING,this.onManifestLoading,this),t.on(Dt.LEVEL_UPDATED,this.onLevelUpdated,this),t.on(Dt.ERROR,this.onError,this))}unregisterListeners(){const{hls:t}=this;t&&(t.off(Dt.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(Dt.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(Dt.MANIFEST_LOADING,this.onManifestLoading,this),t.off(Dt.LEVEL_UPDATED,this.onLevelUpdated,this),t.off(Dt.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===fr.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 KUn extends UXe{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(Dt.MANIFEST_LOADING,this.onManifestLoading,this),t.on(Dt.MANIFEST_LOADED,this.onManifestLoaded,this),t.on(Dt.LEVEL_LOADED,this.onLevelLoaded,this),t.on(Dt.LEVELS_UPDATED,this.onLevelsUpdated,this),t.on(Dt.FRAG_BUFFERED,this.onFragBuffered,this),t.on(Dt.ERROR,this.onError,this)}_unregisterListeners(){const{hls:t}=this;t.off(Dt.MANIFEST_LOADING,this.onManifestLoading,this),t.off(Dt.MANIFEST_LOADED,this.onManifestLoaded,this),t.off(Dt.LEVEL_LOADED,this.onLevelLoaded,this),t.off(Dt.LEVELS_UPDATED,this.onLevelsUpdated,this),t.off(Dt.FRAG_BUFFERED,this.onFragBuffered,this),t.off(Dt.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=B4e(m,r)||void 0),p&&(p=u.videoCodec=T9n(p));const{width:x,height:g,unknownCodecs:y}=u,b=(y==null?void 0:y.length)||0;if(o||(o=!!(x&&g)),c||(c=!!p),d||(d=!!m),b||m&&!this.isAudioSupported(m)||p&&!this.isVideoSupported(p)){this.log(`Some or all CODECS not supported "${h.CODECS}"`);return}const{CODECS:v,"FRAME-RATE":N,"HDCP-LEVEL":C,"PATHWAY-ID":A,RESOLUTION:T,"VIDEO-RANGE":P}=h,I=`${`${A||"."}-`}${u.bitrate}-${T}-${N}-${v}-${P}-${C}`;if(i[I])if(i[I].uri!==u.url&&!u.attrs["PATHWAY-ID"]){const D=l[I]+=1;u.attrs["PATHWAY-ID"]=new Array(D+1).join(".");const B=this.createLevel(u);i[I]=B,a.push(B)}else i[I].addGroupId("audio",h.AUDIO),i[I].addGroupId("text",h.SUBTITLES);else{const D=this.createLevel(u);i[I]=D,l[I]=1,a.push(D)}}),this.filterAndSortMediaOptions(a,n,o,c,d)}createLevel(t){const n=new fQ(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=AHt(a,[])}return n}isAudioSupported(t){return mQ(t,"audio",this.hls.config.preferManagedMediaSource)}isVideoSupported(t){return mQ(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:v,videoRange:N,width:C,height:A})=>(!!v||!!(C&&A))&&B9n(N))),d.length===0){Promise.resolve().then(()=>{if(this.hls){let v="no level with compatible codecs found in manifest",N=v;n.levels.length&&(N=`one or more CODECS in variant not supported: ${Lh(n.levels.map(A=>A.attrs.CODECS).filter((A,T,P)=>P.indexOf(A)===T))}`,this.warn(N),v+=` (${N})`);const C=new Error(v);this.hls.trigger(Dt.ERROR,{type:mo.MEDIA_ERROR,details:fr.MANIFEST_INCOMPATIBLE_CODECS_ERROR,fatal:!0,url:n.url,error:C,reason:N})}}),u.end=performance.now();return}n.audioTracks&&(o=n.audioTracks.filter(v=>!v.audioCodec||this.isAudioSupported(v.audioCodec)),Mbt(o)),n.subtitles&&(c=n.subtitles,Mbt(c));const h=d.slice(0);d.sort((v,N)=>{if(v.attrs["HDCP-LEVEL"]!==N.attrs["HDCP-LEVEL"])return(v.attrs["HDCP-LEVEL"]||"")>(N.attrs["HDCP-LEVEL"]||"")?1:-1;if(r&&v.height!==N.height)return v.height-N.height;if(v.frameRate!==N.frameRate)return v.frameRate-N.frameRate;if(v.videoRange!==N.videoRange)return $4e.indexOf(v.videoRange)-$4e.indexOf(N.videoRange);if(v.videoCodec!==N.videoCodec){const C=w1t(v.videoCodec),A=w1t(N.videoCodec);if(C!==A)return A-C}if(v.uri===N.uri&&v.codecSet!==N.codecSet){const C=z4e(v.codecSet),A=z4e(N.codecSet);if(C!==A)return A-C}return v.averageBitrate!==N.averageBitrate?v.averageBitrate-N.averageBitrate:0});let m=h[0];if(this.steering&&(d=this.steering.filterParsedLevels(d),d.length!==h.length)){for(let v=0;vC&&C===this.hls.abrEwmaDefaultEstimate&&(this.hls.bandwidthEstimate=A)}break}const x=i&&!a,g=this.hls.config,y=!!(g.audioStreamController&&g.audioTrackController),b={levels:d,audioTracks:o,subtitleTracks:c,sessionData:n.sessionData,sessionKeys:n.sessionKeys,firstLevel:this._firstLevel,stats:n.stats,audio:i,video:a,altAudio:y&&!x&&o.some(v=>!!v.url)};u.end=performance.now(),this.hls.trigger(Dt.MANIFEST_PARSED,b)}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(Dt.ERROR,{type:mo.OTHER_ERROR,details:fr.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(Dt.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===$c.LEVEL&&n.context.level===this.level&&this.checkRetry(n)}onFragBuffered(t,{frag:n}){if(n!==void 0&&n.type===Gi.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(Dt.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));YHt(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(Dt.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(Dt.MAX_AUTO_LEVEL_UPDATED,{autoLevelCapping:t,levels:this.levels,maxAutoLevel:n,minAutoLevel:this.hls.minAutoLevel,maxHdcpLevel:r}))}}function Mbt(s){const t={};s.forEach(n=>{const r=n.groupId||"";n.id=t[r]=t[r]||0,t[r]++})}function VGt(){return self.SourceBuffer||self.WebKitSourceBuffer}function HGt(){if(!f6())return!1;const t=VGt();return!t||t.prototype&&typeof t.prototype.appendBuffer=="function"&&typeof t.prototype.remove=="function"}function YUn(){if(!HGt())return!1;const s=f6();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(pQ(t,"video")))||["mp4a.40.2","fLaC"].some(t=>s.isTypeSupported(pQ(t,"audio"))))}function ZUn(){var s;const t=VGt();return typeof(t==null||(s=t.prototype)==null?void 0:s.changeType)=="function"}const XUn=100;class QUn extends IXe{constructor(t,n,r){super(t,n,r,"stream-controller",Gi.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||!Mi(i)||(this.log(`Media seeked to ${i.toFixed(3)}`),!this.getBufferedFrag(i)))return;const l=this.getFwdBufferInfoAtPos(a,i,Gi.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(Dt.MANIFEST_PARSED,this.onManifestParsed,this),t.on(Dt.LEVEL_LOADING,this.onLevelLoading,this),t.on(Dt.LEVEL_LOADED,this.onLevelLoaded,this),t.on(Dt.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),t.on(Dt.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.on(Dt.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),t.on(Dt.BUFFER_CREATED,this.onBufferCreated,this),t.on(Dt.BUFFER_FLUSHED,this.onBufferFlushed,this),t.on(Dt.LEVELS_UPDATED,this.onLevelsUpdated,this),t.on(Dt.FRAG_BUFFERED,this.onFragBuffered,this)}unregisterListeners(){super.unregisterListeners();const{hls:t}=this;t.off(Dt.MANIFEST_PARSED,this.onManifestParsed,this),t.off(Dt.LEVEL_LOADED,this.onLevelLoaded,this),t.off(Dt.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),t.off(Dt.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.off(Dt.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),t.off(Dt.BUFFER_CREATED,this.onBufferCreated,this),t.off(Dt.BUFFER_FLUSHED,this.onBufferFlushed,this),t.off(Dt.LEVELS_UPDATED,this.onLevelsUpdated,this),t.off(Dt.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(XUn),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=ea.IDLE,this.nextLoadPosition=this.lastCurrentTime=t+this.timelineOffset,this.startPosition=n?-1:t,this.tick()}else this._forceStartLoad=!0,this.state=ea.STOPPED}stopLoad(){this._forceStartLoad=!1,super.stopLoad()}doTick(){switch(this.state){case ea.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=ea.IDLE;break}else if(this.hls.nextLoadLevel!==this.level){this.state=ea.IDLE;break}break}case ea.FRAG_LOADING_WAITING_RETRY:this.checkRetryDate();break}this.state===ea.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 g={};this.altAudio===2&&(g.type="video"),this.hls.trigger(Dt.BUFFER_EOS,g),this.state=ea.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===ea.WAITING_LEVEL||this.waitForLive(l)){this.level=i,this.state=ea.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&&Jf(p)&&this.fragmentTracker.getState(p)!==ug.OK){var x;const y=((x=this.backtrackFragment)!=null?x:p).sn-d.startSN,b=d.fragments[y-1];b&&p.cc===b.cc&&(p=b,this.fragmentTracker.removeFragment(b))}else this.backtrackFragment&&o.len&&(this.backtrackFragment=null);if(p&&this.isLoopLoading(p,m)){if(!p.gap){const y=this.audioOnly&&!this.altAudio?kh.AUDIO:kh.VIDEO,b=(y===kh.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;b&&this.afterBufferFlushed(b,y,Gi.MAIN)}p=this.getNextFragmentLoopLoading(p,d,o,Gi.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===ug.NOT_LOADED||a===ug.PARTIAL?Jf(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,Gi.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(Dt.AUDIO_TRACK_SWITCHED,n)}),r.trigger(Dt.BUFFER_FLUSHING,{startOffset:0,endOffset:Number.POSITIVE_INFINITY,type:null});return}r.trigger(Dt.AUDIO_TRACK_SWITCHED,n)}}onAudioTrackSwitched(t,n){const r=U4e(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===Gi.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===ea.PARSED&&(this.state=ea.IDLE);return}const o=a?a.stats:r.stats;this.fragLastKbps=Math.round(8*o.total/(o.buffering.end-o.loading.first)),Jf(r)&&(this.fragPrevious=r),this.fragBufferedComplete(r,a)}const l=this.media;l&&(!this._hasEnoughToStart&&Bl.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=ea.ERROR;return}switch(n.details){case fr.FRAG_GAP:case fr.FRAG_PARSING_ERROR:case fr.FRAG_DECRYPT_ERROR:case fr.FRAG_LOAD_ERROR:case fr.FRAG_LOAD_TIMEOUT:case fr.KEY_LOAD_ERROR:case fr.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(Gi.MAIN,n);break;case fr.LEVEL_LOAD_ERROR:case fr.LEVEL_LOAD_TIMEOUT:case fr.LEVEL_PARSING_ERROR:!n.levelRetry&&this.state===ea.WAITING_LEVEL&&((r=n.context)==null?void 0:r.type)===$c.LEVEL&&(this.state=ea.IDLE);break;case fr.BUFFER_ADD_CODEC_ERROR:case fr.BUFFER_APPEND_ERROR:if(n.parent!=="main")return;this.reduceLengthAndFlushBuffer(n)&&this.resetLoadingState();break;case fr.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 fr.INTERNAL_EXCEPTION:this.recoverWorkerError(n);break}}onFragLoadEmergencyAborted(){this.state=ea.IDLE,this._hasEnoughToStart||(this.startFragRequested=!1,this.nextLoadPosition=this.lastCurrentTime),this.tickImmediate()}onBufferFlushed(t,{type:n}){if(n!==kh.AUDIO||!this.altAudio){const r=(n===kh.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;r&&(this.afterBufferFlushed(r,n,Gi.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=ea.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(Dt.FRAG_LOADED,r),i.bitrateTest=!1}).catch(r=>{this.state===ea.STOPPED||this.state===ea.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:x}=d,g=this.altAudio?void 0:a.audio;if(this.fragContextChanged(o)){this.fragmentTracker.removeFragment(o);return}if(this.state=ea.PARSING,p){const y=p.tracks;if(y){const C=o.initSegment||o;if(this.unhandledEncryptionError(p,o))return;this._bufferInitSegment(d,y,C,i),r.trigger(Dt.FRAG_PARSING_INIT_SEGMENT,{frag:C,id:n,tracks:y})}const b=p.initPTS,v=p.timescale,N=this.initPTS[o.cc];if(Mi(b)&&(!N||N.baseTime!==b||N.timescale!==v)){const C=p.trackId;this.initPTS[o.cc]={baseTime:b,timescale:v,trackId:C},r.trigger(Dt.INIT_PTS_FOUND,{frag:o,id:n,initPTS:b,timescale:v,trackId:C})}}if(u&&x){g&&u.type==="audiovideo"&&this.logMuxedErr(o);const y=x.fragments[o.sn-1-x.startSN],b=o.sn===x.startSN,v=!y||o.cc>y.cc;if(a.independent!==!1){const{startPTS:N,endPTS:C,startDTS:A,endDTS:T}=u;if(c)c.elementaryStreams[u.type]={startPTS:N,endPTS:C,startDTS:A,endDTS:T};else if(u.firstKeyFrame&&u.independent&&i.id===1&&!v&&(this.couldBacktrack=!0),u.dropped&&u.independent){const P=this.getMainFwdBufferInfo(),M=(P?P.end:this.getLoadPosition())+this.config.maxBufferHole,I=u.firstKeyFramePTS?u.firstKeyFramePTS:N;if(!b&&M$Ne&&(o.gap=!0);o.setElementaryStreamInfo(u.type,N,C,A,T),this.backtrackFragment&&(this.backtrackFragment=o),this.bufferFragmentData(u,o,c,i,b||v)}else if(b||v)o.gap=!0;else{this.backtrack(o);return}}if(g){const{startPTS:y,endPTS:b,startDTS:v,endDTS:N}=g;c&&(c.elementaryStreams[kh.AUDIO]={startPTS:y,endPTS:b,startDTS:v,endDTS:N}),o.setElementaryStreamInfo(kh.AUDIO,y,b,v,N),this.bufferFragmentData(g,o,c,i)}if(x&&m!=null&&m.samples.length){const y={id:n,frag:o,details:x,samples:m.samples};r.trigger(Dt.FRAG_PARSING_METADATA,y)}if(x&&h){const y={id:n,frag:o,details:x,samples:h.samples};r.trigger(Dt.FRAG_PARSING_USERDATA,y)}}logMuxedErr(t){this.warn(`${Jf(t)?"Media":"Init"} segment with muxed audiovideo where only video expected: ${t.url}`)}_bufferInitSegment(t,n,r,a){if(this.state!==ea.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=INe(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=Gi.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=Gi.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(Dt.BUFFER_CODECS,n),!this.hls)return;c.forEach(d=>{const h=n[d].initSegment;h!=null&&h.byteLength&&this.hls.trigger(Dt.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,Gi.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=ea.IDLE}checkFragmentChanged(){const t=this.media;let n=null;if(t&&t.readyState>1&&t.seeking===!1){const r=t.currentTime;if(Bl.isBuffered(t,r)?n=this.getAppendedFrag(r):Bl.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(Dt.FRAG_CHANGED,{frag:n}),(!a||a.level!==i)&&this.hls.trigger(Dt.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 Mi(n)?this.getAppendedFrag(n):null}get currentProgramDateTime(){var t;const n=((t=this.media)==null?void 0:t.currentTime)||this.lastCurrentTime;if(Mi(n)){const r=this.getLevelDetails(),a=this.currentFrag||(r?$O(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 JUn extends v2{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=fr.KEY_LOAD_ERROR,r,a,i){return new H4({type:mo.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=RNe(o);if(c)return this.emeController.getKeySystemAccess([c])})}if(this.config.requireKeySystemAccessOnStart){const a=JW(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,fr.KEY_LOAD_ERROR,d))}const l=i.uri;if(!l)return Promise.reject(this.createKeyLoadError(t,fr.KEY_LOAD_ERROR,new Error(`Invalid key URI: "${l}"`)));const o=nRe(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: "+ly(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,fr.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=y9n(n.initSegment.data);if(l.length){let o=l[0];o.some(c=>c!==0)?(this.log(`Using keyId found in init segment ${ly(o)}`),KT.setKeyIdForUri(t.decryptdata.uri,o)):(o=KT.addKeyIdForUri(t.decryptdata.uri),this.log(`Generating keyId to patch media ${ly(o)}`)),t.decryptdata.keyId=o}}if(!t.decryptdata.keyId&&!Jf(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,x,g)=>{const{frag:y,keyInfo:b}=x,v=nRe(b.decryptdata);if(!y.decryptdata||b!==this.keyIdToKeyInfo[v])return o(this.createKeyLoadError(y,fr.KEY_LOAD_ERROR,new Error("after key load, decryptdata unset or changed"),g));b.decryptdata.key=y.decryptdata.key=new Uint8Array(m.data),y.keyLoader=null,b.loader=null,l({frag:y,keyInfo:b})},onError:(m,p,x,g)=>{this.resetLoader(p),o(this.createKeyLoadError(n,fr.KEY_LOAD_ERROR,new Error(`HTTP Error ${m.code} loading key ${m.text}`),x,qu({url:c.url,data:void 0},m)))},onTimeout:(m,p,x)=>{this.resetLoader(p),o(this.createKeyLoadError(n,fr.KEY_LOAD_TIMEOUT,new Error("key loading timed out"),x))},onAbort:(m,p,x)=>{this.resetLoader(p),o(this.createKeyLoadError(n,fr.INTERNAL_ABORTED,new Error("key loading aborted"),x))}};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=nRe(r.decryptdata)||a;delete this.keyIdToKeyInfo[l],i&&i.destroy()}}function nRe(s){if(s.keyFormat!==hy.FAIRPLAY){const t=s.keyId;if(t)return ly(t)}return s.uri}function Lbt(s){const{type:t}=s;switch(t){case $c.AUDIO_TRACK:return Gi.AUDIO;case $c.SUBTITLE_TRACK:return Gi.SUBTITLE;default:return Gi.MAIN}}function rRe(s,t){let n=s.url;return(n===void 0||n.indexOf("data:")===0)&&(n=t.url),n}class eqn{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(Dt.MANIFEST_LOADING,this.onManifestLoading,this),t.on(Dt.LEVEL_LOADING,this.onLevelLoading,this),t.on(Dt.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),t.on(Dt.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),t.on(Dt.LEVELS_UPDATED,this.onLevelsUpdated,this)}unregisterListeners(){const{hls:t}=this;t.off(Dt.MANIFEST_LOADING,this.onManifestLoading,this),t.off(Dt.LEVEL_LOADING,this.onLevelLoading,this),t.off(Dt.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),t.off(Dt.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),t.off(Dt.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:$c.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:$c.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:$c.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:$c.SUBTITLE_TRACK,url:i,deliveryDirectives:l,levelOrTrack:o})}onLevelsUpdated(t,n){const r=this.loaders[$c.LEVEL];if(r){const a=r.context;a&&!n.levels.some(i=>i===a.levelOrTrack)&&(r.abort(),delete this.loaders[$c.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===$c.MANIFEST?i=r.manifestLoadPolicy.default:i=dh({},r.playlistLoadPolicy.default,{timeoutRetry:null,errorRetry:null}),a=this.createInternalLoader(t),Mi((n=t.deliveryDirectives)==null?void 0:n.part)){let d;if(t.type===$c.LEVEL&&t.level!==null?d=this.hls.levels[t.level].details:t.type===$c.AUDIO_TRACK&&t.id!==null?d=this.hls.audioTracks[t.id].details:t.type===$c.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=dh({},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 x=d.data;u.parsing.start=performance.now(),YS.isMediaPlaylist(x)||h.type!==$c.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=rRe(t,r),c=YS.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:x}=c;this.variableList=x,u.forEach(v=>{const{unknownCodecs:N}=v;if(N){const{preferManagedMediaSource:C}=this.hls.config;let{audioCodec:A,videoCodec:T}=v;for(let P=N.length;P--;){const M=N[P];mQ(M,"audio",C)?(v.audioCodec=A=A?`${A},${M}`:M,sq.audio[A.substring(0,4)]=2,N.splice(P,1)):mQ(M,"video",C)&&(v.videoCodec=T=T?`${T},${M}`:M,sq.video[T.substring(0,4)]=2,N.splice(P,1))}}});const{AUDIO:g=[],SUBTITLES:y,"CLOSED-CAPTIONS":b}=YS.parseMasterPlaylistMedia(l,o,c);g.length&&!g.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"),g.unshift({type:"main",name:"main",groupId:"main",default:!1,autoselect:!1,forced:!1,id:-1,attrs:new Sp({}),bitrate:0,url:""})),i.trigger(Dt.MANIFEST_LOADED,{levels:u,audioTracks:g,subtitles:y,captions:b,contentSteering:d,url:o,stats:n,networkDetails:a,sessionData:h,sessionKeys:m,startTimeOffset:p,variableList:x})}handleTrackOrLevelPlaylist(t,n,r,a,i){const l=this.hls,{id:o,level:c,type:d}=r,u=rRe(t,r),h=Mi(c)?c:Mi(o)?o:0,m=Lbt(r),p=YS.parseLevelPlaylist(t.data,u,h,m,0,this.variableList);if(d===$c.MANIFEST){const x={attrs:new Sp({}),bitrate:0,details:p,name:"",url:u};p.requestScheduled=n.loading.start+GHt(p,0),l.trigger(Dt.MANIFEST_LOADED,{levels:[x],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(Dt.ERROR,{type:mo.NETWORK_ERROR,details:fr.MANIFEST_PARSING_ERROR,fatal:n.type===$c.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===$c.LEVEL?l+=`: ${t.level} id: ${t.id}`:(t.type===$c.AUDIO_TRACK||t.type===$c.SUBTITLE_TRACK)&&(l+=` id: ${t.id} group-id: "${t.groupId}"`);const o=new Error(l);this.hls.logger.warn(`[playlist-loader]: ${l}`);let c=fr.UNKNOWN,d=!1;const u=this.getInternalLoader(t);switch(t.type){case $c.MANIFEST:c=r?fr.MANIFEST_LOAD_TIMEOUT:fr.MANIFEST_LOAD_ERROR,d=!0;break;case $c.LEVEL:c=r?fr.LEVEL_LOAD_TIMEOUT:fr.LEVEL_LOAD_ERROR,d=!1;break;case $c.AUDIO_TRACK:c=r?fr.AUDIO_TRACK_LOAD_TIMEOUT:fr.AUDIO_TRACK_LOAD_ERROR,d=!1;break;case $c.SUBTITLE_TRACK:c=r?fr.SUBTITLE_TRACK_LOAD_TIMEOUT:fr.SUBTITLE_LOAD_ERROR,d=!1;break}u&&this.resetInternalLoader(t.type);const h={type:mo.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=qu({url:m,data:void 0},a)}this.hls.trigger(Dt.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,x=rRe(n,a),g=Lbt(a);let y=typeof a.level=="number"&&g===Gi.MAIN?d:void 0;const b=t.playlistParsingError;if(b){if(this.hls.logger.warn(`${b} ${t.url}`),!o.config.ignorePlaylistParsingErrors){o.trigger(Dt.ERROR,{type:mo.NETWORK_ERROR,details:fr.LEVEL_PARSING_ERROR,fatal:!1,url:x,error:b,reason:b.message,response:n,context:a,level:y,parent:g,networkDetails:i,stats:r});return}t.playlistParsingError=null}if(!t.fragments.length){const v=t.playlistParsingError=new Error("No Segments found in Playlist");o.trigger(Dt.ERROR,{type:mo.NETWORK_ERROR,details:fr.LEVEL_EMPTY_ERROR,fatal:!1,url:x,error:v,reason:v.message,response:n,context:a,level:y,parent:g,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 $c.MANIFEST:case $c.LEVEL:if(y){if(!u)y=0;else if(u!==o.levels[y]){const v=o.levels.indexOf(u);v>-1&&(y=v)}}o.trigger(Dt.LEVEL_LOADED,{details:t,levelInfo:u||o.levels[0],level:y||0,id:h||0,stats:r,networkDetails:i,deliveryDirectives:p,withoutMultiVariant:c===$c.MANIFEST});break;case $c.AUDIO_TRACK:o.trigger(Dt.AUDIO_TRACK_LOADED,{details:t,track:u,id:h||0,groupId:m||"",stats:r,networkDetails:i,deliveryDirectives:p});break;case $c.SUBTITLE_TRACK:o.trigger(Dt.SUBTITLE_TRACK_LOADED,{details:t,track:u,id:h||0,groupId:m||"",stats:r,networkDetails:i,deliveryDirectives:p});break}}}class zS{static get version(){return xQ}static isMSESupported(){return HGt()}static isSupported(){return YUn()}static getMediaSource(){return f6()}static get Events(){return Dt}static get MetadataSchema(){return q_}static get ErrorTypes(){return mo}static get ErrorDetails(){return fr}static get DefaultConfig(){return zS.defaultConfig?zS.defaultConfig:OUn}static set DefaultConfig(t){zS.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 DXe,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=i9n(t.debug||!1,"Hls instance",t.assetPlayerId),r=this.config=zUn(zS.DefaultConfig,t,n);this.userConfig=t,r.progressive&&BUn(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 tzn(this),m=r.interstitialsController,p=m?this.interstitialsController=new m(this,zS):null,x=this.bufferController=new i(this,h),g=this.capLevelController=new l(this),y=new c(this),b=new eqn(this),v=r.contentSteeringController,N=v?new v(this):null,C=this.levelController=new KUn(this,N),A=new GUn(this),T=new JUn(this.config,this.logger),P=this.streamController=new QUn(this,h,T),M=this.gapController=new VUn(this,h);g.setStreamController(P),y.setStreamController(P);const I=[b,C,P];p&&I.splice(1,0,p),N&&I.splice(1,0,N),this.networkControllers=I;const D=[u,x,M,g,y,A,h];this.audioTrackController=this.createController(r.audioTrackController,I);const B=r.audioStreamController;B&&I.push(this.audioStreamController=new B(this,h,T)),this.subtitleTrackController=this.createController(r.subtitleTrackController,I);const q=r.subtitleStreamController;q&&I.push(this.subtititleStreamController=new q(this,h,T)),this.createController(r.timelineController,D),T.emeController=this.emeController=this.createController(r.emeController,D),this.cmcdController=this.createController(r.cmcdController,D),this.latencyController=this.createController(WUn,D),this.coreComponents=D,I.push(d);const W=d.onErrorOut;typeof W=="function"&&this.on(Dt.ERROR,W,d),this.on(Dt.MANIFEST_LOADED,b.onManifestLoaded,b)}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===Dt.ERROR;this.trigger(Dt.ERROR,{type:mo.OTHER_ERROR,details:fr.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(Dt.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(Dt.ERROR,{type:mo.OTHER_ERROR,details:fr.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(Dt.MEDIA_ATTACHING,a)}detachMedia(){this.logger.log("detachMedia"),this.trigger(Dt.MEDIA_DETACHING,{}),this._media=null}transferMedia(){this._media=null;const t=this.bufferController.transferMedia();return this.trigger(Dt.MEDIA_DETACHING,{transferMedia:t}),t}loadSource(t){this.stopLoad();const n=this.media,r=this._url,a=this._url=NXe.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(Dt.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={[Gi.MAIN]:this.streamController.inFlightFrag};return this.audioStreamController&&(t[Gi.AUDIO]=this.audioStreamController.inFlightFrag),this.subtititleStreamController&&(t[Gi.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=V$n()),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){z9n(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=MHt(n);return EHt(t,r,navigator.mediaCapabilities)}}zS.defaultConfig=void 0;const tqn=/(?:player\.mediadelivery\.net|iframe\.mediadelivery\.net|iframe\.n\.net|video\.bunnycdn\.com|[a-z0-9-]+\.b-cdn\.net)/i;function az(s){return!!s&&tqn.test(s)&&!/\.mp4($|\?)/i.test(s)}function sqn(s){const t=s.match(/\/(?:play|embed)\/(\d+)\/([a-z0-9-]+)/i);return t?{libraryId:t[1],videoId:t[2]}:null}function nqn(s,t){if(!s)return null;const n=sqn(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 rqn(s){const t=s.match(/https:\/\/[^"']+playlist\.m3u8[^"']*/i);return t?t[0].replace(/&/g,"&").replace(/\u0026/g,"&"):null}const FUe=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(()=>nqn(t,{autoplay:!!r,muted:!!a,loop:!!i}),[t,r,a,i]);j.useEffect(()=>{let x=!1;if(!t){h(null);return}if(!az(t)){h(t);return}if(!m){h(null);return}return h(null),fetch(m).then(async g=>{if(!g.ok)throw new Error(`Failed to load Bunny embed (${g.status})`);const y=await g.text();return rqn(y)}).then(g=>{x||h(g)}).catch(()=>{x||h(null)}),()=>{x=!0}},[m,t]),j.useEffect(()=>{const x=d.current;if(!x||!u)return;let g=null;const y=()=>{if(!r)return;const v=x.play();v&&v.catch(()=>{})};if(x.muted=!!a,x.loop=!!i,u.endsWith(".m3u8")){if(x.canPlayType("application/vnd.apple.mpegurl")){x.src=u;const v=()=>y();return x.addEventListener("loadedmetadata",v),()=>{x.removeEventListener("loadedmetadata",v),x.removeAttribute("src"),x.load()}}return zS.isSupported()?(g=new zS({enableWorker:!0,lowLatencyMode:!0}),g.loadSource(u),g.attachMedia(x),g.on(zS.Events.MANIFEST_PARSED,y),()=>{g==null||g.destroy(),x.removeAttribute("src"),x.load()}):void 0}x.src=u;const b=()=>y();return x.addEventListener("loadedmetadata",b),()=>{x.removeEventListener("loadedmetadata",b),x.removeAttribute("src"),x.load()}},[r,i,a,u]),j.useEffect(()=>{const x=d.current;if(x){if(x.muted=!!a,x.loop=!!i,r&&u){const g=x.play();g&&g.catch(()=>{});return}x.pause()}},[r,i,a,u]);const p=x=>{if(d.current=x,typeof c=="function"){c(x);return}c&&(c.current=x)};return e.jsx("video",{ref:p,poster:n||void 0,autoPlay:r,muted:a,loop:i,playsInline:l,preload:"metadata",...o})}),aqn={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 iqn(){try{let s=localStorage.getItem("vg_visitor_token");return s||(s=crypto.randomUUID(),localStorage.setItem("vg_visitor_token",s)),s}catch{return null}}function Pbt(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 KXe({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"),[x,g]=j.useState(!1),[y,b]=j.useState(!1),[v,N]=j.useState({name:"",email:"",phone:""}),[C,A]=j.useState(()=>({width:typeof window<"u"?window.innerWidth:1280,height:typeof window<"u"?window.innerHeight:720})),T=j.useRef(null),P=j.useRef(null),M=j.useRef(!1),I=async(Ae,Be)=>{if(!n)try{await U.from("widget_events").insert({user_id:s.user_id,app_slug:t,event_type:Ae,visitor_token:iqn(),page_url:typeof window<"u"?window.location.href:null,metadata:Be||{}})}catch{}};j.useEffect(()=>{if(u)return;const Ae=typeof window<"u"?window.location.pathname:"/",Be=s.targeting||{mode:"all"};if(Be.mode==="include"&&!Pbt(Be.include,Ae)||Be.mode==="exclude"&&Pbt(Be.exclude,Ae))return;const qe=s.trigger||{type:"immediate"};if(qe.type==="immediate"||n){i(!0);return}if(qe.type==="delay"){const Ke=(qe.value||3)*1e3,Ze=setTimeout(()=>i(!0),Ke);return()=>clearTimeout(Ze)}if(qe.type==="scroll"){const Ke=(qe.value||25)/100,Ze=()=>{(window.scrollY+window.innerHeight)/document.documentElement.scrollHeight>=Ke&&(i(!0),window.removeEventListener("scroll",Ze))};return window.addEventListener("scroll",Ze,{passive:!0}),()=>window.removeEventListener("scroll",Ze)}if(qe.type==="exit_intent"){const Ke=Ze=>{Ze.clientY<=0&&i(!0)};return document.addEventListener("mouseleave",Ke),()=>document.removeEventListener("mouseleave",Ke)}},[u,s.targeting,s.trigger,n]),j.useEffect(()=>{a&&!M.current&&(M.current=!0,I("impression"))},[a]),j.useEffect(()=>{if(l&&P.current&&!az(s.video_url)){P.current.currentTime=0,P.current.muted=!1,d(!1);const Ae=P.current.play();Ae&&Ae.catch(()=>{})}else l&&az(s.video_url)&&d(!1)},[l,s.video_url]),j.useEffect(()=>{if(!s.thumbnail_url)return;let Ae=!1;const Be=new Image;return Be.onload=()=>{Ae||p(Be.naturalWidth>Be.naturalHeight?"landscape":"portrait")},Be.src=s.thumbnail_url,()=>{Ae=!0}},[s.thumbnail_url]),j.useEffect(()=>{const Ae=()=>{A({width:window.innerWidth,height:window.innerHeight})};return Ae(),window.addEventListener("resize",Ae),()=>window.removeEventListener("resize",Ae)},[]);const D=()=>{o(!0),I("expand")},B=Ae=>{Ae.stopPropagation(),h(!0),o(!1)},q=Ae=>{I("cta_click",{cta_id:Ae.id,label:Ae.label,url:Ae.url})},W=async Ae=>{if(Ae.preventDefault(),n){g(!0);return}if(!(!v.email||!v.name)){b(!0);try{const{error:Be}=await U.functions.invoke("submit-widget-lead",{body:{user_id:s.user_id,app_slug:t,name:v.name,email:v.email,phone:v.phone||void 0,page_url:window.location.href}});if(Be)throw Be;I("lead_capture",{email:v.email}),g(!0)}catch(Be){console.error("lead submit failed",Be)}finally{b(!1)}}};if(!a||u||!s.video_url&&!s.video_embed_url)return null;const V=aqn[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",Q=s.shape==="circle"?"rounded-full":"rounded-2xl",J=n?m==="landscape"?"w-[280px]":"w-[220px]":m==="landscape"?"w-[360px] sm:w-[420px]":"w-[300px] sm:w-[340px]",ce=m==="landscape"?"aspect-video":"aspect-[9/16]",ue=s.agent||{},ne=s.lead_form_fields||["name","email","phone"],ee=!!(s.show_socials&&(ue.instagram_url||ue.facebook_url||ue.linkedin_url)),le=108+(s.ctas||[]).length*48+(s.lead_form_enabled&&!x?72+ne.length*42:0)+(x?40:0)+(ee?34:0),he=Math.max(300,C.height-32),ve=Math.max(220,C.width-32),ge=Math.max(150,he-le),fe=Math.floor(m==="landscape"?ge*(16/9):ge*(9/16)),je=m==="landscape"?Math.max(220,Math.min(420,ve,fe)):Math.max(180,Math.min(340,ve,fe)),Ee=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":`${J} 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`,Me=r?{width:`${je}px`,maxHeight:"calc(100dvh - 2rem)"}:void 0,De=r?"p-3 space-y-2.5":"p-4 space-y-3",ze=r?"w-9 h-9 rounded-full object-cover":"w-10 h-10 rounded-full object-cover",ke=r?"font-bold text-[15px] text-gray-900 leading-tight":"font-bold text-gray-900 leading-tight",Xe=r?"text-[11px] text-gray-500 mt-0.5":"text-xs text-gray-500 mt-0.5",Se=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",Re=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:Ee,style:Me,children:[e.jsxs("div",{className:`relative bg-black ${ce}`,children:[az(s.video_url)?e.jsx(FUe,{ref:P,sourceUrl:s.video_url,thumbnailUrl:s.thumbnail_url,autoPlay:!0,muted:c,loop:!1,className:"w-full h-full object-cover",onLoadedMetadata:Ae=>{const{videoWidth:Be,videoHeight:qe}=Ae.currentTarget;Be&&qe&&p(Be>qe?"landscape":"portrait")},onEnded:()=>I("watch_complete")},`expanded-${s.video_url}-${s.thumbnail_url||"no-thumb"}-${l?"on":"off"}`):e.jsx("video",{ref:P,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:Ae=>{const{videoWidth:Be,videoHeight:qe}=Ae.currentTarget;Be&&qe&&p(Be>qe?"landscape":"portrait")}}),e.jsx("button",{onClick:()=>{P.current&&(P.current.muted=!P.current.muted,d(P.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(rY,{className:"w-4 h-4"}):e.jsx(nY,{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(pr,{className:"w-4 h-4"})})]}),e.jsxs("div",{className:De,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:ze}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:ke,children:s.greeting_title||"Glad you're here!"}),s.greeting_subtitle&&e.jsx("p",{className:Xe,children:s.greeting_subtitle})]})]}),(s.ctas||[]).length>0&&e.jsx("div",{className:"space-y-2",children:(s.ctas||[]).map(Ae=>{var Be;return e.jsxs("a",{href:Ae.url,target:(Be=Ae.url)!=null&&Be.startsWith("http")?"_blank":void 0,rel:"noopener noreferrer",onClick:()=>q(Ae),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 ${Ae.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:Ae.label}),e.jsx(Tr,{className:"w-3.5 h-3.5 opacity-60"})]},Ae.id)})}),s.lead_form_enabled&&!x&&e.jsxs("form",{onSubmit:W,className:"space-y-2 pt-1",children:[ne.includes("name")&&e.jsx("input",{type:"text",placeholder:"Name",required:!0,value:v.name,onChange:Ae=>N({...v,name:Ae.target.value}),className:Se}),ne.includes("email")&&e.jsx("input",{type:"email",placeholder:"Email",required:!0,value:v.email,onChange:Ae=>N({...v,email:Ae.target.value}),className:Se}),ne.includes("phone")&&e.jsx("input",{type:"tel",placeholder:"Phone (optional)",value:v.phone,onChange:Ae=>N({...v,phone:Ae.target.value}),className:Se}),e.jsxs("button",{type:"submit",disabled:y,className:Re,children:[e.jsx(Br,{className:"w-3.5 h-3.5"}),y?"Sending...":"Send"]})]}),x&&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(Qh,{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(jf,{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(kg,{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:D,className:`relative ${Q} 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:[az(s.video_url)?e.jsx(FUe,{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:Ae=>{const{videoWidth:Be,videoHeight:qe}=Ae.currentTarget;Be&&qe&&p(Be>qe?"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:Ae=>{const{videoWidth:Be,videoHeight:qe}=Ae.currentTarget;Be&&qe&&p(Be>qe?"landscape":"portrait")}}),e.jsx("div",{className:"absolute inset-0 bg-gradient-to-t from-black/40 via-transparent to-transparent pointer-events-none"}),e.jsx("div",{className:"absolute bottom-2 left-1/2 -translate-x-1/2 w-12 h-12 rounded-full bg-white/95 flex items-center justify-center shadow-lg pointer-events-none",children:e.jsx("svg",{viewBox:"0 0 24 24",className:"w-6 h-6 text-black ml-0.5",fill:"currentColor",children:e.jsx("path",{d:"M8 5v14l11-7z"})})}),e.jsx("span",{className:"absolute top-2 right-2 px-2 py-0.5 text-[10px] font-bold uppercase tracking-wider bg-red-500 text-white rounded-full animate-pulse",children:"Live"})]}),e.jsx("button",{onClick:B,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(pr,{className:"w-3.5 h-3.5"})})]})})}function YXe({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 U.rpc("get_public_video_greeter_config",{_slug:s});!r&&!i&&a&&n(a)})(),()=>{r=!0}},[s]),t?e.jsx(KXe,{config:t}):null}const GGt="eip_last_shown",Ibt="eip_visitor_token";function oqn(){try{let s=localStorage.getItem(Ibt);return s||(s=crypto.randomUUID(),localStorage.setItem(Ibt,s)),s}catch{return}}function lqn(s){try{const t=Number(localStorage.getItem(GGt)||0);return t?Date.now()-t>s*24*60*60*1e3:!0}catch{return!0}}function cqn(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 WGt({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,P={})=>{if(!t)try{await U.from("widget_events").insert({user_id:s.user_id,app_slug:"exit_intent",event_type:T,visitor_token:oqn(),page_url:window.location.href,metadata:P})}catch{}};j.useEffect(()=>{if(t||!cqn(s.targeting)||!lqn(s.frequency_days))return;const T=/Mobi|Android/i.test(navigator.userAgent),P={low:5,medium:15,high:30}[s.trigger_sensitivity]||15,M=q=>{if(!h.current){h.current=!0,a(!0);try{localStorage.setItem(GGt,String(Date.now()))}catch{}p("impression",{reason:q})}},I=q=>{q.clientY<=P&&M("mouse_leave")},D=()=>{s.enable_mobile_back&&T&&M("back_button")};if(s.enable_mobile_back&&T){try{window.history.pushState({eip:!0},"")}catch{}window.addEventListener("popstate",D)}else document.addEventListener("mouseleave",I);let B;return s.enable_time_fallback&&(B=window.setTimeout(()=>M("time_fallback"),Math.max(5,s.time_fallback_seconds)*1e3)),()=>{document.removeEventListener("mouseleave",I),window.removeEventListener("popstate",D),B&&window.clearTimeout(B)}},[s,t]),j.useEffect(()=>{r&&!m.current&&!t&&!h.current&&(m.current=!0)},[r,t]);const x=()=>{a(!1),t||p("close")},g=async T=>{if(T.preventDefault(),t){l(!0);return}if(!(!d.email||!d.name)){c(!0);try{const{error:P}=await U.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(P)throw P;p("lead_capture",{email:d.email}),l(!0),s.cta_url&&setTimeout(()=>{window.location.href=s.cta_url},1200)}catch(P){console.error("exit intent submit failed",P)}finally{c(!1)}}};if(!r)return null;const y=s.form_fields||["name","email"],b=s.agent||{},v=[b.first_name,b.last_name].filter(Boolean).join(" "),N=s.use_agent_photo&&b.avatar_url||s.image_url,C=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, ${C}, ${aRe(C,-25)})`}}),e.jsx("button",{onClick:x,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(pr,{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:v||"Agent",className:"w-14 h-14 rounded-full object-cover ring-2 shadow-md",style:{boxShadow:`0 0 0 2px ${C}33`,"--tw-ring-color":C}}),e.jsxs("div",{className:"inline-flex items-center gap-1.5 px-2.5 py-1 rounded-full text-xs font-semibold",style:{background:`${C}1A`,color:C},children:[e.jsx(dn,{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:`${C}10`,color:C},children:[e.jsx("div",{className:"text-3xl",children:"🎉"}),e.jsx("p",{className:"text-sm font-medium",style:{color:C},children:s.success_message})]}):s.form_enabled?e.jsxs("form",{onSubmit:g,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":C},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":C},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":C}}),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, ${C}, ${aRe(C,-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, ${C}, ${aRe(C,-20)})`},children:s.cta_label}),v&&e.jsxs("p",{className:"text-[11px] text-center text-muted-foreground pt-1",children:["Sent personally by ",v]})]})]})})}function aRe(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 ZXe({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 U.rpc("get_public_exit_intent_config",{_slug:s});!r&&!i&&a&&n(a)})(),()=>{r=!0}},[s]),t?e.jsx(WGt,{config:t}):null}const Dbt="lm_dismissed",Rbt="lm_visitor_token";function dqn(){try{let s=localStorage.getItem(Rbt);return s||(s=crypto.randomUUID(),localStorage.setItem(Rbt,s)),s}catch{return}}function uqn(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 XXe({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,C={})=>{if(!t)try{await U.from("widget_events").insert({user_id:s.user_id,app_slug:"lead_magnet",event_type:N,visitor_token:dqn(),page_url:window.location.href,metadata:C})}catch{}};j.useEffect(()=>{if(t){r(!0);return}if(!uqn(s.targeting))return;try{if(sessionStorage.getItem(Dbt))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 C=window.setTimeout(N,Math.max(0,s.trigger_value)*1e3);return()=>window.clearTimeout(C)}else if(s.trigger_type==="scroll"){const C=()=>{(window.scrollY+window.innerHeight)/document.documentElement.scrollHeight*100>=(s.trigger_value||30)&&N()};return window.addEventListener("scroll",C,{passive:!0}),()=>window.removeEventListener("scroll",C)}},[s,t]);const x=()=>{r(!1);try{sessionStorage.setItem(Dbt,"1")}catch{}t||p("close")},g=async N=>{if(N.preventDefault(),t){o(!0);return}if(!(!u.email||!u.name)){d(!0);try{const{error:C}=await U.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(C)throw C;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(C){console.error("lead magnet submit failed",C)}finally{d(!1)}}};if(!n)return null;const y=s.theme_color||"#2563eb",b=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}, ${VG(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(Co,{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:x,className:"text-white/80 hover:text-white","aria-label":"Close",children:e.jsx(pr,{className:"w-4 h-4"})})]})}),a&&v()]});if(!a)return e.jsxs(e.Fragment,{children:[e.jsxs("button",{onClick:()=>{i(!0),p("expand")},className:`${b} 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}, ${VG(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(wf,{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(),x()},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(pr,{className:"w-3 h-3"})})]}),a&&v()]});return v();function v(){const N=s.form_fields||["name","email"],C=s.agent||{},A=[C.first_name,C.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}, ${VG(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(Wr,{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(Co,{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(pr,{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(di,{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:g,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}, ${VG(y,-20)})`},children:[e.jsx(di,{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}, ${VG(y,-20)})`},children:s.download_label}),A&&e.jsxs("p",{className:"text-[11px] text-center text-muted-foreground",children:["Curated by ",A]})]})]})})}}function VG(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 QXe({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 U.rpc("get_public_lead_magnet_config",{_slug:s});!r&&!i&&a&&n(a)})(),()=>{r=!0}},[s]),t?e.jsx(XXe,{config:t}):null}const KGt=` 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 YGt(s){return ht({queryKey:["lead-site-exchange-listings",s],enabled:!!s,staleTime:5*60*1e3,queryFn:async()=>{const{data:t,error:n}=await U.from("listings").select(KGt).eq("agent_id",s).eq("show_on_lead_site",!0).eq("is_approved",!0).order("created_at",{ascending:!1});if(n)throw n;return t||[]}})}function HQn(s,t){return ht({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=U.from("listings").select(KGt).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 GQn(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 WQn(s){return s?`$${s.toLocaleString()}`:"Price upon request"}function hqn({children:s,siteConfig:t}){var fe,je,Ee,Me,De,ze,ke,Xe,Se;const n=Wd(),r=Vn(),[a,i]=j.useState(!1),[l,o]=j.useState(!1),[c,d]=j.useState(!1),[u,h]=j.useState([]),[m,p]=j.useState([]),[x,g]=j.useState(null),y=j.useRef(null),b=j.useRef(null),{user:v,profile:N,signOut:C}=LTe();wXe(t,v==null?void 0:v.id),jXe(t,v==null?void 0:v.id);const A=((fe=t.agent)==null?void 0:fe.full_name)||"Agent",T=t.siteTitle||`${A} Real Estate`,P=n.pathname==="/search",M=n.pathname==="/",I=t.leadRegistrationMode!=="disabled";j.useEffect(()=>{(async()=>{const{data:Ae}=await U.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(Ae||[])})()},[t.id]),j.useEffect(()=>{(async()=>{const{data:Ae}=await U.from("lead_site_menu_items").select("*").eq("site_id",t.id).eq("is_visible",!0).order("sort_order",{ascending:!0});p(Ae||[])})()},[t.id]),j.useEffect(()=>{const Re=Ae=>{y.current&&!y.current.contains(Ae.target)&&d(!1),b.current&&!b.current.contains(Ae.target)&&g(null)};return document.addEventListener("mousedown",Re),()=>document.removeEventListener("mousedown",Re)},[]);const D=yXe(t),B=t==null?void 0:t.bookingUrl,{data:q}=YGt(D?t.agentId:null),W=((q==null?void 0:q.length)??0)>0,V=D?m.filter(Re=>{const Ae=String(Re.target_url||"").toLowerCase(),Be=String(Re.label||"").toLowerCase();return Ae!=="/search"&&!Ae.startsWith("/search?")&&!Be.includes("search")}):m,K=D&&W&&V.length>0&&!V.some(Re=>String(Re.target_url||"").toLowerCase().startsWith("/listings"))?[...V,{id:"__my-listings",label:"My Listings",target_url:"/listings",parent_id:null,is_visible:!0}]:V,Q=K.length>0,J=[{to:"/",label:"Home"},...D?[]:[{to:"/search",label:"Search"}],...D&&W?[{to:"/listings",label:"My Listings"}]:[],{to:"/sell",label:"Sell"},{to:"/blog",label:"Blog"},{to:"/community",label:"Community"},{to:"/about",label:"About"},{to:"/contact",label:"Contact"}],ce=Q?[]:J,ue=K.filter(Re=>!Re.parent_id),ne=Re=>K.filter(Ae=>Ae.parent_id===Re),ee=M?"bg-transparent text-white":"bg-white/95 backdrop-blur text-gray-900 border-b border-gray-100 shadow-sm",le=t.siteTitle||`${A} - Real Estate`,he=t.siteTagline||`Browse homes and listings with ${A}`,ve=t.ogImageUrl||((je=t.agent)==null?void 0:je.avatar_url)||"",ge=`https://${t.subdomainSlug||""}.thelocalmove.com`;return e.jsxs("div",{className:`flex flex-col ${P?"h-screen overflow-hidden":"min-h-screen"} bg-white`,children:[e.jsx(bXe,{siteConfig:t,pagePath:n.pathname}),e.jsx(_Xe,{siteConfig:t}),e.jsxs(Ul,{children:[e.jsx("title",{children:le}),e.jsx("meta",{name:"description",content:he}),e.jsx("meta",{property:"og:title",content:le}),e.jsx("meta",{property:"og:description",content:he}),e.jsx("meta",{property:"og:type",content:"website"}),e.jsx("meta",{property:"og:url",content:ge+n.pathname}),ve&&e.jsx("meta",{property:"og:image",content:ve}),e.jsx("meta",{name:"twitter:card",content:"summary_large_image"}),e.jsx("meta",{name:"twitter:title",content:le}),e.jsx("meta",{name:"twitter:description",content:he}),ve&&e.jsx("meta",{name:"twitter:image",content:ve}),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 ${ee}`,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(Wn,{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"}):(Ee=t.agent)!=null&&Ee.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(J3,{bookingUrl:t.bookingUrl,label:"Schedule",size:"sm",className:"order-last ml-3",source:"nav"}),ce.map(Re=>e.jsx(Wn,{to:Re.to,className:`px-4 py-2 rounded-lg text-sm font-medium tracking-wide transition-colors ${n.pathname===Re.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:Re.label},Re.to)),Q&&ue.map(Re=>{if(Re.item_type==="dropdown"){const Ae=ne(Re.id);return e.jsxs("div",{ref:b,className:"relative",children:[e.jsxs("button",{onClick:()=>g(x===Re.id?null:Re.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:[Re.label," ",e.jsx(_o,{className:`h-3.5 w-3.5 transition-transform ${x===Re.id?"rotate-180":""}`})]}),x===Re.id&&Ae.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:Ae.map(Be=>e.jsx(Oae,{item:Be,onClick:()=>g(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"},Be.id))})]},Re.id)}return e.jsx(Oae,{item:Re,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"}`},Re.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(_o,{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(Re=>e.jsx("button",{onClick:()=>{r(`/homes-for-sale-in-${Re.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:Re.city_name},Re.city_slug))})]}),v?e.jsxs("div",{className:"flex items-center gap-1 ml-2",children:[e.jsxs(Wn,{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(fo,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden lg:inline",children:"Saved"})]}),e.jsxs(Wn,{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(Lo,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden lg:inline",children:((Me=N==null?void 0:N.name)==null?void 0:Me.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(pr,{className:"h-5 w-5"}):e.jsx(jT,{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(J3,{bookingUrl:t.bookingUrl,label:"Schedule a Free Consultation",size:"sm",className:"w-full mb-3",source:"mobile_nav"}),ce.map(Re=>e.jsx(Wn,{to:Re.to,onClick:()=>i(!1),className:`block px-3 py-2.5 rounded-lg text-sm font-medium ${n.pathname===Re.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:Re.label},Re.to)),Q&&ue.map(Re=>{if(Re.item_type==="dropdown"){const Ae=ne(Re.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:Re.label}),Ae.map(Be=>e.jsx(Oae,{item:Be,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"}`},Be.id))]},Re.id)}return e.jsx(Oae,{item:Re,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"}`},Re.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(Re=>e.jsx(Wn,{to:`/homes-for-sale-in-${Re.city_slug}`,onClick:()=>i(!1),className:`block px-3 py-2.5 rounded-lg text-sm font-medium ${n.pathname===`/homes-for-sale-in-${Re.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:Re.city_name},Re.city_slug))]}),v?e.jsxs(e.Fragment,{children:[e.jsx(Wn,{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 C(),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}),!P&&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:[((De=t.agent)==null?void 0:De.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:((ze=t.agent)==null?void 0:ze.title)||"Real Estate Professional"})]})]}),((ke=t.agent)==null?void 0:ke.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(ya,{className:"h-3.5 w-3.5"})," ",t.agent.phone]})}),((Xe=t.agent)==null?void 0:Xe.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(nn,{className:"h-3.5 w-3.5"})," ",t.agent.email]})})]}),e.jsxs("div",{children:[e.jsx("h4",{className:"font-semibold text-white mb-4 text-sm tracking-wider uppercase",children:"Quick Links"}),e.jsxs("ul",{className:"space-y-3 text-sm",children:[ce.map(Re=>e.jsx("li",{children:e.jsx(Wn,{to:Re.to,className:"hover:text-white transition-colors",children:Re.label})},Re.to)),B&&e.jsx("li",{children:e.jsx("a",{href:B,target:"_blank",rel:"noopener noreferrer",className:"hover:text-white transition-colors",children:"Schedule a Call"})})]})]}),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:D?"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(Wn,{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."]})]})]})]})}),!P&&((Se=t.agent)==null?void 0:Se.avatar_url)&&e.jsx(mqn,{agent:t.agent,bookingUrl:B}),l&&e.jsx(vXe,{open:l,mode:"optional",siteConfig:t,onComplete:()=>o(!1),onSkip:()=>o(!1)}),e.jsx(YXe,{slug:t.subdomainSlug}),e.jsx(ZXe,{slug:t.subdomainSlug}),e.jsx(QXe,{slug:t.subdomainSlug})]})}function mqn({agent:s,bookingUrl:t}){var i;const[n,r]=j.useState(!1),a=Vn();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(ya,{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(nn,{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(pr,{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 Oae({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(Wn,{to:r,className:t,onClick:n,children:s.label})}const Obt={california:"California DRE License",ca:"California DRE License"};function zUe(s){const t=(s||"").trim();if(!t)return"Real Estate License";const n=t.toLowerCase();return Obt[n]?Obt[n]:`${t.replace(/\b\w/g,a=>a.toUpperCase())} Real Estate License`}function Fbt(s){if(s)return s.replace(/^\s*DRE\s*#?\s*/i,"").replace(/^\s*#/,"").trim()||void 0}function pqn({children:s,siteConfig:t}){var Me,De,ze,ke,Xe,Se,Re,Ae;const n=Wd(),r=Vn(),[a,i]=j.useState(!1),[l,o]=j.useState(!1),[c,d]=j.useState(!1),[u,h]=j.useState(!1),[m,p]=j.useState([]),[x,g]=j.useState(!1),y=j.useRef(null),b=j.useRef(null),{user:v,profile:N,signOut:C}=LTe();wXe(t,v==null?void 0:v.id),jXe(t,v==null?void 0:v.id);const A=((Me=t.agent)==null?void 0:Me.full_name)||"Agent",T=Fbt(t.agentLicenseNumber),P=Fbt(t.brokerageLicenseNumber),M=t.siteTitle||`${A} Real Estate`,I=Be=>{if(!Be)return Be;const qe=A.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),Ke=new RegExp(`^\\s*${qe}\\s*[|\\-–—:]\\s*`,"i");return Be.replace(Ke,"").trim()},D=M&&M!==`${A} Real Estate`?M:null,B=D?I(D):null,q=B&&B.toLowerCase()!==A.toLowerCase()?B:null,W=n.pathname==="/search",V=n.pathname==="/",K=t.leadRegistrationMode!=="disabled",Q="#c9a96e",J=t.bookingUrl;j.useEffect(()=>{const Be=()=>g(window.scrollY>80);return window.addEventListener("scroll",Be,{passive:!0}),()=>window.removeEventListener("scroll",Be)},[]),j.useEffect(()=>{(async()=>{const{data:qe}=await U.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(qe||[])})()},[t.id]),j.useEffect(()=>{const Be=qe=>{y.current&&!y.current.contains(qe.target)&&d(!1),b.current&&!b.current.contains(qe.target)&&h(!1)};return document.addEventListener("mousedown",Be),()=>document.removeEventListener("mousedown",Be)},[]);const ce=(((De=t.themeConfig)==null?void 0:De.focusPages)??[]).filter(Be=>Be==null?void 0:Be.slug).map(Be=>({to:`/${Be.slug}`,label:Be.navLabel||Be.title})),ue=Z7t(t)||yXe(t),{data:ne}=YGt(ue?t.agentId:null),ee=((ne==null?void 0:ne.length)??0)>0,le=[{to:"/",label:"Home"},...ue?ee?[{to:"/listings",label:"My Listings"}]:[]:[{to:"/search",label:"Search"}],{to:"/sell",label:"Sell"},{to:"/blog",label:"Blog"},{to:"/community",label:"Community"},{to:"/about",label:"About"},{to:"/contact",label:"Contact"}],he=[...le,...ce],ve=t.siteTitle||`${A} - Real Estate`,ge=t.siteTagline||`Browse homes and listings with ${A}`,fe=t.ogImageUrl||((ze=t.agent)==null?void 0:ze.avatar_url)||"",je=`https://${t.subdomainSlug||""}.thelocalmove.com`,Ee=V?x?"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 ${W?"h-screen overflow-hidden":"min-h-screen"} bg-[#0d0b0a]`,children:[e.jsx(bXe,{siteConfig:t,pagePath:n.pathname}),e.jsx(_Xe,{siteConfig:t}),e.jsxs(Ul,{children:[e.jsx("title",{children:ve}),e.jsx("meta",{name:"description",content:ge}),e.jsx("meta",{property:"og:title",content:ve}),e.jsx("meta",{property:"og:description",content:ge}),e.jsx("meta",{property:"og:type",content:"website"}),e.jsx("meta",{property:"og:url",content:je+n.pathname}),fe&&e.jsx("meta",{property:"og:image",content:fe}),e.jsx("meta",{name:"twitter:card",content:"summary_large_image"}),e.jsx("meta",{name:"twitter:title",content:ve}),e.jsx("meta",{name:"twitter:description",content:ge}),fe&&e.jsx("meta",{name:"twitter:image",content:fe}),t.faviconUrl&&e.jsx("link",{rel:"icon",href:t.faviconUrl,type:"image/png"}),e.jsx("link",{rel:"canonical",href:`${je}${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 ${Ee}`,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(Wn,{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}),q&&e.jsx("span",{className:"hidden xl:block whitespace-nowrap text-[10px] tracking-[0.18em] uppercase text-white/40",children:q})]})]}),e.jsxs("nav",{className:"hidden lg:flex items-center justify-end gap-0 flex-1 min-w-0",children:[le.map(Be=>e.jsx(Wn,{to:Be.to,className:`whitespace-nowrap px-2.5 xl:px-4 py-2 text-xs tracking-[0.15em] uppercase transition-colors duration-300 ${n.pathname===Be.to?"text-white":"text-white/40 hover:text-white"}`,children:Be.label},Be.to)),ce.length>0&&e.jsxs("div",{ref:b,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 ${ce.some(Be=>n.pathname===Be.to)?"text-white":"text-white/40 hover:text-white"}`,children:["Specialty"," ",e.jsx(_o,{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:ce.map(Be=>e.jsx(Wn,{to:Be.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===Be.to?"text-white":""}`,children:Be.label},Be.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(_o,{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(Be=>e.jsx("button",{onClick:()=>{r(`/homes-for-sale-in-${Be.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:Be.city_name},Be.city_slug))})]}),v?e.jsxs("div",{className:"flex items-center gap-1 ml-3",children:[e.jsxs(Wn,{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(fo,{className:"h-3.5 w-3.5"}),e.jsx("span",{className:"hidden xl:inline",children:"Saved"})]}),e.jsxs(Wn,{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(Lo,{className:"h-3.5 w-3.5"}),e.jsx("span",{className:"hidden xl:inline",children:((ke=N==null?void 0:N.name)==null?void 0:ke.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,J&&e.jsx(J3,{bookingUrl:J,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(pr,{className:"h-5 w-5"}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"w-6 h-px bg-current"}),e.jsx("div",{className:"w-4 h-px bg-current mt-1.5"}),e.jsx("div",{className:"w-6 h-px bg-current mt-1.5"})]})}),e.jsx("span",{className:"text-[8px] tracking-[0.3em] uppercase mt-1 block",children:"MENU"})]})]})}),a&&e.jsx("div",{className:"lg:hidden border-t border-white/5 bg-[#0d0b0a]/98 backdrop-blur-lg",children:e.jsxs("div",{className:"px-6 py-4 space-y-1",children:[J&&e.jsx(J3,{bookingUrl:J,label:"Schedule a Free Consultation",size:"sm",className:"w-full mb-3",source:"mobile_nav"}),le.map(Be=>e.jsx(Wn,{to:Be.to,onClick:()=>i(!1),className:`block px-3 py-3 text-xs tracking-[0.2em] uppercase transition-colors ${n.pathname===Be.to?"text-white":"text-white/40 hover:text-white"}`,children:Be.label},Be.to)),ce.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:Q},children:"Specialty"}),ce.map(Be=>e.jsx(Wn,{to:Be.to,onClick:()=>i(!1),className:`block px-3 py-2.5 text-xs tracking-wider uppercase transition-colors ${n.pathname===Be.to?"text-white":"text-white/40 hover:text-white"}`,children:Be.label},Be.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:Q},children:"Cities"}),m.map(Be=>e.jsx(Wn,{to:`/homes-for-sale-in-${Be.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:Be.city_name},Be.city_slug))]}),v?e.jsxs(e.Fragment,{children:[e.jsx(Wn,{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 C(),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}),!W&&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:((Xe=t.agent)==null?void 0:Xe.title)||"Real Estate Professional"}),(T||P)&&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:[zUe(t.licenseState)," #",T]}),P&&e.jsxs("p",{className:"text-xs text-white/70 tracking-wider uppercase mt-1",children:["Brokerage License #",P]})]}),((Se=t.agent)==null?void 0:Se.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(ya,{className:"h-3.5 w-3.5"})," ",t.agent.phone]}),((Re=t.agent)==null?void 0:Re.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(nn,{className:"h-3.5 w-3.5"})," ",t.agent.email]})]}),e.jsxs("div",{children:[e.jsx("h4",{className:"text-xs tracking-[0.3em] uppercase mb-6 text-white",style:{color:Q},children:"Quick Links"}),e.jsxs("ul",{className:"space-y-3",children:[he.map(Be=>e.jsx("li",{children:e.jsx(Wn,{to:Be.to,className:"text-xs tracking-wider uppercase text-white/70 hover:text-white transition-colors",children:Be.label})},Be.to)),J&&e.jsx("li",{children:e.jsx("a",{href:J,target:"_blank",rel:"noopener noreferrer",className:"text-xs tracking-wider uppercase transition-colors hover:opacity-80",style:{color:TV},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:Q},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:[J&&e.jsx(J3,{bookingUrl:J,label:"Schedule a Free Consultation",size:"sm",source:"footer"}),e.jsx(Wn,{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:[zUe(t.licenseState)," #",T]}),P&&e.jsxs("span",{children:["Brokerage #",P]})]}),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."]})]})]})]})}),!W&&((Ae=t.agent)==null?void 0:Ae.avatar_url)&&e.jsx(fqn,{agent:t.agent,agentLicense:T,siteConfig:t,accentColor:Q}),l&&e.jsx(vXe,{open:l,mode:"optional",siteConfig:t,onComplete:()=>o(!1),onSkip:()=>o(!1),theme:"luxury",accentColor:Q}),e.jsx(YXe,{slug:t.subdomainSlug}),e.jsx(ZXe,{slug:t.subdomainSlug}),e.jsx(QXe,{slug:t.subdomainSlug})]})}function fqn({agent:s,agentLicense:t,siteConfig:n,accentColor:r}){var o;const[a,i]=j.useState(!1),l=Vn();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:zUe(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(ya,{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(nn,{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(pr,{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 HG="#2c1810",Gk="#b8860b";function xqn({children:s,siteConfig:t}){var M,I,D;const n=Wd();Vn();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:x,profile:g,signOut:y}=LTe();wXe(t,x==null?void 0:x.id),jXe(t,x==null?void 0:x.id);const b=((M=t.agent)==null?void 0:M.full_name)||"Agent",v=t.siteTitle||`${b} Land & Ranch`,N=n.pathname==="/",C=t.leadRegistrationMode!=="disabled";j.useEffect(()=>{const B=()=>m(window.scrollY>80);return window.addEventListener("scroll",B,{passive:!0}),()=>window.removeEventListener("scroll",B)},[]),j.useEffect(()=>{(async()=>{const{data:q}=await U.from("lead_site_city_pages").select("city_name, city_slug").eq("site_id",t.id).eq("is_published",!0).order("sort_order");q&&u(q)})()},[t.id]),j.useEffect(()=>{const B=q=>{p.current&&!p.current.contains(q.target)&&c(!1)};return document.addEventListener("mousedown",B),()=>document.removeEventListener("mousedown",B)},[]);const A=[{label:"Home",path:"/"},{label:"Search Properties",path:"/search"},{label:"About",path:"/about"},{label:"Blog",path:"/blog"},{label:"Contact",path:"/contact"}],T=h||!N?"bg-white/95 backdrop-blur-md shadow-sm":"bg-transparent",P=h||!N?HG:"#ffffff";return e.jsxs("div",{className:"min-h-screen",style:{fontFamily:"'Lora', Georgia, serif"},children:[e.jsxs(Ul,{children:[e.jsx("title",{children:v}),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(bXe,{siteConfig:t}),e.jsx(_Xe,{siteConfig:t}),e.jsxs("header",{className:`fixed top-0 left-0 right-0 z-50 transition-all duration-300 ${T}`,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(Wn,{to:"/",className:"flex items-center gap-2.5",children:[e.jsx(uR,{className:"w-7 h-7",style:{color:Gk}}),e.jsx("span",{className:"text-lg font-bold tracking-wide",style:{color:P,fontFamily:"'Playfair Display', Georgia, serif"},children:v})]}),e.jsxs("nav",{className:"hidden md:flex items-center gap-1",children:[A.map(B=>e.jsx(Wn,{to:B.path,className:"px-4 py-2 text-sm font-medium tracking-wide uppercase transition-colors hover:opacity-80",style:{color:n.pathname===B.path?Gk:P},children:B.label},B.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:P},children:["Areas ",e.jsx(_o,{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(B=>e.jsx(Wn,{to:`/homes-for-sale-in-${B.city_slug}`,className:"block px-4 py-2.5 text-sm hover:bg-gray-50 transition-colors",style:{color:HG},onClick:()=>c(!1),children:B.city_name},B.city_slug))})]}),x?e.jsx("div",{className:"flex items-center gap-2 ml-3",children:e.jsxs(Wn,{to:"/account",className:"px-4 py-2 text-sm font-medium rounded-full border-2 transition-all hover:scale-105",style:{borderColor:Gk,color:P},children:[e.jsx(Lo,{className:"w-4 h-4 inline mr-1.5"}),(g==null?void 0:g.name)||"Account"]})}):C?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:Gk},children:"Sign In"}):null]}),e.jsx("button",{onClick:()=>a(!r),className:"md:hidden p-2",style:{color:P},children:r?e.jsx(pr,{className:"w-6 h-6"}):e.jsx(jT,{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:[A.map(B=>e.jsx(Wn,{to:B.path,className:"block px-4 py-3 text-base font-medium rounded-lg hover:bg-gray-50 transition-colors",style:{color:n.pathname===B.path?Gk:HG},onClick:()=>a(!1),children:B.label},B.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(B=>e.jsx(Wn,{to:`/homes-for-sale-in-${B.city_slug}`,className:"block px-4 py-2.5 text-sm rounded-lg hover:bg-gray-50",style:{color:HG},onClick:()=>a(!1),children:B.city_name},B.city_slug))]}),!x&&C&&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:Gk},children:"Sign In"})]})})]}),e.jsx("main",{children:s}),e.jsx("footer",{className:"py-16 px-4",style:{backgroundColor:HG},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(uR,{className:"w-6 h-6",style:{color:Gk}}),e.jsx("span",{className:"text-lg font-bold text-white",style:{fontFamily:"'Playfair Display', Georgia, serif"},children:v})]}),e.jsx("p",{className:"text-white/60 text-sm leading-relaxed",children:"Your trusted specialist in land, ranch, and rural properties. Expert guidance for every acre."})]}),e.jsxs("div",{children:[e.jsx("h4",{className:"text-white font-semibold mb-4 text-sm tracking-wider uppercase",children:"Quick Links"}),e.jsx("div",{className:"space-y-2",children:A.map(B=>e.jsx(Wn,{to:B.path,className:"block text-white/60 hover:text-white text-sm transition-colors",children:B.label},B.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:[((I=t.agent)==null?void 0:I.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(ya,{className:"w-4 h-4",style:{color:Gk}}),t.agent.phone]}),((D=t.agent)==null?void 0:D.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(nn,{className:"w-4 h-4",style:{color:Gk}}),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()," ",v,". All rights reserved."]}),e.jsx("div",{className:"h-px w-16",style:{backgroundColor:Gk}})]})]})}),i&&e.jsx(vXe,{open:i,mode:t.leadRegistrationMode==="required"?"required":"optional",siteConfig:t,onSkip:()=>l(!1),onComplete:()=>l(!1)}),e.jsx(YXe,{slug:t.subdomainSlug}),e.jsx(ZXe,{slug:t.subdomainSlug}),e.jsx(QXe,{slug:t.subdomainSlug})]})}function gqn(){const{pathname:s}=Wd();return j.useEffect(()=>{window.scrollTo({top:0,left:0,behavior:"auto"})},[s]),null}const yqn=j.lazy(()=>mi(()=>import("./LeadSiteHome-BwGfSotH.js"),__vite__mapDeps([0,1,2,3,4]))),vqn=j.lazy(()=>mi(()=>import("./LeadSiteLuxuryHome-CEGYQyhj.js"),__vite__mapDeps([5,2,3,4,6]))),bqn=j.lazy(()=>mi(()=>import("./LeadSiteLandRanchHome-ysxr3lKH.js"),__vite__mapDeps([7,1,2,3,4]))),_qn=j.lazy(()=>mi(()=>import("./LeadSiteSearch-aidAFov1.js"),__vite__mapDeps([8,1,9,4,10]))),wqn=j.lazy(()=>mi(()=>import("./LeadSiteLuxurySearch-CJi7aaRC.js"),__vite__mapDeps([11,1,9,4,10]))),jqn=j.lazy(()=>mi(()=>import("./LeadSiteListingDetail-CMt0VEf7.js"),__vite__mapDeps([12,13,4,14]))),Nqn=j.lazy(()=>mi(()=>import("./LeadSiteLuxuryListingDetail-Dn2H4bhF.js"),__vite__mapDeps([15,13,4,14]))),kqn=j.lazy(()=>mi(()=>import("./LeadSiteAbout-CILCGyFG.js"),[])),Sqn=j.lazy(()=>mi(()=>import("./LeadSiteLuxuryAbout-5OmwDHJR.js"),[])),Cqn=j.lazy(()=>mi(()=>import("./LeadSiteContact-BjIy--Ng.js"),[])),Aqn=j.lazy(()=>mi(()=>import("./LeadSiteLuxuryContact-Dv4v4FRC.js"),[])),Eqn=j.lazy(()=>mi(()=>import("./LeadSiteConsumerDashboard-B_h8Affd.js"),[])),zbt=j.lazy(()=>mi(()=>import("./LeadSiteBlog-g-3PDcNk.js"),[])),Tqn=j.lazy(()=>mi(()=>import("./LeadSiteCommunity-CmKBX_iE.js"),[])),Mqn=j.lazy(()=>mi(()=>import("./LeadSiteSellers-BfwtqbPc.js"),[])),Lqn=j.lazy(()=>mi(()=>import("./LeadSiteCityPage-BIZNcc98.js"),__vite__mapDeps([16,4,10]))),Pqn=j.lazy(()=>mi(()=>import("./LeadSiteSubdivisionPage-D1Y2mVlQ.js"),__vite__mapDeps([17,4]))),Iqn=j.lazy(()=>mi(()=>import("./LeadSiteCustomPage-B_v9G0fh.js"),[])),Dqn=j.lazy(()=>mi(()=>import("./LeadSiteFocusPage-3SUxeuV-.js"),__vite__mapDeps([18,3,4]))),Rqn=j.lazy(()=>mi(()=>import("./LeadSiteExchangeListings-2ExF9SnZ.js"),[]).then(s=>({default:s.LeadSiteExchangeListingsIndex}))),Oqn=j.lazy(()=>mi(()=>import("./LeadSiteExchangeListings-2ExF9SnZ.js"),[]).then(s=>({default:s.LeadSiteExchangeListingDetail})));function Fqn(){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 zqn(){var u;const{siteConfig:s,themeConfig:t,isLoading:n,error:r}=I7n();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?xqn:a?pqn:hqn,o=Z7t(s),c=!o&&yXe(s,t),d=i?e.jsx(bqn,{siteConfig:s,themeConfig:t??void 0}):a?e.jsx(vqn,{siteConfig:s,themeConfig:t??void 0}):e.jsx(yqn,{siteConfig:s,themeConfig:t??void 0});return e.jsxs(R7n,{siteConfig:s,children:[e.jsx(gqn,{}),e.jsxs(l,{siteConfig:s,children:[e.jsx(j.Suspense,{fallback:e.jsx(Fqn,{}),children:e.jsxs(RZ,{children:[e.jsx(ds,{path:"/",element:d}),e.jsx(ds,{path:"/listings",element:e.jsx(Rqn,{siteConfig:s})}),e.jsx(ds,{path:"/listings/:slug",element:e.jsx(Oqn,{siteConfig:s})}),e.jsx(ds,{path:"/search",element:o?e.jsx(r1,{to:"/listings",replace:!0}):c?e.jsx(r1,{to:"/contact",replace:!0}):a?e.jsx(wqn,{siteConfig:s}):e.jsx(_qn,{siteConfig:s})}),e.jsx(ds,{path:"/listing/:mlsNumber",element:o?e.jsx(r1,{to:"/listings",replace:!0}):c?e.jsx(r1,{to:"/contact",replace:!0}):a?e.jsx(Nqn,{siteConfig:s}):e.jsx(jqn,{siteConfig:s})}),e.jsx(ds,{path:"/about",element:a?e.jsx(Sqn,{siteConfig:s}):e.jsx(kqn,{siteConfig:s})}),e.jsx(ds,{path:"/contact",element:a?e.jsx(Aqn,{siteConfig:s}):e.jsx(Cqn,{siteConfig:s})}),e.jsx(ds,{path:"/account",element:e.jsx(Eqn,{siteConfig:s})}),e.jsx(ds,{path:"/blog",element:e.jsx(zbt,{siteConfig:s,isLuxury:a})}),e.jsx(ds,{path:"/blog/:slug",element:e.jsx(zbt,{siteConfig:s,isLuxury:a})}),e.jsx(ds,{path:"/sell",element:e.jsx(Mqn,{siteConfig:s,themeConfig:t??void 0,isLuxury:a})}),e.jsx(ds,{path:"/community",element:e.jsx(Tqn,{siteConfig:s,isLuxury:a})}),e.jsx(ds,{path:"/schedule",element:e.jsx(U7n,{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(ds,{path:`/${h.slug}`,element:e.jsx(Dqn,{siteConfig:s,page:h,accentColor:(t==null?void 0:t.accentColor)||s.accentColor||"#c9a96e"})},h.slug)),e.jsx(ds,{path:"/p/:pageSlug",element:e.jsx(Iqn,{siteConfig:s})}),e.jsx(ds,{path:"/*",element:e.jsx(Bqn,{siteConfig:s,referralMode:c})})]})}),e.jsx($7n,{bookingUrl:s.bookingUrl})]})]})}function Bqn({siteConfig:s,referralMode:t}){const n=Wd(),r=n.pathname.match(/^\/homes-in-(.+)$/);if(r)return e.jsx(Pqn,{siteConfig:s,subdivisionSlug:r[1]});const a=n.pathname.match(/^\/homes-for-sale-in-(.+)$/);return a?e.jsx(Lqn,{siteConfig:s,citySlugOverride:a[1],referralMode:t}):null}function $qn(){const{user:s,loading:t}=_s(),{data:n,isLoading:r}=ht({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 U.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 Uqn({children:s}){const{user:t,loading:n}=_s(),{hasAccess:r,isLoading:a}=$qn(),i=Wd();return j.useEffect(()=>{!n&&!a&&t&&!r&&ae.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(r1,{to:"/dashboard",replace:!0}):(sessionStorage.setItem("redirectAfterLogin",i.pathname),e.jsx(r1,{to:"/auth",replace:!0}))}function Bbt({children:s}){const{user:t,loading:n}=_s(),{hasAccess:r,isLoading:a}=uCe(),i=Wd();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(r1,{to:"/dashboard",replace:!0}):(sessionStorage.setItem("redirectAfterLogin",i.pathname),e.jsx(r1,{to:"/auth",replace:!0}))}const BUe={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"},qqn=["First-time buyers","Move-up buyers","Luxury","New construction","Investors","Relocation","Downsizing / seniors","Military / VA","Land & ranch","Waterfront","Condos","Multi-family"],Vqn=["Buyers","Sellers","Both equally","Investors","Renters","Builders / developers"],Hqn=["Warm & approachable","Bold & direct","Educational & analytical","Playful & funny","Polished & luxury","Down-to-earth & local","High-energy & motivational"],Gqn=[{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"}],Wqn=["Under $250k","$250k – $500k","$500k – $750k","$750k – $1M","$1M – $2M","$2M+"],Kqn=["Brand new (under 1 year)","1–3 years","3–5 years","5–10 years","10–20 years","20+ years"],Yqn=[{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"}],Zqn=[{value:"instagram",label:"Instagram"},{value:"tiktok",label:"TikTok"},{value:"facebook",label:"Facebook"},{value:"youtube",label:"YouTube Shorts"},{value:"linkedin",label:"LinkedIn"}],Xqn=[{value:"15-30s",label:"15–30 seconds"},{value:"30-45s",label:"30–45 seconds"},{value:"45-60s",label:"45–60 seconds"}],Qqn=[{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"}],Jqn=[{value:"local",label:"Mostly local market content"},{value:"evergreen",label:"Mostly evergreen content"},{value:"mix",label:"A healthy mix of both"}];function ZGt({value:s,label:t}){const[n,r]=j.useState(!1);return s?e.jsxs($,{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),ae.success(`${t} copied`),setTimeout(()=>r(!1),1600)},children:[n?e.jsx(oa,{className:"h-3.5 w-3.5 mr-1"}):e.jsx(Ca,{className:"h-3.5 w-3.5 mr-1"}),"Copy"]}):null}function GM({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(ZGt,{value:n,label:s}):null]}),e.jsx("div",{className:"text-[14.5px] leading-relaxed text-foreground whitespace-pre-wrap",children:t})]})}function UNe({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(_e,{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($e,{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($e,{variant:"outline",className:"text-[10.5px] font-medium text-muted-foreground",children:BUe[s.category]??s.category}):null,o?e.jsx($e,{className:"bg-emerald-100 text-emerald-800 border-0 text-[10.5px]",children:"Posted"}):l?e.jsx($e,{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($,{type:"button",size:"icon",variant:"ghost","aria-label":s.favorited?"Remove from saved":"Save this reel",className:Tt("h-9 w-9 shrink-0",s.favorited&&"text-amber-500"),onClick:()=>n({favorited:!s.favorited}),children:e.jsx(Qa,{className:Tt("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(ZGt,{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(GM,{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($,{type:"button",size:"sm",variant:l?"default":"outline",className:"rounded-full",onClick:()=>n({recorded_at:l?null:new Date().toISOString()}),children:[e.jsx(Xr,{className:"h-3.5 w-3.5 mr-1.5"}),l?"Recorded":"Mark as recorded"]}),e.jsxs($,{type:"button",size:"sm",variant:o?"default":"outline",className:"rounded-full",onClick:()=>n({posted_at:o?null:new Date().toISOString()}),children:[e.jsx(Br,{className:"h-3.5 w-3.5 mr-1.5"}),o?"Posted":"Mark as posted"]})]}):null,e.jsxs(uv,{open:a,onOpenChange:i,children:[e.jsx(hv,{asChild:!0,children:e.jsxs($,{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(_o,{className:Tt("h-4 w-4 transition-transform",a&&"rotate-180")})]})}),e.jsxs(mv,{className:"space-y-5 pt-2",children:[e.jsx(Hl,{}),s.filming_directions?e.jsx(GM,{label:"How to film it",children:e.jsxs("span",{className:"flex gap-2",children:[e.jsx(gz,{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(GM,{label:"Caption",copyValue:s.caption,children:s.caption}):null,(c=s.hashtags)!=null&&c.length?e.jsx(GM,{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(GM,{label:"Pinned comment",copyValue:s.pinned_comment,children:s.pinned_comment}):null,s.reply_strategy?e.jsx(GM,{label:"Reply strategy",children:e.jsxs("span",{className:"flex gap-2",children:[e.jsx(Ji,{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(dn,{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(GM,{label:"Bonus content idea",children:e.jsxs("span",{className:"flex gap-2",children:[e.jsx(i5,{className:"h-4 w-4 mt-0.5 shrink-0 text-muted-foreground"}),e.jsx("span",{children:s.bonus_idea})]})}):null]})]})]})})}function XGt(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 $bt(){const s=XGt(),[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 cZ(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 JXe(s){const{user:t}=_s(),n=s??(t==null?void 0:t.id),r=ts(),a=ht({queryKey:["weekly-reels-profile",n],enabled:!!n,queryFn:async()=>{const{data:h,error:m}=await U.from("weekly_reel_profiles").select("*").eq("user_id",n).maybeSingle();if(m)throw m;return h??null}}),i=ht({queryKey:["weekly-reels-packs",n],enabled:!!n,queryFn:async()=>{const{data:h,error:m}=await U.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(g=>g.id);let x=[];if(p.length){const{data:g,error:y}=await U.from("weekly_reels").select("*").in("pack_id",p).order("position",{ascending:!0});if(y)throw y;x=g??[]}return(h??[]).map(g=>({...g,reels:x.filter(y=>y.pack_id===g.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 U.from("weekly_reel_profiles").upsert(m,{onConflict:"user_id"});if(p)throw p},onSuccess:()=>{r.invalidateQueries({queryKey:["weekly-reels-profile",n]})},onError:h=>ae.error(h.message)}),o=yt({mutationFn:async({id:h,values:m})=>{const{error:p}=await U.from("weekly_reels").update(m).eq("id",h);if(p)throw p},onSuccess:()=>r.invalidateQueries({queryKey:["weekly-reels-packs",n]}),onError:h=>ae.error(h.message)}),c=XGt(),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 Fae({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 eVn(){var D,B,q,W,V;const s=Vn(),{user:t}=_s(),{profile:n,packs:r,currentPack:a,history:i,saveProfile:l,updateReel:o}=JXe(),[c,d]=j.useState(!1),[u,h]=j.useState(!1),[m,p]=j.useState(""),[x,g]=j.useState("all"),[y,b]=j.useState("all"),v=(((D=n.data)==null?void 0:D.full_name)||((B=t==null?void 0:t.user_metadata)==null?void 0:B.full_name)||"there").split(" ")[0],N=!!((q=n.data)!=null&&q.onboarding_completed),C=j.useMemo(()=>(r.data??[]).flatMap(K=>K.reels.map(Q=>({reel:Q,pack:K}))),[r.data]),A=j.useMemo(()=>{const K=m.trim().toLowerCase();return C.filter(({pack:Q})=>y==="all"?!0:Q.week_start_date===y).filter(({reel:Q})=>x==="all"?!0:Q.category===x).filter(({reel:Q})=>K?`${Q.topic} ${Q.hook} ${Q.script}`.toLowerCase().includes(K):!0)},[C,m,x,y]),T=C.filter(({reel:K})=>K.favorited),P=async()=>{d(!0);try{const{data:K,error:Q}=await U.functions.invoke("weekly-reels-generate",{body:{action:"generate_pack",force:!0}});if(Q)throw Q;if(K!=null&&K.error)throw new Error(K.error);await r.refetch(),ae.success(K!=null&&K.skipped?String(K.skipped):"Your pack is ready")}catch(K){ae.error(K instanceof Error?K.message:"Generation failed")}finally{d(!1)}},M=async()=>{if(a){h(!0);try{const{data:K,error:Q}=await U.functions.invoke("weekly-reels-generate",{body:{action:"send_pack_email",packId:a.id}});if(Q)throw Q;if(K!=null&&K.error)throw new Error(K.error);await r.refetch(),ae.success(`Sent to ${(K==null?void 0:K.recipient)??"your inbox"}`)}catch(K){ae.error(K instanceof Error?K.message:"Could not send the email")}finally{h(!1)}}},I=K=>Q=>o.mutate({id:K.id,values:Q});return!n.isLoading&&!N?e.jsx(Ks,{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(_e,{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(lh,{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($,{size:"lg",className:"neon-cta mt-7",onClick:()=>s("/weekly-reels/onboarding"),children:[e.jsx(dn,{className:"h-4 w-4 mr-2"})," Start setup — about 5 minutes"]})]})})})}):e.jsx(Ks,{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, ",v]}),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($,{variant:"outline",onClick:()=>s("/weekly-reels/onboarding"),children:[e.jsx(G3,{className:"h-4 w-4 mr-2"})," Edit my profile"]})]}),e.jsxs(_e,{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(Fae,{icon:Fr,label:"Onboarding",value:N?"Complete":"Incomplete"}),e.jsx(Fae,{icon:gz,label:"Weekly delivery",value:(W=n.data)!=null&&W.delivery_active?"Active":"Paused"}),e.jsx(Fae,{icon:Xu,label:"Next pack",value:$bt()}),e.jsx(Fae,{icon:nn,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(Tn,{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($,{variant:"outline",size:"sm",onClick:M,disabled:u,children:[u?e.jsx(Ht,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(nn,{className:"h-4 w-4 mr-2"}),"Email me this week's pack"]}):null,e.jsxs($,{size:"sm",className:"neon-cta",onClick:P,disabled:c,children:[c?e.jsx(Ht,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(dn,{className:"h-4 w-4 mr-2"}),a&&a.reels.length?"Regenerate this week":"Generate this week's pack"]})]})]})]}),e.jsxs(ua,{defaultValue:"current",className:"mt-8",children:[e.jsxs(ha,{children:[e.jsx(Qt,{value:"current",children:"This week"}),e.jsx(Qt,{value:"history",children:"History"}),e.jsxs(Qt,{value:"saved",children:["Saved",T.length?` (${T.length})`:""]})]}),e.jsx(Jt,{value:"current",className:"mt-6",children:r.isLoading?e.jsx("div",{className:"flex justify-center py-16",children:e.jsx(Ht,{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($e,{variant:"outline",className:"text-[11.5px]",children:["Week of ",cZ(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,Q)=>e.jsx(UNe,{reel:K,index:Q,onUpdate:I(K)},K.id))})]}):e.jsxs(_e,{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(lh,{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: ",$bt(),". Don't want to wait? Write them now."]}),e.jsxs($,{className:"neon-cta mt-6",onClick:P,disabled:c,children:[c?e.jsx(Ht,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(dn,{className:"h-4 w-4 mr-2"}),"Generate it now"]})]})}),e.jsxs(Jt,{value:"history",className:"mt-6",children:[e.jsx(_e,{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(Vr,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),e.jsx(be,{value:m,onChange:K=>p(K.target.value),placeholder:"Search topics and scripts...",className:"pl-9"})]}),e.jsxs(vs,{value:x,onValueChange:g,children:[e.jsx(gs,{className:"sm:w-[190px]",children:e.jsx(bs,{placeholder:"All topics"})}),e.jsxs(ys,{children:[e.jsx(Ye,{value:"all",children:"All topics"}),Object.entries(BUe).map(([K,Q])=>e.jsx(Ye,{value:K,children:Q},K))]})]}),e.jsxs(vs,{value:y,onValueChange:b,children:[e.jsx(gs,{className:"sm:w-[180px]",children:e.jsx(bs,{placeholder:"All weeks"})}),e.jsxs(ys,{children:[e.jsx(Ye,{value:"all",children:"All weeks"}),(r.data??[]).map(K=>e.jsx(Ye,{value:K.week_start_date,children:cZ(K.week_start_date)},K.id))]})]})]})}),A.length?e.jsx(JO,{type:"multiple",className:"mt-4 space-y-3",children:A.map(({reel:K,pack:Q})=>e.jsxs(D6,{value:K.id,className:"rounded-2xl border border-border/70 bg-card px-4 sm:px-5",children:[e.jsx(R6,{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($e,{variant:"outline",className:"text-[10.5px] shrink-0",children:cZ(Q.week_start_date)}),K.category?e.jsx($e,{className:"bg-muted text-muted-foreground border-0 text-[10.5px] shrink-0",children:BUe[K.category]??K.category}):null,e.jsx("span",{className:"truncate text-[14.5px] font-medium text-foreground",children:K.topic})]})}),e.jsx(O6,{className:"pb-4",children:e.jsx(UNe,{reel:K,index:K.position-1,onUpdate:I(K)})})]},K.id))}):e.jsxs(_e,{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(Vr,{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:C.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(Jt,{value:"saved",className:"mt-6",children:T.length?e.jsx("div",{className:"space-y-4",children:T.map(({reel:K},Q)=>e.jsx(UNe,{reel:K,index:Q,onUpdate:I(K)},K.id))}):e.jsxs(_e,{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(Qa,{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 WM=[{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 tVn(){const s=Vn(),{user:t}=_s(),{profile:n,saveProfile:r}=JXe(),[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(v=>{var N,C,A,T,P,M;return{...v,...n.data??{},full_name:((N=n.data)==null?void 0:N.full_name)??((C=t==null?void 0:t.user_metadata)==null?void 0:C.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:((P=n.data)==null?void 0:P.client_types)??[],brand_voice:((M=n.data)==null?void 0:M.brand_voice)??[]}}),h(!0))},[n.isLoading,n.data,t,u]);const m=(v,N)=>o(C=>({...C,[v]:N})),p=(v,N)=>o(C=>{const A=C[v]??[];return{...C,[v]:A.includes(N)?A.filter(T=>T!==N):[...A,N]}}),x=j.useMemo(()=>{var v,N,C;return a===0?!!((v=l.full_name)!=null&&v.trim())&&!!((N=l.email)!=null&&N.trim()):a===1?!!((C=l.primary_market)!=null&&C.trim()):a===2?(l.brand_voice??[]).length>0:!0},[a,l]),g=async(v,N)=>{if(t){d(!0);try{const C=v.name.split(".").pop(),A=`${t.id}/weekly-reels-${N}-${Date.now()}.${C}`,{error:T}=await U.storage.from("avatars").upload(A,v,{upsert:!0});if(T)throw T;const{data:P}=U.storage.from("avatars").getPublicUrl(A);m(N,P.publicUrl),ae.success("Image uploaded")}catch(C){ae.error(C instanceof Error?C.message:"Upload failed")}finally{d(!1)}}},y=async()=>{await r.mutateAsync({...l,onboarding_completed:!0}),ae.success("You're all set — your first pack is on the way."),s("/weekly-reels")},b=async()=>{await r.mutateAsync(l),ae.success("Progress saved")};return e.jsx(Ks,{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 ",WM.length," · ",WM[a].title]}),e.jsxs("span",{className:"neon-stat font-black",children:[Math.round((a+1)/WM.length*100),"%"]})]}),e.jsx(Ki,{value:(a+1)/WM.length*100,className:"mt-2 h-1.5"})]}),e.jsxs(_e,{className:"neon-topline rounded-2xl p-5 sm:p-7",children:[e.jsx("h2",{className:"text-lg font-semibold tracking-tight text-foreground",children:WM[a].title}),e.jsx("p",{className:"mt-1 text-[14px] text-muted-foreground",children:WM[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(se,{children:"Full name *"}),e.jsx(be,{value:l.full_name??"",onChange:v=>m("full_name",v.target.value),placeholder:"Jane Realtor"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:"Email *"}),e.jsx(be,{type:"email",value:l.email??"",onChange:v=>m("email",v.target.value),placeholder:"jane@brokerage.com"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:"Mobile number"}),e.jsx(be,{value:l.mobile_number??"",onChange:v=>m("mobile_number",v.target.value),placeholder:"Optional"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:"Brokerage"}),e.jsx(be,{value:l.brokerage??"",onChange:v=>m("brokerage",v.target.value)})]})]}),e.jsx("div",{className:"grid gap-4 sm:grid-cols-2",children:["headshot_url","logo_url"].map(v=>e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs(se,{children:[v==="headshot_url"?"Headshot":"Logo"," (optional)"]}),e.jsxs("div",{className:"flex items-center gap-3",children:[l[v]?e.jsx("img",{src:l[v],alt:v==="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 C=(A=N.target.files)==null?void 0:A[0];C&&g(C,v)}}),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(Ht,{className:"h-4 w-4 animate-spin"}):e.jsx(si,{className:"h-4 w-4"}),"Upload"]})]})]})]},v))})]}),a===1&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:"Primary market — city & state *"}),e.jsx(be,{value:l.primary_market??"",onChange:v=>m("primary_market",v.target.value),placeholder:"Tulsa, OK"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:"Neighborhoods or service areas"}),e.jsx(Is,{rows:2,value:l.service_areas??"",onChange:v=>m("service_areas",v.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(se,{children:"Years in real estate"}),e.jsxs(vs,{value:l.years_in_real_estate??"",onValueChange:v=>m("years_in_real_estate",v),children:[e.jsx(gs,{children:e.jsx(bs,{placeholder:"Select"})}),e.jsx(ys,{children:Kqn.map(v=>e.jsx(Ye,{value:v,children:v},v))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:"Typical price point"}),e.jsxs(vs,{value:l.typical_price_point??"",onValueChange:v=>m("typical_price_point",v),children:[e.jsx(gs,{children:e.jsx(bs,{placeholder:"Select"})}),e.jsx(ys,{children:Wqn.map(v=>e.jsx(Ye,{value:v,children:v},v))})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Primary specialties / niches"}),e.jsx("div",{className:"grid gap-2 sm:grid-cols-2",children:qqn.map(v=>e.jsxs("label",{className:"flex items-center gap-2.5 text-[14px]",children:[e.jsx(ui,{checked:(l.specialties??[]).includes(v),onCheckedChange:()=>p("specialties",v)}),v]},v))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Client types you serve"}),e.jsx("div",{className:"grid gap-2 sm:grid-cols-2",children:Vqn.map(v=>e.jsxs("label",{className:"flex items-center gap-2.5 text-[14px]",children:[e.jsx(ui,{checked:(l.client_types??[]).includes(v),onCheckedChange:()=>p("client_types",v)}),v]},v))})]})]}),a===2&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Brand voice — pick everything that fits *"}),e.jsx("div",{className:"grid gap-2 sm:grid-cols-2",children:Hqn.map(v=>e.jsxs("label",{className:"flex items-center gap-2.5 text-[14px]",children:[e.jsx(ui,{checked:(l.brand_voice??[]).includes(v),onCheckedChange:()=>p("brand_voice",v)}),v]},v))})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:"Anything else about how you talk?"}),e.jsx(Is,{rows:2,value:l.brand_voice_notes??"",onChange:v=>m("brand_voice_notes",v.target.value),placeholder:"I say 'y'all' a lot and I hate corporate jargon."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Humor level"}),e.jsx(wb,{value:l.humor_level??"",onValueChange:v=>m("humor_level",v),className:"space-y-1.5",children:Gqn.map(v=>e.jsxs("label",{className:"flex items-center gap-2.5 text-[14px]",children:[e.jsx(rh,{value:v.value}),v.label]},v.value))})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:"Personal interests & hobbies"}),e.jsx(Is,{rows:2,value:l.personal_interests??"",onChange:v=>m("personal_interests",v.target.value),placeholder:"Golf, smoking brisket, coaching my son's baseball team"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:"Family or community details you're happy to reference"}),e.jsx(Is,{rows:2,value:l.family_community_notes??"",onChange:v=>m("family_community_notes",v.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(se,{children:"Preferred Reel length"}),e.jsxs(vs,{value:l.preferred_reel_length??"30-45s",onValueChange:v=>m("preferred_reel_length",v),children:[e.jsx(gs,{children:e.jsx(bs,{})}),e.jsx(ys,{children:Xqn.map(v=>e.jsx(Ye,{value:v.value,children:v.label},v.value))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:"Preferred CTA style"}),e.jsxs(vs,{value:l.preferred_cta_style??"",onValueChange:v=>m("preferred_cta_style",v),children:[e.jsx(gs,{children:e.jsx(bs,{placeholder:"Select"})}),e.jsx(ys,{children:Yqn.map(v=>e.jsx(Ye,{value:v.value,children:v.label},v.value))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:"Main social platform"}),e.jsxs(vs,{value:l.main_platform??"instagram",onValueChange:v=>m("main_platform",v),children:[e.jsx(gs,{children:e.jsx(bs,{})}),e.jsx(ys,{children:Zqn.map(v=>e.jsx(Ye,{value:v.value,children:v.label},v.value))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:"Instagram handle"}),e.jsx(be,{value:l.instagram_handle??"",onChange:v=>m("instagram_handle",v.target.value),placeholder:"@janerealtor"})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:"Website"}),e.jsx(be,{value:l.website??"",onChange:v=>m("website",v.target.value),placeholder:"https://janerealtor.com"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"On-camera comfort level"}),e.jsx(wb,{value:l.content_comfort_level??"",onValueChange:v=>m("content_comfort_level",v),className:"space-y-1.5",children:Qqn.map(v=>e.jsxs("label",{className:"flex items-center gap-2.5 text-[14px]",children:[e.jsx(rh,{value:v.value}),v.label]},v.value))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Local vs evergreen content"}),e.jsx(wb,{value:l.content_mix??"mix",onValueChange:v=>m("content_mix",v),className:"space-y-1.5",children:Jqn.map(v=>e.jsxs("label",{className:"flex items-center gap-2.5 text-[14px]",children:[e.jsx(rh,{value:v.value}),v.label]},v.value))})]})]}),a===4&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:"Topics you love talking about"}),e.jsx(Is,{rows:2,value:l.topics_enjoyed??"",onChange:v=>m("topics_enjoyed",v.target.value),placeholder:"Renovation ROI, negotiating repairs, small-town living"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:"Topics you never want to cover"}),e.jsx(Is,{rows:2,value:l.topics_avoided??"",onChange:v=>m("topics_avoided",v.target.value),placeholder:"Politics, interest rate predictions, dancing trends"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:"Lead magnets or offers to promote"}),e.jsx(Is,{rows:2,value:l.lead_magnets??"",onChange:v=>m("lead_magnets",v.target.value),placeholder:"Free home value report, first-time buyer guide"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:"Current business goals"}),e.jsx(Is,{rows:2,value:l.business_goals??"",onChange:v=>m("business_goals",v.target.value),placeholder:"Two listings a month and more sphere referrals"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:"Compliance or brokerage disclaimer notes"}),e.jsx(Is,{rows:2,value:l.compliance_notes??"",onChange:v=>m("compliance_notes",v.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($,{type:"button",variant:"ghost",disabled:a===0,onClick:()=>i(v=>Math.max(0,v-1)),children:[e.jsx(ka,{className:"h-4 w-4 mr-1.5"})," Back"]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx($,{type:"button",variant:"outline",onClick:b,disabled:r.isPending,children:"Save draft"}),ai(v=>v+1),children:["Continue ",e.jsx(ni,{className:"h-4 w-4 ml-1.5"})]}):e.jsxs($,{className:"neon-cta",type:"button",onClick:y,disabled:r.isPending,children:[r.isPending?e.jsx(Ht,{className:"h-4 w-4 mr-1.5 animate-spin"}):e.jsx(oa,{className:"h-4 w-4 mr-1.5"}),"Finish setup"]})]})]})]})]})})})}function QGt(s,t=!1){const{user:n}=_s(),r=ts(),a=ht({queryKey:["wr-admin-members",s,t,n==null?void 0:n.id],enabled:!!n,queryFn:async()=>{let g=null;if(t){const{data:D,error:B}=await U.from("feature_entitlements").select("user_id").eq("feature_key",B9).eq("enabled",!0);if(B)throw B;if(g=(D??[]).map(q=>q.user_id),!g.length)return[]}let y=U.from("profiles").select("id, email, name").order("name",{ascending:!0}).limit(t?1e3:100);if(g&&(y=y.in("id",g)),s.trim()){const D=`%${s.trim()}%`;y=y.or(`email.ilike.${D},name.ilike.${D}`)}const{data:b,error:v}=await y;if(v)throw v;const N=(b??[]).map(D=>D.id);if(!N.length)return[];const[{data:C},{data:A},{data:T}]=await Promise.all([U.from("feature_entitlements").select("user_id, enabled, tier, expires_at").eq("feature_key",B9).in("user_id",N),U.from("weekly_reel_profiles").select("user_id, onboarding_completed, delivery_active, primary_market").in("user_id",N),U.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})]),P=new Map((C??[]).map(D=>[D.user_id,D])),M=new Map((A??[]).map(D=>[D.user_id,D])),I=new Map;return(T??[]).forEach(D=>{I.has(D.user_id)||I.set(D.user_id,D)}),(b??[]).map(D=>{const B=P.get(D.id),q=M.get(D.id),W=I.get(D.id);return{user_id:D.id,email:D.email,full_name:D.name,enabled:!!(B!=null&&B.enabled),tier:(B==null?void 0:B.tier)??null,expires_at:(B==null?void 0:B.expires_at)??null,onboarded:!!(q!=null&&q.onboarding_completed),delivery_active:(q==null?void 0:q.delivery_active)??!1,primary_market:(q==null?void 0:q.primary_market)??null,latest_week:(W==null?void 0:W.week_start_date)??null,latest_pack_id:(W==null?void 0:W.id)??null,latest_generation_status:(W==null?void 0:W.generation_status)??null,latest_delivery_status:(W==null?void 0:W.delivery_status)??null}})}}),i=ht({queryKey:["wr-admin-generation-logs"],enabled:!!n,queryFn:async()=>{const{data:g,error:y}=await U.from("weekly_reel_generation_logs").select("*").order("created_at",{ascending:!1}).limit(100);if(y)throw y;return g??[]}}),l=ht({queryKey:["wr-admin-delivery-logs"],enabled:!!n,queryFn:async()=>{const{data:g,error:y}=await U.from("weekly_reel_delivery_logs").select("*").order("created_at",{ascending:!1}).limit(100);if(y)throw y;return g??[]}}),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:g,enabled:y})=>{const{error:b}=await U.from("feature_entitlements").upsert({user_id:g,feature_key:B9,enabled:y,tier:"member",enabled_by:n.id,enabled_at:new Date().toISOString()},{onConflict:"user_id,feature_key"});if(b)throw b;await U.from("feature_entitlement_audit").insert({feature_key:B9,target_user_id:g,action:y?"grant":"revoke",performed_by:n.id})},onSuccess:(g,y)=>{o(),ae.success(y.enabled?"Access granted":"Access revoked")},onError:g=>ae.error(g.message)}),d=async g=>{const{data:y,error:b}=await U.functions.invoke("weekly-reels-generate",{body:g});if(b)throw b;if(y!=null&&y.error)throw new Error(String(y.error));return y},u=yt({mutationFn:g=>d({action:"generate_pack",userId:g.userId,force:g.force??!0}),onSuccess:()=>{o(),ae.success("Pack generated")},onError:g=>ae.error(g.message)}),h=yt({mutationFn:g=>d({action:"regenerate_reel",reelId:g.reelId,instructions:g.instructions}),onSuccess:()=>{o(),ae.success("Reel regenerated")},onError:g=>ae.error(g.message)}),m=yt({mutationFn:g=>d({action:"send_pack_email",packId:g.packId}),onSuccess:()=>{o(),ae.success("Pack emailed")},onError:g=>ae.error(g.message)}),p=yt({mutationFn:g=>d({action:"send_test_email",packId:g.packId,to:g.to}),onSuccess:()=>ae.success("Test email sent"),onError:g=>ae.error(g.message)}),x=yt({mutationFn:()=>d({action:"run_weekly"}),onSuccess:g=>{o(),ae.success(`Weekly run complete${(g==null?void 0:g.processed)!=null?` — ${g.processed} agents`:""}`)},onError:g=>ae.error(g.message)});return{members:a,generationLogs:i,deliveryLogs:l,setAccess:c,generatePack:u,regenerateReel:h,sendPack:m,sendTest:p,runWeekly:x}}function iz({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($e,{className:`${t} border-0 text-[11px] capitalize`,children:s})}function sVn({member:s,onClose:t}){var m,p,x;const n=QGt(""),{packs:r,profile:a}=JXe(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(Os,{open:!!s,onOpenChange:g=>!g&&t(),children:e.jsxs(Rs,{className:"max-w-3xl max-h-[88vh] overflow-y-auto",children:[e.jsxs(Us,{children:[e.jsx(zs,{children:(s==null?void 0:s.full_name)||(s==null?void 0:s.email)}),e.jsxs(Sr,{children:[((p=a.data)==null?void 0:p.primary_market)??"No market on file"," ·"," ",(x=a.data)!=null&&x.onboarding_completed?"Onboarded":"Onboarding incomplete"]})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs($,{size:"sm",onClick:()=>s&&n.generatePack.mutate({userId:s.user_id}),disabled:n.generatePack.isPending,children:[n.generatePack.isPending?e.jsx(Ht,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(dn,{className:"h-4 w-4 mr-2"}),"Generate pack"]}),e.jsxs($,{size:"sm",variant:"outline",disabled:!h||n.sendPack.isPending,onClick:()=>h&&n.sendPack.mutate({packId:h.id}),children:[e.jsx(nn,{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(se,{className:"text-[12px]",children:"Send a test copy to"}),e.jsx(be,{value:i,onChange:g=>l(g.target.value),placeholder:"you@relevelup.com"})]}),e.jsxs($,{size:"sm",variant:"outline",disabled:!h||!i||n.sendTest.isPending,onClick:()=>h&&n.sendTest.mutate({packId:h.id,to:i}),children:[e.jsx(Br,{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($e,{variant:"outline",children:["Week of ",cZ(h.week_start_date)]}),e.jsx(iz,{value:h.generation_status}),e.jsx(iz,{value:h.delivery_status})]}),h.reels.map((g,y)=>e.jsxs("div",{className:"space-y-2",children:[e.jsx(UNe,{reel:g,index:y,readOnly:!0}),d===g.id?e.jsxs("div",{className:"rounded-xl border border-border/70 p-3 space-y-2",children:[e.jsx(Is,{rows:2,value:o,onChange:b=>c(b.target.value),placeholder:"Optional guidance: make it more local, less salesy, focus on sellers..."}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs($,{size:"sm",disabled:n.regenerateReel.isPending,onClick:()=>n.regenerateReel.mutate({reelId:g.id,instructions:o||void 0},{onSuccess:()=>{u(null),c(""),r.refetch()}}),children:[n.regenerateReel.isPending?e.jsx(Ht,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(Wi,{className:"h-4 w-4 mr-2"}),"Regenerate"]}),e.jsx($,{size:"sm",variant:"ghost",onClick:()=>u(null),children:"Cancel"})]})]}):e.jsxs($,{size:"sm",variant:"outline",onClick:()=>u(g.id),children:[e.jsx(Wi,{className:"h-4 w-4 mr-2"})," Regenerate this reel"]})]},g.id))]}):e.jsx("p",{className:"py-6 text-center text-[14px] text-muted-foreground",children:"No packs generated for this agent yet."}),e.jsx(kr,{children:e.jsx($,{variant:"outline",onClick:t,children:"Close"})})]})})}function nVn(){const[s,t]=j.useState(""),[n,r]=j.useState(!1),[a,i]=j.useState(null),l=QGt(s,n),o=j.useMemo(()=>l.members.data??[],[l.members.data]);return e.jsxs(Ks,{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($,{onClick:()=>l.runWeekly.mutate(),disabled:l.runWeekly.isPending,children:[l.runWeekly.isPending?e.jsx(Ht,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(dn,{className:"h-4 w-4 mr-2"}),"Run this week now"]})]}),e.jsxs(ua,{defaultValue:"members",className:"mt-7",children:[e.jsxs(ha,{children:[e.jsx(Qt,{value:"members",children:"Members"}),e.jsx(Qt,{value:"generation",children:"Generation log"}),e.jsx(Qt,{value:"delivery",children:"Delivery log"})]}),e.jsxs(Jt,{value:"members",className:"mt-5",children:[e.jsx(_e,{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(Vr,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),e.jsx(be,{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(Tn,{checked:n,onCheckedChange:r}),"Only members with access"]})]})}),e.jsx(_e,{className:"mt-4 rounded-2xl overflow-hidden",children:e.jsxs(Va,{children:[e.jsx(Ha,{children:e.jsxs(hn,{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(Ga,{children:l.members.isLoading?e.jsx(hn,{children:e.jsx(gt,{colSpan:8,className:"py-10 text-center",children:e.jsx(Ht,{className:"mx-auto h-5 w-5 animate-spin text-muted-foreground"})})}):o.length?o.map(c=>e.jsxs(hn,{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($e,{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?cZ(c.latest_week):"—"}),e.jsx(gt,{children:e.jsx(iz,{value:c.latest_generation_status})}),e.jsx(gt,{children:e.jsx(iz,{value:c.latest_delivery_status})}),e.jsx(gt,{className:"text-right",children:e.jsx(Tn,{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($,{size:"sm",variant:"ghost",onClick:()=>i(c),children:"Manage"})})]},c.user_id)):e.jsx(hn,{children:e.jsx(gt,{colSpan:8,className:"py-10 text-center text-muted-foreground",children:"No members match this search."})})})]})})]}),e.jsx(Jt,{value:"generation",className:"mt-5",children:e.jsx(_e,{className:"rounded-2xl overflow-hidden",children:e.jsxs(Va,{children:[e.jsx(Ha,{children:e.jsxs(hn,{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(Ga,{children:(l.generationLogs.data??[]).map(c=>e.jsxs(hn,{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(iz,{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(Jt,{value:"delivery",className:"mt-5",children:e.jsx(_e,{className:"rounded-2xl overflow-hidden",children:e.jsxs(Va,{children:[e.jsx(Ha,{children:e.jsxs(hn,{children:[e.jsx(Lt,{children:"When"}),e.jsx(Lt,{children:"Recipient"}),e.jsx(Lt,{children:"Status"}),e.jsx(Lt,{children:"Error"})]})}),e.jsx(Ga,{children:(l.deliveryLogs.data??[]).map(c=>e.jsxs(hn,{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(iz,{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(sVn,{member:a,onClose:()=>i(null)})]})}function MV(){const{user:s}=_s(),t=ts(),n=ht({queryKey:["attract-settings",s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:i,error:l}=await U.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 U.from("attract_settings").upsert(l,{onConflict:"user_id"}).select().single();if(c)throw c;return o},onSuccess:()=>{t.invalidateQueries({queryKey:["attract-settings"]}),ae.success("Settings saved")},onError:i=>ae.error(i.message)}),a=yt({mutationFn:async()=>{const{error:i}=await U.from("attract_settings").update({onboarding_completed_at:null}).eq("user_id",s.id);if(i)throw i},onSuccess:()=>{t.invalidateQueries({queryKey:["attract-settings"]}),ae.success("Onboarding reset — run it again anytime")}});return{settings:n.data,isLoading:n.isLoading,save:r,upsert:r,resetOnboarding:a}}const JGt="v1",wh={recency:22,consistency:16,value_delivered:14,kit_engagement:16,event_participation:12,follow_up_discipline:10,pipeline_momentum:10};Object.values(wh).reduce((s,t)=>s+t,0);const eWt=864e5,og=(s,t=new Date)=>Math.floor((new Date(t).getTime()-new Date(s).getTime())/eWt),tWt=["touch_logged","call","text","email","dm","meeting","note"];function rVn(s,t,n=new Date){var g,y,b;const a=t.activities.filter(v=>v.agent_id===s.id).filter(v=>tWt.includes(v.activity_type)).sort((v,N)=>+new Date(N.created_at)-+new Date(v.created_at)),i=s.last_touch_at||((g=a[0])==null?void 0:g.created_at)||null,l=t.shares.filter(v=>v.agent_id===s.id),o=new Set(l.map(v=>v.id)),c=t.kitEvents.filter(v=>o.has(v.share_id)),d={};for(const v of l)d[v.id]=[];for(const v of c)(d[y=v.share_id]||(d[y]=[])).push(v);const u=t.attendees.filter(v=>v.agent_id===s.id),h=t.followUps.filter(v=>v.agent_id===s.id),m=h.filter(v=>!v.completed_at),p=t.stageChanges.filter(v=>v.agent_id===s.id).sort((v,N)=>+new Date(N.created_at)-+new Date(v.created_at)),x=new Set(a.filter(v=>og(v.created_at,n)<=180).map(v=>v.created_at.slice(0,7)));return{agent:s,touches:a,lastTouchAt:i,daysSinceTouch:i?og(i,n):null,touches90:a.filter(v=>og(v.created_at,n)<=90).length,touches30:a.filter(v=>og(v.created_at,n)<=30).length,distinctTouchMonths:x.size,shares:l,shareEvents:d,highIntentShares:l.filter(v=>v.engagement_level==="high_intent"||v.engagement_level==="engaged"),lastShareAt:l.map(v=>v.created_at).sort().reverse()[0]||null,totalKitOpens:l.reduce((v,N)=>v+(N.open_count||0),0),downloads:c.filter(v=>v.event_type==="file_download").length,ctaClicks:c.filter(v=>v.event_type==="primary_cta_click"||v.event_type==="external_link_click").length,questions:c.filter(v=>v.event_type==="question_submitted").length,meetingRequests:c.filter(v=>v.event_type==="meeting_requested").length+u.filter(v=>v.meeting_requested).length,attendees:u,attended:u.filter(v=>!!v.checked_in_at||v.status==="attended").length,noShows:u.filter(v=>!!v.no_show_at||v.status==="no_show").length,invitedNotRegistered:u.filter(v=>!!v.invited_at&&!v.registered_at&&!v.checked_in_at).length,openFollowUps:m,overdueFollowUps:m.filter(v=>v.due_at&&new Date(v.due_at)!!v.completed_at),stageChanges:p,lastStageChangeAt:((b=p[0])==null?void 0:b.created_at)||null,daysSinceStageChange:p[0]?og(p[0].created_at,n):null,scoreEvents:t.scoreEvents.filter(v=>v.agent_id===s.id)}}const qNe=["new_connection","building_relationship","engaging_with_value","active_conversation","exploring_options","brokerage_presentation","decision_pending","joined"],VNe=["not_right_now","not_a_fit","long_term_relationship"];function aVn(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=wh.recency,c=`Last meaningful touch ${l} day(s) ago.`,r.push("Recent personal contact")):l<=21?(o=wh.recency*.85,c=`Last touch ${l} days ago.`,r.push("Contact is still fresh")):l<=45?(o=wh.recency*.6,c=`Last touch ${l} days ago.`,i.push("Reach out within the next week to keep momentum.")):l<=90?(o=wh.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=wh.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:wh.recency,earned:Math.round(o),detail:c,direction:o>=wh.recency*.6?"positive":"negative"});const d=Math.min(s.distinctTouchMonths,6),u=wh.consistency*(d/6),h=s.touches30>6;n.push({key:"consistency",label:"Consistency of touches",weight:wh.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>=wh.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=wh.value_delivered*Math.min(m/3,1);n.push({key:"value_delivered",label:"Value delivered",weight:wh.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 x=(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),g=Math.min(x,wh.kit_engagement);n.push({key:"kit_engagement",label:"Kit engagement",weight:wh.kit_engagement,earned:g,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:g>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,b=Math.max(0,Math.min(y,wh.event_participation));n.push({key:"event_participation",label:"Event participation",weight:wh.event_participation,earned:b,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:b>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 v=s.completedFollowUps.length+s.openFollowUps.length;let N=v===0?wh.follow_up_discipline*.4:wh.follow_up_discipline*(s.completedFollowUps.length/v);N-=Math.min(s.overdueFollowUps.length,3)*2,N=Math.max(0,Math.min(N,wh.follow_up_discipline)),n.push({key:"follow_up_discipline",label:"Follow-up discipline",weight:wh.follow_up_discipline,earned:Math.round(N),detail:v?`${s.completedFollowUps.length} of ${v} 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 C=qNe.indexOf(s.agent.stage);let A=0,T;if(VNe.includes(s.agent.stage))A=wh.pipeline_momentum*.3,T="Relationship is intentionally parked — long-term nurture.";else if(C<0)A=wh.pipeline_momentum*.3,T=`Stage "${s.agent.stage}" is outside the advancing ladder.`;else{const I=wh.pipeline_momentum*(C/(qNe.length-1)),D=s.daysSinceStageChange!==null&&s.daysSinceStageChange>60;A=D?I*.5:I,T=`Stage ${C+1} of ${qNe.length}`+(s.daysSinceStageChange!==null?`, last moved ${s.daysSinceStageChange} days ago.`:", never moved."),D&&(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:wh.pipeline_momentum,earned:Math.round(A),detail:T,direction:A>wh.pipeline_momentum*.5?"positive":"neutral"});let P=n.reduce((I,D)=>I+D.earned,0);s.agent.temperature==="hot"&&(P+=4,r.push("You marked this relationship hot")),s.agent.temperature==="cold"&&(P-=4,a.push("You marked this relationship cold")),h&&(P-=3),P=Math.max(0,Math.min(100,Math.round(P)));const M=P>=75?"thriving":P>=55?"healthy":P>=35?"cooling":"at_risk";return{agent_id:s.agent.id,score:P,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:{...wh},engine_version:JGt,calculated_at:t.toISOString()}}const sWt=[{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"}],iVn={urgent:100,high:70,medium:40,low:15},cj=(s,t=new Date)=>new Date(t.getTime()+s*eWt).toISOString(),Qk=s=>s.first_name||"there",oVn=3;function dj(s,t,n={}){var o,c;const r=Qk(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 lVn(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 b;return(b=t.kits.find(v=>v.id===y))==null?void 0:b.title},o=y=>{r.push({...y,message_source:"rules",rank_score:y.rank_score??iVn[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,b=[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 ${Qk(a)} — they are actively engaging`,reasons:b,priority:"urgent",suggested_due_at:cj(1,n),draft_message:dj("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&&og(y.last_opened_at,n)<=7&&og(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:`${Qk(a)} came back to a kit you shared`,reasons:[`Re-opened "${l(d.kit_id)??"a shared kit"}" ${og(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:cj(2,n),draft_message:dj("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&&og(y.checked_in_at,n)<=7&&y.followup_status!=="done").sort((y,b)=>+new Date(b.checked_in_at)-+new Date(y.checked_in_at))[0];if(u){const y=t.events.find(v=>v.id===u.event_id),b=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"} — ${b}h since they attended`,reasons:[`Checked in to "${(y==null?void 0:y.title)??"event"}" ${b} hours ago`,`Follow-up status is "${u.followup_status??"pending"}"`,b<=48?"Inside the 48-hour window where follow-up matters most":"Past the ideal 48-hour window — still worth doing today"],priority:b<=48?"urgent":"high",suggested_due_at:cj(b<=48?1:0,n),draft_message:dj("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:b},rank_score:b<=48?96:74})}else{const y=s.attendees.find(b=>b.no_show_at&&og(b.no_show_at,n)<=10);if(y){const b=t.events.find(v=>v.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:`${Qk(a)} missed ${(b==null?void 0:b.title)??"an event"} — recover gracefully`,reasons:[`Registered but did not attend "${(b==null?void 0:b.title)??"event"}"`,"No-show recovery works best within a week, with zero guilt"],priority:"medium",suggested_due_at:cj(2,n),draft_message:dj("event_no_show",s,{eventTitle:b==null?void 0:b.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&&og(y.first_opened_at,n)>=3&&og(y.first_opened_at,n)<=30&&(s.daysSinceTouch===null||s.lastTouchAt&&new Date(s.lastTouchAt)!y.first_opened_at&&og(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 ${og(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:cj(2,n),draft_message:dj("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 ${Qk(a)} personally`,reasons:[`Shared ${og(m.created_at,n)} days ago and never opened`,"A personal message beats a resend"],priority:"medium",suggested_due_at:cj(2,n),draft_message:dj("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,b)=>+new Date(y.due_at)-+new Date(b.due_at))[0];if(p){const y=og(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:cj(0,n),draft_message:dj("overdue_commitment",s,{followUpTitle:p.title}),source_signals:{follow_up_id:p.id,days_late:y},rank_score:92+Math.min(y,8)})}const x=qNe.indexOf(a.stage);if(!VNe.includes(a.stage)&&x>=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 ${Qk(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:cj(4,n),draft_message:dj("ready_deeper",s),source_signals:{stage:a.stage,attended:s.attended},rank_score:72}),s.daysSinceTouch===null&&og(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 ${Qk(a)}`,reasons:[`Added to your pipeline ${og(a.created_at,n)} days ago`,"No touch, kit, or event activity logged"],priority:"medium",suggested_due_at:cj(3,n),draft_message:dj("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 b=s.daysSinceTouch>y*2;o({agent_id:a.id,rec_key:b?"no_touch_long":"going_cold",signal_group:b?"no_touch":"going_cold",signal_label:b?"No meaningful touch recently":"Relationship going cold",action_type:"check_in",channel:"personal_check_in",title:`${Qk(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:b?"high":"medium",suggested_due_at:cj(3,n),draft_message:dj(b?"no_touch":"going_cold",s),source_signals:{days_since_touch:s.daysSinceTouch,threshold:y},rank_score:b?62:44})}}if(!s.shares.length&&!VNe.includes(a.stage)&&t.primaryPillar==="provide"){const y=t.kits.find(b=>b.status==="published"&&(!b.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 ${Qk(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:cj(5,n),draft_message:dj("share_value",s,{kitTitle:y.title}),suggested_kit_id:y.id,source_signals:{pillar:"provide"},rank_score:38})}if(!s.attendees.length&&!VNe.includes(a.stage)&&t.primaryPillar==="connect"){const y=t.events.filter(b=>b.status==="published"&&b.starts_at&&new Date(b.starts_at)>n).sort((b,v)=>+new Date(b.starts_at)-+new Date(v.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 ${Qk(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:cj(4,n),draft_message:dj("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,b)=>b.rank_score-y.rank_score).slice(0,3)}const Ubt=[{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"]}],cVn={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 dVn(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:tWt.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 uVn(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,x)=>+new Date(p.created_at)-+new Date(x.created_at))[0]??null,h=s.stageChanges.filter(p=>new Date(p.created_at)>new Date(r.created_at)).sort((p,x)=>+new Date(p.created_at)-+new Date(x.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 hVn(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 nh=U;function mVn(){const{user:s}=_s();return ht({queryKey:["attract-intel-data",s==null?void 0:s.id],enabled:!!s,staleTime:3e4,queryFn:async()=>{var x,g;const[t,n,r,a,i,l,o,c,d,u,h,m]=await Promise.all([nh.from("attract_agents").select("*").order("updated_at",{ascending:!1}),nh.from("attract_activities").select("*").order("created_at",{ascending:!1}).limit(2e3),nh.from("attract_follow_ups").select("*").order("created_at",{ascending:!1}).limit(2e3),nh.from("attract_kit_shares").select("*").order("created_at",{ascending:!1}).limit(1e3),nh.from("attract_kit_events").select("*").order("created_at",{ascending:!1}).limit(2e3),nh.from("attract_event_attendees").select("*").order("created_at",{ascending:!1}).limit(2e3),nh.from("attract_events").select("id, title, starts_at, status, resource_kit_id, public_slug").limit(500),nh.from("attract_pipeline_history").select("*").order("created_at",{ascending:!1}).limit(2e3),nh.from("attract_score_events").select("*").order("created_at",{ascending:!1}).limit(2e3),nh.from("attract_resource_kits").select("id, title, audience, pillar, status, is_template").eq("is_template",!1),nh.from("attract_event_notes").select("*").order("created_at",{ascending:!1}).limit(1e3),nh.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:((x=m==null?void 0:m.data)==null?void 0:x.primary_pillar)??((g=m==null?void 0:m.data)==null?void 0:g.attraction_style)??null}}})}function sM(){const s=mVn(),t=j.useMemo(()=>{if(!s.data)return[];const r=new Date;return s.data.agents.map(a=>{const i=rVn(a,s.data,r),l=aVn(i,r),o=lVn(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 pVn(s){const{dataset:t,byId:n,isLoading:r,error:a,refetch:i}=sM(),l=s?n.get(s)??null:null,o=j.useMemo(()=>l&&t?dVn(l.signals,t,t.eventNotes??[]):[],[l,t]),c=j.useMemo(()=>l&&t?uVn(l.signals,t,typeof window<"u"?window.location.origin:""):[],[l,t]),d=j.useMemo(()=>l&&t?hVn(l.signals,t):null,[l,t]);return{item:l,dataset:t,timeline:o,valueShared:c,nextKit:d,isLoading:r,error:a,refetch:i}}function nWt(){const{user:s}=_s(),t=ts();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:JGt,calculated_at:i.score.calculated_at}));for(let i=0;i{t.invalidateQueries({queryKey:["attract-score-snapshots"]}),n&&!r&&ae.success(`Recalculated ${n} relationship score${n===1?"":"s"}`)},onError:n=>ae.error(n.message??"Could not save scores")})}function vte(){const{user:s}=_s();return ht({queryKey:["attract-recommendations",s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await nh.from("attract_recommendations").select("*").order("rank_score",{ascending:!1});if(n)throw n;return t??[]}})}function RTe(){const{user:s}=_s(),t=ts();return yt({mutationFn:async n=>{if(!s)return{inserted:0,refreshed:0};const r=n.flatMap(u=>u.recommendations),{data:a,error:i}=await nh.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 nh.from("attract_recommendations").insert(o);if(u)throw u}for(const u of c)await nh.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=>ae.error(n.message??"Could not sync recommendations")})}function rWt(){const{user:s}=_s(),t=ts(),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 nh.from("attract_recommendations").update(d).eq("id",c);if(u)throw u},onSuccess:n,onError:c=>ae.error(c.message)}),a=yt({mutationFn:async c=>{const{error:d}=await nh.from("attract_recommendations").update({status:"dismissed",dismissed_at:new Date().toISOString()}).eq("id",c);if(d)throw d},onSuccess:()=>{n(),ae.success("Dismissed")}}),i=yt({mutationFn:async({id:c,days:d})=>{const u=new Date(Date.now()+d*864e5).toISOString(),{error:h}=await nh.from("attract_recommendations").update({status:"snoozed",snoozed_until:u}).eq("id",c);if(h)throw h},onSuccess:()=>{n(),ae.success("Snoozed")}}),l=yt({mutationFn:async c=>{if(c.follow_up_id){const{data:h}=await nh.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 nh.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 nh.from("attract_recommendations").update({follow_up_id:d.id}).eq("id",c.id),{id:d.id,existed:!1}},onSuccess:c=>{n(),ae.success(c.existed?"Follow-up already exists":"Follow-up created")},onError:c=>ae.error(c.message)}),o=yt({mutationFn:async({rec:c,note:d})=>{const u=new Date().toISOString(),{error:h}=await nh.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 nh.from("attract_follow_ups").update({completed_at:u}).eq("id",c.follow_up_id).is("completed_at",null),await nh.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 nh.from("attract_recommendations").update({status:"completed",completed_at:u}).eq("id",c.id);if(m)throw m},onSuccess:()=>{n(),t.invalidateQueries({queryKey:["attract-score"]}),ae.success("Logged — timeline and score updated")},onError:c=>ae.error(c.message)});return{update:r,dismiss:a,snooze:i,createFollowUp:l,logCompleted:o}}function fVn(){const{user:s}=_s(),t=ts();return yt({mutationFn:async n=>{const{error:r}=await nh.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"]}),ae.success("Logged")},onError:n=>ae.error(n.message)})}const qbt={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 eQe({score:s,className:t}){const n=qbt[s.band]??qbt.cooling;return e.jsxs($e,{variant:"outline",className:Tt("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 aWt({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(eQe,{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:Tt("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(Il,{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(FN,{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(DN,{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 Vbt({className:s}){const{intel:t}=sM(),[n,r]=j.useState(""),[a,i]=j.useState(!1),l=Vn(),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:Tt("relative",s),children:[e.jsx(Vr,{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(eQe,{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 iRe=[{to:"/attract",label:"Today",icon:Kj,exact:!0},{to:"/attract/relationships",label:"Relationships",icon:qn},{to:"/attract/share",label:"Share Value",icon:pR},{to:"/attract/create",label:"Create Content",icon:wm},{to:"/attract/results",label:"Results",icon:ml},{to:"/attract/settings",label:"Settings",icon:pc}],Hbt=[{to:"/attract/plan",label:"90-Day Plan"},{to:"/attract/opportunities",label:"Opportunities"},{to:"/attract/pipeline",label:"Agent Pipeline (legacy)"},{to:"/attract/follow-up",label:"Follow-Up Center"},{to:"/attract/landing-page",label:"Attraction Page"},{to:"/attract/events",label:"Events"},{to:"/attract/provide/kits",label:"Resource Kits"},{to:"/attract/provide/masterclasses",label:"Masterclasses"},{to:"/attract/resources",label:"Resources"},{to:"/attract/templates",label:"Templates & Scripts"},{to:"/attract/digest",label:"Weekly Digest"},{to:"/attract/produce",label:"Produce tools"},{to:"/attract/influence",label:"Influence tools"},{to:"/attract/connect",label:"Connect tools"}];function xVn(){const s=Wd(),{settings:t,isLoading:n}=MV(),r=!n&&!!t&&!t.onboarding_completed_at,a=s.pathname==="/attract/onboarding";if(r&&!a&&!s.pathname.startsWith("/attract/settings"))return e.jsx(r1,{to:"/attract/onboarding",replace:!0});const i=iRe.slice(0,5);return e.jsxs("div",{className:"attract-root min-h-screen bg-[#F7F7FB] 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-72 flex-col bg-[#0B0F1E] text-slate-200 border-r border-white/5",children:[e.jsxs("div",{className:"px-6 py-6 border-b border-white/10",children:[e.jsxs(_A,{to:"/dashboard",className:"inline-flex items-center gap-1.5 text-[11px] uppercase tracking-widest text-slate-400 hover:text-white transition-colors",children:[e.jsx(ka,{className:"h-3 w-3"})," LevelUp Hub"]}),e.jsxs("div",{className:"mt-3 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/40",children:e.jsx(W3,{className:"h-4 w-4 text-white"})}),e.jsxs("div",{children:[e.jsx("div",{className:"text-[15px] font-semibold tracking-tight text-white",children:"LEVELUP ATTRACT"}),e.jsx("div",{className:"text-[10.5px] text-slate-400 leading-tight",children:"Attract through value. Grow through relationships."})]})]})]}),e.jsx("div",{className:"px-4 pt-3",children:e.jsx(Vbt,{})}),e.jsxs("nav",{className:"flex-1 overflow-y-auto py-3 px-3",children:[iRe.map(l=>{const o=l.icon;return e.jsxs(_A,{to:l.to,end:l.exact,className:({isActive:c})=>Tt("group flex items-center gap-3 px-3 py-2.5 rounded-xl text-[13.5px] font-medium transition-all",c?"bg-gradient-to-r from-violet-600/30 to-indigo-600/10 text-white ring-1 ring-inset ring-violet-500/40":"text-slate-300 hover:bg-white/5 hover:text-white"),children:[e.jsx(o,{className:"h-4 w-4 flex-shrink-0 opacity-80 group-hover:opacity-100"}),e.jsx("span",{className:"flex-1",children:l.label})]},l.to)}),e.jsxs(uv,{className:"mt-4",children:[e.jsxs(hv,{className:"w-full flex items-center justify-between px-3 py-2 text-[11px] uppercase tracking-[0.14em] text-slate-500 font-semibold hover:text-slate-300",children:["All tools ",e.jsx(_o,{className:"h-3.5 w-3.5"})]}),e.jsx(mv,{className:"pt-1",children:Hbt.map(l=>e.jsx(_A,{to:l.to,className:({isActive:o})=>Tt("block rounded-lg px-3 py-2 text-[12.5px]",o?"bg-white/10 text-white":"text-slate-400 hover:text-white hover:bg-white/5"),children:l.label},l.to))})]})]}),e.jsx("div",{className:"px-4 py-4 border-t border-white/5",children:e.jsxs("div",{className:"rounded-xl bg-white/5 p-3",children:[e.jsx("div",{className:"text-[11px] font-medium text-violet-300",children:"Beta preview"}),e.jsx("div",{className:"text-[11.5px] text-slate-400 mt-1 leading-snug",children:"Build relationships first. Personalize every message and verify brokerage and compensation info before sharing."})]})})]}),e.jsxs("div",{className:"lg:hidden fixed top-0 inset-x-0 z-40 bg-[#0B0F1E] text-white px-4 py-3 flex items-center gap-3 border-b border-white/10",children:[e.jsx(_A,{to:"/dashboard",className:"text-slate-400",children:e.jsx(ka,{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(W3,{className:"h-4 w-4"})}),e.jsxs("div",{children:[e.jsx("div",{className:"text-[13px] font-semibold tracking-tight",children:"LEVELUP ATTRACT"}),e.jsx("div",{className:"text-[10px] text-slate-400",children:"Attract through value"})]})]}),e.jsxs("div",{className:"lg:hidden fixed bottom-0 inset-x-0 z-40 bg-[#0B0F1E]/95 backdrop-blur border-t border-white/10 flex",children:[i.map(l=>{const o=l.icon;return e.jsxs(_A,{to:l.to,end:l.exact,className:({isActive:c})=>Tt("flex-1 min-w-0 flex flex-col items-center gap-1 py-2 text-[10px]",c?"text-white":"text-slate-400"),children:[e.jsx(o,{className:"h-4 w-4"}),e.jsx("span",{className:"truncate max-w-[70px]",children:l.label})]},l.to)}),e.jsxs(Ub,{children:[e.jsx(cee,{asChild:!0,children:e.jsxs("button",{className:"flex-1 min-w-0 flex flex-col items-center gap-1 py-2 text-[10px] text-slate-400",children:[e.jsx(p0,{className:"h-4 w-4"}),e.jsx("span",{children:"More"})]})}),e.jsx(T1,{side:"bottom",className:"bg-[#0B0F1E] text-slate-200 border-white/10 rounded-t-3xl max-h-[75vh] overflow-y-auto",children:e.jsxs("div",{className:"pt-4 pb-8",children:[e.jsx(Vbt,{className:"mb-4"}),e.jsx("div",{className:"text-[10px] uppercase tracking-widest text-slate-500 font-semibold mb-2",children:"All sections"}),iRe.map(l=>{const o=l.icon;return e.jsxs(_A,{to:l.to,end:l.exact,className:({isActive:c})=>Tt("flex items-center gap-3 rounded-xl px-3 py-3 text-[13.5px] font-medium",c?"bg-violet-600/30 text-white":"text-slate-300 hover:bg-white/5"),children:[e.jsx(o,{className:"h-4 w-4 opacity-80"}),e.jsx("span",{children:l.label})]},l.to)}),e.jsx("div",{className:"mt-4 mb-1 text-[10px] uppercase tracking-widest text-slate-500 font-semibold",children:"All tools"}),Hbt.map(l=>e.jsx(_A,{to:l.to,className:({isActive:o})=>Tt("block rounded-xl px-3 py-2.5 text-[13px]",o?"bg-white/10 text-white":"text-slate-400 hover:bg-white/5"),children:l.label},l.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-[1400px] mx-auto px-4 sm:px-6 lg:px-10 py-6 lg:py-10",children:e.jsx(mSt,{})},s.pathname)})]})]})}function GG({label:s,value:t,delta:n,icon:r,tone:a="violet"}){const i={violet:"from-violet-500 to-indigo-600",teal:"from-teal-500 to-cyan-600",green:"from-emerald-500 to-green-600",orange:"from-orange-500 to-amber-600",rose:"from-rose-500 to-pink-600"};return e.jsx(_e,{className:"p-5 rounded-2xl border-slate-200/70 bg-white shadow-sm hover:shadow-md transition-shadow",children:e.jsxs("div",{className:"flex items-start justify-between",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[11.5px] uppercase tracking-wider font-medium text-slate-500",children:s}),e.jsx("div",{className:"mt-2 text-[26px] font-semibold tracking-tight text-slate-900",children:t}),n&&e.jsxs("div",{className:"mt-1 text-[11.5px] font-medium text-emerald-600 flex items-center gap-1",children:[e.jsx(mT,{className:"h-3 w-3"}),n]})]}),e.jsx("div",{className:Tt("h-10 w-10 rounded-xl bg-gradient-to-br grid place-items-center shadow-sm",i[a]),children:e.jsx(r,{className:"h-5 w-5 text-white"})})]})})}function gVn(){const{user:s}=_s();return ht({queryKey:["attract-score",s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await U.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 yVn=[{key:"relationships_added",label:"Relationships Added",icon:t1,target:15},{key:"follow_ups_completed",label:"Follow-Ups Completed",icon:Fr,target:15},{key:"resources_shared",label:"Resources Shared",icon:vd,target:15},{key:"content_posted",label:"Agent Content Posted",icon:Eh,target:15},{key:"events_connections",label:"Events / Connections",icon:LN,target:20},{key:"brokerage_conversations",label:"Brokerage Conversations",icon:Mz,target:20}];function iWt(){const{data:s}=gVn(),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(_e,{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(Il,{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:yVn.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($,{variant:"outline",size:"sm",className:"rounded-full",children:"View Score Breakdown"})})]})}const WG=U;function M0(){const{user:s}=_s(),t=ts(),n=ht({queryKey:["attract-agents",s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:d,error:u}=await U.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 U.from("attract_agents").update(u).eq("id",d.id).select().single():await U.from("attract_agents").insert(u).select().single();if(m)throw m;return h},onSuccess:()=>{r(),ae.success("Saved")},onError:d=>ae.error(d.message)}),i=yt({mutationFn:async({id:d,to_stage:u,from_stage:h})=>{const{error:m}=await U.from("attract_agents").update({stage:u}).eq("id",d);if(m)throw m;await U.from("attract_pipeline_history").insert({user_id:s.id,agent_id:d,from_stage:h??null,to_stage:u})},onSuccess:()=>r(),onError:d=>ae.error(d.message)}),l=yt({mutationFn:async({id:d,values:u,changedLabels:h,previousStage:m})=>{const{stage:p,...x}=u;if(Object.keys(x).length){const{error:g}=await WG.from("attract_agents").update(x).eq("id",d);if(g)throw g}if(p&&p!==m){const{error:g}=await WG.from("attract_agents").update({stage:p}).eq("id",d);if(g)throw g;await WG.from("attract_pipeline_history").insert({user_id:s.id,agent_id:d,from_stage:m??null,to_stage:p})}h.length&&await WG.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(),ae.success("Contact updated")},onError:d=>ae.error(d.message??"Could not save contact")}),o=yt({mutationFn:async({id:d,archived:u})=>{const{error:h}=await WG.from("attract_agents").update({is_archived:u}).eq("id",d);if(h)throw h},onSuccess:(d,u)=>{r(),ae.success(u.archived?"Removed from active pipeline":"Restored to pipeline")},onError:d=>ae.error(d.message)}),c=yt({mutationFn:async d=>{const{error:u}=await U.from("attract_agents").delete().eq("id",d);if(u)throw u},onSuccess:()=>{r(),ae.success("Contact permanently deleted")},onError:d=>ae.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}}const oRe=[{key:"new_connection",label:"New Connection"},{key:"building_relationship",label:"Building Relationship"},{key:"engaging_with_value",label:"Engaging With Value"},{key:"active_conversation",label:"Active Conversation"},{key:"exploring_options",label:"Exploring Options"},{key:"brokerage_presentation",label:"Brokerage Presentation"},{key:"decision_pending",label:"Decision Pending"},{key:"joined",label:"Joined"}];function vVn(){const{agents:s}=M0(),t=Math.max(1,...oRe.map(n=>s.filter(r=>r.stage===n.key).length));return e.jsxs(_e,{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:"Pipeline Overview"}),e.jsx("div",{className:"text-[18px] font-semibold text-slate-900 mt-0.5",children:"Where relationships live right now"})]}),e.jsx($,{asChild:!0,variant:"outline",size:"sm",className:"rounded-full gap-1",children:e.jsxs(Wn,{to:"/attract/relationships",children:["View All Relationships ",e.jsx(Ja,{className:"h-3.5 w-3.5"})]})})]}),e.jsx("div",{className:"space-y-2",children:oRe.map((n,r)=>{const a=s.filter(o=>o.stage===n.key).length,i=30+a/t*70,l=.35+(1-r/oRe.length)*.55;return e.jsxs("div",{className:"grid grid-cols-[180px_1fr_36px] items-center gap-3",children:[e.jsx("span",{className:"text-[12.5px] text-slate-700 font-medium",children:n.label}),e.jsx("div",{className:"h-8 rounded-lg bg-slate-50 overflow-hidden",children:e.jsx("div",{className:"h-full rounded-lg flex items-center justify-end pr-3 text-white text-[11.5px] font-semibold",style:{width:`${i}%`,background:`linear-gradient(90deg, rgba(139,92,246,${l}) 0%, rgba(79,70,229,${l}) 100%)`},children:a>0&&a})}),e.jsx("span",{className:"text-[11px] tabular-nums text-slate-500 text-right",children:a})]},n.key)})})]})}function oWt(){const{user:s}=_s(),t=ts(),n=ht({queryKey:["attract-daily-plan",s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:a,error:i}=await U.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 U.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}}function OTe(s=!0){const{intel:t,isLoading:n}=sM(),r=nWt(),a=RTe(),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 bVn(){const{items:s,toggle:t}=oWt(),{data:n=[]}=vte(),{byId:r}=sM(),{logCompleted:a}=rWt();OTe();const i=s.filter(u=>u.completed).length,l=s.length?Math.round(i/s.length*100):0,o=Date.now(),c=n.filter(u=>u.status==="open"||u.status==="snoozed"&&u.snoozed_until&&+new Date(u.snoozed_until)<=o).sort((u,h)=>h.rank_score-u.rank_score).slice(0,3),d=u=>{var m;const h=(m=r.get(u))==null?void 0:m.agent;return h?[h.first_name,h.last_name].filter(Boolean).join(" "):"this relationship"};return e.jsxs(_e,{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:"Today's Attraction Plan"}),e.jsx("div",{className:"text-[18px] font-semibold text-slate-900 mt-0.5",children:"Small daily reps compound."})]}),e.jsxs("div",{className:"text-right",children:[e.jsxs("div",{className:"text-2xl font-semibold tabular-nums text-slate-900",children:[i,e.jsxs("span",{className:"text-slate-400 text-base",children:["/",s.length]})]}),e.jsx("div",{className:"text-[11px] text-slate-500 uppercase tracking-wider",children:"complete"})]})]}),e.jsx("div",{className:"h-1.5 rounded-full bg-slate-100 mb-4 overflow-hidden",children:e.jsx("div",{className:"h-full rounded-full bg-gradient-to-r from-violet-500 to-indigo-500 transition-all",style:{width:`${l}%`}})}),e.jsx("ul",{className:"space-y-1.5",children:s.map(u=>e.jsxs("li",{onClick:()=>t.mutate(u),className:"group flex items-center gap-3 px-3 py-2.5 rounded-xl hover:bg-slate-50 cursor-pointer transition-colors",children:[e.jsx(ui,{checked:u.completed,className:"border-slate-300 data-[state=checked]:bg-violet-600 data-[state=checked]:border-violet-600"}),e.jsx("span",{className:`flex-1 text-[13.5px] ${u.completed?"line-through text-slate-400":"text-slate-800"}`,children:u.label}),e.jsxs("span",{className:"text-[11px] tabular-nums text-slate-400",children:[u.progress,"/",u.target]}),u.completed&&e.jsx(Fr,{className:"h-4 w-4 text-emerald-500"})]},u.id))}),e.jsxs("div",{className:"mt-5 pt-5 border-t border-slate-100",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-wider font-semibold text-slate-500 mb-2.5",children:"Who to reach today"}),c.length?e.jsx("ul",{className:"space-y-2",children:c.map(u=>e.jsx("li",{className:"rounded-xl bg-slate-50 px-3 py-2.5",children:e.jsxs("div",{className:"flex items-start justify-between gap-2 flex-wrap",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx(Wn,{to:`/attract/agents/${u.agent_id}`,className:"text-[13.5px] font-medium text-slate-900 hover:text-violet-700",children:d(u.agent_id)}),e.jsx("div",{className:"text-[12px] text-slate-600 mt-0.5",children:u.title}),e.jsx("div",{className:"text-[11.5px] text-slate-500 mt-0.5",children:(u.reasons??[]).slice(0,2).join(" · ")})]}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx($e,{variant:"outline",className:Tt("rounded-full text-[10.5px] capitalize",u.priority==="urgent"&&"bg-rose-50 text-rose-700 border-rose-200"),children:u.priority}),e.jsx($,{size:"sm",variant:"ghost",className:"rounded-full h-7 px-2 text-[11.5px]",onClick:()=>a.mutate({rec:u}),disabled:a.isPending,children:"Done"})]})]})},u.id))}):e.jsx("div",{className:"text-[13px] text-slate-500",children:"No recommendations right now — Attract only surfaces conversations backed by a real signal."})]}),e.jsxs("div",{className:"mt-4 flex justify-end gap-2",children:[e.jsx($,{variant:"ghost",size:"sm",className:"text-violet-700 hover:text-violet-900",asChild:!0,children:e.jsxs(Wn,{to:"/attract/relationships",children:["All relationships ",e.jsx(ni,{className:"h-3.5 w-3.5 ml-1.5"})]})}),e.jsx($,{variant:"ghost",size:"sm",className:"text-violet-700 hover:text-violet-900",asChild:!0,children:e.jsx(Wn,{to:"/attract/plan",children:"View full plan"})})]})]})}function tQe(s=12){const{user:t}=_s(),n=ht({queryKey:["attract-activities",t==null?void 0:t.id,s],enabled:!!t,queryFn:async()=>{const{data:r,error:a}=await U.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 _Vn={agent_joined:dn,resource_shared:vd,presentation:by,conversation:Mz,social_engagement:fo,new_agent:il,content_posted:Eh,follow_up:Jh};function wVn(){const{activities:s}=tQe(8);return e.jsxs(_e,{className:"p-6 rounded-2xl border-slate-200/70 bg-white shadow-sm",children:[e.jsxs("div",{className:"mb-4",children:[e.jsx("div",{className:"text-[11.5px] uppercase tracking-wider font-medium text-violet-600",children:"Recent Activity"}),e.jsx("div",{className:"text-[18px] font-semibold text-slate-900 mt-0.5",children:"Momentum from the past few days"})]}),e.jsxs("ol",{className:"relative space-y-4",children:[s.map(t=>{const n=_Vn[t.activity_type]??dn;return e.jsxs("li",{className:"flex items-start gap-3",children:[e.jsx("div",{className:"h-8 w-8 rounded-full bg-violet-50 grid place-items-center flex-shrink-0 mt-0.5",children:e.jsx(n,{className:"h-4 w-4 text-violet-600"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"text-[13.5px] font-medium text-slate-900 truncate",children:t.title}),t.description&&e.jsx("div",{className:"text-[12px] text-slate-500 truncate",children:t.description}),e.jsxs("div",{className:"text-[11px] text-slate-400 mt-0.5",children:[fc(new Date(t.created_at),{addSuffix:!0}),t.pillar&&e.jsxs(e.Fragment,{children:[" · ",e.jsx("span",{className:"capitalize",children:t.pillar})]})]})]})]},t.id)}),s.length===0&&e.jsx("li",{className:"text-sm text-slate-500 text-center py-6",children:"No activity yet — start with one small touch today."})]})]})}function FTe(s){const{user:t}=_s();return ht({queryKey:["attract-events",t==null?void 0:t.id,s],enabled:!!t,queryFn:async()=>{let n=U.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 sQe(s){return ht({queryKey:["attract-event",s],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await U.from("attract_events").select("*").eq("id",s).single();if(n)throw n;return t}})}function lWt(s){return ht({queryKey:["attract-event-attendees",s],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await U.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 jVn(s){return ht({queryKey:["attract-event-invitations",s],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await U.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 NVn(s){return ht({queryKey:["attract-event-notes",s],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await U.from("attract_event_notes").select("*").eq("event_id",s).order("created_at",{ascending:!1});if(n)throw n;return t??[]}})}function cWt(){return ht({queryKey:["attract-event-templates"],queryFn:async()=>{const{data:s,error:t}=await U.from("attract_event_templates").select("*").order("title");if(t)throw t;return s??[]}})}function dWt(){const{user:s}=_s(),t=ts();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 U.from("attract_events").insert(r).select().single();if(i)throw i;return a},onSuccess:()=>t.invalidateQueries({queryKey:["attract-events"]})})}function uWt(){const s=ts();return yt({mutationFn:async({id:t,patch:n})=>{const{data:r,error:a}=await U.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 kVn(){const s=ts();return yt({mutationFn:async t=>{const{error:n}=await U.from("attract_events").delete().eq("id",t);if(n)throw n},onSuccess:()=>s.invalidateQueries({queryKey:["attract-events"]})})}function hWt(){const{user:s}=_s(),t=ts();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 U.from("attract_event_attendees").update(r).eq("id",n.id).select().single():await U.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 SVn(){const{user:s}=_s(),t=ts();return yt({mutationFn:async n=>{if(!s)throw new Error("Not authenticated");const{data:r,error:a}=await U.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 CVn(){const{user:s}=_s(),t=ts();return yt({mutationFn:async n=>{if(!s)throw new Error("Not authenticated");const{data:r,error:a}=await U.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 AVn(){const{user:s}=_s(),t=ts();return yt({mutationFn:async n=>{if(!s)throw new Error("Not authenticated");const{data:r,error:a}=await U.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:x,error:g}=await U.from("attract_events").insert({...p,title:r.title+" (Copy)",status:"draft"}).select().single();if(g)throw g;return x},onSuccess:()=>t.invalidateQueries({queryKey:["attract-events"]})})}function zTe(s){return`${window.location.origin}/attract-event/${s}`}function EVn(s,t){return`${window.location.origin}/attract-event-checkin/${s}?a=${encodeURIComponent(t)}`}function mWt(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 pWt(){const{data:s=[]}=FTe(),t=s.slice(0,3);return e.jsxs(_e,{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($,{variant:"outline",size:"sm",className:"rounded-full gap-1",children:[e.jsx(sn,{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:Hs(r,"MMM")}),e.jsx("div",{className:"text-xl font-semibold leading-tight",children:Hs(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:Hs(r,"p")}),"·",n.event_type==="virtual"?e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Xr,{className:"h-3 w-3"})," Virtual"]}):e.jsxs("span",{className:"flex items-center gap-1 truncate",children:[e.jsx(ai,{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(LN,{className:"h-6 w-6 mx-auto text-slate-300 mb-2"}),e.jsx("div",{className:"text-sm",children:"No upcoming events yet."})]})]})]})}function fWt(){const{user:s}=_s(),t=ht({queryKey:["attract-resources",s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:r,error:a}=await U.from("attract_resources").select("*").order("created_at",{ascending:!1});if(a)throw a;return r??[]}}),n=ht({queryKey:["attract-resource-shares",s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:r,error:a}=await U.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}}function TVn(){const{shares:s}=fWt(),t={resources:s.length,emails:s.filter(r=>r.channel==="email").length,opens:s.filter(r=>r.opened_at).length,clicks:s.filter(r=>r.clicked_at).length},n=[{label:"Resources Shared",value:t.resources,icon:vd,tone:"text-violet-600 bg-violet-50"},{label:"Emails Sent",value:t.emails,icon:Br,tone:"text-teal-600 bg-teal-50"},{label:"Agent Opens",value:t.opens,icon:Cz,tone:"text-emerald-600 bg-emerald-50"},{label:"Clicks",value:t.clicks,icon:uu,tone:"text-orange-600 bg-orange-50"}];return e.jsxs(_e,{className:"p-6 rounded-2xl border-slate-200/70 bg-white shadow-sm",children:[e.jsxs("div",{className:"mb-4",children:[e.jsx("div",{className:"text-[11.5px] uppercase tracking-wider font-medium text-violet-600",children:"Value Shared This Week"}),e.jsx("div",{className:"text-[18px] font-semibold text-slate-900 mt-0.5",children:"Small gifts, measured."})]}),e.jsx("div",{className:"grid grid-cols-2 gap-3",children:n.map(r=>e.jsxs("div",{className:"rounded-xl border border-slate-100 p-3.5",children:[e.jsx("div",{className:`h-8 w-8 rounded-lg grid place-items-center ${r.tone}`,children:e.jsx(r.icon,{className:"h-4 w-4"})}),e.jsx("div",{className:"text-[22px] font-semibold tabular-nums text-slate-900 mt-2 leading-none",children:r.value}),e.jsx("div",{className:"text-[11.5px] text-slate-500 mt-1",children:r.label})]},r.label))})]})}function MVn(){const{agents:s}=M0(),t=s.filter(r=>r.stage==="joined").sort((r,a)=>(a.joined_at??"").localeCompare(r.joined_at??"")),n=t.reduce((r,a)=>r+(Number(a.est_revenue_share)||0),0);return e.jsxs(_e,{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:"Agents Joined"}),e.jsxs("div",{className:"text-[18px] font-semibold text-slate-900 mt-0.5",children:["Est. annual rev share ",e.jsx("span",{className:"text-violet-700",children:Au(n)})]})]}),e.jsx(dn,{className:"h-5 w-5 text-violet-500"})]}),e.jsxs("ul",{className:"space-y-2.5",children:[t.map(r=>{var a;return e.jsxs("li",{className:"flex items-center gap-3 p-2.5 rounded-xl hover:bg-slate-50",children:[e.jsxs("div",{className:"h-9 w-9 rounded-full bg-gradient-to-br from-violet-500 to-indigo-600 text-white grid place-items-center text-[13px] font-semibold flex-shrink-0",children:[r.first_name[0],((a=r.last_name)==null?void 0:a[0])??""]}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"text-[13.5px] font-semibold text-slate-900 truncate",children:[r.first_name," ",r.last_name]}),e.jsxs("div",{className:"text-[11.5px] text-slate-500 truncate",children:[r.brokerage," · ",r.city,", ",r.state]})]}),e.jsxs("div",{className:"text-right",children:[e.jsx("div",{className:"text-[13px] font-semibold text-emerald-600 tabular-nums",children:r.est_revenue_share?Au(Number(r.est_revenue_share)):"—"}),e.jsx("div",{className:"text-[10.5px] text-slate-400",children:r.joined_at?fc(new Date(r.joined_at),{addSuffix:!0}):""})]})]},r.id)}),t.length===0&&e.jsx("li",{className:"text-sm text-slate-500 text-center py-6",children:"No joined agents yet."})]})]})}function NF(){const{user:s}=_s(),t=ts(),n=ht({queryKey:["attract-followups",s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:a,error:i}=await U.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 U.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 LVn(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]}const Gbt={produce:{label:"Your primary pillar is Produce — log one recent transaction today.",cta:"Open Transaction Tracker",to:"/attract/produce/transaction-tracker"},influence:{label:"Your primary pillar is Influence — create one authority post today.",cta:"Open Content Studio",to:"/attract/influence/content-studio"},provide:{label:"Your primary pillar is Provide — share one resource with an agent today.",cta:"Open Resources",to:"/attract/resources"},connect:{label:"Your primary pillar is Connect — schedule one 1:1 this week.",cta:"Open Follow-Up Center",to:"/attract/follow-up"},balanced:{label:"Balanced plan — pick one pillar for today and go deep.",cta:"View 90-Day Plan",to:"/attract/plan"}};function PVn(){const{user:s}=_s(),t=Vn(),{agents:n}=M0(),{followUps:r}=NF(),{settings:a}=MV();j.useState(!1);const i=j.useMemo(()=>{const d=ep(new Date),u=n.filter(y=>!["joined","not_a_fit","not_right_now"].includes(y.stage)).length,h=n.filter(y=>new Date(y.created_at)>Bd(d,-30)).length,m=r.filter(y=>!y.completed_at&&y.due_at&&hu(new Date(y.due_at),d)).length,p=r.filter(y=>!y.completed_at&&y.due_at&&aw(new Date(y.due_at),d)).length,g=n.filter(y=>y.stage==="joined").reduce((y,b)=>y+(Number(b.est_revenue_share)||0),0);return{inPipeline:u,newRels:h,dueToday:m,overdue:p,revShare:g}},[n,r]),l=(a==null?void 0:a.primary_pillar)||(a==null?void 0:a.attraction_style)||"balanced",o=Gbt[l]??Gbt.balanced,c=a==null?void 0:a.ninety_day_plan;return e.jsxs("div",{children:[e.jsxs("div",{className:"flex flex-col md:flex-row md:items-center md:justify-between gap-4 mb-8",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-violet-600 font-semibold mb-2",children:"LevelUp Attract"}),e.jsxs("h1",{className:"text-3xl md:text-[34px] font-semibold tracking-tight text-slate-900",children:["Good to see you, ",LVn(s),"."]}),e.jsxs("p",{className:"text-slate-600 mt-1.5",children:["Here's your attraction overview for today · ",Hs(new Date,"EEEE, MMM d")]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(vs,{defaultValue:"week",children:[e.jsx(gs,{className:"w-[150px] rounded-full bg-white",children:e.jsx(bs,{})}),e.jsxs(ys,{children:[e.jsx(Ye,{value:"week",children:"This Week"}),e.jsx(Ye,{value:"month",children:"This Month"}),e.jsx(Ye,{value:"90",children:"Last 90 Days"})]})]}),e.jsx($,{variant:"outline",size:"icon",className:"rounded-full",children:e.jsx(Dx,{className:"h-4 w-4"})}),e.jsxs(Hd,{children:[e.jsx(Gd,{asChild:!0,children:e.jsxs($,{className:"rounded-full bg-gradient-to-r from-violet-600 to-indigo-600 hover:from-violet-700 hover:to-indigo-700 gap-1.5 shadow-sm",children:[e.jsx(sn,{className:"h-4 w-4"})," Add New ",e.jsx(_o,{className:"h-3.5 w-3.5 opacity-70"})]})}),e.jsxs(Md,{align:"end",className:"w-64",children:[e.jsx(iO,{children:"Quick add"}),e.jsx(S0,{}),e.jsxs(Na,{onClick:()=>t("/attract/pipeline?new=1"),children:[e.jsx(il,{className:"h-4 w-4 mr-2"})," Add Agent to Pipeline"]}),e.jsxs(Na,{onClick:()=>t("/attract/produce/transaction-tracker"),children:[e.jsx(Qa,{className:"h-4 w-4 mr-2"})," Log a Transaction"]}),e.jsxs(Na,{onClick:()=>t("/attract/influence/content-studio"),children:[e.jsx(wm,{className:"h-4 w-4 mr-2"})," Create Authority Content"]}),e.jsxs(Na,{onClick:()=>t("/attract/follow-up"),children:[e.jsx(Jh,{className:"h-4 w-4 mr-2"})," Add Follow-Up"]}),e.jsxs(Na,{onClick:()=>t("/attract/events/new"),children:[e.jsx(gg,{className:"h-4 w-4 mr-2"})," Plan an Event"]}),e.jsxs(Na,{onClick:()=>t("/attract/resources"),children:[e.jsx(g1,{className:"h-4 w-4 mr-2"})," Add Resource"]})]})]})]})]}),e.jsx(_e,{className:"p-4 rounded-2xl mb-6 bg-gradient-to-r from-violet-50 to-indigo-50 border-violet-100",children:e.jsxs("div",{className:"flex items-center gap-3 flex-wrap",children:[e.jsx("div",{className:"h-10 w-10 rounded-xl bg-white grid place-items-center text-violet-700 shadow-sm",children:e.jsx(Mu,{className:"h-5 w-5"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"text-[10.5px] uppercase tracking-widest text-violet-700 font-semibold",children:"Today's move"}),e.jsx("div",{className:"text-[14px] font-semibold text-slate-900",children:o.label}),c&&e.jsxs("div",{className:"text-[12px] text-slate-600 mt-0.5",children:["Weekly goal: ",c.weekly_targets.new_relationships," new relationships · ",c.weekly_targets.content_pieces," content pieces"]})]}),e.jsx($,{size:"sm",className:"rounded-full bg-gradient-to-r from-violet-600 to-indigo-600",onClick:()=>t(o.to),children:o.cta})]})}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-3 xl:grid-cols-5 gap-4 mb-6",children:[e.jsx(GG,{label:"Agents in Pipeline",value:i.inPipeline,delta:"+3 this week",icon:t1,tone:"violet"}),e.jsx(GG,{label:"New Relationships",value:i.newRels,delta:"+2 this week",icon:Il,tone:"teal"}),e.jsx(GG,{label:"Follow-Ups Due Today",value:i.dueToday,icon:bK,tone:"orange"}),e.jsx(GG,{label:"Overdue Follow-Ups",value:i.overdue,icon:mc,tone:"rose"}),e.jsx(GG,{label:"Est. Revenue Share",value:Au(i.revShare,!0),delta:"annualized",icon:qd,tone:"green"})]}),e.jsxs("div",{className:"grid grid-cols-1 xl:grid-cols-3 gap-6",children:[e.jsxs("div",{className:"xl:col-span-2 space-y-6",children:[e.jsx(iWt,{}),e.jsx(vVn,{}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-6",children:[e.jsx(wVn,{}),e.jsx(pWt,{})]})]}),e.jsxs("div",{className:"space-y-6",children:[e.jsx(bVn,{}),e.jsx(TVn,{}),e.jsx(MVn,{})]})]}),e.jsx("div",{className:"mt-8 rounded-2xl overflow-hidden bg-gradient-to-r from-violet-600 via-indigo-600 to-violet-700 p-6 md:p-7 text-white shadow-lg",children:e.jsxs("div",{className:"flex items-center justify-between gap-4 flex-wrap",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] opacity-80 mb-1",children:"Your 90-day promise"}),e.jsx("div",{className:"text-lg md:text-xl font-semibold",children:(c==null?void 0:c.outcome)??"Show up for agents the way you'd want someone to show up for you."}),e.jsx("div",{className:"text-white/80 mt-1 text-[13.5px]",children:"Small daily reps compound. Keep the rhythm."})]}),e.jsx($,{asChild:!0,variant:"secondary",className:"rounded-full bg-white text-violet-700 hover:bg-white/90",children:e.jsx(Wn,{to:"/attract/plan",children:"View 90-Day Plan"})})]})})]})}const Wbt={call:{icon:ya,label:"Call"},text:{icon:Ji,label:"Text"},email:{icon:nn,label:"Email"},dm:{icon:Br,label:"DM"},resource_share:{icon:g1,label:"Share a kit"},event_invitation:{icon:gg,label:"Invite to event"},personal_check_in:{icon:fR,label:"Personal check-in"}},Kbt={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 IVn(s){var t;return((t=sWt.find(n=>n.key===s))==null?void 0:t.blurb)??""}function xWt(s){var t;return((t=sWt.find(n=>n.key===s))==null?void 0:t.label)??s.replace(/_/g," ")}function Z4e({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}=rWt(),[p,x]=j.useState(!1),[g,y]=j.useState(s.draft_message??""),b=c.isPending||d.isPending||u.isPending||h.isPending||m.isPending,v=Wbt[s.channel]??Wbt.personal_check_in,N=s.suggested_due_at?new Date(s.suggested_due_at):null,C=N?N{c.mutate({id:s.id,patch:{draft_message:g}},{onSuccess:()=>{x(!1),ae.success("Opening message updated")}})},T=async()=>{try{await navigator.clipboard.writeText(s.draft_message??""),ae.success("Opening message copied — send it yourself from your phone or inbox")}catch{ae.error("Could not copy — select the text manually")}};return e.jsx(_e,{className:Tt("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(v.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($e,{variant:"outline",className:Tt("rounded-full text-[10.5px] uppercase tracking-wider font-semibold ring-1 border-transparent",Kbt[s.priority]??Kbt.medium),children:s.priority}),e.jsx("span",{className:"text-[11px] text-violet-700 font-medium",children:xWt(s.signal_group)}),s.is_demo&&e.jsx($e,{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(Wn,{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(Ja,{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:["· ",v.label]}),N&&e.jsxs("span",{className:Tt("inline-flex items-center gap-1",C?"text-rose-600 font-medium":""),children:["· ",e.jsx(Hr,{className:"h-3 w-3"})," ",C?"Due now":`Do by ${N.toLocaleDateString()}`]})]})]}),e.jsxs(Hd,{children:[e.jsx(Gd,{asChild:!0,children:e.jsx($,{variant:"ghost",size:"icon",className:"rounded-full","aria-label":"More recommendation actions",children:e.jsx(cy,{className:"h-4 w-4"})})}),e.jsxs(Md,{align:"end",className:"w-56",children:[e.jsx(iO,{children:"Recommendation"}),e.jsx(S0,{}),e.jsxs(Na,{onClick:()=>x(P=>!P),children:[e.jsx(Ya,{className:"h-4 w-4 mr-2"})," Edit opening message"]}),e.jsxs(Na,{onClick:T,children:[e.jsx(Ca,{className:"h-4 w-4 mr-2"})," Copy message"]}),e.jsx(S0,{}),e.jsxs(Na,{onClick:()=>u.mutate({id:s.id,days:3}),children:[e.jsx(Hr,{className:"h-4 w-4 mr-2"})," Snooze 3 days"]}),e.jsxs(Na,{onClick:()=>u.mutate({id:s.id,days:7}),children:[e.jsx(Hr,{className:"h-4 w-4 mr-2"})," Snooze 1 week"]}),e.jsxs(Na,{className:"text-rose-600",onClick:()=>d.mutate(s.id),children:[e.jsx(pr,{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(r5,{className:"h-3 w-3"})," Why this, right now"]}),e.jsx("ul",{className:"space-y-1",children:s.reasons.map((P,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:P})]},M))}),e.jsx("div",{className:"text-[11px] text-slate-400 mt-2",children:IVn(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(Is,{value:g,onChange:P=>y(P.target.value),rows:4,className:"text-[13.5px]","aria-label":"Opening message"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx($,{size:"sm",className:"rounded-full btn-primary text-white",onClick:A,disabled:b,children:"Save message"}),e.jsx($,{size:"sm",variant:"ghost",className:"rounded-full",onClick:()=>{y(s.draft_message??""),x(!1)},children:"Cancel"})]})]}):e.jsxs("button",{onClick:()=>x(!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($,{size:"sm",className:"rounded-full btn-primary text-white",disabled:b,onClick:()=>m.mutate({rec:s}),children:[e.jsx(oa,{className:"h-3.5 w-3.5 mr-1.5"})," I did this"]}),e.jsxs($,{size:"sm",variant:"outline",className:"rounded-full",disabled:b,onClick:()=>h.mutate(s),children:[e.jsx(gg,{className:"h-3.5 w-3.5 mr-1.5"})," ",s.follow_up_id?"Follow-up created":"Create follow-up"]}),e.jsxs($,{size:"sm",variant:"ghost",className:"rounded-full",onClick:T,children:[e.jsx(Ca,{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 DVn({label:s="Nothing needs attention right now."}){return e.jsxs(_e,{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(oa,{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 YT=[{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"}],BTe={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"},gWt=new Map;for(const s of[...YT,BTe])for(const t of s.legacy)gWt.set(t,s);function SB(s){return s?gWt.get(s)??YT[0]:YT[0]}function yWt(s){return SB(s).label}function nQe(s){var n;return((n=[...YT,BTe].find(r=>r.key===s))==null?void 0:n.canonical)??"new_connection"}const lRe={first_name:"",last_name:"",brokerage:"",email:"",phone:"",city:"",source:"",notes:""};function vWt({open:s,onOpenChange:t,defaultStageKey:n,onAdded:r}){const{upsertAgent:a,agents:i}=M0(),[l,o]=j.useState({...lRe}),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:nQe(n??"new_relationship"),temperature:"warm"},{onSuccess:h=>{o({...lRe}),t(!1),r==null||r(h==null?void 0:h.id)}})};return e.jsx(Os,{open:s,onOpenChange:h=>{t(h),h||o({...lRe})},children:e.jsxs(Rs,{className:"max-w-lg",children:[e.jsxs(Us,{children:[e.jsx(zs,{children:"Add a relationship"}),e.jsx(Sr,{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(se,{children:"First name *"}),e.jsx(be,{value:l.first_name,onChange:c("first_name"),autoFocus:!0})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Last name"}),e.jsx(be,{value:l.last_name,onChange:c("last_name")})]}),e.jsxs("div",{className:"col-span-2",children:[e.jsx(se,{children:"Brokerage"}),e.jsx(be,{value:l.brokerage,onChange:c("brokerage"),placeholder:"Where they hang their license"})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Email"}),e.jsx(be,{type:"email",value:l.email,onChange:c("email")})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Phone"}),e.jsx(be,{value:l.phone,onChange:c("phone")})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Market"}),e.jsx(be,{value:l.city,onChange:c("city"),placeholder:"City or area"})]}),e.jsxs("div",{children:[e.jsx(se,{children:"How you know each other"}),e.jsx(be,{value:l.source,onChange:c("source"),placeholder:"Co-op deal, event, referral…"})]}),e.jsxs("div",{className:"col-span-2",children:[e.jsx(se,{children:"Note (optional)"}),e.jsx(Is,{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(kr,{children:[e.jsx($,{variant:"ghost",onClick:()=>t(!1),children:"Cancel"}),e.jsx($,{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 RVn(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 OVn(){const s=new Date().getHours();return s<12?"Good morning":s<18?"Good afternoon":"Good evening"}const Ybt=20;function FVn(){const{user:s}=_s(),{intel:t,byId:n,isLoading:r}=sM(),{data:a=[],isLoading:i}=vte(),l=RTe();OTe();const{items:o,toggle:c}=oWt(),{agents:d,isLoading:u}=M0(),{followUps:h}=NF(),{activities:m}=tQe(200),[p,x]=j.useState(!1),g=r||i||u,y=j.useMemo(()=>{const C=Date.now();return a.filter(A=>A.status==="open"||A.status==="snoozed"&&A.snoozed_until&&+new Date(A.snoozed_until)<=C).sort((A,T)=>T.rank_score-A.rank_score).slice(0,5)},[a]),b=j.useMemo(()=>{const C=new Date;C.setHours(0,0,0,0),C.setDate(C.getDate()-(C.getDay()+6)%7);const A=m.filter(M=>new Date(M.created_at)>=C).length,T=h.filter(M=>M.completed_at&&new Date(M.completed_at)>=C).length,P=A+T;return{moves:P,pct:Math.min(100,Math.round(P/Ybt*100))}},[m,h]),v=C=>{var T;const A=(T=n.get(C))==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(vWt,{open:p,onOpenChange:x}),e.jsxs("div",{className:"mb-7",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-violet-600 font-semibold mb-2",children:"LevelUp Attract"}),e.jsxs("h1",{className:"text-[28px] md:text-[34px] font-semibold tracking-tight text-slate-900 leading-tight",children:[OVn(),", ",RVn(s),". Here are your best moves today."]}),e.jsx("p",{className:"text-slate-600 mt-2 text-[14.5px]",children:"Build relationships. Provide value. Let the opportunity develop naturally."}),e.jsxs("div",{className:"mt-5 rounded-2xl bg-white border border-slate-200/70 px-4 py-3.5 shadow-sm",children:[e.jsxs("div",{className:"flex items-baseline justify-between gap-3",children:[e.jsxs("div",{className:"text-[13.5px] text-slate-700",children:[e.jsxs("span",{className:"font-semibold text-slate-900 tabular-nums",children:[b.moves," of ",Ybt]})," meaningful moves completed this week"]}),e.jsx("span",{className:"text-[11px] uppercase tracking-wider text-slate-400",children:"This week"})]}),e.jsx("div",{className:"h-1.5 rounded-full bg-slate-100 mt-2.5 overflow-hidden",children:e.jsx("div",{className:"h-full rounded-full bg-gradient-to-r from-violet-500 to-indigo-500 transition-all",style:{width:`${b.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"}),!g&&e.jsxs($,{variant:"ghost",size:"sm",className:"rounded-full text-slate-500 h-8",onClick:()=>l.mutate(t),disabled:l.isPending,children:[e.jsx(Wi,{className:Tt("h-3.5 w-3.5 mr-1.5",l.isPending&&"animate-spin")})," Refresh"]})]}),g?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(C=>e.jsx(on,{className:"h-40 w-full rounded-2xl"},C))]}):y.length?e.jsx("div",{className:"space-y-3",children:y.map(C=>{var A;return e.jsx(Z4e,{rec:C,agentName:v(C.agent_id),agentStage:yWt((A=n.get(C.agent_id))==null?void 0:A.agent.stage)},C.id)})}):N?e.jsxs(_e,{className:"rounded-2xl border-dashed border-slate-300 bg-white/60 p-8 text-center",children:[e.jsx(dn,{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($,{className:"rounded-full btn-primary text-white",asChild:!0,children:e.jsx(Wn,{to:"/attract/relationships?view=attention",children:"See who’s gone quiet"})}),e.jsx($,{variant:"outline",className:"rounded-full",asChild:!0,children:e.jsx(Wn,{to:"/attract/share",children:"Share something useful"})})]})]}):e.jsxs(_e,{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(il,{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($,{className:"rounded-full btn-primary text-white mt-4",onClick:()=>x(!0),children:[e.jsx(il,{className:"h-4 w-4 mr-1.5"})," Add your first relationship"]})]}),!!o.length&&e.jsxs(_e,{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(C=>e.jsxs("li",{onClick:()=>c.mutate(C),className:"flex items-center gap-3 px-2 py-2 rounded-xl hover:bg-slate-50 cursor-pointer transition-colors",children:[e.jsx(ui,{checked:C.completed,className:"border-slate-300 data-[state=checked]:bg-violet-600 data-[state=checked]:border-violet-600"}),e.jsx("span",{className:Tt("flex-1 text-[13.5px]",C.completed?"line-through text-slate-400":"text-slate-800"),children:C.label}),e.jsxs("span",{className:"text-[11px] tabular-nums text-slate-400",children:[C.progress,"/",C.target]})]},C.id))})]}),e.jsxs("div",{className:"mt-6 grid grid-cols-1 sm:grid-cols-3 gap-3",children:[e.jsx(cRe,{icon:il,label:"Add a relationship",onClick:()=>x(!0)}),e.jsx(cRe,{icon:g1,label:"Share something useful",to:"/attract/share"}),e.jsx(cRe,{icon:wm,label:"Create content",to:"/attract/create"})]}),e.jsxs("div",{className:"mt-6 space-y-3",children:[e.jsxs(uv,{children:[e.jsxs(hv,{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(LN,{className:"h-4 w-4 text-violet-500"})," Upcoming conversations & events"]}),e.jsx(_o,{className:"h-4 w-4 text-slate-400"})]}),e.jsx(mv,{className:"pt-3",children:e.jsx(pWt,{})})]}),e.jsxs(uv,{children:[e.jsxs(hv,{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(dn,{className:"h-4 w-4 text-violet-500"})," View coaching insights"]}),e.jsx(_o,{className:"h-4 w-4 text-slate-400"})]}),e.jsx(mv,{className:"pt-3",children:e.jsx(iWt,{})})]})]}),e.jsx("div",{className:"mt-6 flex justify-center",children:e.jsx($,{variant:"ghost",className:"rounded-full text-violet-700",asChild:!0,children:e.jsxs(Wn,{to:"/attract/relationships?view=attention",children:["See everyone who needs attention ",e.jsx(ni,{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 cRe({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(Wn,{to:n,children:a}):e.jsx("button",{className:"text-left w-full",onClick:r,children:a})}function nm({eyebrow:s,title:t,description:n,actions:r,className:a}){return e.jsxs("div",{className:Tt("flex flex-col md:flex-row md:items-end md:justify-between gap-4 mb-8",a),children:[e.jsxs("div",{children:[s&&e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-violet-600 font-semibold mb-2",children:s}),e.jsx("h1",{className:"text-3xl md:text-[34px] font-semibold tracking-tight text-slate-900",children:t}),n&&e.jsx("p",{className:"text-slate-600 mt-2 max-w-2xl",children:n})]}),r&&e.jsx("div",{className:"flex items-center gap-2 flex-wrap",children:r})]})}function kF(){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 zVn(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 L4=(s,t)=>{for(const n of t)if(s[n])return s[n];return""};function BVn({open:s,onOpenChange:t}){const{user:n}=_s(),r=ts(),[a,i]=j.useState([]),[l,o]=j.useState(""),[c,d]=j.useState(!1),u=()=>{i([]),o("")},h=async x=>{if(!x)return;const g=await x.text(),y=zVn(g);if(!y.length){ae.error("That file looks empty.");return}o(x.name),i(y)},m=a.map(x=>{const g=L4(x,["name","full name","full_name"]),y=L4(x,["first name","first_name","firstname"])||g.split(" ")[0]||"",b=L4(x,["last name","last_name","lastname"])||g.split(" ").slice(1).join(" ")||null;return{first_name:y,last_name:b,email:L4(x,["email","email address","e-mail"])||null,phone:L4(x,["phone","phone number","mobile","cell"])||null,brokerage:L4(x,["brokerage","company","office"])||null,city:L4(x,["city"])||null,state:L4(x,["state","province"])||null,notes:L4(x,["notes","note"])||null,source:"csv_import",stage:"prospect"}}).filter(x=>x.first_name),p=async()=>{if(!(!n||!m.length)){d(!0);try{const x=m.map(y=>({...y,user_id:n.id}));let g=0;for(let y=0;y{x||u(),t(x)},children:e.jsxs(Rs,{className:"sm:max-w-lg",children:[e.jsxs(Us,{children:[e.jsx(zs,{children:"Import relationships"}),e.jsx(Sr,{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(be,{type:"file",accept:".csv,text/csv",onChange:x=>{var g;return h((g=x.target.files)==null?void 0:g[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(PN,{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(x=>`${x.first_name} ${x.last_name??""}`.trim()).join(", "),m.length>3?"…":""]})]})]}),e.jsxs(kr,{children:[e.jsx($,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsxs($,{onClick:p,disabled:c||!m.length,children:[e.jsx(si,{className:"h-4 w-4 mr-1.5"}),c?"Importing…":`Import ${m.length||""}`.trim()]})]})]})})}const $Vn=["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"],UVn={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"},e0=s=>typeof s=="string"&&s.trim()===""?null:s,J7=s=>{const t=s.trim();return t?/^https?:\/\//i.test(t)?t:`https://${t}`:null},qVn=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},KG=s=>(s??"").replace(/[^\d]/g,""),VVn=s=>/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(s.trim()),zae=s=>s?String(s).slice(0,10):"";function Zbt(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:zae(s.birthday_on),work_anniversary_on:zae(s.work_anniversary_on),license_anniversary_on:zae(s.license_anniversary_on),next_follow_up_at:zae(s.next_follow_up_at)}}function e9({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 Hm({label:s,value:t,onChange:n,className:r,...a}){return e.jsxs("div",{className:r,children:[e.jsx(se,{className:"text-[12px] text-slate-600",children:s}),e.jsx(be,{className:"mt-1",value:t,onChange:i=>n(i.target.value),...a})]})}function rQe({agent:s,open:t,onOpenChange:n,onDeleted:r}){const{agents:a,saveAgentDetails:i,archiveAgent:l,deleteAgent:o}=M0(),[c,d]=j.useState({}),[u,h]=j.useState(!1),[m,p]=j.useState(!1),[x,g]=j.useState(!1);j.useEffect(()=>{s&&t&&(d(Zbt(s)),g(!1))},[s==null?void 0:s.id,t]);const y=j.useMemo(()=>s?Zbt(s):{},[s]),b=j.useMemo(()=>Object.keys(c).filter(M=>String(c[M]??"")!==String(y[M]??"")),[c,y]),v=b.length>0,N=(M,I)=>d(D=>({...D,[M]:I}));if(!s)return null;const C=M=>{if(!M&&v){h(!0);return}n(M)},A=()=>{var B;const M=(B=c.email)==null?void 0:B.trim().toLowerCase(),I=KG(c.phone),D=`${c.first_name} ${c.last_name}`.trim().toLowerCase();return a.filter(q=>{var W;return q.id===s.id||q.is_archived?!1:!!(M&&((W=q.email)==null?void 0:W.toLowerCase())===M||I.length>=10&&KG(q.phone)===I||D&&`${q.first_name} ${q.last_name??""}`.trim().toLowerCase()===D)})},T=()=>{var q,W,V;if(!((q=c.first_name)!=null&&q.trim())){ae.error("First name is required");return}if((W=c.email)!=null&&W.trim()&&!VVn(c.email)){ae.error("That email address looks incomplete");return}const M=A(),I=M.some(K=>{var Q,J;return((Q=c.email)==null?void 0:Q.trim())&&((J=K.email)==null?void 0:J.toLowerCase())===c.email.trim().toLowerCase()||KG(c.phone).length>=10&&KG(K.phone)===KG(c.phone)});if(M.length&&!x){g(!0),ae.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 D={first_name:c.first_name.trim(),last_name:e0(c.last_name),preferred_name:e0(c.preferred_name),email:(V=c.email)!=null&&V.trim()?c.email.trim().toLowerCase():null,phone:qVn(c.phone??""),website_url:J7(c.website_url??""),instagram_url:J7(c.instagram_url??""),linkedin_url:J7(c.linkedin_url??""),facebook_url:J7(c.facebook_url??""),other_url:J7(c.other_url??""),photo_url:J7(c.photo_url??""),brokerage:e0(c.brokerage),team_name:e0(c.team_name),city:e0(c.city),state:e0(c.state),postal_code:e0(c.postal_code),market_area:e0(c.market_area),source:e0(c.source),relationship_owner:e0(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:e0(c.goals),challenges:e0(c.challenges),interests:e0(c.interests),production_context:e0(c.production_context),notes:e0(c.notes),birthday_on:e0(c.birthday_on),work_anniversary_on:e0(c.work_anniversary_on),license_anniversary_on:e0(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},B={};if(b.forEach(K=>{K in D&&(B[K]=D[K])}),!Object.keys(B).length){n(!1);return}i.mutate({id:s.id,values:B,changedLabels:b.map(K=>UVn[K]??K),previousStage:s.stage},{onSuccess:()=>n(!1)})},P=A();return e.jsxs(e.Fragment,{children:[e.jsx(Ub,{open:t,onOpenChange:C,children:e.jsxs(T1,{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(kw,{className:"space-y-1 text-left",children:[e.jsxs(Sw,{className:"text-white text-lg",children:["Edit ",[s.first_name,s.last_name].filter(Boolean).join(" ")]}),e.jsx(dee,{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:[!!P.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(mc,{className:"h-4 w-4 mt-0.5 shrink-0"}),e.jsxs("span",{children:["Possible duplicate: ",P.slice(0,3).map(M=>`${M.first_name} ${M.last_name??""}`.trim()).join(", "),". You can still save — just double-check first."]})]}),e.jsxs(e9,{title:"Basic info",children:[e.jsx(Hm,{label:"First name *",value:c.first_name,onChange:M=>N("first_name",M)}),e.jsx(Hm,{label:"Last name",value:c.last_name,onChange:M=>N("last_name",M)}),e.jsx(Hm,{label:"Preferred name",value:c.preferred_name,onChange:M=>N("preferred_name",M),placeholder:"What they go by"}),e.jsx(Hm,{label:"Photo / headshot URL",value:c.photo_url,onChange:M=>N("photo_url",M),placeholder:"https://…"})]}),e.jsxs(e9,{title:"Contact & social",children:[e.jsx(Hm,{label:"Email",type:"email",value:c.email,onChange:M=>N("email",M)}),e.jsx(Hm,{label:"Phone",value:c.phone,onChange:M=>N("phone",M)}),e.jsx(Hm,{label:"Website",value:c.website_url,onChange:M=>N("website_url",M)}),e.jsx(Hm,{label:"Instagram",value:c.instagram_url,onChange:M=>N("instagram_url",M)}),e.jsx(Hm,{label:"LinkedIn",value:c.linkedin_url,onChange:M=>N("linkedin_url",M)}),e.jsx(Hm,{label:"Facebook",value:c.facebook_url,onChange:M=>N("facebook_url",M)}),e.jsx(Hm,{label:"Other link",value:c.other_url,onChange:M=>N("other_url",M),className:"sm:col-span-2"})]}),e.jsxs(e9,{title:"Brokerage & market",children:[e.jsx(Hm,{label:"Brokerage",value:c.brokerage,onChange:M=>N("brokerage",M)}),e.jsx(Hm,{label:"Team",value:c.team_name,onChange:M=>N("team_name",M)}),e.jsx(Hm,{label:"City",value:c.city,onChange:M=>N("city",M)}),e.jsx(Hm,{label:"State",value:c.state,onChange:M=>N("state",M)}),e.jsx(Hm,{label:"ZIP / postal code",value:c.postal_code,onChange:M=>N("postal_code",M)}),e.jsx(Hm,{label:"Market / service area",value:c.market_area,onChange:M=>N("market_area",M)})]}),e.jsxs(e9,{title:"Relationship intelligence",hint:"These drive scoring, recommendations, filters and reports.",children:[e.jsxs("div",{children:[e.jsx(se,{className:"text-[12px] text-slate-600",children:"Pipeline stage"}),e.jsxs(vs,{value:c.stage,onValueChange:M=>N("stage",M),children:[e.jsx(gs,{className:"mt-1",children:e.jsx(bs,{})}),e.jsx(ys,{children:$Vn.map(M=>e.jsx(Ye,{value:M,className:"capitalize",children:M.replace(/_/g," ")},M))})]})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-[12px] text-slate-600",children:"Temperature"}),e.jsxs(vs,{value:c.temperature,onValueChange:M=>N("temperature",M),children:[e.jsx(gs,{className:"mt-1",children:e.jsx(bs,{})}),e.jsx(ys,{children:["cold","warm","hot"].map(M=>e.jsx(Ye,{value:M,className:"capitalize",children:M},M))})]})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-[12px] text-slate-600",children:"Primary pillar"}),e.jsxs(vs,{value:c.primary_pillar,onValueChange:M=>N("primary_pillar",M),children:[e.jsx(gs,{className:"mt-1",children:e.jsx(bs,{})}),e.jsxs(ys,{children:[e.jsx(Ye,{value:"none",children:"Not set"}),["produce","influence","provide","connect"].map(M=>e.jsx(Ye,{value:M,className:"capitalize",children:M},M))]})]})]}),e.jsx(Hm,{label:"Source",value:c.source,onChange:M=>N("source",M),placeholder:"Event, referral, social…"}),e.jsx(Hm,{label:"Relationship owner",value:c.relationship_owner,onChange:M=>N("relationship_owner",M),placeholder:"You, or a teammate"}),e.jsx(Hm,{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($e,{variant:"outline",className:"rounded-full text-[11px]",children:M},M))})]}),e.jsxs(e9,{title:"Important dates",hint:"Birthdays and anniversaries feed Milestones & Celebrations automatically — no duplicate entry needed.",children:[e.jsx(Hm,{label:"Birthday",type:"date",value:c.birthday_on,onChange:M=>N("birthday_on",M)}),e.jsx(Hm,{label:"Work anniversary",type:"date",value:c.work_anniversary_on,onChange:M=>N("work_anniversary_on",M)}),e.jsx(Hm,{label:"License anniversary",type:"date",value:c.license_anniversary_on,onChange:M=>N("license_anniversary_on",M)}),e.jsx(Hm,{label:"Next follow-up",type:"date",value:c.next_follow_up_at,onChange:M=>N("next_follow_up_at",M)})]}),e.jsxs(e9,{title:"Notes",children:[e.jsxs("div",{className:"sm:col-span-2",children:[e.jsx(se,{className:"text-[12px] text-slate-600",children:"Goals"}),e.jsx(Is,{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(se,{className:"text-[12px] text-slate-600",children:"Challenges"}),e.jsx(Is,{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(se,{className:"text-[12px] text-slate-600",children:"Interests"}),e.jsx(Is,{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(se,{className:"text-[12px] text-slate-600",children:"Production context"}),e.jsx(Is,{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(se,{className:"text-[12px] text-slate-600",children:"Personal notes"}),e.jsx(Is,{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($,{variant:"outline",size:"sm",className:"rounded-full",onClick:()=>l.mutate({id:s.id,archived:!s.is_archived},{onSuccess:()=>n(!1)}),children:[e.jsx(Am,{className:"h-3.5 w-3.5 mr-1.5"}),s.is_archived?"Restore to pipeline":"Remove from pipeline (archive)"]}),e.jsxs($,{variant:"destructive",size:"sm",className:"rounded-full",onClick:()=>p(!0),children:[e.jsx(Pn,{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…":v?`${b.length} unsaved change${b.length>1?"s":""}`:"All changes saved"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs($,{variant:"ghost",className:"rounded-full",onClick:()=>C(!1),children:[e.jsx(pr,{className:"h-4 w-4 mr-1"})," Cancel"]}),e.jsxs($,{className:"rounded-full bg-gradient-to-r from-violet-600 to-indigo-600 text-white",disabled:!v||i.isPending,onClick:T,children:[i.isPending&&e.jsx(Ht,{className:"h-4 w-4 mr-1.5 animate-spin"}),"Save changes"]})]})]})]})}),e.jsx(Ll,{open:u,onOpenChange:h,children:e.jsxs(yl,{children:[e.jsxs(vl,{children:[e.jsx(_l,{children:"Discard unsaved changes?"}),e.jsxs(wl,{children:["You have ",b.length," unsaved change(s) on this contact."]})]}),e.jsxs(bl,{children:[e.jsx(jl,{children:"Keep editing"}),e.jsx(fl,{onClick:()=>{h(!1),n(!1)},children:"Discard"})]})]})}),e.jsx(Ll,{open:m,onOpenChange:p,children:e.jsxs(yl,{children:[e.jsxs(vl,{children:[e.jsx(_l,{children:"Delete this contact permanently?"}),e.jsx(wl,{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(bl,{children:[e.jsx(jl,{children:"Cancel"}),e.jsx(fl,{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 HVn(){const s=Vn(),[t,n]=oc(),{agents:r,activeAgents:a,isLoading:i,moveStage:l}=M0(),{followUps:o,complete:c}=NF(),{data:d=[]}=vte();OTe();const u=t.get("view")||"attention",h=K=>n(Q=>(Q.set("view",K),Q),{replace:!0}),[m,p]=j.useState(""),[x,g]=j.useState("all"),[y,b]=j.useState(!1),[v,N]=j.useState(!1),[C,A]=j.useState(!1),[T,P]=j.useState(null),[M,I]=j.useState(null),D=K=>!!K.is_archived!==y||x!=="all"&&SB(K.stage).key!==x?!1:m.trim()?`${K.first_name} ${K.last_name??""} ${K.brokerage??""} ${K.city??""} ${(K.tags??[]).join(" ")} ${K.email??""}`.toLowerCase().includes(m.trim().toLowerCase()):!0,B=j.useMemo(()=>r.filter(D),[r,m,x,y]),q=j.useMemo(()=>{const K=ep(new Date),Q=o.filter(le=>!le.completed_at),J=d.filter(le=>le.status==="open"),ce=Q.filter(le=>le.due_at&&aw(new Date(le.due_at),K)),ue=Q.filter(le=>le.due_at&&x0(new Date(le.due_at))),ne=a.filter(le=>{const he=le.last_touch_at?new Date(le.last_touch_at):null;return he?Date.now()-+he>45*864e5:!!le.created_at&&Date.now()-+new Date(le.created_at)>14*864e5}),ee=a.filter(le=>!le.next_follow_up_at&&!Q.some(he=>he.agent_id===le.id));return{overdue:ce,dueToday:ue,quiet:ne,noNextStep:ee,openRecs:J}},[o,d,a]),W=K=>{const Q=r.find(J=>J.id===K);return Q?`${Q.first_name} ${Q.last_name??""}`.trim():"Someone"},V=[{label:"Relationships",value:a.length,icon:t1},{label:"Overdue",value:q.overdue.length,icon:xo,tone:"text-rose-600"},{label:"Due today",value:q.dueToday.length,icon:xo,tone:"text-orange-600"},{label:"Gone quiet",value:q.quiet.length,icon:xo,tone:"text-slate-600"}];return e.jsxs("div",{children:[e.jsx(vWt,{open:v,onOpenChange:N,onAdded:K=>K&&s(`/attract/agents/${K}`)}),e.jsx(BVn,{open:C,onOpenChange:A}),e.jsx(rQe,{agent:T?r.find(K=>K.id===T.id)??T:null,open:!!T,onOpenChange:K=>!K&&P(null)}),e.jsx(nm,{eyebrow:"Relationships",title:"The people you're building with",description:"Everyone you know, who needs attention, and what you promised — in one place.",actions:e.jsxs(e.Fragment,{children:[e.jsxs($,{variant:"outline",className:"rounded-full",onClick:()=>A(!0),children:[e.jsx(si,{className:"h-3.5 w-3.5 mr-1.5"})," Import"]}),e.jsxs($,{className:"rounded-full bg-gradient-to-r from-violet-600 to-indigo-600 text-white",onClick:()=>N(!0),children:[e.jsx(sn,{className:"h-4 w-4 mr-1"})," Add relationship"]})]})}),e.jsx("div",{className:"grid grid-cols-2 lg:grid-cols-4 gap-3 mb-5",children:V.map(K=>e.jsxs(_e,{className:"p-4 rounded-2xl",children:[e.jsx("div",{className:Tt("text-2xl font-semibold tabular-nums text-slate-900",K.tone),children:K.value}),e.jsx("div",{className:"text-[11.5px] text-slate-500 mt-0.5",children:K.label})]},K.label))}),e.jsxs(_e,{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(Vr,{className:"h-4 w-4 absolute left-3 top-1/2 -translate-y-1/2 text-slate-400"}),e.jsx(be,{value:m,onChange:K=>p(K.target.value),placeholder:"Search name, brokerage, market, tag…",className:"pl-9 rounded-full h-9","aria-label":"Search relationships"})]}),e.jsxs(vs,{value:x,onValueChange:g,children:[e.jsx(gs,{className:"w-[190px] h-9 rounded-full text-[13px]",children:e.jsx(bs,{})}),e.jsxs(ys,{children:[e.jsx(Ye,{value:"all",children:"All stages"}),[...YT,BTe].map(K=>e.jsx(Ye,{value:K.key,children:K.label},K.key))]})]}),e.jsxs($,{variant:y?"default":"outline",size:"sm",className:"rounded-full h-9",onClick:()=>b(K=>!K),children:[e.jsx(Am,{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(([K,Q])=>e.jsxs("button",{onClick:()=>h(K),className:Tt("rounded-full h-8 px-3 text-[12.5px] font-medium transition-colors",u===K?"bg-white text-slate-900 shadow-sm":"text-slate-500 hover:text-slate-800"),children:[K==="stages"?e.jsx(_0,{className:"h-3.5 w-3.5 mr-1 inline"}):K==="list"?e.jsx(Sg,{className:"h-3.5 w-3.5 mr-1 inline"}):null,Q]},K))})]}),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(K=>e.jsx(on,{className:"h-24 w-full rounded-2xl"},K))]}):r.length?u==="attention"?e.jsxs("div",{className:"space-y-6",children:[e.jsx(Bae,{title:"Overdue commitments",tone:"#f43f5e",items:q.overdue,render:K=>e.jsx(Xbt,{f:K,name:W(K.agent_id),onDone:()=>c.mutate(K.id)},K.id)}),e.jsx(Bae,{title:"Due today",tone:"#f97316",items:q.dueToday,render:K=>e.jsx(Xbt,{f:K,name:W(K.agent_id),onDone:()=>c.mutate(K.id)},K.id)}),e.jsx(Bae,{title:"Haven't talked in a while",tone:"#8b5cf6",items:q.quiet.filter(D),render:K=>e.jsx(dRe,{a:K,note:K.last_touch_at?`Last touch ${Hs(new Date(K.last_touch_at),"MMM d")}`:"No meaningful touch yet"},K.id)}),e.jsx(Bae,{title:"No next step set",tone:"#94a3b8",items:q.noNextStep.filter(D),render:K=>e.jsx(dRe,{a:K,note:"Decide one small next step"},K.id)}),!q.overdue.length&&!q.dueToday.length&&!q.quiet.length&&!q.noNextStep.length&&e.jsxs(_e,{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(Oi,{className:"w-full",children:[e.jsx("div",{className:"flex gap-4 pb-4",style:{minWidth:YT.length*290},children:YT.map(K=>{const Q=B.filter(J=>SB(J.stage).key===K.key);return e.jsxs("div",{className:"w-[275px] flex-shrink-0",onDragOver:J=>{J.preventDefault(),J.dataTransfer.dropEffect="move"},onDrop:J=>{J.preventDefault();const ce=r.find(ue=>ue.id===M);ce&&SB(ce.stage).key!==K.key&&l.mutate({id:ce.id,to_stage:nQe(K.key),from_stage:ce.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:K.color}}),e.jsx("h3",{className:"text-[13px] font-semibold text-slate-800",children:K.label}),e.jsx($e,{variant:"secondary",className:"text-[10px] h-5 px-1.5",children:Q.length})]}),e.jsx("div",{className:"text-[11px] text-slate-400 mt-0.5 pl-4.5",children:K.help})]}),e.jsxs("div",{className:"rounded-2xl bg-slate-100/60 p-2 space-y-2 min-h-[180px]",children:[Q.map(J=>e.jsxs("div",{draggable:!0,onDragStart:()=>I(J.id),onClick:()=>s(`/attract/agents/${J.id}`),className:"bg-white rounded-xl p-3 cursor-pointer hover:shadow-md border-l-[3px] transition-all",style:{borderLeftColor:K.color},children:[e.jsxs("div",{className:"text-[13.5px] font-semibold text-slate-900 truncate",children:[J.first_name," ",J.last_name]}),e.jsxs("div",{className:"text-[11.5px] text-slate-500 flex items-center gap-1 mt-0.5 truncate",children:[e.jsx(Ai,{className:"h-3 w-3"}),e.jsx("span",{className:"truncate",children:J.brokerage??"Brokerage not set"})]}),!J.email&&!J.phone&&e.jsx("div",{className:"mt-1.5 text-[10.5px] text-amber-700",children:"No contact info yet"})]},J.id)),!Q.length&&e.jsx("div",{className:"text-[11.5px] text-slate-400 text-center py-4",children:"Drag someone here"})]})]},K.key)})}),e.jsx(Nq,{orientation:"horizontal"})]}):e.jsxs(_e,{className:"rounded-2xl divide-y divide-slate-100 overflow-hidden",children:[B.map(K=>e.jsx(dRe,{a:K,onEdit:()=>P(K)},K.id)),!B.length&&e.jsx("div",{className:"p-10 text-center text-[13px] text-slate-500",children:"No one matches this view."})]}):e.jsx(GVn,{onAdd:()=>N(!0)})]})}function Bae({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($e,{variant:"secondary",className:"text-[10px]",children:n.length})]}),e.jsx(_e,{className:"rounded-2xl divide-y divide-slate-100 overflow-hidden",children:n.slice(0,12).map(r)})]}):null}function Xbt({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(ui,{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(Wn,{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 ",Hs(new Date(s.due_at),"MMM d")]})]})]})]})}function dRe({a:s,note:t,onEdit:n}){var i,l;const r=SB(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(Wn,{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(Ai,{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(ai,{className:"h-3 w-3"}),s.city]}),t&&e.jsxs("span",{className:"text-slate-400",children:["· ",t]})]})]}),e.jsx($e,{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($,{variant:"ghost",size:"sm",className:"rounded-full",onClick:n,children:"Edit"})]})}function GVn({onAdd:s}){return e.jsxs(_e,{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(t1,{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($,{className:"rounded-full btn-primary text-white mt-4",onClick:s,children:[e.jsx(sn,{className:"h-4 w-4 mr-1.5"})," Add a relationship"]})]})}const WVn=[{icon:g1,title:"Helpful Resource",blurb:"One useful document, guide or tool.",to:"/attract/resources"},{icon:Tu,title:"Resource Kit",blurb:"A themed bundle you can personalize and track.",to:"/attract/provide/kits"},{icon:Ph,title:"Training or Masterclass",blurb:"Invite someone to learn something with you.",to:"/attract/provide/masterclasses"},{icon:LN,title:"Event Invitation",blurb:"A room worth being in — online or in person.",to:"/attract/events"},{icon:Tb,title:"Coffee Invitation",blurb:"One conversation is enough.",to:"/attract/relationships?view=attention"},{icon:W3,title:"My Brokerage Story",blurb:"Your personal “why I’m here” page.",to:"/attract/landing-page"},{icon:Ai,title:"Brokerage Information",blurb:"Approved, verified brokerage facts only.",to:"/attract/templates"},{icon:VK,title:"Comparison Guide",blurb:"A fair, honest side-by-side.",to:"/attract/templates"}],KVn=["Agent Business Planning Kit","Open House Conversion Kit","Listing Marketing Kit","Database Follow-Up Kit","AI for Realtors Kit","New Agent Success Kit","Team-Building Guide","Brokerage Evaluation Checklist","Production Growth Kit","90-Day Agent Business Plan","Social Media Planning Kit","Buyer & Seller Lead Conversion Kit"];function YVn(){return e.jsxs("div",{className:"max-w-4xl mx-auto",children:[e.jsx(nm,{eyebrow:"Share Value",title:"What would you like to share?",description:"Give something genuinely useful. Curiosity follows value — it never has to be pushed."}),e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-3",children:WVn.map(s=>e.jsxs(Wn,{to:s.to,className:"rounded-2xl bg-white border border-slate-200/70 p-4 hover:border-violet-300 hover:shadow-sm transition-all flex items-start gap-3",children:[e.jsx("div",{className:"h-10 w-10 rounded-xl bg-violet-50 text-violet-600 grid place-items-center flex-shrink-0",children:e.jsx(s.icon,{className:"h-4.5 w-4.5"})}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"text-[14px] font-semibold text-slate-900",children:s.title}),e.jsx("div",{className:"text-[12.5px] text-slate-500 mt-0.5",children:s.blurb})]})]},s.title))}),e.jsxs(_e,{className:"mt-6 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-[13px] font-semibold uppercase tracking-wider text-slate-600",children:"Ready-to-personalize kits"}),e.jsx("p",{className:"text-[13px] text-slate-500 mt-1 max-w-xl",children:"LevelUp-built starting points. Your headshot, contact details and branding are added automatically — you never re-enter your profile."})]}),e.jsx($,{variant:"outline",className:"rounded-full",asChild:!0,children:e.jsxs(Wn,{to:"/attract/provide/kits/templates",children:["Browse kit templates ",e.jsx(ni,{className:"h-3.5 w-3.5 ml-1.5"})]})})]}),e.jsx("div",{className:"mt-4 flex flex-wrap gap-2",children:KVn.map(s=>e.jsx("span",{className:"rounded-full bg-slate-50 border border-slate-200 px-3 py-1.5 text-[12px] text-slate-700",children:s},s))})]}),e.jsx("p",{className:"mt-6 text-center text-[11.5px] text-slate-400 max-w-lg mx-auto",children:"Engagement means someone found your resource useful — not that they want to change brokerages. Treat it as a reason to keep the relationship going."})]})}function ZVn(){const{settings:s}=MV(),{activeAgents:t}=M0(),n=j.useMemo(()=>{const r=(s==null?void 0:s.primary_pillar)??(s==null?void 0:s.attraction_style)??"balanced",a=((s==null?void 0:s.audiences)??[])[0];return[{icon:Xr,kind:"Talking-head video",title:"Share one thing that changed in your business this year",why:"Personal experience is the only thing no other agent can copy.",to:"/attract/influence/content-studio"},{icon:xR,kind:"Educational carousel",title:"Break down a system other agents could steal from you",why:r==="provide"?"Teaching is your strongest pillar — this plays to it.":"Useful teaching creates curiosity without a pitch.",to:"/attract/influence/content-studio"},{icon:Ez,kind:"Conversation starter",title:a?`Ask ${a} what they’re struggling with right now`:"Ask agents what they’re struggling with right now",why:t.length?`Replies become real conversations with the ${t.length} people you’re already building with.`:"Replies are the easiest way to start new relationships.",to:"/attract/influence/content-studio"}]},[s,t.length]);return e.jsxs("div",{className:"max-w-3xl mx-auto",children:[e.jsx(nm,{eyebrow:"Create Content",title:"Here are three ways to build attraction through content this week.",description:"Start from a real thing that happened in your business — not a blank page."}),e.jsx("div",{className:"space-y-3",children:n.map(r=>e.jsx(_e,{className:"p-5 rounded-2xl border-slate-200/70",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:"h-10 w-10 rounded-xl bg-violet-50 text-violet-600 grid place-items-center flex-shrink-0",children:e.jsx(r.icon,{className:"h-4.5 w-4.5"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx($e,{variant:"outline",className:"rounded-full text-[10.5px] uppercase tracking-wider",children:r.kind}),e.jsx("h3",{className:"text-[15px] font-semibold text-slate-900 mt-1.5 leading-snug",children:r.title}),e.jsx("p",{className:"text-[12.5px] text-slate-500 mt-1",children:r.why}),e.jsx($,{size:"sm",className:"rounded-full btn-primary text-white mt-3",asChild:!0,children:e.jsxs(Wn,{to:r.to,children:[e.jsx(wm,{className:"h-3.5 w-3.5 mr-1.5"})," Build it"]})})]})]})},r.title))}),e.jsxs("div",{className:"mt-6 grid grid-cols-1 sm:grid-cols-3 gap-3",children:[e.jsx(uRe,{icon:wm,label:"Content Studio",to:"/attract/influence/content-studio"}),e.jsx(uRe,{icon:nn,label:"Content calendar",to:"/attract/influence/content-calendar"}),e.jsx(uRe,{icon:Vj,label:"Speaking opportunities",to:"/attract/influence/speaking"})]}),e.jsx("p",{className:"mt-6 text-center text-[11.5px] text-slate-400",children:"Every piece you mark as posted counts toward your weekly attraction plan."})]})}function uRe({icon:s,label:t,to:n}){return e.jsxs(Wn,{to:n,className:"rounded-2xl bg-white border border-slate-200/70 px-4 py-4 hover:border-violet-300 hover:shadow-sm transition-all block",children:[e.jsx(s,{className:"h-4.5 w-4.5 text-violet-600 mb-2"}),e.jsxs("div",{className:"text-[13.5px] font-medium text-slate-800 flex items-center gap-1",children:[t," ",e.jsx(ni,{className:"h-3 w-3 opacity-40"})]})]})}const $ae=[{key:"new_connection",label:"New Connection",color:"#94a3b8"},{key:"building_relationship",label:"Building Relationship",color:"#38bdf8"},{key:"engaging_with_value",label:"Engaging With Value",color:"#14b8a6"},{key:"active_conversation",label:"Active Conversation",color:"#8b5cf6"},{key:"exploring_options",label:"Exploring Options",color:"#6366f1"},{key:"brokerage_presentation",label:"Brokerage Presentation",color:"#f97316"},{key:"decision_pending",label:"Decision Pending",color:"#f59e0b"},{key:"joined",label:"Joined",color:"#16a34a"},{key:"not_right_now",label:"Not Right Now",color:"#64748b"},{key:"long_term_relationship",label:"Long-Term Relationship",color:"#a78bfa"},{key:"not_a_fit",label:"Not a Fit",color:"#cbd5e1"}],Qbt={hot:"bg-rose-100 text-rose-700 border-rose-200",warm:"bg-orange-100 text-orange-700 border-orange-200",cold:"bg-sky-100 text-sky-700 border-sky-200"};function XVn(){const s=Vn(),{agents:t,isLoading:n,upsertAgent:r,moveStage:a,archiveAgent:i,deleteAgent:l}=M0(),[o,c]=j.useState("kanban"),[d,u]=j.useState(""),[h,m]=j.useState(!1),[p,x]=j.useState(!1),[g,y]=j.useState(),[b,v]=j.useState(null),[N,C]=j.useState(null),[A,T]=j.useState(null),[P,M]=j.useState(null),{gmailEmail:I}=ux(),D=t.filter(W=>!!W.is_archived!==h?!1:d?`${W.first_name} ${W.last_name??""} ${W.brokerage??""} ${W.city??""} ${(W.tags??[]).join(" ")} ${W.email??""}`.toLowerCase().includes(d.toLowerCase()):!0),B=b?t.find(W=>W.id===b.id)??b:null,q=({agent:W})=>e.jsxs(Hd,{children:[e.jsx(Gd,{asChild:!0,children:e.jsx($,{variant:"ghost",size:"icon",className:"h-6 w-6 -mr-1",onClick:V=>V.stopPropagation(),"aria-label":"Agent actions",children:e.jsx(cy,{className:"h-3.5 w-3.5"})})}),e.jsxs(Md,{align:"end",onClick:V=>V.stopPropagation(),children:[e.jsxs(Na,{onClick:()=>C(W),children:[e.jsx(Ya,{className:"h-3.5 w-3.5 mr-2"})," Edit contact"]}),e.jsxs(Na,{onClick:()=>s(`/attract/agents/${W.id}`),children:[e.jsx(Tr,{className:"h-3.5 w-3.5 mr-2"})," Open relationship"]}),e.jsx(S0,{}),e.jsxs(Na,{onClick:()=>i.mutate({id:W.id,archived:!W.is_archived}),children:[e.jsx(Am,{className:"h-3.5 w-3.5 mr-2"})," ",W.is_archived?"Restore to pipeline":"Remove from pipeline"]})]})]});return e.jsxs("div",{children:[e.jsx(nm,{eyebrow:"Agent Pipeline",title:"Where relationships live",description:"Move agents through relationship-first stages. Never a target — always a real conversation.",actions:e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex bg-white border rounded-full p-0.5",children:[e.jsxs($,{size:"sm",variant:o==="kanban"?"default":"ghost",className:"rounded-full h-8 px-3",onClick:()=>c("kanban"),children:[e.jsx(_0,{className:"h-3.5 w-3.5 mr-1"})," Board"]}),e.jsxs($,{size:"sm",variant:o==="list"?"default":"ghost",className:"rounded-full h-8 px-3",onClick:()=>c("list"),children:[e.jsx(Sg,{className:"h-3.5 w-3.5 mr-1"})," List"]})]}),e.jsxs($,{className:"rounded-full bg-gradient-to-r from-violet-600 to-indigo-600 hover:opacity-95",onClick:()=>{y(void 0),x(!0)},children:[e.jsx(sn,{className:"h-4 w-4 mr-1"})," Add Agent"]})]})}),e.jsxs("div",{className:"mb-4 flex items-center gap-3 flex-wrap",children:[e.jsxs("div",{className:"relative flex-1 min-w-[220px] max-w-md",children:[e.jsx(Vr,{className:"h-4 w-4 text-slate-400 absolute left-3 top-1/2 -translate-y-1/2"}),e.jsx(be,{value:d,onChange:W=>u(W.target.value),placeholder:"Search name, brokerage, city, tag, email…",className:"pl-9 rounded-full bg-white"})]}),e.jsxs($,{variant:h?"default":"outline",size:"sm",className:"rounded-full",onClick:()=>m(W=>!W),children:[e.jsx(Am,{className:"h-3.5 w-3.5 mr-1.5"})," ",h?"Viewing archived":"Archived"]}),e.jsxs("div",{className:"text-[12.5px] text-slate-500",children:[D.length," agents"]})]}),e.jsx("div",{className:"mb-4",children:e.jsx(kF,{})}),n?e.jsx("div",{className:"py-24 text-center text-slate-500",children:"Loading pipeline…"}):o==="kanban"?e.jsxs(Oi,{className:"w-full",children:[e.jsx("div",{className:"flex gap-4 pb-4",style:{minWidth:$ae.length*300},children:$ae.map(W=>{const V=D.filter(K=>K.stage===W.key);return e.jsxs("div",{className:"w-[280px] flex-shrink-0 flex flex-col",onDragOver:K=>{K.preventDefault(),K.dataTransfer.dropEffect="move"},onDrop:K=>{if(K.preventDefault(),A){const Q=t.find(J=>J.id===A);Q&&Q.stage!==W.key&&a.mutate({id:A,to_stage:W.key,from_stage:Q.stage}),T(null)}},children:[e.jsxs("div",{className:"flex items-center justify-between px-1 mb-3",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:W.color}}),e.jsx("h3",{className:"text-[13px] font-semibold text-slate-800",children:W.label}),e.jsx($e,{variant:"secondary",className:"text-[10px] h-5 px-1.5",children:V.length})]}),e.jsx($,{variant:"ghost",size:"icon",className:"h-6 w-6",onClick:()=>{y(W.key),x(!0)},children:e.jsx(sn,{className:"h-3.5 w-3.5"})})]}),e.jsxs("div",{className:"rounded-2xl bg-slate-100/60 p-2 space-y-2 min-h-[200px]",children:[V.map(K=>e.jsxs("div",{draggable:!0,onDragStart:()=>T(K.id),onClick:()=>v(K),className:"bg-white rounded-xl p-3 cursor-pointer hover:shadow-md border-l-[3px] transition-all",style:{borderLeftColor:W.color},children:[e.jsxs("div",{className:"flex items-start justify-between gap-2",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"text-[13.5px] font-semibold text-slate-900 truncate",children:[K.first_name," ",K.last_name]}),e.jsxs("div",{className:"text-[11.5px] text-slate-500 flex items-center gap-1 mt-0.5 truncate",children:[e.jsx(Ai,{className:"h-3 w-3"}),e.jsx("span",{className:"truncate",children:K.brokerage??"—"})]})]}),K.temperature&&e.jsxs($e,{variant:"outline",className:`text-[9.5px] px-1.5 py-0 ${Qbt[K.temperature]}`,children:[e.jsx(XK,{className:"h-2.5 w-2.5 mr-0.5"}),K.temperature]}),e.jsx(q,{agent:K})]}),e.jsxs("div",{className:"mt-2 flex items-center gap-2 text-[11px] text-slate-500",children:[e.jsx(ai,{className:"h-3 w-3"}),e.jsxs("span",{className:"truncate",children:[K.city,K.state&&`, ${K.state}`]})]}),K.next_follow_up_at&&e.jsxs("div",{className:"mt-1.5 text-[10.5px] text-violet-700 font-medium",children:["Next touch · ",Hs(new Date(K.next_follow_up_at),"MMM d")]})]},K.id)),V.length===0&&e.jsx("div",{className:"text-[11.5px] text-slate-400 text-center py-4",children:"Drop an agent here"})]})]},W.key)})}),e.jsx(Nq,{orientation:"horizontal"})]}):e.jsx(_e,{className:"rounded-2xl overflow-hidden",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{className:"bg-slate-50 text-[11px] uppercase tracking-wider text-slate-500",children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left px-4 py-3",children:"Agent"}),e.jsx("th",{className:"text-left px-4 py-3",children:"Brokerage"}),e.jsx("th",{className:"text-left px-4 py-3",children:"Location"}),e.jsx("th",{className:"text-left px-4 py-3",children:"Stage"}),e.jsx("th",{className:"text-left px-4 py-3",children:"Temp"}),e.jsx("th",{className:"text-left px-4 py-3",children:"Next Follow-Up"}),e.jsx("th",{className:"text-right px-4 py-3",children:"Actions"})]})}),e.jsxs("tbody",{children:[D.map(W=>{const V=$ae.find(K=>K.key===W.stage);return e.jsxs("tr",{onClick:()=>v(W),className:"border-t border-slate-100 hover:bg-slate-50 cursor-pointer",children:[e.jsxs("td",{className:"px-4 py-3 font-medium text-slate-900",children:[W.first_name," ",W.last_name]}),e.jsx("td",{className:"px-4 py-3 text-slate-600",children:W.brokerage}),e.jsxs("td",{className:"px-4 py-3 text-slate-600",children:[W.city,", ",W.state]}),e.jsx("td",{className:"px-4 py-3",children:e.jsx($e,{style:{background:V==null?void 0:V.color,color:"white"},children:V==null?void 0:V.label})}),e.jsx("td",{className:"px-4 py-3",children:W.temperature&&e.jsx($e,{variant:"outline",className:Qbt[W.temperature],children:W.temperature})}),e.jsx("td",{className:"px-4 py-3 text-slate-600",children:W.next_follow_up_at?Hs(new Date(W.next_follow_up_at),"MMM d"):"—"}),e.jsx("td",{className:"px-4 py-3 text-right",children:e.jsx(q,{agent:W})})]},W.id)}),D.length===0&&e.jsx("tr",{children:e.jsx("td",{colSpan:7,className:"px-4 py-10 text-center text-slate-500",children:"No agents match this view."})})]})]})}),e.jsx(QVn,{open:p,onOpenChange:x,defaultStage:g,onSubmit:W=>r.mutate(W,{onSuccess:()=>x(!1)})}),e.jsx(rQe,{agent:N?t.find(W=>W.id===N.id)??N:null,open:!!N,onOpenChange:W=>!W&&C(null),onDeleted:()=>v(null)}),e.jsx(Ub,{open:!!b,onOpenChange:W=>!W&&v(null),children:e.jsx(T1,{className:"w-full sm:max-w-lg overflow-y-auto",children:B&&e.jsxs(e.Fragment,{children:[e.jsxs(kw,{children:[e.jsxs(Sw,{className:"text-xl",children:[B.first_name," ",B.last_name]}),e.jsxs("div",{className:"text-[12.5px] text-slate-500 flex items-center gap-2",children:[e.jsx(Ai,{className:"h-3.5 w-3.5"})," ",B.brokerage??"—"," · ",B.city,", ",B.state]})]}),e.jsxs("div",{className:"mt-6 space-y-5",children:[e.jsxs("div",{className:"flex gap-2 flex-wrap",children:[e.jsxs($,{size:"sm",className:"gap-1.5 bg-gradient-to-r from-violet-600 to-indigo-600 text-white",onClick:()=>C(B),children:[e.jsx(Ya,{className:"h-3.5 w-3.5"})," Edit contact"]}),e.jsxs($,{variant:"outline",size:"sm",className:"gap-1.5",onClick:()=>s(`/attract/agents/${B.id}`),children:[e.jsx(Tr,{className:"h-3.5 w-3.5"})," Open relationship"]}),B.email&&e.jsxs($,{variant:"outline",size:"sm",className:"gap-1.5",onClick:()=>M(B),children:[e.jsx(nn,{className:"h-3.5 w-3.5"})," Email"]}),B.phone&&e.jsx($,{variant:"outline",size:"sm",className:"gap-1.5",asChild:!0,children:e.jsxs("a",{href:`tel:${B.phone}`,children:[e.jsx(ya,{className:"h-3.5 w-3.5"})," Call"]})}),e.jsxs($,{variant:"outline",size:"sm",className:"gap-1.5",onClick:()=>s(`/attract/agents/${B.id}`),children:[e.jsx(Ji,{className:"h-3.5 w-3.5"})," Log touch"]})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-[11px] uppercase tracking-wider text-slate-500",children:"Stage"}),e.jsxs(vs,{value:B.stage,onValueChange:W=>a.mutate({id:B.id,to_stage:W,from_stage:B.stage}),children:[e.jsx(gs,{className:"mt-1",children:e.jsx(bs,{})}),e.jsx(ys,{children:$ae.map(W=>e.jsx(Ye,{value:W.key,children:W.label},W.key))})]})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-[11px] uppercase tracking-wider text-slate-500",children:"Temperature"}),e.jsxs(vs,{value:B.temperature??"warm",onValueChange:W=>r.mutate({id:B.id,first_name:B.first_name,temperature:W}),children:[e.jsx(gs,{className:"mt-1",children:e.jsx(bs,{})}),e.jsx(ys,{children:["cold","warm","hot"].map(W=>e.jsx(Ye,{value:W,className:"capitalize",children:W},W))})]})]}),!!(B.tags??[]).length&&e.jsx("div",{className:"flex flex-wrap gap-1.5",children:(B.tags??[]).map(W=>e.jsx($e,{variant:"outline",className:"rounded-full",children:W},W))}),e.jsx(hRe,{label:"Notes",value:B.notes}),e.jsx(hRe,{label:"Goals",value:B.goals}),e.jsx(hRe,{label:"Challenges",value:B.challenges}),e.jsxs("div",{className:"pt-4 border-t flex justify-between",children:[e.jsxs($,{variant:"ghost",size:"sm",onClick:()=>i.mutate({id:B.id,archived:!B.is_archived}),children:[e.jsx(Am,{className:"h-4 w-4 mr-1"})," ",B.is_archived?"Restore":"Remove from pipeline"]}),e.jsxs($,{variant:"ghost",size:"sm",className:"text-rose-600",onClick:()=>C(B),children:[e.jsx(Pn,{className:"h-4 w-4 mr-1"})," Delete…"]})]})]})]})})}),(P==null?void 0:P.email)&&e.jsx(x2,{open:!!P,onOpenChange:W=>!W&&M(null),contact:{id:P.id,first_name:P.preferred_name||P.first_name,last_name:P.last_name||"",email:P.email},gmailEmail:I,sendSource:"attract",logTouchpoint:!1})]})}function hRe({label:s,value:t}){return e.jsxs("div",{children:[e.jsx(se,{className:"text-[11px] uppercase tracking-wider text-slate-500",children:s}),e.jsx("div",{className:"mt-1 text-[13.5px] text-slate-800 whitespace-pre-wrap min-h-[24px]",children:t||e.jsx("span",{className:"text-slate-400",children:"Not set"})})]})}function QVn({open:s,onOpenChange:t,defaultStage:n,onSubmit:r}){const[a,i]=j.useState({first_name:"",last_name:"",brokerage:"",city:"",state:"",temperature:"warm",primary_pillar:"connect",stage:n??"new_connection",notes:""});return e.jsx(Os,{open:s,onOpenChange:t,children:e.jsxs(Rs,{className:"max-w-lg",children:[e.jsx(Us,{children:e.jsx(zs,{children:"Add an agent to your pipeline"})}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(se,{children:"First name *"}),e.jsx(be,{value:a.first_name,onChange:l=>i({...a,first_name:l.target.value})})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Last name"}),e.jsx(be,{value:a.last_name,onChange:l=>i({...a,last_name:l.target.value})})]}),e.jsxs("div",{className:"col-span-2",children:[e.jsx(se,{children:"Current brokerage"}),e.jsx(be,{value:a.brokerage,onChange:l=>i({...a,brokerage:l.target.value})})]}),e.jsxs("div",{children:[e.jsx(se,{children:"City"}),e.jsx(be,{value:a.city,onChange:l=>i({...a,city:l.target.value})})]}),e.jsxs("div",{children:[e.jsx(se,{children:"State"}),e.jsx(be,{value:a.state,onChange:l=>i({...a,state:l.target.value})})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Temperature"}),e.jsxs(vs,{value:a.temperature,onValueChange:l=>i({...a,temperature:l}),children:[e.jsx(gs,{children:e.jsx(bs,{})}),e.jsxs(ys,{children:[e.jsx(Ye,{value:"cold",children:"Cold"}),e.jsx(Ye,{value:"warm",children:"Warm"}),e.jsx(Ye,{value:"hot",children:"Hot"})]})]})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Primary pillar"}),e.jsxs(vs,{value:a.primary_pillar,onValueChange:l=>i({...a,primary_pillar:l}),children:[e.jsx(gs,{children:e.jsx(bs,{})}),e.jsxs(ys,{children:[e.jsx(Ye,{value:"produce",children:"Produce"}),e.jsx(Ye,{value:"influence",children:"Influence"}),e.jsx(Ye,{value:"provide",children:"Provide"}),e.jsx(Ye,{value:"connect",children:"Connect"})]})]})]}),e.jsxs("div",{className:"col-span-2",children:[e.jsx(se,{children:"Notes"}),e.jsx(Is,{rows:3,value:a.notes,onChange:l=>i({...a,notes:l.target.value})})]})]}),e.jsxs(kr,{children:[e.jsx($,{variant:"ghost",onClick:()=>t(!1),children:"Cancel"}),e.jsx($,{disabled:!a.first_name,className:"bg-gradient-to-r from-violet-600 to-indigo-600",onClick:()=>r(a),children:"Add Agent"})]})]})})}const JVn={call:ya,email:nn,coffee:Tb,gift:Co,text:nn,event:Xu};function eHn(){const{followUps:s,complete:t}=NF(),{agents:n}=M0(),r=j.useMemo(()=>{const l=ep(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);aw(p,l)?o.push(m):x0(p)?c.push(m):Kvs(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:xo},{label:"Due Today",value:r.today.length,tone:"text-orange-600 bg-orange-50",icon:Hr},{label:"Completed This Week",value:r.done.filter(l=>l.completed_at&&new Date(l.completed_at)>Bd(new Date,-7)).length,tone:"text-emerald-600 bg-emerald-50",icon:Fr}];return e.jsxs("div",{children:[e.jsx(nm,{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(_e,{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(kF,{})}),e.jsxs("div",{className:"space-y-6",children:[e.jsx(YG,{title:"Overdue",items:r.overdue,agentMap:a,onComplete:l=>t.mutate(l),tone:"rose"}),e.jsx(YG,{title:"Today",items:r.today,agentMap:a,onComplete:l=>t.mutate(l),tone:"orange"}),e.jsx(YG,{title:"Tomorrow",items:r.tomorrow,agentMap:a,onComplete:l=>t.mutate(l),tone:"violet"}),e.jsx(YG,{title:"Later This Week",items:r.later,agentMap:a,onComplete:l=>t.mutate(l),tone:"slate"}),r.done.length>0&&e.jsx(YG,{title:"Recently Completed",items:r.done.slice(0,5),agentMap:a,onComplete:()=>{},tone:"emerald",done:!0})]})]})}function YG({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($e,{variant:"secondary",className:"text-[10px]",children:t.length})]}),e.jsx(_e,{className:"rounded-2xl divide-y divide-slate-100 overflow-hidden",children:t.map(o=>{const c=n.get(o.agent_id),d=JVn[o.touch_type??""]??nn;return e.jsxs("div",{className:`flex items-start gap-3 p-4 hover:bg-slate-50 ${i?"opacity-60":""}`,children:[e.jsx(ui,{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:Hs(new Date(o.due_at),"MMM d")}),e.jsx($,{variant:"ghost",size:"sm",children:"Snooze"})]},o.id)})})]})}const tHn={pdf:Wr,link:Dc,video:Xr,tool:c5,guide:wf},sHn={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 nHn(){const{resources:s,isLoading:t}=fWt(),[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.jsx(nm,{eyebrow:"Resource Library",title:"The stack you share with future teammates.",description:"Every resource, script, and tool you use — ready to share in one click.",actions:e.jsxs($,{className:"rounded-full bg-gradient-to-r from-violet-600 to-indigo-600",children:[e.jsx(sn,{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(Vr,{className:"h-4 w-4 text-slate-400 absolute left-3 top-1/2 -translate-y-1/2"}),e.jsx(be,{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($,{size:"sm",variant:a==="all"?"default":"outline",className:"rounded-full h-8",onClick:()=>i("all"),children:"All"}),l.map(c=>e.jsx($,{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(_e,{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=tHn[c.resource_type]??Wr;return e.jsxs(_e,{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($e,{className:`${sHn[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($,{size:"sm",variant:"outline",className:"rounded-full gap-1",children:[e.jsx(vd,{className:"h-3.5 w-3.5"})," Share"]})]})]},c.id)})})]})}const rHn=[{category:"First Touch",icon:Ji,color:"#7c3aed",items:[{title:"Warm intro after meeting",body:"Hey {{first_name}} — really enjoyed meeting you at {{event}}. Would love to grab coffee sometime and hear more about what you're building at {{brokerage}}."},{title:"Congrats on a recent close",body:"Saw your closing at {{property}} pop up — nice work {{first_name}}. Those aren't easy right now. If you ever want to compare notes on how you're getting deals across the line, I'm always up for a coffee."}]},{category:"Value Share",icon:nn,color:"#4f46e5",items:[{title:"Sending a helpful resource",body:"Hey {{first_name}} — thought of you when I put this together. No agenda, just something I think you'll actually use: {{resource_link}}"},{title:"Market update forward",body:"Sending along this month's local market snapshot — figured you might want it for your buyer conversations this week: {{link}}"}]},{category:"Coffee Invite",icon:Tb,color:"#0d9488",items:[{title:"Casual 30-min coffee",body:"Hey {{first_name}}, are you free for a 30-min coffee sometime in the next couple weeks? No agenda — just want to hear how the year is going for you."},{title:"Follow-up after coffee",body:"Really enjoyed catching up {{first_name}}. Here's the {{resource}} I mentioned — and I'll circle back in a few weeks. In the meantime, if I can help with anything, just text."}]},{category:"Check-In",icon:ya,color:"#9333ea",items:[{title:"Quarterly check-in",body:"Hey {{first_name}} — just thinking of you. How's the quarter shaping up? No ask, just checking in."},{title:"Birthday message",body:"Happy birthday {{first_name}}! Hope you get to slow down for a minute today. 🎉"}]}];function aHn(){const s=t=>{navigator.clipboard.writeText(t),ae.success("Template copied")};return e.jsxs("div",{children:[e.jsx(nm,{eyebrow:"Message Templates",title:"Words that sound like you.",description:"Starting points — never scripts. Personalize the details and let the relationship speak."}),e.jsx("div",{className:"space-y-8",children:rHn.map(t=>{const n=t.icon;return e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-3 mb-4",children:[e.jsx("div",{className:"h-10 w-10 rounded-xl grid place-items-center",style:{background:`${t.color}18`,color:t.color},children:e.jsx(n,{className:"h-5 w-5"})}),e.jsxs("div",{children:[e.jsx("h3",{className:"text-lg font-semibold text-slate-900",children:t.category}),e.jsxs("div",{className:"text-[12.5px] text-slate-500",children:[t.items.length," templates"]})]})]}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:t.items.map(r=>e.jsxs(_e,{className:"p-5 rounded-2xl",children:[e.jsxs("div",{className:"flex items-start justify-between gap-2",children:[e.jsx("div",{className:"font-semibold text-slate-900",children:r.title}),e.jsx($e,{variant:"outline",className:"text-[10px]",children:t.category})]}),e.jsx("p",{className:"mt-3 text-[13.5px] text-slate-700 leading-relaxed whitespace-pre-wrap",children:r.body}),e.jsx("div",{className:"mt-4 pt-4 border-t border-slate-100 flex justify-end",children:e.jsxs($,{variant:"outline",size:"sm",className:"rounded-full gap-1",onClick:()=>s(r.body),children:[e.jsx(Ca,{className:"h-3.5 w-3.5"})," Copy"]})})]},r.title))})]},t.category)})})]})}const iHn={produce:"#7c3aed",influence:"#4f46e5",provide:"#0d9488",connect:"#9333ea"};function Jbt(){const{agents:s}=M0(),{activities:t}=tQe(180),n=j.useMemo(()=>Array.from({length:12},(l,o)=>Tg(fY(new Date,(11-o)*7))).map(l=>{const o=Bd(l,7),c=t.filter(d=>new Date(d.created_at)>=l&&new Date(d.created_at){const i={produce:0,influence:0,provide:0,connect:0};for(const l of t)l.pillar&&(i[l.pillar]=(i[l.pillar]||0)+1);return Object.entries(i).map(([l,o])=>({name:l,value:o,color:iHn[l]}))},[t]),a=j.useMemo(()=>["new_connection","building_relationship","engaging_with_value","active_conversation","brokerage_presentation","joined"].map(l=>({stage:l.replace(/_/g," "),count:s.filter(o=>o.stage===l).length})),[s]);return e.jsxs("div",{children:[e.jsx(nm,{eyebrow:"Reports & Insights",title:"See the compounding effect.",description:"Attraction is a long game. These reports show you the small consistent trend lines that matter."}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-6",children:[e.jsxs(_e,{className:"p-6 rounded-2xl",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-wider text-slate-500 mb-1",children:"Weekly Activity"}),e.jsx("div",{className:"text-lg font-semibold text-slate-900 mb-4",children:"Attraction activities · Last 12 weeks"}),e.jsx(Ob,{width:"100%",height:260,children:e.jsxs(iYe,{data:n,children:[e.jsx(k1,{dataKey:"week",tick:{fontSize:11}}),e.jsx(S1,{tick:{fontSize:11}}),e.jsx(yf,{}),e.jsx(dF,{type:"monotone",dataKey:"activities",stroke:"#7c3aed",strokeWidth:2.5,dot:{r:3}})]})})]}),e.jsxs(_e,{className:"p-6 rounded-2xl",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-wider text-slate-500 mb-1",children:"Pillar Balance"}),e.jsx("div",{className:"text-lg font-semibold text-slate-900 mb-4",children:"Where you're investing time"}),e.jsx(Ob,{width:"100%",height:260,children:e.jsxs(oYe,{children:[e.jsx(ok,{data:r,dataKey:"value",nameKey:"name",cx:"50%",cy:"50%",innerRadius:55,outerRadius:90,paddingAngle:2,children:r.map((i,l)=>e.jsx(eV,{fill:i.color},l))}),e.jsx(yf,{}),e.jsx(FR,{})]})})]}),e.jsxs(_e,{className:"p-6 rounded-2xl lg:col-span-2",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-wider text-slate-500 mb-1",children:"Pipeline Distribution"}),e.jsx("div",{className:"text-lg font-semibold text-slate-900 mb-4",children:"Agents by stage"}),e.jsx(Ob,{width:"100%",height:280,children:e.jsxs(REe,{data:a,children:[e.jsx(k1,{dataKey:"stage",tick:{fontSize:10}}),e.jsx(S1,{tick:{fontSize:11}}),e.jsx(yf,{}),e.jsx(i2,{dataKey:"count",fill:"#4f46e5",radius:[8,8,0,0]})]})})]})]})]})}function oHn(){const{settings:s,upsert:t,resetOnboarding:n}=MV(),[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(nm,{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(_e,{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(Mu,{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($,{asChild:!0,variant:"outline",className:"rounded-full",children:e.jsx(Wn,{to:"/attract/plan",children:"View plan"})}),e.jsxs($,{variant:"outline",className:"rounded-full",onClick:()=>n.mutate(),children:[e.jsx(Ih,{className:"h-4 w-4 mr-1.5"})," Rerun onboarding"]})]})]}),e.jsxs("div",{className:"space-y-6",children:[e.jsxs(_e,{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(se,{children:"Elevator introduction"}),e.jsx(Is,{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(se,{children:"Focus market"}),e.jsx(be,{value:r.focus_market??"",onChange:l=>i({focus_market:l.target.value}),placeholder:"Orange County, CA"})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Annual attraction goal"}),e.jsx(be,{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(se,{children:'Your "why" for attraction'}),e.jsx(Is,{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(_e,{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(se,{children:"Hot leads follow-up"}),e.jsxs(vs,{value:String(r.hot_cadence_days??3),onValueChange:l=>i({hot_cadence_days:Number(l)}),children:[e.jsx(gs,{children:e.jsx(bs,{})}),e.jsxs(ys,{children:[e.jsx(Ye,{value:"1",children:"Every day"}),e.jsx(Ye,{value:"3",children:"Every 3 days"}),e.jsx(Ye,{value:"7",children:"Every week"})]})]})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Warm leads follow-up"}),e.jsxs(vs,{value:String(r.warm_cadence_days??14),onValueChange:l=>i({warm_cadence_days:Number(l)}),children:[e.jsx(gs,{children:e.jsx(bs,{})}),e.jsxs(ys,{children:[e.jsx(Ye,{value:"7",children:"Weekly"}),e.jsx(Ye,{value:"14",children:"Every 2 weeks"}),e.jsx(Ye,{value:"30",children:"Monthly"})]})]})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Long-term nurture"}),e.jsxs(vs,{value:String(r.longterm_cadence_days??60),onValueChange:l=>i({longterm_cadence_days:Number(l)}),children:[e.jsx(gs,{children:e.jsx(bs,{})}),e.jsxs(ys,{children:[e.jsx(Ye,{value:"30",children:"Monthly"}),e.jsx(Ye,{value:"60",children:"Every 2 months"}),e.jsx(Ye,{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(Tn,{checked:r.weekly_digest_enabled??!0,onCheckedChange:l=>i({weekly_digest_enabled:l})})]})})]})]}),e.jsxs(_e,{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($,{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 $Ue=[{key:"transaction_tracker",pillar:"produce",title:"Transaction-to-Relationship Tracker",route:"/attract/produce/transaction-tracker",status:"live",tables:["attract_transactions","attract_agents"],notes:"Full CRUD, converts co-op agents into pipeline relationships."},{key:"production_goals",pillar:"produce",title:"Production Goals",route:"/attract/produce/goals",status:"live",tables:["attract_production_goals","attract_transactions"],notes:"Annual/quarterly/monthly targets, pace vs actual, auto closings from logged transactions, weekly breakdown."},{key:"awards",pillar:"produce",title:"Awards & Recognition",route:"/attract/produce/awards",status:"live",tables:["attract_awards"],notes:"CRUD + copyable proof points into Content Studio."},{key:"content_calendar",pillar:"produce",title:"Content Calendar",route:"/attract/influence/content-calendar",status:"live",tables:["attract_content_drafts","attract_market_presence","attract_speaking_opportunities"],notes:"Unified month grid; schedules undated drafts."},{key:"market_presence",pillar:"produce",title:"Market Presence",route:"/attract/produce/market-presence",status:"live",tables:["attract_market_presence"],notes:"Cadence commitments with status pipeline, past-due tracking, task + activity wiring."},{key:"testimonials",pillar:"produce",title:"Client Testimonials",route:"/attract/produce/testimonials",status:"live",tables:["attract_testimonials"],notes:"Permission tracking, approval gate, usage counter to prevent overexposure."},{key:"content_studio",pillar:"influence",title:"Authority Content Studio",route:"/attract/influence/content-studio",status:"live",tables:["attract_content_drafts"],notes:"AI-assisted drafts with status workflow."},{key:"speaking",pillar:"influence",title:"Speaking Calendar",route:"/attract/influence/speaking",status:"live",tables:["attract_speaking_opportunities","attract_follow_ups","attract_activities"],notes:"Month/week/agenda, full CRUD, status pipeline, ICS export, follow-up + activity wiring."},{key:"masterclass",pillar:"influence",title:"Masterclass Builder",route:"/attract/provide/masterclasses",status:"live",tables:["attract_masterclasses","attract_events","attract_resource_kits","attract_follow_ups"],notes:"Lives under Provide; 6-step builder, autosave, event + kit conversion."},{key:"podcast",pillar:"influence",title:"Podcast & Guest Spots",route:"/attract/influence/speaking",status:"partial",tables:["attract_speaking_opportunities"],notes:"Tracked as event_type = podcast inside the Speaking Calendar."},{key:"roundtables",pillar:"influence",title:"Agent Roundtables",route:"/attract/events/new",status:"partial",tables:["attract_events"],notes:"Uses the Connect Event Engine rather than a separate system."},{key:"resource_kits",pillar:"provide",title:"Resource Kit Builder",route:"/attract/provide/kits",status:"live",tables:["attract_resource_kits","attract_resource_kit_items","attract_kit_shares","attract_kit_events"],notes:"Flagship — build, share, track engagement."},{key:"kit_templates",pillar:"provide",title:"Starter Kit Library",route:"/attract/provide/kits/templates",status:"live",tables:["attract_kit_templates"],notes:"10 starter kits, clone to own."},{key:"masterclass_builder",pillar:"provide",title:"Masterclass Builder",route:"/attract/provide/masterclasses",status:"live",tables:["attract_masterclasses"],notes:"8 starter templates, deterministic copy generation, no auto-send."},{key:"value_library",pillar:"provide",title:"Value Library",route:"/attract/resources",status:"partial",tables:["attract_resources"],notes:"Read + save works; no categorization/search yet."},{key:"event_engine",pillar:"connect",title:"Event & Mastermind Engine",route:"/attract/events",status:"live",tables:["attract_events","attract_event_attendees","attract_event_invitations","attract_event_notes"],notes:"Builder, public registration, invitations, QR check-in, follow-up."},{key:"checkin",pillar:"connect",title:"Mobile Check-In",route:"/attract/events/:eventId/checkin",status:"live",tables:["attract_event_attendees"],notes:"QR + manual check-in."},{key:"coffee_meetings",pillar:"connect",title:"Coffee & Meetings",route:"/attract/follow-up",status:"partial",tables:["attract_follow_ups"],notes:"Handled as follow-ups; no dedicated meeting scheduler."},{key:"milestones",pillar:"connect",title:"Milestones & Celebrations",route:"/attract/connect/milestones",status:"live",tables:["attract_milestones","attract_follow_ups"],notes:"Recurring annual dates roll forward; reach-out tasks + celebration logging."},{key:"checkins",pillar:"connect",title:"Personal Check-Ins",route:"/attract/opportunities",status:"partial",tables:["attract_recommendations"],notes:"Surfaced by the intelligence layer as recommendations."},{key:"circles",pillar:"connect",title:"Agent Circles",route:"/attract/events/new",status:"partial",tables:["attract_events"],notes:"Create as a recurring mastermind event."},{key:"opportunities",pillar:"core",title:"Relationship Opportunities",route:"/attract/opportunities",status:"live",tables:["attract_recommendations","attract_agent_scores"],notes:"Ranked, explainable recommendations."},{key:"digest",pillar:"core",title:"Weekly Digest",route:"/attract/digest",status:"live",tables:["attract_digests","attract_digest_items","attract_digest_settings"],notes:"Manual send + preview via attract-send-digest."},{key:"plan",pillar:"core",title:"90-Day Plan",route:"/attract/plan",status:"live",tables:["attract_settings","attract_daily_plan"],notes:""},{key:"pipeline",pillar:"core",title:"Agent Pipeline",route:"/attract/pipeline",status:"live",tables:["attract_agents","attract_pipeline_history"],notes:"Kanban with stage history."},{key:"reports",pillar:"core",title:"Reports",route:"/attract/reports",status:"partial",tables:["attract_activities","attract_agents"],notes:"Core charts only; no export."}],UUe={live:"Live",partial:"Partial",placeholder:"Placeholder",integration_required:"Integration required"},bWt={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 lHn({tool:s,accent:t}){const[n,r]=j.useState(!1),a=Vn(),i=s.icon,l=!!s.to,o=$Ue.find(u=>u.key===s.key),c=(o==null?void 0:o.status)??(l?"live":"placeholder"),d=()=>{l&&s.to?a(s.to):r(!0)};return e.jsxs(e.Fragment,{children:[e.jsxs(_e,{onClick:d,className:"group p-5 rounded-2xl border-slate-200/70 bg-white shadow-sm hover:shadow-md cursor-pointer transition-all hover:-translate-y-0.5 relative",children:[e.jsxs("div",{className:`absolute top-3 right-3 inline-flex items-center gap-1 text-[10px] font-semibold uppercase tracking-wider rounded-full px-2 py-0.5 border ${bWt[c]}`,children:[c==="live"&&e.jsx(dn,{className:"h-2.5 w-2.5"}),UUe[c]]}),e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsx("div",{className:"h-11 w-11 rounded-xl grid place-items-center flex-shrink-0",style:{background:`${t}18`,color:t},children:e.jsx(i,{className:"h-5 w-5"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"text-[15px] font-semibold text-slate-900",children:s.title}),e.jsx("div",{className:"text-[13px] text-slate-600 mt-1 leading-relaxed",children:s.description}),e.jsxs("div",{className:"mt-3 inline-flex items-center gap-1 text-[12.5px] font-semibold",style:{color:t},children:[s.cta??(l?"Open Tool":"Preview")," ",e.jsx(Ja,{className:"h-3.5 w-3.5 group-hover:translate-x-0.5 transition-transform"})]})]})]})]}),e.jsx(Os,{open:n,onOpenChange:r,children:e.jsxs(Rs,{className:"max-w-lg",children:[e.jsxs(Us,{children:[e.jsx("div",{className:"h-12 w-12 rounded-2xl grid place-items-center mb-2",style:{background:`${t}18`,color:t},children:e.jsx(i,{className:"h-6 w-6"})}),e.jsx(zs,{children:s.title})]}),e.jsxs("div",{className:"text-[14px] text-slate-700 leading-relaxed",children:[s.description,e.jsx("div",{className:"mt-4 rounded-xl bg-violet-50 border border-violet-100 p-4 text-[13px] text-violet-900",children:"This tool is on the roadmap. Mark your interest and it will jump the queue in your next release."})]}),e.jsxs(kr,{children:[e.jsx($,{variant:"ghost",onClick:()=>r(!1),children:"Close"}),e.jsx($,{className:"bg-gradient-to-r from-violet-600 to-indigo-600",onClick:()=>{ae.success("Added to your plan"),r(!1)},children:"Add to My Plan"})]})]})})]})}function aQe({pillar:s,title:t,tagline:n,intro:r,accent:a,icon:i,tools:l,stats:o}){return e.jsxs("div",{children:[e.jsxs("div",{className:"rounded-3xl p-7 md:p-10 mb-8 relative overflow-hidden text-white",style:{background:`linear-gradient(135deg, ${a} 0%, #4f46e5 100%)`},children:[e.jsx("div",{className:"absolute -right-16 -top-16 h-64 w-64 rounded-full bg-white/10 blur-2xl"}),e.jsxs("div",{className:"relative",children:[e.jsxs("div",{className:"inline-flex items-center gap-2 text-[11px] uppercase tracking-[0.18em] font-semibold opacity-80 mb-3",children:[e.jsx(i,{className:"h-4 w-4"})," Pillar ",s]}),e.jsx("h1",{className:"text-4xl md:text-5xl font-semibold tracking-tight",children:t}),e.jsx("p",{className:"text-white/85 text-lg mt-2",children:n}),e.jsx("p",{className:"text-white/70 mt-4 max-w-2xl leading-relaxed",children:r}),o&&e.jsx("div",{className:"mt-6 grid grid-cols-2 md:grid-cols-4 gap-3 max-w-2xl",children:o.map(c=>e.jsxs("div",{className:"rounded-xl bg-white/10 backdrop-blur px-4 py-3",children:[e.jsx("div",{className:"text-2xl font-semibold tabular-nums",children:c.value}),e.jsx("div",{className:"text-[11.5px] uppercase tracking-wider opacity-80",children:c.label})]},c.label))})]})]}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-4",children:l.map(c=>e.jsx(lHn,{tool:c,accent:a},c.key))})]})}function e_t(){return e.jsx(aQe,{pillar:"01",title:"Produce",accent:"#7c3aed",icon:pl,tagline:"Become the agent others want to be around.",intro:"Production isn't ego — it's proof. When you're actively closing, learning, and getting recognized, agents naturally lean in. Use these tools to make your production visible without bragging.",stats:[{label:"Closed YTD",value:24},{label:"Awards",value:3},{label:"Content Pieces",value:12},{label:"Speaking",value:2}],tools:[{key:"transaction_tracker",icon:Qa,title:"Transaction-to-Relationship Tracker",description:"Turn great cooperating agents from real transactions into long-term professional relationships.",to:"/attract/produce/transaction-tracker"},{key:"production_goals",icon:w0,title:"Production Goals",description:"Set annual, quarterly, and monthly targets, then track whether you are ahead or behind pace.",to:"/attract/produce/goals"},{key:"awards",icon:pu,title:"Awards & Recognition",description:"Track brokerage and industry awards so you can reference them naturally in agent conversations.",to:"/attract/produce/awards"},{key:"content_calendar",icon:Gj,title:"Content Calendar",description:"One month view of every draft, market update, and speaking date you have committed to.",to:"/attract/influence/content-calendar"},{key:"market_presence",icon:Il,title:"Market Presence",description:"Publish market updates on a set cadence so agents see you as the local voice.",to:"/attract/produce/market-presence"},{key:"testimonials",icon:Qa,title:"Client Testimonials",description:"A permission-tracked library of client quotes that make future agent conversations easier.",to:"/attract/produce/testimonials"}]})}function t_t(){return e.jsx(aQe,{pillar:"02",title:"Influence",accent:"#4f46e5",icon:dn,tagline:"Show up in ways that draw the right agents to you.",intro:"Influence is earned by helping publicly and consistently. These tools give you simple ways to teach, speak, and be seen — so the right agents come to you first.",stats:[{label:"Speaking Slots",value:4},{label:"Podcast Guests",value:2},{label:"Masterclasses",value:6},{label:"Reach",value:"12.4k"}],tools:[{key:"content_studio",icon:H3,title:"Authority Content Studio",description:"Turn your real experience into agent-focused content — script, caption, carousel, email — in one shot.",to:"/attract/influence/content-studio"},{key:"content_calendar",icon:Nl,title:"Content Calendar",description:"See drafts, market updates, and speaking dates on one month grid — and schedule what has no date.",to:"/attract/influence/content-calendar"},{key:"speaking",icon:Vj,title:"Speaking Calendar",description:"Track panels, MLS talks, podcasts, and keynotes from first idea through post-event follow-up.",to:"/attract/influence/speaking"},{key:"masterclass",icon:Ph,title:"Masterclass Builder",description:"Turn what you already know into a 45-minute teaching moment agents actually attend.",to:"/attract/provide/masterclasses"},{key:"podcast",icon:Xr,title:"Podcast & Guest Spots",description:"Log podcast appearances in the Speaking Calendar and repurpose clips into agent touch points.",to:"/attract/influence/speaking"},{key:"roundtables",icon:qn,title:"Agent Roundtables",description:"Host small-group conversations using the Connect Event Engine — value first, no pitching.",to:"/attract/events/new"}]})}const C9=["attract-kits"],ZG=s=>["attract-kit-items",s],XG=s=>["attract-kit-shares",s??"all"],cHn=s=>["attract-kit-events",s??"all"],dHn=["attract-kit-templates"];function LV(){const{user:s}=_s(),t=ts(),n=ht({queryKey:[...C9,s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:o,error:c}=await U.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 U.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:C9})}),a=yt({mutationFn:async({id:o,patch:c})=>{const{data:d,error:u}=await U.from("attract_resource_kits").update(c).eq("id",o).select("*").single();if(u)throw u;return d},onSuccess:()=>t.invalidateQueries({queryKey:C9})}),i=yt({mutationFn:async o=>{const{error:c}=await U.from("attract_resource_kits").delete().eq("id",o);if(c)throw c},onSuccess:()=>t.invalidateQueries({queryKey:C9})}),l=yt({mutationFn:async o=>{const{data:c,error:d}=await U.rpc("duplicate_attract_kit",{_kit_id:o});if(d)throw d;return c},onSuccess:()=>t.invalidateQueries({queryKey:C9})});return{kits:n.data??[],isLoading:n.isLoading,create:r,update:a,remove:i,duplicate:l}}function _Wt(s){return ht({queryKey:["attract-kit",s],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await U.from("attract_resource_kits").select("*").eq("id",s).single();if(n)throw n;return t}})}function uHn(s){const t=ts(),n=ht({queryKey:ZG(s??""),enabled:!!s,queryFn:async()=>{const{data:o,error:c}=await U.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 U.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:ZG(s??"")})}),a=yt({mutationFn:async({id:o,patch:c})=>{const{error:d}=await U.from("attract_resource_kit_items").update(c).eq("id",o);if(d)throw d},onSuccess:()=>t.invalidateQueries({queryKey:ZG(s??"")})}),i=yt({mutationFn:async o=>{const{error:c}=await U.from("attract_resource_kit_items").delete().eq("id",o);if(c)throw c},onSuccess:()=>t.invalidateQueries({queryKey:ZG(s??"")})}),l=yt({mutationFn:async o=>{await Promise.all(o.map((c,d)=>U.from("attract_resource_kit_items").update({sort_order:d}).eq("id",c)))},onSuccess:()=>t.invalidateQueries({queryKey:ZG(s??"")})});return{items:n.data??[],isLoading:n.isLoading,add:r,update:a,remove:i,reorder:l}}function wWt(s){const{user:t}=_s(),n=ts(),r=ht({queryKey:XG(s),enabled:!!t,queryFn:async()=>{let l=U.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 U.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:XG(s)}),n.invalidateQueries({queryKey:XG()});try{(o=navigator.clipboard)==null||o.writeText(NWt(l.share_token)),ae.success("Share link created and copied")}catch{ae.success("Share link created")}},onError:l=>ae.error((l==null?void 0:l.message)||"Could not create share link")}),i=yt({mutationFn:async l=>{const{error:o}=await U.from("attract_kit_shares").update({status:"revoked"}).eq("id",l);if(o)throw o},onSuccess:()=>{n.invalidateQueries({queryKey:XG(s)}),n.invalidateQueries({queryKey:XG()}),ae.success("Link revoked")},onError:l=>ae.error((l==null?void 0:l.message)||"Could not revoke link")});return{shares:r.data??[],isLoading:r.isLoading,create:a,revoke:i}}function jWt(s){return ht({queryKey:cHn(s),queryFn:async()=>{let t=U.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 hHn(){return ht({queryKey:dHn,queryFn:async()=>{const{data:s,error:t}=await U.from("attract_kit_templates").select("*").eq("is_active",!0).order("sort_order");if(t)throw t;return s??[]}})}function mHn(){const s=ts();return yt({mutationFn:async t=>{const{data:n,error:r}=await U.rpc("clone_attract_kit_template",{_template_id:t});if(r)throw r;return n},onSuccess:()=>s.invalidateQueries({queryKey:C9})})}function NWt(s){return`${typeof window<"u"?window.location.origin:""}/attract-kit/${s}`}function s_t(){const{kits:s}=LV(),{data:t=[]}=jWt(),{followUps:n}=NF(),r=j.useMemo(()=>{const l=o=>t.filter(c=>c.event_type===o).length;return{published:s.filter(o=>o.status==="published").length,drafts:s.filter(o=>o.status==="draft").length,views:l("page_view"),downloads:l("file_download"),cta:l("primary_cta_click"),questions:l("question_submitted")}},[s,t]),a=t.slice(0,8),i=n.filter(l=>!l.completed_at&&l.touch_type==="kit_engagement").slice(0,6);return e.jsxs("div",{className:"space-y-6",children:[e.jsx(nm,{eyebrow:"Pillar 03 · Provide",title:"Give more value than any agent expected.",description:"Package the value you already share into beautiful, trackable kits. See exactly which value creates conversations.",actions:e.jsxs("div",{className:"flex gap-2",children:[e.jsx($,{variant:"outline",asChild:!0,className:"rounded-full",children:e.jsxs(Wn,{to:"/attract/provide/kits/templates",children:[e.jsx(g1,{className:"h-4 w-4 mr-2"}),"Starter library"]})}),e.jsx($,{asChild:!0,className:"rounded-full bg-gradient-to-r from-violet-600 to-indigo-600",children:e.jsxs(Wn,{to:"/attract/provide/kits/new",children:[e.jsx(sn,{className:"h-4 w-4 mr-2"}),"New kit"]})})]})}),e.jsx(_e,{className:"p-6 md:p-8 rounded-2xl bg-gradient-to-br from-teal-50 via-violet-50 to-indigo-50 border-slate-200",children:e.jsxs("div",{className:"flex items-start gap-4 flex-wrap",children:[e.jsx("div",{className:"h-12 w-12 rounded-2xl bg-white grid place-items-center shadow-sm",children:e.jsx(pR,{className:"h-6 w-6 text-teal-600"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"text-[15px] font-semibold text-slate-900",children:"Resource Kits — the flagship of Provide"}),e.jsx("p",{className:"text-[13.5px] text-slate-700 mt-1 max-w-3xl",children:"Bundle 3–7 pieces of real value (scripts, checklists, videos, tools) into a beautiful shareable kit. Send a personalized link to an agent, then let engagement recommend the next relationship touch. No pressure. Just real value that compounds."}),e.jsxs("div",{className:"flex gap-2 mt-4",children:[e.jsx($,{asChild:!0,size:"sm",className:"bg-gradient-to-r from-violet-600 to-indigo-600",children:e.jsx(Wn,{to:"/attract/provide/kits/new",children:"Start a kit"})}),e.jsx($,{variant:"outline",size:"sm",asChild:!0,children:e.jsx(Wn,{to:"/attract/provide/kits/templates",children:"Browse 10 starter kits"})})]})]})]})}),e.jsx(_e,{className:"p-6 rounded-2xl border-slate-200",children:e.jsxs("div",{className:"flex items-start gap-4 flex-wrap",children:[e.jsx("div",{className:"h-12 w-12 rounded-2xl bg-violet-50 grid place-items-center",children:e.jsx(dn,{className:"h-6 w-6 text-violet-600"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"text-[15px] font-semibold text-slate-900",children:"Masterclass Builder"}),e.jsx("p",{className:"text-[13.5px] text-slate-700 mt-1 max-w-3xl",children:"Turn what you already know into a 45-minute teaching moment. Build the curriculum, workbook, promotion drafts and run-of-show — then convert it into a Connect event or a Resource Kit in one click."}),e.jsx("div",{className:"flex gap-2 mt-4",children:e.jsx($,{asChild:!0,size:"sm",className:"bg-gradient-to-r from-violet-600 to-indigo-600",children:e.jsx(Wn,{to:"/attract/provide/masterclasses",children:"Open Masterclass Builder"})})})]})]})}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-6 gap-3",children:[e.jsx(t9,{label:"Published",value:r.published}),e.jsx(t9,{label:"Drafts",value:r.drafts}),e.jsx(t9,{label:"Views",value:r.views,icon:ga}),e.jsx(t9,{label:"Downloads",value:r.downloads,icon:di}),e.jsx(t9,{label:"CTA clicks",value:r.cta,icon:uu}),e.jsx(t9,{label:"Questions",value:r.questions,icon:Ed})]}),e.jsxs("div",{className:"grid grid-cols-1 xl:grid-cols-3 gap-6",children:[e.jsxs(_e,{className:"p-5 rounded-2xl xl:col-span-2",children:[e.jsxs("div",{className:"flex items-center justify-between mb-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[11px] uppercase tracking-widest text-violet-700 font-semibold",children:"Recent kit engagement"}),e.jsx("div",{className:"text-[12.5px] text-slate-500",children:"Live signals from agents opening your value."})]}),e.jsx($,{variant:"outline",size:"sm",asChild:!0,children:e.jsxs(Wn,{to:"/attract/provide/kits",children:["View kits ",e.jsx(ni,{className:"h-3.5 w-3.5 ml-1"})]})})]}),a.length===0?e.jsx("div",{className:"text-sm text-slate-500 py-8 text-center border border-dashed rounded-xl",children:"No engagement yet. Share a published kit to start seeing activity."}):e.jsx("div",{className:"space-y-2",children:a.map(l=>e.jsxs("div",{className:"flex items-center justify-between border-b py-2 text-[13px]",children:[e.jsx("div",{className:"capitalize",children:l.event_type.replace(/_/g," ")}),e.jsx("div",{className:"text-slate-500 text-[11.5px]",children:fc(new Date(l.created_at),{addSuffix:!0})})]},l.id))})]}),e.jsxs(_e,{className:"p-5 rounded-2xl",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-widest text-violet-700 font-semibold mb-2",children:"Recommended follow-ups"}),i.length===0?e.jsx("div",{className:"text-sm text-slate-500 py-6 text-center border border-dashed rounded-xl",children:"We'll surface follow-ups here as agents engage."}):e.jsx("div",{className:"space-y-2",children:i.map(l=>e.jsxs("div",{className:"border rounded-lg p-2.5 text-[12.5px]",children:[e.jsx("div",{className:"font-medium text-slate-900 line-clamp-2",children:l.title}),l.due_at&&e.jsxs("div",{className:"text-slate-500 text-[11px] mt-1",children:["Due ",fc(new Date(l.due_at),{addSuffix:!0})]})]},l.id))})]})]}),e.jsxs(_e,{className:"p-5 rounded-2xl",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:"My kits"}),e.jsx($,{size:"sm",variant:"ghost",asChild:!0,children:e.jsxs(Wn,{to:"/attract/provide/kits",children:["See all ",e.jsx(ni,{className:"h-3.5 w-3.5 ml-1"})]})})]}),s.length===0?e.jsxs("div",{className:"text-sm text-slate-500 py-8 text-center border border-dashed rounded-xl",children:["No kits yet. ",e.jsx(Wn,{to:"/attract/provide/kits/templates",className:"text-violet-700 underline",children:"Start from a template"}),"."]}):e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-3",children:s.slice(0,6).map(l=>e.jsxs(Wn,{to:`/attract/provide/kits/${l.id}/edit`,className:"block p-4 rounded-xl border hover:border-violet-300 hover:shadow-sm transition",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx($e,{variant:"outline",className:"capitalize",children:l.status}),l.pillar&&e.jsx($e,{variant:"secondary",className:"capitalize",children:l.pillar})]}),e.jsx("div",{className:"font-semibold text-slate-900 line-clamp-2",children:l.title}),l.description&&e.jsx("div",{className:"text-[12.5px] text-slate-500 line-clamp-2 mt-1",children:l.description})]},l.id))})]}),e.jsx(kF,{})]})}function t9({label:s,value:t,icon:n}){return e.jsxs(_e,{className:"p-4 rounded-2xl",children:[n&&e.jsx(n,{className:"h-4 w-4 text-violet-600"}),e.jsx("div",{className:"mt-1 text-[20px] font-semibold tabular-nums text-slate-900",children:t}),e.jsx("div",{className:"text-[11.5px] text-slate-500",children:s})]})}function n_t(){return e.jsx(aQe,{pillar:"04",title:"Connect",accent:"#9333ea",icon:fR,tagline:"Real relationships. On a rhythm. For years.",intro:"Connect is the pillar that makes the other three matter. It's showing up in the small, consistent ways real friendships require — birthdays, coffees, check-ins, celebrations.",stats:[{label:"Coffees This Q",value:14},{label:"Events Hosted",value:3},{label:"Birthdays Sent",value:22},{label:"On Cadence",value:"87%"}],tools:[{key:"coffee_meetings",icon:Tb,title:"Coffee & Meetings",description:"The coffees to book this month, tracked as follow-ups in your Follow-Up Center.",to:"/attract/follow-up"},{key:"event_engine",icon:ia,title:"Attraction Events",description:"Design intimate gatherings — happy hours, dinners, mastermind lunches — with registration and check-in.",to:"/attract/events"},{key:"milestones",icon:np,title:"Milestones & Celebrations",description:"Never miss a birthday, license anniversary, or business milestone for a prospective agent.",to:"/attract/connect/milestones"},{key:"checkins",icon:Ed,title:"Personal Check-Ins",description:"Relationship-first check-ins surfaced by your intelligence layer, ranked by signal.",to:"/attract/opportunities"},{key:"circles",icon:t1,title:"Agent Circles",description:"Small peer groups you host quarterly — built on the Connect Event Engine.",to:"/attract/events/new"}]})}const pHn=[{key:"coffee",label:"Coffee & Conversation",icon:Tb,tone:"from-amber-500 to-orange-500",description:"A 1:1 or 3-person coffee where the goal is one real conversation."},{key:"roundtable",label:"Agent Roundtable",icon:t1,tone:"from-violet-500 to-indigo-500",description:"4–6 agents share what is actually working right now."},{key:"mastermind",label:"Mastermind",icon:dn,tone:"from-fuchsia-500 to-pink-500",description:"A quarterly small group solving each other’s biggest questions."},{key:"workshop",label:"Workshop / Webinar",icon:Mu,tone:"from-sky-500 to-blue-500",description:"A live hands-on session that delivers one clear outcome."},{key:"dinner",label:"Dinner or Happy Hour",icon:iY,tone:"from-rose-500 to-red-500",description:"The relationship-first gathering. No agenda, just presence."},{key:"networking_plan",label:"Networking Game Plan",icon:fR,tone:"from-teal-500 to-emerald-500",description:"Not an event — a plan for the next 5 rooms you will walk into."}];function fHn(){const s=Vn(),{data:t=[]}=FTe(),{followUps:n}=NF(),{agents:r}=M0(),a=j.useMemo(()=>{const l=new Date,o=Bd(l,7),c=t.filter(m=>m.status==="published"&&Pb(new Date(m.starts_at),l)),d=t.filter(m=>m.status==="draft").length,u=t.reduce((m,p)=>m+(Pb(new Date(p.created_at),Bd(l,-7))?p.registration_count:0),0),h=n.filter(m=>!m.completed_at&&m.due_at&&aw(new Date(m.due_at),o)&&(m.touch_type==="event_followup"||m.touch_type==="event_no_show")).length;return{upcoming:c,draftsNeedingInvites:d,regs:u,dueSoon:h}},[t,n]),i=a.upcoming[0];return e.jsxs("div",{className:"space-y-8",children:[e.jsxs("div",{className:"flex flex-col md:flex-row md:items-center md:justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-violet-600 font-semibold mb-2",children:"Pillar 04 · Connect"}),e.jsx("h1",{className:"text-3xl md:text-[34px] font-semibold tracking-tight text-slate-900",children:"Real events. Small rooms. Long relationships."}),e.jsx("p",{className:"text-slate-600 mt-1.5 max-w-2xl",children:"Build the room, invite personally, host with care, capture one honest note, and follow up within 48 hours."})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs($,{variant:"outline",className:"rounded-full",onClick:()=>s("/attract/events"),children:[e.jsx(ia,{className:"h-4 w-4 mr-2"})," All events"]}),e.jsxs($,{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(sn,{className:"h-4 w-4 mr-2"})," Create an event"]})]})]}),e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[{label:"Upcoming events",value:a.upcoming.length,icon:ia,tone:"text-violet-700 bg-violet-100"},{label:"Drafts needing invites",value:a.draftsNeedingInvites,icon:Br,tone:"text-amber-700 bg-amber-100"},{label:"Registrations this week",value:a.regs,icon:Il,tone:"text-emerald-700 bg-emerald-100"},{label:"48-hour follow-ups due",value:a.dueSoon,icon:Jh,tone:"text-rose-700 bg-rose-100"}].map(l=>e.jsxs(_e,{className:"p-5 rounded-2xl border-slate-200 bg-white",children:[e.jsx("div",{className:`h-9 w-9 rounded-xl grid place-items-center ${l.tone}`,children:e.jsx(l.icon,{className:"h-4.5 w-4.5"})}),e.jsx("div",{className:"text-[26px] font-semibold tabular-nums mt-3",children:l.value}),e.jsx("div",{className:"text-[12.5px] text-slate-500 mt-0.5",children:l.label})]},l.label))}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-3 gap-6",children:[e.jsxs(_e,{className:"lg:col-span-2 p-6 rounded-2xl border-slate-200 bg-gradient-to-br from-slate-900 to-slate-800 text-white overflow-hidden relative",children:[e.jsx("div",{className:"text-[10.5px] uppercase tracking-widest text-white/60 mb-2",children:"Your next event"}),i?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"text-xl md:text-2xl font-semibold",children:i.title}),e.jsxs("div",{className:"text-white/70 mt-1",children:[Hs(new Date(i.starts_at),"EEE, MMM d · h:mm a")," · ",i.format.replace("_"," ")]}),e.jsxs("div",{className:"flex flex-wrap gap-2 mt-4",children:[e.jsxs($e,{variant:"secondary",className:"bg-white/10 border-white/10 text-white",children:[i.registration_count," registered"]}),i.capacity&&e.jsxs($e,{variant:"secondary",className:"bg-white/10 border-white/10 text-white",children:[Math.max(0,i.capacity-i.registration_count)," seats left"]})]}),e.jsxs("div",{className:"mt-5 flex gap-2 flex-wrap",children:[e.jsxs($,{size:"sm",className:"rounded-full bg-white text-slate-900 hover:bg-white/90",onClick:()=>s(`/attract/events/${i.id}`),children:["Open command center ",e.jsx(ni,{className:"h-3.5 w-3.5 ml-1"})]}),e.jsx($,{size:"sm",variant:"outline",className:"rounded-full bg-transparent text-white border-white/30 hover:bg-white/10",onClick:()=>s(`/attract/events/${i.id}/checkin`),children:"Mobile check-in"})]})]}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"text-xl font-semibold",children:"No upcoming events yet"}),e.jsx("div",{className:"text-white/70 mt-1",children:"Start with a small coffee. One conversation is enough."}),e.jsx($,{size:"sm",className:"mt-5 rounded-full bg-white text-slate-900 hover:bg-white/90",onClick:()=>s("/attract/events/new?type=coffee"),children:"Plan a coffee"})]})]}),e.jsxs(_e,{className:"p-6 rounded-2xl border-amber-200 bg-amber-50",children:[e.jsx("div",{className:"text-[10.5px] uppercase tracking-widest text-amber-700 font-semibold mb-2",children:"Reminder"}),e.jsx("div",{className:"text-[15px] text-slate-900 leading-relaxed",children:"Build relationships first. Personalize every invitation and follow-up, and verify brokerage and compensation information before sharing."})]})]}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[11px] uppercase tracking-widest text-slate-500 font-semibold",children:"Quick starts"}),e.jsx("div",{className:"text-lg font-semibold text-slate-900",children:"What kind of room do you want to build?"})]}),e.jsxs(Wn,{to:"/attract/events/new",className:"text-[13px] text-violet-700 hover:underline flex items-center gap-1",children:["Start from scratch ",e.jsx(Ja,{className:"h-3.5 w-3.5"})]})]}),e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4",children:pHn.map(l=>e.jsxs("button",{onClick:()=>s(`/attract/events/new?type=${l.key}`),className:"group text-left rounded-2xl border border-slate-200 bg-white p-5 hover:border-violet-300 hover:shadow-md transition",children:[e.jsx("div",{className:`h-10 w-10 rounded-xl grid place-items-center bg-gradient-to-br ${l.tone} text-white shadow-sm`,children:e.jsx(l.icon,{className:"h-5 w-5"})}),e.jsx("div",{className:"text-[15px] font-semibold text-slate-900 mt-3",children:l.label}),e.jsx("div",{className:"text-[13px] text-slate-600 mt-1 leading-snug",children:l.description}),e.jsxs("div",{className:"text-[12px] text-violet-700 mt-3 flex items-center gap-1 opacity-0 group-hover:opacity-100 transition",children:["Start planning ",e.jsx(ni,{className:"h-3 w-3"})]})]},l.key))})]}),e.jsxs(_e,{className:"p-6 rounded-2xl border-slate-200 bg-white",children:[e.jsxs("div",{className:"flex items-center justify-between mb-4",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[11px] uppercase tracking-widest text-slate-500 font-semibold",children:"Personal connection goals"}),e.jsx("div",{className:"text-lg font-semibold text-slate-900",children:"This week"})]}),e.jsx($,{variant:"outline",size:"sm",className:"rounded-full",onClick:()=>s("/attract/follow-up"),children:"Open Follow-Up Center"})]}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4",children:[{label:"Coffees booked",target:3,actual:a.upcoming.filter(l=>(l.event_type_key||l.event_type)==="coffee").length,icon:Tb,tone:"text-amber-600 bg-amber-50"},{label:"Roundtables/masterminds",target:1,actual:a.upcoming.filter(l=>["roundtable","mastermind"].includes(l.event_type_key||l.event_type)).length,icon:dn,tone:"text-violet-600 bg-violet-50"},{label:"People in pipeline",target:r.length,actual:r.length,icon:t1,tone:"text-emerald-600 bg-emerald-50"}].map(l=>e.jsxs("div",{className:"rounded-xl border border-slate-100 p-4",children:[e.jsx("div",{className:`h-8 w-8 rounded-lg grid place-items-center ${l.tone}`,children:e.jsx(l.icon,{className:"h-4 w-4"})}),e.jsxs("div",{className:"text-[22px] font-semibold tabular-nums mt-2 leading-none",children:[l.actual,e.jsxs("span",{className:"text-slate-400 text-[15px] font-normal",children:[" / ",l.target]})]}),e.jsx("div",{className:"text-[12px] text-slate-500 mt-1",children:l.label})]},l.label))})]})]})}function xHn(){const s=Vn(),{data:t=[],isLoading:n}=FTe(),r=AVn(),a=kVn(),[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.jsxs("div",{children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-violet-600 font-semibold mb-2",children:"Connect · Events"}),e.jsx("h1",{className:"text-3xl font-semibold tracking-tight text-slate-900",children:"Events"}),e.jsx("p",{className:"text-slate-600 mt-1",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(Vr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-slate-400"}),e.jsx(be,{placeholder:"Search events",className:"pl-9 rounded-full w-[240px] bg-white",value:o,onChange:u=>c(u.target.value)})]}),e.jsxs($,{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(sn,{className:"h-4 w-4 mr-2"})," New event"]})]})]}),e.jsxs(ua,{value:i,onValueChange:u=>l(u),children:[e.jsxs(ha,{className:"rounded-full bg-white border border-slate-200",children:[e.jsxs(Qt,{value:"all",className:"rounded-full",children:["All (",t.length,")"]}),e.jsxs(Qt,{value:"draft",className:"rounded-full",children:["Drafts (",t.filter(u=>u.status==="draft").length,")"]}),e.jsxs(Qt,{value:"published",className:"rounded-full",children:["Published (",t.filter(u=>u.status==="published").length,")"]}),e.jsxs(Qt,{value:"completed",className:"rounded-full",children:["Completed (",t.filter(u=>u.status==="completed").length,")"]})]}),e.jsx(Jt,{value:i,className:"mt-5",children:n?e.jsx(_e,{className:"p-12 rounded-2xl text-center text-slate-500",children:"Loading events…"}):d.length===0?e.jsxs(_e,{className:"p-12 rounded-2xl text-center border-dashed",children:[e.jsx(ia,{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($,{className:"mt-4 rounded-full",onClick:()=>s("/attract/events/new"),children:[e.jsx(sn,{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(_e,{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($e,{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($e,{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:Hs(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(Xr,{className:"h-3.5 w-3.5"})," Virtual"]}):u.format==="hybrid"?e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Xr,{className:"h-3.5 w-3.5"})," Hybrid"]}):e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(ai,{className:"h-3.5 w-3.5"})," ",u.location||"In person"]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(qn,{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($,{variant:"ghost",size:"sm",className:"h-8 rounded-full text-slate-500",onClick:()=>r.mutate(u.id),children:[e.jsx(Ca,{className:"h-3.5 w-3.5 mr-1"})," Duplicate"]}),u.status==="published"&&u.public_slug&&e.jsxs($,{variant:"ghost",size:"sm",className:"h-8 rounded-full text-slate-500",onClick:()=>{navigator.clipboard.writeText(zTe(u.public_slug)),ae.success("Registration link copied")},children:[e.jsx(Tr,{className:"h-3.5 w-3.5 mr-1"})," Link"]})]}),e.jsx($,{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(Pn,{className:"h-3.5 w-3.5"})})]})]})]},u.id))})})]})]})}const gHn=[{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 r_t(){const{eventId:s}=Vi(),t=Vn(),[n]=oc(),r=n.get("type"),a=!!s,{data:i}=sQe(s),{data:l=[]}=cWt(),{kits:o}=LV(),c=dWt(),d=uWt(),[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=b=>h(v=>({...v,...b})),p=j.useMemo(()=>l.slice(0,4),[l]),x=b=>{m({title:b.title,description:b.description,event_type_key:b.event_type_key,related_pillar:b.related_pillar,intended_audience:b.intended_audience,agenda:b.suggested_agenda||[],learning_outcomes:b.suggested_outcomes||[],registration_questions:b.suggested_questions||[],confirmation_message:b.suggested_confirmation}),ae.success(`Loaded "${b.title}"`)},g=async(b={})=>{const v={...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:b.publish?"published":u.status||"draft"};if(a)await d.mutateAsync({id:s,patch:v}),ae.success(b.publish?"Published":"Saved");else{const N=await c.mutateAsync(v);ae.success(b.publish?"Event published":"Draft saved"),t(`/attract/events/${N.id}${b.publish?"":"/edit"}`,{replace:!0})}},y=i!=null&&i.public_slug?zTe(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($,{variant:"ghost",size:"sm",className:"rounded-full",onClick:()=>t("/attract/events"),children:[e.jsx(ka,{className:"h-4 w-4 mr-2"})," All events"]}),e.jsxs("div",{className:"flex items-center gap-2",children:[y&&e.jsxs($,{variant:"outline",size:"sm",className:"rounded-full",onClick:()=>{navigator.clipboard.writeText(y),ae.success("Registration link copied")},children:[e.jsx(kc,{className:"h-3.5 w-3.5 mr-2"})," Copy link"]}),e.jsxs($,{variant:"outline",size:"sm",className:"rounded-full",onClick:()=>g(),children:[e.jsx(Jo,{className:"h-4 w-4 mr-2"})," Save draft"]}),e.jsxs($,{size:"sm",className:"rounded-full bg-gradient-to-r from-violet-600 to-indigo-600",onClick:()=>g({publish:!0}),children:[e.jsx(w0,{className:"h-4 w-4 mr-2"})," ",(i==null?void 0:i.status)==="published"?"Update published":"Publish"]})]})]}),!a&&p.length>0&&e.jsxs(_e,{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(dn,{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(b=>e.jsxs("button",{onClick:()=>x(b),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:b.title}),e.jsx("div",{className:"text-[12px] text-slate-600 line-clamp-2 mt-0.5",children:b.description})]},b.id))})]}),e.jsxs(_e,{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(se,{children:"Title"}),e.jsx(be,{value:u.title,onChange:b=>m({title:b.target.value}),placeholder:"Coffee & Systems Roundtable"})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Event type"}),e.jsxs(vs,{value:u.event_type_key,onValueChange:b=>m({event_type_key:b}),children:[e.jsx(gs,{children:e.jsx(bs,{})}),e.jsx(ys,{children:gHn.map(b=>e.jsx(Ye,{value:b.key,children:b.label},b.key))})]})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Related pillar"}),e.jsxs(vs,{value:u.related_pillar||"connect",onValueChange:b=>m({related_pillar:b}),children:[e.jsx(gs,{children:e.jsx(bs,{})}),e.jsxs(ys,{children:[e.jsx(Ye,{value:"produce",children:"Produce"}),e.jsx(Ye,{value:"influence",children:"Influence"}),e.jsx(Ye,{value:"provide",children:"Provide"}),e.jsx(Ye,{value:"connect",children:"Connect"})]})]})]}),e.jsxs("div",{className:"md:col-span-2",children:[e.jsx(se,{children:"Intended audience"}),e.jsx(be,{value:u.intended_audience||"",onChange:b=>m({intended_audience:b.target.value}),placeholder:"Producing agents 1–5 years in"})]}),e.jsxs("div",{className:"md:col-span-2",children:[e.jsx(se,{children:"Description"}),e.jsx(Is,{rows:4,value:u.description||"",onChange:b=>m({description:b.target.value}),placeholder:"What is this event and why does it matter?"})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Starts at"}),e.jsx(be,{type:"datetime-local",value:u.starts_at||"",onChange:b=>m({starts_at:b.target.value})})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Ends at"}),e.jsx(be,{type:"datetime-local",value:u.ends_at||"",onChange:b=>m({ends_at:b.target.value})})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Time zone"}),e.jsxs(vs,{value:u.timezone||"America/New_York",onValueChange:b=>m({timezone:b}),children:[e.jsx(gs,{children:e.jsx(bs,{})}),e.jsx(ys,{children:["America/New_York","America/Chicago","America/Denver","America/Los_Angeles","America/Phoenix"].map(b=>e.jsx(Ye,{value:b,children:b},b))})]})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Format"}),e.jsxs(vs,{value:u.format,onValueChange:b=>m({format:b}),children:[e.jsx(gs,{children:e.jsx(bs,{})}),e.jsxs(ys,{children:[e.jsx(Ye,{value:"in_person",children:"In person"}),e.jsx(Ye,{value:"virtual",children:"Virtual"}),e.jsx(Ye,{value:"hybrid",children:"Hybrid"})]})]})]}),u.format!=="virtual"&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{children:[e.jsx(se,{children:"Venue / location name"}),e.jsx(be,{value:u.location||"",onChange:b=>m({location:b.target.value}),placeholder:"Rise Coffee — Downtown"})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Address"}),e.jsx(be,{value:u.address||"",onChange:b=>m({address:b.target.value}),placeholder:"123 Main St, City, ST"})]})]}),u.format!=="in_person"&&e.jsxs("div",{className:"md:col-span-2",children:[e.jsx(se,{children:"Virtual meeting URL"}),e.jsx(be,{value:u.virtual_url||"",onChange:b=>m({virtual_url:b.target.value}),placeholder:"https://zoom.us/…"})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Capacity (optional)"}),e.jsx(be,{type:"number",value:u.capacity,onChange:b=>m({capacity:b.target.value}),placeholder:"No limit"})]}),e.jsxs("div",{className:"flex items-center gap-3 pt-6",children:[e.jsx(Tn,{checked:u.waitlist_enabled,onCheckedChange:b=>m({waitlist_enabled:b}),id:"wl"}),e.jsx(se,{htmlFor:"wl",className:"cursor-pointer",children:"Allow waitlist if full"})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Host name (as shown publicly)"}),e.jsx(be,{value:u.host_name||"",onChange:b=>m({host_name:b.target.value}),placeholder:"Jeremy from LevelUp"})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Cover image URL"}),e.jsx(be,{value:u.cover_image_url||"",onChange:b=>m({cover_image_url:b.target.value}),placeholder:"https://…"})]})]})]}),e.jsxs(_e,{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(se,{children:"Agenda"}),e.jsxs($,{size:"sm",variant:"ghost",className:"rounded-full",onClick:()=>m({agenda:[...u.agenda||[],{time:"",item:""}]}),children:[e.jsx(sn,{className:"h-3.5 w-3.5 mr-1"})," Add item"]})]}),e.jsxs("div",{className:"space-y-2",children:[(u.agenda||[]).map((b,v)=>e.jsxs("div",{className:"flex gap-2",children:[e.jsx(be,{className:"w-24",value:b.time||"",onChange:N=>{const C=[...u.agenda];C[v]={...C[v],time:N.target.value},m({agenda:C})},placeholder:"0:00"}),e.jsx(be,{value:b.item||"",onChange:N=>{const C=[...u.agenda];C[v]={...C[v],item:N.target.value},m({agenda:C})},placeholder:"What happens here"}),e.jsx($,{size:"icon",variant:"ghost",onClick:()=>m({agenda:u.agenda.filter((N,C)=>C!==v)}),children:e.jsx(pr,{className:"h-4 w-4"})})]},v)),(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(Hl,{}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx(se,{children:"What attendees will receive"}),e.jsxs($,{size:"sm",variant:"ghost",className:"rounded-full",onClick:()=>m({learning_outcomes:[...u.learning_outcomes||[],""]}),children:[e.jsx(sn,{className:"h-3.5 w-3.5 mr-1"})," Add outcome"]})]}),e.jsx("div",{className:"space-y-2",children:(u.learning_outcomes||[]).map((b,v)=>e.jsxs("div",{className:"flex gap-2",children:[e.jsx(be,{value:b,onChange:N=>{const C=[...u.learning_outcomes];C[v]=N.target.value,m({learning_outcomes:C})},placeholder:"One clear, honest outcome"}),e.jsx($,{size:"icon",variant:"ghost",onClick:()=>m({learning_outcomes:u.learning_outcomes.filter((N,C)=>C!==v)}),children:e.jsx(pr,{className:"h-4 w-4"})})]},v))})]})]})]}),e.jsxs(_e,{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(se,{children:"Registration questions"}),e.jsxs($,{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(sn,{className:"h-3.5 w-3.5 mr-1"})," Add question"]})]}),e.jsx("div",{className:"space-y-2",children:(u.registration_questions||[]).map((b,v)=>e.jsxs("div",{className:"flex gap-2 items-center",children:[e.jsx(be,{className:"flex-1",value:b.label,onChange:N=>{const C=[...u.registration_questions];C[v]={...C[v],label:N.target.value,key:b.key||`q${v+1}`},m({registration_questions:C})},placeholder:"Question shown to registrants"}),e.jsxs(vs,{value:b.type,onValueChange:N=>{const C=[...u.registration_questions];C[v]={...C[v],type:N},m({registration_questions:C})},children:[e.jsx(gs,{className:"w-32",children:e.jsx(bs,{})}),e.jsxs(ys,{children:[e.jsx(Ye,{value:"text",children:"Short text"}),e.jsx(Ye,{value:"long",children:"Long text"})]})]}),e.jsx($,{size:"icon",variant:"ghost",onClick:()=>m({registration_questions:u.registration_questions.filter((N,C)=>C!==v)}),children:e.jsx(pr,{className:"h-4 w-4"})})]},v))})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Confirmation message (shown after registration)"}),e.jsx(Is,{rows:3,value:u.confirmation_message||"",onChange:b=>m({confirmation_message:b.target.value}),placeholder:"You are in — come with one honest question."})]})]})]}),e.jsxs(_e,{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(se,{children:"Attach a Resource Kit"}),e.jsxs(vs,{value:u.resource_kit_id||"none",onValueChange:b=>m({resource_kit_id:b==="none"?null:b}),children:[e.jsx(gs,{children:e.jsx(bs,{placeholder:"None"})}),e.jsxs(ys,{children:[e.jsx(Ye,{value:"none",children:"None"}),(o||[]).map(b=>e.jsx(Ye,{value:b.id,children:b.title},b.id))]})]})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Deliver kit"}),e.jsxs(vs,{value:u.kit_delivery_trigger||"after_attendance",onValueChange:b=>m({kit_delivery_trigger:b}),children:[e.jsx(gs,{children:e.jsx(bs,{})}),e.jsxs(ys,{children:[e.jsx(Ye,{value:"on_registration",children:"On registration"}),e.jsx(Ye,{value:"on_confirmation",children:"On confirmation"}),e.jsx(Ye,{value:"on_check_in",children:"At check-in"}),e.jsx(Ye,{value:"after_attendance",children:"After attendance"}),e.jsx(Ye,{value:"manual",children:"Only manually"})]})]})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Default follow-up window (hours)"}),e.jsx(be,{type:"number",value:u.followup_hours??48,onChange:b=>m({followup_hours:Number(b.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(_e,{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($e,{variant:"secondary",className:"bg-rose-50 text-rose-700 border-rose-200",children:"Add title and start time"}),(u.agenda||[]).length===0&&e.jsx($e,{variant:"secondary",className:"bg-amber-50 text-amber-700 border-amber-200",children:"No agenda yet"}),(u.learning_outcomes||[]).length===0&&e.jsx($e,{variant:"secondary",className:"bg-amber-50 text-amber-700 border-amber-200",children:"No stated outcomes"}),!u.resource_kit_id&&e.jsx($e,{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($,{variant:"outline",className:"rounded-full",onClick:()=>g(),children:[e.jsx(Jo,{className:"h-4 w-4 mr-2"})," Save draft"]}),e.jsxs($,{className:"rounded-full bg-gradient-to-r from-violet-600 to-indigo-600",onClick:()=>g({publish:!0}),children:[e.jsx(w0,{className:"h-4 w-4 mr-2"})," Publish"]})]})]})]})}const HNe=s=>s?[s.first_name,s.last_name].filter(Boolean).join(" "):"";function yHn(){const{eventId:s}=Vi(),t=Vn(),{data:n}=sQe(s),{data:r=[]}=lWt(s),{data:a=[]}=jVn(s),{data:i=[]}=NVn(s),{agents:l}=M0(),{data:o=[]}=cWt(),c=hWt(),d=SVn(),u=CVn(),h=uWt(),m=j.useMemo(()=>{const g=r.length,y=r.filter(I=>I.status==="registered"||I.status==="confirmed").length,b=r.filter(I=>I.status==="attended").length,v=r.filter(I=>I.status==="no_show").length,N=r.filter(I=>I.status==="waitlisted").length,C=y+b+v,A=C>0?Math.round(b/C*100):0,T=a.length>0?Math.round(a.filter(I=>I.viewed_at).length/a.length*100):0,P=r.filter(I=>I.followup_status==="done").length,M=b>0?Math.round(P/b*100):0;return{total:g,registered:y,attended:b,noShow:v,waitlist:N,attendRate:A,invView:T,followed:P,followedRate:M}},[r,a]);if(!n)return e.jsx("div",{className:"p-8 text-slate-500",children:"Loading…"});const p=n.public_slug?zTe(n.public_slug):null,x=()=>{const g=new Blob([mWt(n)],{type:"text/calendar"}),y=URL.createObjectURL(g),b=document.createElement("a");b.href=y,b.download=`${n.public_slug||"event"}.ics`,b.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($,{variant:"ghost",size:"sm",className:"rounded-full",onClick:()=>t("/attract/events"),children:[e.jsx(ka,{className:"h-4 w-4 mr-2"})," All events"]}),e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsxs($,{variant:"outline",size:"sm",className:"rounded-full",onClick:x,children:[e.jsx(di,{className:"h-3.5 w-3.5 mr-2"})," ICS"]}),p&&e.jsxs($,{variant:"outline",size:"sm",className:"rounded-full",onClick:()=>{navigator.clipboard.writeText(p),ae.success("Link copied")},children:[e.jsx(Ca,{className:"h-3.5 w-3.5 mr-2"})," Copy link"]}),p&&e.jsx($,{variant:"outline",size:"sm",className:"rounded-full",asChild:!0,children:e.jsxs("a",{href:p,target:"_blank",rel:"noreferrer",children:[e.jsx(Tr,{className:"h-3.5 w-3.5 mr-2"})," Preview page"]})}),e.jsxs($,{size:"sm",className:"rounded-full",onClick:()=>t(`/attract/events/${n.id}/checkin`),children:[e.jsx(Rx,{className:"h-3.5 w-3.5 mr-2"})," Check-in mode"]}),e.jsx($,{size:"sm",variant:"outline",className:"rounded-full",onClick:()=>t(`/attract/events/${n.id}/edit`),children:"Edit"})]})]}),e.jsx(_e,{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($e,{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($e,{variant:"secondary",className:"bg-white/10 border-white/10 text-white capitalize",children:n.related_pillar}),n.event_type_key&&e.jsx($e,{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(ia,{className:"h-4 w-4"})," ",Hs(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(Xr,{className:"h-4 w-4"})," Virtual"]}):e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(ai,{className:"h-4 w-4"})," ",n.location||"In person"]}),e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(qn,{className:"h-4 w-4"})," ",n.registration_count," registered",n.capacity?` / ${n.capacity}`:""]})]})]}),n.status==="draft"&&e.jsx($,{className:"rounded-full bg-white text-slate-900 hover:bg-white/90",onClick:async()=>{await h.mutateAsync({id:n.id,patch:{status:"published"}}),ae.success("Published")},children:"Publish now"}),n.status==="published"&&new Date(n.starts_at){await h.mutateAsync({id:n.id,patch:{status:"completed"}}),ae.success("Marked completed")},children:"Mark completed"})]})}),e.jsxs(ua,{defaultValue:"overview",children:[e.jsxs(ha,{className:"rounded-full bg-white border border-slate-200 flex-wrap h-auto",children:[e.jsx(Qt,{value:"overview",className:"rounded-full",children:"Overview"}),e.jsxs(Qt,{value:"invitations",className:"rounded-full",children:["Invitations (",a.length,")"]}),e.jsxs(Qt,{value:"registrations",className:"rounded-full",children:["Registrations (",r.length,")"]}),e.jsxs(Qt,{value:"notes",className:"rounded-full",children:["Notes (",i.length,")"]}),e.jsx(Qt,{value:"kit",className:"rounded-full",children:"Resource Kit"}),e.jsx(Qt,{value:"followup",className:"rounded-full",children:"48-hour follow-up"}),e.jsx(Qt,{value:"analytics",className:"rounded-full",children:"Analytics"})]}),e.jsxs(Jt,{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(uj,{icon:qn,label:"Registered",value:m.registered+m.attended}),e.jsx(uj,{icon:oa,label:"Attended",value:m.attended}),e.jsx(uj,{icon:ml,label:"Attendance rate",value:`${m.attendRate}%`}),e.jsx(uj,{icon:Jh,label:"Follow-up completion",value:`${m.followedRate}%`})]}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-3 gap-6",children:[e.jsxs(_e,{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((g,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:g.time||""}),e.jsx("span",{className:"text-slate-800",children:g.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((g,y)=>e.jsxs("li",{className:"text-[13.5px] text-slate-700 flex gap-2",children:[e.jsx(oa,{className:"h-4 w-4 text-emerald-600 shrink-0 mt-0.5"})," ",g]},y))})]})]}),e.jsxs(_e,{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($,{size:"sm",variant:"outline",className:"rounded-full mt-2 w-full",onClick:()=>{navigator.clipboard.writeText(p),ae.success("Copied")},children:[e.jsx(Ca,{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($,{size:"sm",variant:"outline",className:"rounded-full w-full",onClick:()=>t(`/attract/events/${n.id}/checkin`),children:[e.jsx(Rx,{className:"h-3.5 w-3.5 mr-2"})," Open check-in"]})]})]})]})]}),e.jsx(Jt,{value:"invitations",className:"mt-5",children:e.jsx(vHn,{eventId:n.id,eventSlug:n.public_slug,agents:l,invitations:a,templates:o,onCreate:u.mutate})}),e.jsx(Jt,{value:"registrations",className:"mt-5",children:e.jsx(bHn,{eventId:n.id,attendees:r,onUpsert:c.mutate,checkInToken:n.check_in_token})}),e.jsx(Jt,{value:"notes",className:"mt-5",children:e.jsx(_Hn,{eventId:n.id,attendees:r,notes:i,onCreate:d.mutate})}),e.jsx(Jt,{value:"kit",className:"mt-5",children:e.jsxs(_e,{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($,{variant:"outline",className:"rounded-full mt-4",onClick:()=>t(`/attract/provide/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($,{className:"rounded-full",onClick:()=>t(`/attract/events/${n.id}/edit`),children:"Attach a kit"}),e.jsx($,{variant:"outline",className:"rounded-full",onClick:()=>t("/attract/provide/kits/new"),children:"Create a new kit"})]})]})]})}),e.jsx(Jt,{value:"followup",className:"mt-5",children:e.jsx(wHn,{eventId:n.id,attendees:r,onUpsert:c.mutate})}),e.jsxs(Jt,{value:"analytics",className:"mt-5",children:[e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[e.jsx(uj,{icon:Br,label:"Invitations sent",value:a.length}),e.jsx(uj,{icon:Tr,label:"Invitation view rate",value:`${m.invView}%`}),e.jsx(uj,{icon:qn,label:"Registered",value:m.registered+m.attended}),e.jsx(uj,{icon:oa,label:"Attended",value:m.attended}),e.jsx(uj,{icon:ml,label:"Attendance rate",value:`${m.attendRate}%`}),e.jsx(uj,{icon:Jh,label:"Follow-up complete (48h)",value:`${m.followedRate}%`}),e.jsx(uj,{icon:H3,label:"Notes captured",value:i.length}),e.jsx(uj,{icon:il,label:"Meetings requested",value:r.filter(g=>g.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 uj({icon:s,label:t,value:n}){return e.jsxs(_e,{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 vHn({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"),[x,g]=j.useState(""),y=a==null?void 0:a[0],b=()=>{if(!y)return;const N=m==="sms"?y.suggested_invitation_sms:m==="dm"?y.suggested_invitation_dm:y.suggested_invitation_email,C=t?`${window.location.origin}/attract-event/${t}`:"";g((N||"").replaceAll("{{first_name}}",(c||"friend").split(" ")[0]).replaceAll("{{link}}",C).replaceAll("{{date}}",""))},v=()=>{if(!c||m==="email"&&!u){ae.error("Add a name and email");return}const N=n.find(C=>C.id===l);i({event_id:s,agent_id:l||null,recipient_name:c||HNe(N),recipient_email:u||(N==null?void 0:N.email),channel:m,message_body:x,status:"sent"}),d(""),h(""),g(""),o(""),ae.success("Invitation logged")};return e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-3 gap-6",children:[e.jsxs(_e,{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(se,{children:"Attract agent (optional)"}),e.jsxs(vs,{value:l||"none",onValueChange:N=>{o(N==="none"?"":N);const C=n.find(A=>A.id===N);C&&(d(HNe(C)),h(C.email||""))},children:[e.jsx(gs,{children:e.jsx(bs,{placeholder:"Pick an agent"})}),e.jsxs(ys,{children:[e.jsx(Ye,{value:"none",children:"Guest (not in pipeline)"}),n.map(N=>e.jsx(Ye,{value:N.id,children:HNe(N)},N.id))]})]})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Channel"}),e.jsxs(vs,{value:m,onValueChange:p,children:[e.jsx(gs,{children:e.jsx(bs,{})}),e.jsxs(ys,{children:[e.jsx(Ye,{value:"email",children:"Email"}),e.jsx(Ye,{value:"sms",children:"Text message"}),e.jsx(Ye,{value:"dm",children:"DM"}),e.jsx(Ye,{value:"call",children:"Phone call"}),e.jsx(Ye,{value:"in_person",children:"In person"})]})]})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Recipient name"}),e.jsx(be,{value:c,onChange:N=>d(N.target.value)})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Recipient email"}),e.jsx(be,{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(se,{children:"Message"}),y&&e.jsxs($,{size:"sm",variant:"ghost",className:"rounded-full text-xs",onClick:b,children:[e.jsx(dn,{className:"h-3 w-3 mr-1"})," Draft from template"]})]}),e.jsx(Is,{rows:5,value:x,onChange:N=>g(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($,{variant:"outline",className:"rounded-full",onClick:()=>{x&&(navigator.clipboard.writeText(x),ae.success("Copied"))},children:[e.jsx(Ca,{className:"h-3.5 w-3.5 mr-2"})," Copy message"]}),e.jsxs($,{className:"rounded-full bg-gradient-to-r from-violet-600 to-indigo-600",onClick:v,children:[e.jsx(Br,{className:"h-3.5 w-3.5 mr-2"})," Log invitation"]})]})]})]}),e.jsxs(_e,{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($e,{variant:"secondary",className:"capitalize",children:N.status})]}),e.jsxs("div",{className:"text-[11.5px] text-slate-500 mt-0.5",children:["via ",N.channel," · ",fc(new Date(N.sent_at))," ago",N.view_count>0?` · viewed ${N.view_count}×`:""]})]},N.id))})]})]})}function bHn({eventId:s,attendees:t,onUpsert:n,checkInToken:r}){const[a,i]=j.useState(""),[l,o]=j.useState(""),c=()=>{if(!a){ae.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(""),ae.success("Walk-in added")};return e.jsxs("div",{className:"space-y-5",children:[e.jsxs(_e,{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(be,{placeholder:"Name",value:a,onChange:d=>i(d.target.value)}),e.jsx(be,{placeholder:"Email (optional)",value:l,onChange:d=>o(d.target.value)}),e.jsxs($,{className:"rounded-full md:col-span-2",onClick:c,children:[e.jsx(il,{className:"h-4 w-4 mr-2"})," Add & check in"]})]})]}),e.jsx(_e,{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||HNe(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($e,{variant:"secondary",className:"capitalize",children:d.status}),e.jsxs(vs,{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(gs,{className:"h-8 w-40 text-xs",children:e.jsx(bs,{})}),e.jsx(ys,{children:["invited","registered","confirmed","waitlisted","attended","no_show","cancelled"].map(u=>e.jsx(Ye,{value:u,className:"text-xs",children:u.replace("_"," ")},u))})]}),r&&d.personalized_token&&e.jsx($,{variant:"ghost",size:"sm",className:"rounded-full text-xs",onClick:()=>{navigator.clipboard.writeText(EVn(r,d.personalized_token)),ae.success("Check-in link copied")},children:e.jsx(Ca,{className:"h-3.5 w-3.5"})})]})]},d.id))})})]})}function _Hn({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(""),x=()=>{if(!l.trim()){ae.error("Add a note");return}const g=t.find(y=>y.id===a);r({event_id:s,attendee_id:a||null,agent_id:(g==null?void 0:g.agent_id)||null,note:l,temperature:c,recommended_next_action:m||null,wants_one_on_one:u}),o(""),i(""),p(""),h(!1),ae.success("Note captured")};return e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-3 gap-6",children:[e.jsxs(_e,{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(se,{children:"Attendee (optional)"}),e.jsxs(vs,{value:a||"none",onValueChange:g=>i(g==="none"?"":g),children:[e.jsx(gs,{children:e.jsx(bs,{placeholder:"Anyone in the room"})}),e.jsxs(ys,{children:[e.jsx(Ye,{value:"none",children:"General note"}),t.map(g=>e.jsx(Ye,{value:g.id,children:g.guest_name||g.guest_email},g.id))]})]})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Note"}),e.jsx(Is,{rows:4,value:l,onChange:g=>o(g.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(se,{children:"Relationship temperature"}),e.jsxs(vs,{value:c,onValueChange:d,children:[e.jsx(gs,{children:e.jsx(bs,{})}),e.jsx(ys,{children:["cold","warm","hot"].map(g=>e.jsx(Ye,{value:g,children:g},g))})]})]}),e.jsxs("div",{className:"md:col-span-2",children:[e.jsx(se,{children:"Recommended next action"}),e.jsx(be,{value:m,onChange:g=>p(g.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:g=>h(g.target.checked)}),"They should get a one-on-one conversation"]})]}),e.jsx("div",{className:"flex justify-end mt-4",children:e.jsxs($,{className:"rounded-full bg-gradient-to-r from-violet-600 to-indigo-600",onClick:x,children:[e.jsx(sn,{className:"h-4 w-4 mr-2"})," Save note"]})})]}),e.jsxs(_e,{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(g=>{const y=t.find(b=>b.id===g.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:g.note}),e.jsxs("div",{className:"flex items-center gap-2 mt-2 flex-wrap text-[11px] text-slate-500",children:[g.temperature&&e.jsx($e,{variant:"secondary",className:"capitalize",children:g.temperature}),g.wants_one_on_one&&e.jsx($e,{className:"bg-emerald-500",children:"Wants 1:1"}),g.recommended_next_action&&e.jsxs("span",{children:["Next: ",g.recommended_next_action]})]})]},g.id)})})]})]})}function wHn({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(_e,{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($,{size:"sm",variant:"ghost",className:"rounded-full h-8",onClick:()=>a(d.id,"in_progress"),children:"In progress"}),e.jsx($,{size:"sm",className:"rounded-full h-8 bg-emerald-600 hover:bg-emerald-700",onClick:()=>a(d.id,"done"),children:e.jsx(oa,{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 PV={},jHn=function(){return typeof Promise=="function"&&Promise.prototype&&Promise.prototype.then},kWt={},Ew={};let iQe;const NHn=[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];Ew.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};Ew.getSymbolTotalCodewords=function(t){return NHn[t]};Ew.getBCHDigit=function(s){let t=0;for(;s!==0;)t++,s>>>=1;return t};Ew.setToSJISFunction=function(t){if(typeof t!="function")throw new Error('"toSJISFunc" is not a valid function.');iQe=t};Ew.isKanjiModeEnabled=function(){return typeof iQe<"u"};Ew.toSJIS=function(t){return iQe(t)};var $Te={};(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}}})($Te);function SWt(){this.buffer=[],this.length=0}SWt.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 kHn=SWt;function bte(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)}bte.prototype.set=function(s,t,n,r){const a=s*this.size+t;this.data[a]=n,r&&(this.reservedBit[a]=!0)};bte.prototype.get=function(s,t){return this.data[s*this.size+t]};bte.prototype.xor=function(s,t,n){this.data[s*this.size+t]^=n};bte.prototype.isReserved=function(s,t){return this.reservedBit[s*this.size+t]};var SHn=bte,CWt={};(function(s){const t=Ew.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 AHn=oQe,LWt={},nM={},lQe={};lQe.isValid=function(t){return!isNaN(t)&&t>=1&&t<=40};var G5={};const PWt="[0-9]+",EHn="[A-Z $%*+\\-./:]+";let bQ="(?:[u3000-u303F]|[u3040-u309F]|[u30A0-u30FF]|[uFF00-uFFEF]|[u4E00-u9FAF]|[u2605-u2606]|[u2190-u2195]|u203B|[u2010u2015u2018u2019u2025u2026u201Cu201Du2225u2260]|[u0391-u0451]|[u00A7u00A8u00B1u00B4u00D7u00F7])+";bQ=bQ.replace(/u/g,"\\u");const THn="(?:(?![A-Z0-9 $%*+\\-./:]|"+bQ+`)(?:.|[\r ]))+`;G5.KANJI=new RegExp(bQ,"g");G5.BYTE_KANJI=new RegExp("[^A-Z0-9 $%*+\\-./:]+","g");G5.BYTE=new RegExp(THn,"g");G5.NUMERIC=new RegExp(PWt,"g");G5.ALPHANUMERIC=new RegExp(EHn,"g");const MHn=new RegExp("^"+bQ+"$"),LHn=new RegExp("^"+PWt+"$"),PHn=new RegExp("^[A-Z0-9 $%*+\\-./:]+$");G5.testKanji=function(t){return MHn.test(t)};G5.testNumeric=function(t){return LHn.test(t)};G5.testAlphanumeric=function(t){return PHn.test(t)};(function(s){const t=lQe,n=G5;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}}})(nM);(function(s){const t=Ew,n=UTe,r=$Te,a=nM,i=lQe,l=7973,o=t.getBCHDigit(l);function c(m,p,x){for(let g=1;g<=40;g++)if(p<=s.getCapacity(g,x,m))return g}function d(m,p){return a.getCharCountIndicator(m,p)+4}function u(m,p){let x=0;return m.forEach(function(g){const y=d(g.mode,p);x+=y+g.getBitsLength()}),x}function h(m,p){for(let x=1;x<=40;x++)if(u(m,x)<=s.getCapacity(x,p,a.MIXED))return x}s.from=function(p,x){return i.isValid(p)?parseInt(p,10):x},s.getCapacity=function(p,x,g){if(!i.isValid(p))throw new Error("Invalid QR Code version");typeof g>"u"&&(g=a.BYTE);const y=t.getSymbolTotalCodewords(p),b=n.getTotalCodewordsCount(p,x),v=(y-b)*8;if(g===a.MIXED)return v;const N=v-d(g,p);switch(g){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,x){let g;const y=r.from(x,r.M);if(Array.isArray(p)){if(p.length>1)return h(p,y);if(p.length===0)return 1;g=p[0]}else g=p;return c(g.mode,g.getLength(),y)},s.getEncodedBits=function(p){if(!i.isValid(p)||p<7)throw new Error("Invalid QR Code version");let x=p<<12;for(;t.getBCHDigit(x)-o>=0;)x^=l<=0;)a^=DWt<0&&(r=this.data.substr(n),a=parseInt(r,10),t.put(a,i*3+1))};var RHn=rq;const OHn=nM,mRe=["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 aq(s){this.mode=OHn.ALPHANUMERIC,this.data=s}aq.getBitsLength=function(t){return 11*Math.floor(t/2)+6*(t%2)};aq.prototype.getLength=function(){return this.data.length};aq.prototype.getBitsLength=function(){return aq.getBitsLength(this.data.length)};aq.prototype.write=function(t){let n;for(n=0;n+2<=this.data.length;n+=2){let r=mRe.indexOf(this.data[n])*45;r+=mRe.indexOf(this.data[n+1]),t.put(r,11)}this.data.length%2&&t.put(mRe.indexOf(this.data[n]),6)};var FHn=aq;const zHn=nM;function iq(s){this.mode=zHn.BYTE,typeof s=="string"?this.data=new TextEncoder().encode(s):this.data=new Uint8Array(s)}iq.getBitsLength=function(t){return t*8};iq.prototype.getLength=function(){return this.data.length};iq.prototype.getBitsLength=function(){return iq.getBitsLength(this.data.length)};iq.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 qHn=oq,OWt={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,x,g,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],x=h+p,g=l[u],y=typeof l[u]>"u",(y||g>x)&&(l[u]=x,o.push(u,x),i[u]=d))}if(typeof a<"u"&&typeof l[a]>"u"){var b=["Could not find a path from ",r," to ",a,"."].join("");throw new Error(b)}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})(OWt);var VHn=OWt.exports;(function(s){const t=nM,n=RHn,r=FHn,a=BHn,i=qHn,l=G5,o=Ew,c=VHn;function d(b){return unescape(encodeURIComponent(b)).length}function u(b,v,N){const C=[];let A;for(;(A=b.exec(N))!==null;)C.push({data:A[0],index:A.index,mode:v,length:A[0].length});return C}function h(b){const v=u(l.NUMERIC,t.NUMERIC,b),N=u(l.ALPHANUMERIC,t.ALPHANUMERIC,b);let C,A;return o.isKanjiModeEnabled()?(C=u(l.BYTE,t.BYTE,b),A=u(l.KANJI,t.KANJI,b)):(C=u(l.BYTE_KANJI,t.BYTE,b),A=[]),v.concat(N,C,A).sort(function(P,M){return P.index-M.index}).map(function(P){return{data:P.data,mode:P.mode,length:P.length}})}function m(b,v){switch(v){case t.NUMERIC:return n.getBitsLength(b);case t.ALPHANUMERIC:return r.getBitsLength(b);case t.KANJI:return i.getBitsLength(b);case t.BYTE:return a.getBitsLength(b)}}function p(b){return b.reduce(function(v,N){const C=v.length-1>=0?v[v.length-1]:null;return C&&C.mode===N.mode?(v[v.length-1].data+=N.data,v):(v.push(N),v)},[])}function x(b){const v=[];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 JHn(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 xRe(s,t,n){const r=s.size,a=ZHn.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 sGn(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 nGn(s,t,n){const r=new HHn;n.forEach(function(c){r.put(c.mode.bit,4),r.put(c.getLength(),XHn.getCharCountIndicator(c.mode,s)),c.write(r)});const a=VTe.getSymbolTotalCodewords(s),i=HUe.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&&tGn(c,t),sGn(c,l),isNaN(r)&&(r=VUe.getBestMask(c,xRe.bind(null,c,n))),VUe.applyMask(r,c),xRe(c,n,r),{modules:c,version:t,errorCorrectionLevel:n,maskPattern:r,segments:a}}kWt.create=function(t,n){if(typeof t>"u"||t==="")throw new Error("No input text");let r=pRe.M,a,i;return typeof n<"u"&&(r=pRe.from(n.errorCorrectionLevel,pRe.M),a=Q4e.from(n.version),i=VUe.from(n.maskPattern),n.toSJISFunc&&VTe.setToSJISFunction(n.toSJISFunc)),aGn(t,a,r,i)};var FWt={},cQe={};(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)}})(FWt);var zWt={};const iGn=cQe;function o_t(s,t){const n=s.a/255,r=t+'="'+s.hex+'"';return n<1?r+" "+t+'-opacity="'+n.toFixed(2).slice(1)+'"':r}function gRe(s,t,n){let r=s+t;return typeof n<"u"&&(r+=" "+n),r}function oGn(s,t,n){let r="",a=0,i=!1,l=0;for(let o=0;o0&&c>0&&s[o-1]||(r+=i?gRe("M",c+n,.5+d+n):gRe("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 lGn=jHn,GUe=kWt,BWt=FWt,cGn=zWt;function dQe(s,t,n,r,a){const i=[].slice.call(arguments,1),l=i.length,o=typeof i[l-1]=="function";if(!o&&!lGn())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=GUe.create(n,r);c(s(u,t,r))}catch(u){d(u)}})}try{const c=GUe.create(n,r);a(null,s(c,t,r))}catch(c){a(c)}}PV.create=GUe.create;PV.toCanvas=dQe.bind(null,BWt.render);PV.toDataURL=dQe.bind(null,BWt.renderToDataURL);PV.toString=dQe.bind(null,function(s,t,n){return cGn.render(s,n)});function dGn(){const{eventId:s}=Vi(),t=Vn(),{data:n}=sQe(s),{data:r=[]}=lWt(s),a=hWt(),[i,l]=j.useState(""),[o,c]=j.useState(""),[d,u]=j.useState(""),[h,m]=j.useState(""),p=n!=null&&n.public_slug?zTe(n.public_slug):"";j.useEffect(()=>{p&&PV.toDataURL(p,{width:320,margin:1}).then(m).catch(()=>{})},[p]);const x=j.useMemo(()=>i?r.filter(b=>(b.guest_name||"").toLowerCase().includes(i.toLowerCase())||(b.guest_email||"").toLowerCase().includes(i.toLowerCase())):r,[r,i]),g=b=>{a.mutate({id:b.id,event_id:s,status:"attended",checked_in_at:new Date().toISOString()}),ae.success(`${b.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(""),ae.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($,{variant:"ghost",size:"sm",className:"rounded-full mb-3",onClick:()=>t(`/attract/events/${s}`),children:[e.jsx(ka,{className:"h-4 w-4 mr-2"})," Back to event"]}),e.jsxs(_e,{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(_e,{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(Rx,{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(_e,{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(be,{placeholder:"Name",value:o,onChange:b=>c(b.target.value)}),e.jsx(be,{placeholder:"Email (optional)",value:d,onChange:b=>u(b.target.value)}),e.jsxs($,{className:"w-full rounded-full",onClick:y,children:[e.jsx(il,{className:"h-4 w-4 mr-2"})," Add & check in"]})]})]})]}),e.jsxs(_e,{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(Vr,{className:"absolute left-6 top-1/2 -translate-y-1/2 h-4 w-4 text-slate-400"}),e.jsx(be,{placeholder:"Search attendees",value:i,onChange:b=>l(b.target.value),className:"pl-9 rounded-full border-slate-200"})]}),x.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:x.map(b=>{const v=b.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:b.guest_name||b.guest_email}),e.jsx("div",{className:"text-[12px] text-slate-500 truncate",children:b.guest_email})]}),v?e.jsxs($e,{className:"bg-emerald-500",children:[e.jsx(oa,{className:"h-3 w-3 mr-1"})," Checked in"]}):e.jsxs($,{size:"lg",className:"rounded-full bg-gradient-to-r from-violet-600 to-indigo-600",onClick:()=>g(b),children:[e.jsx(oa,{className:"h-5 w-5 mr-2"})," Check in"]})]},b.id)})})]})]})}):e.jsx("div",{className:"p-8 text-slate-500",children:"Loading…"})}const uGn=["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"],hGn=["Lead generation","Database marketing","Listing marketing","Social media/video","Open houses","Negotiation","Systems and technology","Team building","Leadership","New construction","Luxury","Business planning"],l_t=[{key:"produce",icon:pl,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:dn,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:pR,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:LN,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:W3,title:"Balanced Plan",blurb:"A little of all four. Best for veteran attractors.",example:"Rotate weekly focus between production, teaching, providing, and connecting."}],mGn=[{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"}],c_t=["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 d_t(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 pGn(){const s=Vn(),{settings:t,save:n}=MV(),[r,a]=j.useState(0),[i,l]=j.useState([]),[o,c]=j.useState([]),[d,u]=j.useState(null),[h,m]=j.useState({}),[p,x]=j.useState("");j.useEffect(()=>{var N,C;t&&((N=t.audiences)!=null&&N.length&&l(t.audiences),(C=t.teachables)!=null&&C.length&&c(t.teachables),t.attraction_style&&u(t.attraction_style),t.activity_baseline&&m(t.activity_baseline),t.ninety_day_outcome&&x(t.ninety_day_outcome))},[t==null?void 0:t.user_id]);const g=["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]),b=(N,C,A)=>{A(N.includes(C)?N.filter(T=>T!==C):[...N,C])},v=async()=>{if(!d)return;const N=d_t({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()}),ae.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:g.map((N,C)=>e.jsx("div",{className:Tt("h-1.5 flex-1 rounded-full transition-colors",C<=r?"bg-violet-600":"bg-slate-200")},N))}),e.jsx(Lq,{mode:"wait",children:e.jsxs(jr.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:l_t.filter(N=>N.key!=="balanced").map(N=>e.jsxs(_e,{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(QG,{icon:qn,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:uGn.map(N=>e.jsx(yRe,{label:N,active:i.includes(N),onClick:()=>b(i,N,l)},N))})}),r===2&&e.jsx(QG,{icon:Ph,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:hGn.map(N=>e.jsx(yRe,{label:N,active:o.includes(N),onClick:()=>b(o,N,c)},N))})}),r===3&&e.jsx(QG,{icon:W3,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:l_t.map(N=>e.jsx(_e,{onClick:()=>u(N.key),className:Tt("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(oa,{className:"h-5 w-5 text-violet-600"})]})},N.key))})}),r===4&&e.jsx(QG,{icon:zp,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:mGn.map(N=>e.jsxs("div",{children:[e.jsx(se,{className:"text-[12.5px] text-slate-700",children:N.label}),e.jsx(be,{type:"number",min:0,value:h[N.key]??"",onChange:C=>m({...h,[N.key]:Number(C.target.value)||0})})]},N.key))})}),r===5&&e.jsx(QG,{icon:Mu,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:[c_t.map(N=>e.jsx(yRe,{label:N,active:p===N,onClick:()=>x(N),full:!0},N)),e.jsxs("div",{className:"mt-3",children:[e.jsx(se,{className:"text-[12.5px] text-slate-700",children:"Or write your own"}),e.jsx(Is,{rows:2,placeholder:"A specific outcome you can measure in 90 days...",value:c_t.includes(p)?"":p,onChange:N=>x(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($Wt,{plan:d_t({style:d,baseline:h,outcome:p})})]})]},r)}),e.jsxs("div",{className:"mt-10 flex items-center justify-between",children:[e.jsxs($,{variant:"ghost",onClick:()=>r===0?s("/attract"):a(r-1),children:[e.jsx(ka,{className:"h-4 w-4 mr-1"})," ",r===0?"Skip for now":"Back"]}),r<6?e.jsxs($,{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(ni,{className:"h-4 w-4 ml-1"})]}):e.jsxs($,{className:"bg-gradient-to-r from-violet-600 to-indigo-600 rounded-full px-6",onClick:v,disabled:n.isPending,children:[e.jsx(w0,{className:"h-4 w-4 mr-1.5"})," Activate my 90-day plan"]})]})]})}function QG({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 yRe({label:s,active:t,onClick:n,full:r}){return e.jsx("button",{type:"button",onClick:n,className:Tt("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(oa,{className:"h-4 w-4 text-violet-600"})," ",s]})})}function $Wt({plan:s}){return e.jsxs("div",{className:"mt-6 space-y-6",children:[e.jsxs(_e,{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(_e,{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(_e,{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(_e,{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(_e,{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 fGn(){const{settings:s,resetOnboarding:t}=MV(),n=s==null?void 0:s.ninety_day_plan;return e.jsxs("div",{className:"max-w-4xl",children:[e.jsx(nm,{eyebrow:"90-Day Plan",title:"Your personalized attraction plan.",description:"Generated from your onboarding responses. Adjust any time by rerunning onboarding.",actions:e.jsxs($,{variant:"outline",className:"rounded-full",onClick:()=>t.mutate(),children:[e.jsx(Ih,{className:"h-4 w-4 mr-1.5"})," Rerun onboarding"]})}),n?e.jsx($Wt,{plan:n}):e.jsxs(_e,{className:"p-8 rounded-2xl text-center",children:[e.jsx("p",{className:"text-slate-700 mb-4",children:"You haven't set up your 90-day plan yet."}),e.jsx($,{asChild:!0,className:"bg-gradient-to-r from-violet-600 to-indigo-600 rounded-full",children:e.jsx(Wn,{to:"/attract/onboarding",children:"Start onboarding"})})]})]})}async function u_t(s,t,n,r={}){await U.rpc("award_attract_activity",{_user_id:s,_activity_type:t,_title:n,_description:r.description??null,_pillar:r.pillar??null,_agent_id:r.agent_id??null,_metadata:r.metadata??{},_dedupe_minutes:30})}function UWt(){const{user:s}=_s(),t=ts(),n=ht({queryKey:["attract-transactions",s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:o,error:c}=await U.from("attract_transactions").select("*").order("closing_date",{ascending:!1,nullsFirst:!1});if(c)throw c;return o??[]}}),r=yt({mutationFn:async o=>{const c=[o.rating_communication,o.rating_professionalism,o.rating_problem_solving].filter(x=>typeof x=="number"),d=c.length?Number((c.reduce((x,g)=>x+g,0)/c.length).toFixed(2)):null,u={...o,user_id:s.id,overall_rating:d},{data:h,error:m}=o.id?await U.from("attract_transactions").update(u).eq("id",o.id).select().single():await U.from("attract_transactions").insert(u).select().single();if(m)throw m;const p=h;return o.id||await u_t(s.id,"transaction_logged",`Reviewed ${p.property_address}`,{description:p.cooperating_first_name?`Cooperating agent: ${p.cooperating_first_name} ${p.cooperating_last_name??""}`:null,pillar:"produce",metadata:{transaction_id:p.id,overall_rating:d}}),p},onSuccess:()=>{t.invalidateQueries({queryKey:["attract-transactions"]}),t.invalidateQueries({queryKey:["attract-activities"]}),ae.success("Transaction saved")},onError:o=>ae.error(o.message)}),a=yt({mutationFn:async({id:o,decision:c,notes:d})=>{const{data:u,error:h}=await U.from("attract_transactions").update({decision:c,decision_notes:d??null}).eq("id",o).select().single();if(h)throw h;return u},onSuccess:()=>{t.invalidateQueries({queryKey:["attract-transactions"]})}}),i=yt({mutationFn:async o=>{let c=o.attract_agent_id;if(!c){const{data:d}=await U.from("attract_agents").select("id").eq("user_id",s.id).eq("first_name",o.cooperating_first_name??"").eq("last_name",o.cooperating_last_name??"").maybeSingle();if(d!=null&&d.id)c=d.id;else{const{data:u,error:h}=await U.from("attract_agents").insert({user_id:s.id,first_name:o.cooperating_first_name??"Unknown",last_name:o.cooperating_last_name,email:o.cooperating_email,phone:o.cooperating_phone,brokerage:o.cooperating_brokerage,source:"cooperating_transaction",stage:"new_connection",temperature:o.enjoy_business_with==="yes"?"warm":"cold",notes:o.stood_out}).select("id").single();if(h)throw h;c=u.id}}return await U.from("attract_transactions").update({attract_agent_id:c,decision:"add_pipeline"}).eq("id",o.id),await u_t(s.id,"agent_added_from_transaction",`Added ${o.cooperating_first_name??"agent"} to pipeline`,{pillar:"produce",agent_id:c,metadata:{transaction_id:o.id}}),c},onSuccess:()=>{t.invalidateQueries({queryKey:["attract-transactions"]}),t.invalidateQueries({queryKey:["attract-agents"]}),t.invalidateQueries({queryKey:["attract-activities"]}),ae.success("Added to Agent Pipeline")},onError:o=>ae.error(o.message)}),l=yt({mutationFn:async o=>{const{error:c}=await U.from("attract_transactions").delete().eq("id",o);if(c)throw c},onSuccess:()=>{t.invalidateQueries({queryKey:["attract-transactions"]}),ae.success("Transaction removed")}});return{transactions:n.data??[],isLoading:n.isLoading,upsert:r,setDecision:a,addToPipeline:i,remove:l}}function xGn({value:s,onChange:t}){return e.jsx("div",{className:"flex gap-1",children:[1,2,3,4,5].map(n=>e.jsx("button",{type:"button",onClick:()=>t(n),children:e.jsx(Qa,{className:Tt("h-5 w-5",(s??0)>=n?"fill-amber-400 text-amber-400":"text-slate-300")})},n))})}function gGn(s,t){var l;const n=s.cooperating_first_name||"there",r=s.property_address||"the transaction",a=(l=s.stood_out)==null?void 0:l.trim(),i=a?`You ${a.replace(/^You\s+/i,"").replace(/[.!]$/,"")}.`:"You communicated clearly and handled the inevitable curveballs with real professionalism.";switch(t){case"warm":return`Hi ${n}, I really enjoyed working with you on ${r}. ${i} It made the deal feel smooth for both sides — and that's rare. Would love to stay connected. Grab coffee or a Zoom sometime this month? — `;case"peer":return`${n} — quick note. Working with you on ${r} was refreshing. ${i} We should stay in touch — I like being around agents who operate that way.`;case"text":return`Hey ${n} — just wanted to say thanks for the way you handled ${r}. ${i} Let's grab coffee soon.`;case"email":default:return`Subject: A quick thank you Hi ${n}, Wrapping up on ${r} and I wanted to send a note. ${i} It's the kind of transaction I remember for a long time. Would love to stay in touch — coffee, a Zoom, or a shared MLS thought when it hits. Whatever works. All the best, `}}const yGn={1:"Poor",2:"Fair",3:"OK",4:"Good",5:"Excellent"},vRe={add_pipeline:{label:"In Pipeline",color:"bg-emerald-100 text-emerald-800"},send_compliment:{label:"Compliment sent",color:"bg-violet-100 text-violet-800"},invite_coffee:{label:"Coffee invited",color:"bg-amber-100 text-amber-800"},share_resource:{label:"Resource shared",color:"bg-sky-100 text-sky-800"},no_action:{label:"No action",color:"bg-slate-100 text-slate-700"},pending:{label:"Needs review",color:"bg-rose-100 text-rose-800"}};function vGn(){const{transactions:s,isLoading:t,upsert:n,setDecision:r,addToPipeline:a,remove:i}=UWt(),[l,o]=j.useState(""),[c,d]=j.useState(!1),[u,h]=j.useState(null),[m,p]=j.useState(null),x=j.useMemo(()=>{const y=l.trim().toLowerCase();return y?s.filter(b=>[b.property_address,b.cooperating_first_name,b.cooperating_last_name,b.cooperating_brokerage,b.city].filter(Boolean).some(v=>String(v).toLowerCase().includes(y))):s},[s,l]),g=j.useMemo(()=>{const y=s.length,b=s.filter(C=>C.enjoy_business_with==="yes").length,v=s.filter(C=>C.decision==="add_pipeline").length,N=s.filter(C=>C.follow_up_created).length;return{reviewed:y,highFit:b,inPipeline:v,followUps:N}},[s]);return e.jsxs("div",{children:[e.jsxs(Wn,{to:"/attract/produce",className:"inline-flex items-center gap-1.5 text-[12px] text-slate-500 hover:text-violet-700 mb-3",children:[e.jsx(ka,{className:"h-3.5 w-3.5"})," Back to Produce"]}),e.jsx(nm,{eyebrow:"Produce → Tool",title:"Transaction-to-Relationship Tracker",description:"Every good cooperating agent is a future relationship. Log the transaction, note what stood out, and turn the best experiences into real professional friendships.",actions:e.jsxs($,{className:"rounded-full bg-gradient-to-r from-violet-600 to-indigo-600",onClick:()=>d(!0),children:[e.jsx(sn,{className:"h-4 w-4 mr-1.5"})," Add Transaction"]})}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-3 mb-6",children:[e.jsx(Vae,{label:"Transactions reviewed",value:g.reviewed}),e.jsx(Vae,{label:"High-fit agents",value:g.highFit,tone:"emerald"}),e.jsx(Vae,{label:"Added to pipeline",value:g.inPipeline,tone:"violet"}),e.jsx(Vae,{label:"Follow-ups created",value:g.followUps,tone:"amber"})]}),e.jsx("div",{className:"flex items-center gap-3 mb-4",children:e.jsxs("div",{className:"relative flex-1 max-w-md",children:[e.jsx(Vr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-slate-400"}),e.jsx(be,{value:l,onChange:y=>o(y.target.value),placeholder:"Search property, agent, brokerage...",className:"pl-9 rounded-full"})]})}),t?e.jsx("div",{className:"space-y-3",children:[0,1,2].map(y=>e.jsx(_e,{className:"p-5 rounded-2xl h-24 animate-pulse bg-slate-100"},y))}):x.length===0?e.jsxs(_e,{className:"p-10 rounded-2xl text-center",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(dn,{className:"h-6 w-6 text-violet-700"})}),e.jsx("h3",{className:"text-lg font-semibold text-slate-900",children:"Turn transactions into relationships"}),e.jsx("p",{className:"text-[13.5px] text-slate-600 max-w-md mx-auto mt-2",children:"Add your last 5 closed transactions to spot the agents you'd love to be in business with — then send a thoughtful compliment that opens the door."}),e.jsxs($,{className:"mt-6 rounded-full bg-gradient-to-r from-violet-600 to-indigo-600",onClick:()=>d(!0),children:[e.jsx(sn,{className:"h-4 w-4 mr-1.5"})," Add your first transaction"]})]}):e.jsx("div",{className:"space-y-3",children:x.map(y=>{var b,v;return e.jsx(_e,{className:"p-5 rounded-2xl hover:shadow-md transition-shadow",children:e.jsxs("div",{className:"flex flex-col md:flex-row md:items-center 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("div",{className:"text-[14px] font-semibold text-slate-900 truncate",children:y.property_address}),y.closing_date&&e.jsx($e,{variant:"outline",className:"text-[10.5px]",children:Hs(new Date(y.closing_date),"MMM d, yyyy")}),e.jsx($e,{className:Tt("text-[10.5px] border-0",((b=vRe[y.decision])==null?void 0:b.color)??vRe.pending.color),children:((v=vRe[y.decision])==null?void 0:v.label)??"Needs review"})]}),e.jsxs("div",{className:"text-[12.5px] text-slate-600 mt-1",children:[y.cooperating_first_name||y.cooperating_last_name?`${y.cooperating_first_name??""} ${y.cooperating_last_name??""}`:"Cooperating agent",y.cooperating_brokerage?` · ${y.cooperating_brokerage}`:""]}),e.jsxs("div",{className:"flex items-center gap-3 mt-2 text-[12px] text-slate-600",children:[y.overall_rating!=null&&e.jsxs("span",{className:"inline-flex items-center gap-1",children:[e.jsx(Qa,{className:"h-3.5 w-3.5 fill-amber-400 text-amber-400"})," ",y.overall_rating]}),y.enjoy_business_with&&e.jsxs("span",{className:"capitalize",children:["Fit: ",e.jsx("span",{className:Tt("font-medium",y.enjoy_business_with==="yes"?"text-emerald-700":y.enjoy_business_with==="maybe"?"text-amber-700":"text-slate-600"),children:y.enjoy_business_with})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsxs($,{size:"sm",variant:"outline",className:"rounded-full",onClick:()=>h(y),children:["Review ",e.jsx(Ja,{className:"h-3.5 w-3.5 ml-1"})]}),e.jsxs($,{size:"sm",variant:"outline",className:"rounded-full",onClick:()=>p(y),children:[e.jsx(Tz,{className:"h-3.5 w-3.5 mr-1"})," Message"]}),e.jsx($,{size:"sm",variant:"ghost",className:"text-rose-600 hover:text-rose-700",onClick:()=>i.mutate(y.id),children:"Remove"})]})]})},y.id)})}),e.jsx("div",{className:"mt-8",children:e.jsx(kF,{})}),e.jsx(bGn,{open:c,onClose:()=>d(!1),onSaved:y=>{d(!1),h(y)},upsert:n}),e.jsx(_Gn,{tx:u,onClose:()=>h(null),onDecision:y=>u&&r.mutate({id:u.id,decision:y}),onAddToPipeline:()=>u&&a.mutate(u),onMessage:()=>{p(u),h(null)}}),e.jsx(wGn,{tx:m,onClose:()=>p(null)})]})}function Vae({label:s,value:t,tone:n="slate"}){const r={slate:"text-slate-900",emerald:"text-emerald-700",violet:"text-violet-700",amber:"text-amber-700"};return e.jsxs(_e,{className:"p-4 rounded-2xl",children:[e.jsx("div",{className:Tt("text-2xl font-semibold tabular-nums",r[n]),children:t}),e.jsx("div",{className:"text-[11.5px] text-slate-500 mt-0.5",children:s})]})}function bGn({open:s,onClose:t,onSaved:n,upsert:r}){const[a,i]=j.useState({enjoy_business_with:"maybe"}),l=c=>i({...a,...c}),o=async()=>{var d;if(!((d=a.property_address)!=null&&d.trim())){ae.error("Property address is required");return}const c=await r.mutateAsync(a);i({enjoy_business_with:"maybe"}),n(c)};return e.jsx(Os,{open:s,onOpenChange:c=>!c&&t(),children:e.jsxs(Rs,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsxs(Us,{children:[e.jsx(zs,{children:"Add Transaction"}),e.jsx(Sr,{children:"Capture what stood out while it's fresh."})]}),e.jsxs("div",{className:"space-y-4",children:[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(se,{children:"Property address *"}),e.jsx(be,{value:a.property_address??"",onChange:c=>l({property_address:c.target.value})})]}),e.jsxs("div",{children:[e.jsx(se,{children:"City"}),e.jsx(be,{value:a.city??"",onChange:c=>l({city:c.target.value})})]}),e.jsxs("div",{children:[e.jsx(se,{children:"State"}),e.jsx(be,{value:a.state??"",onChange:c=>l({state:c.target.value})})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Closing date"}),e.jsx(be,{type:"date",value:a.closing_date??"",onChange:c=>l({closing_date:c.target.value})})]}),e.jsxs("div",{children:[e.jsx(se,{children:"You represented"}),e.jsxs(vs,{value:a.represented??"",onValueChange:c=>l({represented:c}),children:[e.jsx(gs,{children:e.jsx(bs,{placeholder:"Buyer or seller"})}),e.jsxs(ys,{children:[e.jsx(Ye,{value:"buyer",children:"Buyer"}),e.jsx(Ye,{value:"seller",children:"Seller"}),e.jsx(Ye,{value:"both",children:"Both"}),e.jsx(Ye,{value:"other",children:"Other"})]})]})]})]}),e.jsxs("div",{className:"border-t pt-4",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-widest text-slate-500 font-semibold mb-3",children:"Cooperating agent"}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx(se,{children:"First name"}),e.jsx(be,{value:a.cooperating_first_name??"",onChange:c=>l({cooperating_first_name:c.target.value})})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Last name"}),e.jsx(be,{value:a.cooperating_last_name??"",onChange:c=>l({cooperating_last_name:c.target.value})})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Email"}),e.jsx(be,{type:"email",value:a.cooperating_email??"",onChange:c=>l({cooperating_email:c.target.value})})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Phone"}),e.jsx(be,{value:a.cooperating_phone??"",onChange:c=>l({cooperating_phone:c.target.value})})]}),e.jsxs("div",{className:"md:col-span-2",children:[e.jsx(se,{children:"Brokerage"}),e.jsx(be,{value:a.cooperating_brokerage??"",onChange:c=>l({cooperating_brokerage:c.target.value})})]})]})]}),e.jsxs("div",{className:"border-t pt-4",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-widest text-slate-500 font-semibold mb-3",children:"Experience"}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4",children:[["rating_communication","Communication"],["rating_professionalism","Professionalism"],["rating_problem_solving","Problem solving"]].map(([c,d])=>e.jsxs("div",{children:[e.jsx(se,{children:d}),e.jsx(xGn,{value:a[c],onChange:u=>l({[c]:u})}),e.jsx("div",{className:"text-[11px] text-slate-500 mt-1",children:yGn[a[c]]??"—"})]},c))}),e.jsxs("div",{className:"mt-4",children:[e.jsx(se,{children:"Would you enjoy being in business with this agent?"}),e.jsx("div",{className:"flex gap-2 mt-2",children:["yes","maybe","no"].map(c=>e.jsx("button",{type:"button",onClick:()=>l({enjoy_business_with:c}),className:Tt("rounded-full px-4 py-1.5 text-[12.5px] font-medium border capitalize",a.enjoy_business_with===c?"bg-violet-600 text-white border-violet-600":"bg-white text-slate-700 border-slate-200"),children:c},c))})]}),e.jsxs("div",{className:"mt-4",children:[e.jsx(se,{children:"What stood out?"}),e.jsx(Is,{rows:2,value:a.stood_out??"",onChange:c=>l({stood_out:c.target.value})})]}),e.jsxs("div",{className:"mt-4",children:[e.jsx(se,{children:"Private notes"}),e.jsx(Is,{rows:2,value:a.private_notes??"",onChange:c=>l({private_notes:c.target.value}),placeholder:"Only you can see these."})]})]})]}),e.jsxs(kr,{children:[e.jsx($,{variant:"ghost",onClick:t,children:"Cancel"}),e.jsx($,{onClick:o,disabled:r.isPending,className:"bg-gradient-to-r from-violet-600 to-indigo-600",children:"Save & review"})]})]})})}function _Gn({tx:s,onClose:t,onDecision:n,onAddToPipeline:r,onMessage:a}){return s?e.jsx(Os,{open:!!s,onOpenChange:i=>!i&&t(),children:e.jsxs(Rs,{className:"max-w-lg",children:[e.jsxs(Us,{children:[e.jsx(zs,{children:"Would you like to build a relationship?"}),e.jsxs(Sr,{children:[s.cooperating_first_name?`${s.cooperating_first_name} ${s.cooperating_last_name??""}`:"This agent"," on ",s.property_address,"."]})]}),e.jsxs("div",{className:"grid grid-cols-1 gap-2",children:[e.jsx(JG,{icon:il,label:"Add to Agent Pipeline",tone:"violet",onClick:r}),e.jsx(JG,{icon:Tz,label:"Send a professional compliment",tone:"teal",onClick:()=>{n("send_compliment"),a()}}),e.jsx(JG,{icon:Tb,label:"Invite to coffee",tone:"amber",onClick:()=>{n("invite_coffee"),a()}}),e.jsx(JG,{icon:dn,label:"Share a relevant resource",tone:"sky",onClick:()=>n("share_resource")}),e.jsx(JG,{icon:$d,label:"No action right now",tone:"slate",onClick:()=>{n("no_action"),t()}})]})]})}):null}function JG({icon:s,label:t,tone:n,onClick:r}){const a={violet:"bg-violet-50 text-violet-700 hover:bg-violet-100",teal:"bg-teal-50 text-teal-700 hover:bg-teal-100",amber:"bg-amber-50 text-amber-700 hover:bg-amber-100",sky:"bg-sky-50 text-sky-700 hover:bg-sky-100",slate:"bg-slate-50 text-slate-700 hover:bg-slate-100"};return e.jsxs("button",{onClick:r,className:Tt("flex items-center gap-3 rounded-xl px-4 py-3 text-left transition-colors",a[n]),children:[e.jsx(s,{className:"h-5 w-5"}),e.jsx("div",{className:"flex-1 text-[13.5px] font-medium",children:t}),e.jsx(Ja,{className:"h-4 w-4 opacity-60"})]})}function wGn({tx:s,onClose:t}){const[n,r]=j.useState("warm");if(!s)return null;const a=gGn(s,n);return e.jsx(Os,{open:!!s,onOpenChange:i=>!i&&t(),children:e.jsxs(Rs,{className:"max-w-lg",children:[e.jsxs(Us,{children:[e.jsx(zs,{children:"Personalized message"}),e.jsx(Sr,{children:"Adjust the tone, then copy and send from your usual inbox."})]}),e.jsx("div",{className:"flex gap-1.5 mb-3",children:[["warm","Warm & pro"],["peer","Casual peer"],["text","Short text"],["email","Email"]].map(([i,l])=>e.jsx("button",{onClick:()=>r(i),className:Tt("rounded-full px-3 py-1 text-[11.5px] font-medium border",n===i?"bg-violet-600 text-white border-violet-600":"bg-white text-slate-700 border-slate-200"),children:l},i))}),e.jsx(Is,{value:a,readOnly:!0,rows:10,className:"font-mono text-[12.5px]"}),e.jsxs(kr,{children:[e.jsx($,{variant:"ghost",onClick:t,children:"Close"}),e.jsxs($,{className:"bg-gradient-to-r from-violet-600 to-indigo-600",onClick:()=>{navigator.clipboard.writeText(a),ae.success("Copied to clipboard")},children:[e.jsx(Ca,{className:"h-4 w-4 mr-1.5"})," Copy"]})]})]})})}function qWt(){const{user:s}=_s(),t=ts(),n=ht({queryKey:["attract-content",s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:o,error:c}=await U.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 U.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?ae.info("Demo generation used — configure AI provider for live results"):ae.success("Content generated")},onError:o=>ae.error(o.message)}),a=yt({mutationFn:async o=>{const{data:c,error:d}=await U.from("attract_content_drafts").update(o).eq("id",o.id).select().single();if(d)throw d;return c},onSuccess:()=>{t.invalidateQueries({queryKey:["attract-content"]}),ae.success("Saved")}}),i=yt({mutationFn:async o=>{const{error:c}=await U.from("attract_content_drafts").update({status:"posted",posted_at:new Date().toISOString()}).eq("id",o);if(c)throw c;await U.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"]}),ae.success("Marked as posted")}}),l=yt({mutationFn:async o=>{const{error:c}=await U.from("attract_content_drafts").delete().eq("id",o);if(c)throw c},onSuccess:()=>{t.invalidateQueries({queryKey:["attract-content"]}),ae.success("Draft removed")}});return{drafts:n.data??[],isLoading:n.isLoading,generate:r,save:a,markPosted:i,remove:l}}const WUe=[{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"}]}],jGn=["Direct","Educational","Fun","Contrarian","Encouraging"],NGn=["short","medium","long"],kGn=["instagram","linkedin","facebook","youtube","email"],J4e={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 SGn(){const{drafts:s,isLoading:t,generate:n,save:r,markPosted:a,remove:i}=qWt(),[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(Wn,{to:"/attract/influence",className:"inline-flex items-center gap-1.5 text-[12px] text-slate-500 hover:text-violet-700 mb-3",children:[e.jsx(ka,{className:"h-3.5 w-3.5"})," Back to Influence"]}),e.jsx(nm,{eyebrow:"Influence → Tool",title:"Authority Content Studio",description:"Turn your real experience into agent-focused content that builds authority — without sounding like a brokerage pitch.",actions:e.jsxs($,{className:"rounded-full bg-gradient-to-r from-violet-600 to-indigo-600",onClick:()=>{d(null),o(!0)},children:[e.jsx(wm,{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(dn,{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(ua,{defaultValue:"all",className:"mb-8",children:[e.jsxs(ha,{children:[e.jsxs(Qt,{value:"all",children:["All (",s.length,")"]}),e.jsxs(Qt,{value:"ready",children:["Ready (",u.ready.length,")"]}),e.jsxs(Qt,{value:"draft",children:["Draft (",u.draft.length,")"]}),e.jsxs(Qt,{value:"posted",children:["Posted (",u.posted.length,")"]})]}),e.jsx(Jt,{value:"all",children:e.jsx(Hae,{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(Jt,{value:"ready",children:e.jsx(Hae,{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(Jt,{value:"draft",children:e.jsx(Hae,{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(Jt,{value:"posted",children:e.jsx(Hae,{drafts:u.posted,isLoading:t,onOpen:h=>{d(h),o(!0)},onPosted:()=>{},onRemove:h=>i.mutate(h),onEmpty:()=>{d(null),o(!0)}})})]}),e.jsx(kF,{}),e.jsx(CGn,{open:l,editing:c,onClose:()=>{o(!1),d(null)},generate:n,save:r,markPosted:h=>a.mutate(h)})]})}function Hae({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(_e,{className:"p-5 rounded-2xl h-24 animate-pulse bg-slate-100"},l))}):s.length===0?e.jsxs(_e,{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(wN,{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($,{className:"mt-6 rounded-full bg-gradient-to-r from-violet-600 to-indigo-600",onClick:i,children:[e.jsx(sn,{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=WUe.find(u=>u.key===l.mode))==null?void 0:c.label)??l.mode;return e.jsx(_e,{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($e,{className:Tt("text-[10.5px] border-0",J4e[l.status].color),children:J4e[l.status].label}),e.jsx($e,{variant:"outline",className:"text-[10.5px]",children:o}),l.tone&&e.jsx($e,{variant:"outline",className:"text-[10.5px]",children:l.tone}),l.ratio_flag&&e.jsxs($e,{className:"text-[10.5px] bg-amber-100 text-amber-900 border-0 gap-1",children:[e.jsx(mc,{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 ${Hs(new Date(l.posted_at),"MMM d")}`:`Updated ${Hs(new Date(l.updated_at),"MMM d")}`})]}),e.jsxs("div",{className:"flex flex-col gap-1.5",children:[e.jsx($,{size:"sm",variant:"outline",className:"rounded-full",onClick:()=>n(l),children:"Open"}),l.status!=="posted"&&e.jsxs($,{size:"sm",variant:"ghost",className:"text-emerald-700",onClick:()=>r(l.id),children:[e.jsx(oa,{className:"h-3.5 w-3.5 mr-1"})," Posted"]}),e.jsx($,{size:"sm",variant:"ghost",className:"text-rose-600",onClick:()=>a(l.id),children:e.jsx(Pn,{className:"h-3.5 w-3.5"})})]})]})},l.id)})})}function CGn({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"),[x,g]=j.useState((t==null?void 0:t.length)??"medium"),[y,b]=j.useState((t==null?void 0:t.platforms)??["instagram"]),[v,N]=j.useState((t==null?void 0:t.include_brokerage_reference)??!1),[C,A]=j.useState(t??null),[T,P]=j.useState(""),[M,I]=j.useState((t==null?void 0:t.status)??"draft"),D=WUe.find(W=>W.key===l),B=async W=>{const V=await r.mutateAsync({mode:l,topic:u,inputs:c,tone:m,length:x,platforms:y,include_brokerage_reference:v,refinement:W??T,draft_id:C==null?void 0:C.id});V!=null&&V.draft&&A(V.draft),P("")},q=async W=>{if(!C)return;const V=await a.mutateAsync({id:C.id,...W});A(V)};return e.jsx(Os,{open:s,onOpenChange:W=>!W&&n(),children:e.jsx(Rs,{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(Us,{children:[e.jsx(zs,{className:"text-base",children:"Content Studio"}),e.jsx(Sr,{className:"text-[12px]",children:D.blurb})]}),e.jsxs("div",{className:"mt-4 space-y-3",children:[e.jsxs("div",{children:[e.jsx(se,{className:"text-[12px]",children:"Content mode"}),e.jsxs(vs,{value:l,onValueChange:W=>{o(W),d({})},children:[e.jsx(gs,{children:e.jsx(bs,{})}),e.jsx(ys,{children:WUe.map(W=>e.jsx(Ye,{value:W.key,children:W.label},W.key))})]})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-[12px]",children:"Topic (optional)"}),e.jsx(be,{value:u,onChange:W=>h(W.target.value),placeholder:"1-line summary"})]}),D.fields.map(W=>e.jsxs("div",{children:[e.jsx(se,{className:"text-[12px]",children:W.label}),e.jsx(Is,{rows:2,value:c[W.key]??"",onChange:V=>d({...c,[W.key]:V.target.value}),placeholder:W.placeholder})]},W.key)),e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsxs("div",{children:[e.jsx(se,{className:"text-[12px]",children:"Tone"}),e.jsxs(vs,{value:m,onValueChange:p,children:[e.jsx(gs,{children:e.jsx(bs,{})}),e.jsx(ys,{children:jGn.map(W=>e.jsx(Ye,{value:W,children:W},W))})]})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-[12px]",children:"Length"}),e.jsxs(vs,{value:x,onValueChange:g,children:[e.jsx(gs,{children:e.jsx(bs,{})}),e.jsx(ys,{children:NGn.map(W=>e.jsx(Ye,{value:W,children:W},W))})]})]})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-[12px]",children:"Platforms"}),e.jsx("div",{className:"flex flex-wrap gap-1.5 mt-1",children:kGn.map(W=>e.jsx("button",{type:"button",onClick:()=>b(y.includes(W)?y.filter(V=>V!==W):[...y,W]),className:Tt("rounded-full px-2.5 py-1 text-[11px] capitalize border",y.includes(W)?"bg-violet-600 text-white border-violet-600":"bg-white border-slate-200 text-slate-700"),children:W},W))})]}),e.jsxs("label",{className:"flex items-center gap-2 text-[12px] text-slate-700",children:[e.jsx("input",{type:"checkbox",checked:v,onChange:W=>N(W.target.checked)}),"Include a light brokerage reference"]}),e.jsxs($,{className:"w-full bg-gradient-to-r from-violet-600 to-indigo-600 rounded-full",onClick:()=>B(),disabled:r.isPending,children:[e.jsx(wm,{className:"h-4 w-4 mr-1.5"})," ",r.isPending?"Generating…":C?"Regenerate":"Generate content"]})]})]}),e.jsx("div",{className:"overflow-y-auto p-6",children:C?e.jsxs("div",{className:"space-y-5",children:[C.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(mc,{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($,{size:"sm",variant:"outline",onClick:()=>B("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($e,{className:Tt("text-[10.5px] border-0",J4e[M].color),children:J4e[M].label}),e.jsxs(vs,{value:M,onValueChange:W=>{I(W),q({status:W})},children:[e.jsx(gs,{className:"h-8 w-32 text-[12px]",children:e.jsx(bs,{})}),e.jsxs(ys,{children:[e.jsx(Ye,{value:"idea",children:"Idea"}),e.jsx(Ye,{value:"draft",children:"Draft"}),e.jsx(Ye,{value:"ready",children:"Ready"}),e.jsx(Ye,{value:"posted",children:"Posted"})]})]}),e.jsx(be,{type:"date",className:"h-8 w-40 text-[12px]",value:C.planned_at?C.planned_at.slice(0,10):"",onChange:W=>q({planned_at:W.target.value?new Date(W.target.value).toISOString():null})}),C.status!=="posted"&&e.jsxs($,{size:"sm",variant:"outline",className:"rounded-full",onClick:()=>i(C.id),children:[e.jsx(Br,{className:"h-3.5 w-3.5 mr-1"})," Mark posted"]}),e.jsx($,{size:"sm",variant:"outline",className:"rounded-full",asChild:!0,children:e.jsxs(Wn,{to:`/attract/provide/kits/new?seed=${encodeURIComponent(C.topic||C.mode)}`,children:[e.jsx(sn,{className:"h-3.5 w-3.5 mr-1"})," Turn into a kit"]})})]}),e.jsx(s9,{title:"Hook options",children:e.jsx("div",{className:"space-y-1.5",children:(C.hook_options??[]).map((W,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:W}),e.jsx(KUe,{value:W})]},V))})}),e.jsx(s9,{title:"Teleprompter script",children:e.jsx(bRe,{value:C.script??"",onSave:W=>q({script:W})})}),e.jsx(s9,{title:"Social caption",children:e.jsx(bRe,{value:C.caption??"",onSave:W=>q({caption:W})})}),e.jsx(s9,{title:"Carousel outline",children:e.jsx("div",{className:"space-y-1.5",children:(C.carousel_outline??[]).map((W,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 ",W.slide??V+1]}),e.jsx("div",{className:"text-slate-800 mt-0.5",children:W.text})]},V))})}),e.jsx(s9,{title:"Email lesson",children:e.jsx(bRe,{value:C.email_lesson??"",onSave:W=>q({email_lesson:W})})}),e.jsx(s9,{title:"CTA options",children:e.jsx("div",{className:"space-y-1.5",children:(C.cta_options??[]).map((W,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:W}),e.jsx(KUe,{value:W})]},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(W=>e.jsx($,{size:"sm",variant:"outline",className:"text-[11.5px]",onClick:()=>B(W),children:W},W))}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(be,{value:T,onChange:W=>P(W.target.value),placeholder:"Custom refinement…"}),e.jsxs($,{variant:"outline",onClick:()=>B(),disabled:r.isPending,children:[e.jsx(Wi,{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(HK,{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 s9({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(ia,{className:"h-3 w-3 opacity-0"})," ",s]}),t]})}function bRe({value:s,onSave:t}){const[n,r]=j.useState(s);return e.jsxs("div",{children:[e.jsx(Is,{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($,{size:"sm",variant:"outline",onClick:()=>t(n),children:"Save edit"}),e.jsx(KUe,{value:n})]})]})}function KUe({value:s}){return e.jsx($,{size:"sm",variant:"ghost",onClick:()=>{navigator.clipboard.writeText(s),ae.success("Copied")},children:e.jsx(Ca,{className:"h-3.5 w-3.5"})})}const AGn={draft:"bg-slate-100 text-slate-700",published:"bg-emerald-100 text-emerald-800",archived:"bg-amber-100 text-amber-800"};function EGn(){const{kits:s,isLoading:t,create:n,duplicate:r,remove:a}=LV(),i=Vn(),l=async()=>{const o=await n.mutateAsync({title:"Untitled Kit",status:"draft"});i(`/attract/provide/kits/${o.id}/edit`)};return e.jsxs("div",{children:[e.jsx(nm,{eyebrow:"Provide · Resource Kits",title:"Your Resource Kits",description:"Package the value you already share, then track what actually creates conversations.",actions:e.jsxs("div",{className:"flex gap-2",children:[e.jsx($,{variant:"outline",asChild:!0,className:"rounded-full",children:e.jsxs(Wn,{to:"/attract/provide/kits/templates",children:[e.jsx(g1,{className:"h-4 w-4 mr-2"}),"Starter library"]})}),e.jsxs($,{onClick:l,className:"rounded-full bg-gradient-to-r from-violet-600 to-indigo-600",children:[e.jsx(sn,{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(_e,{className:"p-10 text-center rounded-2xl border-dashed border-slate-300 bg-white",children:[e.jsx(dn,{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($,{variant:"outline",asChild:!0,children:e.jsx(Wn,{to:"/attract/provide/kits/templates",children:"Browse starter library"})}),e.jsx($,{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(_e,{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($e,{className:AGn[o.status]+" capitalize",children:o.status}),o.pillar&&e.jsx($e,{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($e,{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($,{size:"sm",variant:"outline",asChild:!0,children:e.jsxs(Wn,{to:`/attract/provide/kits/${o.id}/edit`,children:[e.jsx(Iz,{className:"h-3.5 w-3.5 mr-1.5"}),"Edit"]})}),e.jsx($,{size:"sm",variant:"outline",asChild:!0,children:e.jsxs(Wn,{to:`/attract/provide/kits/${o.id}/analytics`,children:[e.jsx(ml,{className:"h-3.5 w-3.5 mr-1.5"}),"Analytics"]})}),e.jsx($,{size:"sm",variant:"ghost",onClick:async()=>{const d=await r.mutateAsync(o.id);ae.success("Duplicated"),i(`/attract/provide/kits/${d}/edit`)},children:e.jsx(Ca,{className:"h-3.5 w-3.5"})}),e.jsx($,{size:"sm",variant:"ghost",onClick:async()=>{await Yi("Delete this kit? Shares and events will also be removed.")&&a.mutate(o.id,{onSuccess:()=>ae.success("Deleted")})},children:e.jsx(Pn,{className:"h-3.5 w-3.5 text-rose-600"})})]})]},o.id)})})]})}const TGn={pdf:Wr,video:Td,link:kc,checklist:Jh,template:H3,text:Wr,content_studio:dn,resource:Wr};function VWt({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(_e,{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:MGn(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=TGn[o.type]??Wr;return e.jsx(_e,{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($,{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(Tr,{className:"h-3.5 w-3.5 mr-1.5"}),"Open"]})}),o.allow_download&&o.type!=="link"&&e.jsx($,{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(di,{className:"h-3.5 w-3.5 mr-1.5"}),"Download"]})}),o.type==="link"&&e.jsx($,{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($,{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 MGn(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 LGn=[{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 h_t(){var W,V;const{kitId:s}=Vi(),[t]=oc(),n=Vn(),{user:r}=_s(),a=s===void 0,{create:i,update:l}=LV(),{data:o,isLoading:c}=_Wt(s),{items:d,add:u,update:h,remove:m,reorder:p}=uHn(s),{shares:x,create:g,revoke:y}=wWt(s),{agents:b}=M0(),[v,N]=j.useState(null),[C,A]=j.useState("desktop"),[T,P]=j.useState("idle"),M=j.useRef(null);j.useEffect(()=>{a&&!v&&(async()=>{const K=t.get("seed"),Q=await i.mutateAsync({title:K?`From: ${K}`:"Untitled Kit",status:"draft"});n(`/attract/provide/kits/${Q.id}/edit`,{replace:!0})})()},[a]),j.useEffect(()=>{o&&N(o)},[o==null?void 0:o.id]);const I=K=>{s&&(N(Q=>({...Q,...K})),P("saving"),clearTimeout(M.current),M.current=setTimeout(async()=>{try{await l.mutateAsync({id:s,patch:K}),P("saved"),setTimeout(()=>P("idle"),1500)}catch(Q){ae.error(Q.message??"Save failed"),P("idle")}},800))},D=async K=>{!s||!r||await u.mutateAsync({user_id:r.id,type:K,title:`New ${K.replace("_"," ")}`})},B=(K,Q)=>{const J=[...d],ce=K+Q;ce<0||ce>=J.length||([J[K],J[ce]]=[J[ce],J[K]],p.mutate(J.map(ue=>ue.id)))},q=x.filter(K=>K.status==="active");return a||!v?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(nm,{eyebrow:"Provide · Kit builder",title:v.title||"Untitled Kit",description:T==="saving"?"Saving…":T==="saved"?"Saved":`Last edited ${Hs(new Date(v.updated_at),"MMM d, h:mm a")}`,actions:e.jsxs("div",{className:"flex gap-2 flex-wrap",children:[e.jsx($,{variant:"outline",size:"sm",asChild:!0,className:"rounded-full",children:e.jsxs(Wn,{to:"/attract/provide/kits",children:[e.jsx(ka,{className:"h-4 w-4 mr-1"}),"Kits"]})}),e.jsx($,{variant:"outline",size:"sm",asChild:!0,className:"rounded-full",children:e.jsx(Wn,{to:`/attract/provide/kits/${s}/analytics`,children:"Analytics"})}),e.jsxs(vs,{value:v.status,onValueChange:K=>I({status:K}),children:[e.jsx(gs,{className:"w-[130px] rounded-full",children:e.jsx(bs,{})}),e.jsxs(ys,{children:[e.jsx(Ye,{value:"draft",children:"Draft"}),e.jsx(Ye,{value:"published",children:"Published"}),e.jsx(Ye,{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(_e,{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(se,{children:"Title"}),e.jsx(be,{value:v.title??"",onChange:K=>I({title:K.target.value})})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Short description"}),e.jsx(Is,{rows:3,value:v.description??"",onChange:K=>I({description:K.target.value})})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Cover image URL"}),e.jsx(be,{placeholder:"https://…",value:v.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(se,{children:"Audience"}),e.jsx(be,{placeholder:"e.g. New agents",value:v.audience??"",onChange:K=>I({audience:K.target.value})})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Pillar"}),e.jsxs(vs,{value:v.pillar??"",onValueChange:K=>I({pillar:K}),children:[e.jsx(gs,{children:e.jsx(bs,{placeholder:"Choose"})}),e.jsxs(ys,{children:[e.jsx(Ye,{value:"produce",children:"Produce"}),e.jsx(Ye,{value:"influence",children:"Influence"}),e.jsx(Ye,{value:"provide",children:"Provide"}),e.jsx(Ye,{value:"connect",children:"Connect"})]})]})]})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Tags (comma separated)"}),e.jsx(be,{value:(v.tags??[]).join(", "),onChange:K=>I({tags:K.target.value.split(",").map(Q=>Q.trim()).filter(Boolean)})})]})]})]}),e.jsxs(_e,{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(Is,{rows:4,placeholder:"Write a short personal note that opens the kit.",value:v.intro_text??"",onChange:K=>I({intro_text:K.target.value})}),e.jsxs("div",{children:[e.jsx(se,{children:"Intro video URL (optional)"}),e.jsx(be,{placeholder:"Loom/YouTube/Vimeo",value:v.intro_video_url??"",onChange:K=>I({intro_video_url:K.target.value})})]})]})]}),e.jsxs(_e,{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(se,{children:"Button label"}),e.jsx(be,{value:v.cta_label??"",onChange:K=>I({cta_label:K.target.value})})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Button URL"}),e.jsx(be,{placeholder:"https://…",value:v.cta_url??"",onChange:K=>I({cta_url:K.target.value})})]})]}),e.jsxs("div",{className:"mt-3",children:[e.jsx(se,{children:"Expiration (optional)"}),e.jsx(be,{type:"datetime-local",value:v.expires_at?v.expires_at.slice(0,16):"",onChange:K=>I({expires_at:K.target.value?new Date(K.target.value).toISOString():null})})]})]}),e.jsxs(_e,{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(PGn,{kitId:s,agents:b,shares:q,onCreate:K=>g.mutate(K),onRevoke:K=>y.mutate(K),status:v.status})]})]}),e.jsx("div",{className:"xl:col-span-5 space-y-4",children:e.jsxs(_e,{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(vs,{onValueChange:K=>D(K),children:[e.jsx(gs,{className:"w-[180px]",children:e.jsx(bs,{placeholder:"+ Add item"})}),e.jsx(ys,{children:LGn.map(K=>e.jsx(Ye,{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,Q)=>{var J,ce;return e.jsx(_e,{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:()=>B(Q,-1),children:e.jsx(sp,{className:"h-4 w-4"})}),e.jsx("button",{className:"text-slate-400 hover:text-slate-700",onClick:()=>B(Q,1),children:e.jsx(ax,{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($e,{variant:"outline",className:"capitalize",children:K.type.replace("_"," ")}),e.jsx(be,{className:"flex-1",value:K.title,onChange:ue=>h.mutate({id:K.id,patch:{title:ue.target.value}})})]}),e.jsx(Is,{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(be,{placeholder:"URL",value:K.url??"",onChange:ue=>h.mutate({id:K.id,patch:{url:ue.target.value}})}),["text","template"].includes(K.type)&&e.jsx(Is,{rows:4,placeholder:"Body text or script",value:((J=K.content)==null?void 0:J.body)??"",onChange:ue=>h.mutate({id:K.id,patch:{content:{...K.content??{},body:ue.target.value}}})}),K.type==="checklist"&&e.jsx(Is,{rows:5,placeholder:"One item per line",value:(((ce=K.content)==null?void 0:ce.items)??[]).join(` `),onChange:ue=>h.mutate({id:K.id,patch:{content:{items:ue.target.value.split(` `).map(ne=>ne.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(Tn,{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(Tn,{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(Pn,{className:"h-3.5 w-3.5"}),"Delete"]})]})]})]})},K.id)})]})]})}),e.jsx("div",{className:"xl:col-span-3",children:e.jsxs(_e,{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(ua,{value:C,onValueChange:K=>A(K),children:e.jsxs(ha,{className:"h-8",children:[e.jsx(Qt,{value:"desktop",className:"h-6 px-2",children:e.jsx(Hj,{className:"h-3.5 w-3.5"})}),e.jsx(Qt,{value:"mobile",className:"h-6 px-2",children:e.jsx(dv,{className:"h-3.5 w-3.5"})})]})})]}),e.jsx("div",{className:C==="mobile"?"max-w-[320px] mx-auto":"",children:e.jsx(VWt,{kit:v,items:d,owner:{display_name:((W=r==null?void 0:r.user_metadata)==null?void 0:W.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 PGn({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(vs,{value:l,onValueChange:u=>o(u),children:[e.jsx(gs,{children:e.jsx(bs,{placeholder:"Choose agent"})}),e.jsxs(ys,{children:[e.jsx(Ye,{value:"general",children:"General share link"}),t.map(u=>e.jsxs(Ye,{value:u.id,children:[u.first_name," ",u.last_name??""]},u.id))]})]}),e.jsx(Is,{rows:2,placeholder:"Optional personal note shown on the page",value:c,onChange:u=>d(u.target.value)}),e.jsxs($,{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(vd,{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=NWt(u.share_token),m=u.agent_id?((p=t.find(x=>x.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($e,{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($,{size:"sm",variant:"outline",onClick:()=>{navigator.clipboard.writeText(h),ae.success("Link copied")},children:[e.jsx(Ca,{className:"h-3.5 w-3.5 mr-1"}),"Copy"]}),e.jsx($,{size:"sm",variant:"outline",asChild:!0,children:e.jsxs("a",{href:h,target:"_blank",rel:"noreferrer",children:[e.jsx(Tr,{className:"h-3.5 w-3.5 mr-1"}),"Open"]})}),e.jsxs($,{size:"sm",variant:"ghost",className:"text-rose-600",onClick:()=>a(u.id),children:[e.jsx(fz,{className:"h-3.5 w-3.5 mr-1"}),"Revoke"]})]})]},u.id)})]})]})}const IGn={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 DGn(){const{kitId:s}=Vi(),{data:t}=_Wt(s),{shares:n}=wWt(s),{data:r=[]}=jWt(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=Hs(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(nm,{eyebrow:"Kit analytics",title:(t==null?void 0:t.title)??"Kit",description:"Which value is actually creating conversations.",actions:e.jsx($,{variant:"outline",size:"sm",asChild:!0,className:"rounded-full",children:e.jsxs(Wn,{to:`/attract/provide/kits/${s}/edit`,children:[e.jsx(ka,{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(fA,{label:"Shares",value:a.shares,icon:ga,tone:"violet"}),e.jsx(fA,{label:"Unique agents",value:a.uniqueAgents,icon:ga,tone:"indigo"}),e.jsx(fA,{label:"View rate",value:`${a.viewRate}%`,icon:ga,tone:"teal"}),e.jsx(fA,{label:"Engaged",value:a.engaged,icon:uu,tone:"emerald"}),e.jsx(fA,{label:"Downloads",value:a.downloads,icon:di,tone:"orange"}),e.jsx(fA,{label:"CTA clicks",value:a.ctaClicks,icon:uu,tone:"rose"}),e.jsx(fA,{label:"Questions",value:a.questions,icon:Ed,tone:"violet"}),e.jsx(fA,{label:"Meetings",value:a.meetings,icon:Xu,tone:"indigo"})]}),e.jsxs("div",{className:"grid grid-cols-1 xl:grid-cols-3 gap-6",children:[e.jsxs(_e,{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(Ob,{width:"100%",height:"100%",children:e.jsxs(iYe,{data:i,children:[e.jsx(AO,{strokeDasharray:"3 3",stroke:"#eee"}),e.jsx(k1,{dataKey:"date",fontSize:11}),e.jsx(S1,{fontSize:11,allowDecimals:!1}),e.jsx(yf,{}),e.jsx(dF,{type:"monotone",dataKey:"count",stroke:"#7c3aed",strokeWidth:2})]})})})]}),e.jsxs(_e,{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(IGn).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(_e,{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 ",Hs(new Date(l.created_at),"MMM d")," · ",l.open_count," opens",l.last_opened_at&&` · last opened ${Hs(new Date(l.last_opened_at),"MMM d")}`]})]}),e.jsx($e,{variant:"secondary",className:"capitalize",children:l.engagement_level.replace("_"," ")})]},l.id))]})]})]})}function fA({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(_e,{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 RGn(){const{data:s=[],isLoading:t}=hHn(),n=mHn(),r=Vn(),a=async i=>{try{const l=await n.mutateAsync(i);ae.success("Added to your drafts"),r(`/attract/provide/kits/${l}/edit`)}catch(l){ae.error(l.message??"Could not clone template")}};return e.jsxs("div",{children:[e.jsx(nm,{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($,{variant:"outline",asChild:!0,className:"rounded-full",children:e.jsxs(Wn,{to:"/attract/provide/kits",children:[e.jsx(ka,{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(_e,{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(dn,{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($e,{variant:"outline",className:"capitalize",children:i.pillar}),(i.tags??[]).slice(0,4).map(o=>e.jsxs($e,{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($,{className:"mt-4 bg-gradient-to-r from-violet-600 to-indigo-600",onClick:()=>a(i.id),children:[e.jsx(wm,{className:"h-4 w-4 mr-2"}),"Use this kit"]})]},i.id)})})]})}const OGn=U,FGn=[...YT,BTe],zGn={hot:yd,warm:Kj,cold:Z_},eW=({label:s})=>e.jsxs("span",{className:"text-slate-400 italic",children:["Not recorded",s?` — add ${s}`:""]}),xA=s=>[s.first_name,s.last_name].filter(Boolean).join(" "),BGn=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 n9({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 $Gn={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 UGn(){const{agentId:s}=Vi(),t=Vn(),{item:n,timeline:r,valueShared:a,nextKit:i,isLoading:l,error:o,refetch:c}=pVn(s),{data:d=[]}=vte(),{upsertAgent:u,moveStage:h}=M0(),{followUps:m,complete:p}=NF(),x=fVn(),{gmailEmail:g}=ux(),[y,b]=j.useState("all"),[v,N]=j.useState(!1),[C,A]=j.useState(!1),[T,P]=j.useState("call"),[M,I]=j.useState(""),[D,B]=j.useState(""),[q,W]=j.useState(!1),[V,K]=j.useState(""),[Q,J]=j.useState(!1),[ce,ue]=j.useState(""),[ne,ee]=j.useState(new Date(Date.now()+3*864e5).toISOString().slice(0,10)),[le,he]=j.useState(null),[ve,ge]=j.useState(!1),fe=j.useMemo(()=>d.filter(Ae=>Ae.agent_id===s&&Ae.status==="open").sort((Ae,Be)=>Be.rank_score-Ae.rank_score),[d,s]),je=j.useMemo(()=>m.filter(Ae=>Ae.agent_id===s),[m,s]),Ee=j.useMemo(()=>{const Ae=Ubt.find(Be=>Be.key===y);return!Ae||!Ae.kinds.length?r:r.filter(Be=>Ae.kinds.includes(Be.kind))},[r,y]);if(l)return e.jsxs("div",{className:"space-y-4",children:[e.jsx(on,{className:"h-8 w-40"}),e.jsx(on,{className:"h-40 w-full rounded-2xl"}),e.jsx(on,{className:"h-64 w-full rounded-2xl"})]});if(o)return e.jsxs(_e,{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($,{className:"rounded-full mt-4",onClick:()=>c(),children:[e.jsx(Wi,{className:"h-4 w-4 mr-2"})," Try again"]})]});if(!n)return e.jsxs(_e,{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($,{className:"rounded-full mt-4",onClick:()=>t("/attract/relationships"),children:"Back to relationships"})]});const Me=n.agent,De=n.signals,ze=zGn[Me.temperature??""]??Kj,ke=()=>{x.mutate({agent_id:Me.id,activity_type:T,title:M||`${T.replace(/_/g," ")} with ${xA(Me)}`,description:D||void 0},{onSuccess:()=>{N(!1),I(""),B("")}})},Xe=async()=>{var Be;if(!V.trim())return;const Ae=[(Be=Me.notes)==null?void 0:Be.trim(),`[${new Date().toLocaleDateString()}] ${V.trim()}`].filter(Boolean).join(` `);u.mutate({id:Me.id,first_name:Me.first_name,notes:Ae},{onSuccess:()=>{W(!1),K(""),c()}}),x.mutate({agent_id:Me.id,activity_type:"note",title:"Note added",description:V.trim()})},Se=async()=>{if(!ce.trim()){ae.error("Give the follow-up a title");return}if(je.find(Ke=>!Ke.completed_at&&Ke.title.trim().toLowerCase()===ce.trim().toLowerCase())){ae.error("An open follow-up with that title already exists");return}const{data:Be}=await U.auth.getUser(),{error:qe}=await OGn.from("attract_follow_ups").insert({user_id:Be.user.id,agent_id:Me.id,title:ce.trim(),due_at:new Date(`${ne}T12:00:00`).toISOString(),touch_type:"call",priority:"medium"});if(qe){ae.error(qe.message);return}ae.success("Follow-up created"),J(!1),ue(""),c()},Re=()=>{le&&(window.open(le.href,"_self"),x.mutate({agent_id:Me.id,activity_type:le.kind,title:`${le.kind==="call"?"Called":le.kind==="text"?"Texted":"Emailed"} ${xA(Me)}`}),he(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(Wn,{to:"/attract",className:"hover:text-violet-700",children:"Attract"}),e.jsx(Ja,{className:"h-3 w-3"}),e.jsx(Wn,{to:"/attract/relationships",className:"hover:text-violet-700",children:"Relationships"}),e.jsx(Ja,{className:"h-3 w-3"}),e.jsx("span",{className:"text-slate-800 font-medium truncate",children:xA(Me)})]}),e.jsxs(_e,{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($,{variant:"ghost",size:"sm",className:"text-slate-300 hover:text-white -ml-2 mb-3 rounded-full",onClick:()=>t(-1),children:[e.jsx(ka,{className:"h-3.5 w-3.5 mr-1.5"})," Back"]}),e.jsxs("div",{className:"flex items-start gap-4 flex-wrap",children:[Me.photo_url?e.jsx("img",{src:Me.photo_url,alt:`${xA(Me)} 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:BGn(Me)}),e.jsxs("div",{className:"flex-1 min-w-[220px]",children:[e.jsx("h1",{className:"text-2xl font-semibold tracking-tight",children:xA(Me)}),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:Me.brokerage||"Brokerage not recorded"}),e.jsx("span",{className:"opacity-40",children:"·"}),e.jsx("span",{children:[Me.city,Me.state].filter(Boolean).join(", ")||"Market not recorded"}),Me.is_demo&&e.jsx($e,{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($e,{className:"rounded-full bg-white/10 text-white border-transparent",children:yWt(Me.stage)}),e.jsxs($e,{className:"rounded-full bg-white/10 text-white border-transparent capitalize inline-flex items-center gap-1",children:[e.jsx(ze,{className:"h-3 w-3"})," ",Me.temperature??"temperature unset"]}),e.jsx(eQe,{score:n.score,className:"bg-white/10 text-white ring-white/20"}),(Me.tags??[]).map(Ae=>e.jsx($e,{variant:"outline",className:"rounded-full bg-transparent text-slate-200 border-white/20",children:Ae},Ae))]})]}),e.jsxs("div",{className:"text-[12px] text-slate-300 space-y-1 min-w-[190px]",children:[e.jsx("div",{children:Me.email?e.jsx("a",{className:"hover:text-white underline decoration-white/30",href:`mailto:${Me.email}`,children:Me.email}):"No email on file"}),e.jsx("div",{children:Me.phone?e.jsx("a",{className:"hover:text-white underline decoration-white/30",href:`tel:${Me.phone}`,children:Me.phone}):"No phone on file"}),e.jsxs("div",{children:["Last meaningful touch: ",De.lastTouchAt?`${new Date(De.lastTouchAt).toLocaleDateString()} (${De.daysSinceTouch}d ago)`:"never logged"]}),e.jsxs("div",{children:["Next follow-up: ",Me.next_follow_up_at?new Date(Me.next_follow_up_at).toLocaleDateString():"none scheduled"]}),e.jsxs("div",{children:["Source: ",Me.source||"not recorded"," · Owner: ",Me.relationship_owner||"you"]})]})]})]}),e.jsxs("div",{className:"p-3 sm:p-4 bg-white flex flex-wrap gap-2",children:[e.jsxs($,{size:"sm",variant:"outline",className:"rounded-full",onClick:()=>A(!0),children:[e.jsx(Ya,{className:"h-3.5 w-3.5 mr-1.5"})," Edit contact"]}),e.jsxs(Os,{open:v,onOpenChange:N,children:[e.jsx(Ko,{asChild:!0,children:e.jsxs($,{size:"sm",className:"rounded-full btn-primary text-white",children:[e.jsx(Fr,{className:"h-3.5 w-3.5 mr-1.5"})," Log touch"]})}),e.jsxs(Rs,{children:[e.jsxs(Us,{children:[e.jsx(zs,{children:"Log a conversation"}),e.jsx(Sr,{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(se,{children:"Type"}),e.jsxs(vs,{value:T,onValueChange:P,children:[e.jsx(gs,{children:e.jsx(bs,{})}),e.jsx(ys,{children:["call","text","email","dm","meeting","note"].map(Ae=>e.jsx(Ye,{value:Ae,className:"capitalize",children:Ae},Ae))})]})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Title"}),e.jsx(be,{value:M,onChange:Ae=>I(Ae.target.value),placeholder:`Call with ${Me.first_name}`})]}),e.jsxs("div",{children:[e.jsx(se,{children:"What happened"}),e.jsx(Is,{rows:4,value:D,onChange:Ae=>B(Ae.target.value)})]})]}),e.jsx(kr,{children:e.jsx($,{className:"rounded-full btn-primary text-white",onClick:ke,disabled:x.isPending,children:"Log it"})})]})]}),e.jsxs(Os,{open:q,onOpenChange:W,children:[e.jsx(Ko,{asChild:!0,children:e.jsxs($,{size:"sm",variant:"outline",className:"rounded-full",children:[e.jsx(SR,{className:"h-3.5 w-3.5 mr-1.5"})," Add note"]})}),e.jsxs(Rs,{children:[e.jsx(Us,{children:e.jsx(zs,{children:"Add a relationship note"})}),e.jsx(Is,{rows:5,value:V,onChange:Ae=>K(Ae.target.value),placeholder:"What did you learn about them?"}),e.jsx(kr,{children:e.jsx($,{className:"rounded-full btn-primary text-white",onClick:Xe,children:"Save note"})})]})]}),e.jsxs($,{size:"sm",variant:"outline",className:"rounded-full",disabled:!Me.phone,onClick:()=>Me.phone&&he({kind:"call",href:`tel:${Me.phone}`}),children:[e.jsx(ya,{className:"h-3.5 w-3.5 mr-1.5"})," Call"]}),e.jsxs($,{size:"sm",variant:"outline",className:"rounded-full",disabled:!Me.phone,onClick:()=>Me.phone&&he({kind:"text",href:`sms:${Me.phone}`}),children:[e.jsx(Ji,{className:"h-3.5 w-3.5 mr-1.5"})," Text"]}),e.jsxs($,{size:"sm",variant:"outline",className:"rounded-full",disabled:!Me.email,onClick:()=>Me.email&&ge(!0),children:[e.jsx(nn,{className:"h-3.5 w-3.5 mr-1.5"})," Email"]}),e.jsx($,{size:"sm",variant:"outline",className:"rounded-full",asChild:!0,children:e.jsxs(Wn,{to:"/attract/provide/kits",children:[e.jsx(g1,{className:"h-3.5 w-3.5 mr-1.5"})," Share kit"]})}),e.jsx($,{size:"sm",variant:"outline",className:"rounded-full",asChild:!0,children:e.jsxs(Wn,{to:"/attract/events",children:[e.jsx(gg,{className:"h-3.5 w-3.5 mr-1.5"})," Invite to event"]})}),e.jsxs(Os,{open:Q,onOpenChange:J,children:[e.jsx(Ko,{asChild:!0,children:e.jsxs($,{size:"sm",variant:"outline",className:"rounded-full",children:[e.jsx(Hr,{className:"h-3.5 w-3.5 mr-1.5"})," Create follow-up"]})}),e.jsxs(Rs,{children:[e.jsx(Us,{children:e.jsx(zs,{children:"Create a follow-up"})}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx(se,{children:"What will you do?"}),e.jsx(be,{value:ce,onChange:Ae=>ue(Ae.target.value),placeholder:"Call about their Q3 goals"})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Due"}),e.jsx(be,{type:"date",value:ne,onChange:Ae=>ee(Ae.target.value)})]})]}),e.jsx(kr,{children:e.jsx($,{className:"rounded-full btn-primary text-white",onClick:Se,children:"Create"})})]})]}),e.jsxs(vs,{value:SB(Me.stage).key,onValueChange:Ae=>{const Be=nQe(Ae);Be!==Me.stage&&h.mutate({id:Me.id,to_stage:Be,from_stage:Me.stage})},children:[e.jsxs(gs,{className:"w-[230px] h-9 rounded-full text-[13px]","aria-label":"Change relationship stage",children:[e.jsx(QS,{className:"h-3.5 w-3.5 mr-1.5 opacity-60"}),e.jsx(bs,{})]}),e.jsx(ys,{children:FGn.map(Ae=>e.jsx(Ye,{value:Ae.key,children:e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"h-2 w-2 rounded-full",style:{background:Ae.color}}),Ae.label]})},Ae.key))})]})]})]}),e.jsx(Os,{open:!!le,onOpenChange:Ae=>!Ae&&he(null),children:e.jsxs(Rs,{children:[e.jsxs(Us,{children:[e.jsxs(zs,{children:["Open your ",(le==null?void 0:le.kind)==="email"?"email app":(le==null?void 0:le.kind)==="text"?"messaging app":"phone app","?"]}),e.jsx(Sr,{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(kr,{children:[e.jsx($,{variant:"ghost",className:"rounded-full",onClick:()=>he(null),children:"Cancel"}),e.jsx($,{className:"rounded-full btn-primary text-white",onClick:Re,children:"Continue"})]})]})}),e.jsxs(ua,{defaultValue:"overview",children:[e.jsx(ha,{className:"rounded-full bg-white border border-slate-200 p-1 flex-wrap h-auto",children:["overview","timeline","value","events","followups","notes"].map(Ae=>e.jsx(Qt,{value:Ae,className:"rounded-full text-[13px] capitalize data-[state=active]:bg-violet-600 data-[state=active]:text-white",children:Ae==="value"?"Value shared":Ae==="followups"?"Follow-ups":Ae==="notes"?"Notes & insights":Ae},Ae))}),e.jsxs(Jt,{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(_e,{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"}),fe[0]?e.jsx(Z4e,{rec:fe[0],agentName:xA(Me),agentStage:Me.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(_e,{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(n9,{label:"Goals",children:Me.goals||e.jsx(eW,{label:"their goals"})}),e.jsx(n9,{label:"Challenges",children:Me.challenges||e.jsx(eW,{label:"their challenges"})}),e.jsx(n9,{label:"Interests",children:Me.interests||e.jsx(eW,{label:"interests"})}),e.jsx(n9,{label:"Production context",children:Me.production_context||e.jsx(eW,{label:"production context"})}),e.jsx(n9,{label:"Primary pillar",children:Me.primary_pillar?e.jsx("span",{className:"capitalize",children:Me.primary_pillar}):e.jsx(eW,{label:"a pillar"})}),e.jsx(n9,{label:"Added to pipeline",children:new Date(Me.created_at).toLocaleDateString()})]})]}),e.jsx("div",{className:"grid sm:grid-cols-2 lg:grid-cols-4 gap-3",children:[{label:"Touches (90d)",value:De.touches90},{label:"Kits shared",value:De.shares.length},{label:"Kit opens",value:De.totalKitOpens},{label:"Events attended",value:De.attended}].map(Ae=>e.jsxs(_e,{className:"p-4 rounded-2xl",children:[e.jsx("div",{className:"text-2xl font-semibold tabular-nums text-slate-900",children:Ae.value}),e.jsx("div",{className:"text-[11.5px] text-slate-500 mt-0.5",children:Ae.label})]},Ae.label))})]}),e.jsxs(_e,{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(aWt,{score:n.score})]})]}),fe.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"}),fe.slice(1).map(Ae=>e.jsx(Z4e,{rec:Ae,agentName:xA(Me),showAgentLink:!1,compact:!0},Ae.id))]})]}),e.jsx(Jt,{value:"timeline",className:"mt-5",children:e.jsxs(_e,{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:Ubt.map(Ae=>e.jsx("button",{onClick:()=>b(Ae.key),className:Tt("rounded-full px-3 py-1.5 text-[12px] font-medium transition-colors",y===Ae.key?"bg-violet-600 text-white":"bg-slate-100 text-slate-600 hover:bg-slate-200"),children:Ae.label},Ae.key))}),e.jsxs($,{size:"sm",className:"rounded-full btn-primary text-white",onClick:()=>N(!0),children:[e.jsx(Fr,{className:"h-3.5 w-3.5 mr-1.5"})," Log something"]})]}),Ee.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"}),Ee.map(Ae=>e.jsxs("li",{className:"relative pb-5",children:[e.jsx("span",{"aria-hidden":!0,className:Tt("absolute -left-[15px] sm:-left-[18px] top-1.5 h-2.5 w-2.5 rounded-full ring-2 ring-white",$Gn[Ae.kind]??"bg-slate-300")}),e.jsx("div",{className:"text-[13.5px] font-medium text-slate-900",children:Ae.title}),Ae.detail&&e.jsx("div",{className:"text-[12.5px] text-slate-600 mt-0.5 whitespace-pre-wrap",children:Ae.detail}),e.jsxs("div",{className:"text-[11px] text-slate-400 mt-1",children:[new Date(Ae.at).toLocaleString()," · ",e.jsx("span",{className:"capitalize",children:Ae.kind.replace(/_/g," ")})]})]},Ae.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(Jt,{value:"value",className:"mt-5 space-y-4",children:[i&&e.jsxs(_e,{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($,{size:"sm",className:"rounded-full mt-3 btn-primary text-white",asChild:!0,children:e.jsx(Wn,{to:"/attract/provide/kits",children:"Open Resource Kits"})})]}),a.length?a.map(Ae=>e.jsxs(_e,{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:Ae.kitTitle}),e.jsxs("div",{className:"text-[12px] text-slate-500 mt-0.5",children:["Sent ",new Date(Ae.share.created_at).toLocaleDateString()," ·",Ae.firstViewedAt?` first viewed ${new Date(Ae.firstViewedAt).toLocaleDateString()}`:" never viewed",Ae.lastViewedAt?` · last viewed ${new Date(Ae.lastViewedAt).toLocaleDateString()}`:""]})]}),e.jsx($e,{variant:"outline",className:Tt("rounded-full border-transparent ring-1",Ae.classification==="High Intent"?"bg-rose-50 text-rose-700 ring-rose-200":Ae.classification==="Engaged"?"bg-teal-50 text-teal-700 ring-teal-200":Ae.classification==="Viewed"?"bg-amber-50 text-amber-700 ring-amber-200":"bg-slate-50 text-slate-600 ring-slate-200"),children:Ae.classification})]}),e.jsx("div",{className:"grid grid-cols-2 sm:grid-cols-5 gap-3 mt-4",children:[["Visits",Ae.visits],["Downloads",Ae.downloads],["Link clicks",Ae.ctaClicks],["Questions",Ae.questions],["Meeting asks",Ae.meetingRequests]].map(([Be,qe])=>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:qe}),e.jsx("div",{className:"text-[10.5px] text-slate-500",children:Be})]},Be))}),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:Ae.share.status})]}),e.jsxs("div",{children:["Follow-up after sharing: ",Ae.followUp?`${Ae.followUp.title}${Ae.followUp.completed_at?" (completed)":" (open)"}`:"none created"]}),e.jsxs("div",{children:["Stage movement after sharing: ",Ae.stageAdvancedAfter?`moved to ${Ae.stageAdvancedAfter.to_stage.replace(/_/g," ")} on ${new Date(Ae.stageAdvancedAfter.created_at).toLocaleDateString()}`:"no stage movement yet"]})]}),e.jsx($,{size:"sm",variant:"outline",className:"rounded-full mt-3",asChild:!0,children:e.jsxs("a",{href:Ae.shareUrl,target:"_blank",rel:"noreferrer",children:["Open share link ",e.jsx(Tr,{className:"h-3.5 w-3.5 ml-1.5"})]})})]},Ae.share.id)):e.jsxs(_e,{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(Jt,{value:"events",className:"mt-5 space-y-3",children:De.attendees.length?De.attendees.map(Ae=>e.jsx(_e,{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(Wn,{to:`/attract/events/${Ae.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:[Ae.invited_at&&`Invited ${new Date(Ae.invited_at).toLocaleDateString()} · `,Ae.registered_at?`Registered ${new Date(Ae.registered_at).toLocaleDateString()}`:"Not registered",Ae.checked_in_at&&` · Attended ${new Date(Ae.checked_in_at).toLocaleDateString()}`,Ae.no_show_at&&" · No-show"]})]}),e.jsx($e,{variant:"outline",className:"rounded-full capitalize",children:Ae.followup_status?`follow-up ${Ae.followup_status}`:Ae.status??"invited"})]})},Ae.id)):e.jsxs(_e,{className:"p-8 rounded-2xl text-center",children:[e.jsx(t1,{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($,{size:"sm",className:"rounded-full mt-4 btn-primary text-white",asChild:!0,children:e.jsx(Wn,{to:"/attract/events",children:"See your events"})})]})}),e.jsx(Jt,{value:"followups",className:"mt-5 space-y-3",children:je.length?je.map(Ae=>{const Be=!Ae.completed_at&&Ae.due_at&&new Date(Ae.due_at)p.mutate(Ae.id),children:[e.jsx(Fr,{className:"h-3.5 w-3.5 mr-1.5"})," Complete"]})]},Ae.id)}):e.jsxs(_e,{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($,{size:"sm",className:"rounded-full mt-4 btn-primary text-white",onClick:()=>J(!0),children:"Create one"})]})}),e.jsxs(Jt,{value:"notes",className:"mt-5 space-y-4",children:[e.jsxs(_e,{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($,{size:"sm",variant:"outline",className:"rounded-full",onClick:()=>W(!0),children:"Add note"})]}),Me.notes?e.jsx("div",{className:"text-[13.5px] text-slate-700 whitespace-pre-wrap",children:Me.notes}):e.jsx("div",{className:"text-[13px] text-slate-500",children:"No notes recorded yet."})]}),e.jsxs(_e,{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(Ae=>`Strength: ${Ae}`),...n.score.negatives.map(Ae=>`Risk: ${Ae}`),...n.score.improvements.map(Ae=>`Next: ${Ae}`)].map((Ae,Be)=>e.jsx("li",{children:Ae},Be))})]})]})]}),e.jsx(rQe,{agent:Me,open:C,onOpenChange:A,onDeleted:()=>t("/attract/relationships")}),Me.email&&e.jsx(x2,{open:ve,onOpenChange:ge,contact:{id:Me.id,first_name:Me.preferred_name||Me.first_name,last_name:Me.last_name||"",email:Me.email},gmailEmail:g,sendSource:"attract",logTouchpoint:!1,onSendComplete:()=>{x.mutate({agent_id:Me.id,activity_type:"email",title:`Emailed ${xA(Me)}`})}})]})}const qGn=[{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 VGn(){const{intel:s,byId:t,isLoading:n,error:r,refetch:a}=sM(),{data:i=[],isLoading:l}=vte(),o=RTe();OTe();const[c,d]=j.useState(""),[u,h]=j.useState("all"),[m,p]=j.useState("open"),x=b=>{var N;const v=(N=t.get(b))==null?void 0:N.agent;return v?[v.first_name,v.last_name].filter(Boolean).join(" "):"Unknown agent"},g=j.useMemo(()=>{const b=Date.now();return i.filter(v=>m==="open"?v.status==="open"||v.status==="snoozed"&&v.snoozed_until&&+new Date(v.snoozed_until)<=b:m==="snoozed"?v.status==="snoozed":m==="done"?v.status==="completed":m==="dismissed"?v.status==="dismissed":!0).filter(v=>u==="all"||v.signal_group===u).filter(v=>{if(!c.trim())return!0;const N=c.toLowerCase();return x(v.agent_id).toLowerCase().includes(N)||v.title.toLowerCase().includes(N)||(v.reasons??[]).join(" ").toLowerCase().includes(N)}).sort((v,N)=>N.rank_score-v.rank_score)},[i,m,u,c,t]),y=j.useMemo(()=>{const b=i.filter(v=>v.status==="open");return{open:b.length,urgent:b.filter(v=>v.priority==="urgent").length,highIntent:b.filter(v=>v.signal_group==="high_intent").length,overdue:b.filter(v=>v.suggested_due_at&&+new Date(v.suggested_due_at)e.jsx(on,{className:"h-28 w-full rounded-2xl"},b))}):r?e.jsxs(_e,{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($,{className:"rounded-full mt-4",onClick:()=>a(),children:[e.jsx(Wi,{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($,{variant:"outline",className:"rounded-full",onClick:()=>o.mutate(s),disabled:o.isPending,children:[e.jsx(Wi,{className:Tt("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(b=>e.jsxs(_e,{className:"p-4 rounded-2xl",children:[e.jsx("div",{className:"text-2xl font-semibold tabular-nums text-slate-900",children:b.value}),e.jsx("div",{className:"text-[11.5px] text-slate-500 mt-0.5",children:b.label})]},b.label))}),e.jsxs(_e,{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(Vr,{className:"h-4 w-4 absolute left-3 top-1/2 -translate-y-1/2 text-slate-400"}),e.jsx(be,{value:c,onChange:b=>d(b.target.value),placeholder:"Search agents or reasons",className:"pl-9 rounded-full h-9","aria-label":"Search recommendations"})]}),e.jsxs(vs,{value:u,onValueChange:h,children:[e.jsxs(gs,{className:"w-[190px] h-9 rounded-full text-[13px]",children:[e.jsx($j,{className:"h-3.5 w-3.5 mr-1.5 opacity-60"}),e.jsx(bs,{})]}),e.jsx(ys,{children:qGn.map(b=>e.jsx(Ye,{value:b.key,children:b.label},b.key))})]}),e.jsxs(vs,{value:m,onValueChange:p,children:[e.jsx(gs,{className:"w-[150px] h-9 rounded-full text-[13px]",children:e.jsx(bs,{})}),e.jsxs(ys,{children:[e.jsx(Ye,{value:"open",children:"Needs action"}),e.jsx(Ye,{value:"snoozed",children:"Snoozed"}),e.jsx(Ye,{value:"done",children:"Completed"}),e.jsx(Ye,{value:"dismissed",children:"Dismissed"}),e.jsx(Ye,{value:"all",children:"All"})]})]})]}),g.length?e.jsx("div",{className:"space-y-3",children:g.map(b=>{var v;return e.jsx(Z4e,{rec:b,agentName:x(b.agent_id),agentStage:(v=t.get(b.agent_id))==null?void 0:v.agent.stage},b.id)})}):i.length?e.jsx(DVn,{label:"Nothing matches this view. Try switching the filter."}):e.jsxs(_e,{className:"p-10 rounded-2xl text-center",children:[e.jsx(dn,{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($,{className:"rounded-full btn-primary text-white",asChild:!0,children:e.jsx(Wn,{to:"/attract/pipeline",children:"Open pipeline"})}),e.jsx($,{variant:"outline",className:"rounded-full",asChild:!0,children:e.jsx(Wn,{to:"/attract/provide/kits",children:"Share a kit"})})]})]}),!!g.length&&e.jsxs("div",{className:"text-[11.5px] text-slate-400",children:["Showing ",g.length," of ",i.length," tracked recommendations · grouped signals: ",[...new Set(g.map(b=>xWt(b.signal_group)))].join(", ")]})]})}const _Re=s=>[s.first_name,s.last_name].filter(Boolean).join(" ");function HGn(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 HWt(s,t,n=new Date){const r=HGn(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:_Re(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 D=M(I);return D?{agent_id:I.agent.id,agent_name:_Re(I.agent),detail:D}: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),x=t.shares.filter(M=>new Date(M.created_at)>=i),g={shares:x.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}))},b=[...s.filter(M=>M.agent.next_follow_up_at&&new Date(M.agent.next_follow_up_at)>n&&og(n,M.agent.next_follow_up_at)<=7).slice(0,5).map(M=>({label:_Re(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),v=t.activities.filter(M=>new Date(M.created_at)>=i),N={produce:0,influence:0,provide:0,connect:0};for(const M of v)M.pillar&&N[M.pillar]!==void 0&&N[M.pillar]++;const C=Object.entries(N).map(([M,I])=>({pillar:M,count:I})),A=C.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.`,P={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:v.filter(M=>["touch_logged","call","text","email","dm","meeting"].includes(M.activity_type)).length,kits_shared:x.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:g,event_summary:y,upcoming_opportunities:b,pillar_balance:C,recommended_focus:T,wins:P}}function m_t(s,t){const n=l=>String(l??"").replace(/[<>&]/g,o=>({"<":"<",">":">","&":"&"})[o]),r=(l,o)=>o?`
${n(l)}
${o}`:"",a=l=>l.length?`
    ${l.map(o=>`
  • ${n(o.agent_name)} — ${n(o.detail)}
  • `).join("")}
`:"",i=s.conversations.map(l=>`
${l.rank}. ${n(l.agent_name)} ${n(l.channel.replace(/_/g," "))} health ${l.score}
Why: ${n(l.reason)}
${n(l.draft_message)}
Open relationship →
`).join("");return`
${r("Five conversations for this week",i||'
No recommended conversations yet — add agents to your pipeline.
')} ${r("High-intent signals",a(s.high_intent))} ${r("Renewed interest",a(s.renewed))} ${r("Overdue commitments",a(s.overdue))} ${r("Going quiet",a(s.stale))} ${r("Resource kit engagement",`
${s.kit_summary.shares} shared · ${s.kit_summary.opened} opened · ${s.kit_summary.engaged} engaged · ${s.kit_summary.high_intent} high intent · ${s.kit_summary.downloads} downloads · ${s.kit_summary.questions} questions
`)} ${r("Events",`
${s.event_summary.invited} invited · ${s.event_summary.registered} registered · ${s.event_summary.attended} attended · ${s.event_summary.no_shows} no-shows · ${s.event_summary.follow_ups_pending} follow-ups pending
`)} ${r("Four-pillar balance",`
${s.pillar_balance.map(l=>`${l.pillar}: ${l.count}`).join(" · ")}
${n(s.recommended_focus)}
`)} ${r("Wins this week",`
${s.wins.advanced} relationships advanced · ${s.wins.follow_ups_completed} follow-ups completed · ${s.wins.conversations_logged} conversations logged · ${s.wins.kits_shared} kits shared
`)}
LevelUp Attract
Your Weekly Attraction Digest
Week of ${s.week_start} → ${s.week_end}
Open Relationship Opportunities
`}const z3=U;function GGn(){const{user:s}=_s(),t=ts(),n=ht({queryKey:["attract-digest-settings",s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:a,error:i}=await z3.from("attract_digest_settings").select("*").eq("user_id",s.id).maybeSingle();if(i)throw i;return a??null}}),r=yt({mutationFn:async a=>{const{error:i}=await z3.from("attract_digest_settings").upsert({user_id:s.id,...a},{onConflict:"user_id"});if(i)throw i},onSuccess:()=>{t.invalidateQueries({queryKey:["attract-digest-settings"]}),ae.success("Digest settings saved")},onError:a=>ae.error(a.message)});return{settings:n.data,isLoading:n.isLoading,save:r}}function WGn(){const{user:s}=_s();return ht({queryKey:["attract-digests",s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await z3.from("attract_digests").select("*").order("week_start",{ascending:!1}).limit(26);if(n)throw n;return t??[]}})}function KGn(s){const t=ts(),n=ht({queryKey:["attract-digest-items",s],enabled:!!s,queryFn:async()=>{const{data:a,error:i}=await z3.from("attract_digest_items").select("*").eq("digest_id",s).order("rank");if(i)throw i;return a??[]}}),r=yt({mutationFn:async a=>{const{error:i}=await z3.from("attract_digest_items").update({completed_at:new Date().toISOString()}).eq("id",a);if(i)throw i},onSuccess:()=>{t.invalidateQueries({queryKey:["attract-digest-items",s]}),ae.success("Marked as done")}});return{items:n.data??[],isLoading:n.isLoading,markComplete:r}}function YGn(){const{user:s}=_s(),t=ts();return yt({mutationFn:async n=>{const{data:r,error:a}=await z3.from("attract_digests").upsert({user_id:s.id,week_start:n.week_start,payload:n,delivery_status:"generated",generated_at:n.generated_at},{onConflict:"user_id,week_start"}).select("id").single();if(a)throw a;const i=r.id;await z3.from("attract_digest_items").delete().eq("digest_id",i).is("completed_at",null);const{data:l}=await z3.from("attract_digest_items").select("agent_id").eq("digest_id",i),o=new Set((l??[]).map(d=>d.agent_id)),c=n.conversations.filter(d=>!o.has(d.agent_id)).map(d=>({digest_id:i,user_id:s.id,agent_id:d.agent_id,rank:d.rank,agent_name:d.agent_name,reason:d.reason,channel:d.channel,draft_message:d.draft_message}));if(c.length){const{error:d}=await z3.from("attract_digest_items").insert(c);if(d)throw d}return i},onSuccess:()=>{t.invalidateQueries({queryKey:["attract-digests"]}),t.invalidateQueries({queryKey:["attract-digest-items"]})},onError:n=>ae.error(n.message)})}function ZGn(){const s=ts();return yt({mutationFn:async t=>{const{data:n,error:r}=await U.functions.invoke("attract-send-digest",{body:t});if(r)throw r;return n},onSuccess:t=>{s.invalidateQueries({queryKey:["attract-digests"]}),t!=null&&t.ok?ae.success("Digest email sent"):ae.error((t==null?void 0:t.reason)||"Email delivery is not configured yet")},onError:t=>ae.error(t.message??"Send failed")})}const XGn=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"];function r9({title:s,children:t}){return e.jsxs("div",{children:[e.jsx("div",{className:"text-[11px] uppercase tracking-wider font-semibold text-slate-500 mb-2",children:s}),t]})}function Gae({rows:s,empty:t}){return s.length?e.jsx("ul",{className:"space-y-1.5",children:s.map(n=>e.jsxs("li",{className:"text-[13px] text-slate-700",children:[e.jsx(Wn,{to:`/attract/agents/${n.agent_id}`,className:"font-medium text-slate-900 hover:text-violet-700",children:n.agent_name}),e.jsxs("span",{className:"text-slate-500",children:[" — ",n.detail]})]},n.agent_id+n.detail))}):e.jsx("div",{className:"text-[13px] text-slate-500",children:t})}function QGn(){var T;const{user:s}=_s(),{intel:t,dataset:n,isLoading:r}=sM(),{settings:a,save:i}=GGn(),{data:l=[]}=WGn(),o=YGn(),c=ZGn(),[d,u]=j.useState(),h=d??((T=l[0])==null?void 0:T.id),{items:m,markComplete:p}=KGn(h),[x,g]=j.useState(""),y=j.useMemo(()=>n?HWt(t,n):null,[t,n]),b=l.find(P=>P.id===h),v=(b==null?void 0:b.payload)??y,N=x||(a==null?void 0:a.email)||(s==null?void 0:s.email)||"",C=()=>{y&&o.mutate(y,{onSuccess:P=>{u(P),ae.success("This week's digest is ready")}})},A=P=>{if(!v)return;if(!N){ae.error("Add an email address first");return}const M=I=>c.mutate({digestId:I,to:N,subject:`Your Weekly Attraction Digest — ${v.week_start}`,html:m_t(v,window.location.origin),test:P});b?M(b.id):y&&o.mutate(y,{onSuccess:I=>{u(I),M(I)}})};return r||!v?e.jsxs("div",{className:"space-y-4",children:[e.jsx(on,{className:"h-10 w-56"}),e.jsx(on,{className:"h-72 w-full rounded-2xl"})]}):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:"Weekly Attraction Digest"}),e.jsxs("p",{className:"text-[13.5px] text-slate-500 mt-1",children:["Week of ",new Date(`${v.week_start}T12:00:00`).toLocaleDateString()," – ",new Date(`${v.week_end}T12:00:00`).toLocaleDateString(),b&&e.jsxs(e.Fragment,{children:[" · ",e.jsx("span",{className:"capitalize",children:b.delivery_status.replace(/_/g," ")}),b.sent_at?` ${new Date(b.sent_at).toLocaleString()}`:""]})]})]}),e.jsxs("div",{className:"flex gap-2 flex-wrap",children:[e.jsxs($,{variant:"outline",className:"rounded-full",onClick:C,disabled:o.isPending,children:[e.jsx(Wi,{className:Tt("h-3.5 w-3.5 mr-1.5",o.isPending&&"animate-spin")})," Regenerate"]}),e.jsxs($,{variant:"outline",className:"rounded-full",onClick:()=>{navigator.clipboard.writeText(m_t(v,window.location.origin)),ae.success("Digest HTML copied")},children:[e.jsx(Ca,{className:"h-3.5 w-3.5 mr-1.5"})," Copy HTML"]}),e.jsxs($,{className:"rounded-full btn-primary text-white",onClick:()=>A(!0),disabled:c.isPending,children:[e.jsx(Br,{className:"h-3.5 w-3.5 mr-1.5"})," Email it to me"]})]})]}),e.jsxs(ua,{defaultValue:"digest",children:[e.jsx(ha,{className:"rounded-full bg-white border border-slate-200 p-1",children:[["digest","This week"],["history","History"],["settings","Delivery settings"]].map(([P,M])=>e.jsx(Qt,{value:P,className:"rounded-full text-[13px] data-[state=active]:bg-violet-600 data-[state=active]:text-white",children:M},P))}),e.jsxs(Jt,{value:"digest",className:"mt-5 space-y-5",children:[e.jsx("div",{className:"grid grid-cols-2 lg:grid-cols-4 gap-3",children:[["Conversations logged",v.wins.conversations_logged],["Stage moves",v.wins.advanced],["Follow-ups completed",v.wins.follow_ups_completed],["Kits shared",v.wins.kits_shared]].map(([P,M])=>e.jsxs(_e,{className:"p-4 rounded-2xl",children:[e.jsx("div",{className:"text-2xl font-semibold tabular-nums text-slate-900",children:M}),e.jsx("div",{className:"text-[11.5px] text-slate-500 mt-0.5",children:P})]},P))}),e.jsxs(_e,{className:"p-5 rounded-2xl",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-wider font-semibold text-violet-600 mb-3",children:"Your five conversations this week"}),v.conversations.length?e.jsx("div",{className:"space-y-3",children:v.conversations.map(P=>{const M=m.find(D=>D.agent_id===P.agent_id),I=!!(M!=null&&M.completed_at);return e.jsxs("div",{className:Tt("rounded-xl border border-slate-200 p-4",I&&"bg-emerald-50/60 border-emerald-200"),children:[e.jsxs("div",{className:"flex items-start justify-between gap-3 flex-wrap",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"text-[14.5px] font-semibold text-slate-900",children:[P.rank,". ",e.jsx(Wn,{to:`/attract/agents/${P.agent_id}`,className:"hover:text-violet-700",children:P.agent_name})]}),e.jsx("div",{className:"text-[12.5px] text-slate-600 mt-0.5",children:P.reason})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx($e,{variant:"outline",className:"rounded-full capitalize",children:P.channel}),e.jsxs($e,{variant:"outline",className:"rounded-full",children:["Health ",P.score]})]})]}),P.draft_message&&e.jsx("div",{className:"mt-3 rounded-lg bg-slate-50 p-3 text-[13px] text-slate-700 whitespace-pre-wrap",children:P.draft_message}),e.jsxs("div",{className:"flex gap-2 mt-3",children:[e.jsxs($,{size:"sm",variant:"outline",className:"rounded-full",onClick:()=>{navigator.clipboard.writeText(P.draft_message||""),ae.success("Copied")},children:[e.jsx(Ca,{className:"h-3.5 w-3.5 mr-1.5"})," Copy"]}),M&&!I&&e.jsxs($,{size:"sm",className:"rounded-full btn-primary text-white",onClick:()=>p.mutate(M.id),children:[e.jsx(Fr,{className:"h-3.5 w-3.5 mr-1.5"})," Mark done"]}),I&&e.jsx("span",{className:"text-[12.5px] text-emerald-700 font-medium self-center",children:"Completed"}),e.jsx($,{size:"sm",variant:"ghost",className:"rounded-full",asChild:!0,children:e.jsx(Wn,{to:`/attract/agents/${P.agent_id}`,children:"Open relationship"})})]})]},P.agent_id)})}):e.jsx("div",{className:"text-[13px] text-slate-500",children:"No conversations to recommend yet — Attract needs real signals first."})]}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-4",children:[e.jsxs(_e,{className:"p-5 rounded-2xl space-y-4",children:[e.jsx(r9,{title:"High intent",children:e.jsx(Gae,{rows:v.high_intent,empty:"No high-intent signals this week."})}),e.jsx(r9,{title:"Renewed interest",children:e.jsx(Gae,{rows:v.renewed,empty:"Nobody re-engaged after going quiet."})})]}),e.jsxs(_e,{className:"p-5 rounded-2xl space-y-4",children:[e.jsx(r9,{title:"Overdue commitments",children:e.jsx(Gae,{rows:v.overdue,empty:"Nothing overdue. Well kept."})}),e.jsx(r9,{title:"Going cold",children:e.jsx(Gae,{rows:v.stale,empty:"No relationships past 60 days of silence."})})]}),e.jsx(_e,{className:"p-5 rounded-2xl",children:e.jsx(r9,{title:"Value shared",children:e.jsxs("div",{className:"text-[13px] text-slate-700 space-y-1",children:[e.jsxs("div",{children:[v.kit_summary.shares," kits shared · ",v.kit_summary.opened," opened"]}),e.jsxs("div",{children:[v.kit_summary.downloads," downloads · ",v.kit_summary.questions," questions asked"]}),e.jsxs("div",{children:[v.kit_summary.engaged," engaged · ",v.kit_summary.high_intent," high intent"]})]})})}),e.jsx(_e,{className:"p-5 rounded-2xl",children:e.jsx(r9,{title:"Events",children:e.jsxs("div",{className:"text-[13px] text-slate-700 space-y-1",children:[e.jsxs("div",{children:[v.event_summary.invited," invited · ",v.event_summary.registered," registered"]}),e.jsxs("div",{children:[v.event_summary.attended," attended · ",v.event_summary.no_shows," no-shows"]}),e.jsxs("div",{children:[v.event_summary.follow_ups_pending," attendee follow-ups still pending"]}),v.event_summary.upcoming.map(P=>e.jsxs("div",{className:"text-slate-600 flex items-center gap-1.5",children:[e.jsx(Nl,{className:"h-3.5 w-3.5"})," ",P.title,P.starts_at?` — ${new Date(P.starts_at).toLocaleDateString()}`:""]},P.title))]})})})]}),e.jsxs(_e,{className:"p-5 rounded-2xl bg-gradient-to-r from-violet-50 to-indigo-50 border-violet-100",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-wider font-semibold text-violet-700",children:"Recommended focus"}),e.jsx("p",{className:"text-[14px] text-slate-800 mt-1.5",children:v.recommended_focus}),e.jsx("div",{className:"flex gap-2 mt-3 flex-wrap",children:v.pillar_balance.map(P=>e.jsxs($e,{variant:"outline",className:"rounded-full capitalize bg-white/70",children:[P.pillar,": ",P.count]},P.pillar))})]})]}),e.jsx(Jt,{value:"history",className:"mt-5 space-y-3",children:l.length?l.map(P=>e.jsxs(_e,{className:Tt("p-4 rounded-2xl flex items-center justify-between gap-3 flex-wrap",P.id===h&&"ring-1 ring-violet-300"),children:[e.jsxs("div",{children:[e.jsxs("div",{className:"text-[14px] font-semibold text-slate-900",children:["Week of ",new Date(`${P.week_start}T12:00:00`).toLocaleDateString()]}),e.jsxs("div",{className:"text-[12px] text-slate-500 mt-0.5",children:[e.jsx("span",{className:"capitalize",children:P.delivery_status.replace(/_/g," ")}),P.sent_at&&` · sent ${new Date(P.sent_at).toLocaleString()}`,P.delivery_note&&` · ${P.delivery_note}`]})]}),e.jsx($,{size:"sm",variant:"outline",className:"rounded-full",onClick:()=>u(P.id),children:"View"})]},P.id)):e.jsx(_e,{className:"p-8 rounded-2xl text-center text-[13.5px] text-slate-500",children:"No digests generated yet."})}),e.jsx(Jt,{value:"settings",className:"mt-5",children:e.jsxs(_e,{className:"p-5 rounded-2xl max-w-xl space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[14px] font-medium text-slate-900",children:"Weekly email"}),e.jsx("div",{className:"text-[12.5px] text-slate-500",children:"Send the digest automatically each week."})]}),e.jsx(Tn,{checked:!!(a!=null&&a.enabled),onCheckedChange:P=>i.mutate({enabled:P})})]}),e.jsxs("div",{className:"grid sm:grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(se,{children:"Day"}),e.jsxs(vs,{value:String((a==null?void 0:a.weekday)??1),onValueChange:P=>i.mutate({weekday:Number(P)}),children:[e.jsx(gs,{children:e.jsx(bs,{})}),e.jsx(ys,{children:XGn.map((P,M)=>e.jsx(Ye,{value:String(M),children:P},P))})]})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Hour (local)"}),e.jsxs(vs,{value:String((a==null?void 0:a.send_hour)??7),onValueChange:P=>i.mutate({send_hour:Number(P)}),children:[e.jsx(gs,{children:e.jsx(bs,{})}),e.jsx(ys,{children:Array.from({length:24},(P,M)=>e.jsxs(Ye,{value:String(M),children:[M,":00"]},M))})]})]})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Send to"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(be,{value:x||(a==null?void 0:a.email)||(s==null?void 0:s.email)||"",onChange:P=>g(P.target.value),placeholder:"you@example.com"}),e.jsx($,{variant:"outline",className:"rounded-full",onClick:()=>i.mutate({email:N}),children:"Save"})]})]}),e.jsxs("div",{className:"rounded-xl bg-amber-50 border border-amber-200 p-3 text-[12.5px] text-amber-900 flex gap-2",children:[e.jsx(nn,{className:"h-4 w-4 mt-0.5 shrink-0"}),`Automatic weekly scheduling is not wired to a scheduler yet — use "Email it to me" to send on demand. If delivery isn't configured, the digest is still saved here and the status will say so honestly.`]})]})})]})]})}const KM=U,JGn=[{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 eWn(){const{user:s}=_s(),t=ts(),{intel:n,dataset:r,isLoading:a,refetch:i}=sM(),l=RTe(),o=nWt(),[c,d]=j.useState(""),[u,h]=j.useState(!1),m=j.useMemo(()=>r?HWt(n,r):null,[n,r]),p=j.useMemo(()=>{const y=c.toLowerCase().trim();return n.filter(b=>!y||`${b.agent.first_name} ${b.agent.last_name??""}`.toLowerCase().includes(y))},[n,c]),x=async()=>{if(!s)return;h(!0);const{data:y}=await KM.from("attract_agents").select("id").eq("user_id",s.id).eq("is_demo",!0);if((y??[]).length){ae.info("Demo agents already exist"),h(!1);return}const{data:b,error:v}=await KM.from("attract_agents").insert(JGn.map(C=>({...C,user_id:s.id,is_demo:!0,source:"demo_seed"}))).select("id, first_name");if(v){ae.error(v.message),h(!1);return}const N=Date.now();await KM.from("attract_activities").insert((b??[]).map((C,A)=>({user_id:s.id,agent_id:C.id,activity_type:"touch_logged",pillar:"connect",title:`Demo conversation with ${C.first_name}`,created_at:new Date(N-(A+1)*14*864e5).toISOString()}))),await KM.from("attract_follow_ups").insert({user_id:s.id,agent_id:b[0].id,title:"Demo overdue commitment",touch_type:"call",priority:"high",due_at:new Date(N-6*864e5).toISOString()}),ae.success("Demo relationships seeded"),h(!1),t.invalidateQueries({queryKey:["attract-intel-data"]}),i()},g=async()=>{if(!s)return;h(!0);const{data:y}=await KM.from("attract_agents").select("id").eq("user_id",s.id).eq("is_demo",!0),b=(y??[]).map(v=>v.id);if(!b.length){ae.info("No demo data to clear"),h(!1);return}for(const v of["attract_recommendations","attract_agent_scores","attract_follow_ups","attract_activities"])await KM.from(v).delete().in("agent_id",b);await KM.from("attract_agents").delete().in("id",b),ae.success("Demo data removed"),h(!1),t.invalidateQueries({queryKey:["attract-intel-data"]}),i()};return a?e.jsx(on,{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($,{variant:"ghost",size:"sm",className:"rounded-full -ml-2",asChild:!0,children:e.jsxs(Wn,{to:"/admin",children:[e.jsx(ka,{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($,{variant:"outline",className:"rounded-full",onClick:()=>{o.mutate({items:n}),l.mutate(n)},disabled:l.isPending||o.isPending,children:[e.jsx(Wi,{className:"h-3.5 w-3.5 mr-1.5"})," Recompute & persist"]}),e.jsxs($,{variant:"outline",className:"rounded-full",onClick:x,disabled:u,children:[e.jsx(xK,{className:"h-3.5 w-3.5 mr-1.5"})," Seed demo relationships"]}),e.jsxs($,{variant:"outline",className:"rounded-full text-destructive",onClick:g,disabled:u,children:[e.jsx(Pn,{className:"h-3.5 w-3.5 mr-1.5"})," Clear demo data"]})]}),e.jsxs(ua,{defaultValue:"agents",children:[e.jsxs(ha,{className:"rounded-full",children:[e.jsx(Qt,{value:"agents",className:"rounded-full",children:"Scores & signals"}),e.jsx(Qt,{value:"digest",className:"rounded-full",children:"Digest payload"})]}),e.jsxs(Jt,{value:"agents",className:"mt-4 space-y-3",children:[e.jsx(be,{value:c,onChange:y=>d(y.target.value),placeholder:"Filter by name",className:"max-w-sm rounded-full"}),!p.length&&e.jsx(_e,{className:"p-6 rounded-2xl text-[13.5px] text-muted-foreground",children:"No agents in your Attract pipeline."}),p.map(y=>e.jsxs(_e,{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(Wn,{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($e,{variant:"outline",className:"rounded-full",children:"Demo"})]}),e.jsxs("div",{className:"grid md:grid-cols-2 gap-4 mt-4",children:[e.jsx(aWt,{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(b=>e.jsxs("li",{className:"text-[12.5px]",children:[e.jsx("span",{className:"font-medium",children:b.title}),e.jsxs("span",{className:"text-muted-foreground",children:[" · ",b.signal_group," · rank ",b.rank_score," · ",b.priority]}),e.jsx("div",{className:"text-muted-foreground",children:b.reasons.join(" · ")})]},b.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(Jt,{value:"digest",className:"mt-4",children:e.jsx(_e,{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)})})})]})]})}function tWn(){const[s,t]=j.useState(""),[n,r]=j.useState("all"),a=j.useMemo(()=>$Ue.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 $Ue.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($,{variant:"ghost",size:"sm",className:"rounded-full -ml-2",asChild:!0,children:e.jsxs(Wn,{to:"/admin",children:[e.jsx(ka,{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(_e,{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:UUe[l]})]},l))}),e.jsxs("div",{className:"flex gap-2 flex-wrap",children:[e.jsx(be,{value:s,onChange:l=>t(l.target.value),placeholder:"Filter tools",className:"max-w-sm rounded-full"}),n!=="all"&&e.jsx($,{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(_e,{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($e,{variant:"outline",className:"rounded-full capitalize",children:l.pillar}),e.jsx($e,{variant:"outline",className:`rounded-full ${bWt[l.status]}`,children:UUe[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($,{variant:"outline",size:"sm",className:"rounded-full",asChild:!0,children:e.jsxs(Wn,{to:l.route,children:[l.route," ",e.jsx(Tr,{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}`))})]})}const YM=U,p_t=["idea","researching","pitching","applied","tentative","confirmed","completed","declined","archived"],f_t=["panel","keynote","mls_talk","podcast","webinar","mastermind","training","conference","other"],x_t=["attract-speaking"];function GWt(){const{user:s}=_s(),t=ts(),n=ht({queryKey:[...x_t,s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:u,error:h}=await YM.from("attract_speaking_opportunities").select("*").order("starts_at",{ascending:!0,nullsFirst:!1});if(h)throw h;return u??[]}}),r=()=>{t.invalidateQueries({queryKey:x_t}),t.invalidateQueries({queryKey:["attract-followups"]}),t.invalidateQueries({queryKey:["attract-activities"]})},a=yt({mutationFn:async u=>{const{data:h,error:m}=await YM.from("attract_speaking_opportunities").insert({...u,user_id:s.id}).select("*").single();if(m)throw m;return h},onSuccess:()=>{r(),ae.success("Speaking opportunity saved")},onError:u=>ae.error(u.message)}),i=yt({mutationFn:async({id:u,...h})=>{const{error:m}=await YM.from("attract_speaking_opportunities").update(h).eq("id",u);if(m)throw m},onSuccess:()=>{r(),ae.success("Updated")},onError:u=>ae.error(u.message)}),l=yt({mutationFn:async u=>{const{id:h,created_at:m,updated_at:p,user_id:x,...g}=u,{data:y,error:b}=await YM.from("attract_speaking_opportunities").insert({...g,title:`${u.title} (copy)`,status:"idea",user_id:s.id}).select("id").single();if(b)throw b;return y},onSuccess:()=>{r(),ae.success("Duplicated")},onError:u=>ae.error(u.message)}),o=yt({mutationFn:async u=>{const{error:h}=await YM.from("attract_speaking_opportunities").delete().eq("id",u);if(h)throw h},onSuccess:()=>{r(),ae.success("Deleted")},onError:u=>ae.error(u.message)}),c=yt({mutationFn:async({title:u,dueAt:h,notes:m,touchType:p="speaking"})=>{const{error:x}=await YM.from("attract_follow_ups").insert({user_id:s.id,title:u,due_at:h??null,notes:m??null,touch_type:p,priority:"medium"});if(x)throw x},onSuccess:()=>{r(),ae.success("Added to Follow-Up Center")},onError:u=>ae.error(u.message)}),d=yt({mutationFn:async({title:u,pillar:h="influence",activityType:m="speaking_outreach",agentId:p})=>{const{error:x}=await YM.from("attract_activities").insert({user_id:s.id,title:u,pillar:h,activity_type:m,agent_id:p??null});if(x)throw x},onSuccess:()=>{r(),ae.success("Outreach logged")},onError:u=>ae.error(u.message)});return{items:n.data??[],isLoading:n.isLoading,error:n.error,refetch:n.refetch,create:a,update:i,duplicate:l,remove:o,addTask:c,logActivity:d}}const YUe={idea:"bg-slate-100 text-slate-700 border-slate-200",researching:"bg-sky-50 text-sky-700 border-sky-200",pitching:"bg-amber-50 text-amber-700 border-amber-200",applied:"bg-orange-50 text-orange-700 border-orange-200",tentative:"bg-violet-50 text-violet-700 border-violet-200",confirmed:"bg-emerald-50 text-emerald-700 border-emerald-200",completed:"bg-teal-50 text-teal-700 border-teal-200",declined:"bg-rose-50 text-rose-700 border-rose-200",archived:"bg-slate-100 text-slate-500 border-slate-200"},wRe={title:"",organization:"",event_type:"panel",status:"idea",timezone:"America/New_York",pillar:"influence",linked_agent_ids:[]};function sWn(){const{items:s,isLoading:t,create:n,update:r,duplicate:a,remove:i,addTask:l,logActivity:o}=GWt(),{agents:c=[]}=M0(),{kits:d=[]}=LV(),u=FTe(),h=(u==null?void 0:u.events)??(u==null?void 0:u.data)??[],[m,p]=j.useState("month"),[x,g]=j.useState(new Date),[y,b]=j.useState("all"),[v,N]=j.useState("all"),[C,A]=j.useState("all"),[T,P]=j.useState(!1),[M,I]=j.useState(null),[D,B]=j.useState(null),q=j.useMemo(()=>s.filter(ee=>!(!T&&(ee.is_archived||ee.status==="archived")||y!=="all"&&ee.status!==y||v!=="all"&&ee.event_type!==v||C!=="all"&&!(ee.linked_agent_ids??[]).includes(C))),[s,y,v,C,T]),W=q.filter(ee=>ee.starts_at),V=q.filter(ee=>!ee.starts_at),K=new Date,Q=j.useMemo(()=>{const ee=W.filter(fe=>Pb(Lp(fe.starts_at),K)&&["confirmed","tentative"].includes(fe.status)),le=q.filter(fe=>fe.submission_deadline&&Pb(Lp(fe.submission_deadline),K)),he=q.filter(fe=>["pitching","applied","researching"].includes(fe.status)),ve=q.filter(fe=>fe.status==="confirmed"),ge=q.filter(fe=>fe.follow_up_date&&fe.status==="completed");return{upcoming:ee,deadlines:le,pitches:he,confirmed:ve,followUps:ge}},[q,W]),J=j.useMemo(()=>TFe(m==="week"?{start:Tg(x),end:eU(x)}:{start:Tg(Hu(x)),end:eU(e1(x))}),[x,m]),ce=ee=>W.filter(le=>hu(Lp(le.starts_at),ee)),ue=async()=>{var le;if(!((le=M==null?void 0:M.title)!=null&&le.trim())){ae.error("Give the talk a title");return}const ee={...M};delete ee.created_at,delete ee.updated_at,delete ee.user_id,(ee.fee===""||ee.fee==null)&&(ee.fee=null),["starts_at","ends_at","submission_deadline","follow_up_date","linked_event_id","linked_kit_id"].forEach(he=>{ee[he]===""&&(ee[he]=null)}),M.id?await r.mutateAsync(ee):await n.mutateAsync(ee),I(null)},ne=ee=>{if(!ee.starts_at){ae.error("Add a date first");return}const le=je=>new Date(je).toISOString().replace(/[-:]|\.\d{3}/g,""),he=ee.ends_at??new Date(new Date(ee.starts_at).getTime()+60*6e4).toISOString(),ve=["BEGIN:VCALENDAR","VERSION:2.0","PRODID:-//LevelUp Attract//Speaking//EN","BEGIN:VEVENT",`UID:${ee.id}@levelup-attract`,`DTSTAMP:${le(new Date().toISOString())}`,`DTSTART:${le(ee.starts_at)}`,`DTEND:${le(he)}`,`SUMMARY:${(ee.title||"").replace(/\n/g," ")}`,`LOCATION:${(ee.location||ee.virtual_link||"").replace(/\n/g," ")}`,`DESCRIPTION:${[ee.organization,ee.topic].filter(Boolean).join(" — ").replace(/\n/g," ")}`,"END:VEVENT","END:VCALENDAR"].join(`\r `),ge=URL.createObjectURL(new Blob([ve],{type:"text/calendar"})),fe=document.createElement("a");fe.href=ge,fe.download=`${ee.title.replace(/\W+/g,"-").toLowerCase()}.ics`,fe.click(),URL.revokeObjectURL(ge)};return t?e.jsxs("div",{className:"space-y-4",children:[e.jsx(on,{className:"h-32 rounded-2xl"}),e.jsx(on,{className:"h-96 rounded-2xl"})]}):e.jsxs("div",{className:"space-y-6",children:[e.jsx(nm,{eyebrow:"Pillar 02 · Influence",title:"Speaking Calendar",description:"Every stage, panel, podcast, and MLS talk — from first idea to post-event follow-up.",actions:e.jsxs($,{className:"rounded-full bg-gradient-to-r from-violet-600 to-indigo-600",onClick:()=>I({...wRe}),children:[e.jsx(sn,{className:"h-4 w-4 mr-2"}),"New opportunity"]})}),e.jsxs("div",{className:"grid grid-cols-2 lg:grid-cols-5 gap-3",children:[e.jsx(tW,{label:"Upcoming talks",value:Q.upcoming.length,icon:Vj}),e.jsx(tW,{label:"Deadlines ahead",value:Q.deadlines.length,icon:Hr}),e.jsx(tW,{label:"Pitches in flight",value:Q.pitches.length,icon:Br}),e.jsx(tW,{label:"Confirmed",value:Q.confirmed.length,icon:Fr}),e.jsx(tW,{label:"Post-event follow-ups",value:Q.followUps.length,icon:Jh})]}),e.jsxs(_e,{className:"p-3 rounded-2xl flex flex-wrap items-center gap-2",children:[e.jsx("div",{className:"flex rounded-full bg-slate-100 p-1",children:["month","week","agenda"].map(ee=>e.jsx("button",{onClick:()=>p(ee),className:`px-3 py-1.5 rounded-full text-[12.5px] font-medium capitalize ${m===ee?"bg-white shadow-sm text-slate-900":"text-slate-500"}`,children:ee},ee))}),m!=="agenda"&&e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx($,{variant:"ghost",size:"icon",className:"rounded-full",onClick:()=>g(m==="week"?P3(x,-1):zx(x,-1)),children:e.jsx(Ic,{className:"h-4 w-4"})}),e.jsx("div",{className:"text-[13.5px] font-semibold min-w-[130px] text-center",children:Hs(x,m==="week"?"'Week of' MMM d":"MMMM yyyy")}),e.jsx($,{variant:"ghost",size:"icon",className:"rounded-full",onClick:()=>g(m==="week"?P3(x,1):zx(x,1)),children:e.jsx(Ja,{className:"h-4 w-4"})}),e.jsx($,{variant:"ghost",size:"sm",className:"rounded-full",onClick:()=>g(new Date),children:"Today"})]}),e.jsx("div",{className:"flex-1"}),e.jsxs(vs,{value:y,onValueChange:b,children:[e.jsx(gs,{className:"w-[140px] rounded-full h-9",children:e.jsx(bs,{placeholder:"Status"})}),e.jsxs(ys,{children:[e.jsx(Ye,{value:"all",children:"All statuses"}),p_t.map(ee=>e.jsx(Ye,{value:ee,className:"capitalize",children:ee.replace(/_/g," ")},ee))]})]}),e.jsxs(vs,{value:v,onValueChange:N,children:[e.jsx(gs,{className:"w-[140px] rounded-full h-9",children:e.jsx(bs,{placeholder:"Type"})}),e.jsxs(ys,{children:[e.jsx(Ye,{value:"all",children:"All types"}),f_t.map(ee=>e.jsx(Ye,{value:ee,className:"capitalize",children:ee.replace(/_/g," ")},ee))]})]}),e.jsxs(vs,{value:C,onValueChange:A,children:[e.jsx(gs,{className:"w-[160px] rounded-full h-9",children:e.jsx(bs,{placeholder:"Relationship"})}),e.jsxs(ys,{children:[e.jsx(Ye,{value:"all",children:"All relationships"}),c.map(ee=>e.jsx(Ye,{value:ee.id,children:[ee.first_name,ee.last_name].filter(Boolean).join(" ")},ee.id))]})]}),e.jsxs($,{variant:T?"default":"outline",size:"sm",className:"rounded-full",onClick:()=>P(ee=>!ee),children:[e.jsx(Am,{className:"h-3.5 w-3.5 mr-1.5"}),"Archived"]})]}),s.length===0?e.jsxs(_e,{className:"p-10 rounded-2xl text-center",children:[e.jsx(Vj,{className:"h-8 w-8 mx-auto text-violet-500"}),e.jsx("div",{className:"text-[16px] font-semibold mt-3",children:"No speaking opportunities yet"}),e.jsx("p",{className:"text-[13.5px] text-slate-500 mt-1 max-w-md mx-auto",children:"Start with the rooms you already have access to — your office meeting, a local MLS class, a peer's podcast. Track the pitch, the deadline, and the follow-up in one place."}),e.jsxs($,{className:"mt-4 rounded-full bg-gradient-to-r from-violet-600 to-indigo-600",onClick:()=>I({...wRe}),children:[e.jsx(sn,{className:"h-4 w-4 mr-2"}),"Add your first opportunity"]})]}):m==="agenda"?e.jsxs("div",{className:"space-y-3",children:[[...W,...V].length===0&&e.jsx(_e,{className:"p-8 rounded-2xl text-center text-[13.5px] text-slate-500",children:"Nothing matches these filters."}),[...W,...V].map(ee=>e.jsx(nWn,{o:ee,onEdit:()=>I(ee),onComplete:()=>B(ee),onDuplicate:()=>a.mutate(ee),onDelete:()=>i.mutate(ee.id),onArchive:()=>r.mutate({id:ee.id,is_archived:!ee.is_archived,status:ee.is_archived?"idea":"archived"}),onIcs:()=>ne(ee),onPitchTask:()=>l.mutate({title:`Pitch: ${ee.title}${ee.organization?` (${ee.organization})`:""}`,dueAt:ee.submission_deadline?new Date(ee.submission_deadline).toISOString():null,notes:ee.notes??void 0}),onLogOutreach:()=>o.mutate({title:`Outreach for ${ee.title}`}),onConfirm:()=>r.mutate({id:ee.id,status:"confirmed"})},ee.id))]}):e.jsxs(_e,{className:"rounded-2xl overflow-hidden",children:[e.jsx("div",{className:"grid grid-cols-7 border-b bg-slate-50",children:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"].map(ee=>e.jsx("div",{className:"px-2 py-2 text-[11px] uppercase tracking-wider font-semibold text-slate-500 text-center",children:ee},ee))}),e.jsx("div",{className:"grid grid-cols-7",children:J.map(ee=>{const le=ce(ee);return e.jsxs("div",{className:`min-h-[92px] sm:min-h-[112px] border-b border-r p-1.5 ${Cq(ee,x)||m==="week"?"bg-white":"bg-slate-50/60"}`,children:[e.jsx("button",{onClick:()=>I({...wRe,starts_at:new Date(ee.setHours(10,0,0,0)).toISOString()}),className:`text-[11.5px] font-semibold h-6 w-6 rounded-full grid place-items-center ${hu(ee,K)?"bg-violet-600 text-white":"text-slate-500 hover:bg-slate-100"}`,children:Hs(ee,"d")}),e.jsxs("div",{className:"mt-1 space-y-1",children:[le.slice(0,3).map(he=>e.jsx("button",{onClick:()=>I(he),className:`w-full text-left text-[11px] px-1.5 py-1 rounded-md border truncate ${YUe[he.status]??""}`,children:he.title},he.id)),le.length>3&&e.jsxs("div",{className:"text-[10.5px] text-slate-400 pl-1",children:["+",le.length-3," more"]})]})]},ee.toISOString())})}),V.length>0&&e.jsxs("div",{className:"p-3 bg-slate-50 border-t",children:[e.jsxs("div",{className:"text-[11px] uppercase tracking-wider font-semibold text-slate-500 mb-2",children:["Undated (",V.length,")"]}),e.jsx("div",{className:"flex flex-wrap gap-2",children:V.map(ee=>e.jsx("button",{onClick:()=>I(ee),className:`text-[12px] px-2.5 py-1 rounded-full border ${YUe[ee.status]??""}`,children:ee.title},ee.id))})]})]}),e.jsx(kF,{}),e.jsx(Os,{open:!!M,onOpenChange:ee=>!ee&&I(null),children:e.jsxs(Rs,{className:"max-w-3xl max-h-[90vh] overflow-y-auto",children:[e.jsx(Us,{children:e.jsx(zs,{children:M!=null&&M.id?"Edit speaking opportunity":"New speaking opportunity"})}),M&&e.jsxs("div",{className:"grid sm:grid-cols-2 gap-3",children:[e.jsx(Vh,{label:"Title",className:"sm:col-span-2",children:e.jsx(be,{value:M.title??"",onChange:ee=>I({...M,title:ee.target.value}),placeholder:"Panel: Winning listings in a shifting market"})}),e.jsx(Vh,{label:"Event / organization",children:e.jsx(be,{value:M.organization??"",onChange:ee=>I({...M,organization:ee.target.value})})}),e.jsx(Vh,{label:"Event type",children:e.jsxs(vs,{value:M.event_type??"panel",onValueChange:ee=>I({...M,event_type:ee}),children:[e.jsx(gs,{children:e.jsx(bs,{})}),e.jsx(ys,{children:f_t.map(ee=>e.jsx(Ye,{value:ee,className:"capitalize",children:ee.replace(/_/g," ")},ee))})]})}),e.jsx(Vh,{label:"Contact name",children:e.jsx(be,{value:M.contact_name??"",onChange:ee=>I({...M,contact_name:ee.target.value})})}),e.jsx(Vh,{label:"Contact email",children:e.jsx(be,{type:"email",value:M.contact_email??"",onChange:ee=>I({...M,contact_email:ee.target.value})})}),e.jsx(Vh,{label:"Contact phone",children:e.jsx(be,{value:M.contact_phone??"",onChange:ee=>I({...M,contact_phone:ee.target.value})})}),e.jsx(Vh,{label:"Audience",children:e.jsx(be,{value:M.audience??"",onChange:ee=>I({...M,audience:ee.target.value}),placeholder:"120 local agents"})}),e.jsx(Vh,{label:"Location",children:e.jsx(be,{value:M.location??"",onChange:ee=>I({...M,location:ee.target.value})})}),e.jsx(Vh,{label:"Virtual link",children:e.jsx(be,{value:M.virtual_link??"",onChange:ee=>I({...M,virtual_link:ee.target.value})})}),e.jsx(Vh,{label:"Starts",children:e.jsx(be,{type:"datetime-local",value:g_t(M.starts_at),onChange:ee=>I({...M,starts_at:ee.target.value?new Date(ee.target.value).toISOString():null})})}),e.jsx(Vh,{label:"Ends",children:e.jsx(be,{type:"datetime-local",value:g_t(M.ends_at),onChange:ee=>I({...M,ends_at:ee.target.value?new Date(ee.target.value).toISOString():null})})}),e.jsx(Vh,{label:"Status",children:e.jsxs(vs,{value:M.status??"idea",onValueChange:ee=>I({...M,status:ee}),children:[e.jsx(gs,{children:e.jsx(bs,{})}),e.jsx(ys,{children:p_t.map(ee=>e.jsx(Ye,{value:ee,className:"capitalize",children:ee},ee))})]})}),e.jsx(Vh,{label:"Fee / honorarium",children:e.jsx(be,{type:"number",value:M.fee??"",onChange:ee=>I({...M,fee:ee.target.value===""?null:Number(ee.target.value)})})}),e.jsx(Vh,{label:"Submission deadline",children:e.jsx(be,{type:"date",value:M.submission_deadline??"",onChange:ee=>I({...M,submission_deadline:ee.target.value||null})})}),e.jsx(Vh,{label:"Follow-up date",children:e.jsx(be,{type:"date",value:M.follow_up_date??"",onChange:ee=>I({...M,follow_up_date:ee.target.value||null})})}),e.jsx(Vh,{label:"Application URL",className:"sm:col-span-2",children:e.jsx(be,{value:M.application_url??"",onChange:ee=>I({...M,application_url:ee.target.value})})}),e.jsx(Vh,{label:"Topic",className:"sm:col-span-2",children:e.jsx(be,{value:M.topic??"",onChange:ee=>I({...M,topic:ee.target.value})})}),e.jsx(Vh,{label:"Linked Connect event",children:e.jsxs(vs,{value:M.linked_event_id??"none",onValueChange:ee=>I({...M,linked_event_id:ee==="none"?null:ee}),children:[e.jsx(gs,{children:e.jsx(bs,{placeholder:"None"})}),e.jsxs(ys,{children:[e.jsx(Ye,{value:"none",children:"None"}),h.map(ee=>e.jsx(Ye,{value:ee.id,children:ee.title},ee.id))]})]})}),e.jsx(Vh,{label:"Linked Resource Kit",children:e.jsxs(vs,{value:M.linked_kit_id??"none",onValueChange:ee=>I({...M,linked_kit_id:ee==="none"?null:ee}),children:[e.jsx(gs,{children:e.jsx(bs,{placeholder:"None"})}),e.jsxs(ys,{children:[e.jsx(Ye,{value:"none",children:"None"}),d.map(ee=>e.jsx(Ye,{value:ee.id,children:ee.title},ee.id))]})]})}),e.jsx(Vh,{label:"Linked agent relationships",className:"sm:col-span-2",children:e.jsxs("div",{className:"flex flex-wrap gap-1.5 max-h-32 overflow-y-auto",children:[c.length===0&&e.jsx("div",{className:"text-[12.5px] text-slate-500",children:"No agents in your pipeline yet."}),c.map(ee=>{const le=(M.linked_agent_ids??[]).includes(ee.id);return e.jsx("button",{type:"button",onClick:()=>I({...M,linked_agent_ids:le?(M.linked_agent_ids??[]).filter(he=>he!==ee.id):[...M.linked_agent_ids??[],ee.id]}),className:`text-[12px] px-2.5 py-1 rounded-full border ${le?"bg-violet-600 text-white border-violet-600":"bg-white text-slate-600"}`,children:[ee.first_name,ee.last_name].filter(Boolean).join(" ")},ee.id)})]})}),e.jsx(Vh,{label:"Travel notes",className:"sm:col-span-2",children:e.jsx(Is,{rows:2,value:M.travel_notes??"",onChange:ee=>I({...M,travel_notes:ee.target.value})})}),e.jsx(Vh,{label:"Notes",className:"sm:col-span-2",children:e.jsx(Is,{rows:3,value:M.notes??"",onChange:ee=>I({...M,notes:ee.target.value})})})]}),e.jsxs(kr,{className:"gap-2",children:[e.jsx($,{variant:"ghost",onClick:()=>I(null),children:"Cancel"}),e.jsx($,{onClick:ue,disabled:n.isPending||r.isPending,className:"bg-gradient-to-r from-violet-600 to-indigo-600",children:"Save"})]})]})}),e.jsx(rWn,{item:D,onClose:()=>B(null),onSave:async(ee,le)=>{await r.mutateAsync({id:D.id,status:"completed",outcome:ee}),le&&await l.mutateAsync({title:`Post-event follow-up: ${D.title}`,dueAt:new Date(Date.now()+2*864e5).toISOString(),notes:ee.next_actions}),await o.mutateAsync({title:`Spoke at ${D.title}`,activityType:"speaking_completed"}),B(null)}})]})}function g_t(s){if(!s)return"";const t=new Date(s),n=t.getTimezoneOffset();return new Date(t.getTime()-n*6e4).toISOString().slice(0,16)}function Vh({label:s,children:t,className:n}){return e.jsxs("div",{className:n,children:[e.jsx(se,{className:"text-[12px] text-slate-600 mb-1 block",children:s}),t]})}function tW({label:s,value:t,icon:n}){return e.jsxs(_e,{className:"p-4 rounded-2xl",children:[e.jsx(n,{className:"h-4 w-4 text-violet-600"}),e.jsx("div",{className:"mt-1 text-[22px] font-semibold tabular-nums text-slate-900",children:t}),e.jsx("div",{className:"text-[11.5px] text-slate-500",children:s})]})}function nWn({o:s,onEdit:t,onComplete:n,onDuplicate:r,onDelete:a,onArchive:i,onIcs:l,onPitchTask:o,onLogOutreach:c,onConfirm:d}){var m;const u=s,h=u.submission_deadline?av(Lp(u.submission_deadline),new Date):null;return e.jsx(_e,{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.jsx("button",{onClick:t,className:"text-[15px] font-semibold text-slate-900 hover:text-violet-700 text-left",children:u.title}),e.jsx("div",{className:"text-[12.5px] text-slate-500 mt-0.5",children:[u.organization,(m=u.event_type)==null?void 0:m.replace(/_/g," "),u.audience].filter(Boolean).join(" · ")||"No details yet"}),e.jsxs("div",{className:"text-[12.5px] text-slate-600 mt-1 flex items-center gap-3 flex-wrap",children:[u.starts_at&&e.jsxs("span",{className:"inline-flex items-center gap-1",children:[e.jsx(Nl,{className:"h-3.5 w-3.5"}),Hs(Lp(u.starts_at),"EEE MMM d, h:mm a")]}),h!==null&&e.jsxs("span",{className:`inline-flex items-center gap-1 ${h<7?"text-orange-600":""}`,children:[e.jsx(Hr,{className:"h-3.5 w-3.5"}),"Deadline in ",h,"d"]}),(u.linked_agent_ids??[]).length>0&&e.jsxs("span",{className:"inline-flex items-center gap-1",children:[e.jsx(qn,{className:"h-3.5 w-3.5"}),u.linked_agent_ids.length," linked"]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx($e,{variant:"outline",className:`capitalize rounded-full ${YUe[u.status]??""}`,children:u.status}),e.jsxs(Hd,{children:[e.jsx(Gd,{asChild:!0,children:e.jsx($,{variant:"ghost",size:"icon",className:"rounded-full",children:e.jsx(p0,{className:"h-4 w-4"})})}),e.jsxs(Md,{align:"end",children:[e.jsx(Na,{onClick:t,children:"Edit"}),e.jsxs(Na,{onClick:o,children:[e.jsx(Jh,{className:"h-3.5 w-3.5 mr-2"}),"Add pitch task"]}),e.jsxs(Na,{onClick:c,children:[e.jsx(Br,{className:"h-3.5 w-3.5 mr-2"}),"Log outreach"]}),e.jsxs(Na,{onClick:d,children:[e.jsx(Fr,{className:"h-3.5 w-3.5 mr-2"}),"Mark confirmed"]}),e.jsxs(Na,{onClick:n,children:[e.jsx(Fr,{className:"h-3.5 w-3.5 mr-2"}),"Mark completed"]}),e.jsxs(Na,{onClick:l,children:[e.jsx(di,{className:"h-3.5 w-3.5 mr-2"}),"Download .ics"]}),e.jsxs(Na,{onClick:r,children:[e.jsx(Ca,{className:"h-3.5 w-3.5 mr-2"}),"Duplicate"]}),e.jsxs(Na,{onClick:i,children:[e.jsx(Am,{className:"h-3.5 w-3.5 mr-2"}),u.is_archived?"Unarchive":"Archive"]}),e.jsxs(Na,{className:"text-destructive",onClick:a,children:[e.jsx(Pn,{className:"h-3.5 w-3.5 mr-2"}),"Delete"]})]})]})]})]})})}function rWn({item:s,onClose:t,onSave:n}){const[r,a]=j.useState(""),[i,l]=j.useState(""),[o,c]=j.useState(""),[d,u]=j.useState("");return e.jsx(Os,{open:!!s,onOpenChange:h=>!h&&t(),children:e.jsxs(Rs,{className:"max-w-lg",children:[e.jsx(Us,{children:e.jsx(zs,{children:"Capture the outcome"})}),e.jsxs("div",{className:"space-y-3",children:[e.jsx(Vh,{label:"Attendance",children:e.jsx(be,{value:r,onChange:h=>a(h.target.value),placeholder:"How many were in the room?"})}),e.jsx(Vh,{label:"Leads / relationships created",children:e.jsx(Is,{rows:2,value:i,onChange:h=>l(h.target.value)})}),e.jsx(Vh,{label:"Content captured",children:e.jsx(Is,{rows:2,value:o,onChange:h=>c(h.target.value),placeholder:"Photos, clips, quotes"})}),e.jsx(Vh,{label:"Next actions",children:e.jsx(Is,{rows:2,value:d,onChange:h=>u(h.target.value)})})]}),e.jsxs(kr,{className:"gap-2",children:[e.jsx($,{variant:"ghost",onClick:t,children:"Cancel"}),e.jsx($,{variant:"outline",onClick:()=>n({attendance:r,leads:i,content:o,next_actions:d},!1),children:"Save only"}),e.jsx($,{className:"bg-gradient-to-r from-violet-600 to-indigo-600",onClick:()=>n({attendance:r,leads:i,content:o,next_actions:d},!0),children:"Save + create follow-up"})]})]})})}const oz=U,ZUe=["attract-masterclasses"];function aWn(){const{user:s}=_s(),t=ts(),n=ht({queryKey:[...ZUe,s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:o,error:c}=await oz.from("attract_masterclasses").select("*").order("updated_at",{ascending:!1});if(c)throw c;return o??[]}}),r=()=>t.invalidateQueries({queryKey:ZUe}),a=yt({mutationFn:async o=>{const{data:c,error:d}=await oz.from("attract_masterclasses").insert({title:"Untitled masterclass",...o,user_id:s.id}).select("*").single();if(d)throw d;return c},onSuccess:()=>r(),onError:o=>ae.error(o.message)}),i=yt({mutationFn:async o=>{const{id:c,created_at:d,updated_at:u,user_id:h,...m}=o,{data:p,error:x}=await oz.from("attract_masterclasses").insert({...m,title:`${o.title} (copy)`,status:"draft",user_id:s.id}).select("id").single();if(x)throw x;return p},onSuccess:()=>{r(),ae.success("Duplicated")},onError:o=>ae.error(o.message)}),l=yt({mutationFn:async o=>{const{error:c}=await oz.from("attract_masterclasses").delete().eq("id",o);if(c)throw c},onSuccess:()=>{r(),ae.success("Deleted")},onError:o=>ae.error(o.message)});return{items:n.data??[],isLoading:n.isLoading,refetch:n.refetch,create:a,duplicate:i,remove:l}}function iWn(s){const t=ts(),n=ht({queryKey:["attract-masterclass",s],enabled:!!s,queryFn:async()=>{const{data:a,error:i}=await oz.from("attract_masterclasses").select("*").eq("id",s).maybeSingle();if(i)throw i;return a}}),r=yt({mutationFn:async a=>{const{error:i}=await oz.from("attract_masterclasses").update(a).eq("id",s);if(i)throw i},onSuccess:()=>{t.invalidateQueries({queryKey:["attract-masterclass",s]}),t.invalidateQueries({queryKey:ZUe})},onError:a=>ae.error(a.message)});return{masterclass:n.data??null,isLoading:n.isLoading,save:r}}const Gm=(s,t)=>({id:crypto.randomUUID(),title:s,lessons:t.map(([n,r,a])=>({id:crypto.randomUUID(),title:n,minutes:r,talking_points:a}))}),y_t=[{key:"listing_presentation",title:"Listing Presentation Masterclass",promise:"Walk out with a listing presentation that wins the room in the first five minutes.",target_audience:"Agents who get appointments but lose listings to bigger names.",problem_solved:"Presentations that talk about the agent instead of the seller outcome.",desired_outcome:"A rebuilt opening, pricing story, and close they can use this week.",pillar:"provide",duration_minutes:60,curriculum:[Gm("Open strong",[["Why sellers decide in 5 minutes",8,"Trust signals, pacing, the first question you ask"],["The pre-listing package",7,"What to send ahead and why it changes the room"]]),Gm("The pricing conversation",[["Framing price without arguing",12,"Data as a story, not a spreadsheet"],["Handling the overpriced seller",10,"Language patterns and walking-away criteria"]]),Gm("Close and next steps",[["Asking for the signature",8,"Assumptive close variations"],[`Follow-up if they say "we'll think about it"`,8,"48-hour sequence"]])]},{key:"database_revival",title:"Database Revival Workshop",promise:"Reactivate a cold database into real conversations in 30 days.",target_audience:"Agents with 200+ contacts and no consistent outreach.",problem_solved:"A database that exists but produces nothing.",desired_outcome:"A cleaned list, a cadence, and 10 conversations started live in class.",pillar:"provide",duration_minutes:60,curriculum:[Gm("Audit",[["Sorting your list into A/B/C",10,"Criteria that actually predict referrals"],["Fixing missing data",8,"Birthdays, anniversaries, spouse names"]]),Gm("The reach-out",[["The no-ask message",12,"Scripts that do not feel like prospecting"],["Voice notes and video",10,"Why they convert 3x text"]]),Gm("The cadence",[["Building a 12-touch year",12,"Pop-bys, events, market notes"],["Tracking without a CRM headache",8,"Simple weekly rhythm"]])]},{key:"open_house_conversion",title:"Open House Lead Conversion",promise:"Turn a normal open house into 3-5 real buyer conversations.",target_audience:"Newer agents relying on open houses for pipeline.",problem_solved:"Sign-in sheets full of names that never convert.",desired_outcome:"A pre-, during-, and post-open-house system.",pillar:"produce",duration_minutes:45,curriculum:[Gm("Before",[["Neighborhood invites",8,"Door knocking and digital invites"],["Setting the stage",7,"Materials that create conversations"]]),Gm("During",[["The three questions",10,"How to qualify without interrogating"],["Capturing real contact info",8,"Sign-in that people actually complete"]]),Gm("After",[["The 10-minute follow-up",7,"Speed to lead"],["Week-one nurture",5,"What to send day 1, 3, 7"]])]},{key:"social_authority",title:"Social Media Authority",promise:"Build a local social presence that makes agents and clients come to you.",target_audience:"Agents posting inconsistently with little engagement.",problem_solved:"Random posting with no positioning.",desired_outcome:"A content pillar map and 30 days of planned posts.",pillar:"influence",duration_minutes:60,curriculum:[Gm("Positioning",[["Pick your lane",10,"Neighborhood, niche, or narrative"],["What to never post",6,"The credibility killers"]]),Gm("Content system",[["The four content types",14,"Teach, prove, connect, invite"],["Batch filming",10,"One hour, ten pieces"]]),Gm("Distribution",[["Captions and hooks",10,"First-line formulas"],["Turning comments into DMs",10,"Relationship-first outreach"]])]},{key:"ai_for_agents",title:"AI for Agents",promise:"Use AI to save 5 hours a week without sounding like a robot.",target_audience:"Agents curious about AI but unsure where to start.",problem_solved:"Tool overwhelm and generic AI output.",desired_outcome:"Three working workflows they set up live.",pillar:"influence",duration_minutes:60,curriculum:[Gm("Foundations",[["What AI is good and bad at",10,"Drafting vs deciding"],["Prompting basics",10,"Context, role, constraints"]]),Gm("Workflows",[["Listing descriptions and marketing",12,"Brand voice inputs"],["Follow-up and email drafts",12,"Never auto-send"]]),Gm("Guardrails",[["Compliance and fair housing",10,"What to always review"],["Keeping your voice",6,"Editing pass checklist"]])]},{key:"new_construction",title:"New Construction Buyer Workshop",promise:"Represent new construction buyers with confidence and get paid.",target_audience:"Agents losing buyers to builder sales offices.",problem_solved:"Not knowing builder contracts or registration rules.",desired_outcome:"A registration process and builder relationship plan.",pillar:"produce",duration_minutes:60,curriculum:[Gm("The builder landscape",[["How builder comp works",12,"Registration rules that protect you"],["Local builders worth knowing",8,"Relationship map"]]),Gm("Representing the buyer",[["Contract differences",14,"What is negotiable"],["Inspections and walkthroughs",10,"Timeline checkpoints"]]),Gm("Winning the relationship",[["First-visit protocol",8,"Always accompany"],["Post-close referrals",8,"The neighborhood effect"]])]},{key:"luxury_experience",title:"Luxury Client Experience",promise:"Deliver an experience that earns luxury referrals.",target_audience:"Agents moving into a higher price band.",problem_solved:"Marketing and service that feels mid-market.",desired_outcome:"An upgraded listing experience and presentation standard.",pillar:"provide",duration_minutes:60,curriculum:[Gm("Standards",[["What luxury clients notice",12,"Response time, discretion, detail"],["Your materials",10,"Photography, print, web"]]),Gm("The listing experience",[["Pre-market strategy",12,"Whisper listings and staging"],["Private showings",8,"Choreography"]]),Gm("Referral engine",[["Post-close cadence",10,"Gifting and anniversaries"],["Building the circle",8,"Vendors and advisors"]])]},{key:"recruiting_value",title:"Recruiting Through Value",promise:"Attract agents by helping them, not pitching them.",target_audience:"Team leaders and agents building revenue share.",problem_solved:"Recruiting that feels salesy and gets ignored.",desired_outcome:"A value-first attraction plan for 20 named agents.",pillar:"connect",duration_minutes:60,curriculum:[Gm("Mindset",[["Why value beats pitching",10,"Relationship-first framing"],["Choosing your 20",8,"Fit criteria"]]),Gm("The value plan",[["Resource kits that help",14,"What agents actually want"],["Events and masterminds",10,"Small rooms win"]]),Gm("The conversation",[["When to talk business",10,"Earned invitation"],['Handling "I am happy where I am"',8,"Stay in relationship"]])]}];function oWn(s){return{title:s.title,promise:s.promise,target_audience:s.target_audience,problem_solved:s.problem_solved,desired_outcome:s.desired_outcome,pillar:s.pillar,duration_minutes:s.duration_minutes,curriculum:s.curriculum,source_template_key:s.key,status:"draft"}}function lWn(s){const t=s.title||"Untitled masterclass",n=s.delivery_date?new Date(s.delivery_date).toLocaleString("en-US",{timeZone:"America/New_York",dateStyle:"full",timeStyle:"short"}):"Date to be announced",r=(s.curriculum??[]).flatMap(i=>i.lessons.map(l=>`• ${l.title}`)).slice(0,6).join(` `),a=s.promise||"A practical, no-pitch training session.";return{registration_copy:`${t} ${n} · ${s.duration_minutes??45} minutes · ${s.format??"virtual"} ${a} Who it's for: ${s.target_audience||"Agents who want a practical system."} What we'll cover: ${r||"• Curriculum coming soon"} What you'll leave with: ${s.desired_outcome||"A plan you can use immediately."}`,email_invite:`Subject: ${t} Hi {{first_name}}, I'm hosting ${t} on ${n}. ${a} It's built for ${s.target_audience||"agents like you"} — no pitch, just the system. We'll cover: ${r||"• Curriculum coming soon"} Want me to save you a seat? {{my_name}}`,social_post:`${a} I'm teaching ${t} on ${n}. ${r||""} Free. Comment "SEAT" and I'll send the link.`,dm_invite:`Hey {{first_name}} — I'm running a short session called "${t}" on ${n}. Thought of you because of ${s.problem_solved||"what we talked about"}. Want the link?`,reminder:`Hi {{first_name}} — quick reminder that ${t} starts ${n}. Here's the link: {{join_link}}. Bring one question.`,follow_up:`Hi {{first_name}} — thanks for joining ${t}. Here's the recording and the workbook: {{resource_link}}. One thing to try this week: ${s.desired_outcome||"pick a single takeaway and run it."} Happy to walk through it one-on-one if useful.`}}function cWn(s){const t=[`RUN OF SHOW — ${s.title||"Masterclass"}`,""];let n=0;return t.push("0:00 Welcome, why we're here, one-line promise"),n+=3,(s.curriculum??[]).forEach(r=>{t.push("",`${Wae(n)} SECTION: ${r.title}`),r.lessons.forEach(a=>{t.push(`${Wae(n)} ${a.title}${a.minutes?` (${a.minutes}m)`:""}${a.talking_points?` — ${a.talking_points}`:""}`),n+=a.minutes??5})}),t.push("",`${Wae(n)} Q&A`,`${Wae(n+7)} Close: next step + resource kit`),t.join(` `)}function Wae(s){const t=Math.floor(s/60),n=s%60;return`${t}:${String(n).padStart(2,"0")}`}function dWn(){const{items:s,isLoading:t,create:n,duplicate:r,remove:a}=aWn(),i=Vn(),[l,o]=j.useState(!1),c=s.filter(m=>!m.is_archived),d=s.filter(m=>m.is_archived),u=async()=>{const m=await n.mutateAsync({title:"Untitled masterclass"});i(`/attract/provide/masterclasses/${m.id}`)},h=async m=>{const p=y_t.find(g=>g.key===m),x=await n.mutateAsync(oWn(p));i(`/attract/provide/masterclasses/${x.id}`)};return t?e.jsxs("div",{className:"space-y-4",children:[e.jsx(on,{className:"h-28 rounded-2xl"}),e.jsx(on,{className:"h-64 rounded-2xl"})]}):e.jsxs("div",{className:"space-y-6",children:[e.jsx(nm,{eyebrow:"Pillar 03 · Provide",title:"Masterclass Builder",description:"Turn what you already know into a 45-minute teaching moment agents actually attend — curriculum, assets, promotion, run-of-show, and follow-up.",actions:e.jsxs("div",{className:"flex gap-2",children:[e.jsxs($,{variant:"outline",className:"rounded-full",onClick:()=>o(m=>!m),children:[e.jsx(dn,{className:"h-4 w-4 mr-2"}),"Starter templates"]}),e.jsxs($,{className:"rounded-full bg-gradient-to-r from-violet-600 to-indigo-600",onClick:u,disabled:n.isPending,children:[e.jsx(sn,{className:"h-4 w-4 mr-2"}),"New masterclass"]})]})}),(l||s.length===0)&&e.jsxs(_e,{className:"p-5 rounded-2xl",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-widest text-violet-700 font-semibold mb-3",children:"Starter templates"}),e.jsx("div",{className:"grid sm:grid-cols-2 xl:grid-cols-4 gap-3",children:y_t.map(m=>e.jsxs("button",{onClick:()=>h(m.key),className:"text-left p-4 rounded-xl border hover:border-violet-300 hover:shadow-sm transition",children:[e.jsx($e,{variant:"secondary",className:"capitalize mb-2",children:m.pillar}),e.jsx("div",{className:"font-semibold text-[14px] text-slate-900",children:m.title}),e.jsx("div",{className:"text-[12.5px] text-slate-500 mt-1 line-clamp-3",children:m.promise}),e.jsxs("div",{className:"text-[11.5px] text-slate-400 mt-2",children:[m.duration_minutes," min · ",m.curriculum.length," sections"]})]},m.key))})]}),c.length===0?e.jsxs(_e,{className:"p-10 rounded-2xl text-center",children:[e.jsx(Ph,{className:"h-8 w-8 mx-auto text-violet-500"}),e.jsx("div",{className:"text-[16px] font-semibold mt-3",children:"No masterclasses yet"}),e.jsx("p",{className:"text-[13.5px] text-slate-500 mt-1 max-w-md mx-auto",children:"Pick a starter template above or build one from scratch. Nothing sends automatically — every piece of copy stays an editable draft."})]}):e.jsx("div",{className:"grid sm:grid-cols-2 xl:grid-cols-3 gap-3",children:c.map(m=>e.jsxs(_e,{className:"p-4 rounded-2xl",children:[e.jsxs("div",{className:"flex items-start justify-between gap-2",children:[e.jsx($e,{variant:"outline",className:"capitalize rounded-full",children:m.status}),e.jsxs(Hd,{children:[e.jsx(Gd,{asChild:!0,children:e.jsx($,{variant:"ghost",size:"icon",className:"rounded-full h-7 w-7",children:e.jsx(p0,{className:"h-4 w-4"})})}),e.jsxs(Md,{align:"end",children:[e.jsx(Na,{onClick:()=>i(`/attract/provide/masterclasses/${m.id}`),children:"Open builder"}),e.jsxs(Na,{onClick:()=>r.mutate(m),children:[e.jsx(Ca,{className:"h-3.5 w-3.5 mr-2"}),"Duplicate"]}),e.jsxs(Na,{className:"text-destructive",onClick:()=>a.mutate(m.id),children:[e.jsx(Pn,{className:"h-3.5 w-3.5 mr-2"}),"Delete"]})]})]})]}),e.jsxs(Wn,{to:`/attract/provide/masterclasses/${m.id}`,className:"block mt-2",children:[e.jsx("div",{className:"font-semibold text-slate-900 line-clamp-2",children:m.title}),m.promise&&e.jsx("div",{className:"text-[12.5px] text-slate-500 line-clamp-2 mt-1",children:m.promise})]}),e.jsxs("div",{className:"text-[11.5px] text-slate-400 mt-3",children:[(m.curriculum??[]).length," sections · ",m.duration_minutes??45," min",m.delivery_date&&` · ${Hs(new Date(m.delivery_date),"MMM d")}`]})]},m.id))}),d.length>0&&e.jsxs(_e,{className:"p-4 rounded-2xl",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(Am,{className:"h-3.5 w-3.5"}),"Archived"]}),e.jsx("div",{className:"flex flex-wrap gap-2",children:d.map(m=>e.jsx(Wn,{to:`/attract/provide/masterclasses/${m.id}`,className:"text-[12.5px] px-2.5 py-1 rounded-full border text-slate-600",children:m.title},m.id))})]}),e.jsx(kF,{})]})}const v_t=U,uWn=["Strategy","Curriculum","Assets","Promotion","Delivery","Follow-up"];function hWn(){var W,V,K,Q,J,ce,ue,ne,ee,le,he,ve,ge;const{masterclassId:s}=Vi(),t=Vn(),{user:n}=_s(),{masterclass:r,isLoading:a,save:i}=iWn(s),l=dWt(),{create:o}=LV(),[c,d]=j.useState(null),[u,h]=j.useState(0),[m,p]=j.useState(!1),[x,g]=j.useState("idle"),y=j.useRef(null),b=j.useRef(!1);j.useEffect(()=>{r&&!c&&d(r)},[r,c]);const v=fe=>{d(je=>je&&{...je,...fe}),b.current=!0,g("saving"),clearTimeout(y.current),y.current=setTimeout(()=>N({...c??{},...fe}),900)},N=async fe=>{const{id:je,user_id:Ee,created_at:Me,updated_at:De,...ze}=fe;await i.mutateAsync(ze),b.current=!1,g("saved"),setTimeout(()=>g(ke=>ke==="saved"?"idle":ke),1800)},C=(c==null?void 0:c.curriculum)??[],A=fe=>v({curriculum:fe}),T=j.useMemo(()=>C.reduce((fe,je)=>fe+je.lessons.reduce((Ee,Me)=>Ee+(Me.minutes??0),0),0),[C]);if(a||!c)return e.jsxs("div",{className:"space-y-4",children:[e.jsx(on,{className:"h-24 rounded-2xl"}),e.jsx(on,{className:"h-96 rounded-2xl"})]});const P=()=>{v({promotion:{...c.promotion,...lWn(c)}}),ae.success("Draft copy generated — edit before you send anything")},M=()=>{v({delivery:{...c.delivery,run_of_show:cWn(c)}}),ae.success("Run of show generated")},I=async()=>{const fe=await l.mutateAsync({title:c.title,description:c.promise??void 0,event_type:"masterclass",intended_audience:c.target_audience??void 0,related_pillar:c.pillar??"provide",starts_at:c.delivery_date??new Date(Date.now()+12096e5).toISOString(),format:c.format==="in_person"?"in_person":"virtual",agenda:C.flatMap(je=>je.lessons.map(Ee=>({item:`${je.title}: ${Ee.title}`}))),learning_outcomes:c.desired_outcome?[c.desired_outcome]:[]});await i.mutateAsync({linked_event_id:fe.id,status:"scheduled"}),d(je=>je&&{...je,linked_event_id:fe.id,status:"scheduled"}),ae.success("Connect event created as a draft"),t(`/attract/events/${fe.id}/edit`)},D=async()=>{var Ee,Me,De,ze,ke;const fe=await o.mutateAsync({title:`${c.title} — Resource Kit`,description:c.promise??void 0,audience:c.target_audience??void 0,pillar:c.pillar??"provide",intro_text:((Ee=c.assets)==null?void 0:Ee.workbook)??void 0,cta_label:((Me=c.assets)==null?void 0:Me.cta_label)??void 0,cta_url:((De=c.assets)==null?void 0:De.cta_url)??void 0}),je=[...(((ze=c.assets)==null?void 0:ze.downloads)??[]).map((Xe,Se)=>({type:"link",title:Xe.title,url:Xe.url,sort_order:Se})),...(((ke=c.assets)==null?void 0:ke.videos)??[]).map((Xe,Se)=>({type:"video",title:Xe.title,url:Xe.url,sort_order:100+Se}))];je.length&&await v_t.from("attract_resource_kit_items").insert(je.map(Xe=>({...Xe,kit_id:fe.id,user_id:n.id}))),await i.mutateAsync({linked_kit_id:fe.id}),d(Xe=>Xe&&{...Xe,linked_kit_id:fe.id}),ae.success("Resource Kit created from your assets"),t(`/attract/provide/kits/${fe.id}/edit`)},B=async()=>{const fe=Date.now(),je=[{title:`Send recap + resources: ${c.title}`,due_at:new Date(fe+1*864e5).toISOString()},{title:`Personal check-in with attendees: ${c.title}`,due_at:new Date(fe+3*864e5).toISOString()},{title:`Invite engaged attendees to a 1:1: ${c.title}`,due_at:new Date(fe+7*864e5).toISOString()}],{error:Ee}=await v_t.from("attract_follow_ups").insert(je.map(Me=>({...Me,user_id:n.id,touch_type:"masterclass",priority:"medium"})));if(Ee){ae.error(Ee.message);return}ae.success("3 follow-ups added to your Follow-Up Center")};return e.jsxs("div",{className:"space-y-5",children:[e.jsx($,{variant:"ghost",size:"sm",className:"rounded-full -ml-2",asChild:!0,children:e.jsxs(Wn,{to:"/attract/provide/masterclasses",children:[e.jsx(ka,{className:"h-3.5 w-3.5 mr-1.5"}),"All masterclasses"]})}),e.jsx(nm,{eyebrow:"Pillar 03 · Provide",title:c.title||"Untitled masterclass",description:c.promise??"Build the promise, curriculum, assets, promotion, delivery and follow-up.",actions:e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx("span",{className:"text-[12px] text-slate-500 inline-flex items-center gap-1.5",children:x==="saving"?e.jsxs(e.Fragment,{children:[e.jsx(Ht,{className:"h-3.5 w-3.5 animate-spin"}),"Saving…"]}):x==="saved"?e.jsxs(e.Fragment,{children:[e.jsx(oa,{className:"h-3.5 w-3.5 text-emerald-600"}),"Saved"]}):"All changes saved"}),e.jsxs($,{variant:"outline",className:"rounded-full",onClick:()=>p(fe=>!fe),children:[e.jsx(ga,{className:"h-4 w-4 mr-2"}),m?"Edit":"Preview"]})]})}),e.jsx(_e,{className:"p-2 rounded-2xl flex gap-1 overflow-x-auto",children:uWn.map((fe,je)=>e.jsxs("button",{onClick:()=>{p(!1),h(je)},className:`px-3.5 py-2 rounded-xl text-[13px] font-medium whitespace-nowrap ${u===je&&!m?"bg-violet-600 text-white":"text-slate-600 hover:bg-slate-100"}`,children:[je+1,". ",fe]},fe))}),m?e.jsx(pWn,{m:c}):e.jsxs(_e,{className:"p-5 rounded-2xl space-y-4",children:[u===0&&e.jsxs("div",{className:"grid sm:grid-cols-2 gap-3",children:[e.jsx(lf,{label:"Title",className:"sm:col-span-2",children:e.jsx(be,{value:c.title,onChange:fe=>v({title:fe.target.value})})}),e.jsx(lf,{label:"The promise",className:"sm:col-span-2",children:e.jsx(Is,{rows:2,value:c.promise??"",onChange:fe=>v({promise:fe.target.value}),placeholder:"Walk out with…"})}),e.jsx(lf,{label:"Target audience",children:e.jsx(be,{value:c.target_audience??"",onChange:fe=>v({target_audience:fe.target.value})})}),e.jsx(lf,{label:"Problem solved",children:e.jsx(be,{value:c.problem_solved??"",onChange:fe=>v({problem_solved:fe.target.value})})}),e.jsx(lf,{label:"Desired outcome",className:"sm:col-span-2",children:e.jsx(be,{value:c.desired_outcome??"",onChange:fe=>v({desired_outcome:fe.target.value})})}),e.jsx(lf,{label:"Pillar",children:e.jsxs(vs,{value:c.pillar??"provide",onValueChange:fe=>v({pillar:fe}),children:[e.jsx(gs,{children:e.jsx(bs,{})}),e.jsx(ys,{children:["produce","influence","provide","connect"].map(fe=>e.jsx(Ye,{value:fe,className:"capitalize",children:fe},fe))})]})}),e.jsx(lf,{label:"Format",children:e.jsxs(vs,{value:c.format??"virtual",onValueChange:fe=>v({format:fe}),children:[e.jsx(gs,{children:e.jsx(bs,{})}),e.jsx(ys,{children:["virtual","in_person","hybrid"].map(fe=>e.jsx(Ye,{value:fe,className:"capitalize",children:fe.replace("_"," ")},fe))})]})}),e.jsx(lf,{label:"Duration (minutes)",children:e.jsx(be,{type:"number",value:c.duration_minutes??45,onChange:fe=>v({duration_minutes:Number(fe.target.value)})})}),e.jsx(lf,{label:"Delivery date",children:e.jsx(be,{type:"datetime-local",value:mWn(c.delivery_date),onChange:fe=>v({delivery_date:fe.target.value?new Date(fe.target.value).toISOString():null})})}),e.jsx(lf,{label:"Status",children:e.jsxs(vs,{value:c.status,onValueChange:fe=>v({status:fe}),children:[e.jsx(gs,{children:e.jsx(bs,{})}),e.jsx(ys,{children:["draft","ready","scheduled","delivered","archived"].map(fe=>e.jsx(Ye,{value:fe,className:"capitalize",children:fe},fe))})]})})]}),u===1&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"text-[12.5px] text-slate-500",children:[C.length," sections · ",T," minutes planned"]}),e.jsxs($,{size:"sm",variant:"outline",className:"rounded-full",onClick:()=>A([...C,{id:crypto.randomUUID(),title:"New section",lessons:[]}]),children:[e.jsx(sn,{className:"h-3.5 w-3.5 mr-1.5"}),"Add section"]})]}),C.length===0&&e.jsx("div",{className:"text-[13.5px] text-slate-500 border border-dashed rounded-xl p-8 text-center",children:"No sections yet. Add your first one."}),C.map((fe,je)=>e.jsxs(_e,{className:"p-4 rounded-xl bg-slate-50/60",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(be,{value:fe.title,onChange:Ee=>A(C.map(Me=>Me.id===fe.id?{...Me,title:Ee.target.value}:Me)),className:"font-semibold"}),e.jsx($,{variant:"ghost",size:"icon",disabled:je===0,onClick:()=>A(Kae(C,je,je-1)),children:e.jsx(jg,{className:"h-4 w-4"})}),e.jsx($,{variant:"ghost",size:"icon",disabled:je===C.length-1,onClick:()=>A(Kae(C,je,je+1)),children:e.jsx(_o,{className:"h-4 w-4"})}),e.jsx($,{variant:"ghost",size:"icon",className:"text-destructive",onClick:()=>A(C.filter(Ee=>Ee.id!==fe.id)),children:e.jsx(Pn,{className:"h-4 w-4"})})]}),e.jsxs("div",{className:"mt-3 space-y-3",children:[fe.lessons.map((Ee,Me)=>e.jsxs("div",{className:"rounded-lg border bg-white p-3 space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(be,{value:Ee.title,placeholder:"Lesson title",onChange:De=>q(fe.id,Ee.id,{title:De.target.value})}),e.jsx(be,{type:"number",className:"w-20",value:Ee.minutes??"",placeholder:"min",onChange:De=>q(fe.id,Ee.id,{minutes:Number(De.target.value)})}),e.jsx($,{variant:"ghost",size:"icon",disabled:Me===0,onClick:()=>A(C.map(De=>De.id===fe.id?{...De,lessons:Kae(De.lessons,Me,Me-1)}:De)),children:e.jsx(jg,{className:"h-4 w-4"})}),e.jsx($,{variant:"ghost",size:"icon",disabled:Me===fe.lessons.length-1,onClick:()=>A(C.map(De=>De.id===fe.id?{...De,lessons:Kae(De.lessons,Me,Me+1)}:De)),children:e.jsx(_o,{className:"h-4 w-4"})}),e.jsx($,{variant:"ghost",size:"icon",className:"text-destructive",onClick:()=>A(C.map(De=>De.id===fe.id?{...De,lessons:De.lessons.filter(ze=>ze.id!==Ee.id)}:De)),children:e.jsx(Pn,{className:"h-4 w-4"})})]}),e.jsxs("div",{className:"grid sm:grid-cols-2 gap-2",children:[e.jsx(Is,{rows:2,placeholder:"Talking points",value:Ee.talking_points??"",onChange:De=>q(fe.id,Ee.id,{talking_points:De.target.value})}),e.jsx(Is,{rows:2,placeholder:"Exercise",value:Ee.exercise??"",onChange:De=>q(fe.id,Ee.id,{exercise:De.target.value})}),e.jsx(Is,{rows:2,placeholder:"Example / story",value:Ee.example??"",onChange:De=>q(fe.id,Ee.id,{example:De.target.value})}),e.jsx(Is,{rows:2,placeholder:"Speaker notes",value:Ee.speaker_notes??"",onChange:De=>q(fe.id,Ee.id,{speaker_notes:De.target.value})})]})]},Ee.id)),e.jsxs($,{size:"sm",variant:"ghost",onClick:()=>A(C.map(Ee=>Ee.id===fe.id?{...Ee,lessons:[...Ee.lessons,{id:crypto.randomUUID(),title:""}]}:Ee)),children:[e.jsx(sn,{className:"h-3.5 w-3.5 mr-1.5"}),"Add lesson"]})]})]},fe.id))]}),u===2&&e.jsxs("div",{className:"space-y-3",children:[e.jsx(lf,{label:"Slide outline",children:e.jsx(Is,{rows:5,value:((W=c.assets)==null?void 0:W.slide_outline)??"",onChange:fe=>v({assets:{...c.assets,slide_outline:fe.target.value}})})}),e.jsx(lf,{label:"Workbook / checklist outline",children:e.jsx(Is,{rows:5,value:((V=c.assets)==null?void 0:V.workbook)??"",onChange:fe=>v({assets:{...c.assets,workbook:fe.target.value}})})}),e.jsx(b_t,{label:"Downloads",items:((K=c.assets)==null?void 0:K.downloads)??[],onChange:fe=>v({assets:{...c.assets,downloads:fe}})}),e.jsx(b_t,{label:"Videos",items:((Q=c.assets)==null?void 0:Q.videos)??[],onChange:fe=>v({assets:{...c.assets,videos:fe}})}),e.jsxs("div",{className:"grid sm:grid-cols-2 gap-3",children:[e.jsx(lf,{label:"CTA label",children:e.jsx(be,{value:((J=c.assets)==null?void 0:J.cta_label)??"",onChange:fe=>v({assets:{...c.assets,cta_label:fe.target.value}})})}),e.jsx(lf,{label:"CTA URL",children:e.jsx(be,{value:((ce=c.assets)==null?void 0:ce.cta_url)??"",onChange:fe=>v({assets:{...c.assets,cta_url:fe.target.value}})})})]}),e.jsxs($,{variant:"outline",className:"rounded-full",onClick:D,disabled:o.isPending,children:[e.jsx(OK,{className:"h-4 w-4 mr-2"}),"Create Resource Kit from these assets"]}),c.linked_kit_id&&e.jsx($e,{variant:"outline",className:"ml-2",children:"Kit linked"})]}),u===3&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between flex-wrap gap-2",children:[e.jsx("div",{className:"text-[12.5px] text-slate-500",children:"Every piece stays an editable draft. Nothing sends automatically."}),e.jsxs($,{variant:"outline",className:"rounded-full",onClick:P,children:[e.jsx(wm,{className:"h-4 w-4 mr-2"}),"Generate draft copy"]})]}),[["registration_copy","Registration page copy"],["email_invite","Email invite"],["social_post","Social post"],["dm_invite","DM / text invite"],["reminder","Reminder message"],["follow_up","Follow-up message"]].map(([fe,je])=>{var Ee;return e.jsx(lf,{label:je,children:e.jsx(Is,{rows:5,value:((Ee=c.promotion)==null?void 0:Ee[fe])??"",onChange:Me=>v({promotion:{...c.promotion,[fe]:Me.target.value}})})},fe)})]}),u===4&&e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"flex justify-end",children:e.jsxs($,{variant:"outline",className:"rounded-full",onClick:M,children:[e.jsx(wm,{className:"h-4 w-4 mr-2"}),"Build run of show"]})}),e.jsx(lf,{label:"Run of show",children:e.jsx(Is,{rows:12,className:"font-mono text-[12.5px]",value:((ue=c.delivery)==null?void 0:ue.run_of_show)??"",onChange:fe=>v({delivery:{...c.delivery,run_of_show:fe.target.value}})})}),e.jsx(lf,{label:"Check-in link",children:e.jsx(be,{value:((ne=c.delivery)==null?void 0:ne.checkin_link)??"",onChange:fe=>v({delivery:{...c.delivery,checkin_link:fe.target.value}}),placeholder:"Paste the Connect event check-in URL"})}),e.jsx(lf,{label:"Event notes",children:e.jsx(Is,{rows:4,value:((ee=c.delivery)==null?void 0:ee.event_notes)??"",onChange:fe=>v({delivery:{...c.delivery,event_notes:fe.target.value}})})}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs($,{variant:"outline",className:"rounded-full",onClick:I,disabled:l.isPending,children:[e.jsx(gg,{className:"h-4 w-4 mr-2"}),"Convert to a Connect event"]}),c.linked_event_id&&e.jsx($,{variant:"ghost",className:"rounded-full",asChild:!0,children:e.jsx(Wn,{to:`/attract/events/${c.linked_event_id}`,children:"Open linked event"})})]})]}),u===5&&e.jsxs("div",{className:"space-y-3",children:[e.jsx(lf,{label:"Attendee segmentation",children:e.jsx(Is,{rows:3,value:((le=c.follow_up)==null?void 0:le.segments)??"",onChange:fe=>v({follow_up:{...c.follow_up,segments:fe.target.value}}),placeholder:"Attended + asked a question / attended / registered no-show"})}),e.jsx(lf,{label:"Resource kit sharing note",children:e.jsx(Is,{rows:3,value:((he=c.follow_up)==null?void 0:he.kit_note)??"",onChange:fe=>v({follow_up:{...c.follow_up,kit_note:fe.target.value}})})}),e.jsx(lf,{label:"Suggested personal follow-ups",children:e.jsx(Is,{rows:3,value:((ve=c.follow_up)==null?void 0:ve.personal_touches)??"",onChange:fe=>v({follow_up:{...c.follow_up,personal_touches:fe.target.value}})})}),e.jsx(lf,{label:"Conversion / relationship outcomes",children:e.jsx(Is,{rows:3,value:((ge=c.follow_up)==null?void 0:ge.outcomes)??"",onChange:fe=>v({follow_up:{...c.follow_up,outcomes:fe.target.value}})})}),e.jsxs($,{variant:"outline",className:"rounded-full",onClick:B,children:[e.jsx(Jh,{className:"h-4 w-4 mr-2"}),"Add 3 follow-ups to Follow-Up Center"]})]})]})]});function q(fe,je,Ee){A(C.map(Me=>Me.id===fe?{...Me,lessons:Me.lessons.map(De=>De.id===je?{...De,...Ee}:De)}:Me))}}function Kae(s,t,n){const r=[...s],[a]=r.splice(t,1);return r.splice(n,0,a),r}function mWn(s){if(!s)return"";const t=new Date(s);return new Date(t.getTime()-t.getTimezoneOffset()*6e4).toISOString().slice(0,16)}function lf({label:s,children:t,className:n}){return e.jsxs("div",{className:n,children:[e.jsx(se,{className:"text-[12px] text-slate-600 mb-1 block",children:s}),t]})}function b_t({label:s,items:t,onChange:n}){return e.jsxs("div",{children:[e.jsx(se,{className:"text-[12px] text-slate-600 mb-1 block",children:s}),e.jsxs("div",{className:"space-y-2",children:[t.map((r,a)=>e.jsxs("div",{className:"flex gap-2",children:[e.jsx(be,{value:r.title,placeholder:"Title",onChange:i=>n(t.map((l,o)=>o===a?{...l,title:i.target.value}:l))}),e.jsx(be,{value:r.url,placeholder:"https://",onChange:i=>n(t.map((l,o)=>o===a?{...l,url:i.target.value}:l))}),e.jsx($,{variant:"ghost",size:"icon",className:"text-destructive",onClick:()=>n(t.filter((i,l)=>l!==a)),children:e.jsx(Pn,{className:"h-4 w-4"})})]},a)),e.jsxs($,{size:"sm",variant:"ghost",onClick:()=>n([...t,{title:"",url:""}]),children:[e.jsx(sn,{className:"h-3.5 w-3.5 mr-1.5"}),"Add ",s.toLowerCase().slice(0,-1)]})]})]})}function pWn({m:s}){var t,n,r;return e.jsxs("div",{className:"grid lg:grid-cols-2 gap-4",children:[e.jsxs(_e,{className:"p-5 rounded-2xl",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-widest text-violet-700 font-semibold mb-2",children:"Curriculum"}),(s.curriculum??[]).length===0?e.jsx("div",{className:"text-[13px] text-slate-500",children:"Nothing yet."}):(s.curriculum??[]).map(a=>e.jsxs("div",{className:"mb-3",children:[e.jsx("div",{className:"font-semibold text-[14px]",children:a.title}),e.jsx("ul",{className:"mt-1 space-y-1",children:a.lessons.map(i=>e.jsxs("li",{className:"text-[13px] text-slate-600",children:["• ",i.title,i.minutes?` (${i.minutes}m)`:""]},i.id))})]},a.id))]}),e.jsxs(_e,{className:"p-5 rounded-2xl",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-widest text-violet-700 font-semibold mb-2",children:"Workbook outline"}),e.jsx("pre",{className:"text-[12.5px] whitespace-pre-wrap text-slate-700",children:((t=s.assets)==null?void 0:t.workbook)||"Nothing yet."})]}),e.jsxs(_e,{className:"p-5 rounded-2xl",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-widest text-violet-700 font-semibold mb-2",children:"Registration copy"}),e.jsx("pre",{className:"text-[12.5px] whitespace-pre-wrap text-slate-700",children:((n=s.promotion)==null?void 0:n.registration_copy)||"Nothing yet."})]}),e.jsxs(_e,{className:"p-5 rounded-2xl",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-widest text-violet-700 font-semibold mb-2",children:"Presenter run of show"}),e.jsx("pre",{className:"text-[12.5px] whitespace-pre-wrap font-mono text-slate-700",children:((r=s.delivery)==null?void 0:r.run_of_show)||"Nothing yet."})]})]})}const YA=U;function _te(s,t={}){const{orderBy:n="created_at",ascending:r=!1,titleField:a="title",duplicateOverrides:i={},label:l="Record"}=t,{user:o}=_s(),c=ts(),d=[s,o==null?void 0:o.id],u=ht({queryKey:d,enabled:!!o,queryFn:async()=>{const{data:b,error:v}=await YA.from(s).select("*").order(n,{ascending:r,nullsFirst:!1});if(v)throw v;return b??[]}}),h=()=>{c.invalidateQueries({queryKey:[s]}),c.invalidateQueries({queryKey:["attract-followups"]}),c.invalidateQueries({queryKey:["attract-activities"]})},m=yt({mutationFn:async b=>{const{data:v,error:N}=await YA.from(s).insert({...b,user_id:o.id}).select("*").single();if(N)throw N;return v},onSuccess:()=>{h(),ae.success(`${l} saved`)},onError:b=>ae.error(b.message)}),p=yt({mutationFn:async({id:b,...v})=>{const{error:N}=await YA.from(s).update(v).eq("id",b);if(N)throw N},onSuccess:()=>{h(),ae.success("Updated")},onError:b=>ae.error(b.message)}),x=yt({mutationFn:async b=>{const{id:v,created_at:N,updated_at:C,user_id:A,...T}=b,P={...T,...i,user_id:o.id};a&&P[a]&&(P[a]=`${P[a]} (copy)`);const{data:M,error:I}=await YA.from(s).insert(P).select("id").single();if(I)throw I;return M},onSuccess:()=>{h(),ae.success("Duplicated")},onError:b=>ae.error(b.message)}),g=yt({mutationFn:async({id:b,archived:v})=>{const{error:N}=await YA.from(s).update({is_archived:v}).eq("id",b);if(N)throw N},onSuccess:(b,v)=>{h(),ae.success(v.archived?"Archived":"Restored")},onError:b=>ae.error(b.message)}),y=yt({mutationFn:async b=>{const{error:v}=await YA.from(s).delete().eq("id",b);if(v)throw v},onSuccess:()=>{h(),ae.success("Deleted")},onError:b=>ae.error(b.message)});return{items:u.data??[],isLoading:u.isLoading,error:u.error,refetch:u.refetch,create:m,update:p,duplicate:x,archive:g,remove:y,userId:o==null?void 0:o.id}}function HTe(){const{user:s}=_s(),t=ts();return yt({mutationFn:async({title:n,dueAt:r,notes:a,touchType:i="task",agentId:l})=>{const{error:o}=await YA.from("attract_follow_ups").insert({user_id:s.id,title:n,due_at:r??null,notes:a??null,touch_type:i,priority:"medium",agent_id:l??null});if(o)throw o},onSuccess:()=>{t.invalidateQueries({queryKey:["attract-followups"]}),t.invalidateQueries({queryKey:["attract-daily-plan"]}),ae.success("Added to Follow-Up Center & Today’s Plan")},onError:n=>ae.error(n.message)})}function wte(){const{user:s}=_s(),t=ts();return yt({mutationFn:async({title:n,description:r,pillar:a="produce",activityType:i="tool_action",agentId:l,metadata:o})=>{const{error:c}=await YA.rpc("award_attract_activity",{_user_id:s.id,_activity_type:i,_title:n,_description:r??null,_pillar:a,_agent_id:l??null,_metadata:o??{},_dedupe_minutes:5});if(c)throw c},onSuccess:()=>{t.invalidateQueries({queryKey:["attract-activities"]}),t.invalidateQueries({queryKey:["attract-score"]})},onError:n=>ae.error(n.message)})}const fWn=["annual","quarterly","monthly"],a9=[{key:"closings",label:"Closings",target:"closings_target",actual:"closings_actual",format:"number"},{key:"gci",label:"GCI",target:"gci_target",actual:"gci_actual",format:"currency"},{key:"volume",label:"Volume",target:"volume_target",actual:"volume_actual",format:"currency"},{key:"listings",label:"Listings",target:"listings_target",actual:"listings_actual",format:"number"},{key:"buyer_sides",label:"Buyer Sides",target:"buyer_sides_target",actual:"buyer_sides_actual",format:"number"},{key:"appointments",label:"Appointments",target:"appointments_target",actual:"appointments_actual",format:"number"}];function i9(s){return s.period_type==="quarterly"?`Q${s.quarter??1} ${s.year}`:s.period_type==="monthly"?`${new Date(2e3,(s.month??1)-1,1).toLocaleString("en-US",{month:"long"})} ${s.year}`:`${s.year}`}function xWn(s,t=new Date){let n,r;if(s.period_type==="monthly"){const l=(s.month??1)-1;n=new Date(s.year,l,1),r=new Date(s.year,l+1,1)}else if(s.period_type==="quarterly"){const l=(s.quarter??1)-1;n=new Date(s.year,l*3,1),r=new Date(s.year,l*3+3,1)}else n=new Date(s.year,0,1),r=new Date(s.year+1,0,1);const a=r.getTime()-n.getTime(),i=t.getTime()-n.getTime();return Math.max(0,Math.min(1,i/a))}function gWn(s,t){if(!s)return!1;const[n,r]=s.split(/[-/T]/).map(Number);return n!==t.year?!1:t.period_type==="monthly"?r===t.month:t.period_type==="quarterly"?Math.ceil(r/3)===t.quarter:!0}function yWn(){const s=_te("attract_production_goals",{orderBy:"year",ascending:!1,titleField:"label",label:"Goal",duplicateOverrides:{closings_actual:0,gci_actual:0,volume_actual:0,listings_actual:0,buyer_sides_actual:0,appointments_actual:0,is_archived:!1}}),{transactions:t}=UWt(),n=HTe(),r=wte(),a=j.useMemo(()=>{const i={};return s.items.forEach(l=>{i[l.id]={closings:t.filter(o=>gWn(o.closing_date,l)).length}}),i},[s.items,t]);return{...s,goals:s.items,autoProgress:a,quickTask:n,logActivity:r}}function vWn(s){const t=Number(s??0);return t?{monthly:t/12,weekly:t/52}:null}const bWn=Array.from({length:12},(s,t)=>({value:t+1,label:new Date(2e3,t,1).toLocaleString("en-US",{month:"long"})}));function P4(s,t){return Number.isFinite(s)?t==="currency"?s>=1e3?`$${Math.round(s).toLocaleString()}`:`$${s.toFixed(0)}`:Number.isInteger(s)?String(s):s.toFixed(1):"—"}function _Wn({pct:s,size:t=92}){const n=(t-12)/2,r=2*Math.PI*n,a=Math.max(0,Math.min(1,s));return e.jsxs("svg",{width:t,height:t,className:"-rotate-90 flex-shrink-0",children:[e.jsx("circle",{cx:t/2,cy:t/2,r:n,stroke:"#ede9fe",strokeWidth:9,fill:"none"}),e.jsx("circle",{cx:t/2,cy:t/2,r:n,stroke:"#7c3aed",strokeWidth:9,fill:"none",strokeLinecap:"round",strokeDasharray:r,strokeDashoffset:r*(1-a)})]})}const __t={period_type:"annual",year:new Date().getFullYear(),quarter:1,month:new Date().getMonth()+1,use_auto_progress:!0};function wWn(){const{goals:s,isLoading:t,error:n,refetch:r,create:a,update:i,duplicate:l,archive:o,remove:c,autoProgress:d,quickTask:u,logActivity:h}=yWn(),[m,p]=j.useState(!1),[x,g]=j.useState(null),[y,b]=j.useState(null),[v,N]=j.useState(null),C=j.useMemo(()=>s.filter(M=>m?M.is_archived:!M.is_archived),[s,m]),A=(M,I)=>{var B;const D=Number(M[I.actual]??0);return M.use_auto_progress&&I.key==="closings"?Math.max(D,((B=d[M.id])==null?void 0:B.closings)??0):D},T=async()=>{var I;if(!x)return;const M={label:((I=x.label)==null?void 0:I.trim())||null,period_type:x.period_type??"annual",year:Number(x.year)||new Date().getFullYear(),quarter:x.period_type==="quarterly"?Number(x.quarter)||1:null,month:x.period_type==="monthly"?Number(x.month)||1:null,closings_target:x.closings_target??null,gci_target:x.gci_target??null,volume_target:x.volume_target??null,listings_target:x.listings_target??null,buyer_sides_target:x.buyer_sides_target??null,appointments_target:x.appointments_target??null,use_auto_progress:x.use_auto_progress??!0,notes:x.notes??null};x.id?await i.mutateAsync({id:x.id,...M}):await a.mutateAsync(M),g(null)},P=async()=>{if(!y)return;const M={};a9.forEach(I=>{M[I.actual]=Number(y[I.actual]??0)}),await i.mutateAsync({id:y.id,...M}),await h.mutateAsync({title:`Updated production progress — ${i9(y)}`,pillar:"produce",activityType:"goal_progress"}),b(null)};return e.jsxs("div",{children:[e.jsxs(Wn,{to:"/attract/produce",className:"inline-flex items-center gap-1.5 text-[12px] text-slate-500 hover:text-violet-700 mb-3",children:[e.jsx(ka,{className:"h-3.5 w-3.5"})," Back to Produce"]}),e.jsx(nm,{eyebrow:"Produce → Tool",title:"Production Goals",description:"Set the annual, quarterly, and monthly numbers you're playing for — then track pace, not just totals. Progress can be updated manually or pulled from the transactions you log.",actions:e.jsxs(e.Fragment,{children:[e.jsx($,{variant:"outline",className:"rounded-full",onClick:()=>p(M=>!M),children:m?"Show active":"Show archived"}),e.jsxs($,{className:"rounded-full bg-gradient-to-r from-violet-600 to-indigo-600",onClick:()=>g({...__t}),children:[e.jsx(sn,{className:"h-4 w-4 mr-1.5"})," New Goal"]})]})}),t&&e.jsx("div",{className:"grid gap-4 md:grid-cols-2",children:[0,1].map(M=>e.jsx(on,{className:"h-56 rounded-2xl"},M))}),!t&&n&&e.jsxs(_e,{className:"p-8 rounded-2xl text-center",children:[e.jsx(xo,{className:"h-6 w-6 text-rose-500 mx-auto mb-2"}),e.jsx("div",{className:"font-semibold text-slate-900",children:"Couldn't load your goals"}),e.jsx("div",{className:"text-[13px] text-slate-600 mt-1",children:n.message}),e.jsxs($,{variant:"outline",className:"rounded-full mt-4",onClick:()=>r(),children:[e.jsx(Ih,{className:"h-3.5 w-3.5 mr-1.5"})," Retry"]})]}),!t&&!n&&C.length===0&&e.jsxs(_e,{className:"p-10 rounded-2xl text-center border-dashed",children:[e.jsx("div",{className:"h-12 w-12 rounded-2xl bg-violet-50 text-violet-600 grid place-items-center mx-auto mb-3",children:e.jsx(Mu,{className:"h-6 w-6"})}),e.jsx("div",{className:"text-[16px] font-semibold text-slate-900",children:m?"No archived goals":"No production goals yet"}),e.jsx("p",{className:"text-[13.5px] text-slate-600 mt-1.5 max-w-md mx-auto",children:"Start with one annual goal. Attract will break it into monthly and weekly activity targets and show whether you're ahead or behind pace."}),!m&&e.jsxs($,{className:"rounded-full mt-4 bg-gradient-to-r from-violet-600 to-indigo-600",onClick:()=>g({...__t}),children:[e.jsx(sn,{className:"h-4 w-4 mr-1.5"})," Create your first goal"]})]}),e.jsx("div",{className:"grid gap-4 md:grid-cols-2",children:C.map(M=>{const I=xWn(M),D=a9.find(J=>M[J.target])??a9[0],B=Number(M[D.target]??0),q=A(M,D),W=B?q/B:0,V=B*I,K=q>=V,Q=vWn(B);return e.jsxs(_e,{className:"p-5 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-[16px] font-semibold text-slate-900",children:M.label||`${i9(M)} Goals`}),e.jsx($e,{variant:"outline",className:"rounded-full capitalize",children:M.period_type}),e.jsx($e,{variant:"outline",className:"rounded-full",children:i9(M)})]}),M.notes&&e.jsx("div",{className:"text-[12.5px] text-slate-600 mt-1 line-clamp-2",children:M.notes})]}),e.jsxs("div",{className:"flex gap-1",children:[e.jsx($,{size:"icon",variant:"ghost",className:"h-8 w-8",title:"Edit",onClick:()=>g(M),children:e.jsx(Ya,{className:"h-3.5 w-3.5"})}),e.jsx($,{size:"icon",variant:"ghost",className:"h-8 w-8",title:"Duplicate",onClick:()=>l.mutate(M),children:e.jsx(Ca,{className:"h-3.5 w-3.5"})}),e.jsx($,{size:"icon",variant:"ghost",className:"h-8 w-8",title:M.is_archived?"Restore":"Archive",onClick:()=>o.mutate({id:M.id,archived:!M.is_archived}),children:e.jsx(Am,{className:"h-3.5 w-3.5"})}),e.jsx($,{size:"icon",variant:"ghost",className:"h-8 w-8 text-rose-600",title:"Delete",onClick:()=>N(M),children:e.jsx(Pn,{className:"h-3.5 w-3.5"})})]})]}),e.jsxs("div",{className:"flex items-center gap-4 mt-4",children:[e.jsxs("div",{className:"relative",children:[e.jsx(_Wn,{pct:W}),e.jsx("div",{className:"absolute inset-0 grid place-items-center",children:e.jsxs("div",{className:"text-[15px] font-semibold tabular-nums text-slate-900",children:[Math.round(W*100),"%"]})})]}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"text-[12px] uppercase tracking-wider text-slate-500",children:D.label}),e.jsxs("div",{className:"text-[22px] font-semibold tabular-nums text-slate-900",children:[P4(q,D.format)," ",e.jsxs("span",{className:"text-slate-400 text-[15px]",children:["/ ",P4(B,D.format)]})]}),e.jsxs("div",{className:`text-[12.5px] mt-0.5 font-medium ${K?"text-emerald-600":"text-amber-600"}`,children:[K?"Ahead of pace":"Behind pace"," · pace target ",P4(V,D.format)," (",Math.round(I*100),"% of period elapsed)"]})]})]}),e.jsx("div",{className:"grid grid-cols-2 sm:grid-cols-3 gap-2 mt-4",children:a9.filter(J=>M[J.target]).map(J=>{const ce=Number(M[J.target]),ue=A(M,J);return e.jsxs("div",{className:"rounded-xl bg-slate-50 px-3 py-2",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-wider text-slate-500",children:J.label}),e.jsxs("div",{className:"text-[13.5px] font-semibold tabular-nums text-slate-900",children:[P4(ue,J.format)," / ",P4(ce,J.format)]}),e.jsx("div",{className:"h-1.5 rounded-full bg-slate-200 mt-1.5 overflow-hidden",children:e.jsx("div",{className:"h-full bg-violet-600",style:{width:`${Math.min(100,ce?ue/ce*100:0)}%`}})})]},J.key)})}),M.period_type==="annual"&&Q&&e.jsxs("div",{className:"mt-3 rounded-xl border border-violet-100 bg-violet-50/60 px-3.5 py-2.5 text-[12.5px] text-violet-900",children:["Break it down: ",e.jsx("strong",{children:P4(Q.monthly,D.format)})," per month ·"," ",e.jsx("strong",{children:P4(Q.weekly,D.format)})," per week of ",D.label.toLowerCase(),"."]}),e.jsxs("div",{className:"flex gap-2 mt-4 flex-wrap",children:[e.jsx($,{size:"sm",variant:"outline",className:"rounded-full",onClick:()=>b({...M}),children:"Update progress"}),e.jsxs($,{size:"sm",variant:"outline",className:"rounded-full",onClick:()=>u.mutate({title:`Goal push: ${D.label} — ${P4(Q?Q.weekly:B,D.format)} this week`,dueAt:new Date().toISOString(),notes:`From ${i9(M)} production goal`,touchType:"goal"}),children:[e.jsx(Jh,{className:"h-3.5 w-3.5 mr-1.5"})," Add to Today's Plan"]}),e.jsxs($,{size:"sm",variant:"outline",className:"rounded-full",onClick:()=>h.mutate({title:`Win logged toward ${i9(M)} goals`,pillar:"produce",activityType:"goal_win"}),children:[e.jsx(pl,{className:"h-3.5 w-3.5 mr-1.5"})," Log a win"]})]})]},M.id)})}),e.jsx(Os,{open:!!x,onOpenChange:M=>!M&&g(null),children:e.jsxs(Rs,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsxs(Us,{children:[e.jsx(zs,{children:x!=null&&x.id?"Edit goal":"New production goal"}),e.jsx(Sr,{children:"Only fill in the targets you actually track. Blank targets are hidden."})]}),x&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid sm:grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(se,{children:"Label (optional)"}),e.jsx(be,{value:x.label??"",onChange:M=>g({...x,label:M.target.value}),placeholder:"e.g. 2026 Big Rock"})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Period"}),e.jsxs(vs,{value:x.period_type,onValueChange:M=>g({...x,period_type:M}),children:[e.jsx(gs,{children:e.jsx(bs,{})}),e.jsx(ys,{children:fWn.map(M=>e.jsx(Ye,{value:M,className:"capitalize",children:M},M))})]})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Year"}),e.jsx(be,{type:"number",value:x.year??"",onChange:M=>g({...x,year:Number(M.target.value)})})]}),x.period_type==="quarterly"&&e.jsxs("div",{children:[e.jsx(se,{children:"Quarter"}),e.jsxs(vs,{value:String(x.quarter??1),onValueChange:M=>g({...x,quarter:Number(M)}),children:[e.jsx(gs,{children:e.jsx(bs,{})}),e.jsx(ys,{children:[1,2,3,4].map(M=>e.jsxs(Ye,{value:String(M),children:["Q",M]},M))})]})]}),x.period_type==="monthly"&&e.jsxs("div",{children:[e.jsx(se,{children:"Month"}),e.jsxs(vs,{value:String(x.month??1),onValueChange:M=>g({...x,month:Number(M)}),children:[e.jsx(gs,{children:e.jsx(bs,{})}),e.jsx(ys,{children:bWn.map(M=>e.jsx(Ye,{value:String(M.value),children:M.label},M.value))})]})]})]}),e.jsx("div",{className:"grid sm:grid-cols-3 gap-3",children:a9.map(M=>e.jsxs("div",{children:[e.jsxs(se,{children:[M.label," target"]}),e.jsx(be,{type:"number",value:x[M.target]??"",onChange:I=>g({...x,[M.target]:I.target.value===""?null:Number(I.target.value)})})]},M.key))}),e.jsxs("div",{className:"flex items-center justify-between rounded-xl border border-slate-200 px-4 py-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[13.5px] font-medium text-slate-900",children:"Pull closings from logged transactions"}),e.jsx("div",{className:"text-[12px] text-slate-600",children:"Uses the transactions in your Transaction-to-Relationship Tracker for this period."})]}),e.jsx(Tn,{checked:x.use_auto_progress??!0,onCheckedChange:M=>g({...x,use_auto_progress:M})})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Notes"}),e.jsx(Is,{value:x.notes??"",onChange:M=>g({...x,notes:M.target.value}),rows:3})]})]}),e.jsxs(kr,{children:[e.jsx($,{variant:"ghost",onClick:()=>g(null),children:"Cancel"}),e.jsx($,{className:"bg-gradient-to-r from-violet-600 to-indigo-600",onClick:T,disabled:a.isPending||i.isPending,children:"Save goal"})]})]})}),e.jsx(Os,{open:!!y,onOpenChange:M=>!M&&b(null),children:e.jsxs(Rs,{className:"max-w-lg",children:[e.jsxs(Us,{children:[e.jsx(zs,{children:"Update progress"}),e.jsxs(Sr,{children:[y?i9(y):""," — enter your actuals to date."]})]}),y&&e.jsx("div",{className:"grid sm:grid-cols-2 gap-3",children:a9.filter(M=>y[M.target]).map(M=>e.jsxs("div",{children:[e.jsx(se,{children:M.label}),e.jsx(be,{type:"number",value:y[M.actual]??0,onChange:I=>b({...y,[M.actual]:Number(I.target.value)})})]},M.key))}),e.jsxs(kr,{children:[e.jsx($,{variant:"ghost",onClick:()=>b(null),children:"Cancel"}),e.jsx($,{className:"bg-gradient-to-r from-violet-600 to-indigo-600",onClick:P,children:"Save progress"})]})]})}),e.jsx(Os,{open:!!v,onOpenChange:M=>!M&&N(null),children:e.jsxs(Rs,{className:"max-w-md",children:[e.jsxs(Us,{children:[e.jsx(zs,{children:"Delete this goal?"}),e.jsx(Sr,{children:"This can't be undone. Archive it instead if you want to keep the history."})]}),e.jsxs(kr,{children:[e.jsx($,{variant:"ghost",onClick:()=>N(null),children:"Cancel"}),e.jsx($,{variant:"destructive",onClick:()=>{c.mutate(v.id),N(null)},children:"Delete"})]})]})})]})}const jRe=[{value:"award",label:"Award"},{value:"ranking",label:"Ranking"},{value:"certification",label:"Certification"},{value:"milestone",label:"Milestone"},{value:"media",label:"Media Mention"},{value:"production",label:"Production Recognition"}];function jWn(){const s=_te("attract_awards",{orderBy:"awarded_on",ascending:!1,label:"Award",duplicateOverrides:{is_archived:!1}}),t=wte();return{...s,awards:s.items,logActivity:t}}const w_t={category:"award",status:"active",is_public:!0};function j_t(s){if(!s)return"No date";const[t,n,r]=s.split(/[-/T]/).map(Number);return new Date(t,n-1,r).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"})}function NWn(){const{awards:s,isLoading:t,error:n,refetch:r,create:a,update:i,duplicate:l,archive:o,remove:c,logActivity:d}=jWn(),[u,h]=j.useState(!1),[m,p]=j.useState("all"),[x,g]=j.useState(""),[y,b]=j.useState(null),[v,N]=j.useState(null),C=j.useMemo(()=>s.filter(P=>{if(u!==!!P.is_archived||m!=="all"&&P.category!==m)return!1;const M=x.toLowerCase().trim();return!M||`${P.title} ${P.issuer??""} ${P.description??""}`.toLowerCase().includes(M)}),[s,u,m,x]),A=async()=>{var M;if(!((M=y==null?void 0:y.title)!=null&&M.trim())){ae.error("Add a title");return}const P={title:y.title.trim(),issuer:y.issuer||null,awarded_on:y.awarded_on||null,category:y.category??"award",description:y.description||null,proof_url:y.proof_url||null,production_period:y.production_period||null,is_public:y.is_public??!0};y.id?await i.mutateAsync({id:y.id,...P}):(await a.mutateAsync(P),await d.mutateAsync({title:`Added recognition: ${P.title}`,pillar:"produce",activityType:"award_added"})),b(null)},T=P=>{var I;const M=[P.title,P.issuer&&`— ${P.issuer}`,P.awarded_on&&`(${j_t(P.awarded_on)})`].filter(Boolean).join(" ");(I=navigator.clipboard)==null||I.writeText(M),ae.success("Proof point copied — paste it into Content Studio")};return e.jsxs("div",{children:[e.jsxs(Wn,{to:"/attract/produce",className:"inline-flex items-center gap-1.5 text-[12px] text-slate-500 hover:text-violet-700 mb-3",children:[e.jsx(ka,{className:"h-3.5 w-3.5"})," Back to Produce"]}),e.jsx(nm,{eyebrow:"Produce → Tool",title:"Awards & Recognition",description:"Your credibility file. Keep every award, ranking, and certification in one place so proof points are ready when you write content or pitch a speaking slot.",actions:e.jsxs(e.Fragment,{children:[e.jsx($,{variant:"outline",className:"rounded-full",onClick:()=>h(P=>!P),children:u?"Show active":"Show archived"}),e.jsxs($,{className:"rounded-full bg-gradient-to-r from-violet-600 to-indigo-600",onClick:()=>b({...w_t}),children:[e.jsx(sn,{className:"h-4 w-4 mr-1.5"})," Add Recognition"]})]})}),e.jsxs("div",{className:"flex gap-2 flex-wrap mb-4",children:[e.jsx(be,{value:x,onChange:P=>g(P.target.value),placeholder:"Search recognitions",className:"max-w-xs rounded-full"}),e.jsxs(vs,{value:m,onValueChange:p,children:[e.jsx(gs,{className:"w-[190px] rounded-full",children:e.jsx(bs,{})}),e.jsxs(ys,{children:[e.jsx(Ye,{value:"all",children:"All categories"}),jRe.map(P=>e.jsx(Ye,{value:P.value,children:P.label},P.value))]})]})]}),t&&e.jsx("div",{className:"grid gap-3 md:grid-cols-2",children:[0,1,2,3].map(P=>e.jsx(on,{className:"h-36 rounded-2xl"},P))}),!t&&n&&e.jsxs(_e,{className:"p-8 rounded-2xl text-center",children:[e.jsx(xo,{className:"h-6 w-6 text-rose-500 mx-auto mb-2"}),e.jsx("div",{className:"font-semibold text-slate-900",children:"Couldn't load recognitions"}),e.jsx("div",{className:"text-[13px] text-slate-600 mt-1",children:n.message}),e.jsxs($,{variant:"outline",className:"rounded-full mt-4",onClick:()=>r(),children:[e.jsx(Ih,{className:"h-3.5 w-3.5 mr-1.5"})," Retry"]})]}),!t&&!n&&C.length===0&&e.jsxs(_e,{className:"p-10 rounded-2xl text-center border-dashed",children:[e.jsx("div",{className:"h-12 w-12 rounded-2xl bg-violet-50 text-violet-600 grid place-items-center mx-auto mb-3",children:e.jsx(pu,{className:"h-6 w-6"})}),e.jsx("div",{className:"text-[16px] font-semibold text-slate-900",children:u?"Nothing archived":"No recognitions logged yet"}),e.jsx("p",{className:"text-[13.5px] text-slate-600 mt-1.5 max-w-md mx-auto",children:"Add awards, production rankings, and designations. Copy any one of them as a proof point when writing authority content."}),!u&&e.jsxs($,{className:"rounded-full mt-4 bg-gradient-to-r from-violet-600 to-indigo-600",onClick:()=>b({...w_t}),children:[e.jsx(sn,{className:"h-4 w-4 mr-1.5"})," Add your first"]})]}),e.jsx("div",{className:"grid gap-3 md:grid-cols-2",children:C.map(P=>{var M;return e.jsxs(_e,{className:"p-5 rounded-2xl",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3",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-[15.5px] font-semibold text-slate-900",children:P.title}),e.jsx($e,{variant:"outline",className:"rounded-full capitalize",children:((M=jRe.find(I=>I.value===P.category))==null?void 0:M.label)??P.category})]}),e.jsx("div",{className:"text-[12.5px] text-slate-500 mt-1",children:[P.issuer,j_t(P.awarded_on),P.production_period].filter(Boolean).join(" · ")}),P.description&&e.jsx("p",{className:"text-[13px] text-slate-600 mt-2 line-clamp-3",children:P.description})]}),e.jsxs("div",{className:"flex gap-1 flex-shrink-0",children:[e.jsx($,{size:"icon",variant:"ghost",className:"h-8 w-8",title:"Edit",onClick:()=>b(P),children:e.jsx(Ya,{className:"h-3.5 w-3.5"})}),e.jsx($,{size:"icon",variant:"ghost",className:"h-8 w-8",title:"Duplicate",onClick:()=>l.mutate(P),children:e.jsx(Ca,{className:"h-3.5 w-3.5"})}),e.jsx($,{size:"icon",variant:"ghost",className:"h-8 w-8",title:P.is_archived?"Restore":"Archive",onClick:()=>o.mutate({id:P.id,archived:!P.is_archived}),children:e.jsx(Am,{className:"h-3.5 w-3.5"})}),e.jsx($,{size:"icon",variant:"ghost",className:"h-8 w-8 text-rose-600",title:"Delete",onClick:()=>N(P),children:e.jsx(Pn,{className:"h-3.5 w-3.5"})})]})]}),e.jsxs("div",{className:"flex gap-2 mt-4 flex-wrap",children:[e.jsxs($,{size:"sm",variant:"outline",className:"rounded-full",onClick:()=>T(P),children:[e.jsx(Dc,{className:"h-3.5 w-3.5 mr-1.5"})," Copy proof point"]}),e.jsx($,{size:"sm",variant:"outline",className:"rounded-full",asChild:!0,children:e.jsxs(Wn,{to:"/attract/influence/content-studio",children:[e.jsx(dn,{className:"h-3.5 w-3.5 mr-1.5"})," Write about it"]})}),P.proof_url&&e.jsx($,{size:"sm",variant:"ghost",className:"rounded-full",asChild:!0,children:e.jsxs("a",{href:P.proof_url,target:"_blank",rel:"noreferrer",children:["Proof ",e.jsx(Tr,{className:"h-3 w-3 ml-1.5"})]})})]})]},P.id)})}),e.jsx(Os,{open:!!y,onOpenChange:P=>!P&&b(null),children:e.jsxs(Rs,{className:"max-w-xl max-h-[90vh] overflow-y-auto",children:[e.jsxs(Us,{children:[e.jsx(zs,{children:y!=null&&y.id?"Edit recognition":"Add recognition"}),e.jsx(Sr,{children:"Keep it factual — this feeds the proof points you use publicly."})]}),y&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx(se,{children:"Title *"}),e.jsx(be,{value:y.title??"",onChange:P=>b({...y,title:P.target.value}),placeholder:"e.g. Top 1% Producer"})]}),e.jsxs("div",{className:"grid sm:grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(se,{children:"Issued by"}),e.jsx(be,{value:y.issuer??"",onChange:P=>b({...y,issuer:P.target.value}),placeholder:"Board, brokerage, publication"})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Category"}),e.jsxs(vs,{value:y.category??"award",onValueChange:P=>b({...y,category:P}),children:[e.jsx(gs,{children:e.jsx(bs,{})}),e.jsx(ys,{children:jRe.map(P=>e.jsx(Ye,{value:P.value,children:P.label},P.value))})]})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Date awarded"}),e.jsx(be,{type:"date",value:y.awarded_on??"",onChange:P=>b({...y,awarded_on:P.target.value})})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Production period"}),e.jsx(be,{value:y.production_period??"",onChange:P=>b({...y,production_period:P.target.value}),placeholder:"e.g. 2025"})]})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Proof link"}),e.jsx(be,{value:y.proof_url??"",onChange:P=>b({...y,proof_url:P.target.value}),placeholder:"https://"})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Description"}),e.jsx(Is,{rows:3,value:y.description??"",onChange:P=>b({...y,description:P.target.value})})]})]}),e.jsxs(kr,{children:[e.jsx($,{variant:"ghost",onClick:()=>b(null),children:"Cancel"}),e.jsx($,{className:"bg-gradient-to-r from-violet-600 to-indigo-600",onClick:A,disabled:a.isPending||i.isPending,children:"Save"})]})]})}),e.jsx(Os,{open:!!v,onOpenChange:P=>!P&&N(null),children:e.jsxs(Rs,{className:"max-w-md",children:[e.jsxs(Us,{children:[e.jsx(zs,{children:"Delete this recognition?"}),e.jsx(Sr,{children:"This can't be undone."})]}),e.jsxs(kr,{children:[e.jsx($,{variant:"ghost",onClick:()=>N(null),children:"Cancel"}),e.jsx($,{variant:"destructive",onClick:()=>{c.mutate(v.id),N(null)},children:"Delete"})]})]})})]})}const kWn=U,N_t=[{value:"pending",label:"Permission pending"},{value:"granted",label:"Permission granted"},{value:"anonymous_only",label:"Anonymous use only"},{value:"declined",label:"Permission declined"}],SWn=["buyer","seller","both","investor","referral_partner","agent","other"];function Yae(s){return s.status==="approved"&&(s.permission_status==="granted"||s.permission_status==="anonymous_only")}function CWn(){const s=_te("attract_testimonials",{orderBy:"created_at",ascending:!1,titleField:"client_name",label:"Testimonial",duplicateOverrides:{use_count:0,last_used_at:null,usage_log:[],status:"draft",is_archived:!1}}),t=wte(),n=ts(),r=yt({mutationFn:async({item:a,kind:i,note:l})=>{const o=[...a.usage_log??[],{at:new Date().toISOString(),kind:i,note:l}].slice(-25),{error:c}=await kWn.from("attract_testimonials").update({use_count:(a.use_count??0)+1,last_used_at:new Date().toISOString(),usage_log:o}).eq("id",a.id);if(c)throw c},onSuccess:()=>{n.invalidateQueries({queryKey:["attract_testimonials"]}),ae.success("Usage recorded")},onError:a=>ae.error(a.message)});return{...s,testimonials:s.items,recordUse:r,logActivity:t}}const k_t={permission_status:"pending",status:"draft",rating:5,tags:[]};function AWn(){const{testimonials:s,isLoading:t,error:n,refetch:r,create:a,update:i,duplicate:l,archive:o,remove:c,recordUse:d,logActivity:u}=CWn(),[h,m]=j.useState(!1),[p,x]=j.useState("all"),[g,y]=j.useState(""),[b,v]=j.useState(null),[N,C]=j.useState(null),A=j.useMemo(()=>s.filter(I=>{if(h!==!!I.is_archived||p==="usable"&&!Yae(I)||p==="pending"&&I.permission_status!=="pending")return!1;const D=g.toLowerCase().trim();return!D||`${I.client_name} ${I.quote} ${(I.tags??[]).join(" ")}`.toLowerCase().includes(D)}),[s,h,p,g]),T=s.filter(I=>!I.is_archived&&Yae(I)).length,P=async()=>{var D,B;if(!((D=b==null?void 0:b.client_name)!=null&&D.trim())||!((B=b==null?void 0:b.quote)!=null&&B.trim())){ae.error("Client name and quote are required");return}const I={client_name:b.client_name.trim(),quote:b.quote.trim(),relationship_type:b.relationship_type||null,transaction_type:b.transaction_type||null,rating:b.rating??null,received_on:b.received_on||null,source_url:b.source_url||null,permission_status:b.permission_status??"pending",market:b.market||null,status:b.status??"draft",tags:b.tags??[]};b.id?await i.mutateAsync({id:b.id,...I}):(await a.mutateAsync(I),await u.mutateAsync({title:`Captured a testimonial from ${I.client_name}`,pillar:"produce",activityType:"testimonial_added"})),v(null)},M=(I,D)=>{var B;if(!Yae(I)){ae.error("Mark it approved with permission before using it publicly");return}(B=navigator.clipboard)==null||B.writeText(`"${I.quote}" — ${I.permission_status==="anonymous_only"?"Client":I.client_name}`),d.mutate({item:I,kind:D})};return e.jsxs("div",{children:[e.jsxs(Wn,{to:"/attract/produce",className:"inline-flex items-center gap-1.5 text-[12px] text-slate-500 hover:text-violet-700 mb-3",children:[e.jsx(ka,{className:"h-3.5 w-3.5"})," Back to Produce"]}),e.jsx(nm,{eyebrow:"Produce → Tool",title:"Client Testimonials",description:"Your social proof library. Capture the exact words clients use, track who gave permission, and see which quotes you've already used so nothing gets overexposed.",actions:e.jsxs(e.Fragment,{children:[e.jsx($,{variant:"outline",className:"rounded-full",onClick:()=>m(I=>!I),children:h?"Show active":"Show archived"}),e.jsxs($,{className:"rounded-full bg-gradient-to-r from-violet-600 to-indigo-600",onClick:()=>v({...k_t}),children:[e.jsx(sn,{className:"h-4 w-4 mr-1.5"})," Add Testimonial"]})]})}),e.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-3 gap-3 mb-4",children:[e.jsxs(_e,{className:"p-4 rounded-2xl",children:[e.jsx("div",{className:"text-[22px] font-semibold tabular-nums text-slate-900",children:s.filter(I=>!I.is_archived).length}),e.jsx("div",{className:"text-[12px] text-slate-500",children:"In library"})]}),e.jsxs(_e,{className:"p-4 rounded-2xl",children:[e.jsx("div",{className:"text-[22px] font-semibold tabular-nums text-emerald-600",children:T}),e.jsx("div",{className:"text-[12px] text-slate-500",children:"Cleared for use"})]}),e.jsxs(_e,{className:"p-4 rounded-2xl",children:[e.jsx("div",{className:"text-[22px] font-semibold tabular-nums text-amber-600",children:s.filter(I=>!I.is_archived&&I.permission_status==="pending").length}),e.jsx("div",{className:"text-[12px] text-slate-500",children:"Permission pending"})]})]}),e.jsxs("div",{className:"flex gap-2 flex-wrap mb-4",children:[e.jsx(be,{value:g,onChange:I=>y(I.target.value),placeholder:"Search quotes, clients, tags",className:"max-w-xs rounded-full"}),e.jsxs(vs,{value:p,onValueChange:I=>x(I),children:[e.jsx(gs,{className:"w-[200px] rounded-full",children:e.jsx(bs,{})}),e.jsxs(ys,{children:[e.jsx(Ye,{value:"all",children:"All testimonials"}),e.jsx(Ye,{value:"usable",children:"Cleared for use"}),e.jsx(Ye,{value:"pending",children:"Permission pending"})]})]})]}),t&&e.jsx("div",{className:"grid gap-3 md:grid-cols-2",children:[0,1,2,3].map(I=>e.jsx(on,{className:"h-40 rounded-2xl"},I))}),!t&&n&&e.jsxs(_e,{className:"p-8 rounded-2xl text-center",children:[e.jsx(xo,{className:"h-6 w-6 text-rose-500 mx-auto mb-2"}),e.jsx("div",{className:"font-semibold text-slate-900",children:"Couldn't load testimonials"}),e.jsx("div",{className:"text-[13px] text-slate-600 mt-1",children:n.message}),e.jsxs($,{variant:"outline",className:"rounded-full mt-4",onClick:()=>r(),children:[e.jsx(Ih,{className:"h-3.5 w-3.5 mr-1.5"})," Retry"]})]}),!t&&!n&&A.length===0&&e.jsxs(_e,{className:"p-10 rounded-2xl text-center border-dashed",children:[e.jsx("div",{className:"h-12 w-12 rounded-2xl bg-violet-50 text-violet-600 grid place-items-center mx-auto mb-3",children:e.jsx(RN,{className:"h-6 w-6"})}),e.jsx("div",{className:"text-[16px] font-semibold text-slate-900",children:"No testimonials match"}),e.jsx("p",{className:"text-[13.5px] text-slate-600 mt-1.5 max-w-md mx-auto",children:"Paste in the reviews and thank-you notes you already have. Mark permission so you always know what's safe to publish."}),!h&&e.jsxs($,{className:"rounded-full mt-4 bg-gradient-to-r from-violet-600 to-indigo-600",onClick:()=>v({...k_t}),children:[e.jsx(sn,{className:"h-4 w-4 mr-1.5"})," Add one"]})]}),e.jsx("div",{className:"grid gap-3 md:grid-cols-2",children:A.map(I=>{var D;return e.jsxs(_e,{className:"p-5 rounded-2xl flex flex-col",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3",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 text-slate-900",children:I.client_name}),I.relationship_type&&e.jsx($e,{variant:"outline",className:"rounded-full capitalize",children:I.relationship_type.replace("_"," ")}),e.jsx($e,{variant:"outline",className:`rounded-full ${Yae(I)?"bg-emerald-50 text-emerald-700 border-emerald-200":"bg-amber-50 text-amber-700 border-amber-200"}`,children:((D=N_t.find(B=>B.value===I.permission_status))==null?void 0:D.label)??I.permission_status})]}),!!I.rating&&e.jsx("div",{className:"flex gap-0.5 mt-1.5",children:Array.from({length:5}).map((B,q)=>e.jsx(Qa,{className:`h-3.5 w-3.5 ${q<(I.rating??0)?"text-amber-500 fill-amber-500":"text-slate-200"}`},q))})]}),e.jsxs("div",{className:"flex gap-1 flex-shrink-0",children:[e.jsx($,{size:"icon",variant:"ghost",className:"h-8 w-8",title:"Edit",onClick:()=>v(I),children:e.jsx(Ya,{className:"h-3.5 w-3.5"})}),e.jsx($,{size:"icon",variant:"ghost",className:"h-8 w-8",title:"Duplicate",onClick:()=>l.mutate(I),children:e.jsx(Ca,{className:"h-3.5 w-3.5"})}),e.jsx($,{size:"icon",variant:"ghost",className:"h-8 w-8",title:I.is_archived?"Restore":"Archive",onClick:()=>o.mutate({id:I.id,archived:!I.is_archived}),children:e.jsx(Am,{className:"h-3.5 w-3.5"})}),e.jsx($,{size:"icon",variant:"ghost",className:"h-8 w-8 text-rose-600",title:"Delete",onClick:()=>C(I),children:e.jsx(Pn,{className:"h-3.5 w-3.5"})})]})]}),e.jsxs("blockquote",{className:"mt-3 text-[13.5px] text-slate-700 border-l-2 border-violet-200 pl-3 italic",children:['"',I.quote,'"']}),e.jsxs("div",{className:"text-[11.5px] text-slate-500 mt-3",children:["Used ",I.use_count??0," ",I.use_count===1?"time":"times",I.last_used_at?` · last ${new Date(I.last_used_at).toLocaleDateString("en-US")}`:"",I.status==="approved"?"":" · draft"]}),e.jsxs("div",{className:"flex gap-2 mt-3 flex-wrap",children:[e.jsxs($,{size:"sm",variant:"outline",className:"rounded-full",onClick:()=>M(I,"copied"),children:[e.jsx(Ca,{className:"h-3.5 w-3.5 mr-1.5"})," Copy & log use"]}),e.jsx($,{size:"sm",variant:"outline",className:"rounded-full",asChild:!0,children:e.jsxs(Wn,{to:"/attract/influence/content-studio",children:[e.jsx(dn,{className:"h-3.5 w-3.5 mr-1.5"})," Draft social proof"]})}),I.status!=="approved"&&e.jsxs($,{size:"sm",variant:"ghost",className:"rounded-full text-emerald-700",onClick:()=>i.mutate({id:I.id,status:"approved"}),children:[e.jsx(j0,{className:"h-3.5 w-3.5 mr-1.5"})," Mark approved"]})]})]},I.id)})}),e.jsx(Os,{open:!!b,onOpenChange:I=>!I&&v(null),children:e.jsxs(Rs,{className:"max-w-xl max-h-[90vh] overflow-y-auto",children:[e.jsxs(Us,{children:[e.jsx(zs,{children:b!=null&&b.id?"Edit testimonial":"Add testimonial"}),e.jsx(Sr,{children:"Use the client's own words. Only publish quotes where permission is granted."})]}),b&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"grid sm:grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(se,{children:"Client name *"}),e.jsx(be,{value:b.client_name??"",onChange:I=>v({...b,client_name:I.target.value})})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Relationship"}),e.jsxs(vs,{value:b.relationship_type??"",onValueChange:I=>v({...b,relationship_type:I}),children:[e.jsx(gs,{children:e.jsx(bs,{placeholder:"Select"})}),e.jsx(ys,{children:SWn.map(I=>e.jsx(Ye,{value:I,className:"capitalize",children:I.replace("_"," ")},I))})]})]})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Quote *"}),e.jsx(Is,{rows:4,value:b.quote??"",onChange:I=>v({...b,quote:I.target.value})})]}),e.jsxs("div",{className:"grid sm:grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(se,{children:"Rating"}),e.jsxs(vs,{value:String(b.rating??5),onValueChange:I=>v({...b,rating:Number(I)}),children:[e.jsx(gs,{children:e.jsx(bs,{})}),e.jsx(ys,{children:[5,4,3,2,1].map(I=>e.jsxs(Ye,{value:String(I),children:[I," star",I>1?"s":""]},I))})]})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Received on"}),e.jsx(be,{type:"date",value:b.received_on??"",onChange:I=>v({...b,received_on:I.target.value})})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Permission"}),e.jsxs(vs,{value:b.permission_status??"pending",onValueChange:I=>v({...b,permission_status:I}),children:[e.jsx(gs,{children:e.jsx(bs,{})}),e.jsx(ys,{children:N_t.map(I=>e.jsx(Ye,{value:I.value,children:I.label},I.value))})]})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Status"}),e.jsxs(vs,{value:b.status??"draft",onValueChange:I=>v({...b,status:I}),children:[e.jsx(gs,{children:e.jsx(bs,{})}),e.jsxs(ys,{children:[e.jsx(Ye,{value:"draft",children:"Draft"}),e.jsx(Ye,{value:"approved",children:"Approved"})]})]})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Market / area"}),e.jsx(be,{value:b.market??"",onChange:I=>v({...b,market:I.target.value})})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Source link"}),e.jsx(be,{value:b.source_url??"",onChange:I=>v({...b,source_url:I.target.value}),placeholder:"https://"})]})]})]}),e.jsxs(kr,{children:[e.jsx($,{variant:"ghost",onClick:()=>v(null),children:"Cancel"}),e.jsx($,{className:"bg-gradient-to-r from-violet-600 to-indigo-600",onClick:P,disabled:a.isPending||i.isPending,children:"Save"})]})]})}),e.jsx(Os,{open:!!N,onOpenChange:I=>!I&&C(null),children:e.jsxs(Rs,{className:"max-w-md",children:[e.jsxs(Us,{children:[e.jsx(zs,{children:"Delete this testimonial?"}),e.jsx(Sr,{children:"This can't be undone."})]}),e.jsxs(kr,{children:[e.jsx($,{variant:"ghost",onClick:()=>C(null),children:"Cancel"}),e.jsx($,{variant:"destructive",onClick:()=>{c.mutate(N.id),C(null)},children:"Delete"})]})]})})]})}const S_t=[{value:"market_update",label:"Market Update"},{value:"local_video",label:"Local Video"},{value:"newsletter",label:"Newsletter"},{value:"stats_post",label:"Stats Post"},{value:"neighborhood",label:"Neighborhood Content"},{value:"speaking",label:"Speaking Opportunity"}],C_t=["idea","planned","drafted","scheduled","published","skipped"],EWn=["weekly","biweekly","monthly","quarterly","one_off"];function WWt(){const s=_te("attract_market_presence",{orderBy:"planned_for",ascending:!0,label:"Commitment",duplicateOverrides:{status:"idea",published_url:null,results_notes:null,is_archived:!1}}),t=HTe(),n=wte();return{...s,commitments:s.items,quickTask:t,logActivity:n}}const A_t={content_type:"market_update",cadence:"monthly",status:"planned"};function TWn(s){if(!s)return"Unscheduled";const[t,n,r]=s.split(/[-/T]/).map(Number);return new Date(t,n-1,r).toLocaleDateString("en-US",{weekday:"short",month:"short",day:"numeric"})}const MWn={idea:"bg-slate-100 text-slate-600 border-slate-200",planned:"bg-blue-50 text-blue-700 border-blue-200",drafted:"bg-violet-50 text-violet-700 border-violet-200",scheduled:"bg-amber-50 text-amber-700 border-amber-200",published:"bg-emerald-50 text-emerald-700 border-emerald-200",skipped:"bg-rose-50 text-rose-700 border-rose-200"};function LWn(){const{commitments:s,isLoading:t,error:n,refetch:r,create:a,update:i,duplicate:l,archive:o,remove:c,quickTask:d,logActivity:u}=WWt(),[h,m]=j.useState(!1),[p,x]=j.useState("all"),[g,y]=j.useState(null),[b,v]=j.useState(null),N=j.useMemo(()=>s.filter(M=>h!==!!M.is_archived?!1:p==="all"||M.status===p),[s,h,p]),C=s.filter(M=>{if(M.status!=="published"||!M.planned_for)return!1;const[I,D,B]=M.planned_for.split(/[-/T]/).map(Number);return(Date.now()-new Date(I,D-1,B).getTime())/864e5<=30}).length,A=s.filter(M=>{if(M.is_archived||!M.planned_for||["published","skipped"].includes(M.status))return!1;const[I,D,B]=M.planned_for.split(/[-/T]/).map(Number);return new Date(I,D-1,B){var I;if(!((I=g==null?void 0:g.title)!=null&&I.trim())){ae.error("Add a title");return}const M={title:g.title.trim(),content_type:g.content_type??"market_update",cadence:g.cadence??"monthly",planned_for:g.planned_for||null,status:g.status??"planned",channel:g.channel||null,audience:g.audience||null,campaign:g.campaign||null,notes:g.notes||null,published_url:g.published_url||null,results_notes:g.results_notes||null};g.id?await i.mutateAsync({id:g.id,...M}):await a.mutateAsync(M),y(null)},P=async M=>{await i.mutateAsync({id:M.id,status:"published"}),await u.mutateAsync({title:`Published market presence: ${M.title}`,pillar:"produce",activityType:"market_presence_published"})};return e.jsxs("div",{children:[e.jsxs(Wn,{to:"/attract/produce",className:"inline-flex items-center gap-1.5 text-[12px] text-slate-500 hover:text-violet-700 mb-3",children:[e.jsx(ka,{className:"h-3.5 w-3.5"})," Back to Produce"]}),e.jsx(nm,{eyebrow:"Produce → Tool",title:"Market Presence",description:"Consistency beats intensity. Commit to a cadence of market updates and local content, then track whether you actually shipped it.",actions:e.jsxs(e.Fragment,{children:[e.jsx($,{variant:"outline",className:"rounded-full",onClick:()=>m(M=>!M),children:h?"Show active":"Show archived"}),e.jsxs($,{className:"rounded-full bg-gradient-to-r from-violet-600 to-indigo-600",onClick:()=>y({...A_t}),children:[e.jsx(sn,{className:"h-4 w-4 mr-1.5"})," New Commitment"]})]})}),e.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-3 gap-3 mb-4",children:[e.jsxs(_e,{className:"p-4 rounded-2xl",children:[e.jsx("div",{className:"text-[22px] font-semibold tabular-nums text-slate-900",children:s.filter(M=>!M.is_archived).length}),e.jsx("div",{className:"text-[12px] text-slate-500",children:"Active commitments"})]}),e.jsxs(_e,{className:"p-4 rounded-2xl",children:[e.jsx("div",{className:"text-[22px] font-semibold tabular-nums text-emerald-600",children:C}),e.jsx("div",{className:"text-[12px] text-slate-500",children:"Published last 30 days"})]}),e.jsxs(_e,{className:"p-4 rounded-2xl",children:[e.jsx("div",{className:"text-[22px] font-semibold tabular-nums text-amber-600",children:A.length}),e.jsx("div",{className:"text-[12px] text-slate-500",children:"Past due"})]})]}),e.jsx("div",{className:"flex gap-2 flex-wrap mb-4",children:e.jsxs(vs,{value:p,onValueChange:x,children:[e.jsx(gs,{className:"w-[190px] rounded-full",children:e.jsx(bs,{})}),e.jsxs(ys,{children:[e.jsx(Ye,{value:"all",children:"All statuses"}),C_t.map(M=>e.jsx(Ye,{value:M,className:"capitalize",children:M},M))]})]})}),t&&e.jsx("div",{className:"space-y-2",children:[0,1,2].map(M=>e.jsx(on,{className:"h-24 rounded-2xl"},M))}),!t&&n&&e.jsxs(_e,{className:"p-8 rounded-2xl text-center",children:[e.jsx(xo,{className:"h-6 w-6 text-rose-500 mx-auto mb-2"}),e.jsx("div",{className:"font-semibold text-slate-900",children:"Couldn't load commitments"}),e.jsx("div",{className:"text-[13px] text-slate-600 mt-1",children:n.message}),e.jsxs($,{variant:"outline",className:"rounded-full mt-4",onClick:()=>r(),children:[e.jsx(Ih,{className:"h-3.5 w-3.5 mr-1.5"})," Retry"]})]}),!t&&!n&&N.length===0&&e.jsxs(_e,{className:"p-10 rounded-2xl text-center border-dashed",children:[e.jsx("div",{className:"h-12 w-12 rounded-2xl bg-violet-50 text-violet-600 grid place-items-center mx-auto mb-3",children:e.jsx(Cg,{className:"h-6 w-6"})}),e.jsx("div",{className:"text-[16px] font-semibold text-slate-900",children:"No commitments yet"}),e.jsx("p",{className:"text-[13.5px] text-slate-600 mt-1.5 max-w-md mx-auto",children:"Start with one: a monthly market update. Set the date, ship it, mark it published — that rhythm is what agents notice."}),!h&&e.jsxs($,{className:"rounded-full mt-4 bg-gradient-to-r from-violet-600 to-indigo-600",onClick:()=>y({...A_t}),children:[e.jsx(sn,{className:"h-4 w-4 mr-1.5"})," Add a commitment"]})]}),e.jsx("div",{className:"space-y-2",children:N.map(M=>{var I;return e.jsxs(_e,{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 text-slate-900",children:M.title}),e.jsx($e,{variant:"outline",className:"rounded-full",children:((I=S_t.find(D=>D.value===M.content_type))==null?void 0:I.label)??M.content_type}),e.jsx($e,{variant:"outline",className:`rounded-full capitalize ${MWn[M.status]??""}`,children:M.status}),e.jsx($e,{variant:"outline",className:"rounded-full capitalize",children:M.cadence.replace("_"," ")})]}),e.jsx("div",{className:"text-[12.5px] text-slate-500 mt-1",children:[TWn(M.planned_for),M.channel,M.audience].filter(Boolean).join(" · ")}),M.notes&&e.jsx("div",{className:"text-[12.5px] text-slate-600 mt-1 line-clamp-2",children:M.notes})]}),e.jsxs("div",{className:"flex gap-1",children:[e.jsx($,{size:"icon",variant:"ghost",className:"h-8 w-8",title:"Edit",onClick:()=>y(M),children:e.jsx(Ya,{className:"h-3.5 w-3.5"})}),e.jsx($,{size:"icon",variant:"ghost",className:"h-8 w-8",title:"Duplicate",onClick:()=>l.mutate(M),children:e.jsx(Ca,{className:"h-3.5 w-3.5"})}),e.jsx($,{size:"icon",variant:"ghost",className:"h-8 w-8",title:M.is_archived?"Restore":"Archive",onClick:()=>o.mutate({id:M.id,archived:!M.is_archived}),children:e.jsx(Am,{className:"h-3.5 w-3.5"})}),e.jsx($,{size:"icon",variant:"ghost",className:"h-8 w-8 text-rose-600",title:"Delete",onClick:()=>v(M),children:e.jsx(Pn,{className:"h-3.5 w-3.5"})})]})]}),e.jsxs("div",{className:"flex gap-2 mt-3 flex-wrap",children:[M.status!=="published"&&e.jsxs($,{size:"sm",variant:"outline",className:"rounded-full",onClick:()=>P(M),children:[e.jsx(Fr,{className:"h-3.5 w-3.5 mr-1.5"})," Mark published"]}),e.jsxs($,{size:"sm",variant:"outline",className:"rounded-full",onClick:()=>d.mutate({title:`Create: ${M.title}`,dueAt:M.planned_for?`${M.planned_for}T09:00:00`:new Date().toISOString(),notes:M.notes,touchType:"content"}),children:[e.jsx(Jh,{className:"h-3.5 w-3.5 mr-1.5"})," Add task"]}),e.jsx($,{size:"sm",variant:"ghost",className:"rounded-full",asChild:!0,children:e.jsxs(Wn,{to:"/attract/influence/content-studio",children:[e.jsx(dn,{className:"h-3.5 w-3.5 mr-1.5"})," Draft it"]})})]})]},M.id)})}),e.jsx(Os,{open:!!g,onOpenChange:M=>!M&&y(null),children:e.jsxs(Rs,{className:"max-w-xl max-h-[90vh] overflow-y-auto",children:[e.jsxs(Us,{children:[e.jsx(zs,{children:g!=null&&g.id?"Edit commitment":"New commitment"}),e.jsx(Sr,{children:"Pick something you can genuinely sustain."})]}),g&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx(se,{children:"Title *"}),e.jsx(be,{value:g.title??"",onChange:M=>y({...g,title:M.target.value}),placeholder:"e.g. October market update video"})]}),e.jsxs("div",{className:"grid sm:grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(se,{children:"Type"}),e.jsxs(vs,{value:g.content_type??"market_update",onValueChange:M=>y({...g,content_type:M}),children:[e.jsx(gs,{children:e.jsx(bs,{})}),e.jsx(ys,{children:S_t.map(M=>e.jsx(Ye,{value:M.value,children:M.label},M.value))})]})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Cadence"}),e.jsxs(vs,{value:g.cadence??"monthly",onValueChange:M=>y({...g,cadence:M}),children:[e.jsx(gs,{children:e.jsx(bs,{})}),e.jsx(ys,{children:EWn.map(M=>e.jsx(Ye,{value:M,className:"capitalize",children:M.replace("_"," ")},M))})]})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Planned for"}),e.jsx(be,{type:"date",value:g.planned_for??"",onChange:M=>y({...g,planned_for:M.target.value})})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Status"}),e.jsxs(vs,{value:g.status??"planned",onValueChange:M=>y({...g,status:M}),children:[e.jsx(gs,{children:e.jsx(bs,{})}),e.jsx(ys,{children:C_t.map(M=>e.jsx(Ye,{value:M,className:"capitalize",children:M},M))})]})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Channel"}),e.jsx(be,{value:g.channel??"",onChange:M=>y({...g,channel:M.target.value}),placeholder:"Instagram, email, YouTube"})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Audience"}),e.jsx(be,{value:g.audience??"",onChange:M=>y({...g,audience:M.target.value}),placeholder:"Agents, sphere, neighborhood"})]})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Notes"}),e.jsx(Is,{rows:3,value:g.notes??"",onChange:M=>y({...g,notes:M.target.value})})]}),e.jsxs("div",{className:"grid sm:grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(se,{children:"Published URL"}),e.jsx(be,{value:g.published_url??"",onChange:M=>y({...g,published_url:M.target.value}),placeholder:"https://"})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Results"}),e.jsx(be,{value:g.results_notes??"",onChange:M=>y({...g,results_notes:M.target.value}),placeholder:"Reach, replies, leads"})]})]})]}),e.jsxs(kr,{children:[e.jsx($,{variant:"ghost",onClick:()=>y(null),children:"Cancel"}),e.jsx($,{className:"bg-gradient-to-r from-violet-600 to-indigo-600",onClick:T,disabled:a.isPending||i.isPending,children:"Save"})]})]})}),e.jsx(Os,{open:!!b,onOpenChange:M=>!M&&v(null),children:e.jsxs(Rs,{className:"max-w-md",children:[e.jsxs(Us,{children:[e.jsx(zs,{children:"Delete this commitment?"}),e.jsx(Sr,{children:"This can't be undone."})]}),e.jsxs(kr,{children:[e.jsx($,{variant:"ghost",onClick:()=>v(null),children:"Cancel"}),e.jsx($,{variant:"destructive",onClick:()=>{c.mutate(b.id),v(null)},children:"Delete"})]})]})})]})}function E_t(s){if(!s)return null;const[t]=s.split("T");return t||null}const Zae={draft:{label:"Content",icon:dn,cls:"bg-violet-50 text-violet-700 border-violet-200"},presence:{label:"Market presence",icon:Cg,cls:"bg-blue-50 text-blue-700 border-blue-200"},speaking:{label:"Speaking",icon:Vj,cls:"bg-amber-50 text-amber-700 border-amber-200"}};function PWn(){const{drafts:s,isLoading:t,save:n}=qWt(),{commitments:r,isLoading:a}=WWt(),i=GWt(),l=HTe(),[o,c]=j.useState(()=>{const A=new Date;return new Date(A.getFullYear(),A.getMonth(),1)}),[d,u]=j.useState("all"),[h,m]=j.useState(null),p=j.useMemo(()=>(i.items??[]).filter(A=>!A.is_archived).map(A=>({id:A.id,kind:"speaking",title:A.title,date:E_t(A.starts_at),status:A.status,href:"/attract/influence/speaking"})),[i.items]),x=j.useMemo(()=>{const A=s.map(P=>({id:P.id,kind:"draft",title:P.topic||P.mode.replace(/_/g," "),date:E_t(P.planned_at??P.posted_at??null),status:P.status,href:"/attract/influence/content-studio"})),T=r.filter(P=>!P.is_archived).map(P=>({id:P.id,kind:"presence",title:P.title,date:P.planned_for,status:P.status,href:"/attract/produce/market-presence"}));return[...A,...T,...p].filter(P=>d==="all"||P.kind===d)},[s,r,p,d]),g=`${o.getFullYear()}-${String(o.getMonth()+1).padStart(2,"0")}`,y=x.filter(A=>{var T;return(T=A.date)==null?void 0:T.startsWith(g)}),b=x.filter(A=>!A.date),v=j.useMemo(()=>{const A=new Date(o.getFullYear(),o.getMonth(),1),T=new Date(A);return T.setDate(A.getDate()-A.getDay()),Array.from({length:42},(P,M)=>{const I=new Date(T);I.setDate(T.getDate()+M);const D=`${I.getFullYear()}-${String(I.getMonth()+1).padStart(2,"0")}-${String(I.getDate()).padStart(2,"0")}`;return{date:I,key:D,inMonth:I.getMonth()===o.getMonth(),items:x.filter(B=>B.date===D)}})},[o,x]),N=(()=>{const A=new Date;return`${A.getFullYear()}-${String(A.getMonth()+1).padStart(2,"0")}-${String(A.getDate()).padStart(2,"0")}`})(),C=t||a;return e.jsxs("div",{children:[e.jsxs(Wn,{to:"/attract/influence",className:"inline-flex items-center gap-1.5 text-[12px] text-slate-500 hover:text-violet-700 mb-3",children:[e.jsx(ka,{className:"h-3.5 w-3.5"})," Back to Influence"]}),e.jsx(nm,{eyebrow:"Produce + Influence → Tool",title:"Content Calendar",description:"One month view of everything you've committed to publish — Content Studio drafts, market presence commitments, and speaking dates.",actions:e.jsx($,{className:"rounded-full bg-gradient-to-r from-violet-600 to-indigo-600",asChild:!0,children:e.jsxs(Wn,{to:"/attract/influence/content-studio",children:[e.jsx(sn,{className:"h-4 w-4 mr-1.5"})," New Draft"]})})}),e.jsxs("div",{className:"flex items-center justify-between gap-2 flex-wrap mb-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx($,{size:"icon",variant:"outline",className:"rounded-full h-9 w-9",onClick:()=>c(new Date(o.getFullYear(),o.getMonth()-1,1)),children:e.jsx(Ic,{className:"h-4 w-4"})}),e.jsx("div",{className:"text-[16px] font-semibold text-slate-900 min-w-[170px] text-center",children:o.toLocaleString("en-US",{month:"long",year:"numeric"})}),e.jsx($,{size:"icon",variant:"outline",className:"rounded-full h-9 w-9",onClick:()=>c(new Date(o.getFullYear(),o.getMonth()+1,1)),children:e.jsx(Ja,{className:"h-4 w-4"})}),e.jsx($,{variant:"ghost",className:"rounded-full",onClick:()=>{const A=new Date;c(new Date(A.getFullYear(),A.getMonth(),1))},children:"Today"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs($e,{variant:"outline",className:"rounded-full",children:[y.length," scheduled this month"]}),e.jsxs(vs,{value:d,onValueChange:A=>u(A),children:[e.jsx(gs,{className:"w-[180px] rounded-full",children:e.jsx(bs,{})}),e.jsxs(ys,{children:[e.jsx(Ye,{value:"all",children:"All types"}),e.jsx(Ye,{value:"draft",children:"Content drafts"}),e.jsx(Ye,{value:"presence",children:"Market presence"}),e.jsx(Ye,{value:"speaking",children:"Speaking"})]})]})]})]}),C?e.jsx(on,{className:"h-[560px] rounded-2xl"}):e.jsxs(_e,{className:"rounded-2xl overflow-hidden",children:[e.jsx("div",{className:"grid grid-cols-7 bg-slate-50 border-b",children:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"].map(A=>e.jsx("div",{className:"px-2 py-2 text-[11px] uppercase tracking-wider text-slate-500 font-semibold text-center",children:A},A))}),e.jsx("div",{className:"grid grid-cols-7",children:v.map(A=>e.jsxs("div",{className:`min-h-[96px] border-b border-r p-1.5 ${A.inMonth?"":"bg-slate-50/60"}`,children:[e.jsx("div",{className:`text-[11.5px] font-medium mb-1 ${A.key===N?"text-violet-700":A.inMonth?"text-slate-700":"text-slate-400"}`,children:A.date.getDate()}),e.jsxs("div",{className:"space-y-1",children:[A.items.slice(0,3).map(T=>{const P=Zae[T.kind];return e.jsx(Wn,{to:T.href,className:`block truncate rounded-md border px-1.5 py-0.5 text-[11px] ${P.cls}`,title:T.title,children:T.title},`${T.kind}-${T.id}`)}),A.items.length>3&&e.jsxs("div",{className:"text-[10.5px] text-slate-500 px-1",children:["+",A.items.length-3," more"]})]})]},A.key))})]}),e.jsxs("div",{className:"grid gap-4 md:grid-cols-2 mt-5",children:[e.jsxs(_e,{className:"p-5 rounded-2xl",children:[e.jsxs("div",{className:"text-[15px] font-semibold text-slate-900 mb-1",children:["Unscheduled (",b.length,")"]}),e.jsx("p",{className:"text-[12.5px] text-slate-600 mb-3",children:"Give these a date so they show on the calendar."}),b.length===0&&e.jsx("div",{className:"text-[13px] text-slate-500",children:"Everything has a date. Nice."}),e.jsx("div",{className:"space-y-2",children:b.slice(0,8).map(A=>e.jsxs("div",{className:"flex items-center justify-between gap-2 rounded-xl bg-slate-50 px-3 py-2",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"text-[13px] font-medium text-slate-900 truncate capitalize",children:A.title}),e.jsxs("div",{className:"text-[11.5px] text-slate-500",children:[Zae[A.kind].label," · ",A.status]})]}),A.kind==="draft"?e.jsx($,{size:"sm",variant:"outline",className:"rounded-full flex-shrink-0",onClick:()=>m({id:A.id,title:A.title,date:N}),children:"Schedule"}):e.jsx($,{size:"sm",variant:"ghost",className:"rounded-full flex-shrink-0",asChild:!0,children:e.jsx(Wn,{to:A.href,children:"Open"})})]},`${A.kind}-${A.id}`))})]}),e.jsxs(_e,{className:"p-5 rounded-2xl",children:[e.jsx("div",{className:"text-[15px] font-semibold text-slate-900 mb-1",children:"This month at a glance"}),e.jsx("p",{className:"text-[12.5px] text-slate-600 mb-3",children:"Keep a steady rhythm across all three surfaces."}),e.jsx("div",{className:"space-y-2",children:Object.keys(Zae).map(A=>{const T=Zae[A],P=T.icon,M=y.filter(I=>I.kind===A).length;return e.jsxs("div",{className:"flex items-center gap-3 rounded-xl bg-slate-50 px-3 py-2",children:[e.jsx("div",{className:`h-8 w-8 rounded-lg grid place-items-center border ${T.cls}`,children:e.jsx(P,{className:"h-4 w-4"})}),e.jsx("div",{className:"text-[13.5px] font-medium text-slate-900 flex-1",children:T.label}),e.jsx("div",{className:"text-[16px] font-semibold tabular-nums text-slate-900",children:M})]},A)})}),e.jsxs($,{variant:"outline",className:"rounded-full mt-4 w-full",onClick:()=>l.mutate({title:`Plan content for ${o.toLocaleString("en-US",{month:"long"})}`,dueAt:new Date().toISOString(),touchType:"content"}),children:[e.jsx(Jh,{className:"h-3.5 w-3.5 mr-1.5"})," Add planning block to Today's Plan"]}),e.jsx($,{variant:"ghost",className:"rounded-full mt-2 w-full",asChild:!0,children:e.jsxs(Wn,{to:"/attract/produce/market-presence",children:[e.jsx(Nl,{className:"h-3.5 w-3.5 mr-1.5"})," Manage market presence cadence"]})})]})]}),e.jsx(Os,{open:!!h,onOpenChange:A=>!A&&m(null),children:e.jsxs(Rs,{className:"max-w-md",children:[e.jsxs(Us,{children:[e.jsx(zs,{children:"Schedule draft"}),e.jsx(Sr,{className:"capitalize",children:h==null?void 0:h.title})]}),h&&e.jsxs("div",{children:[e.jsx(se,{children:"Planned date"}),e.jsx(be,{type:"date",value:h.date,onChange:A=>m({...h,date:A.target.value})})]}),e.jsxs(kr,{children:[e.jsx($,{variant:"ghost",onClick:()=>m(null),children:"Cancel"}),e.jsx($,{className:"bg-gradient-to-r from-violet-600 to-indigo-600",onClick:async()=>{h&&(await n.mutateAsync({id:h.id,planned_at:`${h.date}T09:00:00`}),m(null))},children:"Save"})]})]})})]})}const T_t=[{value:"birthday",label:"Birthday"},{value:"work_anniversary",label:"Work Anniversary"},{value:"license_anniversary",label:"License Anniversary"},{value:"production_milestone",label:"Production Milestone"},{value:"team_milestone",label:"Team Milestone"},{value:"family_milestone",label:"Family Milestone"},{value:"custom",label:"Custom Date"}];function IWn(s){const[t,n,r]=s.split(/[-/T]/).map(Number);return{y:t,m:n,d:r}}function XUe(s,t=new Date){const{y:n,m:r,d:a}=IWn(s.milestone_on);if(!s.recurs_annually)return new Date(n,r-1,a);const i=new Date(t.getFullYear(),r-1,a),l=new Date(t.getFullYear(),t.getMonth(),t.getDate());return i{const l=[];return r.forEach(o=>{const c=[o.preferred_name||o.first_name,o.last_name].filter(Boolean).join(" ");[["birthday",o.birthday_on,`${c} — Birthday`],["work_anniversary",o.work_anniversary_on,`${c} — Work Anniversary`],["license_anniversary",o.license_anniversary_on,`${c} — License Anniversary`]].forEach(([d,u,h])=>{u&&l.push({id:`agent:${o.id}:${d}`,user_id:o.user_id,title:h,milestone_type:d,milestone_on:String(u).slice(0,10),recurs_annually:!0,linked_agent_ids:[o.id],notes:null,last_celebrated_at:null,is_archived:!1,created_at:o.created_at,updated_at:o.updated_at})})}),l},[r]),i=j.useMemo(()=>{const l=new Set(s.items.filter(c=>!c.is_archived).map(c=>{var d;return`${c.milestone_type}|${c.milestone_on.slice(5,10)}|${((d=c.linked_agent_ids)==null?void 0:d[0])??""}`}));return[...s.items.filter(c=>!c.is_archived),...a.filter(c=>!l.has(`${c.milestone_type}|${c.milestone_on.slice(5,10)}|${c.linked_agent_ids[0]}`))].map(c=>({item:c,next:XUe(c)})).map(c=>({...c,days:KWt(c.next)})).filter(c=>c.days>=0).sort((c,d)=>c.days-d.days)},[s.items,a]);return{...s,milestones:s.items,derived:a,upcoming:i,quickTask:t,logActivity:n}}const M_t={milestone_type:"birthday",recurs_annually:!0,linked_agent_ids:[]};function RWn(s){return s.toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"})}function OWn(){var D;const{milestones:s,upcoming:t,isLoading:n,error:r,refetch:a,create:i,update:l,duplicate:o,archive:c,remove:d,quickTask:u,logActivity:h}=DWn(),m=M0(),p=(m==null?void 0:m.agents)??(m==null?void 0:m.items)??[],[x,g]=j.useState(!1),[y,b]=j.useState("90"),[v,N]=j.useState(null),[C,A]=j.useState(null),T=j.useMemo(()=>{if(x)return s.filter(q=>q.is_archived).map(q=>({item:q,next:XUe(q),days:KWt(XUe(q))}));const B=y==="all"?1/0:Number(y);return t.filter(q=>q.days<=B)},[s,t,x,y]),P=B=>{const q=p.find(W=>W.id===B);return q?[q.preferred_name||q.first_name,q.last_name].filter(Boolean).join(" "):"Agent"},M=async()=>{var q;if(!((q=v==null?void 0:v.title)!=null&&q.trim())||!(v!=null&&v.milestone_on)){ae.error("Title and date are required");return}const B={title:v.title.trim(),milestone_type:v.milestone_type??"birthday",milestone_on:v.milestone_on,recurs_annually:v.recurs_annually??!0,linked_agent_ids:v.linked_agent_ids??[],notes:v.notes||null};v.id?await l.mutateAsync({id:v.id,...B}):await i.mutateAsync(B),N(null)},I=async B=>{var q;await l.mutateAsync({id:B.id,last_celebrated_at:new Date().toISOString()}),await h.mutateAsync({title:`Celebrated: ${B.title}`,pillar:"connect",activityType:"milestone_celebrated",agentId:((q=B.linked_agent_ids)==null?void 0:q[0])??null})};return e.jsxs("div",{children:[e.jsxs(Wn,{to:"/attract/connect",className:"inline-flex items-center gap-1.5 text-[12px] text-slate-500 hover:text-violet-700 mb-3",children:[e.jsx(ka,{className:"h-3.5 w-3.5"})," Back to Connect"]}),e.jsx(nm,{eyebrow:"Connect → Tool",title:"Milestones & Celebrations",description:"Remember the dates that matter to the agents in your pipeline. Recurring milestones roll forward every year so you never miss the reason to reach out.",actions:e.jsxs(e.Fragment,{children:[e.jsx($,{variant:"outline",className:"rounded-full",onClick:()=>g(B=>!B),children:x?"Show upcoming":"Show archived"}),e.jsxs($,{className:"rounded-full bg-gradient-to-r from-violet-600 to-indigo-600",onClick:()=>N({...M_t}),children:[e.jsx(sn,{className:"h-4 w-4 mr-1.5"})," Add Milestone"]})]})}),e.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-3 gap-3 mb-4",children:[e.jsxs(_e,{className:"p-4 rounded-2xl",children:[e.jsx("div",{className:"text-[22px] font-semibold tabular-nums text-slate-900",children:t.filter(B=>B.days<=7).length}),e.jsx("div",{className:"text-[12px] text-slate-500",children:"Next 7 days"})]}),e.jsxs(_e,{className:"p-4 rounded-2xl",children:[e.jsx("div",{className:"text-[22px] font-semibold tabular-nums text-violet-600",children:t.filter(B=>B.days<=30).length}),e.jsx("div",{className:"text-[12px] text-slate-500",children:"Next 30 days"})]}),e.jsxs(_e,{className:"p-4 rounded-2xl",children:[e.jsx("div",{className:"text-[22px] font-semibold tabular-nums text-slate-900",children:s.filter(B=>!B.is_archived).length}),e.jsx("div",{className:"text-[12px] text-slate-500",children:"Tracked total"})]})]}),!x&&e.jsx("div",{className:"flex gap-2 flex-wrap mb-4",children:e.jsxs(vs,{value:y,onValueChange:B=>b(B),children:[e.jsx(gs,{className:"w-[190px] rounded-full",children:e.jsx(bs,{})}),e.jsxs(ys,{children:[e.jsx(Ye,{value:"30",children:"Next 30 days"}),e.jsx(Ye,{value:"90",children:"Next 90 days"}),e.jsx(Ye,{value:"all",children:"All upcoming"})]})]})}),n&&e.jsx("div",{className:"space-y-2",children:[0,1,2].map(B=>e.jsx(on,{className:"h-20 rounded-2xl"},B))}),!n&&r&&e.jsxs(_e,{className:"p-8 rounded-2xl text-center",children:[e.jsx(xo,{className:"h-6 w-6 text-rose-500 mx-auto mb-2"}),e.jsx("div",{className:"font-semibold text-slate-900",children:"Couldn't load milestones"}),e.jsx("div",{className:"text-[13px] text-slate-600 mt-1",children:r.message}),e.jsxs($,{variant:"outline",className:"rounded-full mt-4",onClick:()=>a(),children:[e.jsx(Ih,{className:"h-3.5 w-3.5 mr-1.5"})," Retry"]})]}),!n&&!r&&T.length===0&&e.jsxs(_e,{className:"p-10 rounded-2xl text-center border-dashed",children:[e.jsx("div",{className:"h-12 w-12 rounded-2xl bg-violet-50 text-violet-600 grid place-items-center mx-auto mb-3",children:e.jsx(np,{className:"h-6 w-6"})}),e.jsx("div",{className:"text-[16px] font-semibold text-slate-900",children:x?"Nothing archived":"No milestones in this window"}),e.jsx("p",{className:"text-[13.5px] text-slate-600 mt-1.5 max-w-md mx-auto",children:"Add birthdays, license anniversaries, and production milestones for the agents you're building relationships with."}),!x&&e.jsxs($,{className:"rounded-full mt-4 bg-gradient-to-r from-violet-600 to-indigo-600",onClick:()=>N({...M_t}),children:[e.jsx(sn,{className:"h-4 w-4 mr-1.5"})," Add a milestone"]})]}),e.jsx("div",{className:"space-y-2",children:T.map(({item:B,next:q,days:W})=>{var K,Q;const V=String(B.id).startsWith("agent:");return e.jsxs(_e,{className:"p-4 rounded-2xl",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3 flex-wrap",children:[e.jsxs("div",{className:"flex items-start gap-3 min-w-0",children:[e.jsx("div",{className:"h-11 w-11 rounded-xl bg-violet-50 text-violet-700 grid place-items-center flex-shrink-0",children:e.jsxs("div",{className:"text-center leading-none",children:[e.jsx("div",{className:"text-[9px] uppercase tracking-wider",children:q.toLocaleString("en-US",{month:"short"})}),e.jsx("div",{className:"text-[15px] font-semibold",children:q.getDate()})]})}),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 text-slate-900",children:B.title}),e.jsx($e,{variant:"outline",className:"rounded-full",children:((K=T_t.find(J=>J.value===B.milestone_type))==null?void 0:K.label)??B.milestone_type}),V&&e.jsx($e,{variant:"outline",className:"rounded-full bg-violet-50 text-violet-700 border-violet-200",children:"From contact record"}),!x&&e.jsx($e,{variant:"outline",className:`rounded-full ${W<=7?"bg-amber-50 text-amber-700 border-amber-200":""}`,children:W===0?"Today":W===1?"Tomorrow":`in ${W} days`}),B.recurs_annually&&e.jsx($e,{variant:"outline",className:"rounded-full",children:"Annual"})]}),e.jsxs("div",{className:"text-[12.5px] text-slate-500 mt-1",children:[RWn(q),(Q=B.linked_agent_ids)!=null&&Q.length?` · ${B.linked_agent_ids.map(P).join(", ")}`:"",B.last_celebrated_at?` · last celebrated ${new Date(B.last_celebrated_at).toLocaleDateString("en-US")}`:""]}),B.notes&&e.jsx("div",{className:"text-[12.5px] text-slate-600 mt-1 line-clamp-2",children:B.notes})]})]}),e.jsx("div",{className:"flex gap-1",children:V?e.jsx($,{size:"sm",variant:"ghost",className:"rounded-full text-[12px]",asChild:!0,children:e.jsx(Wn,{to:`/attract/agents/${B.linked_agent_ids[0]}`,children:"Open contact"})}):e.jsxs(e.Fragment,{children:[e.jsx($,{size:"icon",variant:"ghost",className:"h-8 w-8",title:"Edit",onClick:()=>N(B),children:e.jsx(Ya,{className:"h-3.5 w-3.5"})}),e.jsx($,{size:"icon",variant:"ghost",className:"h-8 w-8",title:"Duplicate",onClick:()=>o.mutate(B),children:e.jsx(Ca,{className:"h-3.5 w-3.5"})}),e.jsx($,{size:"icon",variant:"ghost",className:"h-8 w-8",title:B.is_archived?"Restore":"Archive",onClick:()=>c.mutate({id:B.id,archived:!B.is_archived}),children:e.jsx(Am,{className:"h-3.5 w-3.5"})}),e.jsx($,{size:"icon",variant:"ghost",className:"h-8 w-8 text-rose-600",title:"Delete",onClick:()=>A(B),children:e.jsx(Pn,{className:"h-3.5 w-3.5"})})]})})]}),e.jsxs("div",{className:"flex gap-2 mt-3 flex-wrap",children:[e.jsxs($,{size:"sm",variant:"outline",className:"rounded-full",onClick:()=>{var J;return u.mutate({title:`Reach out: ${B.title}`,dueAt:q.toISOString(),notes:B.notes,touchType:"celebration",agentId:((J=B.linked_agent_ids)==null?void 0:J[0])??null})},children:[e.jsx(Jh,{className:"h-3.5 w-3.5 mr-1.5"})," Add reach-out task"]}),!V&&e.jsxs($,{size:"sm",variant:"outline",className:"rounded-full",onClick:()=>I(B),children:[e.jsx(Nf,{className:"h-3.5 w-3.5 mr-1.5"})," Mark celebrated"]})]})]},B.id)})}),e.jsx(Os,{open:!!v,onOpenChange:B=>!B&&N(null),children:e.jsxs(Rs,{className:"max-w-xl max-h-[90vh] overflow-y-auto",children:[e.jsxs(Us,{children:[e.jsx(zs,{children:v!=null&&v.id?"Edit milestone":"Add milestone"}),e.jsx(Sr,{children:"Annual milestones roll forward automatically each year."})]}),v&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx(se,{children:"Title *"}),e.jsx(be,{value:v.title??"",onChange:B=>N({...v,title:B.target.value}),placeholder:"e.g. Sarah's birthday"})]}),e.jsxs("div",{className:"grid sm:grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(se,{children:"Type"}),e.jsxs(vs,{value:v.milestone_type??"birthday",onValueChange:B=>N({...v,milestone_type:B}),children:[e.jsx(gs,{children:e.jsx(bs,{})}),e.jsx(ys,{children:T_t.map(B=>e.jsx(Ye,{value:B.value,children:B.label},B.value))})]})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Date *"}),e.jsx(be,{type:"date",value:v.milestone_on??"",onChange:B=>N({...v,milestone_on:B.target.value})})]})]}),e.jsxs("div",{className:"flex items-center justify-between rounded-xl border border-slate-200 px-4 py-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[13.5px] font-medium text-slate-900",children:"Repeats every year"}),e.jsx("div",{className:"text-[12px] text-slate-600",children:"Turn off for one-time milestones."})]}),e.jsx(Tn,{checked:v.recurs_annually??!0,onCheckedChange:B=>N({...v,recurs_annually:B})})]}),p.length>0&&e.jsxs("div",{children:[e.jsx(se,{children:"Link to agent"}),e.jsxs(vs,{value:((D=v.linked_agent_ids)==null?void 0:D[0])??"none",onValueChange:B=>N({...v,linked_agent_ids:B==="none"?[]:[B]}),children:[e.jsx(gs,{children:e.jsx(bs,{placeholder:"Optional"})}),e.jsxs(ys,{children:[e.jsx(Ye,{value:"none",children:"No agent"}),p.map(B=>e.jsx(Ye,{value:B.id,children:P(B.id)},B.id))]})]})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Notes"}),e.jsx(Is,{rows:3,value:v.notes??"",onChange:B=>N({...v,notes:B.target.value}),placeholder:"Gift ideas, personal details, how you'll reach out"})]})]}),e.jsxs(kr,{children:[e.jsx($,{variant:"ghost",onClick:()=>N(null),children:"Cancel"}),e.jsx($,{className:"bg-gradient-to-r from-violet-600 to-indigo-600",onClick:M,disabled:i.isPending||l.isPending,children:"Save"})]})]})}),e.jsx(Os,{open:!!C,onOpenChange:B=>!B&&A(null),children:e.jsxs(Rs,{className:"max-w-md",children:[e.jsxs(Us,{children:[e.jsx(zs,{children:"Delete this milestone?"}),e.jsx(Sr,{children:"This can't be undone."})]}),e.jsxs(kr,{children:[e.jsx($,{variant:"ghost",onClick:()=>A(null),children:"Cancel"}),e.jsx($,{variant:"destructive",onClick:()=>{d.mutate(C.id),A(null)},children:"Delete"})]})]})})]})}function FWn(){var c;const{shareToken:s}=Vi(),[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 U.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"),U.rpc("public_log_attract_kit_event",{_token:s,_event_type:"page_view",_item_id:null,_metadata:{}})})()},[s]);const o=(d,u,h)=>{s&&U.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(_e,{className:"max-w-md w-full p-8 bg-white/5 border-white/10 text-slate-100 rounded-2xl text-center",children:[e.jsx(xo,{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(dn,{className:"h-3.5 w-3.5"})," A LevelUp Attract kit"]}),e.jsx(VWt,{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(_e,{className:"mt-6 p-6 bg-white/5 border-white/10 text-slate-100 rounded-2xl",children:i?e.jsx(zWn,{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($,{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 zWn({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 ae.error("Please add a short message");u(!0);const{data:m,error:p}=await U.rpc("public_submit_attract_kit_question",{_token:s,_name:r,_email:i,_message:o});if(u(!1),p||!(m!=null&&m.ok))return ae.error("Could not send — please try again");ae.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(be,{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(be,{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(Is,{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($,{variant:"outline",onClick:()=>{n("meeting_requested"),ae.success("Request sent")},children:"Request a conversation"}),e.jsx($,{onClick:h,disabled:d,className:"bg-gradient-to-r from-violet-600 to-indigo-600 ml-auto",children:d?"Sending…":"Send question"})]})]})}function BWn(){const{slug:s}=Vi(),[t]=oc(),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:g,error:y}=await U.rpc("public_get_attract_event",{_slug:s});if(y||!g||g.error){a((g==null?void 0:g.error)||"not_found");return}l(g),a("ok"),n&&U.rpc("public_track_attract_invitation_view",{_token:n})})()},[s,n]);const p=async()=>{u(!0);const{data:g,error:y}=await U.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 b=g;if(b!=null&&b.error){alert(b.error==="invalid_email"?"That email looks off.":b.error==="full"?"This event is full.":"Could not register.");return}m(b)},x=()=>{if(!i)return;const g=new Blob([mWt(i)],{type:"text/calendar"}),y=document.createElement("a");y.href=URL.createObjectURL(g),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 g=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:g}),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(_e,{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(ia,{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:Hs(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(Xr,{className:"h-5 w-5 text-violet-600 mt-0.5"}):e.jsx(ai,{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(qn,{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((g,y)=>e.jsxs("li",{className:"flex gap-2 text-[14px] text-slate-800",children:[e.jsx(oa,{className:"h-4 w-4 text-emerald-600 shrink-0 mt-0.5"})," ",g]},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((g,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:g.time}),e.jsx("span",{className:"text-slate-800",children:g.item})]},y))})]})]}),h?e.jsxs(_e,{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(oa,{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($,{variant:"outline",className:"rounded-full mt-5",onClick:x,children:[e.jsx(di,{className:"h-4 w-4 mr-2"})," Add to calendar"]})]}):e.jsxs(_e,{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(dn,{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(se,{children:"Full name"}),e.jsx(be,{value:o.name,onChange:g=>c({...o,name:g.target.value})})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(se,{children:"Email"}),e.jsx(be,{type:"email",value:o.email,onChange:g=>c({...o,email:g.target.value})})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Phone (optional)"}),e.jsx(be,{value:o.phone,onChange:g=>c({...o,phone:g.target.value})})]})]}),(i.registration_questions||[]).map(g=>e.jsxs("div",{children:[e.jsx(se,{children:g.label}),g.type==="long"?e.jsx(Is,{rows:3,value:o.answers[g.key]||"",onChange:y=>c({...o,answers:{...o.answers,[g.key]:y.target.value}})}):e.jsx(be,{value:o.answers[g.key]||"",onChange:y=>c({...o,answers:{...o.answers,[g.key]:y.target.value}})})]},g.key))]}),e.jsx($,{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 $Wn(){const{token:s}=Vi(),[t]=oc(),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 U.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(_e,{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(oa,{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 Xae=s=>s.toLocaleString("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0});function UWn(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 YWt({cfg:s,onSubmitLead:t,onTrack:n,preview:r}){var P,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,x]=j.useState({first_name:"",last_name:"",email:"",phone:"",brokerage:"",message:""}),[g,y]=j.useState({first_name:"",email:""}),b=s.calculator||{},[v,N]=j.useState(15e4),C=j.useMemo(()=>{const D=Number(b.cap??16e3),B=Number(b.split??80)/100,q=Number(b.transaction_fee??250),W=Number(b.current_split??70)/100,V=Number(b.current_monthly_fees??150),K=Math.min(v*(1-B),D),Q=v-K-q*12,J=v*W-V*12;return{here:Math.max(Q,0),current:Math.max(J,0),diff:Math.max(Q-J,0),capped:K>=D}},[v,b]),A=async(D,B,q)=>{if(r||!t){u(D);return}m(!0);try{await t({first_name:B.first_name||"",last_name:B.last_name||"",email:B.email||"",phone:B.phone||"",brokerage:B.brokerage||"",message:B.message||"",source:D,metadata:q}),u(D)}catch(W){ja({title:"We couldn't send that",description:(W==null?void 0:W.message)||"Please try again in a moment.",variant:"destructive"})}finally{m(!1)}},T=D=>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:[D||s.cta_label||"Book a confidential 15-min call",e.jsx(ni,{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(ia,{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((D,B)=>e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"text-2xl font-bold md:text-3xl",style:{color:i},children:D.value}),e.jsx("div",{className:"mt-1 text-xs uppercase tracking-wider text-white/50",children:D.label})]},B))})}),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:UWn(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(Sh,{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((D,B)=>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(oa,{className:"h-4 w-4"})}),e.jsx("h3",{className:"mb-2 text-lg font-semibold",children:D.title}),e.jsx("p",{className:"text-sm leading-relaxed text-white/65",children:D.body}),D.proof&&e.jsx("p",{className:"mt-3 text-xs uppercase tracking-wider text-white/40",children:D.proof})]},B))})]})}),l.calculator!==!1&&b.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:b.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(se,{className:"text-white/70",children:"Your annual GCI"}),e.jsx("span",{className:"text-2xl font-bold",style:{color:i},children:Xae(v)})]}),e.jsx("input",{type:"range",min:25e3,max:1e6,step:5e3,value:v,onChange:D=>N(Number(D.target.value)),onMouseUp:()=>n==null?void 0:n("calculator_run","calculator",{gci:v}),onTouchEnd:()=>n==null?void 0:n("calculator_run","calculator",{gci:v}),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:Xae(C.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:Xae(C.here)}),C.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:["+",Xae(C.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((D,B)=>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:B+1}),e.jsxs("div",{children:[e.jsx("h3",{className:"mb-1.5 font-semibold",children:D.title}),e.jsx("p",{className:"text-sm leading-relaxed text-white/65",children:D.body})]})]},B))})]})}),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((D,B)=>e.jsxs("div",{className:"rounded-2xl border border-white/10 bg-white/[0.03] p-6",children:[e.jsx(RN,{className:"mb-4 h-6 w-6",style:{color:i}}),e.jsxs("p",{className:"text-sm leading-relaxed text-white/75",children:['"',D.quote,'"']}),e.jsxs("div",{className:"mt-5 flex items-center gap-3",children:[D.photo_url?e.jsx("img",{src:D.photo_url,alt:D.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(Qa,{className:"h-4 w-4 text-white/50"})}),e.jsxs("div",{children:[e.jsx("div",{className:"text-sm font-medium",children:D.name}),D.role&&e.jsx("div",{className:"text-xs text-white/45",children:D.role})]})]})]},B))})]})}),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(JO,{type:"single",collapsible:!0,className:"w-full",children:(s.faqs||[]).map((D,B)=>e.jsxs(D6,{value:`faq-${B}`,className:"border-white/10",children:[e.jsx(R6,{className:"text-left text-base font-medium text-white hover:no-underline",children:D.q}),e.jsx(O6,{className:"text-sm leading-relaxed text-white/65",children:D.a})]},B))})]})}),l.lead_magnet!==!1&&((P=s.lead_magnet)==null?void 0:P.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(di,{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:D=>{D.preventDefault(),A("lead_magnet",{first_name:g.first_name,email:g.email,message:`Requested: ${s.lead_magnet.title}`})},children:[e.jsx(be,{required:!0,placeholder:"First name",value:g.first_name,onChange:D=>y(B=>({...B,first_name:D.target.value})),className:"h-12 border-white/15 bg-white/5 text-white placeholder:text-white/35"}),e.jsx(be,{required:!0,type:"email",placeholder:"Email",value:g.email,onChange:D=>y(B=>({...B,email:D.target.value})),className:"h-12 border-white/15 bg-white/5 text-white placeholder:text-white/35"}),e.jsx($,{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(oa,{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(ia,{className:"h-4 w-4"})," Pick a time"]})]}):e.jsxs("form",{onSubmit:D=>{D.preventDefault(),A("attraction_page",p,{gci:v})},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(se,{className:"text-sm text-white/70",children:"First name *"}),e.jsx(be,{required:!0,value:p.first_name,onChange:D=>x(B=>({...B,first_name:D.target.value})),className:"h-11 border-white/15 bg-white/5 text-white"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{className:"text-sm text-white/70",children:"Last name"}),e.jsx(be,{value:p.last_name,onChange:D=>x(B=>({...B,last_name:D.target.value})),className:"h-11 border-white/15 bg-white/5 text-white"})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{className:"text-sm text-white/70",children:"Email *"}),e.jsx(be,{required:!0,type:"email",value:p.email,onChange:D=>x(B=>({...B,email:D.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(se,{className:"text-sm text-white/70",children:"Phone"}),e.jsx(be,{value:p.phone,onChange:D=>x(B=>({...B,phone:D.target.value})),className:"h-11 border-white/15 bg-white/5 text-white"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{className:"text-sm text-white/70",children:"Current brokerage"}),e.jsx(be,{value:p.brokerage,onChange:D=>x(B=>({...B,brokerage:D.target.value})),className:"h-11 border-white/15 bg-white/5 text-white"})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{className:"text-sm text-white/70",children:"What would you want to know?"}),e.jsx(Is,{rows:3,value:p.message,onChange:D=>x(B=>({...B,message:D.target.value})),className:"resize-none border-white/15 bg-white/5 text-white"})]}),e.jsx($,{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(kf,{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(ya,{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(ni,{className:"h-4 w-4"})]})})]})}const Qae=U;function qWn(){const{slug:s}=Vi(),[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 Qae.rpc("public_get_attract_landing_page",{_slug:s});if(!o){if(d||!c||c.error){a("missing");return}n(c),a("ready"),Qae.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&&Qae.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 Qae.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(Ul,{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(YWt,{cfg:t,onSubmitLead:l,onTrack:i})]})}const L_t={media_mode:"photo",show_property_snapshot:!0,show_discover:!0,show_testimonial:!0};function ZWt(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 CB=[{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."}],XWt=[{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"}],VWn=["New Lead","Attempting Contact","Conversation Started","Nurturing","Appointment Requested","Appointment Scheduled","Listing Presentation","Listing Signed","Long Term Follow Up","Lost"],HWn=[{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"}],GWn=["Not enough showings","No offers","Marketing felt thin","Communication from my agent","Priced too high","Timing / market conditions","Something else"];function WWn(s){return s.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,48)}function KWn(s){const t=WWn(s)||"property",n=Math.random().toString(36).slice(2,7);return`${t}-${n}`}function g6(s){return s==null?"—":`$${Number(s).toLocaleString("en-US",{maximumFractionDigits:0})}`}const P_t="https://dashboard.relevelup.com";function QUe(){if(typeof window>"u")return P_t;const s=window.location.hostname;return s==="localhost"||s==="127.0.0.1"||s==="dashboard.relevelup.com"?window.location.origin:P_t}function QWt(s){return`${QUe()}/revival/${s}`}const I_t=[Vr,ml,y0,Mu,uR,dn];function D_t(){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 NRe(s){const{data:t,error:n}=await U.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 YWn(){var I,D;const{slug:s=""}=Vi(),[t]=oc(),[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=(B,q)=>m(W=>({...W,[B]:q}));j.useEffect(()=>{let B=!0;return(async()=>{try{const q=await NRe({action:"get",slug:s});if(!B)return;r(q),await NRe({action:"track",slug:s,event_type:t.get("src")==="qr"?"qr_scan":"page_view",session_id:D_t(),metadata:{referrer:document.referrer||null}})}catch{B&&r(null)}finally{B&&i(!1)}})(),()=>{B=!1}},[s,t]);const g=((n==null?void 0:n.campaign.content)??{}).landing,y=(n==null?void 0:n.campaign.landing_config)??{},b=(n==null?void 0:n.property)??((I=n==null?void 0:n.campaign)==null?void 0:I.property),v=n==null?void 0:n.agent,N=y.media_mode??"photo",C=ZWt(y.video_url),A=y.media_image_url||(b==null?void 0:b.photo_url)||null;j.useEffect(()=>{b!=null&&b.property_address&&(document.title=`Your Free Property Review — ${b.property_address}`)},[b==null?void 0:b.property_address]);const T=j.useMemo(()=>(g==null?void 0:g.discover)??[],[g]),P=async B=>{if(B.preventDefault(),!(!h.first_name.trim()||!h.email.trim()&&!h.phone.trim())){o(!0);try{await NRe({action:"submit",slug:s,session_id:D_t(),...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(Ht,{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(sa,{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:[b!=null&&b.photo_url?e.jsx("img",{src:b.photo_url,alt:b.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(jr.div,{initial:{opacity:0,y:18},animate:{opacity:1,y:0},transition:{duration:.6},children:[e.jsx("div",{className:"revival-eyebrow text-accent",children:(g==null?void 0:g.eyebrow)??"A complimentary review"}),e.jsx("h1",{className:"revival-serif text-4xl sm:text-[54px] leading-[1.08] mt-3",children:(g==null?void 0:g.headline)??"Your Free Real Estate Relaunch Review"}),e.jsx("p",{className:"text-white/75 text-lg mt-4 max-w-2xl mx-auto",children:(g==null?void 0:g.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(sa,{className:"h-4 w-4 text-accent"})," ",b==null?void 0:b.property_address]}),e.jsx("div",{className:"mt-8",children:e.jsx($,{size:"lg",className:"bg-accent text-accent-foreground hover:bg-accent/90",onClick:()=>{var B;return(B=u.current)==null?void 0:B.scrollIntoView({behavior:"smooth"})},children:(g==null?void 0:g.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(jr.div,{initial:{opacity:0,scale:.97},animate:{opacity:1,scale:1},className:"revival-tile p-10 text-center",children:[e.jsx(Fr,{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:[(v==null?void 0:v.name)??"Your agent"," has been notified and will personally prepare your Property Revival Plan. Watch your inbox — you’ll hear back shortly."]}),e.jsx($,{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 ",(v==null?void 0:v.name)??"your agent"]}),e.jsx("p",{className:"mt-3 text-lg leading-relaxed",children:g==null?void 0:g.intro}),v?e.jsxs("div",{className:"mt-6 flex items-center gap-4",children:[v.avatar_url?e.jsx("img",{src:v.avatar_url,alt:v.name??"",className:"h-14 w-14 rounded-full object-cover"}):null,e.jsxs("div",{children:[e.jsx("div",{className:"font-semibold",children:v.name}),e.jsxs("div",{className:"text-sm text-muted-foreground",children:[v.title??"Real Estate Specialist",v.brokerage_name?` · ${v.brokerage_name}`:""]})]})]}):null]}),N==="video"&&C?e.jsxs("div",{className:"space-y-2",children:[e.jsx("div",{className:"revival-tile aspect-video overflow-hidden",children:C.kind==="file"?e.jsx("video",{src:C.src,controls:!0,playsInline:!0,className:"h-full w-full object-cover"}):e.jsx("iframe",{src:C.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:(b==null?void 0:b.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(Sh,{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 ",(v==null?void 0:v.name)??"your agent"]})]})}):null]}),b&&y.show_property_snapshot!==!1?e.jsxs("section",{className:"revival-tile overflow-hidden grid md:grid-cols-[1.1fr_1fr]",children:[b.photo_url?e.jsx("img",{src:b.photo_url,alt:b.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:b.property_address}),e.jsx("p",{className:"text-muted-foreground",children:[b.city,b.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:g6(b.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:g6(b.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:b.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((B,q)=>{const W=I_t[q%I_t.length];return e.jsxs(jr.div,{initial:{opacity:0,y:18},whileInView:{opacity:1,y:0},viewport:{once:!0},transition:{delay:q*.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(W,{className:"h-5 w-5 text-accent-foreground"})}),e.jsx("div",{className:"font-semibold mt-3",children:B.title}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1 leading-relaxed",children:B.body})]},q)})})]}):null,(D=g==null?void 0:g.testimonial)!=null&&D.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:["“",g.testimonial.quote,"”"]}),e.jsx("p",{className:"text-accent text-sm mt-4 uppercase tracking-[0.2em]",children:g.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:P,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:B=>p("honeypot",B.target.value)}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:"First name *"}),e.jsx(be,{required:!0,value:h.first_name,onChange:B=>p("first_name",B.target.value)})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:"Last name"}),e.jsx(be,{value:h.last_name,onChange:B=>p("last_name",B.target.value)})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:"Email"}),e.jsx(be,{type:"email",value:h.email,onChange:B=>p("email",B.target.value)})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:"Phone"}),e.jsx(be,{value:h.phone,onChange:B=>p("phone",B.target.value)})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:"Are you still interested in selling?"}),e.jsxs(vs,{value:h.still_selling,onValueChange:B=>p("still_selling",B),children:[e.jsx(gs,{children:e.jsx(bs,{placeholder:"Select one"})}),e.jsxs(ys,{children:[e.jsx(Ye,{value:"yes",children:"Yes"}),e.jsx(Ye,{value:"maybe",children:"Maybe — depends on the plan"}),e.jsx(Ye,{value:"no",children:"Not right now"})]})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:"Your timeline"}),e.jsxs(vs,{value:h.timeline,onValueChange:B=>p("timeline",B),children:[e.jsx(gs,{children:e.jsx(bs,{placeholder:"Select one"})}),e.jsx(ys,{children:HWn.map(B=>e.jsx(Ye,{value:B.value,children:B.label},B.value))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:"Biggest frustration last time"}),e.jsxs(vs,{value:h.frustration,onValueChange:B=>p("frustration",B),children:[e.jsx(gs,{children:e.jsx(bs,{placeholder:"Select one"})}),e.jsx(ys,{children:GWn.map(B=>e.jsx(Ye,{value:B,children:B},B))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:"Preferred contact method"}),e.jsxs(vs,{value:h.preferred_contact,onValueChange:B=>p("preferred_contact",B),children:[e.jsx(gs,{children:e.jsx(bs,{})}),e.jsxs(ys,{children:[e.jsx(Ye,{value:"email",children:"Email"}),e.jsx(Ye,{value:"phone",children:"Phone call"}),e.jsx(Ye,{value:"text",children:"Text message"})]})]})]}),e.jsxs("div",{className:"sm:col-span-2 space-y-1.5",children:[e.jsx(se,{children:"Anything you'd like me to know?"}),e.jsx(Is,{rows:3,value:h.comments,onChange:B=>p("comments",B.target.value)})]}),e.jsxs("label",{className:"sm:col-span-2 flex items-center gap-3 text-sm",children:[e.jsx(ui,{checked:h.wants_plan,onCheckedChange:B=>p("wants_plan",!!B)}),"Send me the full Property Revival Plan for my home"]}),e.jsx("div",{className:"sm:col-span-2",children:e.jsx($,{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(Ht,{className:"h-4 w-4 mr-2 animate-spin"})," Sending…"]}):(g==null?void 0:g.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:v==null?void 0:v.name}),e.jsx("div",{className:"text-accent text-sm",children:(v==null?void 0:v.title)??"Real Estate Specialist"}),e.jsx("div",{className:"text-white/60 text-sm mt-2",children:[v==null?void 0:v.phone,v==null?void 0:v.email].filter(Boolean).join(" · ")}),v!=null&&v.brokerage_name?e.jsx("div",{className:"text-white/40 text-xs mt-3",children:v.brokerage_name}):null]})]})}const N_="#0f2540",oS="#c9a227";function sW({children:s,className:t,footer:n,page:r}){return e.jsxs("div",{"data-revival-plan-page":"",className:Tt("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 Jae({eyebrow:s,title:t}){return e.jsxs("div",{children:[e.jsx("div",{className:"text-[10.5px] tracking-[0.28em] uppercase font-bold",style:{color:oS},children:s}),e.jsx("h2",{className:"revival-serif text-[30px] leading-tight mt-1",style:{color:N_},children:t}),e.jsx("div",{className:"mt-3 h-[3px] w-14 rounded-full",style:{background:oS}})]})}function ZWn({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:N_},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?oS:"rgba(15,37,64,.10)"}},r))})]})}function JUe({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:Tt("space-y-8",a),children:[e.jsxs(sW,{children:[e.jsxs("div",{className:"relative h-[52%] overflow-hidden",style:{background:N_},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), ${N_})`}}),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:oS},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:g6(t.original_price)},{k:"Final price",v:g6(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:N_},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:N_},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(XN,{value:r,size:64,level:"M",fgColor:N_})}),e.jsx("div",{className:"text-[8.5px] tracking-[0.18em] uppercase text-[#0f2540]/45 mt-1",children:"View online"})]}):null]})]})]}),o.length?e.jsx(sW,{footer:d,page:2,children:e.jsxs("div",{className:"px-12 pt-12 flex-1 flex flex-col",children:[e.jsx(Jae,{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,x])=>e.jsx(ZWn,{label:p,value:Number(x)},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:oS},children:"What buyers experienced"}),e.jsx("ul",{className:"mt-3 space-y-2",children:s.buyers_experienced.slice(0,5).map((p,x)=>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:oS}}),p]},x))})]}):null]})}):null,(h=s==null?void 0:s.differently)!=null&&h.length?e.jsx(sW,{footer:d,page:3,children:e.jsxs("div",{className:"px-12 pt-12 flex-1 flex flex-col",children:[e.jsx(Jae,{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,x)=>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:N_},children:x+1}),e.jsx("span",{className:"text-[13px] leading-6 text-[#28313f]",children:p})]},x))})]})}):null,c.length?e.jsx(sW,{footer:d,page:4,children:e.jsxs("div",{className:"px-12 pt-12 flex-1 flex flex-col",children:[e.jsx(Jae,{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,x)=>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:N_},children:x+1}),e.jsxs("div",{children:[e.jsx("div",{className:"text-[10px] tracking-[0.26em] uppercase font-bold",style:{color:oS},children:p.week}),e.jsx("div",{className:"text-[16px] font-semibold mt-0.5",style:{color:N_},children:p.title}),e.jsx("p",{className:"text-[13px] leading-6 text-[#28313f] mt-1",children:p.body})]})]},x))})]})}):null,e.jsx(sW,{footer:d,page:5,children:e.jsxs("div",{className:"px-12 pt-12 flex-1 flex flex-col",children:[e.jsx(Jae,{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:oS},children:"Questions to ask any agent"}),e.jsx("ol",{className:"mt-3 space-y-2",children:s.questions.slice(0,6).map((p,x)=>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:N_},children:[x+1,"."]}),p]},x))})]}):null,e.jsxs("div",{className:"mt-8 rounded-2xl p-8 text-white",style:{background:N_},children:[e.jsx("div",{className:"text-[10.5px] tracking-[0.28em] uppercase font-bold",style:{color:oS},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:oS},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(XN,{value:r,size:60,level:"M",fgColor:N_})}):null]})]})]})})]})}const nW=[15,37,64],kRe=[201,162,39],R_t=[31,41,55],eie=[107,114,128];async function XWn(s,t=8){return PV.toDataURL(s,{margin:0,scale:t,color:{dark:"#0f2540",light:"#ffffff"}})}function QWn(s){return[s.title,s.brokerage_name,s.phone,s.email,s.website_url].filter(Boolean).map(String)}function uQe(s){return s.replace(/[^a-z0-9]+/gi,"-").replace(/^-+|-+$/g,"").toLowerCase().slice(0,60)}async function JWn(s){const{campaign:t,agent:n,url:r,photoDataUrl:a}=s,i=t.property,l=new go({unit:"pt",format:[648,432],orientation:"landscape"}),o=648,c=432;if(l.setFillColor(...nW),l.rect(0,0,o,c,"F"),a)try{l.addImage(a,"JPEG",0,0,o,c*.62)}catch{}l.setFillColor(...nW),l.rect(0,c*.6,o,c*.4,"F"),l.setFillColor(...kRe),l.rect(0,c*.6-4,o,4,"F"),l.setTextColor(...kRe),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(...nW),l.rect(0,0,10,c,"F");const d=44;l.setTextColor(...nW),l.setFont("times","normal"),l.setFontSize(19),l.text(n.name??"",d,54),l.setFont("helvetica","normal"),l.setFontSize(9),l.setTextColor(...eie),l.text(QWn(n).join(" · "),d,72,{maxWidth:o/2+40}),l.setDrawColor(...kRe),l.setLineWidth(1),l.line(d,88,o/2+60,88),l.setTextColor(...R_t),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 XWn(r);l.addImage(h,"PNG",d,c-150,108,108),l.setFont("helvetica","bold"),l.setFontSize(10),l.setTextColor(...nW),l.text("Scan for your free review",d+122,c-112),l.setFont("helvetica","normal"),l.setFontSize(8.5),l.setTextColor(...eie),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(...eie),l.text("MAILING ADDRESS",m+10,126),l.setFontSize(11),l.setTextColor(...R_t),[(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((x,g)=>l.text(String(x),m+14,162+g*18,{maxWidth:o-m-72})),l.setDrawColor(210,214,220),l.rect(o-118,40,74,62),l.setFontSize(7.5),l.setTextColor(...eie),l.text("POSTAGE",o-96,74),l.save(`revival-postcard-${uQe((i==null?void 0:i.property_address)??t.name)}.pdf`)}async function JWt(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 eKn(s,t){const{toPng:n}=await mi(async()=>{const{toPng:d}=await Promise.resolve().then(()=>BIt);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 JWt(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 go({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-${uQe(t)}.pdf`)}async function eKt(s,t){const{toPng:n}=await mi(async()=>{const{toPng:d}=await Promise.resolve().then(()=>BIt);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 JWt(h);m&&d.setAttribute("src",m)}));const l=new go({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-${uQe(t)}.pdf`)}function O_t(){var m,p,x;const{slug:s=""}=Vi(),[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 eKt(o.current,(c==null?void 0:c.property_address)??"plan")}finally{l(!1)}}};if(j.useEffect(()=>{let g=!0;return(async()=>{try{const{data:y,error:b}=await U.functions.invoke("listing-revival-public",{body:{action:"get",slug:s}});if(b)throw b;if(!g)return;n(y),await U.functions.invoke("listing-revival-public",{body:{action:"track",slug:s,event_type:"plan_view"}})}catch{g&&n(null)}finally{g&&a(!1)}})(),()=>{g=!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(Ht,{className:"h-6 w-6 animate-spin text-[#0f2540]"})});if(!t||!((x=(p=t.campaign)==null?void 0:p.content)!=null&&x.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(sa,{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(Ht,{className:"h-4 w-4 animate-spin"}):e.jsx(di,{className:"h-4 w-4"}),"Download PDF"]})]}),e.jsx("div",{ref:o,children:e.jsx(JUe,{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 tKn(){const{user:s}=_s();return ht({queryKey:["revival-campaigns",s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await U.from("listing_revival_campaigns").select("*, property:listing_revival_properties(*)").order("created_at",{ascending:!1});if(n)throw n;return t??[]}})}function sKn(s){return ht({queryKey:["revival-campaign",s],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await U.from("listing_revival_campaigns").select("*, property:listing_revival_properties(*)").eq("id",s).maybeSingle();if(n)throw n;return t??null}})}function nKn(){const{user:s}=_s();return ht({queryKey:["revival-properties",s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await U.from("listing_revival_properties").select("*").order("created_at",{ascending:!1});if(n)throw n;return t??[]}})}function tKt(){const{user:s}=_s();return ht({queryKey:["revival-leads",s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await U.from("listing_revival_leads").select("*").order("created_at",{ascending:!1});if(n)throw n;return t??[]}})}function rKn(){const{user:s}=_s();return ht({queryKey:["revival-tasks",s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await U.from("listing_revival_tasks").select("*").order("due_date",{ascending:!0});if(n)throw n;return t??[]}})}function sKt(){const{user:s}=_s();return ht({queryKey:["revival-events",s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await U.from("listing_revival_events").select("*").order("created_at",{ascending:!1}).limit(1e3);if(n)throw n;return t??[]}})}function hQe(){const s=ts(),t=()=>{["revival-campaigns","revival-campaign","revival-properties","revival-leads","revival-tasks","revival-events"].forEach(o=>s.invalidateQueries({queryKey:[o]}))},n=yt({mutationFn:async o=>{const{data:c,error:d}=await U.functions.invoke("listing-revival-generate",{body:o});if(d)throw d;if(c!=null&&c.error)throw new Error(String(c.error));return c},onSuccess:t,onError:o=>ae.error(o.message)}),r=yt({mutationFn:async o=>{const{error:c}=await U.from("listing_revival_campaigns").update(o.patch).eq("id",o.id);if(c)throw c},onSuccess:()=>{t(),ae.success("Saved")},onError:o=>ae.error(o.message)}),a=yt({mutationFn:async o=>{const{error:c}=await U.from("listing_revival_campaigns").delete().eq("id",o);if(c)throw c},onSuccess:()=>{t(),ae.success("Campaign deleted")},onError:o=>ae.error(o.message)}),i=yt({mutationFn:async o=>{const{error:c}=await U.from("listing_revival_campaigns").update({status:o.archived?"archived":"active",published:!o.archived}).eq("id",o.id);if(c)throw c;return o},onSuccess:o=>{t(),ae.success(o.archived?"Campaign archived":"Campaign restored")},onError:o=>ae.error(o.message)}),l=yt({mutationFn:async o=>{const{error:c}=await U.from("listing_revival_tasks").update({completed_at:o.done?new Date().toISOString():null}).eq("id",o.id);if(c)throw c},onSuccess:t,onError:o=>ae.error(o.message)});return{generate:n,saveCampaign:r,deleteCampaign:a,archiveCampaign:i,toggleTask:l,invalidate:t}}const aKn=[{id:"dashboard",label:"Dashboard",icon:zp},{id:"campaigns",label:"Campaigns",icon:dn},{id:"properties",label:"Properties",icon:sa},{id:"letters",label:"Letters",icon:nn},{id:"landing",label:"Landing Pages",icon:Gl},{id:"plans",label:"Revival Plans",icon:Wr},{id:"followup",label:"Follow Up",icon:v0},{id:"analytics",label:"Analytics",icon:ml},{id:"templates",label:"Templates",icon:nw},{id:"settings",label:"Settings",icon:G3}];function nb({label:s,value:t,icon:n,delay:r=0,hint:a}){return e.jsxs(jr.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 iKn(){const s=Vn(),[t,n]=j.useState("dashboard"),[r,a]=j.useState(""),[i,l]=j.useState(!1),[o,c]=j.useState(null),d=TRn(),u=tKn(),h=nKn(),m=tKt(),p=rKn(),x=sKt(),{toggleTask:g,archiveCampaign:y,deleteCampaign:b}=hQe(),v=u.data??[],N=m.data??[],C=x.data??[],A=p.data??[],T=j.useMemo(()=>{const V=K=>C.filter(Q=>Q.event_type===K).length;return{properties:(h.data??[]).length,campaigns:v.length,letters:v.filter(K=>{var Q;return(Q=K.content)==null?void 0:Q.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}},[v,N,C,h.data]),P=j.useMemo(()=>{const V=[];for(let K=13;K>=0;K--){const Q=new Date(Date.now()-K*864e5),J=Q.toISOString().slice(0,10);V.push({day:Hs(Q,"MMM d"),visits:C.filter(ce=>ce.event_type==="page_view"&&ce.created_at.startsWith(J)).length,scans:C.filter(ce=>ce.event_type==="qr_scan"&&ce.created_at.startsWith(J)).length,leads:N.filter(ce=>ce.created_at.startsWith(J)).length})}return V},[C,N]),M=V=>V.status==="archived",I=v.filter(V=>{var Q,J;if(i?!M(V):M(V))return!1;const K=r.trim().toLowerCase();return K?`${V.name} ${((Q=V.property)==null?void 0:Q.property_address)??""} ${((J=V.property)==null?void 0:J.seller_name)??""}`.toLowerCase().includes(K):!0}),D=v.filter(M).length,B=V=>s(`/apps/listing-revival/campaigns/${V}`),q=V=>{navigator.clipboard.writeText(QWt(V)),ae.success("Landing page link copied")},W=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(Vr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(be,{value:r,onChange:K=>a(K.target.value),placeholder:"Search campaigns…",className:"pl-9"})]}),e.jsxs($,{variant:i?"default":"outline",size:"sm",onClick:()=>l(K=>!K),children:[e.jsx(Am,{className:"h-3.5 w-3.5 mr-1.5"}),i?"Viewing archived":`Archived (${D})`]})]}),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,Q)=>{var ee,le,he,ve;const J=CB.find(ge=>ge.id===K.style),ce=N.filter(ge=>ge.campaign_id===K.id).length,ue=C.filter(ge=>ge.campaign_id===K.id&&ge.event_type==="page_view").length,ne=M(K);return e.jsxs(jr.div,{initial:{opacity:0,y:14},animate:{opacity:1,y:0},transition:{delay:Math.min(Q*.04,.3),duration:.4},className:Tt("revival-tile overflow-hidden",ne&&"opacity-80"),children:[e.jsxs("div",{className:"h-28 bg-muted relative",children:[(ee=K.property)!=null&&ee.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(sa,{className:"h-7 w-7 text-accent"})}),e.jsx($e,{className:"absolute top-3 left-3 bg-background/90 text-foreground border-0",children:(J==null?void 0:J.name)??K.style}),ne?e.jsx($e,{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:((le=K.property)==null?void 0:le.property_address)??K.name}),e.jsx("div",{className:"text-sm text-muted-foreground",children:((he=K.property)==null?void 0:he.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(Gl,{className:"h-3.5 w-3.5"}),ue]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(qn,{className:"h-3.5 w-3.5"}),ce]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(sa,{className:"h-3.5 w-3.5"}),((ve=K.property)==null?void 0:ve.days_on_market)??"—"," DOM"]})]}),e.jsxs("div",{className:"mt-4 flex gap-2",children:[e.jsxs($,{size:"sm",className:"flex-1",onClick:()=>B(K.id),children:["Open ",e.jsx(ni,{className:"h-3.5 w-3.5 ml-1"})]}),e.jsx($,{size:"sm",variant:"outline",onClick:()=>q(K.slug),children:e.jsx(Ca,{className:"h-3.5 w-3.5"})}),e.jsx($,{size:"sm",variant:"outline",asChild:!0,children:e.jsx("a",{href:`/revival/${K.slug}`,target:"_blank",rel:"noreferrer",children:e.jsx(Tr,{className:"h-3.5 w-3.5"})})}),e.jsxs(Hd,{children:[e.jsx(Gd,{asChild:!0,children:e.jsx($,{size:"sm",variant:"outline",children:e.jsx(cy,{className:"h-3.5 w-3.5"})})}),e.jsxs(Md,{align:"end",children:[e.jsx(Na,{onClick:()=>y.mutate({id:K.id,archived:!ne}),children:ne?e.jsxs(e.Fragment,{children:[e.jsx(hT,{className:"h-4 w-4 mr-2"})," Restore campaign"]}):e.jsxs(e.Fragment,{children:[e.jsx(Am,{className:"h-4 w-4 mr-2"})," Archive campaign"]})}),e.jsx(S0,{}),e.jsxs(Na,{className:"text-destructive focus:text-destructive",onClick:()=>{var ge;return c({id:K.id,name:((ge=K.property)==null?void 0:ge.property_address)??K.name})},children:[e.jsx(Pn,{className:"h-4 w-4 mr-2"})," Delete permanently"]})]})]})]})]})]},K.id)})}),e.jsx(Ll,{open:!!o,onOpenChange:K=>!K&&c(null),children:e.jsxs(yl,{children:[e.jsxs(vl,{children:[e.jsx(_l,{children:"Delete this campaign?"}),e.jsxs(wl,{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(bl,{children:[e.jsx(jl,{children:"Cancel"}),e.jsx(fl,{className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",onClick:()=>{o&&b.mutate(o.id),c(null)},children:"Delete permanently"})]})]})})]});return!d.isLoading&&!d.hasAccess?e.jsx(Ks,{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(dn,{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(Ks,{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(jr.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($,{size:"lg",className:"bg-accent text-accent-foreground hover:bg-accent/90",onClick:()=>s("/apps/listing-revival/new"),children:[e.jsx(sn,{className:"h-4 w-4 mr-1"})," New Campaign"]}),e.jsx($,{size:"lg",variant:"outline",className:"bg-transparent text-white border-white/25 hover:bg-white/10",onClick:()=>n("campaigns"),children:"View campaigns"})]})]})]}),e.jsxs(ua,{value:t,onValueChange:n,className:"mt-6",children:[e.jsx(ha,{className:"flex w-full overflow-x-auto no-scrollbar justify-start bg-transparent p-0 gap-2 h-auto",children:aKn.map(V=>e.jsxs(Qt,{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(Jt,{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(nb,{label:"Properties",value:T.properties,icon:sa,delay:0}),e.jsx(nb,{label:"Campaigns",value:T.campaigns,icon:dn,delay:.04}),e.jsx(nb,{label:"Letters",value:T.letters,icon:nn,delay:.08}),e.jsx(nb,{label:"QR Scans",value:T.qr,icon:Rx,delay:.12}),e.jsx(nb,{label:"Page Visits",value:T.visits,icon:Gl,delay:.16}),e.jsx(nb,{label:"Plans Viewed",value:T.planViews,icon:Wr,delay:.2}),e.jsx(nb,{label:"Seller Leads",value:T.leads,icon:qn,delay:.24}),e.jsx(nb,{label:"Appointments",value:T.appointments,icon:gy,delay:.28}),e.jsx(nb,{label:"Listings Won",value:T.won,icon:pl,delay:.32}),e.jsx(nb,{label:"Hot Leads",value:T.hot,icon:yd,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(Ob,{width:"100%",height:"100%",children:e.jsxs(lYe,{data:P,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(AO,{strokeDasharray:"3 3",stroke:"hsl(var(--border))",vertical:!1}),e.jsx(k1,{dataKey:"day",tick:{fontSize:11},stroke:"hsl(var(--muted-foreground))"}),e.jsx(S1,{allowDecimals:!1,tick:{fontSize:11},stroke:"hsl(var(--muted-foreground))",width:28}),e.jsx(yf,{contentStyle:{borderRadius:12,border:"1px solid hsl(var(--border))"}}),e.jsx(Fb,{type:"monotone",dataKey:"visits",stroke:"hsl(var(--primary))",fill:"url(#revVisits)",strokeWidth:2}),e.jsx(Fb,{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:[C.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:Hs(new Date(V.created_at),"MMM d, h:mm a")})]})]},V.id)),C.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(ui,{checked:!!V.completed_at,onCheckedChange:K=>g.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($e,{variant:"outline",children:Hs(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(Jt,{value:"campaigns",className:"mt-6",children:W("No campaigns yet — click New Campaign to build your first one.")}),e.jsx(Jt,{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:g6(V.original_price)}),e.jsx("td",{className:"px-4 py-3",children:g6(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(Jt,{value:"letters",className:"mt-6",children:W("Letters appear here once you create a campaign.")}),e.jsx(Jt,{value:"landing",className:"mt-6",children:W("Landing pages appear here once you create a campaign.")}),e.jsx(Jt,{value:"plans",className:"mt-6",children:W("Property Revival Plans appear here once you create a campaign.")}),e.jsxs(Jt,{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(ui,{checked:!1,onCheckedChange:()=>g.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($e,{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($e,{className:Tt("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:VWn.map(V=>{const K=V.toLowerCase().replace(/ /g,"_"),Q=N.filter(J=>J.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:Q})]},V)})})]})]}),e.jsxs(Jt,{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(nb,{label:"Lead capture %",value:`${T.visits?Math.round(T.leads/T.visits*100):0}%`,icon:qn}),e.jsx(nb,{label:"Scan → visit",value:`${T.qr?Math.round(T.visits/T.qr*100):0}%`,icon:Rx}),e.jsx(nb,{label:"Appointments",value:T.appointments,icon:gy}),e.jsx(nb,{label:"Conversion %",value:`${T.leads?Math.round(T.won/T.leads*100):0}%`,icon:pl})]}),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(Ob,{width:"100%",height:"100%",children:e.jsxs(REe,{data:v.slice(0,10).map(V=>{var K;return{name:(((K=V.property)==null?void 0:K.property_address)??V.name).slice(0,18),visits:C.filter(Q=>Q.campaign_id===V.id&&Q.event_type==="page_view").length,leads:N.filter(Q=>Q.campaign_id===V.id).length}}),children:[e.jsx(AO,{strokeDasharray:"3 3",stroke:"hsl(var(--border))",vertical:!1}),e.jsx(k1,{dataKey:"name",tick:{fontSize:10},stroke:"hsl(var(--muted-foreground))"}),e.jsx(S1,{allowDecimals:!1,tick:{fontSize:11},stroke:"hsl(var(--muted-foreground))",width:28}),e.jsx(yf,{contentStyle:{borderRadius:12,border:"1px solid hsl(var(--border))"}}),e.jsx(i2,{dataKey:"visits",fill:"hsl(var(--primary))",radius:[6,6,0,0]}),e.jsx(i2,{dataKey:"leads",fill:"hsl(var(--accent))",radius:[6,6,0,0]})]})})})]})]}),e.jsxs(Jt,{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:CB.map(V=>e.jsxs("div",{className:"revival-tile p-5",children:[e.jsx("div",{className:Tt("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:XWt.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(Jt,{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($,{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 F_t=["Import the property","Choose the campaign style","Generate everything"];function oKn(){var v;const s=Vn(),{user:t}=_s(),{generate:n,invalidate:r}=hQe(),[a,i]=j.useState(0),[l,o]=j.useState(!1),[c,d]=j.useState(CB[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:""}),x=(N,C)=>p(A=>({...A,[N]:C})),g=a===0?m.property_address.trim().length>3:!0,y=async()=>{if(t){o(!0);try{const{data:N,error:C}=await U.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(C)throw C;const{data:A,error:T}=await U.from("listing_revival_campaigns").insert({owner_user_id:t.id,property_id:N.id,name:m.property_address.trim(),slug:KWn(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(),ae.success("Campaign built — everything is ready."),s(`/apps/listing-revival/campaigns/${A.id}`)}catch(N){ae.error(N instanceof Error?N.message:"Could not create the campaign")}finally{o(!1)}}},b=(N,C,A={})=>e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{className:"text-xs uppercase tracking-wider text-muted-foreground",children:C}),e.jsx(be,{value:m[N],onChange:T=>x(N,T.target.value),...A})]});return e.jsx(Ks,{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($,{variant:"ghost",size:"sm",className:"gap-2 mb-4",onClick:()=>s("/apps/listing-revival"),children:[e.jsx(ka,{className:"h-4 w-4"})," Back to Listing Revival"]}),e.jsx("div",{className:"flex items-center gap-3 mb-6",children:F_t.map((N,C)=>e.jsxs("div",{className:"flex items-center gap-3 flex-1",children:[e.jsx("div",{className:Tt("h-9 w-9 rounded-full grid place-items-center text-sm font-bold shrink-0 transition-colors",Cx("photo_url",N??""),label:"Property photo",prefix:"revival-property"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{className:"text-xs uppercase tracking-wider text-muted-foreground",children:"Agent notes"}),e.jsx(Is,{rows:6,value:m.agent_notes,onChange:N=>x("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:CB.map(N=>e.jsxs("button",{type:"button",onClick:()=>d(N.id),className:Tt("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:Tt("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(oa,{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:XWt.map(N=>e.jsxs("button",{type:"button",onClick:()=>h(N.id),className:Tt("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(wm,{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:(v=CB.find(N=>N.id===c))==null?void 0:v.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($,{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(Ht,{className:"h-4 w-4 mr-2 animate-spin"})," Building your campaign…"]}):e.jsxs(e.Fragment,{children:[e.jsx(dn,{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($,{variant:"outline",disabled:a===0,onClick:()=>i(N=>N-1),children:"Back"}),e.jsxs($,{disabled:!g,onClick:()=>i(N=>N+1),children:["Continue ",e.jsx(ni,{className:"h-4 w-4 ml-1"})]})]}):e.jsx("div",{className:"flex justify-start mt-6",children:e.jsx($,{variant:"outline",disabled:l,onClick:()=>i(1),children:"Back"})})]})})}const z_t={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 lKn(s){return s<=900?1:s<=1150?.94:s<=1400?.88:s<=1700?.82:s<=2100?.76:.7}function B_t({campaign:s,letter:t,agent:n,url:r,className:a}){var h,m;const i=z_t[s.letter_template]??z_t.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=lKn(c),u={fontSize:`${(i.size*d).toFixed(2)}px`,lineHeight:1.6};return e.jsxs("div",{id:"revival-letter-sheet",className:Tt("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:Tt("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:Tt("mt-1 h-[3px] w-16 rounded-full",i.rule)}),e.jsxs("div",{className:Tt("mt-4 text-[#28313f] flex flex-col",i.body),style:{...u,gap:`${(.7*d).toFixed(2)}em`},children:[o.map((p,x)=>e.jsx("p",{children:p},x)),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(XN,{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 nKt({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,x)=>x===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($,{size:"sm",variant:"ghost",onClick:r,disabled:t,children:[e.jsx(pr,{className:"h-3.5 w-3.5 mr-1.5"})," Cancel"]}),e.jsxs($,{size:"sm",onClick:()=>n({...a,paragraphs:a.paragraphs.map(u=>u.trim()).filter(Boolean)}),disabled:t,children:[t?e.jsx(Ht,{className:"h-3.5 w-3.5 mr-1.5 animate-spin"}):e.jsx(Jo,{className:"h-3.5 w-3.5 mr-1.5"}),"Save letter"]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{className:"text-xs",children:"Greeting"}),e.jsx(be,{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(se,{className:"text-xs",children:"Body paragraphs"}),e.jsxs($,{size:"sm",variant:"outline",onClick:c,children:[e.jsx(sn,{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(Is,{value:u,onChange:m=>o(h,m.target.value),rows:4,className:"flex-1"}),e.jsx($,{size:"icon",variant:"ghost",onClick:()=>d(h),"aria-label":"Remove paragraph",children:e.jsx(Pn,{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(se,{className:"text-xs",children:"Closing line"}),e.jsx(be,{value:a.closing??"",onChange:u=>l("closing",u.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{className:"text-xs",children:"Signature"}),e.jsx(be,{value:a.signature??"",onChange:u=>l("signature",u.target.value)})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{className:"text-xs",children:"P.S."}),e.jsx(Is,{value:a.ps??"",onChange:u=>l("ps",u.target.value),rows:2})]})]})}function $_t(s){if(!s)return null;const t=Math.floor(s/60),n=Math.round(s%60);return`${t}:${String(n).padStart(2,"0")}`}function cKn(s){return s.share_token?`https://video.relevelup.com/thumb/${s.share_token}`:s.thumbnail_url}function dKn({video:s}){const[t,n]=j.useState(!1),r=cKn(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(Sh,{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 uKn=(()=>{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 hKn({open:s,onOpenChange:t,onSelect:n,propertyAddress:r}){const{user:a}=_s(),[i,l]=j.useState("library"),[o,c]=j.useState([]),[d,u]=j.useState(!1),[h,m]=j.useState(""),[p,x]=j.useState("record"),[g,y]=j.useState(0),[b,v]=j.useState(0),N=F5(),C=j.useCallback(async()=>{if(a){u(!0);try{const{data:I,error:D}=await U.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(D)throw D;c(I??[])}catch{ae.error("Could not load your video library")}finally{u(!1)}}},[a]);j.useEffect(()=>{s&&C()},[s,C]);const A=j.useMemo(()=>{const I=h.trim().toLowerCase();return I?o.filter(D=>`${D.title??""} ${D.recipient_name??""}`.toLowerCase().includes(I)):o},[o,h]),T=I=>{if(!I.playback_url){ae.error("That video has no playable link yet");return}n(I.playback_url),t(!1)},P=I=>{!I&&(p==="uploading"||p==="processing")||(t(I),I||(x("record"),y(0),v(0)))},M=j.useCallback(async(I,D)=>{x("uploading");const B=r?`Listing Revival — ${r}`:"Listing Revival intro";try{const{videoId:q,libraryId:W}=await Z6(B),{uploadUrl:V,apiKey:K}=await X6(q),Q=new XMLHttpRequest;Q.upload.onprogress=le=>{le.lengthComputable&&y(le.loaded/le.total*100)},await new Promise((le,he)=>{Q.onload=()=>Q.status>=200&&Q.status<300?le():he(new Error("Upload failed")),Q.onerror=()=>he(new Error("Upload failed")),Q.open("PUT",V),Q.setRequestHeader("AccessKey",K),Q.send(I)}),x("processing");const J=`https://iframe.mediadelivery.net/embed/${W}/${q}`,ce=Date.now(),ue=9e4;let ne=0;for(;ne<4;){if(await new Promise(he=>setTimeout(he,3e3)),Date.now()-ce>ue){await N.mutateAsync({bunny_video_id:q,playback_url:`https://iframe.mediadelivery.net/play/${W}/${q}`,file_size_mb:I.size/(1024*1024),title:B,status:"processing",touch_type:"video"}),n(J),ae.success("Video saved — still encoding, it will appear shortly."),x("done"),setTimeout(()=>P(!1),1200);return}const le=await o2(q);if(ne=le.status,v(le.encodeProgress||0),ne===5||ne===6)throw new Error("Video processing failed")}const ee=await o2(q);await N.mutateAsync({bunny_video_id:q,playback_url:ee.directPlayUrl||J,thumbnail_url:ee.thumbnailUrl,preview_url:ee.previewUrl||null,duration_seconds:ee.length||D,file_size_mb:(ee.storageSize||I.size)/(1024*1024),title:B,status:"ready",touch_type:"video"}),n(ee.directPlayUrl||J),ae.success("Video recorded and added to your landing page!"),x("done"),setTimeout(()=>P(!1),1200)}catch(q){console.error("Revival recording upload error:",q),ae.error("Failed to process video. Please try again."),x("record")}},[N,n,r]);return e.jsx(Os,{open:s,onOpenChange:P,children:e.jsxs(Rs,{className:"max-w-4xl max-h-[92vh] overflow-y-auto",children:[e.jsxs(Us,{children:[e.jsx(zs,{children:"Add a video to your landing page"}),e.jsx(Sr,{children:"Pick one you already recorded, or record a brand new one right here without leaving Listing Revival."})]}),e.jsxs(ua,{value:i,onValueChange:l,children:[e.jsxs(ha,{className:"grid w-full grid-cols-2",children:[e.jsxs(Qt,{value:"library",children:[e.jsx(lh,{className:"h-3.5 w-3.5 mr-1.5"})," My library"]}),e.jsxs(Qt,{value:"record",children:[e.jsx(Xr,{className:"h-3.5 w-3.5 mr-1.5"})," Record new"]})]}),e.jsxs(Jt,{value:"library",className:"mt-4 space-y-3",children:[e.jsxs("div",{className:"relative",children:[e.jsx(Vr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(be,{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,D)=>e.jsx(on,{className:"aspect-video rounded-xl"},D))}):A.length===0?e.jsxs("div",{className:"rounded-xl border border-dashed border-border p-10 text-center",children:[e.jsx(Sh,{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($,{size:"sm",variant:"outline",className:"mt-3",onClick:()=>l("record"),children:[e.jsx(Xr,{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(dKn,{video:I}),$_t(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:$_t(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:Hs(new Date(I.created_at),"MMM d, yyyy")}):null]})]},I.id))})]}),e.jsxs(Jt,{value:"record",className:"mt-4",children:[p==="record"?e.jsxs("div",{className:"space-y-3",children:[uKn?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($,{size:"sm",variant:"outline",onClick:()=>window.open(window.location.href,"_blank","noopener"),children:[e.jsx(Tr,{className:"h-3.5 w-3.5 mr-1.5"})," Open in new tab"]})]}):null,e.jsx(J6,{maxDurationSeconds:600,onRecordingComplete:M,onError:I=>ae.error(I)})]}):null,p==="uploading"?e.jsxs("div",{className:"flex flex-col items-center gap-4 py-12",children:[e.jsx(Ht,{className:"h-10 w-10 animate-spin text-primary"}),e.jsx("p",{className:"text-sm font-medium",children:"Uploading your video…"}),e.jsx(Ki,{value:g,className:"w-64"}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[Math.round(g),"%"]})]}):null,p==="processing"?e.jsxs("div",{className:"flex flex-col items-center gap-4 py-12",children:[e.jsx(Ht,{className:"h-10 w-10 animate-spin text-primary"}),e.jsx("p",{className:"text-sm font-medium",children:"Processing your video…"}),e.jsx(Ki,{value:b,className:"w-64"}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[Math.round(b),"%"]})]}):null,p==="done"?e.jsxs("div",{className:"flex flex-col items-center gap-3 py-12",children:[e.jsx(Ro,{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 mKn=[{id:"photo",label:"Property photo",hint:"Shows the listing photo. Best if you have no video.",icon:Jl},{id:"video",label:"Video",hint:"Record one here, pick from your library, or paste a link.",icon:Xr},{id:"none",label:"Nothing",hint:"Hide the media block entirely for a clean, text-only intro.",icon:b0}];function pKn({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({...L_t,...n}),[u,h]=j.useState(!1),[m,p]=j.useState(!1);j.useEffect(()=>{o(t.landing)},[t.landing]),j.useEffect(()=>{d({...L_t,...n})},[n]);const x=(T,P)=>{o(M=>({...M??{},[T]:P})),h(!0)},g=(T,P)=>{d(M=>({...M,[T]:P})),h(!0)},y=(l==null?void 0:l.discover)??[],b=T=>x("discover",T),v=j.useMemo(()=>ZWt(c.video_url),[c.video_url]),N=c.media_image_url||r||null,C=()=>{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($,{size:"sm",onClick:C,disabled:!u||a,children:[a?e.jsx(Ht,{className:"h-3.5 w-3.5 mr-1.5 animate-spin"}):e.jsx(Jo,{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(se,{children:"Eyebrow"}),e.jsx(be,{value:(l==null?void 0:l.eyebrow)??"",onChange:T=>x("eyebrow",T.target.value),placeholder:"A complimentary review"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:"Button text"}),e.jsx(be,{value:(l==null?void 0:l.cta)??"",onChange:T=>x("cta",T.target.value),placeholder:"Get my free review"})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:"Headline"}),e.jsx(be,{value:(l==null?void 0:l.headline)??"",onChange:T=>x("headline",T.target.value)})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:"Subheadline"}),e.jsx(Is,{rows:2,value:(l==null?void 0:l.subheadline)??"",onChange:T=>x("subheadline",T.target.value)})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:"Personal intro paragraph"}),e.jsx(Is,{rows:5,value:(l==null?void 0:l.intro)??"",onChange:T=>x("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:mKn.map(T=>{const P=(c.media_mode??"photo")===T.id;return e.jsxs("button",{type:"button",onClick:()=>g("media_mode",T.id),className:`text-left rounded-xl border p-4 transition ${P?"border-accent ring-1 ring-accent":"border-border hover:border-accent/50"}`,children:[e.jsx(T.icon,{className:`h-5 w-5 ${P?"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(se,{children:"Video link"}),e.jsx(be,{value:c.video_url??"",onChange:T=>g("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($,{type:"button",size:"sm",onClick:()=>p(!0),children:[e.jsx(Xr,{className:"h-3.5 w-3.5 mr-1.5"})," Record or choose a video"]}),c.video_url?e.jsxs($,{type:"button",size:"sm",variant:"ghost",onClick:()=>g("video_url",""),children:[e.jsx(Pn,{className:"h-3.5 w-3.5 mr-1.5"})," Remove video"]}):null]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:"Caption under the video"}),e.jsx(be,{value:c.video_caption??"",onChange:T=>g("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:(v==null?void 0:v.kind)==="file"?e.jsx("video",{src:v.src,controls:!0,className:"h-full w-full object-cover"}):v?e.jsx("iframe",{src:v.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(Sh,{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(xte,{label:"Photo shown next to your intro",value:c.media_image_url??"",onChange:T=>g("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,P,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:P}),e.jsx("p",{className:"text-xs text-muted-foreground",children:M})]}),e.jsx(Tn,{checked:c[T]!==!1,onCheckedChange:I=>g(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($,{size:"sm",variant:"outline",onClick:()=>b([...y,{title:"",body:""}]),children:[e.jsx(sn,{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,P)=>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($e,{variant:"outline",children:P+1}),e.jsx(be,{value:T.title,placeholder:"Card title",onChange:M=>b(y.map((I,D)=>D===P?{...I,title:M.target.value}:I))}),e.jsx($,{size:"icon",variant:"ghost",onClick:()=>b(y.filter((M,I)=>I!==P)),children:e.jsx(Pn,{className:"h-4 w-4"})})]}),e.jsx(Is,{rows:2,value:T.body,placeholder:"What this card explains",onChange:M=>b(y.map((I,D)=>D===P?{...I,body:M.target.value}:I))})]},P))]}),e.jsx("div",{className:"flex justify-end",children:e.jsxs($,{onClick:C,disabled:!u||a,children:[a?e.jsx(Ht,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(Jo,{className:"h-4 w-4 mr-2"}),"Save changes"]})}),e.jsx(hKn,{open:m,onOpenChange:p,propertyAddress:((A=t==null?void 0:t.landing)==null?void 0:A.headline)??null,onSelect:T=>{g("video_url",T),g("media_mode","video")}})]})}const SRe={intro:"",scores:{},buyers_experienced:[],differently:[],strategy_weeks:[],questions:[],resources:[],invitation:""},fKn=s=>Math.min(5,Math.max(1,Math.round(s||1)));function xKn({plan:s,saving:t,onSave:n}){const[r,a]=j.useState({...SRe,...s});j.useEffect(()=>{a({...SRe,...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(se,{children:c}),e.jsxs($,{type:"button",size:"sm",variant:"ghost",onClick:()=>i(o,[...r[o]??[],""]),children:[e.jsx(sn,{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(Is,{value:u,rows:2,onChange:m=>{const p=[...r[o]??[]];p[h]=m.target.value,i(o,p)}}),e.jsx($,{type:"button",size:"icon",variant:"ghost",onClick:()=>i(o,(r[o]??[]).filter((m,p)=>p!==h)),children:e.jsx(Pn,{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($,{type:"button",size:"sm",variant:"ghost",onClick:()=>a({...SRe,...s}),children:[e.jsx(Ih,{className:"h-3.5 w-3.5 mr-1.5"})," Reset"]}),e.jsxs($,{type:"button",size:"sm",disabled:t,className:"bg-accent text-accent-foreground hover:bg-accent/90",onClick:()=>n(r),children:[t?e.jsx(Ht,{className:"h-3.5 w-3.5 mr-1.5 animate-spin"}):e.jsx(Jo,{className:"h-3.5 w-3.5 mr-1.5"}),"Save plan"]})]})]}),e.jsxs("section",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"plan-intro",children:"Introduction"}),e.jsx(Is,{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(se,{children:"Marketing scorecard (1–5)"}),e.jsxs($,{type:"button",size:"sm",variant:"ghost",onClick:()=>i("scores",{...r.scores,[`Category ${Object.keys(r.scores??{}).length+1}`]:3}),children:[e.jsx(sn,{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(be,{value:o,onChange:u=>{const h=Object.entries(r.scores??{});h[d]=[u.target.value,c],i("scores",Object.fromEntries(h))}}),e.jsx(be,{type:"number",min:1,max:5,className:"w-20",value:c,onChange:u=>i("scores",{...r.scores,[o]:fKn(Number(u.target.value))})}),e.jsx($,{type:"button",size:"icon",variant:"ghost",onClick:()=>{const u={...r.scores??{}};delete u[o],i("scores",u)},children:e.jsx(Pn,{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(se,{children:"Relaunch timeline"}),e.jsxs($,{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(sn,{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(be,{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(be,{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($,{type:"button",size:"icon",variant:"ghost",onClick:()=>i("strategy_weeks",(r.strategy_weeks??[]).filter((d,u)=>u!==c)),children:e.jsx(Pn,{className:"h-4 w-4 text-destructive"})})]}),e.jsx(Is,{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(se,{children:"Resources"}),e.jsxs($,{type:"button",size:"sm",variant:"ghost",onClick:()=>i("resources",[...r.resources??[],{title:"",body:""}]),children:[e.jsx(sn,{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(be,{value:o.title,placeholder:"Title",onChange:d=>{const u=[...r.resources??[]];u[c]={...o,title:d.target.value},i("resources",u)}}),e.jsx($,{type:"button",size:"icon",variant:"ghost",onClick:()=>i("resources",(r.resources??[]).filter((d,u)=>u!==c)),children:e.jsx(Pn,{className:"h-4 w-4 text-destructive"})})]}),e.jsx(Is,{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(se,{htmlFor:"plan-invitation",children:"Closing invitation"}),e.jsx(Is,{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($,{type:"button",disabled:t,className:"bg-accent text-accent-foreground hover:bg-accent/90",onClick:()=>n(r),children:[t?e.jsx(Ht,{className:"h-4 w-4 mr-1.5 animate-spin"}):e.jsx(Jo,{className:"h-4 w-4 mr-1.5"}),"Save plan"]})})]})}const gKn=[{key:"letter",label:"Letter",icon:nn,blurb:"Personalized print-ready letter mailed to the homeowner."},{key:"qr_scan",label:"QR Scan",icon:Rx,blurb:"Homeowner scans the unique code on the letter."},{key:"page_view",label:"Landing Page",icon:Gl,blurb:"Private property review page opens on their phone."},{key:"form_submit",label:"Lead Form",icon:v0,blurb:"They request the plan — Agent OS is updated instantly."},{key:"plan_view",label:"Revival Plan",icon:Wr,blurb:"The full Property Revival Plan is delivered."},{key:"email",label:"Email Sequence",icon:Br,blurb:"Seven branded emails nurture the conversation."},{key:"sms",label:"Text Sequence",icon:Ji,blurb:"Five short texts keep momentum going."},{key:"appointment",label:"Appointment",icon:gy,blurb:"They book a complimentary strategy session."},{key:"listing",label:"Listing Signed",icon:pu,blurb:"The relaunch begins."}];function yKn({counts:s,onStep:t,activeStep:n}){return e.jsx("div",{className:"grid gap-3 sm:grid-cols-2 lg:grid-cols-3",children:gKn.map((r,a)=>{const i=r.icon,l=s[r.key]??0,o=l>0;return e.jsxs(jr.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:Tt("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:Tt("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 vKn({open:s,onOpenChange:t,campaignId:n,email:r,ctaUrl:a,seller:i}){const{user:l}=_s(),[o,c]=j.useState([]),[d,u]=j.useState(""),[h,m]=j.useState([]),[p,x]=j.useState(""),[g,y]=j.useState(""),[b,v]=j.useState("View your property review"),[N,C]=j.useState(""),[A,T]=j.useState(!1),[P,M]=j.useState(!1),I=j.useRef(null);j.useEffect(()=>{!s||!r||(c([]),u(""),m([]),x(r.subject||""),y(r.body||""),C(""))},[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:Q}=await U.functions.invoke("listing-revival-email",{body:{campaign_id:n,subject:p,body:g,preview_text:r.preview,cta_label:b,cta_url:a,preview_only:!0}});if(Q)throw Q;K!=null&&K.html&&C(K.html)}catch{}finally{T(!1)}},400);return()=>clearTimeout(V)},[s,n,p,g,b,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}%`,Q=U,{data:J}=await Q.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(J||[])},200),()=>{I.current&&clearTimeout(I.current)}},[d,l==null?void 0:l.id]);const D=V=>{V.email&&(c(K=>K.some(Q=>Q.email.toLowerCase()===V.email.toLowerCase())?K:[...K,V]),u(""),m([]))},B=()=>{const V=d.trim();if(!/\S+@\S+\.\S+/.test(V)){ae.error("Enter a valid email address");return}D({email:V})},q=j.useMemo(()=>!!r&&o.length>0&&p.trim().length>0&&!P,[r,o,p,P]),W=async()=>{if(r){M(!0);try{const{data:V,error:K}=await U.functions.invoke("listing-revival-email",{body:{campaign_id:n,subject:p,body:g,preview_text:r.preview,cta_label:b,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");ae.success(V.failed?`Sent to ${V.sent} · ${V.failed} failed`:`Email sent to ${V.sent} ${V.sent===1?"contact":"contacts"}`),t(!1)}catch(V){ae.error((V==null?void 0:V.message)||"Could not send the email")}finally{M(!1)}}};return e.jsx(Os,{open:s,onOpenChange:t,children:e.jsxs(Rs,{className:"max-w-5xl max-h-[92vh] overflow-y-auto",children:[e.jsxs(Us,{children:[e.jsxs(zs,{className:"flex items-center gap-2",children:[e.jsx(nn,{className:"h-4 w-4"})," Send this email"]}),e.jsx(Sr,{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(se,{children:"Recipients"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(be,{value:d,onChange:V=>u(V.target.value),placeholder:"Search contacts or type an email",onKeyDown:V=>{V.key==="Enter"&&(V.preventDefault(),B())}}),e.jsx($,{type:"button",variant:"outline",size:"icon",onClick:B,children:e.jsx(sn,{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:()=>D({email:V.email,first_name:V.first_name,last_name:V.last_name,contact_id:V.id}),children:[e.jsx(Lo,{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($,{type:"button",size:"sm",variant:"ghost",onClick:()=>D({email:i.email,first_name:(i.name||"").split(" ")[0]}),children:[e.jsx(sn,{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($e,{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(Q=>Q.email!==V.email)),children:e.jsx(pr,{className:"h-3 w-3"})})]},V.email))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Subject"}),e.jsx(be,{value:p,onChange:V=>x(V.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Message"}),e.jsx(Is,{rows:10,value:g,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(se,{children:"Button label"}),e.jsx(be,{value:b,onChange:V=>v(V.target.value)})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(se,{className:"flex items-center gap-2",children:["Live preview ",A&&e.jsx(Ht,{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(kr,{children:[e.jsx($,{variant:"ghost",onClick:()=>t(!1),children:"Cancel"}),e.jsxs($,{onClick:W,disabled:!q,children:[P?e.jsx(Ht,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(Br,{className:"h-4 w-4 mr-2"}),"Send to ",o.length||0]})]})]})})}const bKn=[{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"]}],U_t="c0a11111-0000-4000-8000-000000000030";function _Kn(){var ce,ue,ne,ee,le,he,ve,ge,fe,je,Ee,Me,De,ze,ke,Xe,Se,Re,Ae,Be,qe,Ke,Ze,Ue,et,Qe,Ge,nt,ft;const{id:s}=Vi(),t=Vn(),{user:n}=_s(),r=sKn(s),a=sKt(),i=tKt(),{generate:l,saveCampaign:o,deleteCampaign:c}=hQe(),[d,u]=j.useState(""),[h,m]=j.useState(null),[p,x]=j.useState(!1),[g,y]=j.useState(!1),[b,v]=j.useState(null),N=ht({queryKey:["revival-drip-campaigns",n==null?void 0:n.id],enabled:!!n,queryFn:async()=>{const{data:lt}=await U.from("drip_campaigns").select("id, name").eq("owner_user_id",n.id).order("name");return lt??[]}}),C=yt({mutationFn:async()=>{if(!n)throw new Error("Not signed in");const[{data:lt},{data:Mt}]=await Promise.all([U.from("drip_campaigns").select("*").eq("id",U_t).maybeSingle(),U.from("drip_campaign_steps").select("*").eq("campaign_id",U_t).order("step_order")]);if(!lt)throw new Error("Starter campaign not found");const{data:Ft,error:Ts}=await U.from("drip_campaigns").insert({owner_user_id:n.id,name:lt.name,description:lt.description,category:lt.category,icon:lt.icon,cover_color:lt.cover_color,goal:lt.goal,is_active:!0,is_starter:!1}).select("id, name").single();if(Ts)throw Ts;if(Mt!=null&&Mt.length){const{error:js}=await U.from("drip_campaign_steps").insert(Mt.map(zt=>({campaign_id:Ft.id,step_order:zt.step_order,channel:zt.channel,subject:zt.subject,body:zt.body,delay_type:zt.delay_type,delay_days:zt.delay_days,delay_hours:zt.delay_hours,send_window_start:zt.send_window_start,send_window_end:zt.send_window_end})));if(js)throw js}return Ft},onSuccess:async lt=>{await N.refetch(),o.mutate({id:s,patch:{drip_campaign_id:lt.id}}),ae.success("Expired Listing Revival drip installed and assigned")},onError:lt=>ae.error(lt.message)}),A=(N.data??[]).some(lt=>{var Mt;return(Mt=lt.name)==null?void 0:Mt.startsWith("Expired Listing Revival")}),T=ht({queryKey:["revival-agent-profile",n==null?void 0:n.id],enabled:!!n,queryFn:async()=>{const{data:lt}=await U.from("profiles").select("name, email, phone, avatar_url, brokerage_name, website_url, title").eq("id",n.id).maybeSingle();return lt}}),P=r.data,M=(P==null?void 0:P.content)??{},I=P?QWt(P.slug):"",D={name:(ce=T.data)==null?void 0:ce.name,title:(ue=T.data)==null?void 0:ue.title,phone:(ne=T.data)==null?void 0:ne.phone,email:(ee=T.data)==null?void 0:ee.email,website_url:(le=T.data)==null?void 0:le.website_url,avatar_url:(he=T.data)==null?void 0:he.avatar_url,brokerage_name:(ve=T.data)==null?void 0:ve.brokerage_name},B=j.useRef(null),q=async()=>{var Mt,Ft;const lt=(Mt=B.current)==null?void 0:Mt.firstElementChild;if(lt){m("letter");try{await eKn(lt,((Ft=P==null?void 0:P.property)==null?void 0:Ft.property_address)??(P==null?void 0:P.name)??"letter"),ae.success("Letter PDF downloaded")}catch{ae.error("Could not build the letter PDF")}finally{m(null)}}},W=j.useRef(null),V=async()=>{var Mt;const lt=W.current;if(lt){m("plan");try{await eKt(lt,((Mt=P==null?void 0:P.property)==null?void 0:Mt.property_address)??(P==null?void 0:P.name)??"plan"),ae.success("Plan PDF downloaded")}catch{ae.error("Could not build the plan PDF")}finally{m(null)}}},K=j.useMemo(()=>{var Ft,Ts;const lt=(a.data??[]).filter(js=>js.campaign_id===s),Mt={};return lt.forEach(js=>{Mt[js.event_type]=(Mt[js.event_type]??0)+1}),Mt.letter=M.letter?1:0,Mt.email=((Ft=M.emails)==null?void 0:Ft.length)??0,Mt.sms=((Ts=M.sms)==null?void 0:Ts.length)??0,Mt.form_submit=(i.data??[]).filter(js=>js.campaign_id===s).length,Mt},[a.data,i.data,s,M]);if(r.isLoading)return e.jsx(Ks,{title:"Campaign",children:e.jsx("div",{className:"grid place-items-center py-24",children:e.jsx(Ht,{className:"h-6 w-6 animate-spin"})})});if(!P)return e.jsx(Ks,{title:"Campaign",children:e.jsx("div",{className:"py-24 text-center text-muted-foreground",children:"Campaign not found."})});const Q=CB.find(lt=>lt.id===P.style),J=lt=>l.mutate({campaignId:P.id,section:lt,instruction:d||void 0});return e.jsxs(Ks,{title:P.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($,{variant:"ghost",size:"sm",className:"gap-2 mb-4",onClick:()=>t("/apps/listing-revival"),children:[e.jsx(ka,{className:"h-4 w-4"})," Back to Listing Revival"]}),e.jsx(jr.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:(Q==null?void 0:Q.name)??P.style}),e.jsx("h1",{className:"revival-serif text-3xl mt-1",children:(ge=P.property)==null?void 0:ge.property_address}),e.jsxs("p",{className:"text-white/70 mt-1",children:[((fe=P.property)==null?void 0:fe.seller_name)??"Homeowner",(je=P.property)!=null&&je.city?` · ${P.property.city}, ${P.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:g6((Ee=P.property)==null?void 0:Ee.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:g6((Me=P.property)==null?void 0:Me.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:((De=P.property)==null?void 0:De.days_on_market)??"—"})]})]}),e.jsxs("div",{className:"mt-6 flex flex-wrap gap-2",children:[e.jsx($,{size:"sm",className:"bg-accent text-accent-foreground hover:bg-accent/90",asChild:!0,children:e.jsxs("a",{href:`/revival/${P.slug}`,target:"_blank",rel:"noreferrer",children:[e.jsx(Tr,{className:"h-3.5 w-3.5 mr-1.5"})," View landing page"]})}),e.jsxs($,{size:"sm",variant:"outline",className:"bg-transparent text-white border-white/25 hover:bg-white/10",onClick:()=>{navigator.clipboard.writeText(I),ae.success("Link copied")},children:[e.jsx(Ca,{className:"h-3.5 w-3.5 mr-1.5"})," Copy link"]}),e.jsxs($,{size:"sm",variant:"outline",className:"bg-transparent text-white border-white/25 hover:bg-white/10",disabled:l.isPending,onClick:()=>J(),children:[l.isPending?e.jsx(Ht,{className:"h-3.5 w-3.5 mr-1.5 animate-spin"}):e.jsx(Wi,{className:"h-3.5 w-3.5 mr-1.5"}),"Regenerate all"]})]})]}),e.jsxs("div",{className:"relative min-h-[220px]",children:[(ze=P.property)!=null&&ze.photo_url?e.jsx("img",{src:P.property.photo_url,alt:P.property.property_address??"",className:"absolute inset-0 h-full w-full object-cover"}):null,e.jsx("div",{className:"absolute inset-0 bg-gradient-to-r from-[hsl(var(--revival-navy))] via-transparent to-transparent"})]})]})}),e.jsxs(ua,{defaultValue:"journey",className:"mt-6",children:[e.jsx(ha,{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(lt=>e.jsx(Qt,{value:lt,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:lt},lt))}),e.jsxs(Jt,{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(Fz,{className:"h-4 w-4"})," The homeowner's journey, tracked end to end."]}),e.jsx(yKn,{counts:K})]}),e.jsxs(Jt,{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($,{size:"sm",disabled:!M.letter||h==="letter",onClick:q,children:[h==="letter"?e.jsx(Ht,{className:"h-3.5 w-3.5 mr-1.5 animate-spin"}):e.jsx(AT,{className:"h-3.5 w-3.5 mr-1.5"}),"Download print-ready PDF"]}),e.jsxs($,{size:"sm",variant:"outline",disabled:!M.letter,onClick:()=>y(lt=>!lt),children:[e.jsx(Ya,{className:"h-3.5 w-3.5 mr-1.5"})," ",g?"Close editor":"Edit letter"]}),e.jsxs($,{size:"sm",variant:"outline",disabled:l.isPending,onClick:()=>J("letter"),children:[e.jsx(dn,{className:"h-3.5 w-3.5 mr-1.5"})," Rewrite letter"]}),e.jsx(be,{value:d,onChange:lt=>u(lt.target.value),placeholder:"Optional instruction: e.g. shorter, warmer, mention the pool",className:"max-w-sm"})]}),g&&M.letter?e.jsx(nKt,{letter:M.letter,saving:o.isPending,onCancel:()=>y(!1),onSave:lt=>{o.mutate({id:s,patch:{content:{...M,letter:lt}}},{onSuccess:()=>y(!1)})}}):null,M.letter?e.jsx(B_t,{campaign:P,letter:M.letter,url:I,agent:D}):e.jsx("p",{className:"text-muted-foreground",children:"No letter generated yet."})]}),e.jsx(Jt,{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($,{size:"sm",className:"mt-3",disabled:!M.letter||h==="letter",onClick:q,children:[h==="letter"?e.jsx(Ht,{className:"h-3.5 w-3.5 mr-1.5 animate-spin"}):e.jsx(Bj,{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($,{size:"sm",className:"mt-3",disabled:h==="postcard",onClick:async()=>{var lt,Mt,Ft,Ts,js,zt,Nt,Ds,_t,Xs;m("postcard");try{await JWn({campaign:P,url:I,headline:(lt=M.landing)==null?void 0:lt.headline,subhead:(Mt=M.landing)==null?void 0:Mt.subheadline,message:(Ft=M.landing)==null?void 0:Ft.intro,photoDataUrl:((Ts=P.property)==null?void 0:Ts.photo_url)??null,agent:{name:(js=T.data)==null?void 0:js.name,title:(zt=T.data)==null?void 0:zt.title,phone:(Nt=T.data)==null?void 0:Nt.phone,email:(Ds=T.data)==null?void 0:Ds.email,website_url:(_t=T.data)==null?void 0:_t.website_url,brokerage_name:(Xs=T.data)==null?void 0:Xs.brokerage_name}}),ae.success("Postcard PDF downloaded")}catch{ae.error("Could not build the postcard PDF")}finally{m(null)}},children:[h==="postcard"?e.jsx(Ht,{className:"h-3.5 w-3.5 mr-1.5 animate-spin"}):e.jsx(Bj,{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:[((ke=P.property)==null?void 0:ke.mailing_address)??((Xe=P.property)==null?void 0:Xe.property_address)??"—",(Se=P.property)!=null&&Se.mailing_city?`, ${P.property.mailing_city} ${P.property.mailing_state??""} ${P.property.mailing_zip??""}`:""]})]})]})}),e.jsxs(Jt,{value:"landing",className:"mt-6 space-y-4",children:[e.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[e.jsxs($,{size:"sm",variant:"outline",disabled:l.isPending,onClick:()=>J("landing"),children:[e.jsx(dn,{className:"h-3.5 w-3.5 mr-1.5"})," Rewrite landing copy"]}),e.jsx($,{size:"sm",variant:"outline",asChild:!0,children:e.jsxs("a",{href:`/revival/${P.slug}`,target:"_blank",rel:"noreferrer",children:[e.jsx(Tr,{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(pKn,{campaignId:P.id,content:M,landingConfig:P.landing_config??{},propertyPhotoUrl:(Re=P.property)==null?void 0:Re.photo_url,saving:o.isPending,onSave:lt=>o.mutate({id:P.id,patch:lt})}),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(XN,{value:I,size:168,level:"M"})}),e.jsx("p",{className:"text-xs text-muted-foreground mt-3 max-w-[180px] break-all",children:I})]})]})]}),e.jsxs(Jt,{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($,{size:"sm",variant:"outline",disabled:l.isPending,onClick:()=>J("plan"),children:[e.jsx(dn,{className:"h-3.5 w-3.5 mr-1.5"})," Rewrite plan"]}),e.jsxs($,{size:"sm",variant:p?"secondary":"outline",onClick:()=>x(lt=>!lt),children:[e.jsx(Ya,{className:"h-3.5 w-3.5 mr-1.5"})," ",p?"Done editing":"Edit plan"]}),e.jsx($,{size:"sm",variant:"outline",asChild:!0,children:e.jsxs("a",{href:`/revival/${P.slug}/plan`,target:"_blank",rel:"noreferrer",children:[e.jsx(Tr,{className:"h-3.5 w-3.5 mr-1.5"})," View live plan"]})}),e.jsxs($,{size:"sm",className:"bg-accent text-accent-foreground hover:bg-accent/90",disabled:!M.plan||h==="plan",onClick:V,children:[h==="plan"?e.jsx(Ht,{className:"h-3.5 w-3.5 mr-1.5 animate-spin"}):e.jsx(Bj,{className:"h-3.5 w-3.5 mr-1.5"}),"Download plan PDF"]})]})]})}),p&&M.plan?e.jsx(xKn,{plan:M.plan,saving:o.isPending,onSave:lt=>o.mutate({id:P.id,patch:{content:{...M,plan:lt}}},{onSuccess:()=>ae.success("Plan updated")})}):null,M.plan?e.jsx("div",{className:"rounded-3xl bg-muted/40 p-4 sm:p-8",children:e.jsx(JUe,{plan:M.plan,property:{...P.property??{},seller_name:(Ae=P.property)==null?void 0:Ae.seller_name},agent:D,url:`${QUe()}/revival/${P.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(Jt,{value:"emails",className:"mt-6 space-y-3",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs($,{size:"sm",variant:"outline",disabled:l.isPending,onClick:()=>J("emails"),children:[e.jsx(dn,{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."})]}),(M.emails??[]).map((lt,Mt)=>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:lt.subject}),e.jsx($e,{variant:"outline",children:lt.key})]}),e.jsx("div",{className:"text-xs text-muted-foreground mt-0.5",children:lt.preview}),e.jsx("p",{className:"mt-3 text-sm whitespace-pre-wrap leading-relaxed",children:lt.body}),e.jsxs("div",{className:"mt-2 flex flex-wrap gap-1",children:[e.jsxs($,{size:"sm",onClick:()=>v(lt),children:[e.jsx(nn,{className:"h-3.5 w-3.5 mr-1.5"})," Preview & send"]}),e.jsxs($,{size:"sm",variant:"ghost",onClick:()=>{navigator.clipboard.writeText(`${lt.subject} ${lt.body}`),ae.success("Email copied")},children:[e.jsx(Ca,{className:"h-3.5 w-3.5 mr-1.5"})," Copy"]})]})]},Mt))]}),e.jsxs(Jt,{value:"texts",className:"mt-6 space-y-3",children:[e.jsxs($,{size:"sm",variant:"outline",disabled:l.isPending,onClick:()=>J("sms"),children:[e.jsx(dn,{className:"h-3.5 w-3.5 mr-1.5"})," Rewrite texts"]}),e.jsx("div",{className:"grid gap-3 sm:grid-cols-2",children:(M.sms??[]).map((lt,Mt)=>e.jsxs("div",{className:"revival-tile p-5",children:[e.jsx($e,{variant:"outline",children:lt.key}),e.jsx("p",{className:"mt-2 text-sm leading-relaxed",children:lt.body}),e.jsxs($,{size:"sm",variant:"ghost",className:"mt-2",onClick:()=>{navigator.clipboard.writeText(lt.body),ae.success("Text copied")},children:[e.jsx(Ca,{className:"h-3.5 w-3.5 mr-1.5"})," Copy"]})]},Mt))})]}),e.jsxs(Jt,{value:"scripts",className:"mt-6 space-y-3",children:[e.jsxs($,{size:"sm",variant:"outline",disabled:l.isPending,onClick:()=>J("scripts"),children:[e.jsx(dn,{className:"h-3.5 w-3.5 mr-1.5"})," Rewrite scripts"]}),[["Phone script",(Be=M.scripts)==null?void 0:Be.phone],["Voicemail",(qe=M.scripts)==null?void 0:qe.voicemail],["Video script",(Ke=M.scripts)==null?void 0:Ke.video],["Door knock",(Ze=M.scripts)==null?void 0:Ze.door_knock]].map(([lt,Mt])=>Mt?e.jsxs("div",{className:"revival-tile p-5",children:[e.jsx("div",{className:"font-semibold",children:lt}),e.jsx("p",{className:"mt-2 text-sm whitespace-pre-wrap leading-relaxed",children:Mt})]},lt):null),(((Ue=M.scripts)==null?void 0:Ue.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:(((et=M.scripts)==null?void 0:et.objections)??[]).map((lt,Mt)=>e.jsxs("div",{children:[e.jsxs("div",{className:"text-sm font-medium",children:["“",lt.objection,"”"]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:lt.response})]},Mt))})]}):null]}),e.jsx(Jt,{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(se,{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(Tn,{checked:P.published,onCheckedChange:lt=>o.mutate({id:P.id,patch:{published:lt}})})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{className:"font-semibold",children:"Campaign name"}),e.jsx(be,{defaultValue:P.name,onBlur:lt=>lt.target.value!==P.name&&o.mutate({id:P.id,patch:{name:lt.target.value}})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{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:bKn.map(lt=>e.jsxs("button",{type:"button",onClick:()=>o.mutate({id:P.id,patch:{theme:lt.id}}),className:`text-left rounded-xl border p-3 transition-all ${(P.theme??"estate")===lt.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:[lt.swatch.map(Mt=>e.jsx("span",{className:"h-4 w-4 rounded-full border border-black/10",style:{background:Mt}},Mt)),e.jsx("span",{className:"font-medium ml-1",children:lt.name})]}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1.5",children:lt.description})]},lt.id))})]}),e.jsxs("div",{className:"flex items-center justify-between border-t border-border pt-4",children:[e.jsxs("div",{children:[e.jsxs(se,{className:"font-semibold flex items-center gap-1.5",children:[e.jsx($3,{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(Tn,{checked:!!P.alert_on_engagement,onCheckedChange:lt=>o.mutate({id:P.id,patch:{alert_on_engagement:lt}})})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs(se,{className:"font-semibold flex items-center gap-1.5",children:[e.jsx(nn,{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(vs,{value:P.drip_campaign_id??"none",onValueChange:lt=>o.mutate({id:P.id,patch:{drip_campaign_id:lt==="none"?null:lt}}),children:[e.jsx(gs,{children:e.jsx(bs,{placeholder:"No drip campaign"})}),e.jsxs(ys,{children:[e.jsx(Ye,{value:"none",children:"No drip campaign"}),(N.data??[]).map(lt=>e.jsx(Ye,{value:lt.id,children:lt.name},lt.id))]})]}),!A&&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($,{size:"sm",className:"mt-3",disabled:C.isPending,onClick:()=>C.mutate(),children:C.isPending?"Installing…":"Install & assign to this campaign"})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{className:"font-semibold",children:"Internal notes"}),e.jsx(Is,{rows:4,defaultValue:((Qe=P.branding)==null?void 0:Qe.notes)??"",onBlur:lt=>o.mutate({id:P.id,patch:{branding:{...P.branding,notes:lt.target.value}}})})]}),e.jsx("div",{className:"border-t border-border pt-4",children:e.jsxs($,{variant:"destructive",size:"sm",onClick:async()=>{await Yi("Delete this campaign? The landing page will stop working.")&&c.mutate(P.id,{onSuccess:()=>t("/apps/listing-revival")})},children:[e.jsx(Pn,{className:"h-3.5 w-3.5 mr-1.5"})," Delete campaign"]})})]})})]}),M.letter?e.jsx("div",{ref:B,"aria-hidden":!0,className:"pointer-events-none fixed left-[-10000px] top-0 w-[816px]",children:e.jsx(B_t,{campaign:P,letter:M.letter,url:I,agent:D,className:"shadow-none"})}):null,M.plan?e.jsx("div",{ref:W,"aria-hidden":!0,className:"pointer-events-none fixed left-[-10000px] top-0 w-[816px]",children:e.jsx(JUe,{plan:M.plan,property:{...P.property??{},seller_name:(Ge=P.property)==null?void 0:Ge.seller_name},agent:D,url:`${QUe()}/revival/${P.slug}/plan`})}):null]}),e.jsx(vKn,{open:!!b,onOpenChange:lt=>!lt&&v(null),campaignId:P.id,email:b,ctaUrl:I,seller:{name:(nt=P.property)==null?void 0:nt.seller_name,email:(ft=P.property)==null?void 0:ft.seller_email}})]})}function rKt(){const{user:s}=_s();return ht({queryKey:["fsbo-campaigns",s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await U.from("fsbo_campaigns").select("*, property:fsbo_properties(*)").order("created_at",{ascending:!1});if(n)throw n;return t??[]}})}function wKn(s){return ht({queryKey:["fsbo-campaign",s],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await U.from("fsbo_campaigns").select("*, property:fsbo_properties(*)").eq("id",s).maybeSingle();if(n)throw n;return t??null}})}function aKt(){const{user:s}=_s();return ht({queryKey:["fsbo-properties",s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await U.from("fsbo_properties").select("*").order("created_at",{ascending:!1});if(n)throw n;return t??[]}})}function mQe(){const{user:s}=_s();return ht({queryKey:["fsbo-leads",s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await U.from("fsbo_leads").select("*").order("created_at",{ascending:!1});if(n)throw n;return t??[]}})}function jKn(){const{user:s}=_s();return ht({queryKey:["fsbo-tasks",s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await U.from("fsbo_tasks").select("*").order("due_date",{ascending:!0});if(n)throw n;return t??[]}})}function pQe(){const{user:s}=_s();return ht({queryKey:["fsbo-events",s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await U.from("fsbo_events").select("*").order("created_at",{ascending:!1}).limit(1e3);if(n)throw n;return t??[]}})}function fQe(){const s=ts(),t=()=>{["fsbo-campaigns","fsbo-campaign","fsbo-properties","fsbo-leads","fsbo-tasks","fsbo-events"].forEach(o=>s.invalidateQueries({queryKey:[o]}))},n=yt({mutationFn:async o=>{const{data:c,error:d}=await U.functions.invoke("fsbo-generate",{body:o});if(d)throw d;if(c!=null&&c.error)throw new Error(String(c.error));return c},onSuccess:t,onError:o=>ae.error(o.message)}),r=yt({mutationFn:async o=>{const{error:c}=await U.from("fsbo_campaigns").update(o.patch).eq("id",o.id);if(c)throw c},onSuccess:()=>{t(),ae.success("Saved")},onError:o=>ae.error(o.message)}),a=yt({mutationFn:async o=>{const{error:c}=await U.from("fsbo_campaigns").delete().eq("id",o);if(c)throw c},onSuccess:()=>{t(),ae.success("Campaign deleted")},onError:o=>ae.error(o.message)}),i=yt({mutationFn:async o=>{const{error:c}=await U.from("fsbo_campaigns").update({status:o.archived?"archived":"draft",published:!o.archived}).eq("id",o.id);if(c)throw c;return o},onSuccess:o=>{t(),ae.success(o.archived?"Campaign archived":"Campaign restored")},onError:o=>ae.error(o.message)}),l=yt({mutationFn:async o=>{const{error:c}=await U.from("fsbo_tasks").update({completed_at:o.done?new Date().toISOString():null}).eq("id",o.id);if(c)throw c},onSuccess:t,onError:o=>ae.error(o.message)});return{generate:n,saveCampaign:r,deleteCampaign:a,archiveCampaign:i,toggleTask:l,invalidate:t}}function NKn(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 e3e=[{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."}],iKt=[{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"}],kKn=[{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"}],SKn=[{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"}],CKn=["Need to sell quickly","Want to maximize net proceeds","Testing the market","Already bought another home","Relocating","Downsizing / Upsizing","Estate sale","Other"],AKn=[{value:"email",label:"Email"},{value:"phone",label:"Phone"},{value:"text",label:"Text"}];function eqe(s){return s.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,48)}function EKn(s){const t=eqe(s)||"property",n=Math.random().toString(36).slice(2,7);return`${t}-${n}`}function oKt(s){return s==null?"—":`$${Number(s).toLocaleString("en-US",{maximumFractionDigits:0})}`}function TKn(){return typeof window>"u"?"":window.location.origin}function lKt(s){return`${TKn()}/fsbo/${s}`}const q_t="fsbo_breakthrough";function MKn(){const{user:s,loading:t,isAdmin:n}=_s(),{data:r}=ht({queryKey:["feature-entitlement",q_t,s==null?void 0:s.id],enabled:!!s&&!n,staleTime:5*60*1e3,queryFn:async()=>{const{data:a,error:i}=await U.from("feature_entitlements").select("enabled, expires_at, tier").eq("user_id",s.id).eq("feature_key",q_t).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 LKn=[{id:"dashboard",label:"Dashboard",icon:zp},{id:"campaigns",label:"Campaigns",icon:dn},{id:"properties",label:"Properties",icon:sa},{id:"letters",label:"Letters",icon:nn},{id:"landing",label:"Landing Pages",icon:Gl},{id:"guides",label:"Seller Guides",icon:Wr},{id:"followup",label:"Follow Up",icon:v0},{id:"analytics",label:"Analytics",icon:ml},{id:"templates",label:"Templates",icon:nw},{id:"settings",label:"Settings",icon:G3}];function Wk({label:s,value:t,icon:n,delay:r=0,hint:a}){return e.jsxs(jr.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 PKn(){const s=Vn(),[t,n]=j.useState("dashboard"),[r,a]=j.useState(""),[i,l]=j.useState(!1),[o,c]=j.useState(null),d=MKn(),u=rKt(),h=aKt(),m=mQe(),p=jKn(),x=pQe(),{toggleTask:g,archiveCampaign:y,deleteCampaign:b}=fQe(),v=u.data??[],N=m.data??[],C=x.data??[],A=p.data??[],T=j.useMemo(()=>{const V=K=>C.filter(Q=>Q.event_type===K).length;return{properties:(h.data??[]).length,campaigns:v.length,letters:v.filter(K=>{var Q;return(Q=K.content)==null?void 0:Q.letter}).length,qr:V("qr_scan"),visits:V("page_view"),guideViews:V("guide_view"),leads:N.length,appointments:V("appointment"),listed:N.filter(K=>K.temperature==="hot").length,hot:N.filter(K=>K.temperature==="hot").length}},[v,N,C,h.data]),P=j.useMemo(()=>{const V=[];for(let K=13;K>=0;K--){const Q=new Date(Date.now()-K*864e5),J=Q.toISOString().slice(0,10);V.push({day:Hs(Q,"MMM d"),visits:C.filter(ce=>ce.event_type==="page_view"&&ce.created_at.startsWith(J)).length,scans:C.filter(ce=>ce.event_type==="qr_scan"&&ce.created_at.startsWith(J)).length,leads:N.filter(ce=>ce.created_at.startsWith(J)).length})}return V},[C,N]),M=V=>V.status==="archived",I=v.filter(V=>{var Q,J;if(i?!M(V):M(V))return!1;const K=r.trim().toLowerCase();return K?`${V.name} ${((Q=V.property)==null?void 0:Q.property_address)??""} ${((J=V.property)==null?void 0:J.seller_name)??""}`.toLowerCase().includes(K):!0}),D=v.filter(M).length,B=V=>s(`/apps/fsbo-breakthrough/campaigns/${V}`),q=V=>{navigator.clipboard.writeText(lKt(V)),ae.success("Landing page link copied")},W=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(Vr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(be,{value:r,onChange:K=>a(K.target.value),placeholder:"Search campaigns…",className:"pl-9"})]}),e.jsxs($,{variant:i?"default":"outline",size:"sm",onClick:()=>l(K=>!K),children:[e.jsx(Am,{className:"h-3.5 w-3.5 mr-1.5"}),i?"Viewing archived":`Archived (${D})`]})]}),I.length===0?e.jsx("div",{className:"fsbo-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,Q)=>{var ee,le,he,ve;const J=e3e.find(ge=>ge.id===K.style),ce=N.filter(ge=>ge.campaign_id===K.id).length,ue=C.filter(ge=>ge.campaign_id===K.id&&ge.event_type==="page_view").length,ne=M(K);return e.jsxs(jr.div,{initial:{opacity:0,y:14},animate:{opacity:1,y:0},transition:{delay:Math.min(Q*.04,.3),duration:.4},className:Tt("fsbo-tile overflow-hidden",ne&&"opacity-80"),children:[e.jsxs("div",{className:"h-28 bg-muted relative",children:[(ee=K.property)!=null&&ee.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 fsbo-dark grid place-items-center",children:e.jsx(sa,{className:"h-7 w-7 text-accent"})}),e.jsx($e,{className:"absolute top-3 left-3 bg-background/90 text-foreground border-0",children:(J==null?void 0:J.name)??K.style}),ne?e.jsx($e,{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:((le=K.property)==null?void 0:le.property_address)??K.name}),e.jsx("div",{className:"text-sm text-muted-foreground",children:((he=K.property)==null?void 0:he.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(Gl,{className:"h-3.5 w-3.5"}),ue]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(qn,{className:"h-3.5 w-3.5"}),ce]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(sa,{className:"h-3.5 w-3.5"}),((ve=K.property)==null?void 0:ve.property_type)??"—"]})]}),e.jsxs("div",{className:"mt-4 flex gap-2",children:[e.jsxs($,{size:"sm",className:"flex-1",onClick:()=>B(K.id),children:["Open ",e.jsx(ni,{className:"h-3.5 w-3.5 ml-1"})]}),e.jsx($,{size:"sm",variant:"outline",onClick:()=>q(K.slug),children:e.jsx(Ca,{className:"h-3.5 w-3.5"})}),e.jsx($,{size:"sm",variant:"outline",asChild:!0,children:e.jsx("a",{href:`/fsbo/${K.slug}`,target:"_blank",rel:"noreferrer",children:e.jsx(Tr,{className:"h-3.5 w-3.5"})})}),e.jsxs(Hd,{children:[e.jsx(Gd,{asChild:!0,children:e.jsx($,{size:"sm",variant:"outline",children:e.jsx(cy,{className:"h-3.5 w-3.5"})})}),e.jsxs(Md,{align:"end",children:[e.jsx(Na,{onClick:()=>y.mutate({id:K.id,archived:!ne}),children:ne?e.jsxs(e.Fragment,{children:[e.jsx(hT,{className:"h-4 w-4 mr-2"})," Restore campaign"]}):e.jsxs(e.Fragment,{children:[e.jsx(Am,{className:"h-4 w-4 mr-2"})," Archive campaign"]})}),e.jsx(S0,{}),e.jsxs(Na,{className:"text-destructive focus:text-destructive",onClick:()=>{var ge;return c({id:K.id,name:((ge=K.property)==null?void 0:ge.property_address)??K.name})},children:[e.jsx(Pn,{className:"h-4 w-4 mr-2"})," Delete permanently"]})]})]})]})]})]},K.id)})}),e.jsx(Ll,{open:!!o,onOpenChange:K=>!K&&c(null),children:e.jsxs(yl,{children:[e.jsxs(vl,{children:[e.jsx(_l,{children:"Delete this campaign?"}),e.jsxs(wl,{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(bl,{children:[e.jsx(jl,{children:"Cancel"}),e.jsx(fl,{className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",onClick:()=>{o&&b.mutate(o.id),c(null)},children:"Delete permanently"})]})]})})]});return!d.isLoading&&!d.hasAccess?e.jsx(Ks,{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(dn,{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(Ks,{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(jr.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($,{size:"lg",className:"bg-accent text-accent-foreground hover:bg-accent/90",onClick:()=>s("/apps/fsbo-breakthrough/new"),children:[e.jsx(sn,{className:"h-4 w-4 mr-1"})," New Campaign"]}),e.jsx($,{size:"lg",variant:"outline",className:"bg-transparent text-white border-white/25 hover:bg-white/10",onClick:()=>n("campaigns"),children:"View campaigns"})]})]})]}),e.jsxs(ua,{value:t,onValueChange:n,className:"mt-6",children:[e.jsx(ha,{className:"flex w-full overflow-x-auto no-scrollbar justify-start bg-transparent p-0 gap-2 h-auto",children:LKn.map(V=>e.jsxs(Qt,{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(Jt,{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(Wk,{label:"Properties",value:T.properties,icon:sa,delay:0}),e.jsx(Wk,{label:"Campaigns",value:T.campaigns,icon:dn,delay:.04}),e.jsx(Wk,{label:"Letters",value:T.letters,icon:nn,delay:.08}),e.jsx(Wk,{label:"QR Scans",value:T.qr,icon:Rx,delay:.12}),e.jsx(Wk,{label:"Page Visits",value:T.visits,icon:Gl,delay:.16}),e.jsx(Wk,{label:"Guide Views",value:T.guideViews,icon:Wr,delay:.2}),e.jsx(Wk,{label:"Seller Leads",value:T.leads,icon:qn,delay:.24}),e.jsx(Wk,{label:"Appointments",value:T.appointments,icon:gy,delay:.28}),e.jsx(Wk,{label:"Hot Leads",value:T.hot,icon:yd,delay:.32,hint:"Score 75+"}),e.jsx(Wk,{label:"Listings Won",value:T.listed,icon:pl,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(Ob,{width:"100%",height:"100%",children:e.jsxs(lYe,{data:P,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(AO,{strokeDasharray:"3 3",stroke:"hsl(var(--border))",vertical:!1}),e.jsx(k1,{dataKey:"day",tick:{fontSize:11},stroke:"hsl(var(--muted-foreground))"}),e.jsx(S1,{allowDecimals:!1,tick:{fontSize:11},stroke:"hsl(var(--muted-foreground))",width:28}),e.jsx(yf,{contentStyle:{borderRadius:12,border:"1px solid hsl(var(--border))"}}),e.jsx(Fb,{type:"monotone",dataKey:"visits",stroke:"hsl(var(--primary))",fill:"url(#fsboVisits)",strokeWidth:2}),e.jsx(Fb,{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:[A.filter(V=>!V.completed_at).slice(0,5).map(V=>e.jsxs("div",{className:"flex items-start gap-3 p-3 rounded-lg bg-muted/40",children:[e.jsx(ui,{checked:!!V.completed_at,onCheckedChange:K=>g.mutate({id:V.id,done:!!K})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"text-sm font-medium",children:V.title}),e.jsx("div",{className:"text-xs text-muted-foreground",children:V.detail}),V.due_date?e.jsxs("div",{className:"text-xs text-muted-foreground mt-1",children:["Due ",V.due_date]}):null]})]},V.id)),!A.filter(V=>!V.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(Jt,{value:"campaigns",className:"mt-6",children:W("No campaigns yet. Start with a new FSBO property.")}),e.jsx(Jt,{value:"properties",className:"mt-6",children:e.jsx("div",{className:"space-y-3",children:(h.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:(h.data??[]).map(V=>e.jsxs("div",{className:"fsbo-tile p-4",children:[e.jsx("div",{className:"font-semibold",children:V.property_address}),e.jsxs("div",{className:"text-sm text-muted-foreground",children:[V.city,V.city&&V.state?", ":"",V.state]}),e.jsx("div",{className:"mt-2 text-sm",children:V.seller_name||"—"}),e.jsxs("div",{className:"mt-1 text-sm text-muted-foreground",children:["Est. value ",oKt(V.estimated_value)]})]},V.id))})})}),e.jsx(Jt,{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:A.map(V=>e.jsxs("div",{className:Tt("flex items-start gap-3 p-3 rounded-lg",V.completed_at?"bg-muted/30":"bg-muted/40"),children:[e.jsx(ui,{checked:!!V.completed_at,onCheckedChange:K=>g.mutate({id:V.id,done:!!K})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:Tt("text-sm font-medium",V.completed_at&&"line-through text-muted-foreground"),children:V.title}),e.jsx("div",{className:"text-xs text-muted-foreground",children:V.detail}),e.jsxs("div",{className:"text-xs text-muted-foreground mt-1 capitalize",children:[V.channel," · ",V.due_date??"No due date"]})]})]},V.id))})]})}),e.jsx(Jt,{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:C.slice(0,50).map(V=>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:V.event_type.replace(/_/g," ")}),e.jsx("div",{className:"text-xs text-muted-foreground",children:Hs(new Date(V.created_at),"MMM d, h:mm a")})]},V.id))})]})}),e.jsx(Jt,{value:"letters",className:"mt-6",children:W("Generate letter content by creating a campaign first.")}),e.jsx(Jt,{value:"landing",className:"mt-6",children:W("Generate landing pages by creating a campaign first.")}),e.jsx(Jt,{value:"guides",className:"mt-6",children:W("Generate seller guides by creating a campaign first.")}),e.jsx(Jt,{value:"templates",className:"mt-6",children:e.jsx("div",{className:"grid gap-3 md:grid-cols-2 lg:grid-cols-3",children:iKt.map(V=>e.jsxs("div",{className:"fsbo-tile p-4",children:[e.jsx("div",{className:"font-semibold",children:V.name}),e.jsx("div",{className:"text-sm text-muted-foreground",children:V.note})]},V.id))})}),e.jsx(Jt,{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."})]})})]})]})})}const V_t=["Add the property","Choose the campaign voice","Generate everything"];function IKn(){const s=Vn(),{user:t}=_s(),{generate:n,invalidate:r}=fQe(),[a,i]=j.useState(0),[l,o]=j.useState(!1),[c,d]=j.useState(e3e[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:""}),x=(v,N)=>p(C=>({...C,[v]:N})),g=a===0?m.property_address.trim().length>3:!0,y=async()=>{if(t){o(!0);try{const{data:v,error:N}=await U.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:C,error:A}=await U.from("fsbo_campaigns").insert({owner_user_id:t.id,property_id:v.id,name:m.property_address.trim(),slug:EKn(m.property_address),style:c,tone:u,status:"generating",published:!0}).select().single();if(A)throw A;await n.mutateAsync({campaignId:C.id}),r(),ae.success("Campaign built — everything is ready."),s(`/apps/fsbo-breakthrough/campaigns/${C.id}`)}catch(v){ae.error(v instanceof Error?v.message:"Could not create the campaign")}finally{o(!1)}}},b=(v,N,C={})=>e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{className:"text-xs uppercase tracking-wider text-muted-foreground",children:N}),e.jsx(be,{value:m[v],onChange:A=>x(v,A.target.value),...C})]});return e.jsx(Ks,{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($,{variant:"ghost",size:"sm",className:"gap-2 mb-4",onClick:()=>s("/apps/fsbo-breakthrough"),children:[e.jsx(ka,{className:"h-4 w-4"})," Back to By-Owner Breakthrough"]}),e.jsx("div",{className:"flex items-center gap-3 mb-6",children:V_t.map((v,N)=>e.jsxs("div",{className:"flex items-center gap-3 flex-1",children:[e.jsx("div",{className:Tt("h-9 w-9 rounded-full grid place-items-center text-sm font-bold shrink-0 transition-colors",Nx("property_type",v.target.value),children:kKn.map(v=>e.jsx("option",{value:v.value,children:v.label},v.value))})]}),b("seller_name","Seller name"),b("seller_email","Seller email",{type:"email"}),b("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(se,{className:"text-xs uppercase tracking-wider text-muted-foreground",children:"Property photo"}),e.jsx(xte,{value:m.photo_url,onChange:v=>x("photo_url",v??""),label:"Property photo",prefix:"fsbo-property"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{className:"text-xs uppercase tracking-wider text-muted-foreground",children:"Agent notes"}),e.jsx(Is,{rows:6,value:m.notes,onChange:v=>x("notes",v.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:e3e.map(v=>e.jsxs("button",{onClick:()=>d(v.id),className:Tt("text-left p-5 rounded-xl border transition-all relative overflow-hidden",c===v.id?"border-primary bg-primary/5":"border-border bg-card hover:border-primary/30"),children:[e.jsx("div",{className:Tt("absolute inset-x-0 top-0 h-1 bg-gradient-to-r",v.accent)}),e.jsx("div",{className:"font-semibold",children:v.name}),e.jsx("div",{className:"text-xs text-muted-foreground mt-1",children:v.tagline}),e.jsx("div",{className:"text-sm text-muted-foreground mt-2",children:v.description}),e.jsx("div",{className:"mt-3 text-xs text-primary font-medium",children:v.previewHeadline}),e.jsx("div",{className:"text-xs text-muted-foreground",children:v.previewBody})]},v.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:iKt.map(v=>e.jsxs("button",{onClick:()=>h(v.id),className:Tt("p-4 rounded-xl border text-left transition-all",u===v.id?"border-primary bg-primary/5":"border-border bg-card hover:border-primary/30"),children:[e.jsx("div",{className:"font-medium",children:v.name}),e.jsx("div",{className:"text-xs text-muted-foreground",children:v.note})]},v.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(wm,{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($,{size:"lg",onClick:y,disabled:l,children:[l?e.jsx(Ht,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(dn,{className:"h-4 w-4 mr-2"}),"Generate campaign"]})})]}):null]},a)}),e.jsxs("div",{className:"flex justify-between mt-6",children:[e.jsxs($,{variant:"outline",disabled:a===0,onClick:()=>i(v=>v-1),children:[e.jsx(ka,{className:"h-4 w-4 mr-1"})," Back"]}),a<2&&e.jsxs($,{disabled:!g,onClick:()=>i(v=>v+1),children:["Next ",e.jsx(ni,{className:"h-4 w-4 ml-1"})]})]})]})})}function DKn(){var ee,le,he,ve,ge,fe,je,Ee,Me,De,ze,ke,Xe,Se,Re,Ae;const{id:s}=Vi(),t=Vn(),{user:n}=_s(),r=wKn(s),a=pQe(),i=mQe(),{generate:l,saveCampaign:o,deleteCampaign:c}=fQe(),[d,u]=j.useState(""),[h,m]=j.useState(!1),[p,x]=j.useState("letter"),[g,y]=j.useState(!1),b=r.data,v=(b==null?void 0:b.content)??{},N=b?lKt(b.slug):"",C=ht({queryKey:["fsbo-agent-profile",n==null?void 0:n.id],enabled:!!n,queryFn:async()=>{const{data:Be}=await U.from("profiles").select("name, email, phone, avatar_url, brokerage_name, website_url, title").eq("id",n.id).maybeSingle();return Be}}),A={name:(ee=C.data)==null?void 0:ee.name,title:(le=C.data)==null?void 0:le.title,phone:(he=C.data)==null?void 0:he.phone,email:(ve=C.data)==null?void 0:ve.email,website_url:(ge=C.data)==null?void 0:ge.website_url,avatar_url:(fe=C.data)==null?void 0:fe.avatar_url,brokerage_name:(je=C.data)==null?void 0:je.brokerage_name},T=j.useRef(null),P=j.useRef(null),M=j.useMemo(()=>{var Ke,Ze;const Be=(a.data??[]).filter(Ue=>Ue.campaign_id===s),qe={};return Be.forEach(Ue=>{qe[Ue.event_type]=(qe[Ue.event_type]??0)+1}),qe.letter=v.letter?1:0,qe.email=((Ke=v.emails)==null?void 0:Ke.length)??0,qe.sms=((Ze=v.sms)==null?void 0:Ze.length)??0,qe.form_submit=(i.data??[]).filter(Ue=>Ue.campaign_id===s).length,qe},[a.data,i.data,s,v]),I=async()=>{var Be;if(T.current){m(!0);try{const qe=await hU(T.current,{pixelRatio:2}),Ke=document.createElement("a");Ke.href=qe;const Ze=eqe(((Be=b==null?void 0:b.property)==null?void 0:Be.property_address)??"letter");Ke.download=`${Ze||"letter"}.png`,Ke.click(),ae.success("Letter image downloaded")}catch{ae.error("Could not download letter")}finally{m(!1)}}},D=async()=>{var Be;if(P.current){m(!0);try{const qe=await hU(P.current,{pixelRatio:2}),Ke=document.createElement("a");Ke.href=qe;const Ze=eqe(((Be=b==null?void 0:b.property)==null?void 0:Be.property_address)??"guide");Ke.download=`${Ze||"guide"}-guide.png`,Ke.click(),ae.success("Guide image downloaded")}catch{ae.error("Could not download guide")}finally{m(!1)}}},B=Be=>{var Qe;const qe=document.querySelector("[data-print-root]"),Ke=qe?document.createElement("div"):null;qe&&Ke&&((Qe=qe.parentNode)==null||Qe.insertBefore(Ke,qe),document.body.appendChild(qe));const Ze=document.title;document.title=Be,document.body.classList.add("printing-doc");let Ue=!1;const et=()=>{Ue||(Ue=!0,qe&&(Ke!=null&&Ke.parentNode)&&Ke.parentNode.replaceChild(qe,Ke),document.body.classList.remove("printing-doc"),document.title=Ze,window.removeEventListener("afterprint",et))};window.addEventListener("afterprint",et);try{window.print()}finally{setTimeout(et,1e3)}},q=(((Ee=b==null?void 0:b.property)==null?void 0:Ee.property_address)??"Campaign").replace(/[\\/:*?"<>|]/g,"-").trim(),W=Be=>{s&&(l.mutate({campaignId:s,section:Be,instruction:d}),u(""))};if(r.isLoading)return e.jsx(Ks,{title:"Campaign",children:e.jsx("div",{className:"grid place-items-center py-24",children:e.jsx(Ht,{className:"h-6 w-6 animate-spin"})})});if(!b)return e.jsx(Ks,{title:"Campaign",children:e.jsx("div",{className:"py-12 text-center text-muted-foreground",children:"Campaign not found."})});const V=e3e.find(Be=>Be.id===b.style),K=v.letter,Q=v.landing,J=v.guide,ce=v.emails??[],ue=v.sms??[],ne=v.scripts;return e.jsx(Ks,{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($,{variant:"ghost",size:"sm",className:"gap-2 mb-4",onClick:()=>t("/apps/fsbo-breakthrough"),children:[e.jsx(ka,{className:"h-4 w-4"})," Back to By-Owner Breakthrough"]}),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:[(V==null?void 0:V.name)??b.style," · ",b.status]}),e.jsx("h1",{className:"fsbo-serif text-2xl sm:text-3xl mt-1",children:((Me=b.property)==null?void 0:Me.property_address)??b.name}),e.jsxs("p",{className:"text-white/70 mt-1",children:[((De=b.property)==null?void 0:De.seller_name)||"Homeowner"," · ",(ze=b.property)==null?void 0:ze.city,(ke=b.property)!=null&&ke.city&&((Xe=b.property)!=null&&Xe.state)?", ":"",(Se=b.property)==null?void 0:Se.state,(Re=b.property)!=null&&Re.estimated_value?` · Est. ${oKt(b.property.estimated_value)}`:""]})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx($,{size:"sm",variant:"outline",className:"bg-white/10 border-white/20 text-white hover:bg-white/20",asChild:!0,children:e.jsxs("a",{href:N,target:"_blank",rel:"noreferrer",children:[e.jsx(Gl,{className:"h-4 w-4 mr-1"})," Preview"]})}),e.jsxs($,{size:"sm",variant:"outline",className:"bg-white/10 border-white/20 text-white hover:bg-white/20",onClick:()=>{navigator.clipboard.writeText(N),ae.success("Copied")},children:[e.jsx(Ca,{className:"h-4 w-4 mr-1"})," Copy link"]}),e.jsxs($,{size:"sm",variant:"outline",className:"bg-white/10 border-white/20 text-white hover:bg-white/20",onClick:()=>W(),children:[e.jsx(Wi,{className:"h-4 w-4 mr-1"})," Regenerate"]}),e.jsx($,{size:"sm",variant:"outline",className:"bg-white/10 border-white/20 text-white hover:bg-white/20 hover:text-destructive",onClick:()=>c.mutate(b.id),children:e.jsx(Pn,{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:M.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:M.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:M.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:M.guide_view??0})]})]})]}),e.jsxs("div",{className:"mt-4 flex gap-2",children:[e.jsx(be,{placeholder:"Tell AI what to change (e.g., 'make it shorter', 'focus on luxury buyers')...",value:d,onChange:Be=>u(Be.target.value),className:"max-w-xl"}),e.jsx($,{variant:"outline",onClick:()=>W(),disabled:l.isPending,children:l.isPending?e.jsx(Ht,{className:"h-4 w-4 animate-spin"}):e.jsx(dn,{className:"h-4 w-4"})})]}),e.jsxs(ua,{value:p,onValueChange:x,className:"mt-6",children:[e.jsx(ha,{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:nn},{id:"landing",label:"Landing Page",icon:Gl},{id:"guide",label:"Seller Guide",icon:Wr},{id:"scripts",label:"Scripts & Drip",icon:Ji},{id:"leads",label:"Leads",icon:ya}].map(Be=>e.jsxs(Qt,{value:Be.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(Be.icon,{className:"h-3.5 w-3.5 mr-1.5"})," ",Be.label]},Be.id))}),e.jsxs(Jt,{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($,{size:"sm",variant:"outline",onClick:()=>y(Be=>!Be),disabled:!K,children:[e.jsx(Ya,{className:"h-4 w-4 mr-1"})," ",g?"Close editor":"Edit letter"]}),e.jsxs($,{size:"sm",variant:"outline",onClick:I,disabled:h,children:[e.jsx(Bj,{className:"h-4 w-4 mr-1"})," Download image"]}),e.jsxs($,{size:"sm",variant:"outline",onClick:()=>B(q),children:[e.jsx(AT,{className:"h-4 w-4 mr-1"})," Print"]})]})]}),g&&K?e.jsx("div",{className:"mb-6 print:hidden","data-print-hide":!0,children:e.jsx(nKt,{letter:K,saving:o.isPending,onCancel:()=>y(!1),onSave:Be=>{o.mutate({id:s,patch:{content:{...v,letter:Be}}},{onSuccess:()=>y(!1)})}})}):null,e.jsx("div",{className:"fsbo-tile p-6 max-w-3xl mx-auto",children:e.jsxs("div",{ref:T,"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:[A.name?e.jsx("div",{className:"font-bold text-lg",children:A.name}):null,A.title?e.jsx("div",{className:"text-sm text-gray-600",children:A.title}):null,A.brokerage_name?e.jsx("div",{className:"text-sm text-gray-600",children:A.brokerage_name}):null]}),A.avatar_url?e.jsx("img",{src:A.avatar_url,alt:A.name??"",className:"h-16 w-16 rounded-full object-cover"}):null]}),K?e.jsxs("div",{className:"space-y-4 text-[15px] leading-relaxed",children:[e.jsx("div",{children:K.greeting}),K.paragraphs.map((Be,qe)=>e.jsx("p",{children:Be},qe)),e.jsx("div",{children:K.closing}),e.jsx("div",{className:"font-semibold","data-print-keep":!0,children:K.signature}),e.jsx("div",{className:"text-sm text-gray-600 italic mt-4","data-print-keep":!0,children:K.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(XN,{value:N,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:N})]})]})]})})]}),e.jsxs(Jt,{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($,{size:"sm",variant:"outline",asChild:!0,children:e.jsxs("a",{href:N,target:"_blank",rel:"noreferrer",children:[e.jsx(Tr,{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:Q?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"text-sm uppercase tracking-wider text-primary",children:Q.eyebrow}),e.jsx("h2",{className:"text-3xl font-bold",children:Q.headline}),e.jsx("p",{className:"text-lg text-muted-foreground",children:Q.subheadline}),e.jsx("p",{className:"text-foreground",children:Q.intro}),e.jsx("div",{className:"grid gap-3 sm:grid-cols-2 mt-4",children:Q.discover.map((Be,qe)=>e.jsxs("div",{className:"bg-muted/40 p-4 rounded-lg",children:[e.jsx("div",{className:"font-semibold",children:Be.title}),e.jsx("div",{className:"text-sm text-muted-foreground",children:Be.body})]},qe))}),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:['"',Q.testimonial.quote,'"']}),e.jsxs("div",{className:"text-sm font-semibold mt-2",children:["— ",Q.testimonial.author]})]}),e.jsx("div",{className:"mt-4",children:e.jsx($,{size:"lg",children:Q.cta})})]}):e.jsx("div",{className:"text-muted-foreground",children:"Landing page content not generated yet."})})]}),e.jsxs(Jt,{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($,{size:"sm",variant:"outline",onClick:D,disabled:h,children:[e.jsx(Bj,{className:"h-4 w-4 mr-1"})," Download image"]}),e.jsxs($,{size:"sm",variant:"outline",onClick:()=>B(q),children:[e.jsx(AT,{className:"h-4 w-4 mr-1"})," Print"]}),e.jsx($,{size:"sm",variant:"outline",asChild:!0,children:e.jsxs("a",{href:`${N}/guide`,target:"_blank",rel:"noreferrer",children:[e.jsx(Tr,{className:"h-4 w-4 mr-1"})," Public view"]})})]})]}),e.jsx("div",{ref:P,"data-print-root":!0,className:"fsbo-tile p-8 max-w-4xl mx-auto space-y-6 bg-white text-foreground",children:J?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:(Ae=b.property)==null?void 0:Ae.property_address})]}),e.jsx("p",{className:"text-lg leading-relaxed",children:J.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:J.checklist.map((Be,qe)=>e.jsxs("li",{className:"flex items-start gap-2",children:[e.jsx("span",{className:"text-primary",children:"✓"}),e.jsx("span",{children:Be})]},qe))})]}),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:J.pitfalls.map((Be,qe)=>e.jsxs("div",{className:"bg-muted/30 p-4 rounded-lg",children:[e.jsx("div",{className:"font-semibold",children:Be.title}),e.jsx("div",{className:"text-sm text-muted-foreground",children:Be.body})]},qe))})]}),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:J.seller_advantages.map((Be,qe)=>e.jsxs("li",{className:"flex items-start gap-2",children:[e.jsx("span",{className:"text-primary",children:"+"}),e.jsx("span",{children:Be})]},qe))})]}),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:J.agent_value.map((Be,qe)=>e.jsxs("li",{className:"flex items-start gap-2",children:[e.jsx("span",{className:"text-primary",children:"→"}),e.jsx("span",{children:Be})]},qe))})]})]}),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:J.cta}),e.jsx("p",{className:"text-muted-foreground mb-4",children:J.cta_body}),e.jsx($,{size:"lg",children:"Request a Free Consultation"})]})]}):e.jsx("div",{className:"text-muted-foreground",children:"Guide content not generated yet."})})]}),e.jsx(Jt,{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"}),ne?e.jsxs("div",{className:"space-y-4",children:[e.jsx(tie,{label:"Phone",text:ne.phone}),e.jsx(tie,{label:"Voicemail",text:ne.voicemail}),e.jsx(tie,{label:"Video",text:ne.video}),e.jsx(tie,{label:"Door knock",text:ne.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:ne.objections.map((Be,qe)=>e.jsxs("div",{className:"bg-muted/40 p-3 rounded-lg",children:[e.jsxs("div",{className:"text-sm font-medium text-destructive",children:['"',Be.objection,'"']}),e.jsx("div",{className:"text-sm mt-1",children:Be.response})]},qe))})]})]}):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:[ce.map((Be,qe)=>e.jsxs("div",{className:"bg-muted/40 p-3 rounded-lg",children:[e.jsxs("div",{className:"text-xs text-muted-foreground",children:["Day ",qe*4+1]}),e.jsx("div",{className:"font-medium",children:Be.subject}),e.jsx("div",{className:"text-sm text-muted-foreground truncate",children:Be.preview})]},Be.key)),!ce.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:[ue.map((Be,qe)=>e.jsxs("div",{className:"bg-muted/40 p-3 rounded-lg",children:[e.jsxs("div",{className:"text-xs text-muted-foreground",children:["Step ",qe+1]}),e.jsx("div",{className:"text-sm",children:Be.body})]},Be.key)),!ue.length&&e.jsx("div",{className:"text-muted-foreground",children:"No SMS messages generated yet."})]})]})]})]})}),e.jsx(Jt,{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(Be=>Be.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(Be=>Be.campaign_id===s).map(Be=>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:[Be.first_name," ",Be.last_name]}),e.jsxs("div",{className:"text-sm text-muted-foreground",children:[Be.email," · ",Be.phone]}),e.jsxs("div",{className:"text-sm text-muted-foreground mt-1",children:["Timeline: ",Be.timeline??"—"," · Motivation: ",Be.motivation??"—"]}),e.jsx("div",{className:"text-sm mt-1",children:Be.message})]}),e.jsxs("div",{className:"text-right",children:[e.jsxs($e,{className:Tt(Be.temperature==="hot"?"bg-red-500/15 text-red-600":"bg-amber-500/15 text-amber-600"),children:[Be.temperature," · ",Be.lead_score]}),e.jsx("div",{className:"text-xs text-muted-foreground mt-1",children:Hs(new Date(Be.created_at),"MMM d")})]})]},Be.id))})]})})]})]})})}function tie({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($,{size:"sm",variant:"ghost",className:"h-6 px-2",onClick:()=>{navigator.clipboard.writeText(t),ae.success("Copied")},children:e.jsx(Ca,{className:"h-3.5 w-3.5"})})]}),e.jsx("div",{className:"text-sm text-muted-foreground",children:t})]})}const RKn="https://relzejiswnotikjgvjhz.supabase.co/functions/v1/fsbo-public",H_t="eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6InJlbHplamlzd25vdGlramd2amh6Iiwicm9sZSI6ImFub24iLCJpYXQiOjE3NjE5NTAzNDQsImV4cCI6MjA3NzUyNjM0NH0.dzIkIr_oFSbFE3oWS0ktIr83iKHHkZxt40Gc7SpC_mM";async function Z8(s){try{const t=await fetch(RKn,{method:"POST",headers:{"Content-Type":"application/json",apikey:H_t,Authorization:`Bearer ${H_t}`},body:JSON.stringify(s)});return t.ok?await t.json():null}catch{return null}}function OKn(){const{slug:s}=Vi(),[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),Z8({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),Z8({action:"track",slug:s,event_type:"page_view",session_id:N})},[s]);const h=async N=>{if(N.preventDefault(),!s)return;c(!0);const C=sessionStorage.getItem(`fsbo-${s}`)||void 0,A=await Z8({action:"submit",slug:s,...d,session_id:C,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(Ht,{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??{},x=p.landing,g=t.agent,y=m.property??{},b=p.landing_config??{media_mode:"photo",show_property_snapshot:!0,show_discover:!0,show_testimonial:!0},v=b.video_url?NKn(b.video_url):null;return e.jsxs("div",{className:"min-h-screen bg-stone-50 text-stone-900",children:[e.jsxs(Ul,{children:[e.jsxs("title",{children:[(x==null?void 0:x.headline)||"Selling On Your Own?"," — ",(g==null?void 0:g.name)||"LevelUp"]}),e.jsx("meta",{name:"description",content:(x==null?void 0:x.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:(x==null?void 0:x.eyebrow)||"Free FSBO Seller Guide"}),e.jsx("h1",{className:"text-3xl sm:text-5xl font-bold mt-4 leading-tight",children:(x==null?void 0:x.headline)||"Selling On Your Own? Here's What You Should Know."}),e.jsx("p",{className:"text-lg text-white/80 mt-4",children:(x==null?void 0:x.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:[(x==null?void 0:x.cta)||"Send Me the Free Guide"," ",e.jsx(ni,{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:(v==null?void 0:v.kind)==="iframe"?e.jsx("iframe",{src:v.src,className:"w-full aspect-video block border-0",scrolling:"no",allowFullScreen:!0,title:"Property media"}):(v==null?void 0:v.kind)==="file"?e.jsx("video",{src:v.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(sa,{className:"h-12 w-12"})})})]})})}),b.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(ai,{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(sa,{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:x==null?void 0:x.intro}),b.show_discover!==!1&&(x==null?void 0:x.discover)&&e.jsx("div",{className:"grid sm:grid-cols-2 gap-4 mt-6",children:x.discover.map((N,C)=>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})]},C))}),b.show_testimonial!==!1&&(x==null?void 0:x.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,C)=>e.jsx(Qa,{className:"h-4 w-4 fill-current"},C))}),e.jsxs("div",{className:"italic text-lg text-stone-800",children:['"',x.testimonial.quote,'"']}),e.jsxs("div",{className:"font-semibold text-sm mt-3",children:["— ",x.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(Fr,{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. ",(g==null?void 0:g.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:(x==null?void 0:x.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(se,{className:"text-xs",children:"First"}),e.jsx(be,{value:d.first_name,onChange:N=>u(C=>({...C,first_name:N.target.value})),required:!0})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(se,{className:"text-xs",children:"Last"}),e.jsx(be,{value:d.last_name,onChange:N=>u(C=>({...C,last_name:N.target.value})),required:!0})]})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(se,{className:"text-xs",children:"Email"}),e.jsx(be,{type:"email",value:d.email,onChange:N=>u(C=>({...C,email:N.target.value})),required:!0})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(se,{className:"text-xs",children:"Phone"}),e.jsx(be,{type:"tel",value:d.phone,onChange:N=>u(C=>({...C,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(se,{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(C=>({...C,timeline:N.target.value})),children:[e.jsx("option",{value:"",children:"Select…"}),SKn.map(N=>e.jsx("option",{value:N.value,children:N.label},N.value))]})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(se,{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(C=>({...C,preferred_contact:N.target.value})),children:AKn.map(N=>e.jsx("option",{value:N.value,children:N.label},N.value))})]})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(se,{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(C=>({...C,motivation:N.target.value})),children:[e.jsx("option",{value:"",children:"Select…"}),CKn.map(N=>e.jsx("option",{value:N,children:N},N))]})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(se,{className:"text-xs",children:"Message (optional)"}),e.jsx(Is,{rows:3,value:d.message,onChange:N=>u(C=>({...C,message:N.target.value}))})]}),e.jsxs($,{type:"submit",className:"w-full",size:"lg",disabled:o,children:[o?e.jsx(Ht,{className:"h-4 w-4 animate-spin mr-2"}):null,(x==null?void 0:x.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 ",(g==null?void 0:g.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:[g!=null&&g.avatar_url?e.jsx("img",{src:g.avatar_url,alt:g.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:g==null?void 0:g.name}),e.jsxs("div",{className:"text-stone-600",children:[g==null?void 0:g.title,g!=null&&g.title&&(g!=null&&g.brokerage)?" · ":"",g==null?void 0:g.brokerage]}),e.jsxs("div",{className:"flex flex-wrap justify-center sm:justify-start gap-2 mt-3",children:[g!=null&&g.phone?e.jsx($,{variant:"outline",asChild:!0,children:e.jsxs("a",{href:`tel:${g.phone}`,children:[e.jsx(ya,{className:"h-4 w-4 mr-1"})," Call"]})}):null,g!=null&&g.email?e.jsx($,{variant:"outline",asChild:!0,children:e.jsxs("a",{href:`mailto:${g.email}`,children:[e.jsx(nn,{className:"h-4 w-4 mr-1"})," Email"]})}):null,g!=null&&g.website_url?e.jsx($,{variant:"outline",asChild:!0,children:e.jsxs("a",{href:g.website_url,target:"_blank",rel:"noreferrer",children:[e.jsx(Ji,{className:"h-4 w-4 mr-1"})," Website"]})}):null]})]})]})})})]})}function FKn(){const{slug:s}=Vi(),[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),Z8({action:"get",slug:s}).then(b=>{b!=null&&b.campaign&&n(b),a(!1)}))},[s]),j.useEffect(()=>{s&&Z8({action:"track",slug:s,event_type:"guide_view"})},[s]);const h=async b=>{if(b.preventDefault(),!s||o)return;c(!0);const v=await Z8({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),v?(u(!0),Z8({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(Ht,{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,x=(m.content??{}).guide,g=t.agent,y=m.property??{};return e.jsxs("div",{className:"min-h-screen bg-stone-50 text-stone-900",children:[e.jsxs(Ul,{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(Wn,{to:`/fsbo/${s}`,className:"inline-flex items-center gap-1 text-sm text-white/80 hover:text-white",children:[e.jsx(ka,{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})]}),x?e.jsxs("div",{className:"space-y-10 mt-8",children:[e.jsx("p",{className:"text-lg leading-relaxed text-stone-700",children:x.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:x.checklist.map((b,v)=>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:b})]},v))})]}),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:x.pitfalls.map((b,v)=>e.jsxs("div",{className:"bg-stone-50 p-5 rounded-xl",children:[e.jsx("div",{className:"font-semibold text-stone-900 mb-1",children:b.title}),e.jsx("div",{className:"text-sm text-stone-600",children:b.body})]},v))})]}),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:x.seller_advantages.map((b,v)=>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:b})]},v))})]}),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:x.agent_value.map((b,v)=>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:b})]},v))})]})]}),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:x.cta}),e.jsx("p",{className:"text-stone-600 mb-6 max-w-lg mx-auto",children:x.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(Fr,{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:[(g==null?void 0:g.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(se,{className:"text-xs",children:"First"}),e.jsx(be,{value:i.first_name,onChange:b=>l(v=>({...v,first_name:b.target.value})),required:!0})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(se,{className:"text-xs",children:"Last"}),e.jsx(be,{value:i.last_name,onChange:b=>l(v=>({...v,last_name:b.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(se,{className:"text-xs",children:"Email"}),e.jsx(be,{type:"email",value:i.email,onChange:b=>l(v=>({...v,email:b.target.value})),required:!0})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(se,{className:"text-xs",children:"Phone"}),e.jsx(be,{type:"tel",value:i.phone,onChange:b=>l(v=>({...v,phone:b.target.value}))})]})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(se,{className:"text-xs",children:"Best time / anything I should know (optional)"}),e.jsx(Is,{rows:3,value:i.message,onChange:b=>l(v=>({...v,message:b.target.value}))})]}),e.jsxs($,{type:"submit",size:"lg",className:"w-full",disabled:o,children:[o?e.jsx(Ht,{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:[g!=null&&g.avatar_url?e.jsx("img",{src:g.avatar_url,alt:g.name??"",className:"h-16 w-16 rounded-full object-cover"}):null,e.jsxs("div",{children:[e.jsx("div",{className:"font-semibold text-lg",children:g==null?void 0:g.name}),e.jsxs("div",{className:"text-sm text-stone-600",children:[g==null?void 0:g.title,g!=null&&g.title&&(g!=null&&g.brokerage)?" · ":"",g==null?void 0:g.brokerage]})]})]}),e.jsxs("div",{className:"flex gap-2",children:[g!=null&&g.phone?e.jsx($,{variant:"outline",asChild:!0,children:e.jsxs("a",{href:`tel:${g.phone}`,children:[e.jsx(ya,{className:"h-4 w-4 mr-1"})," Call"]})}):null,g!=null&&g.email?e.jsx($,{variant:"outline",asChild:!0,children:e.jsxs("a",{href:`mailto:${g.email}`,children:[e.jsx(nn,{className:"h-4 w-4 mr-1"})," Email"]})}):null]})]})]})})]})}function zKn(){const s=rKt(),t=aKt(),n=mQe(),r=pQe(),a=ts(),[i,l]=j.useState(""),o=yt({mutationFn:async()=>{const{data:h,error:m}=await U.from("profiles").select("id");if(m)throw m;const p=new Date().toISOString(),x=(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:g}=await U.from("feature_entitlements").upsert(x,{onConflict:"user_id,feature_key"});if(g)throw g},onSuccess:()=>{ae.success("Enabled for all members"),a.invalidateQueries({queryKey:["fsbo-breakthrough-access"]})},onError:h=>ae.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),x=p.toISOString().slice(0,10);h.push({day:Hs(p,"MMM d"),visits:(r.data??[]).filter(g=>g.event_type==="page_view"&&g.created_at.startsWith(x)).length,scans:(r.data??[]).filter(g=>g.event_type==="qr_scan"&&g.created_at.startsWith(x)).length,leads:(n.data??[]).filter(g=>g.created_at.startsWith(x)).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(Ks,{title:"By-Owner Breakthrough Admin",children:e.jsx("div",{className:"grid place-items-center py-24",children:e.jsx(Ht,{className:"h-6 w-6 animate-spin"})})}):e.jsx(Ks,{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($,{onClick:()=>o.mutate(),disabled:o.isPending,children:[o.isPending?e.jsx(Ht,{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(gA,{label:"Properties",value:c.properties,icon:sa}),e.jsx(gA,{label:"Campaigns",value:c.campaigns,icon:nn}),e.jsx(gA,{label:"Page visits",value:c.visits,icon:Gl}),e.jsx(gA,{label:"QR scans",value:c.qr,icon:Rx}),e.jsx(gA,{label:"Guide views",value:c.guideViews,icon:Wr}),e.jsx(gA,{label:"Leads",value:c.leads,icon:qn}),e.jsx(gA,{label:"Appointments",value:c.appointments,icon:qn}),e.jsx(gA,{label:"Letters",value:c.letters,icon:nn})]}),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(Ob,{width:"100%",height:"100%",children:e.jsxs(lYe,{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(AO,{strokeDasharray:"3 3",stroke:"hsl(var(--border))",vertical:!1}),e.jsx(k1,{dataKey:"day",tick:{fontSize:11},stroke:"hsl(var(--muted-foreground))"}),e.jsx(S1,{allowDecimals:!1,tick:{fontSize:11},stroke:"hsl(var(--muted-foreground))",width:28}),e.jsx(yf,{contentStyle:{borderRadius:12,border:"1px solid hsl(var(--border))"}}),e.jsx(Fb,{type:"monotone",dataKey:"visits",stroke:"hsl(var(--primary))",fill:"url(#fsboAdminVisits)",strokeWidth:2}),e.jsx(Fb,{type:"monotone",dataKey:"scans",stackId:"1",stroke:"hsl(var(--accent))",fill:"url(#fsboAdminLeads)",strokeWidth:2}),e.jsx(Fb,{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(Vr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(be,{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 x,g,y,b,v,N;const m=(n.data??[]).filter(C=>C.campaign_id===h.id).length,p=(r.data??[]).filter(C=>C.campaign_id===h.id&&C.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:((x=h.property)==null?void 0:x.property_address)??h.name}),e.jsxs("div",{className:"text-sm text-muted-foreground",children:[((g=h.property)==null?void 0:g.seller_name)||"Homeowner"," · ",(y=h.property)==null?void 0:y.city,(b=h.property)!=null&&b.city&&((v=h.property)!=null&&v.state)?", ":"",(N=h.property)==null?void 0:N.state]})]}),e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsxs($e,{variant:"secondary",children:[e.jsx(Gl,{className:"h-3 w-3 mr-1"}),p]}),e.jsxs($e,{variant:"secondary",children:[e.jsx(qn,{className:"h-3 w-3 mr-1"}),m]}),e.jsx(ni,{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 gA({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 cKt={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},G_t={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"},BKn=[{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."}],$Kn=[{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."}],UKn=[{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."}],qKn="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.",VKn={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:""},HKn={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 GKn(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:BKn,sponsor_cards:UKn,faqs:$Kn,lead_magnet:VKn,calculator:HKn,sections:cKt,disclaimer:qKn,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 dKt(s){return s.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,48)}const rW=U;function WKn(){const{user:s}=_s(),t=ts(),n=["attract-landing-page",s==null?void 0:s.id],{data:r,isLoading:a}=ht({queryKey:n,enabled:!!s,queryFn:async()=>{const{data:c,error:d}=await rW.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}=ht({queryKey:["attract-landing-analytics",r==null?void 0:r.id],enabled:!!(r!=null&&r.id),queryFn:async()=>{const{data:c,error:d}=await rW.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(x=>x.event_type==="view").length,m=u.filter(x=>x.event_type==="cta_click").length,p=u.filter(x=>x.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=dKt(c||"my-attraction-page")||"attraction-page";let u=d;for(let x=0;x<5;x++){const{data:g}=await rW.from("attract_landing_pages").select("id").eq("slug",u).maybeSingle();if(!g)break;u=`${d}-${Math.random().toString(36).slice(2,6)}`}const h=GKn(c||"Your Name"),{data:m,error:p}=await rW.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}),ae.success("Attraction page created")},onError:c=>ae.error(c.message||"Could not create the page")}),o=yt({mutationFn:async c=>{const{error:d}=await rW.from("attract_landing_pages").update(c).eq("id",r.id);if(d)throw d},onSuccess:()=>{t.invalidateQueries({queryKey:n}),ae.success("Saved")},onError:c=>{var d;return ae.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 KKn(){var y,b,v,N,C,A,T,P,M,I,D,B;const{user:s}=_s(),{page:t,isLoading:n,analytics:r,createPage:a,savePage:i}=WKn(),[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=q=>o(W=>({...W,...q})),m=(q,W)=>h({[q]:W}),p=(q,W,V)=>m(q,l[q].map((K,Q)=>Q===W?{...K,...V}:K)),x=()=>{const{id:q,user_id:W,created_at:V,updated_at:K,...Q}=l;i.mutate({...Q,slug:dKt(Q.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(dn,{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($,{size:"lg",onClick:()=>{var q;return a.mutate(((q=s==null?void 0:s.user_metadata)==null?void 0:q.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($,{variant:"outline",size:"sm",onClick:()=>d(!1),children:"Back to editor"})]}),e.jsx(YWt,{cfg:l,preview:!0})]});const g={...cKt,...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($,{variant:"outline",size:"sm",onClick:()=>d(!0),children:[e.jsx(ga,{className:"mr-2 h-4 w-4"})," Preview"]}),l.is_published&&e.jsx($,{variant:"outline",size:"sm",asChild:!0,children:e.jsxs("a",{href:u,target:"_blank",rel:"noreferrer",children:[e.jsx(Tr,{className:"mr-2 h-4 w-4"})," View live"]})}),e.jsxs($,{size:"sm",onClick:x,disabled:i.isPending,children:[e.jsx(Jo,{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(q=>e.jsx(_e,{children:e.jsxs(Oe,{className:"p-4",children:[e.jsx("div",{className:"text-xs uppercase tracking-wider text-muted-foreground",children:q.label}),e.jsx("div",{className:"mt-1 text-2xl font-bold",children:q.value})]})},q.label))}),e.jsxs(ua,{defaultValue:"content",children:[e.jsxs(ha,{className:"mb-6 flex-wrap",children:[e.jsx(Qt,{value:"content",children:"Content"}),e.jsx(Qt,{value:"proof",children:"Proof & FAQ"}),e.jsx(Qt,{value:"calculator",children:"Calculator"}),e.jsx(Qt,{value:"sections",children:"Sections"}),e.jsx(Qt,{value:"publish",children:"Publish"})]}),e.jsxs(Jt,{value:"content",className:"space-y-6",children:[e.jsxs(_e,{children:[e.jsx(Bt,{children:e.jsx(Ut,{className:"text-base",children:"Hero"})}),e.jsxs(Oe,{className:"grid gap-4 md:grid-cols-2",children:[e.jsx($h,{label:"Your name",value:l.agent_name,onChange:q=>h({agent_name:q})}),e.jsx($h,{label:"Title / brokerage",value:l.agent_title,onChange:q=>h({agent_title:q})}),e.jsx($h,{label:"Eyebrow line",value:l.eyebrow,onChange:q=>h({eyebrow:q}),className:"md:col-span-2"}),e.jsxs("div",{className:"md:col-span-2 space-y-1.5",children:[e.jsx(se,{children:"Headline"}),e.jsx(Is,{rows:2,value:l.headline||"",onChange:q=>h({headline:q.target.value})})]}),e.jsxs("div",{className:"md:col-span-2 space-y-1.5",children:[e.jsx(se,{children:"Subheadline"}),e.jsx(Is,{rows:3,value:l.subheadline||"",onChange:q=>h({subheadline:q.target.value})})]}),e.jsx($h,{label:"Button text",value:l.cta_label,onChange:q=>h({cta_label:q})}),e.jsx($h,{label:"Scheduling link (Calendly etc.)",value:l.calendar_url,onChange:q=>h({calendar_url:q})}),e.jsx($h,{label:"Headshot URL",value:l.headshot_url,onChange:q=>h({headshot_url:q})}),e.jsx($h,{label:"Hero background image URL",value:l.hero_image_url,onChange:q=>h({hero_image_url:q})}),e.jsx($h,{label:"Logo URL",value:l.logo_url,onChange:q=>h({logo_url:q})}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsx($h,{label:"Primary color",type:"color",value:l.primary_color,onChange:q=>h({primary_color:q})}),e.jsx($h,{label:"Accent color",type:"color",value:l.accent_color,onChange:q=>h({accent_color:q})})]}),e.jsx($h,{label:"Phone",value:l.phone,onChange:q=>h({phone:q})}),e.jsx($h,{label:"Email",value:l.email,onChange:q=>h({email:q})})]})]}),e.jsxs(_e,{children:[e.jsx(Bt,{children:e.jsx(Ut,{className:"text-base",children:"Credibility strip"})}),e.jsxs(Oe,{className:"space-y-3",children:[(l.credibility||[]).map((q,W)=>e.jsxs(aW,{onRemove:()=>m("credibility",l.credibility.filter((V,K)=>K!==W)),children:[e.jsx(be,{placeholder:"Value (e.g. $42M)",value:q.value||"",onChange:V=>p("credibility",W,{value:V.target.value})}),e.jsx(be,{placeholder:"Label (e.g. Closed volume)",value:q.label||"",onChange:V=>p("credibility",W,{label:V.target.value})})]},W)),e.jsx(iW,{onClick:()=>m("credibility",[...l.credibility||[],{value:"",label:""}]),label:"Add stat"})]})]}),e.jsxs(_e,{children:[e.jsx(Bt,{children:e.jsx(Ut,{className:"text-base",children:"Your story"})}),e.jsxs(Oe,{className:"space-y-4",children:[e.jsx($h,{label:"Section title",value:l.story_title,onChange:q=>h({story_title:q})}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:"Story"}),e.jsx(Is,{rows:6,value:l.story_body||"",onChange:q=>h({story_body:q.target.value})})]}),e.jsx($h,{label:"Story video URL (YouTube, Vimeo, Loom, MP4)",value:l.story_video_url,onChange:q=>h({story_video_url:q})})]})]}),e.jsxs(_e,{children:[e.jsx(Bt,{children:e.jsx(Ut,{className:"text-base",children:"Value stack"})}),e.jsxs(Oe,{className:"space-y-4",children:[(l.value_cards||[]).map((q,W)=>e.jsxs(aW,{vertical:!0,onRemove:()=>m("value_cards",l.value_cards.filter((V,K)=>K!==W)),children:[e.jsx(be,{placeholder:"Title",value:q.title||"",onChange:V=>p("value_cards",W,{title:V.target.value})}),e.jsx(Is,{rows:2,placeholder:"Description",value:q.body||"",onChange:V=>p("value_cards",W,{body:V.target.value})}),e.jsx(be,{placeholder:"Proof point (optional)",value:q.proof||"",onChange:V=>p("value_cards",W,{proof:V.target.value})})]},W)),e.jsx(iW,{onClick:()=>m("value_cards",[...l.value_cards||[],{title:"",body:""}]),label:"Add value card"})]})]}),e.jsxs(_e,{children:[e.jsx(Bt,{children:e.jsx(Ut,{className:"text-base",children:"What you get from me"})}),e.jsxs(Oe,{className:"space-y-4",children:[(l.sponsor_cards||[]).map((q,W)=>e.jsxs(aW,{vertical:!0,onRemove:()=>m("sponsor_cards",l.sponsor_cards.filter((V,K)=>K!==W)),children:[e.jsx(be,{placeholder:"Title",value:q.title||"",onChange:V=>p("sponsor_cards",W,{title:V.target.value})}),e.jsx(Is,{rows:2,placeholder:"Description",value:q.body||"",onChange:V=>p("sponsor_cards",W,{body:V.target.value})})]},W)),e.jsx(iW,{onClick:()=>m("sponsor_cards",[...l.sponsor_cards||[],{title:"",body:""}]),label:"Add commitment"})]})]}),e.jsxs(_e,{children:[e.jsx(Bt,{children:e.jsx(Ut,{className:"text-base",children:"Free download & upcoming event"})}),e.jsxs(Oe,{className:"space-y-4",children:[e.jsx($h,{label:"Download title",value:(y=l.lead_magnet)==null?void 0:y.title,onChange:q=>h({lead_magnet:{...l.lead_magnet,title:q}})}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:"Download description"}),e.jsx(Is,{rows:2,value:((b=l.lead_magnet)==null?void 0:b.body)||"",onChange:q=>h({lead_magnet:{...l.lead_magnet,body:q.target.value}})})]}),e.jsx($h,{label:"File URL",value:(v=l.lead_magnet)==null?void 0:v.file_url,onChange:q=>h({lead_magnet:{...l.lead_magnet,file_url:q}})}),e.jsxs("div",{className:"grid gap-4 md:grid-cols-3",children:[e.jsx($h,{label:"Event title",value:(N=l.event_block)==null?void 0:N.title,onChange:q=>h({event_block:{...l.event_block,title:q}})}),e.jsx($h,{label:"When",value:(C=l.event_block)==null?void 0:C.when,onChange:q=>h({event_block:{...l.event_block,when:q}})}),e.jsx($h,{label:"Registration link",value:(A=l.event_block)==null?void 0:A.url,onChange:q=>h({event_block:{...l.event_block,url:q}})})]})]})]})]}),e.jsxs(Jt,{value:"proof",className:"space-y-6",children:[e.jsxs(_e,{children:[e.jsx(Bt,{children:e.jsx(Ut,{className:"text-base",children:"Testimonials"})}),e.jsxs(Oe,{className:"space-y-4",children:[(l.testimonials||[]).map((q,W)=>e.jsxs(aW,{vertical:!0,onRemove:()=>m("testimonials",l.testimonials.filter((V,K)=>K!==W)),children:[e.jsx(Is,{rows:3,placeholder:"Quote",value:q.quote||"",onChange:V=>p("testimonials",W,{quote:V.target.value})}),e.jsxs("div",{className:"grid gap-3 md:grid-cols-3",children:[e.jsx(be,{placeholder:"Name",value:q.name||"",onChange:V=>p("testimonials",W,{name:V.target.value})}),e.jsx(be,{placeholder:"Role / market",value:q.role||"",onChange:V=>p("testimonials",W,{role:V.target.value})}),e.jsx(be,{placeholder:"Photo URL",value:q.photo_url||"",onChange:V=>p("testimonials",W,{photo_url:V.target.value})})]})]},W)),e.jsx(iW,{onClick:()=>m("testimonials",[...l.testimonials||[],{quote:"",name:""}]),label:"Add testimonial"})]})]}),e.jsxs(_e,{children:[e.jsx(Bt,{children:e.jsx(Ut,{className:"text-base",children:"Objection-handling FAQ"})}),e.jsxs(Oe,{className:"space-y-4",children:[(l.faqs||[]).map((q,W)=>e.jsxs(aW,{vertical:!0,onRemove:()=>m("faqs",l.faqs.filter((V,K)=>K!==W)),children:[e.jsx(be,{placeholder:"Question",value:q.q||"",onChange:V=>p("faqs",W,{q:V.target.value})}),e.jsx(Is,{rows:3,placeholder:"Answer",value:q.a||"",onChange:V=>p("faqs",W,{a:V.target.value})})]},W)),e.jsx(iW,{onClick:()=>m("faqs",[...l.faqs||[],{q:"",a:""}]),label:"Add question"})]})]}),e.jsxs(_e,{children:[e.jsx(Bt,{children:e.jsx(Ut,{className:"text-base",children:"Income disclaimer"})}),e.jsx(Oe,{children:e.jsx(Is,{rows:4,value:l.disclaimer||"",onChange:q=>h({disclaimer:q.target.value})})})]})]}),e.jsx(Jt,{value:"calculator",children:e.jsxs(_e,{children:[e.jsx(Bt,{children:e.jsx(Ut,{className:"text-base",children:"Earnings calculator"})}),e.jsxs(Oe,{className:"grid gap-4 md:grid-cols-2",children:[e.jsx($h,{label:"Section title",value:(T=l.calculator)==null?void 0:T.title,onChange:q=>h({calculator:{...l.calculator,title:q}}),className:"md:col-span-2"}),e.jsx($h,{label:"Cap ($)",type:"number",value:(P=l.calculator)==null?void 0:P.cap,onChange:q=>h({calculator:{...l.calculator,cap:Number(q)}})}),e.jsx($h,{label:"Your split (%)",type:"number",value:(M=l.calculator)==null?void 0:M.split,onChange:q=>h({calculator:{...l.calculator,split:Number(q)}})}),e.jsx($h,{label:"Per-transaction fee ($)",type:"number",value:(I=l.calculator)==null?void 0:I.transaction_fee,onChange:q=>h({calculator:{...l.calculator,transaction_fee:Number(q)}})}),e.jsx($h,{label:"Typical competitor split (%)",type:"number",value:(D=l.calculator)==null?void 0:D.current_split,onChange:q=>h({calculator:{...l.calculator,current_split:Number(q)}})}),e.jsx($h,{label:"Typical competitor monthly fees ($)",type:"number",value:(B=l.calculator)==null?void 0:B.current_monthly_fees,onChange:q=>h({calculator:{...l.calculator,current_monthly_fees:Number(q)}})}),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(Jt,{value:"sections",children:e.jsxs(_e,{children:[e.jsx(Bt,{children:e.jsx(Ut,{className:"text-base",children:"Show or hide sections"})}),e.jsx(Oe,{className:"divide-y",children:Object.keys(G_t).map(q=>e.jsxs("div",{className:"flex items-center justify-between py-3",children:[e.jsx("span",{className:"text-sm",children:G_t[q]}),e.jsx(Tn,{checked:g[q]!==!1,onCheckedChange:W=>h({sections:{...g,[q]:W}})})]},q))})]})}),e.jsxs(Jt,{value:"publish",className:"space-y-6",children:[e.jsxs(_e,{children:[e.jsx(Bt,{children:e.jsx(Ut,{className:"text-base",children:"Publishing"})}),e.jsxs(Oe,{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(Tn,{checked:!!l.is_published,onCheckedChange:q=>h({is_published:q})})]}),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(Tn,{checked:!!l.noindex,onCheckedChange:q=>h({noindex:q})})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:"Web address"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(be,{value:l.slug||"",onChange:q=>h({slug:q.target.value})}),e.jsx($,{variant:"outline",onClick:()=>{navigator.clipboard.writeText(u),ae.success("Link copied")},children:e.jsx(Ca,{className:"h-4 w-4"})})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:u})]}),e.jsx($h,{label:"Search title",value:l.seo_title,onChange:q=>h({seo_title:q})}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:"Search description"}),e.jsx(Is,{rows:2,value:l.seo_description||"",onChange:q=>h({seo_description:q.target.value})})]})]})]}),e.jsxs(_e,{children:[e.jsx(Bt,{children:e.jsxs(Ut,{className:"flex items-center gap-2 text-base",children:[e.jsx(ml,{className:"h-4 w-4"})," Where leads go"]})}),e.jsx(Oe,{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($,{onClick:x,disabled:i.isPending,children:[e.jsx(Jo,{className:"mr-2 h-4 w-4"})," ",i.isPending?"Saving…":"Save changes"]})})]})}function $h({label:s,value:t,onChange:n,type:r="text",className:a}){return e.jsxs("div",{className:`space-y-1.5 ${a||""}`,children:[e.jsx(se,{children:s}),e.jsx(be,{type:r,value:t??"",onChange:i=>n(i.target.value)})]})}function aW({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($,{variant:"ghost",size:"icon",onClick:t,className:"text-muted-foreground hover:text-destructive",children:e.jsx(Pn,{className:"h-4 w-4"})})]})}function iW({onClick:s,label:t}){return e.jsxs($,{variant:"outline",size:"sm",onClick:s,children:[e.jsx(sn,{className:"mr-2 h-4 w-4"})," ",t]})}function YKn(s){const{user:t}=_s(),n=ts(),r=ht({queryKey:["admin-attract-list",s,t==null?void 0:t.id],enabled:!!t,queryFn:async()=>{let o=U.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 U.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(x=>{h[x.user_id]=x})}return(c??[]).map(m=>{var p,x,g,y,b,v;return{user_id:m.id,email:m.email,full_name:m.full_name,enabled:!!((p=h[m.id])!=null&&p.enabled),tier:((x=h[m.id])==null?void 0:x.tier)??null,enabled_at:((g=h[m.id])==null?void 0:g.enabled_at)??null,expires_at:((y=h[m.id])==null?void 0:y.expires_at)??null,notes:((b=h[m.id])==null?void 0:b.notes)??null,enabled_by:((v=h[m.id])==null?void 0:v.enabled_by)??null}})}}),a=ht({queryKey:["admin-attract-audit",t==null?void 0:t.id],enabled:!!t,queryFn:async()=>{const{data:o,error:c}=await U.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 U.from("feature_entitlements").upsert(h,{onConflict:"user_id,feature_key"});if(m)throw m;await U.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"]}),ae.success("Access granted")},onError:o=>ae.error(o.message)}),l=yt({mutationFn:async o=>{const{error:c}=await U.from("feature_entitlements").update({enabled:!1}).eq("user_id",o).eq("feature_key","levelup_attract");if(c)throw c;await U.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"]}),ae.success("Access revoked")},onError:o=>ae.error(o.message)});return{list:r,audit:a,grant:i,revoke:l}}function ZKn(){const[s,t]=j.useState(""),{list:n,audit:r,grant:a,revoke:i}=YKn(s),[l,o]=j.useState(null),[c,d]=j.useState(null),[u,h]=j.useState("beta"),[m,p]=j.useState(""),[x,g]=j.useState(""),y=v=>{d(v),h(v.tier??"beta"),p(v.expires_at?v.expires_at.slice(0,10):""),g(v.notes??"")},b=async()=>{c&&(await a.mutateAsync({target_user_id:c.user_id,tier:u,expires_at:m?new Date(m).toISOString():null,notes:x||void 0}),d(null))};return e.jsxs("div",{className:"p-6",children:[e.jsx(hh,{title:"LevelUp Attract — Access Management",description:"Grant or revoke access to LevelUp Attract for individual members. Every change is audited."}),e.jsx(_e,{className:"p-4 rounded-2xl mb-4",children:e.jsxs("div",{className:"relative max-w-md",children:[e.jsx(Vr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-slate-400"}),e.jsx(be,{value:s,onChange:v=>t(v.target.value),placeholder:"Search by name or email...",className:"pl-9"})]})}),e.jsxs(_e,{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(v=>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:v.full_name||v.email||v.user_id}),e.jsx("div",{className:"text-[11.5px] text-slate-500 truncate",children:v.email})]}),e.jsx("div",{children:v.enabled?e.jsxs($e,{className:"bg-emerald-100 text-emerald-800 border-0 gap-1",children:[e.jsx(dn,{className:"h-3 w-3"})," ",v.tier??"enabled"]}):e.jsx($e,{variant:"outline",className:"text-slate-500",children:"Not enabled"})}),e.jsx("div",{className:"text-[11.5px] text-slate-500 whitespace-nowrap",children:v.enabled_at?Hs(new Date(v.enabled_at),"MMM d, yyyy"):"—"}),e.jsx("div",{className:"flex gap-1.5",children:v.enabled?e.jsxs(e.Fragment,{children:[e.jsx($,{size:"sm",variant:"outline",onClick:()=>y(v),children:"Edit"}),e.jsx($,{size:"sm",variant:"ghost",className:"text-rose-600",onClick:()=>o({user:v,action:"revoke"}),children:"Revoke"})]}):e.jsxs($,{size:"sm",className:"bg-gradient-to-r from-violet-600 to-indigo-600",onClick:()=>y(v),children:[e.jsx(j0,{className:"h-3.5 w-3.5 mr-1"})," Enable"]})})]},v.user_id))]}),e.jsxs(_e,{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(Uj,{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(v=>e.jsxs("div",{className:"text-[12.5px] text-slate-700 flex items-center gap-2",children:[e.jsx($e,{variant:"outline",className:"text-[10.5px] capitalize",children:v.action}),e.jsx("span",{className:"font-mono text-[11px] text-slate-500",children:v.target_user_id.slice(0,8)}),v.tier&&e.jsxs("span",{className:"text-slate-500",children:["· ",v.tier]}),v.notes&&e.jsxs("span",{className:"text-slate-500",children:["· ",v.notes]}),e.jsx("span",{className:"text-slate-400 ml-auto",children:Hs(new Date(v.created_at),"MMM d h:mm a")})]},v.id))})]}),e.jsx(Os,{open:!!c,onOpenChange:v=>!v&&d(null),children:e.jsxs(Rs,{children:[e.jsxs(Us,{children:[e.jsxs(zs,{children:[c!=null&&c.enabled?"Update":"Enable"," Attract access"]}),e.jsx(Sr,{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(se,{children:"Tier"}),e.jsxs(vs,{value:u,onValueChange:h,children:[e.jsx(gs,{children:e.jsx(bs,{})}),e.jsxs(ys,{children:[e.jsx(Ye,{value:"beta",children:"Beta"}),e.jsx(Ye,{value:"standard",children:"Standard"}),e.jsx(Ye,{value:"pro",children:"Pro"}),e.jsx(Ye,{value:"founder",children:"Founder"})]})]})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Expires (optional)"}),e.jsx(be,{type:"date",value:m,onChange:v=>p(v.target.value)})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Internal notes (optional)"}),e.jsx(Is,{rows:2,value:x,onChange:v=>g(v.target.value)})]})]}),e.jsxs(kr,{children:[e.jsx($,{variant:"ghost",onClick:()=>d(null),children:"Cancel"}),e.jsx($,{className:"bg-gradient-to-r from-violet-600 to-indigo-600",onClick:b,disabled:a.isPending,children:c!=null&&c.enabled?"Save changes":"Enable access"})]})]})}),e.jsx(Ll,{open:!!l,onOpenChange:v=>!v&&o(null),children:e.jsxs(yl,{children:[e.jsxs(vl,{children:[e.jsx(_l,{children:"Revoke Attract access?"}),e.jsxs(wl,{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(bl,{children:[e.jsx(jl,{children:"Cancel"}),e.jsxs(fl,{className:"bg-rose-600 hover:bg-rose-700",onClick:async()=>{l&&await i.mutateAsync(l.user.user_id),o(null)},children:[e.jsx($d,{className:"h-4 w-4 mr-1.5"})," Revoke access"]})]})]})})]})}const XKn=({team:s,onSelect:t})=>{const{data:n}=ht({queryKey:["team-card-info",s.id],queryFn:async()=>{const{data:r}=await U.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 U.from("profiles").select("name, avatar_url").eq("id",i.user_id).single();l=o}return{count:a,leaderProfile:l}}});return e.jsxs(_e,{className:"cursor-pointer hover:shadow-md transition-shadow group",onClick:t,children:[e.jsx(Bt,{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(Ut,{className:"text-lg truncate",children:s.name}),s.description&&e.jsx(vr,{className:"mt-1 line-clamp-2",children:s.description})]}),e.jsxs($e,{variant:"secondary",className:"ml-2 shrink-0",children:[e.jsx(qn,{className:"h-3 w-3 mr-1"}),(n==null?void 0:n.count)??"…"]})]})}),e.jsxs(Oe,{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(ki,{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(Ng,{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(kf,{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($e,{variant:"outline",className:"text-xs py-0",children:"Lead Pond"}),s.shared_assets_enabled&&e.jsx($e,{variant:"outline",className:"text-xs py-0",children:"Shared Assets"}),s.shared_videos_enabled&&e.jsx($e,{variant:"outline",className:"text-xs py-0",children:"Shared Videos"})]})]})]})},QKn=()=>{const{user:s,isAdmin:t,isBrokerageManager:n,brokerageId:r,managedBrokerages:a,selectedBrokerageId:i}=_s(),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:x,updateMemberRole:g}=CC(o),[y,b]=j.useState(!1),[v,N]=j.useState(null),{data:C}=ht({queryKey:["all-brokerages-for-teams"],queryFn:async()=>{const{data:P,error:M}=await U.from("brokerages").select("id, name").order("name");if(M)throw M;return P||[]},enabled:t}),{data:A}=ht({queryKey:["brokerage-agents-for-teams",l],queryFn:async()=>{const{data:P,error:M}=await U.from("profiles").select("id, name, email, avatar_url").eq("brokerage_id",l).order("name");if(M)throw M;return P||[]},enabled:!!l}),T=async P=>{const M=P.brokerage_id||l||null,I=await u.mutateAsync({name:P.name,brokerage_id:M,description:P.description});if(P.leaderId&&P.leaderId!=="none"&&await p.mutateAsync({team_id:I.id,user_id:P.leaderId,role:"team_leader"}),P.memberIds)for(const D of P.memberIds)await p.mutateAsync({team_id:I.id,user_id:D,role:"team_member"});b(!1)};return!n&&!t?e.jsx(Ks,{title:"Teams",description:"Team Management",children:e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(qn,{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(Ks,{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($,{onClick:()=>b(!0),children:[e.jsx(sn,{className:"mr-2 h-4 w-4"}),"Create Team"]})]}),e.jsx(y8t,{open:y,onOpenChange:b,onCreateTeam:T,isCreating:u.isPending,brokerageAgents:A||[],isAdmin:t,allBrokerages:C,activeBrokerageId:l}),d&&e.jsx("div",{className:"grid gap-4 md:grid-cols-2 lg:grid-cols-3",children:[1,2,3].map(P=>e.jsx(_e,{children:e.jsxs(Oe,{className:"p-6",children:[e.jsx(on,{className:"h-5 w-32 mb-3"}),e.jsx(on,{className:"h-4 w-48 mb-4"}),e.jsx(on,{className:"h-8 w-full"})]})},P))}),!d&&c.length===0&&!v&&e.jsx(_e,{children:e.jsxs(Oe,{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(qn,{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($,{onClick:()=>b(!0),children:[e.jsx(sn,{className:"mr-2 h-4 w-4"}),"Create Your First Team"]})]})}),!d&&c.length>0&&!v&&e.jsx("div",{className:"grid gap-4 md:grid-cols-2 lg:grid-cols-3",children:c.map(P=>e.jsx(XKn,{team:P,onSelect:()=>N(P)},P.id))}),v&&e.jsx(g8t,{team:v,brokerageAgents:A||[],onBack:()=>N(null),onUpdate:P=>h.mutateAsync({id:v.id,...P}).then(M=>N(M)),onAddMember:(P,M)=>p.mutateAsync({team_id:v.id,user_id:P,role:M}),onRemoveMember:P=>x.mutateAsync({team_id:v.id,member_id:P}),onUpdateRole:(P,M)=>g.mutateAsync({team_id:v.id,member_id:P,role:M}),onDeleteTeam:()=>m.mutate(v.id),isUpdating:h.isPending,isAddingMember:p.isPending})]})})},JKn=({team:s})=>{const{updateTeam:t}=CC(),n=r=>t.mutate({id:s.id,...r});return e.jsxs("div",{className:"space-y-6",children:[e.jsxs(_e,{children:[e.jsxs(Bt,{children:[e.jsx(Ut,{className:"text-lg",children:"Team Settings"}),e.jsx(vr,{children:"Control how your team shares contacts, leads, and assets."})]}),e.jsxs(Oe,{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Contact Visibility"}),e.jsxs(vs,{defaultValue:s.contact_visibility,onValueChange:r=>n({contact_visibility:r}),children:[e.jsx(gs,{children:e.jsx(bs,{})}),e.jsxs(ys,{children:[e.jsx(Ye,{value:"private",children:"Private — Members keep their contacts private"}),e.jsx(Ye,{value:"leader_only",children:"Leader Only — Only team leaders can see member contacts"}),e.jsx(Ye,{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(se,{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(Tn,{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(se,{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(Tn,{checked:s.shared_assets_enabled,onCheckedChange:r=>n({shared_assets_enabled:r})})]})]})]}),s.lead_pond_enabled&&e.jsx(m8t,{teamId:s.id})]})},eYn=()=>{const{data:s,isLoading:t,teams:n,activeTeamId:r,setActiveTeamId:a}=Nw(),{useTeamMembers:i}=CC(),{data:l=[],isLoading:o}=i((s==null?void 0:s.teamId)||"");if(t)return e.jsx(Ks,{title:"My Team",description:"Your team",children:e.jsxs("div",{className:"space-y-4",children:[e.jsx(on,{className:"h-8 w-48"}),e.jsx(on,{className:"h-40 w-full"})]})});if(!s)return e.jsx(Ks,{title:"My Team",description:"Your team",children:e.jsx(_e,{children:e.jsxs(Oe,{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(qn,{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(Ks,{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(Ng,{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($e,{variant:s.role==="team_leader"?"default":"secondary",className:"capitalize",children:s.role==="team_leader"?e.jsxs(e.Fragment,{children:[e.jsx(Ng,{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(ua,{defaultValue:"members",className:"space-y-4",children:[e.jsxs(ha,{className:"flex-wrap",children:[e.jsx(Qt,{value:"members",children:"Members"}),c.contact_visibility!=="private"&&e.jsxs(Qt,{value:"contacts",children:[e.jsx(hR,{className:"mr-1 h-3.5 w-3.5"}),"Team Contacts"]}),c.lead_pond_enabled&&e.jsxs(Qt,{value:"lead-pond",children:[e.jsx(f1,{className:"mr-1 h-3.5 w-3.5"}),"Lead Pond"]}),c.shared_assets_enabled&&e.jsxs(Qt,{value:"shared-assets",children:[e.jsx(cv,{className:"mr-1 h-3.5 w-3.5"}),"Shared Assets"]}),s.role==="team_leader"&&e.jsxs(Qt,{value:"settings",children:[e.jsx(pc,{className:"mr-1 h-3.5 w-3.5"}),"Settings"]})]}),e.jsx(Jt,{value:"members",className:"space-y-2",children:o?e.jsx("div",{className:"space-y-3",children:[1,2,3].map(d=>e.jsx(on,{className:"h-16 w-full"},d))}):l.map(d=>{var u,h,m,p;return e.jsx(_e,{children:e.jsxs(Oe,{className:"flex items-center gap-3 p-4",children:[e.jsxs(Ea,{className:"h-10 w-10",children:[e.jsx(ki,{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($e,{className:"ml-auto bg-amber-500/10 text-amber-600 border-amber-500",children:[e.jsx(Ng,{className:"mr-1 h-3 w-3"})," Leader"]}):e.jsx($e,{variant:"secondary",className:"ml-auto",children:"Member"})]})},d.id)})}),c.contact_visibility!=="private"&&e.jsx(Jt,{value:"contacts",className:"space-y-4",children:e.jsx(HWe,{})}),c.lead_pond_enabled&&e.jsx(Jt,{value:"lead-pond",className:"space-y-4",children:e.jsx(GWe,{teamId:s.teamId})}),c.shared_assets_enabled&&e.jsx(Jt,{value:"shared-assets",className:"space-y-4",children:e.jsx(x8t,{teamId:s.teamId})}),s.role==="team_leader"&&e.jsx(Jt,{value:"settings",className:"space-y-4",children:e.jsx(JKn,{team:c})})]},s.teamId)]})})},W_t={Home:"🏠",Search:"🔍",DollarSign:"💰",Coffee:"☕",Calendar:"📅",Users:"👥",Phone:"📞",Video:"🎥"};function tYn({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(_e,{children:[e.jsxs(Bt,{className:"flex flex-row items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(Ut,{children:"Booking Types"}),e.jsx(vr,{children:"The meeting types prospects can book with you"})]}),e.jsxs($,{onClick:o,size:"sm",children:[e.jsx(sn,{className:"h-4 w-4 mr-1"})," Add Type"]})]}),e.jsx(Oe,{children:s.length===0?e.jsx("p",{className:"text-center text-muted-foreground py-8",children:"No booking types yet. Add one to get started."}):e.jsx("div",{className:"grid gap-3",children:s.map(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:W_t[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($e,{variant:"secondary",className:"text-xs",children:"Inactive"}),u.is_coaching_only&&e.jsx($e,{variant:"outline",className:"text-xs",children:"Coaching only"}),u.qualification_enabled&&e.jsxs($e,{variant:"outline",className:"text-xs gap-1",children:[e.jsx(IK,{className:"h-3 w-3"})," Qualifying"]})]}),e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(Hr,{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($,{variant:"ghost",size:"sm",onClick:()=>c(u),children:e.jsx(Ya,{className:"h-4 w-4"})}),e.jsx($,{variant:"ghost",size:"sm",onClick:()=>n(u.id),className:"text-destructive hover:text-destructive",children:e.jsx(Pn,{className:"h-4 w-4"})})]})]},u.id))})})]}),e.jsx(Os,{open:i,onOpenChange:l,children:e.jsxs(Rs,{children:[e.jsx(Us,{children:e.jsxs(zs,{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(se,{children:"Name"}),e.jsx(be,{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(se,{children:"Description"}),e.jsx(Is,{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(se,{children:"Duration (minutes)"}),e.jsx(be,{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(se,{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(be,{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(se,{children:"Max bookings per day"}),e.jsx(be,{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(se,{children:"Icon"}),e.jsx("div",{className:"flex flex-wrap gap-2",children:Object.entries(W_t).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(se,{children:"Meeting Link Override (optional)"}),e.jsx(be,{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(se,{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(Tn,{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(se,{children:"Pre-Qualification Questions"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Ask qualifying questions before booking"})]}),e.jsx(Tn,{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(se,{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(Tn,{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(se,{children:"Active"}),e.jsx(Tn,{checked:r.is_active??!0,onCheckedChange:u=>a({...r,is_active:u})})]})]}),e.jsxs(kr,{children:[e.jsx($,{variant:"outline",onClick:()=>l(!1),children:"Cancel"}),e.jsx($,{onClick:d,children:"Save"})]})]})})]})}const sYn={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 nYn({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(Lo,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"font-medium",children:i.guest_name}),e.jsx($e,{className:`text-xs ${sYn[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(Nl,{className:"h-3.5 w-3.5"}),Hs(new Date(i.booking_date+"T00:00:00"),"MMM d, yyyy")]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Hr,{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(nn,{className:"h-3 w-3"}),i.guest_email]}),i.guest_phone&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(ya,{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($e,{variant:"outline",className:"text-xs",children:i.booking_type.name}),i.google_sync_status==="synced"&&e.jsxs($e,{variant:"outline",className:"text-xs gap-1 text-emerald-700 border-emerald-300 dark:text-emerald-400",children:[e.jsx(gy,{className:"h-3 w-3"})," On Google Calendar"]}),i.google_sync_status==="failed"&&e.jsxs($e,{variant:"outline",className:"text-xs gap-1 text-amber-700 border-amber-300 dark:text-amber-400",children:[e.jsx(xz,{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($,{variant:"ghost",size:"sm",onClick:()=>t(i.id),className:"text-destructive hover:text-destructive",children:[e.jsx($d,{className:"h-4 w-4 mr-1"})," Cancel"]})]},i.id)};return e.jsxs("div",{className:"space-y-6",children:[e.jsxs(_e,{children:[e.jsxs(Bt,{children:[e.jsx(Ut,{children:"Upcoming Bookings"}),e.jsxs(vr,{children:[n.length," upcoming appointment",n.length!==1?"s":""]})]}),e.jsx(Oe,{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(_e,{children:[e.jsx(Bt,{children:e.jsx(Ut,{children:"Past & Cancelled"})}),e.jsx(Oe,{children:e.jsx("div",{className:"space-y-3",children:r.slice(0,20).map(i=>a(i))})})]})]})}function rYn(){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:x}=a6t(),[g,y]=j.useState("");j.useState(15),g||s!=null&&s.meeting_link;const b=s!=null&&s.slug?`https://booking.relevelup.com/${s.slug}`:null;return i?e.jsx(Ks,{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(Ks,{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(Nl,{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:[b&&e.jsxs(e.Fragment,{children:[e.jsxs($,{variant:"outline",size:"sm",onClick:()=>{navigator.clipboard.writeText(b),ae.success("Booking link copied!")},children:[e.jsx(Ca,{className:"h-4 w-4 mr-1"})," Copy Link"]}),e.jsx($,{variant:"outline",size:"sm",asChild:!0,children:e.jsxs("a",{href:b,target:"_blank",rel:"noopener noreferrer",children:[e.jsx(Tr,{className:"h-4 w-4 mr-1"})," Preview"]})})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(se,{htmlFor:"scheduler-active",className:"text-sm",children:"Active"}),e.jsx(Tn,{id:"scheduler-active",checked:s.is_active,onCheckedChange:v=>o.mutate({is_active:v})})]})]})]}),e.jsxs(ua,{defaultValue:"types",className:"space-y-4",children:[e.jsxs(ha,{children:[e.jsx(Qt,{value:"types",children:"Booking Types"}),e.jsx(Qt,{value:"availability",children:"Availability"}),e.jsx(Qt,{value:"settings",children:"Settings"}),e.jsxs(Qt,{value:"bookings",children:["Bookings",a.filter(v=>v.status==="confirmed").length>0&&e.jsx($e,{variant:"secondary",className:"ml-1.5 text-xs",children:a.filter(v=>v.status==="confirmed").length})]})]}),e.jsx(Jt,{value:"types",children:e.jsx(tYn,{types:t,onSave:v=>c.mutate(v),onDelete:v=>d.mutate(v)})}),e.jsx(Jt,{value:"availability",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(i6t,{slots:n,onSave:v=>u.mutate(v),onDelete:v=>h.mutate(v)}),e.jsx(o6t,{blockedDates:r,onAdd:v=>m.mutate(v),onRemove:v=>p.mutate(v)})]})}),e.jsxs(Jt,{value:"settings",className:"space-y-6",children:[e.jsx(c6t,{scope:"agent"}),e.jsxs(_e,{children:[e.jsxs(Bt,{children:[e.jsxs(Ut,{className:"flex items-center gap-2",children:[e.jsx(G3,{className:"h-5 w-5"}),"General Settings"]}),e.jsx(vr,{children:"Configure your booking page defaults"})]}),e.jsxs(Oe,{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Booking Page URL"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(be,{value:s.slug,readOnly:!0,className:"bg-muted"}),e.jsx($,{variant:"outline",size:"sm",onClick:()=>{b&&(navigator.clipboard.writeText(b),ae.success("Copied!"))},children:e.jsx(Ca,{className:"h-4 w-4"})})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:b})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(se,{htmlFor:"meeting-link",children:[e.jsx(Dc,{className:"h-4 w-4 inline mr-1"}),"Default Meeting Link"]}),e.jsx(be,{id:"meeting-link",placeholder:"https://zoom.us/j/your-personal-link",defaultValue:s.meeting_link||"",onBlur:v=>o.mutate({meeting_link:v.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(se,{children:"Buffer Between Meetings"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(be,{type:"number",min:0,max:60,defaultValue:s.buffer_minutes,onBlur:v=>o.mutate({buffer_minutes:parseInt(v.target.value)||15})}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"min"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Minimum Notice"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(be,{type:"number",min:0,max:72,defaultValue:s.min_notice_hours,onBlur:v=>o.mutate({min_notice_hours:parseInt(v.target.value)||2})}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"hours"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Max Advance Booking"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(be,{type:"number",min:1,max:90,defaultValue:s.max_advance_days,onBlur:v=>o.mutate({max_advance_days:parseInt(v.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(se,{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(Tn,{checked:s.reminders_enabled!==!1,onCheckedChange:v=>o.mutate({reminders_enabled:v})})]}),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(Tn,{checked:!!s.sms_reminders_enabled,onCheckedChange:v=>o.mutate({sms_reminders_enabled:v})})]})]}),e.jsxs("div",{className:"space-y-2 pt-2 border-t",children:[e.jsx(se,{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($,{variant:"outline",size:"sm",onClick:()=>{navigator.clipboard.writeText(``),ae.success("Embed code copied")},children:[e.jsx(Ca,{className:"h-4 w-4 mr-1.5"})," Copy embed code"]})]})]})]})]}),e.jsx(Jt,{value:"bookings",children:e.jsx(nYn,{bookings:a,onCancel:v=>x.mutate({id:v})})})]})]})}):e.jsx(Ks,{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(Nl,{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(_e,{children:e.jsxs(Oe,{className:"pt-6 space-y-4",children:[e.jsx("div",{className:"grid grid-cols-2 gap-4",children:[{icon:"🏠",title:"Listing Consultation",desc:"60 min"},{icon:"🔍",title:"Buyer Consultation",desc:"45 min"},{icon:"💰",title:"Home Valuation",desc:"30 min"},{icon:"☕",title:"General Meeting",desc:"30 min"}].map(v=>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:v.icon}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-sm",children:v.title}),e.jsx("p",{className:"text-xs text-muted-foreground",children:v.desc})]})]},v.title))}),e.jsx(Hl,{}),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($,{onClick:()=>l.mutate(),disabled:l.isPending,className:"w-full",size:"lg",children:[e.jsx(dn,{className:"h-4 w-4 mr-2"}),l.isPending?"Setting up...":"Activate Scheduler"]})]})})]})})}function aYn(s,t,n=!0){return ht({queryKey:["my-calendar",s,t],enabled:n&&!!s&&!!t,staleTime:6e4,queryFn:async()=>{const{data:r,error:a}=await U.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 CRe(s){const{data:t,error:n}=await U.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 iYn(){const s=ts(),t=()=>{s.invalidateQueries({queryKey:["my-calendar"]}),s.invalidateQueries({queryKey:["agent-appointments"]})},n=yt({mutationFn:async i=>CRe({action:i.id?"update":"create",...i}),onSuccess:t}),r=yt({mutationFn:async i=>CRe({action:"cancel",id:i}),onSuccess:t});return{save:n,remove:r,checkConflicts:async(i,l,o)=>CRe({action:"check_conflicts",start_at:i,end_at:l,id:o})}}const uKt="America/New_York";function K_t(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:uKt,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 x;return Number((x=u.find(g=>g.type===p))==null?void 0:x.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 ARe(s){const t=new Intl.DateTimeFormat("en-CA",{timeZone:uKt,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 oYn=[{id:"google_meet",label:"Google Meet",icon:Xr},{id:"in_person",label:"In person",icon:ai},{id:"phone",label:"Phone",icon:ya}];function lYn({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}=iYn(),m=!!(l!=null&&l.id),[p,x]=j.useState(""),[g,y]=j.useState(""),[b,v]=j.useState("09:00"),[N,C]=j.useState("09:30"),[A,T]=j.useState("in_person"),[P,M]=j.useState(""),[I,D]=j.useState(""),[B,q]=j.useState([]),[W,V]=j.useState(""),[K,Q]=j.useState(!1);j.useEffect(()=>{if(s){if(l){const ve=ARe(l.start_at),ge=ARe(l.end_at);x(l.title),y(ve.date),v(ve.time),C(ge.time),T(l.meeting_mode),M(l.location||""),D(l.notes||""),q((l.agent_appointment_contacts||[]).map(fe=>fe.contact_id))}else{x(""),y(n||ARe(new Date().toISOString()).date);const ve=r||"09:00",[ge,fe]=ve.split(":").map(Number),je=ge*60+fe+30;v(ve),C(`${`${Math.floor(je/60)%24}`.padStart(2,"0")}:${`${je%60}`.padStart(2,"0")}`),T(o?"google_meet":"in_person"),M(""),D(""),q(a?[a]:[])}V(""),Q(!1)}},[s,l,n,r,a,o]),j.useEffect(()=>{if(N<=b){const[ve,ge]=b.split(":").map(Number),fe=new Date(0,0,0,ve,ge+30);C(`${String(fe.getHours()).padStart(2,"0")}:${String(fe.getMinutes()).padStart(2,"0")}`)}},[b]);const J=j.useMemo(()=>g?K_t(g,b):"",[g,b]),ce=j.useMemo(()=>g?K_t(g,N):"",[g,N]);j.useEffect(()=>{if(!s||!o||!J||!ce)return;let ve=!1;const ge=setTimeout(async()=>{try{const fe=await h(J,ce,l==null?void 0:l.id);ve||Q(!!fe.conflicts.length)}catch{}},500);return()=>{ve=!0,clearTimeout(ge)}},[s,o,J,ce]);const{data:ue=[]}=ht({queryKey:["appointment-contact-search",W],enabled:s,queryFn:async()=>{let ve=U.from("innercircle_contacts").select("id, first_name, last_name, email").not("email","is",null).neq("email","").like("email","%@%").order("first_name").limit(20);if(W.trim()){const je=`%${W.trim()}%`;ve=ve.or(`first_name.ilike.${je},last_name.ilike.${je},email.ilike.${je}`)}const{data:ge,error:fe}=await ve;if(fe)throw fe;return(ge||[]).filter(je=>!!je.email&&/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(je.email.trim()))}}),{data:ne=[]}=ht({queryKey:["appointment-selected-contacts",B],enabled:s&&B.length>0,queryFn:async()=>{const{data:ve}=await U.from("innercircle_contacts").select("id, first_name, last_name, email").in("id",B);return ve||[]}}),ee=ve=>[ve.first_name,ve.last_name].filter(Boolean).join(" ")||ve.email||"Contact",le=async()=>{if(!p.trim())return ae.error("Give the appointment a title");if(!g)return ae.error("Pick a date");try{await d.mutateAsync({id:l==null?void 0:l.id,title:p.trim(),start_at:J,end_at:ce,meeting_mode:A,location:A==="google_meet"?null:P||null,notes:I||null,deal_id:i??(l==null?void 0:l.deal_id)??null,contact_ids:B}),ae.success(m?"Appointment updated":"Appointment created"),c==null||c(),t(!1)}catch(ve){ae.error(ve instanceof Error?ve.message:"Could not save the appointment")}},he=async()=>{if(l!=null&&l.id)try{await u.mutateAsync(l.id),ae.success("Appointment deleted"),c==null||c(),t(!1)}catch(ve){ae.error(ve instanceof Error?ve.message:"Could not delete the appointment")}};return e.jsx(Os,{open:s,onOpenChange:t,children:e.jsxs(Rs,{className:"max-w-lg max-h-[90vh] overflow-y-auto",children:[e.jsxs(Us,{children:[e.jsx(zs,{children:m?"Edit appointment":"New appointment"}),e.jsx(Sr,{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(se,{children:"Title"}),e.jsx(be,{value:p,onChange:ve=>x(ve.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(se,{children:"Date"}),e.jsx(be,{type:"date",value:g,onChange:ve=>y(ve.target.value)})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:"Start"}),e.jsx(be,{type:"time",value:b,onChange:ve=>v(ve.target.value)})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:"End"}),e.jsx(be,{type:"time",value:N,onChange:ve=>C(ve.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(mc,{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(se,{children:"Meeting type"}),e.jsx("div",{className:"flex flex-wrap gap-2",children:oYn.map(ve=>{const ge=ve.icon,fe=A===ve.id;return e.jsxs("button",{type:"button",onClick:()=>T(ve.id),className:Tt("inline-flex items-center gap-2 rounded-full border px-3 py-1.5 text-xs font-medium transition-colors",fe?"bg-primary text-primary-foreground border-primary":"hover:bg-accent"),children:[e.jsx(ge,{className:"h-3.5 w-3.5"}),ve.label]},ve.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(se,{children:A==="phone"?"Phone number":"Location"}),e.jsx(be,{value:P,onChange:ve=>M(ve.target.value),placeholder:A==="phone"?"(555) 123-4567":"123 Main St, Suite 200"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs(se,{className:"flex items-center gap-1.5",children:[e.jsx(qn,{className:"h-3.5 w-3.5"})," Contacts"]}),ne.length>0&&e.jsx("div",{className:"flex flex-wrap gap-1.5",children:ne.map(ve=>e.jsxs($e,{variant:"secondary",className:"max-w-[220px] gap-1",title:ee(ve),children:[e.jsx("span",{className:"truncate",children:ee(ve)}),e.jsx("button",{type:"button",onClick:()=>q(ge=>ge.filter(fe=>fe!==ve.id)),children:e.jsx(pr,{className:"h-3 w-3"})})]},ve.id))}),e.jsx(be,{value:W,onChange:ve=>V(ve.target.value),placeholder:"Search contacts with an email…"}),W.trim()&&e.jsxs("div",{className:"max-h-40 overflow-y-auto rounded-lg border divide-y",children:[ue.filter(ve=>!B.includes(ve.id)).map(ve=>e.jsxs("button",{type:"button",onClick:()=>{q(ge=>[...ge,ve.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:[ee(ve),ve.email].filter(Boolean).join(" · "),children:[e.jsx("span",{className:"min-w-0 flex-1 truncate font-medium",children:ee(ve)}),ve.email&&e.jsx("span",{className:"max-w-[45%] shrink-0 truncate text-xs text-muted-foreground",children:ve.email})]},ve.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:B.length===0?"Tap a search result to add a guest — they get the Google invite.":`${B.length} guest${B.length>1?"s":""} will be invited to the calendar event.`})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:"Notes"}),e.jsx(Is,{value:I,onChange:ve=>D(ve.target.value),rows:3,placeholder:"Anything you want on the invite…"})]})]}),e.jsxs(kr,{className:"gap-2 sm:justify-between",children:[m?e.jsxs($,{variant:"ghost",onClick:he,disabled:u.isPending,className:"text-destructive hover:text-destructive",children:[e.jsx(Pn,{className:"h-4 w-4 mr-1.5"})," Delete"]}):e.jsx("span",{}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx($,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsx($,{onClick:le,disabled:d.isPending,children:d.isPending?"Saving…":m?"Save changes":"Create appointment"})]})]})]})})}function cYn(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:"America/New_York",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 eK(s){const[t,n,r]=s.split(/[-/T]/).map(Number);return new Date(t,(n||1)-1,r||1)}function j_(s){const t=`${s.getMonth()+1}`.padStart(2,"0"),n=`${s.getDate()}`.padStart(2,"0");return`${s.getFullYear()}-${t}-${n}`}function B4(s,t){const n=new Date(s);return n.setDate(n.getDate()+t),n}function ERe(s){return B4(s,-s.getDay())}function yA(){return new Intl.DateTimeFormat("en-CA",{timeZone:"America/New_York",year:"numeric",month:"2-digit",day:"2-digit"}).format(new Date)}function xQe(s){return s?new Intl.DateTimeFormat("en-US",{timeZone:"America/New_York",hour:"numeric",minute:"2-digit"}).format(new Date(s)).toLowerCase().replace(" ",""):""}function _Q(s){return new Intl.DateTimeFormat("en-US",{weekday:"long",month:"long",day:"numeric"}).format(eK(s))}const tqe=[{id:"google",label:"Google Calendar",color:"#4285F4",soft:"#4285F41A",icon:Nl},{id:"appointments",label:"My appointments",color:"#0F766E",soft:"#0F766E1A",icon:gg},{id:"bookings",label:"Guest bookings",color:"#406E71",soft:"#406E711A",icon:Hr},{id:"deals",label:"Deal dates",color:"#2a4c64",soft:"#2a4c641A",icon:IN},{id:"tasks",label:"Tasks",color:"#B45309",soft:"#B453091A",icon:Jh},{id:"open_houses",label:"Open houses",color:"#7C3AED",soft:"#7C3AED1A",icon:sa},{id:"events",label:"LevelUp events",color:"#0EA5E9",soft:"#0EA5E91A",icon:dn},{id:"coaching",label:"Coaching",color:"#DB2777",soft:"#DB27771A",icon:Xr}],GTe=Object.fromEntries(tqe.map(s=>[s.id,s])),hKt="levelup.myCalendar.layers",Y_t="levelup.myCalendar.view";function dYn(){try{return JSON.parse(localStorage.getItem(hKt)||"{}")}catch{return{}}}function uYn(){var ge,fe;const s=Vn(),[t,n]=oc(),[r,a]=j.useState(()=>eK(yA())),[i,l]=j.useState(()=>localStorage.getItem(Y_t)||"month"),[o,c]=j.useState(dYn),[d,u]=j.useState(yA()),[h,m]=j.useState(!1),[p,x]=j.useState(yA()),[g,y]=j.useState(void 0),[b,v]=j.useState(null),N=(je,Ee)=>{v(null);const Me=yA(),De=je||Me;x(De{u(je),a(eK(je)),l("day")},A=je=>{je.layer==="appointments"&&(v(cYn(je)),m(!0))};j.useEffect(()=>localStorage.setItem(Y_t,i),[i]),j.useEffect(()=>localStorage.setItem(hKt,JSON.stringify(o)),[o]);const T=l6t(!0,"agent");j.useEffect(()=>{const je=t.get("google_calendar");if(!je)return;je==="connected"?ae.success("Google Calendar connected"):ae.error(t.get("google_calendar_error")||"Google Calendar connection failed");const Ee=new URLSearchParams(t);Ee.delete("google_calendar"),Ee.delete("google_calendar_error"),n(Ee,{replace:!0})},[t,n]);const{rangeStart:P,rangeEnd:M,gridDays:I}=j.useMemo(()=>{if(i==="week"){const De=ERe(r);return{rangeStart:j_(De),rangeEnd:j_(B4(De,6)),gridDays:Array.from({length:7},(ze,ke)=>B4(De,ke))}}if(i==="day")return{rangeStart:j_(r),rangeEnd:j_(r),gridDays:[r]};if(i==="agenda")return{rangeStart:j_(r),rangeEnd:j_(B4(r,44)),gridDays:[]};const je=new Date(r.getFullYear(),r.getMonth(),1),Ee=ERe(je),Me=Array.from({length:42},(De,ze)=>B4(Ee,ze));return{rangeStart:j_(Ee),rangeEnd:j_(Me[41]),gridDays:Me}},[r,i]),{data:D,isLoading:B,isFetching:q,refetch:W,error:V}=aYn(P,M),K=!!((ge=T.status.data)!=null&&ge.connected)||!!(D!=null&&D.google.connected),Q=j.useMemo(()=>((D==null?void 0:D.items)||[]).filter(je=>!o[je.layer]),[D,o]),J=j.useMemo(()=>{const je=new Map;return Q.forEach(Ee=>{const Me=je.get(Ee.date)||[];Me.push(Ee),je.set(Ee.date,Me)}),je},[Q]),ce=j.useMemo(()=>J.get(d)||[],[J,d]),ue=yA(),ne=j.useMemo(()=>Q.filter(je=>je.date>=ue).slice(0,6),[Q,ue]),ee=j.useMemo(()=>Q.filter(je=>{var Ee,Me;return je.date{if(i==="week"){const je=ERe(r),Ee=B4(je,6),Me=je.getMonth()===Ee.getMonth(),De=(ze,ke)=>new Intl.DateTimeFormat("en-US",{month:ke?"short":void 0,day:"numeric"}).format(ze);return`${De(je,!0)} – ${De(Ee,!Me)}, ${Ee.getFullYear()}`}return i==="day"?_Q(j_(r)):i==="agenda"?"Next 45 days":new Intl.DateTimeFormat("en-US",{month:"long",year:"numeric"}).format(r)},[r,i]),he=je=>{if(i==="day"){a(Ee=>{const Me=B4(Ee,je);return u(j_(Me)),Me});return}a(i==="week"?Ee=>B4(Ee,je*7):i==="agenda"?Ee=>B4(Ee,je*45):Ee=>new Date(Ee.getFullYear(),Ee.getMonth()+je,1))},ve=je=>{if(je==="google"&&!K){T.connect.mutate();return}c(Ee=>({...Ee,[je]:!Ee[je]}))};return e.jsxs(Ks,{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("div",{className:"flex items-center gap-2",children:[e.jsxs($,{variant:"outline",size:"sm",onClick:()=>W(),disabled:q,className:"rounded-full",children:[e.jsx(Wi,{className:Tt("h-4 w-4 mr-2",q&&"animate-spin")}),"Refresh"]}),e.jsxs($,{size:"sm",className:"rounded-full",onClick:()=>N(),children:[e.jsx(sn,{className:"h-4 w-4 mr-1.5"}),"New appointment"]}),e.jsxs($,{variant:"outline",size:"sm",className:"rounded-full",onClick:()=>s("/mission-control/scheduler"),children:["Scheduler settings",e.jsx(ni,{className:"h-4 w-4 ml-2"})]})]})]}),e.jsxs("div",{className:"mt-4 flex flex-wrap items-center gap-2",children:[K?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(Fr,{className:"h-3.5 w-3.5"}),"Google Calendar connected",((fe=T.status.data)==null?void 0:fe.account_email)&&e.jsxs("span",{className:"opacity-70",children:["· ",T.status.data.account_email]})]}):e.jsxs("button",{onClick:()=>T.connect.mutate(),disabled:T.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(Nl,{className:"h-3.5 w-3.5"}),T.connect.isPending?"Opening Google…":"Connect Google Calendar"]}),(D==null?void 0:D.google.error)&&e.jsxs("span",{className:"inline-flex items-center gap-1.5 text-xs text-destructive",children:[e.jsx(xo,{className:"h-3.5 w-3.5"}),D.google.error]})]})]}),!K&&!T.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(Nl,{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($,{onClick:()=>T.connect.mutate(),disabled:T.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($,{variant:"outline",size:"icon",className:"rounded-full h-9 w-9",onClick:()=>he(-1),children:e.jsx(Ic,{className:"h-4 w-4"})}),e.jsx($,{variant:"outline",size:"icon",className:"rounded-full h-9 w-9",onClick:()=>he(1),children:e.jsx(Ja,{className:"h-4 w-4"})}),e.jsx($,{variant:"ghost",size:"sm",className:"rounded-full",onClick:()=>{a(eK(yA())),u(yA())},children:"Today"}),e.jsx("h2",{className:"text-lg font-semibold ml-1 text-foreground",children:le})]}),e.jsx("div",{className:"inline-flex rounded-full border p-1 bg-card",children:["month","week","day","agenda"].map(je=>e.jsx("button",{onClick:()=>{je==="day"&&a(eK(d||yA())),l(je)},className:Tt("px-3.5 py-1.5 text-xs font-medium rounded-full capitalize transition-all",i===je?"bg-primary text-primary-foreground shadow-sm":"text-muted-foreground hover:text-foreground"),children:je},je))})]}),e.jsx("div",{className:"flex flex-wrap gap-2",children:tqe.map(je=>{const Ee=je.id==="google"?!K:o[je.id],Me=je.icon;return e.jsxs("button",{onClick:()=>ve(je.id),className:Tt("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",Ee&&"border-dashed opacity-70"),style:Ee?void 0:{background:je.soft,borderColor:`${je.color}55`,color:je.color},children:[e.jsx(Me,{className:"h-3.5 w-3.5"}),je.label,je.id==="google"&&!K&&e.jsx("span",{className:"opacity-70",children:"· connect"})]},je.id)})}),V&&e.jsx(_e,{className:"p-4 border-destructive/40",children:e.jsx("p",{className:"text-sm text-destructive",children:V.message})}),e.jsxs("div",{className:"grid grid-cols-1 xl:grid-cols-[minmax(0,1fr)_320px] gap-5",children:[e.jsx(_e,{className:"rounded-2xl overflow-hidden shadow-sm",children:B?e.jsx("div",{className:"p-6 space-y-3",children:Array.from({length:6}).map((je,Ee)=>e.jsx(on,{className:"h-16 w-full"},Ee))}):i==="agenda"?e.jsx(mYn,{items:Q,today:ue,onOpenItem:A}):i==="day"?e.jsx(pYn,{dayKey:j_(r),items:J.get(j_(r))||[],today:ue,onCreate:N,onOpenItem:A}):e.jsx(hYn,{days:I,byDay:J,anchorMonth:r.getMonth(),today:ue,week:i==="week",selectedDay:d,onSelectDay:u,onOpenDay:C,onCreate:N,onOpenItem:A})}),e.jsxs("div",{className:"space-y-4",children:[i!=="day"&&ce.length>0&&e.jsxs(_e,{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(Nl,{className:"h-4 w-4 text-primary"})," ",_Q(d)]}),e.jsxs($,{size:"sm",variant:"ghost",className:"rounded-full h-7 px-2 text-xs",onClick:()=>C(d),children:["Day view ",e.jsx(ni,{className:"h-3 w-3 ml-1"})]})]}),e.jsx("div",{className:"space-y-2",children:ce.map(je=>e.jsx(TRe,{item:je,onOpen:s},je.id))})]}),e.jsxs(_e,{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(Hr,{className:"h-4 w-4 text-primary"})," Up next"]}),ne.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:ne.map(je=>e.jsx(TRe,{item:je,onOpen:s},je.id))})]}),ee.length>0&&e.jsxs(_e,{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(xo,{className:"h-4 w-4 text-destructive"})," Needs attention"]}),e.jsx("div",{className:"space-y-2",children:ee.map(je=>e.jsx(TRe,{item:je,onOpen:s,overdue:!0},je.id))})]}),e.jsxs(_e,{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:tqe.filter(je=>!o[je.id]).map(je=>{const Ee=Q.filter(Me=>Me.layer===je.id).length;return Ee?e.jsxs("div",{className:"rounded-xl px-3 py-2",style:{background:je.soft},children:[e.jsx("p",{className:"text-lg font-semibold",style:{color:je.color},children:Ee}),e.jsx("p",{className:"text-[11px] text-muted-foreground leading-tight",children:je.label})]},je.id):null})})]})]})]})]}),e.jsx(lYn,{open:h,onOpenChange:m,defaultDate:p,defaultTime:g,appointment:b,googleConnected:K,onSaved:()=>W()})]})}function TRe({item:s,onOpen:t,overdue:n}){const r=GTe[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:[_Q(s.date),s.start&&!s.allDay?` · ${xQe(s.start)}`:"",s.subtitle?` · ${s.subtitle}`:""]})]}),n&&e.jsx($e,{variant:"destructive",className:"text-[10px]",children:"Overdue"})]})}function sqe({item:s,onOpen:t}){var c,d;const n=GTe[s.layer],r=s.layer==="tasks"?!!((c=s.meta)!=null&&c.done):!!((d=s.meta)!=null&&d.completed),a=Tt("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:xQe(s.start)}),e.jsx("span",{className:"truncate",children:s.title}),s.externalLink&&!s.link&&e.jsx(Tr,{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 hYn({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:Tt("grid grid-cols-7",a?"min-h-[520px]":""),children:s.map(h=>{const m=j_(h),p=t.get(m)||[],x=m===r,g=!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:Tt("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]",g&&"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:Tt("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",x?"bg-primary text-primary-foreground hover:bg-primary":g?"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(sn,{className:"h-3.5 w-3.5"})})]})]}),e.jsxs("div",{className:"space-y-1",children:[p.slice(0,u).map(y=>e.jsx(sqe,{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 mYn({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:Tt("text-sm font-semibold",a===t?"text-primary":"text-foreground"),children:_Q(a)}),a===t&&e.jsx($e,{className:"text-[10px]",children:"Today"})]}),e.jsx("div",{className:"space-y-2",children:i.map(l=>{const o=GTe[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":xQe(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($e,{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(Nl,{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 Z_t=6,X_t=22,oW=60;function sie(s){var a,i;const t=new Intl.DateTimeFormat("en-US",{timeZone:"America/New_York",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 pYn({dayKey:s,items:t,today:n,onCreate:r,onOpenItem:a}){const[i,l]=j.useState(()=>sie(new Date().toISOString()));j.useEffect(()=>{const C=setInterval(()=>l(sie(new Date().toISOString())),6e4);return()=>clearInterval(C)},[]);const o=t.filter(C=>C.allDay||!C.start),c=t.filter(C=>!C.allDay&&C.start).map(C=>{const A=sie(C.start),T=C.end?Math.max(sie(C.end),A+15):A+30;return{item:C,start:A,end:T}}).sort((C,A)=>C.start-A.start||C.end-A.end),d=[];let u=[];const h=()=>{if(!u.length)return;const C=[];u.map(T=>{let P=C.findIndex(M=>M<=T.start);return P===-1?(P=C.length,C.push(T.end)):C[P]=T.end,{...T,col:P}}).forEach(T=>d.push({...T,cols:C.length})),u=[]};let m=-1;for(const C of c)u.length&&C.start>=m&&h(),u.push(C),m=Math.max(m,C.end);h();const p=c.length?Math.min(...c.map(C=>C.start)):Z_t*60,x=c.length?Math.max(...c.map(C=>C.end)):X_t*60,g=Math.min(Z_t,Math.floor(p/60)),y=Math.max(X_t,Math.ceil(x/60)),b=Array.from({length:y-g+1},(C,A)=>g+A),v=C=>(C-g*60)/60*oW,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:_Q(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($,{size:"sm",variant:"outline",className:"rounded-full",onClick:()=>r(s),children:[e.jsx(sn,{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(C=>e.jsx("span",{className:"max-w-[240px]",children:e.jsx(sqe,{item:C,onOpen:a})},C.id))]}),e.jsx("div",{className:"relative overflow-y-auto max-h-[640px] pt-3 pb-4",children:e.jsxs("div",{className:"relative",style:{height:b.length*oW},children:[b.map((C,A)=>e.jsxs("div",{className:"absolute left-0 right-0 border-t border-border/60",style:{top:A*oW,height:oW},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,C)).toLowerCase()}),e.jsx("button",{type:"button","aria-label":`Create at ${C}:00`,onClick:()=>r==null?void 0:r(s,`${`${C}`.padStart(2,"0")}:00`),className:"absolute left-16 right-2 top-0 h-full rounded-md hover:bg-accent/50 transition-colors"})]},C)),N&&i>=g*60&&i<=y*60&&e.jsxs("div",{className:"absolute left-14 right-2 z-20 pointer-events-none",style:{top:v(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:C,start:A,end:T,col:P,cols:M})=>{const I=GTe[C.layer],D=Math.max(22,(T-A)/60*oW-4),B=100/M;return e.jsx("div",{className:"absolute z-10",style:{top:v(A)+2,height:D,left:`calc(4rem + ${P*B}% * 0.92)`,width:`calc(${B}% * 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(sqe,{item:C,onOpen:a}),D>44&&C.subtitle&&e.jsx("p",{className:"text-[10px] text-muted-foreground truncate pl-1.5 mt-0.5",children:C.subtitle})]})},C.id)})]})})]})}function nie(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 fYn(s){const[t,n,r]=s.split(/[-/T]/).map(Number);return Hs(new Date(t,n-1,r),"EEEE, MMMM d, yyyy")}function xYn(){var ue;const{token:s}=Vi(),[t]=oc(),[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(""),[x,g]=j.useState(null),[y,b]=j.useState(new Date),[v,N]=j.useState({}),[C,A]=j.useState(!1),[T,P]=j.useState(null),[M,I]=j.useState(null),D=async ne=>{var he,ve;const{data:ee,error:le}=await U.functions.invoke("agent-booking",{body:ne});if(le){let ge=le.message;try{const fe=await((ve=(he=le.context)==null?void 0:he.json)==null?void 0:ve.call(he));fe!=null&&fe.error&&(ge=fe.error)}catch{}throw new Error(ge)}if(ee!=null&&ee.error)throw new Error(ee.error);return ee};j.useEffect(()=>{s&&(async()=>{try{const ne=await D({action:"manage_get",manage_token:s});r(ne),t.get("cancel")==="1"&&d("cancel")}catch(ne){o(ne.message)}finally{i(!1)}})()},[s]),j.useEffect(()=>{if(c!=="reschedule"||!(n!=null&&n.booking_type))return;let ne=!1;return(async()=>{A(!0);try{const ee=new Date(y.getFullYear(),y.getMonth(),1),le=ep(new Date),he=Pb(le,ee)?le:ee,ve=new Date(y.getFullYear(),y.getMonth()+1,0),ge=Math.max(1,Math.round((ve.getTime()-he.getTime())/864e5)+1),fe=await D({action:"availability",slug:n.slug,booking_type_id:n.booking_type.id,start:Hs(he,"yyyy-MM-dd"),days:Math.min(ge,90),ignore_booking_id:n.booking.id});ne||N((fe==null?void 0:fe.availability)||{})}catch(ee){ne||ae.error(ee.message)}finally{ne||A(!1)}})(),()=>{ne=!0}},[c,y,(ue=n==null?void 0:n.booking_type)==null?void 0:ue.id]);const B=j.useMemo(()=>{const ne=y.getFullYear(),ee=y.getMonth(),le=new Date(ne,ee,1),he=new Date(ne,ee+1,0),ve=[];for(let ge=0;ge{h(!0);try{await D({action:"manage_cancel",manage_token:s,reason:m}),g("cancelled"),d("done")}catch(ne){ae.error(ne.message)}finally{h(!1)}},V=async()=>{if(!(!T||!M)){h(!0);try{await D({action:"manage_reschedule",manage_token:s,date:Hs(T,"yyyy-MM-dd"),time:M}),g("rescheduled"),d("done")}catch(ne){ae.error(ne.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(Ht,{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($d,{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:Q,agent:J}=n,ce=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"?x==="cancelled"?"Booking cancelled":"Booking rescheduled":"Manage your booking"}),e.jsxs("p",{className:"text-white/80 text-sm mt-1",children:[(Q==null?void 0:Q.name)||"Meeting",J!=null&&J.name?` with ${J.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(Nl,{className:"h-4 w-4 text-[#406E71]"}),fYn(K.booking_date)]}),e.jsxs("div",{className:"flex items-center gap-2 text-sm text-slate-600",children:[e.jsx(Hr,{className:"h-4 w-4 text-[#406E71]"}),nie(String(K.start_time).slice(0,5))," –"," ",nie(String(K.end_time).slice(0,5)),e.jsxs("span",{className:"text-xs text-slate-400",children:["(",n.timezone.replace(/_/g," "),")"]})]}),ce&&e.jsx("p",{className:"text-xs font-semibold text-red-600 pt-1",children:"This booking is cancelled."})]}),c==="details"&&!ce&&e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-3",children:[n.allow_reschedule&&e.jsx($,{className:"h-12 rounded-xl bg-[#406E71] hover:bg-[#365c5e] text-white font-semibold",onClick:()=>d("reschedule"),children:"Reschedule"}),n.allow_cancel&&e.jsx($,{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"&&!ce&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("p",{className:"text-sm text-slate-600",children:["Let ",(J==null?void 0:J.name)||"your host"," know why you can't make it (optional)."]}),e.jsx(Is,{value:m,onChange:ne=>p(ne.target.value),placeholder:"Something came up…",className:"rounded-xl",rows:3}),e.jsxs("div",{className:"flex gap-3",children:[e.jsx($,{variant:"ghost",className:"flex-1 h-11 rounded-xl",onClick:()=>d("details"),disabled:u,children:"Keep booking"}),e.jsx($,{className:"flex-1 h-11 rounded-xl bg-red-600 hover:bg-red-700 text-white font-semibold",onClick:W,disabled:u,children:u?e.jsx(Ht,{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(ka,{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:()=>b(new Date(y.getFullYear(),y.getMonth()-1,1)),children:e.jsx(Ic,{className:"h-4 w-4 text-slate-500"})}),e.jsx("span",{className:"text-sm font-semibold text-slate-800",children:Hs(y,"MMMM yyyy")}),e.jsx("button",{className:"p-2 rounded-lg hover:bg-slate-100",onClick:()=>b(new Date(y.getFullYear(),y.getMonth()+1,1)),children:e.jsx(Ja,{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((ne,ee)=>e.jsx("div",{className:"text-[11px] font-semibold text-slate-400 py-1",children:ne},ee)),B.map((ne,ee)=>{if(!ne)return e.jsx("div",{},`p${ee}`);const le=Hs(ne,"yyyy-MM-dd"),he=(v[le]||[]).length>0&&!aw(ne,ep(new Date)),ve=T&&hu(ne,T);return e.jsx("button",{disabled:!he,onClick:()=>{P(ne),I(null)},className:`aspect-square rounded-lg text-sm font-medium transition-colors ${ve?"bg-[#406E71] text-white":he?"bg-[#406E71]/10 text-[#406E71] hover:bg-[#406E71]/20":"text-slate-300"}`,children:ne.getDate()},le)})]}),C&&e.jsxs("p",{className:"text-center text-xs text-slate-400 flex items-center justify-center gap-2",children:[e.jsx(Ht,{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:q.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"}):q.map(ne=>e.jsx("button",{onClick:()=>I(ne),className:`px-3 py-2.5 rounded-xl text-sm font-medium ${M===ne?"bg-[#406E71] text-white":"bg-slate-50 text-slate-700 hover:bg-[#406E71]/10"}`,children:nie(ne)},ne))}),e.jsx($,{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(Ht,{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:[x==="cancelled"?e.jsx($d,{className:"h-12 w-12 text-red-500 mx-auto"}):e.jsx(Fr,{className:"h-12 w-12 text-emerald-500 mx-auto"}),e.jsx("p",{className:"text-sm text-slate-600",children:x==="cancelled"?`Your meeting has been cancelled and ${(J==null?void 0:J.name)||"your host"} has been notified.`:`Your meeting is now on ${T?Hs(T,"EEEE, MMMM d"):""} at ${M?nie(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 Q_t=[{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 gYn(){const{user:s}=_s(),t=Za(),{toast:n}=gi(),r=Vn(),a=ts(),[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:x}=ht({queryKey:["landing-pages",t],queryFn:async()=>{const{data:v,error:N}=await U.from("landing_pages").select("*").eq("user_id",t).is("deleted_at",null).order("created_at",{ascending:!1});if(N)throw N;return v},enabled:!!t}),g=yt({mutationFn:async()=>{const v=h.title.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/(^-|-$)/g,"")+"-"+Date.now().toString(36),{data:N}=await U.from("profiles").select("name, phone, avatar_url, email").eq("id",t).single(),C=h.page_type==="just_listed"||h.page_type==="just_sold",{data:A,error:T}=await U.from("landing_pages").insert({user_id:t,title:h.title,description:h.description||null,page_type:h.page_type,slug:v,hero_headline:C?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:C?h.page_type.replace("just_",""):null}).select().single();if(T)throw T;const P=yYn(h.page_type);if(P.length>0){const{error:M}=await U.from("landing_page_fields").insert(P.map((I,D)=>({...I,page_id:A.id,sort_order:D})));if(M)throw M}return A},onSuccess:v=>{a.invalidateQueries({queryKey:["landing-pages"]}),l(!1),m({title:"",description:"",page_type:"lead_capture"}),n({title:"Landing page created!"}),r(`/mission-control/landing-pages/${v.id}`)},onError:v=>n({title:"Error",description:v.message,variant:"destructive"})}),y=yt({mutationFn:async v=>{const{error:N}=await U.from("landing_pages").update({deleted_at:new Date().toISOString(),is_published:!1}).eq("id",v);if(N)throw N},onSuccess:()=>{a.invalidateQueries({queryKey:["landing-pages"]}),c(null),n({title:"Landing page deleted"})}}),b=v=>`https://pages.relevelup.com/${v}`;return e.jsxs(Ks,{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($,{variant:"outline",onClick:()=>r("/mission-control/landing-pages/defaults"),children:[e.jsx(pc,{className:"h-4 w-4 mr-2"})," Defaults"]}),e.jsxs($,{onClick:()=>l(!0),children:[e.jsx(sn,{className:"h-4 w-4 mr-2"})," New Page"]})]})]}),x?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(_e,{children:e.jsxs(Oe,{className:"flex flex-col items-center justify-center py-16",children:[e.jsx(Wr,{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($,{onClick:()=>l(!0),children:[e.jsx(sn,{className:"h-4 w-4 mr-2"})," Create Landing Page"]})]})}):e.jsx("div",{className:"grid gap-4",children:p.map(v=>{var N;return e.jsx(_e,{className:"hover:shadow-md transition-shadow",children:e.jsx(Oe,{className:"p-4",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex-1 min-w-0 cursor-pointer",onClick:()=>r(`/mission-control/landing-pages/${v.id}`),children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("h3",{className:"font-semibold truncate",children:v.title}),e.jsx($e,{variant:v.is_published?"default":"secondary",className:"text-[10px]",children:v.is_published?"Published":"Draft"}),e.jsx($e,{variant:"outline",className:"text-[10px]",children:((N=Q_t.find(C=>C.id===v.page_type))==null?void 0:N.label)||v.page_type})]}),v.description&&e.jsx("p",{className:"text-sm text-muted-foreground mt-1 truncate",children:v.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(ga,{className:"h-3 w-3"})," ",v.view_count," views"]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Wr,{className:"h-3 w-3"})," ",v.submission_count," submissions"]})]})]}),e.jsxs("div",{className:"flex items-center gap-2 ml-4",children:[v.is_published&&e.jsxs(e.Fragment,{children:[e.jsx($,{size:"sm",variant:"outline",onClick:()=>u(b(v.slug)),children:e.jsx(Rx,{className:"h-3.5 w-3.5"})}),e.jsx($,{size:"sm",variant:"outline",onClick:()=>{navigator.clipboard.writeText(b(v.slug)),n({title:"Link copied!"})},children:e.jsx(Ca,{className:"h-3.5 w-3.5"})}),e.jsx($,{size:"sm",variant:"outline",asChild:!0,children:e.jsx("a",{href:b(v.slug),target:"_blank",rel:"noopener noreferrer",children:e.jsx(Tr,{className:"h-3.5 w-3.5"})})})]}),e.jsxs(Hd,{children:[e.jsx(Gd,{asChild:!0,children:e.jsx($,{size:"sm",variant:"ghost",children:e.jsx(cy,{className:"h-4 w-4"})})}),e.jsxs(Md,{align:"end",children:[e.jsxs(Na,{onClick:()=>r(`/mission-control/landing-pages/${v.id}`),children:[e.jsx(Ya,{className:"h-3.5 w-3.5 mr-2"})," Edit"]}),e.jsxs(Na,{onClick:()=>c(v.id),className:"text-destructive",children:[e.jsx(Pn,{className:"h-3.5 w-3.5 mr-2"})," Delete"]})]})]})]})]})})},v.id)})})]}),e.jsx(Os,{open:i,onOpenChange:l,children:e.jsxs(Rs,{children:[e.jsx(Us,{children:e.jsx(zs,{children:"Create Landing Page"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(se,{children:"Page Title"}),e.jsx(be,{value:h.title,onChange:v=>m(N=>({...N,title:v.target.value})),placeholder:"e.g. Veterans Home & Land Expo"})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Description (optional)"}),e.jsx(Is,{value:h.description,onChange:v=>m(N=>({...N,description:v.target.value})),placeholder:"Brief internal description...",rows:2})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Page Template"}),e.jsxs(vs,{value:h.page_type,onValueChange:v=>m(N=>({...N,page_type:v})),children:[e.jsx(gs,{children:e.jsx(bs,{})}),e.jsx(ys,{children:Q_t.map(v=>e.jsx(Ye,{value:v.id,children:e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:v.label}),e.jsx("div",{className:"text-xs text-muted-foreground",children:v.description})]})},v.id))})]})]})]}),e.jsxs(kr,{children:[e.jsx($,{variant:"outline",onClick:()=>l(!1),children:"Cancel"}),e.jsx($,{onClick:()=>g.mutate(),disabled:!h.title.trim()||g.isPending,children:g.isPending?"Creating...":"Create Page"})]})]})}),e.jsx(Ll,{open:!!o,onOpenChange:()=>c(null),children:e.jsxs(yl,{children:[e.jsxs(vl,{children:[e.jsx(_l,{children:"Delete Landing Page?"}),e.jsx(wl,{children:"This will permanently delete this page and all its submissions."})]}),e.jsxs(bl,{children:[e.jsx(jl,{children:"Cancel"}),e.jsx(fl,{onClick:()=>o&&y.mutate(o),children:"Delete"})]})]})}),e.jsx(Os,{open:!!d,onOpenChange:()=>u(null),children:e.jsxs(Rs,{className:"max-w-sm",children:[e.jsx(Us,{children:e.jsx(zs,{children:"QR Code"})}),e.jsxs("div",{className:"flex flex-col items-center gap-4 py-4",children:[d&&e.jsx(XN,{value:d,size:240}),e.jsx("p",{className:"text-xs text-muted-foreground text-center break-all",children:d}),e.jsxs($,{variant:"outline",size:"sm",onClick:()=>{d&&(navigator.clipboard.writeText(d),n({title:"URL copied!"}))},children:[e.jsx(Ca,{className:"h-3.5 w-3.5 mr-1"})," Copy URL"]})]})]})})]})}function yYn(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 vYn(s,t){return t?`${(s/t*100).toFixed(1)}%`:"0%"}function bYn({pageId:s}){const{data:t=[],isLoading:n}=ht({queryKey:["landing-page-events",s],queryFn:async()=>{const l=new Date(Date.now()-2592e6).toISOString(),{data:o,error:c}=await U.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=[]}=ht({queryKey:["landing-page-submissions-analytics",s],queryFn:async()=>{const{data:l}=await U.from("landing_page_submissions").select("id, created_at").eq("page_id",s);return l||[]}}),a=j.useMemo(()=>{const l=t.filter(x=>x.event_type==="view"),o=t.filter(x=>x.event_type==="click"),c=new Set(l.map(x=>x.session_id).filter(Boolean)),d=new Map,u=new Map,h=new Map;for(const x of l){const g=x.utm_source||"Direct / unknown";if(d.set(g,(d.get(g)||0)+1),x.referrer)try{const b=new URL(x.referrer).hostname.replace(/^www\./,"");u.set(b,(u.get(b)||0)+1)}catch{}const y=x.device||"unknown";h.set(y,(h.get(y)||0)+1)}const m=[];for(let x=13;x>=0;x--){const g=new Date;g.setHours(0,0,0,0),g.setDate(g.getDate()-x);const y=new Date(g);y.setDate(g.getDate()+1);const b=g.toLocaleDateString("en-US",{month:"numeric",day:"numeric"}),v=l.filter(C=>{const A=new Date(C.created_at);return A>=g&&A{const A=new Date(C.created_at);return A>=g&&Ax.views));return{views:l.length,sessions:c.size,clicks:o.length,submissions:r.length,conversion:vYn(r.length,c.size||l.length),sourceCounts:[...d.entries()].sort((x,g)=>g[1]-x[1]).slice(0,6),referrerCounts:[...u.entries()].sort((x,g)=>g[1]-x[1]).slice(0,6),deviceCounts:[...h.entries()].sort((x,g)=>g[1]-x[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(on,{className:"h-24"},o))});const i=[{label:"Views (30d)",value:a.views,icon:ga},{label:"Unique visitors",value:a.sessions,icon:qn},{label:"Submissions",value:a.submissions,icon:Br},{label:"Conversion rate",value:a.conversion,icon:Il}];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(_e,{children:e.jsxs(Oe,{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(_e,{children:[e.jsx(Bt,{children:e.jsx(Ut,{className:"text-base",children:"Last 14 days"})}),e.jsxs(Oe,{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(_e,{children:[e.jsx(Bt,{children:e.jsxs(Ut,{className:"text-base flex items-center gap-2",children:[e.jsx(uu,{className:"h-4 w-4"})," Top sources"]})}),e.jsx(Oe,{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(_e,{children:[e.jsx(Bt,{children:e.jsx(Ut,{className:"text-base",children:"Top referrers"})}),e.jsx(Oe,{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(_e,{children:[e.jsx(Bt,{children:e.jsx(Ut,{className:"text-base",children:"Devices"})}),e.jsx(Oe,{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 _Yn=[{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 wYn=0;const J_t=()=>`f_${Date.now()}_${++wYn}`;function jYn({field:s,index:t,updateField:n,removeField:r}){const{attributes:a,listeners:i,setNodeRef:l,transform:o,transition:c,isDragging:d}=VAe({id:s.clientId}),u={transform:l6.Transform.toString(o),transition:c,zIndex:d?50:void 0,opacity:d?.85:1};return e.jsx(_e,{ref:l,style:u,children:e.jsx(Oe,{className:"p-4",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("button",{type:"button",...a,...i,className:"mt-1 p-1 rounded text-muted-foreground hover:text-foreground hover:bg-muted cursor-grab active:cursor-grabbing touch-none","aria-label":"Drag to reorder",children:e.jsx($p,{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(se,{className:"text-xs",children:"Field Type"}),e.jsxs(vs,{value:s.field_type,onValueChange:h=>n(t,{field_type:h}),children:[e.jsx(gs,{children:e.jsx(bs,{})}),e.jsx(ys,{children:_Yn.map(h=>e.jsx(Ye,{value:h.value,children:h.label},h.value))})]})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-xs",children:"Label"}),e.jsx(be,{value:s.label,onChange:h=>n(t,{label:h.target.value}),placeholder:"e.g. Full Name"})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-xs",children:"Placeholder"}),e.jsx(be,{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(se,{className:"text-xs",children:"Options (comma-separated)"}),e.jsx(be,{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(Tn,{checked:s.is_required,onCheckedChange:h=>n(t,{is_required:h})}),e.jsx(se,{className:"text-xs",children:"Required"})]})]}),e.jsx($,{variant:"ghost",size:"sm",onClick:()=>r(t),children:e.jsx(Pn,{className:"h-3.5 w-3.5 text-destructive"})})]})})})}function NYn(){const{pageId:s}=Vi(),t=Vn(),{user:n}=_s(),r=Za(),{toast:a}=gi(),i=ts(),[l,o]=j.useState(null),[c,d]=j.useState(!1),{data:u,isLoading:h}=ht({queryKey:["landing-page",s],queryFn:async()=>{const{data:ne,error:ee}=await U.from("landing_pages").select("*").eq("id",s).single();if(ee)throw ee;return ne},enabled:!!s}),{data:m=[],isLoading:p}=ht({queryKey:["landing-page-fields",s],queryFn:async()=>{const{data:ne,error:ee}=await U.from("landing_page_fields").select("*").eq("page_id",s).order("sort_order");if(ee)throw ee;return ne},enabled:!!s}),{data:x=[]}=ht({queryKey:["landing-page-submissions",s],queryFn:async()=>{const{data:ne,error:ee}=await U.from("landing_page_submissions").select("*").eq("page_id",s).order("created_at",{ascending:!1});if(ee)throw ee;return ne},enabled:!!s}),{data:g=[]}=ht({queryKey:["my-listings-for-pages",r],queryFn:async()=>{const{data:ne,error:ee}=await U.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(ee)throw ee;return ne},enabled:!!n&&((u==null?void 0:u.page_type)==="just_listed"||(u==null?void 0:u.page_type)==="just_sold")}),{data:y=[]}=ht({queryKey:["drips-for-landing",r],queryFn:async()=>{const{data:ne}=await U.from("drip_campaigns").select("id, name").eq("owner_user_id",r).eq("is_active",!0).order("name");return ne||[]},enabled:!!r}),{data:b}=ht({queryKey:["agent-landing-defaults",r],queryFn:async()=>{const{data:ne}=await U.from("agent_landing_page_defaults").select("*").eq("user_id",r).maybeSingle();return ne},enabled:!!r}),[v,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:""}),[C,A]=j.useState([]);j.useEffect(()=>{var ne,ee,le,he,ve,ge,fe,je,Ee;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:((ne=u.settings)==null?void 0:ne.redirect_url)||"",settings_auto_responder_subject:((ee=u.settings)==null?void 0:ee.auto_responder_subject)||"",settings_auto_responder_body:((le=u.settings)==null?void 0:le.auto_responder_body)||"",settings_drip_campaign_id:((he=u.settings)==null?void 0:he.drip_campaign_id)||null,settings_disable_auto_responder:!!((ve=u.settings)!=null&&ve.disable_auto_responder),settings_disable_drip:!!((ge=u.settings)!=null&&ge.disable_drip),settings_event_starts_at:((fe=u.settings)==null?void 0:fe.event_starts_at)||"",settings_event_location_name:((je=u.settings)==null?void 0:je.event_location_name)||"",settings_event_address:((Ee=u.settings)==null?void 0:Ee.event_address)||""})},[u]),j.useEffect(()=>{m.length>0&&A(m.map(ne=>({id:ne.id,clientId:ne.id||J_t(),field_type:ne.field_type,label:ne.label,placeholder:ne.placeholder,is_required:ne.is_required,options:typeof ne.options=="string"?ne.options:ne.options?JSON.stringify(ne.options):null,sort_order:ne.sort_order})))},[m]);const T=yt({mutationFn:async()=>{const{error:ne}=await U.from("landing_pages").update({title:v.title,hero_headline:v.hero_headline,hero_subtext:v.hero_subtext||null,hero_image_url:v.hero_image_url,logo_url:v.logo_url,primary_color:v.primary_color,accent_color:v.accent_color,agent_name:v.agent_name||null,agent_phone:v.agent_phone||null,agent_email:v.agent_email||null,agent_photo_url:v.agent_photo_url,success_message:v.success_message,is_published:v.is_published,description:v.description||null,lead_magnet_file_url:v.lead_magnet_file_url,lead_magnet_file_name:v.lead_magnet_file_name,lead_magnet_external_url:v.lead_magnet_external_url,listing_id:v.listing_id,property_address:v.property_address||null,property_price:v.property_price||null,property_beds:v.property_beds||null,property_baths:v.property_baths||null,property_sqft:v.property_sqft||null,property_description:v.property_description||null,property_photos:v.property_photos,property_status:v.property_status,theme_style:v.theme_style,eyebrow:v.eyebrow||null,headline_accent:v.headline_accent||null,heading_font:v.heading_font,trust_pills:v.trust_pills,redirect_url:v.settings_redirect_url||null,auto_responder_enabled:!v.settings_disable_auto_responder,auto_responder_subject:v.settings_auto_responder_subject||null,auto_responder_body:v.settings_auto_responder_body||null,drip_campaign_id:v.settings_disable_drip?null:v.settings_drip_campaign_id||null,settings:{...(u==null?void 0:u.settings)||{},redirect_url:v.settings_redirect_url||null,auto_responder_subject:v.settings_auto_responder_subject||null,auto_responder_body:v.settings_auto_responder_body||null,drip_campaign_id:v.settings_drip_campaign_id||null,disable_auto_responder:!!v.settings_disable_auto_responder,disable_drip:!!v.settings_disable_drip,event_starts_at:v.settings_event_starts_at||null,event_location_name:v.settings_event_location_name||null,event_address:v.settings_event_address||null},updated_at:new Date().toISOString()}).eq("id",s);if(ne)throw ne;if(await U.from("landing_page_fields").delete().eq("page_id",s),C.length>0){const{error:ee}=await U.from("landing_page_fields").insert(C.map((le,he)=>({page_id:s,field_type:le.field_type,label:le.label,placeholder:le.placeholder||null,is_required:le.is_required,options:le.options?JSON.parse(le.options):null,sort_order:he})));if(ee)throw ee}},onSuccess:()=>{i.invalidateQueries({queryKey:["landing-page",s]}),i.invalidateQueries({queryKey:["landing-page-fields",s]}),a({title:"Page saved!"})},onError:ne=>a({title:"Error",description:ne.message,variant:"destructive"})}),P=async(ne,ee)=>{const le=ne.name.split(".").pop(),he=`landing-pages/${n.id}/${ee}-${Date.now()}.${le}`,{error:ve}=await U.storage.from("recruit-landing").upload(he,ne);if(ve)throw ve;const{data:{publicUrl:ge}}=U.storage.from("recruit-landing").getPublicUrl(he);return ge},M=async(ne,ee)=>{var he;const le=(he=ne.target.files)==null?void 0:he[0];if(le){o(ee);try{const ve=await P(le,ee);N(ge=>({...ge,[ee]:ve})),a({title:"Image uploaded!"})}catch(ve){a({title:"Upload failed",description:ve.message,variant:"destructive"})}finally{o(null)}}},I=async ne=>{var le;const ee=(le=ne.target.files)==null?void 0:le[0];if(ee){o("lead_magnet");try{const he=await P(ee,"lead-magnet");N(ve=>({...ve,lead_magnet_file_url:he,lead_magnet_file_name:ee.name})),a({title:"File uploaded!"})}catch(he){a({title:"Upload failed",description:he.message,variant:"destructive"})}finally{o(null)}}},D=async ne=>{const ee=ne.target.files;if(!(!ee||ee.length===0)){o("property_photos");try{const le=[];for(const he of Array.from(ee)){const ve=await P(he,"property-photo");le.push(ve)}N(he=>({...he,property_photos:[...he.property_photos,...le]})),a({title:`${le.length} photo(s) uploaded!`})}catch(le){a({title:"Upload failed",description:le.message,variant:"destructive"})}finally{o(null)}}},B=async ne=>{const ee=g.find(he=>he.id===ne);if(!ee)return;const{data:le}=await U.from("listing_photos").select("photo_url").eq("listing_id",ne).order("sort_order");N(he=>({...he,listing_id:ne,property_address:ee.property_address||`${ee.city}, ${ee.state}`,property_price:ee.price?`$${ee.price.toLocaleString()}`:"",property_beds:ee.bedrooms?String(ee.bedrooms):"",property_baths:ee.bathrooms?String(ee.bathrooms):"",property_sqft:ee.square_footage?ee.square_footage.toLocaleString():"",property_description:ee.description||"",property_photos:(le==null?void 0:le.map(ve=>ve.photo_url))||he.property_photos})),a({title:"Listing data imported!"})},q=()=>{A(ne=>[...ne,{clientId:J_t(),field_type:"text",label:"",placeholder:"",is_required:!1,options:null,sort_order:ne.length}])},W=(ne,ee)=>{A(le=>le.map((he,ve)=>ve===ne?{...he,...ee}:he))},V=ne=>{A(ee=>ee.filter((le,he)=>he!==ne))},K=DAe(pU(Vq,{activationConstraint:{distance:6}}),pU(FAe,{coordinateGetter:$8t})),Q=ne=>{const{active:ee,over:le}=ne;!le||ee.id===le.id||A(he=>{const ve=he.findIndex(fe=>fe.clientId===ee.id),ge=he.findIndex(fe=>fe.clientId===le.id);return ve<0||ge<0?he:UAe(he,ve,ge).map((fe,je)=>({...fe,sort_order:je}))})},J=u?`https://pages.relevelup.com/${u.slug}`:"",ce=(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(Ks,{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(Ks,{title:v.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($,{variant:"ghost",size:"sm",onClick:()=>t("/mission-control/landing-pages"),children:e.jsx(ka,{className:"h-4 w-4"})}),e.jsxs("div",{children:[e.jsx("h1",{className:"text-xl font-bold",children:v.title||"Untitled Page"}),e.jsxs("div",{className:"flex items-center gap-2 mt-0.5",children:[e.jsx($e,{variant:v.is_published?"default":"secondary",className:"text-[10px]",children:v.is_published?"Published":"Draft"}),e.jsxs("span",{className:"text-xs text-muted-foreground flex items-center gap-1",children:[e.jsx(ga,{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(qn,{className:"h-3 w-3"})," ",x.length," submissions"]})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[v.is_published&&e.jsxs(e.Fragment,{children:[e.jsx($,{size:"sm",variant:"outline",onClick:()=>d(!0),children:e.jsx(Rx,{className:"h-3.5 w-3.5"})}),e.jsxs($,{size:"sm",variant:"outline",onClick:()=>{navigator.clipboard.writeText(J),a({title:"Link copied!"})},children:[e.jsx(Ca,{className:"h-3.5 w-3.5 mr-1"})," Copy Link"]}),e.jsx($,{size:"sm",variant:"outline",asChild:!0,children:e.jsxs("a",{href:J,target:"_blank",rel:"noopener noreferrer",children:[e.jsx(Tr,{className:"h-3.5 w-3.5 mr-1"})," Preview"]})})]}),e.jsxs($,{onClick:()=>T.mutate(),disabled:T.isPending,children:[e.jsx(Jo,{className:"h-4 w-4 mr-2"}),T.isPending?"Saving...":"Save"]})]})]}),e.jsxs(ua,{defaultValue:"design",children:[e.jsxs(ha,{children:[e.jsx(Qt,{value:"design",children:"Design"}),ce&&e.jsx(Qt,{value:"lead_magnet",children:"Lead Magnet"}),ue&&e.jsx(Qt,{value:"property",children:"Property Details"}),e.jsxs(Qt,{value:"fields",children:["Form Fields (",C.length,")"]}),e.jsxs(Qt,{value:"submissions",children:["Submissions (",x.length,")"]}),e.jsx(Qt,{value:"automation",children:"Automation"}),e.jsx(Qt,{value:"analytics",children:"Analytics"}),e.jsx(Qt,{value:"settings",children:"Settings"})]}),e.jsxs(Jt,{value:"design",className:"space-y-4 mt-4",children:[e.jsxs(_e,{children:[e.jsx(Bt,{children:e.jsx(Ut,{className:"text-base",children:"Page Details"})}),e.jsxs(Oe,{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(se,{children:"Page Title (internal)"}),e.jsx(be,{value:v.title,onChange:ne=>N(ee=>({...ee,title:ne.target.value}))})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Description (internal)"}),e.jsx(be,{value:v.description,onChange:ne=>N(ee=>({...ee,description:ne.target.value}))})]})]})]}),e.jsxs(_e,{children:[e.jsx(Bt,{children:e.jsxs(Ut,{className:"text-base flex items-center gap-2",children:["Theme & Style",e.jsx($e,{variant:"secondary",className:"text-[10px]",children:"New"})]})}),e.jsxs(Oe,{className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx(se,{children:"Theme Style"}),e.jsxs(vs,{value:v.theme_style,onValueChange:ne=>N(ee=>({...ee,theme_style:ne})),children:[e.jsx(gs,{children:e.jsx(bs,{})}),e.jsxs(ys,{children:[e.jsx(Ye,{value:"premium",children:"Premium — cinematic + glass form"}),e.jsx(Ye,{value:"classic",children:"Classic — centered card"})]})]})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Headline Font"}),e.jsxs(vs,{value:v.heading_font,onValueChange:ne=>N(ee=>({...ee,heading_font:ne})),children:[e.jsx(gs,{children:e.jsx(bs,{})}),e.jsxs(ys,{children:[e.jsx(Ye,{value:"playfair",children:"Playfair Display (editorial serif)"}),e.jsx(Ye,{value:"baskerville",children:"Libre Baskerville (classic serif)"}),e.jsx(Ye,{value:"instrument",children:"Instrument Serif (modern serif)"}),e.jsx(Ye,{value:"sans",children:"Inter (clean sans-serif)"})]})]})]})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Trust Pills (comma separated, shown under CTA)"}),e.jsx(be,{value:v.trust_pills.join(", "),onChange:ne=>N(ee=>({...ee,trust_pills:ne.target.value.split(",").map(le=>le.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(_e,{children:[e.jsx(Bt,{children:e.jsx(Ut,{className:"text-base",children:"Hero Section"})}),e.jsxs(Oe,{className:"space-y-4",children:[v.theme_style==="premium"&&e.jsxs("div",{children:[e.jsx(se,{children:"Eyebrow (small label above headline)"}),e.jsx(be,{value:v.eyebrow,onChange:ne=>N(ee=>({...ee,eyebrow:ne.target.value})),placeholder:"HOME VALUE"})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Headline"}),e.jsx(be,{value:v.hero_headline,onChange:ne=>N(ee=>({...ee,hero_headline:ne.target.value})),placeholder:"What Is Your Home"})]}),v.theme_style==="premium"&&e.jsxs("div",{children:[e.jsx(se,{children:"Accent Word(s) — italic & colored (optional)"}),e.jsx(be,{value:v.headline_accent,onChange:ne=>N(ee=>({...ee,headline_accent:ne.target.value})),placeholder:"Actually Worth?"})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Subtext"}),e.jsx(Is,{value:v.hero_subtext,onChange:ne=>N(ee=>({...ee,hero_subtext:ne.target.value})),rows:3,placeholder:"A brief description..."})]}),e.jsxs("div",{children:[e.jsxs(se,{children:["Background Image ",v.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:[v.hero_image_url&&e.jsx("img",{src:v.hero_image_url,alt:"Hero",className:"h-16 w-28 object-cover rounded"}),e.jsxs("label",{className:"cursor-pointer",children:[e.jsx($,{variant:"outline",size:"sm",asChild:!0,disabled:l==="hero_image_url",children:e.jsxs("span",{children:[e.jsx(si,{className:"h-3.5 w-3.5 mr-1"}),l==="hero_image_url"?"Uploading...":"Upload"]})}),e.jsx("input",{type:"file",accept:"image/*",className:"hidden",onChange:ne=>M(ne,"hero_image_url")})]}),v.hero_image_url&&e.jsx($,{variant:"ghost",size:"sm",onClick:()=>N(ne=>({...ne,hero_image_url:null})),children:e.jsx(Pn,{className:"h-3.5 w-3.5"})})]})]})]})]}),e.jsxs(_e,{children:[e.jsx(Bt,{children:e.jsx(Ut,{className:"text-base",children:"Branding"})}),e.jsxs(Oe,{className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx(se,{children:"Logo"}),e.jsxs("div",{className:"flex items-center gap-3 mt-1",children:[v.logo_url&&e.jsx("img",{src:v.logo_url,alt:"Logo",className:"h-10 w-auto rounded"}),e.jsxs("label",{className:"cursor-pointer",children:[e.jsx($,{variant:"outline",size:"sm",asChild:!0,disabled:l==="logo_url",children:e.jsxs("span",{children:[e.jsx(si,{className:"h-3.5 w-3.5 mr-1"}),l==="logo_url"?"...":"Upload"]})}),e.jsx("input",{type:"file",accept:"image/*",className:"hidden",onChange:ne=>M(ne,"logo_url")})]})]})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Agent Photo"}),e.jsxs("div",{className:"flex items-center gap-3 mt-1",children:[v.agent_photo_url&&e.jsx("img",{src:v.agent_photo_url,alt:"Agent",className:"h-10 w-10 rounded-full object-cover"}),e.jsxs("label",{className:"cursor-pointer",children:[e.jsx($,{variant:"outline",size:"sm",asChild:!0,disabled:l==="agent_photo_url",children:e.jsxs("span",{children:[e.jsx(si,{className:"h-3.5 w-3.5 mr-1"}),l==="agent_photo_url"?"...":"Upload"]})}),e.jsx("input",{type:"file",accept:"image/*",className:"hidden",onChange:ne=>M(ne,"agent_photo_url")})]})]})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx(se,{children:"Primary Color"}),e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[e.jsx("input",{type:"color",value:v.primary_color,onChange:ne=>N(ee=>({...ee,primary_color:ne.target.value})),className:"h-9 w-12 rounded border cursor-pointer"}),e.jsx(be,{value:v.primary_color,onChange:ne=>N(ee=>({...ee,primary_color:ne.target.value})),className:"font-mono text-xs"})]})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Accent Color"}),e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[e.jsx("input",{type:"color",value:v.accent_color,onChange:ne=>N(ee=>({...ee,accent_color:ne.target.value})),className:"h-9 w-12 rounded border cursor-pointer"}),e.jsx(be,{value:v.accent_color,onChange:ne=>N(ee=>({...ee,accent_color:ne.target.value})),className:"font-mono text-xs"})]})]})]})]})]}),e.jsxs(_e,{children:[e.jsx(Bt,{children:e.jsx(Ut,{className:"text-base",children:"Agent Info (shown on page)"})}),e.jsx(Oe,{className:"space-y-4",children:e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4",children:[e.jsxs("div",{children:[e.jsx(se,{children:"Name"}),e.jsx(be,{value:v.agent_name,onChange:ne=>N(ee=>({...ee,agent_name:ne.target.value}))})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Phone"}),e.jsx(be,{value:v.agent_phone,onChange:ne=>N(ee=>({...ee,agent_phone:ne.target.value}))})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Email"}),e.jsx(be,{value:v.agent_email,onChange:ne=>N(ee=>({...ee,agent_email:ne.target.value}))})]})]})})]})]}),ce&&e.jsx(Jt,{value:"lead_magnet",className:"space-y-4 mt-4",children:e.jsxs(_e,{children:[e.jsx(Bt,{children:e.jsxs(Ut,{className:"text-base flex items-center gap-2",children:[e.jsx(di,{className:"h-4 w-4"})," Giveaway File"]})}),e.jsxs(Oe,{className:"space-y-4",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Upload a file or provide an external URL. Visitors will receive the download link after submitting the form."}),e.jsxs("div",{children:[e.jsx(se,{children:"Upload File (PDF, guide, checklist, etc.)"}),e.jsxs("div",{className:"flex items-center gap-3 mt-1",children:[v.lead_magnet_file_name&&e.jsxs($e,{variant:"outline",className:"gap-1",children:[e.jsx(di,{className:"h-3 w-3"})," ",v.lead_magnet_file_name]}),e.jsxs("label",{className:"cursor-pointer",children:[e.jsx($,{variant:"outline",size:"sm",asChild:!0,disabled:l==="lead_magnet",children:e.jsxs("span",{children:[e.jsx(si,{className:"h-3.5 w-3.5 mr-1"}),l==="lead_magnet"?"Uploading...":"Upload File"]})}),e.jsx("input",{type:"file",className:"hidden",onChange:I})]}),v.lead_magnet_file_url&&e.jsx($,{variant:"ghost",size:"sm",onClick:()=>N(ne=>({...ne,lead_magnet_file_url:null,lead_magnet_file_name:null})),children:e.jsx(Pn,{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(se,{className:"flex items-center gap-1",children:[e.jsx(Dc,{className:"h-3.5 w-3.5"})," External URL"]}),e.jsx(be,{value:v.lead_magnet_external_url||"",onChange:ne=>N(ee=>({...ee,lead_magnet_external_url:ne.target.value||null})),placeholder:"https://drive.google.com/... or https://dropbox.com/...",className:"mt-1"}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"Link to a file on Google Drive, Dropbox, or any URL"})]})]})]})}),ue&&e.jsxs(Jt,{value:"property",className:"space-y-4 mt-4",children:[e.jsxs(_e,{children:[e.jsx(Bt,{children:e.jsxs(Ut,{className:"text-base flex items-center gap-2",children:[e.jsx(sa,{className:"h-4 w-4"})," Import from Listing Exchange"]})}),e.jsxs(Oe,{className:"space-y-4",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Pull property details and photos directly from one of your listings, or enter them manually below."}),e.jsxs(vs,{value:v.listing_id||"",onValueChange:ne=>B(ne),children:[e.jsx(gs,{children:e.jsx(bs,{placeholder:"Select a listing to import..."})}),e.jsx(ys,{children:g.map(ne=>{var ee;return e.jsxs(Ye,{value:ne.id,children:[ne.property_address||`${ne.city}, ${ne.state}`," — $",(ee=ne.price)==null?void 0:ee.toLocaleString()]},ne.id)})})]})]})]}),e.jsxs(_e,{children:[e.jsx(Bt,{children:e.jsx(Ut,{className:"text-base",children:"Property Information"})}),e.jsxs(Oe,{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(se,{children:"Property Address"}),e.jsx(be,{value:v.property_address,onChange:ne=>N(ee=>({...ee,property_address:ne.target.value})),placeholder:"123 Main St, City, State"})]}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[e.jsxs("div",{children:[e.jsx(se,{children:"Price"}),e.jsx(be,{value:v.property_price,onChange:ne=>N(ee=>({...ee,property_price:ne.target.value})),placeholder:"$450,000"})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Beds"}),e.jsx(be,{value:v.property_beds,onChange:ne=>N(ee=>({...ee,property_beds:ne.target.value})),placeholder:"4"})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Baths"}),e.jsx(be,{value:v.property_baths,onChange:ne=>N(ee=>({...ee,property_baths:ne.target.value})),placeholder:"3"})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Sq Ft"}),e.jsx(be,{value:v.property_sqft,onChange:ne=>N(ee=>({...ee,property_sqft:ne.target.value})),placeholder:"2,400"})]})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Description"}),e.jsx(Is,{value:v.property_description,onChange:ne=>N(ee=>({...ee,property_description:ne.target.value})),rows:3,placeholder:"Beautiful home in a great neighborhood..."})]})]})]}),e.jsxs(_e,{children:[e.jsx(Bt,{children:e.jsx(Ut,{className:"text-base",children:"Property Photos"})}),e.jsxs(Oe,{className:"space-y-4",children:[v.property_photos.length>0&&e.jsx("div",{className:"grid grid-cols-3 md:grid-cols-4 gap-2",children:v.property_photos.map((ne,ee)=>e.jsxs("div",{className:"relative group",children:[e.jsx("img",{src:ne,alt:`Property ${ee+1}`,className:"h-24 w-full object-cover rounded"}),e.jsx($,{variant:"destructive",size:"sm",className:"absolute top-1 right-1 h-6 w-6 p-0 opacity-0 group-hover:opacity-100 transition-opacity",onClick:()=>N(le=>({...le,property_photos:le.property_photos.filter((he,ve)=>ve!==ee)})),children:e.jsx(Pn,{className:"h-3 w-3"})})]},ee))}),e.jsxs("label",{className:"cursor-pointer",children:[e.jsx($,{variant:"outline",size:"sm",asChild:!0,disabled:l==="property_photos",children:e.jsxs("span",{children:[e.jsx(si,{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:D})]})]})]})]}),e.jsxs(Jt,{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($,{size:"sm",onClick:q,children:[e.jsx(sn,{className:"h-3.5 w-3.5 mr-1"})," Add Field"]})]}),C.length===0?e.jsx(_e,{children:e.jsx(Oe,{className:"py-8 text-center text-muted-foreground",children:"No fields yet. Add fields to build your form."})}):e.jsx($Ae,{sensors:K,collisionDetection:RAe,onDragEnd:Q,children:e.jsx(qAe,{items:C.map(ne=>ne.clientId),strategy:ZVs,children:e.jsx("div",{className:"space-y-3",children:C.map((ne,ee)=>e.jsx(jYn,{field:ne,index:ee,updateField:W,removeField:V},ne.clientId))})})})]}),e.jsx(Jt,{value:"submissions",className:"mt-4",children:x.length===0?e.jsx(_e,{children:e.jsx(Oe,{className:"py-12 text-center text-muted-foreground",children:"No submissions yet. Share your page to start collecting leads!"})}):e.jsx("div",{className:"space-y-3",children:x.map(ne=>e.jsx(_e,{children:e.jsx(Oe,{className:"p-4",children:e.jsxs("div",{className:"flex items-start justify-between",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"font-medium",children:ne.contact_name||"Anonymous"}),ne.synced_to_crm&&e.jsx($e,{variant:"outline",className:"text-[10px]",children:"Synced"})]}),e.jsxs("div",{className:"text-sm text-muted-foreground mt-0.5",children:[ne.contact_email&&e.jsx("span",{className:"mr-3",children:ne.contact_email}),ne.contact_phone&&e.jsx("span",{children:ne.contact_phone})]}),ne.answers&&typeof ne.answers=="object"&&e.jsx("div",{className:"mt-2 text-sm space-y-1",children:Object.entries(ne.answers).map(([ee,le])=>e.jsxs("div",{children:[e.jsxs("span",{className:"font-medium text-muted-foreground",children:[ee,":"]})," ",e.jsx("span",{children:String(le)})]},ee))})]}),e.jsx("span",{className:"text-xs text-muted-foreground",children:new Date(ne.created_at).toLocaleDateString()})]})})},ne.id))})}),e.jsxs(Jt,{value:"automation",className:"space-y-4 mt-4",children:[(u==null?void 0:u.page_type)==="event_registration"&&e.jsxs(_e,{children:[e.jsxs(Bt,{children:[e.jsx(Ut,{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(Oe,{className:"grid gap-3 md:grid-cols-2",children:[e.jsxs("div",{className:"space-y-1.5 md:col-span-2",children:[e.jsx(se,{children:"Starts at"}),e.jsx(be,{type:"datetime-local",value:v.settings_event_starts_at,onChange:ne=>N(ee=>({...ee,settings_event_starts_at:ne.target.value}))})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:"Venue / location name"}),e.jsx(be,{placeholder:"e.g. The Grand Hotel",value:v.settings_event_location_name,onChange:ne=>N(ee=>({...ee,settings_event_location_name:ne.target.value}))})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:"Address (for map link)"}),e.jsx(be,{placeholder:"123 Main St, City, ST",value:v.settings_event_address,onChange:ne=>N(ee=>({...ee,settings_event_address:ne.target.value}))})]})]})]}),e.jsxs(_e,{children:[e.jsxs(Bt,{children:[e.jsx(Ut,{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",b!=null&&b.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(Oe,{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(se,{children:"Send auto-reply for this page"}),e.jsx(Tn,{checked:!v.settings_disable_auto_responder,onCheckedChange:ne=>N(ee=>({...ee,settings_disable_auto_responder:!ne}))})]}),!v.settings_disable_auto_responder&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{children:[e.jsx(se,{children:"Subject (override)"}),e.jsx(be,{value:v.settings_auto_responder_subject,onChange:ne=>N(ee=>({...ee,settings_auto_responder_subject:ne.target.value})),placeholder:(b==null?void 0:b.default_auto_responder_subject)||"Thanks for reaching out, {{client_first_name}}!"})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Body (override)"}),e.jsx(Is,{rows:8,value:v.settings_auto_responder_body,onChange:ne=>N(ee=>({...ee,settings_auto_responder_body:ne.target.value})),placeholder:(b==null?void 0:b.default_auto_responder_body)||`Hi {{client_first_name}}, Thanks for reaching out…`})]})]})]})]}),e.jsxs(_e,{children:[e.jsxs(Bt,{children:[e.jsx(Ut,{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.",(b==null?void 0:b.default_drip_campaign_id)&&" Account default applies if no override is selected."]})]}),e.jsxs(Oe,{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(se,{children:"Enroll new leads in a drip"}),e.jsx(Tn,{checked:!v.settings_disable_drip,onCheckedChange:ne=>N(ee=>({...ee,settings_disable_drip:!ne}))})]}),!v.settings_disable_drip&&e.jsxs("div",{children:[e.jsx(se,{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:v.settings_drip_campaign_id||"",onChange:ne=>N(ee=>({...ee,settings_drip_campaign_id:ne.target.value||null})),children:[e.jsx("option",{value:"",children:"— Use account default —"}),y.map(ne=>e.jsx("option",{value:ne.id,children:ne.name},ne.id))]})]})]})]}),e.jsxs(_e,{children:[e.jsx(Bt,{children:e.jsx(Ut,{className:"text-base",children:"Redirect after submit"})}),e.jsxs(Oe,{children:[e.jsx(be,{value:v.settings_redirect_url,onChange:ne=>N(ee=>({...ee,settings_redirect_url:ne.target.value})),placeholder:(b==null?void 0:b.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(Jt,{value:"analytics",className:"space-y-4 mt-4",children:e.jsx(bYn,{pageId:s})}),e.jsxs(Jt,{value:"settings",className:"space-y-4 mt-4",children:[e.jsxs(_e,{children:[e.jsx(Bt,{children:e.jsx(Ut,{className:"text-base",children:"Publishing"})}),e.jsxs(Oe,{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(se,{children:"Published"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Make this page publicly accessible"})]}),e.jsx(Tn,{checked:v.is_published,onCheckedChange:ne=>N(ee=>({...ee,is_published:ne}))})]}),v.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:J})]})]})]}),e.jsxs(_e,{children:[e.jsx(Bt,{children:e.jsx(Ut,{className:"text-base",children:"Thank You Message"})}),e.jsx(Oe,{children:e.jsx(Is,{value:v.success_message,onChange:ne=>N(ee=>({...ee,success_message:ne.target.value})),rows:2,placeholder:"Message shown after form submission"})})]})]})]})]}),e.jsx(Os,{open:c,onOpenChange:d,children:e.jsxs(Rs,{className:"max-w-sm",children:[e.jsx(Us,{children:e.jsx(zs,{children:"QR Code"})}),e.jsxs("div",{className:"flex flex-col items-center gap-4 py-4",children:[e.jsx(XN,{value:J,size:240}),e.jsx("p",{className:"text-xs text-muted-foreground text-center break-all",children:J})]})]})})]}):e.jsx(Ks,{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($,{variant:"link",onClick:()=>t("/mission-control/landing-pages"),children:"Go back"})]})})}const kYn={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},SYn=`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 CYn(){const s=Za(),{toast:t}=gi(),n=Vn(),r=ts(),[a,i]=j.useState(kYn),{data:l}=ht({queryKey:["landing-page-defaults",s],queryFn:async()=>{const{data:d}=await U.from("agent_landing_page_defaults").select("*").eq("user_id",s).maybeSingle();return d||null},enabled:!!s}),{data:o=[]}=ht({queryKey:["drip-campaigns-mine",s],queryFn:async()=>{const{data:d}=await U.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 U.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(Ks,{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($,{variant:"ghost",size:"sm",onClick:()=>n("/mission-control/landing-pages"),children:[e.jsx(ka,{className:"h-4 w-4 mr-1"})," Back to pages"]}),e.jsxs($,{onClick:()=>c.mutate(),disabled:c.isPending,children:[e.jsx(Jo,{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(_e,{children:[e.jsxs(Bt,{children:[e.jsx(Ut,{children:"Instant auto-reply to the lead"}),e.jsxs(vr,{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(Oe,{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(se,{children:"Subject"}),e.jsx(be,{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(se,{children:"Message body"}),e.jsx(Is,{rows:10,value:a.default_auto_responder_body||"",onChange:d=>i(u=>({...u,default_auto_responder_body:d.target.value})),placeholder:SYn}),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(_e,{children:[e.jsxs(Bt,{children:[e.jsx(Ut,{children:"Default Smart Drip"}),e.jsx(vr,{children:"Every new lead drops into this drip unless a page overrides it."})]}),e.jsx(Oe,{children:e.jsxs(vs,{value:a.default_drip_campaign_id||"none",onValueChange:d=>i(u=>({...u,default_drip_campaign_id:d==="none"?null:d})),children:[e.jsx(gs,{children:e.jsx(bs,{placeholder:"Pick a drip…"})}),e.jsxs(ys,{children:[e.jsx(Ye,{value:"none",children:"— No default drip —"}),o.map(d=>e.jsx(Ye,{value:d.id,children:d.name},d.id))]})]})})]}),e.jsxs(_e,{children:[e.jsx(Bt,{children:e.jsx(Ut,{children:"Defaults for every page"})}),e.jsxs(Oe,{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(se,{children:"Default booking / calendar link"}),e.jsx(be,{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(se,{children:"Default redirect after submit (optional)"}),e.jsx(be,{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(se,{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(Tn,{checked:a.use_brand_kit,onCheckedChange:d=>i(u=>({...u,use_brand_kit:d}))})]})]})]}),e.jsxs(_e,{children:[e.jsxs(Bt,{children:[e.jsx(Ut,{children:"Text me when a lead submits"}),e.jsx(vr,{children:"Get an SMS the second a lead hits your inbox. Coming soon — requires SMS sender setup."})]}),e.jsxs(Oe,{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between rounded-lg border p-3",children:[e.jsx(se,{className:"text-base",children:"SMS me new leads"}),e.jsx(Tn,{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(se,{children:"Phone number for alerts"}),e.jsx(be,{type:"tel",value:a.agent_sms_phone||"",onChange:d=>i(u=>({...u,agent_sms_phone:d.target.value})),placeholder:"(555) 123-4567"})]})]})]})]})})}function mKt({hasLeadSite:s}){const t=Vn(),n=ts(),[r,a]=j.useState(!1),{offer:i}=TCe(!s);if(s||!i)return null;const l=async()=>{a(!0);try{const{data:o,error:c}=await U.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"]}),ae.success("Your website is live! Let’s make it yours."),t(`/admin/lead-sites/${o.siteId}/edit`)}catch(o){ae.error((o==null?void 0:o.message)||"Could not create your website")}finally{a(!1)}};return e.jsx(_e,{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(Ng,{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(dn,{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($,{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(Tr,{className:"w-3 h-3"})]})]})]})]})})}function AYn(){return ht({queryKey:["website-apps"],queryFn:async()=>{const{data:s,error:t}=await U.from("website_apps").select("*").order("sort_order",{ascending:!0});if(t)throw t;return s||[]}})}function WTe(){const{user:s}=_s();return ht({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 U.from("agent_website_app_installs").select("*").eq("user_id",s.id);if(n)throw n;return t||[]},enabled:!!(s!=null&&s.id)})}function KTe(){const{user:s}=_s(),t=ts();return yt({mutationFn:async({app_slug:n,enabled:r})=>{if(!(s!=null&&s.id))throw new Error("Not authenticated");const{error:a}=await U.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"]}),ae.success(r.enabled?"App installed":"App turned off")},onError:n=>ae.error(n.message||"Failed to update app")})}const EYn={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"}},TYn={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 MYn(){const s=Vn(),{data:t=[],isLoading:n}=AYn(),{data:r=[]}=WTe(),{hasLeadSite:a,siteUrl:i,isLoading:l}=Mf(),o=KTe(),[c,d]=j.useState(!1),u=m=>{var p;return((p=r.find(x=>x.app_slug===m))==null?void 0:p.enabled)??!1},h=m=>r.some(p=>p.app_slug===m);return e.jsxs(Ks,{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(ox,{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(dn,{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($,{onClick:()=>d(!0),className:"mt-5 bg-white text-indigo-700 hover:bg-white/90 shadow-lg font-semibold gap-2",children:[e.jsx(Sh,{className:"w-5 h-5"}),"Watch: How to use Website Apps"]})]})]}),e.jsx(mKt,{hasLeadSite:a}),e.jsxs("div",{className:"grid gap-4 md:grid-cols-2",children:[e.jsx(_e,{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(Gl,{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($e,{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(Tr,{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(Tr,{className:"w-3 h-3"})]})," ","to learn more — apps install automatically once you have one."]})]})]})}),e.jsx(_e,{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(X4,{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=R3e[m.icon||"Sparkles"]||dn,x=u(m.slug),g=h(m.slug),y=m.status==="coming_soon",b=EYn[m.slug]||TYn;return e.jsxs(_e,{className:`group relative overflow-hidden border-0 ring-1 ring-border ${b.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 ${b.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 ${b.iconBg} ${b.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($e,{variant:"secondary",children:"Coming soon"}):x?e.jsxs($e,{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"]}):g?e.jsx($e,{variant:"outline",children:"Paused"}):e.jsx($e,{className:b.chip+" hover:"+b.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(Tn,{checked:x,onCheckedChange:v=>o.mutate({app_slug:m.slug,enabled:v})}),e.jsx("span",{className:"text-sm font-medium text-muted-foreground",children:x?"On":"Off"})]}),e.jsxs($,{size:"sm",className:`bg-gradient-to-r ${b.gradient} text-white hover:opacity-90 shadow-md border-0`,onClick:()=>s(`/website-apps/${m.slug}`),children:[e.jsx(pc,{className:"w-3.5 h-3.5 mr-1.5"}),"Configure",e.jsx(ni,{className:"w-3.5 h-3.5 ml-1"})]})]})]})]},m.id)})})]}),e.jsx(Os,{open:c,onOpenChange:d,children:e.jsxs(Rs,{className:"max-w-4xl p-0 overflow-hidden bg-black border-0",children:[e.jsx(Us,{className:"px-5 pt-4 pb-2 bg-background",children:e.jsx(zs,{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 LYn(){const{leadSite:s,hasLeadSite:t,isLoading:n}=Mf(),{hasOffer:r,isLoading:a}=TCe(!t);return t&&s?e.jsx(r1,{to:`/my-website/${s.id}/edit`,replace:!0}):e.jsx(Ks,{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(mKt,{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 MRe={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 PYn(){const{user:s}=_s();return ht({queryKey:["video-greeter-config",s==null?void 0:s.id],queryFn:async()=>{if(!(s!=null&&s.id))return MRe;const{data:t,error:n}=await U.from("video_greeter_configs").select("*").eq("user_id",s.id).maybeSingle();if(n)throw n;return t?{...MRe,...t}:MRe},enabled:!!(s!=null&&s.id)})}function IYn(){const{user:s}=_s(),t=ts();return yt({mutationFn:async n=>{if(!(s!=null&&s.id))throw new Error("Not authenticated");const{error:r}=await U.from("video_greeter_configs").upsert({user_id:s.id,...n},{onConflict:"user_id"});if(r)throw r},onSuccess:()=>{t.invalidateQueries({queryKey:["video-greeter-config"]}),ae.success("Saved")},onError:n=>ae.error(n.message||"Failed to save")})}function DYn({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/")){ae.error("Please select a video file");return}if(h.size>50*1024*1024){ae.error("Video must be under 50MB");return}c(!0);try{const p=h.name.split(".").pop()||"mp4",x=`lead-site/videos/${Date.now()}-${Math.random().toString(36).slice(2,6)}.${p}`,{error:g}=await U.storage.from("agent-uploads").upload(x,h,{upsert:!0});if(g)throw g;const{data:{publicUrl:y}}=U.storage.from("agent-uploads").getPublicUrl(x);n(y),ae.success("Video uploaded!")}catch(p){ae.error(p.message||"Upload failed")}finally{c(!1),l.current&&(l.current.value="")}}};return e.jsxs("div",{children:[e.jsx(se,{children:s}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(be,{value:t,onChange:u=>n(u.target.value),placeholder:a,className:"flex-1"}),e.jsxs($,{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(Ht,{className:"h-3.5 w-3.5 animate-spin"}):e.jsx(si,{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}):az(t)?e.jsx(FUe,{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($,{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(pr,{className:"h-3 w-3"})})]})})()]})}const RYn=[{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 OYn({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,x]=j.useState(0),g=F5(),y=()=>{a("script"),l(""),m(0),x(0),c(!0)},b=N=>{!N&&(r==="uploading"||r==="processing")||(n(N),N||y())},v=j.useCallback(async(N,C)=>{a("uploading");try{const A="Video Greeter",{videoId:T,libraryId:P}=await Z6(A),{uploadUrl:M,apiKey:I}=await X6(T),D=new XMLHttpRequest;D.upload.onprogress=ue=>{ue.lengthComputable&&m(ue.loaded/ue.total*100)},await new Promise((ue,ne)=>{D.onload=()=>D.status>=200&&D.status<300?ue():ne(new Error("Upload failed")),D.onerror=()=>ne(new Error("Upload failed")),D.open("PUT",M),D.setRequestHeader("AccessKey",I),D.send(N)}),a("processing");let B=0;const q=Date.now(),W=9e4,V=`https://iframe.mediadelivery.net/embed/${P}/${T}`,K=`https://iframe.mediadelivery.net/play/${P}/${T}`;for(;B<4;){if(await new Promise(ne=>setTimeout(ne,3e3)),Date.now()-q>W){const ne=N.size/1048576,ee=await g.mutateAsync({bunny_video_id:T,playback_url:K,file_size_mb:ne,title:A,status:"processing",touch_type:"video"});s({videoId:(ee==null?void 0:ee.id)||T,playbackUrl:V,thumbnailUrl:null}),ae.success("Video saved — still encoding. Will be ready shortly."),a("done"),setTimeout(()=>{n(!1),y()},1500);return}const ue=await o2(T);if(B=ue.status,x(ue.encodeProgress||0),B===5||B===6)throw new Error("Video processing failed")}const Q=await o2(T),J=(Q.storageSize||N.size)/(1024*1024),ce=await g.mutateAsync({bunny_video_id:T,playback_url:Q.directPlayUrl||V,thumbnail_url:Q.thumbnailUrl,preview_url:Q.previewUrl||null,duration_seconds:Q.length||C,file_size_mb:J,title:A,status:"ready",touch_type:"video"});s({videoId:(ce==null?void 0:ce.id)||T,playbackUrl:Q.directPlayUrl||V,thumbnailUrl:Q.thumbnailUrl||null}),ae.success("Video recorded & added to your library!"),a("done"),setTimeout(()=>{n(!1),y()},1500)}catch(A){console.error(A),ae.error("Failed to process video. Please try again."),a("record")}},[g,s]);return e.jsxs(Os,{open:t,onOpenChange:b,children:[e.jsx(Ko,{asChild:!0,children:e.jsxs($,{variant:"default",size:"sm",className:"gap-1.5",children:[e.jsx(Xr,{className:"h-4 w-4"}),"Record now"]})}),e.jsxs(Rs,{className:"sm:max-w-3xl max-h-[92vh] overflow-y-auto",children:[e.jsx(Us,{children:e.jsxs(zs,{className:"flex items-center gap-2",children:[e.jsx(dn,{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(Oi,{className:"h-[280px] pr-3",children:e.jsx("div",{className:"grid sm:grid-cols-2 gap-3",children:RYn.map(N=>e.jsxs(_e,{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($e,{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(Is,{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($,{variant:"ghost",onClick:()=>{l(""),a("record")},children:"Skip — freestyle"}),e.jsxs($,{onClick:()=>a("record"),children:[e.jsx(Wr,{className:"h-4 w-4 mr-1.5"})," Continue to recorder"]})]})]}),r==="record"&&e.jsxs("div",{className:"space-y-3",children:[e.jsx(J6,{maxDurationSeconds:60,onRecordingComplete:v,onRecordingStateChange:u,onError:N=>ae.error(N),teleprompterContent:o&&i?e.jsx(lXe,{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($,{variant:"ghost",size:"sm",onClick:()=>a("script"),children:"← Back to script"}),i&&!o&&e.jsxs($,{variant:"outline",size:"sm",onClick:()=>c(!0),children:[e.jsx(Wr,{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(Ht,{className:"h-10 w-10 animate-spin text-primary"}),e.jsx("p",{className:"text-sm font-medium",children:"Uploading video..."}),e.jsx(Ki,{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(Ht,{className:"h-10 w-10 animate-spin text-primary"}),e.jsx("p",{className:"text-sm font-medium",children:"Processing video..."}),e.jsx(Ki,{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(Ro,{className:"h-12 w-12 text-emerald-500"}),e.jsx("p",{className:"text-sm font-medium",children:"Video attached to your greeter!"})]})]})]})}function FYn(){var C;const s=Vn(),{user:t}=_s(),{leadSite:n}=Mf(),{data:r}=PYn(),a=IYn(),{data:i=[]}=WTe(),l=KTe(),[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&&U.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(P=>P.event_type==="impression").length,expands:T.filter(P=>P.event_type==="expand").length,ctaClicks:T.filter(P=>P.event_type==="cta_click").length,leads:T.filter(P=>P.event_type==="lead_capture").length})})},[t==null?void 0:t.id]),!o)return e.jsx(Ks,{title:"Video Greeter",children:e.jsx("div",{className:"p-8 text-sm text-muted-foreground",children:"Loading..."})});const h=((C=i.find(A=>A.app_slug==="video_greeter"))==null?void 0:C.enabled)??!1,m=A=>c({...o,...A}),p=A=>m({ctas:A}),x=()=>p([...o.ctas||[],{id:crypto.randomUUID(),label:"New Button",url:"https://",style:"primary"}]),g=A=>p((o.ctas||[]).filter(T=>T.id!==A)),y=(A,T)=>p((o.ctas||[]).map(P=>P.id===A?{...P,...T}:P)),b=()=>a.mutate(o),v=(n==null?void 0:n.subdomain_slug)||(t==null?void 0:t.id)||"",N=`